diff --git a/.gitattributes b/.gitattributes index 8a1104624b08bac04a020df71c9ae14e1e2b914b..0261edb4fc96dc3d60313720d129158ebc3e8d6e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -724,3 +724,15 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/torch/testing/_internal/distributed/rpc/__pycache__/rpc_test.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/torch/testing/_internal/generated/__pycache__/annotated_fn_args.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.12/site-packages/torch/testing/_internal/opinfo/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/utils/__pycache__/cpp_extension.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/cuda_to_hip_mappings.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torchgen/__pycache__/model.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torchvision/_C_stable.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torchvision/image_stable.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/transforms.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_geometry.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torchvision.libs/libjpeg.185109e6.so.8 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torchvision.libs/libpng16.fdd68bd0.so.16 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torchvision.libs/libwebp.14e109ad.so.7 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.12/site-packages/torchvision.libs/libz.1140de3a.so.1 filter=lfs diff=lfs merge=lfs -text diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/METADATA b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b76ff29a85ee7aeeae022a69e077e9dc1794ee06 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/METADATA @@ -0,0 +1,745 @@ +Metadata-Version: 2.4 +Name: torch +Version: 2.14.0+cpu +Summary: Tensors and Dynamic neural networks in Python with strong GPU acceleration +Keywords: pytorch,machine learning +Author-Email: PyTorch Team +License-Expression: Apache-2.0 AND Apache-2.0 WITH LLVM-exception AND BSD-2-Clause AND BSD-3-Clause AND BSL-1.0 AND MIT +License-File: LICENSE +License-File: third_party/FP16/LICENSE +License-File: third_party/FXdiv/LICENSE +License-File: third_party/NNPACK/LICENSE +License-File: third_party/NVTX/LICENSE.txt +License-File: third_party/NVTX/docs/LICENSE.txt +License-File: third_party/NVTX/python/LICENSE.txt +License-File: third_party/NVTX/rust/LICENSE +License-File: third_party/VulkanMemoryAllocator/LICENSE.txt +License-File: third_party/XNNPACK/LICENSE +License-File: third_party/aiter/3rdparty/composable_kernel/LICENSE +License-File: third_party/aiter/LICENSE +License-File: third_party/benchmark/LICENSE +License-File: third_party/composable_kernel/LICENSE +License-File: third_party/cpp-httplib/LICENSE +License-File: third_party/cpuinfo/LICENSE +License-File: third_party/cpuinfo/deps/clog/LICENSE +License-File: third_party/cudnn_frontend/LICENSE.txt +License-File: third_party/cutlass/LICENSE.txt +License-File: third_party/cutlass/python/LICENSE.txt +License-File: third_party/fbgemm/LICENSE +License-File: third_party/fbgemm/external/composable_kernel/LICENSE +License-File: third_party/fbgemm/external/cpuinfo/LICENSE +License-File: third_party/fbgemm/external/cpuinfo/deps/clog/LICENSE +License-File: third_party/fbgemm/external/cutlass/LICENSE.txt +License-File: third_party/fbgemm/external/cutlass/python/LICENSE.txt +License-File: third_party/fbgemm/external/googletest/LICENSE +License-File: third_party/fbgemm/external/hipify_torch/LICENSE.txt +License-File: third_party/fbgemm/fbgemm_gpu/experimental/hstu/LICENSE +License-File: third_party/fbgemm/fbgemm_gpu/src/quantize_ops/mx/LICENSE +License-File: third_party/fbgemm/fbgemm_gpu/test/quantize/mx/LICENSE +License-File: third_party/flash-attention/LICENSE +License-File: third_party/flash-attention/csrc/composable_kernel/LICENSE +License-File: third_party/flash-attention/csrc/cutlass/LICENSE.txt +License-File: third_party/flash-attention/csrc/cutlass/python/LICENSE.txt +License-File: third_party/flash-attention/flash_attn/cute/LICENSE +License-File: third_party/flash-attention/third_party/aiter/3rdparty/composable_kernel/LICENSE +License-File: third_party/flash-attention/third_party/aiter/LICENSE +License-File: third_party/flatbuffers/LICENSE +License-File: third_party/flatbuffers/dart/LICENSE +License-File: third_party/flatbuffers/swift/LICENSE +License-File: third_party/fmt/LICENSE +License-File: third_party/gemmlowp/gemmlowp/LICENSE +License-File: third_party/gloo/LICENSE +License-File: third_party/googletest/LICENSE +License-File: third_party/ideep/LICENSE +License-File: third_party/ideep/mkl-dnn/LICENSE +License-File: third_party/ideep/mkl-dnn/third_party/gtest/LICENSE +License-File: third_party/ideep/mkl-dnn/third_party/opencl/LICENSE +License-File: third_party/kineto/LICENSE +License-File: third_party/kineto/libkineto/third_party/dynolog_headers/LICENSE +License-File: third_party/kineto/libkineto/third_party/fmt/LICENSE +License-File: third_party/kineto/libkineto/third_party/googletest/LICENSE +License-File: third_party/llvm-openmp/LICENSE.txt +License-File: third_party/mimalloc/LICENSE +License-File: third_party/miniz-3.0.2/LICENSE +License-File: third_party/mslk/LICENSE +License-File: third_party/mslk/external/composable_kernel/LICENSE +License-File: third_party/mslk/external/cutlass/LICENSE.txt +License-File: third_party/mslk/external/cutlass/python/LICENSE.txt +License-File: third_party/mslk/external/googletest/LICENSE +License-File: third_party/mslk/external/hipify_torch/LICENSE.txt +License-File: third_party/mslk/mslk/attention/flash_attn/LICENSE +License-File: third_party/onnx/LICENSE +License-File: third_party/onnx/third_party/pybind11/LICENSE +License-File: third_party/perfetto/LICENSE +License-File: third_party/protobuf/LICENSE +License-File: third_party/protobuf/third_party/benchmark/LICENSE +License-File: third_party/protobuf/third_party/googletest/LICENSE +License-File: third_party/protobuf/third_party/googletest/googlemock/LICENSE +License-File: third_party/protobuf/third_party/googletest/googlemock/scripts/generator/LICENSE +License-File: third_party/protobuf/third_party/googletest/googletest/LICENSE +License-File: third_party/protobuf/third_party/utf8_range/LICENSE +License-File: third_party/psimd/LICENSE +License-File: third_party/pthreadpool/LICENSE +License-File: third_party/pybind11/LICENSE +License-File: third_party/python-peachpy/LICENSE.rst +License-File: third_party/sleef/LICENSE.txt +License-File: third_party/tensorpipe/LICENSE.txt +License-File: third_party/tensorpipe/third_party/googletest/LICENSE +License-File: third_party/tensorpipe/third_party/googletest/googlemock/LICENSE +License-File: third_party/tensorpipe/third_party/googletest/googlemock/scripts/generator/LICENSE +License-File: third_party/tensorpipe/third_party/googletest/googletest/LICENSE +License-File: third_party/tensorpipe/third_party/libnop/LICENSE +License-File: third_party/tensorpipe/third_party/libuv/LICENSE +License-File: third_party/tensorpipe/third_party/pybind11/LICENSE +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Programming Language :: C++ +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 +Project-URL: Homepage, https://pytorch.org +Project-URL: Repository, https://github.com/pytorch/pytorch +Project-URL: Documentation, https://pytorch.org/docs +Project-URL: Issue Tracker, https://github.com/pytorch/pytorch/issues +Project-URL: Forum, https://discuss.pytorch.org +Requires-Python: >=3.10 +Requires-Dist: filelock +Requires-Dist: typing-extensions>=4.10.0 +Requires-Dist: setuptools>=77.0.3 +Requires-Dist: sympy>=1.13.3 +Requires-Dist: networkx>=2.5.1 +Requires-Dist: jinja2 +Requires-Dist: fsspec>=0.8.5 +Provides-Extra: optree +Requires-Dist: optree>=0.13.0; extra == "optree" +Provides-Extra: opt-einsum +Requires-Dist: opt-einsum>=3.3; extra == "opt-einsum" +Provides-Extra: pyyaml +Requires-Dist: pyyaml; extra == "pyyaml" +Description-Content-Type: text/markdown + + + + + PyTorch logo + + +-------------------------------------------------------------------------------- + +PyTorch is a Python package that provides two high-level features: +- Tensor computation (like NumPy) with strong GPU acceleration +- Deep neural networks built on a tape-based autograd system + +You can reuse your favorite Python packages such as NumPy, SciPy, and Cython to extend PyTorch when needed. + +Our trunk health (Continuous Integration signals) can be found at [hud.pytorch.org](https://hud.pytorch.org/ci/pytorch/pytorch/main). + + + +- [More About PyTorch](#more-about-pytorch) + - [A GPU-Ready Tensor Library](#a-gpu-ready-tensor-library) + - [Dynamic Neural Networks: Tape-Based Autograd](#dynamic-neural-networks-tape-based-autograd) + - [Python First](#python-first) + - [Imperative Experiences](#imperative-experiences) + - [Fast and Lean](#fast-and-lean) + - [Extensions Without Pain](#extensions-without-pain) +- [Installation](#installation) + - [Binaries](#binaries) + - [NVIDIA Jetson Platforms](#nvidia-jetson-platforms) + - [From Source](#from-source) + - [Prerequisites](#prerequisites) + - [NVIDIA CUDA Support](#nvidia-cuda-support) + - [AMD ROCm Support](#amd-rocm-support) + - [Intel GPU Support](#intel-gpu-support) + - [Get the PyTorch Source](#get-the-pytorch-source) + - [Install Dependencies](#install-dependencies) + - [Install PyTorch](#install-pytorch) + - [Adjust Build Options (Optional)](#adjust-build-options-optional) + - [Docker Image](#docker-image) + - [Using pre-built images](#using-pre-built-images) + - [Building the image yourself](#building-the-image-yourself) + - [Building the Documentation](#building-the-documentation) + - [Troubleshooting CI Errors](#troubleshooting-ci-errors) + - [Building a PDF](#building-a-pdf) + - [Previous Versions](#previous-versions) +- [Getting Started](#getting-started) +- [Resources](#resources) +- [Communication](#communication) +- [Releases and Contributing](#releases-and-contributing) +- [The Team](#the-team) +- [License](#license) + + + +## More About PyTorch + +[Learn the basics of PyTorch](https://pytorch.org/tutorials/beginner/basics/intro.html) + +At a granular level, PyTorch is a library that consists of the following components: + +| Component | Description | +| ---- | --- | +| [**torch**](https://pytorch.org/docs/stable/torch.html) | A Tensor library like NumPy, with strong GPU support | +| [**torch.autograd**](https://pytorch.org/docs/stable/autograd.html) | A tape-based automatic differentiation library that supports all differentiable Tensor operations in torch | +| [**torch.jit**](https://pytorch.org/docs/stable/jit.html) | A compilation stack (TorchScript) to create serializable and optimizable models from PyTorch code | +| [**torch.nn**](https://pytorch.org/docs/stable/nn.html) | A neural networks library deeply integrated with autograd designed for maximum flexibility | +| [**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 | +| [**torch.utils**](https://pytorch.org/docs/stable/data.html) | DataLoader and other utility functions for convenience | + +Usually, PyTorch is used either as: + +- A replacement for NumPy to use the power of GPUs. +- A deep learning research platform that provides maximum flexibility and speed. + +Elaborating Further: + +### A GPU-Ready Tensor Library + +If you use NumPy, then you have used Tensors (a.k.a. ndarray). + +![Tensor illustration](https://github.com/pytorch/pytorch/raw/main/docs/source/_static/img/tensor_illustration.png) + +PyTorch provides Tensors that can live either on the CPU or the GPU and accelerates the +computation by a huge amount. + +We provide a wide variety of tensor routines to accelerate and fit your scientific computation needs +such as slicing, indexing, mathematical operations, linear algebra, reductions. +And they are fast! + +### Dynamic Neural Networks: Tape-Based Autograd + +PyTorch has a unique way of building neural networks: using and replaying a tape recorder. + +Most frameworks such as TensorFlow, Theano, Caffe, and CNTK have a static view of the world. +One has to build a neural network and reuse the same structure again and again. +Changing the way the network behaves means that one has to start from scratch. + +With PyTorch, we use a technique called reverse-mode auto-differentiation, which allows you to +change the way your network behaves arbitrarily with zero lag or overhead. Our inspiration comes +from several research papers on this topic, as well as current and past work such as +[torch-autograd](https://github.com/twitter/torch-autograd), +[autograd](https://github.com/HIPS/autograd), +[Chainer](https://chainer.org), etc. + +While this technique is not unique to PyTorch, it's one of the fastest implementations of it to date. +You get the best of speed and flexibility for your crazy research. + +![Dynamic graph](https://github.com/pytorch/pytorch/raw/main/docs/source/_static/img/dynamic_graph.gif) + +### Python First + +PyTorch is not a Python binding into a monolithic C++ framework. +It is built to be deeply integrated into Python. +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. +You can write your new neural network layers in Python itself, using your favorite libraries +and use packages such as [Cython](https://cython.org/) and [Numba](https://numba.pydata.org/). +Our goal is to not reinvent the wheel where appropriate. + +### Imperative Experiences + +PyTorch is designed to be intuitive, linear in thought, and easy to use. +When you execute a line of code, it gets executed. There isn't an asynchronous view of the world. +When you drop into a debugger or receive error messages and stack traces, understanding them is straightforward. +The stack trace points to exactly where your code was defined. +We hope you never spend hours debugging your code because of bad stack traces or asynchronous and opaque execution engines. + +### Fast and Lean + +PyTorch has minimal framework overhead. We integrate acceleration libraries +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. +At the core, its CPU and GPU Tensor and neural network backends +are mature and have been tested for years. + +Hence, PyTorch is quite fast — whether you run small or large neural networks. + +The memory usage in PyTorch is extremely efficient compared to Torch or some of the alternatives. +We've written custom memory allocators for the GPU to make sure that +your deep learning models are maximally memory efficient. +This enables you to train bigger deep learning models than before. + +### Extensions Without Pain + +Writing new neural network modules, or interfacing with PyTorch's Tensor API, was designed to be straightforward +and with minimal abstractions. + +You can write new neural network layers in Python using the torch API +[or your favorite NumPy-based libraries such as SciPy](https://pytorch.org/tutorials/advanced/numpy_extensions_tutorial.html). + +If you want to write your layers in C/C++, we provide a convenient extension API that is efficient and with minimal boilerplate. +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). + + +## Installation + +### Binaries +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/) + + +#### NVIDIA Jetson Platforms + +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) + +They require JetPack 4.2 and above, and [@dusty-nv](https://github.com/dusty-nv) and [@ptrblck](https://github.com/ptrblck) are maintaining them. + + +### From Source + +#### Prerequisites +If you are installing from source, you will need: +- Python 3.10 or later +- A compiler that fully supports C++20, such as clang or gcc (gcc 11.3.0 or newer is required, on Linux) +- Visual Studio or Visual Studio Build Tool (Windows only) +- At least 10 GB of free disk space +- 30-60 minutes for the initial build (subsequent rebuilds are much faster) + +\* PyTorch CI uses Visual C++ BuildTools, which come with Visual Studio Enterprise, +Professional, or Community Editions. You can also install the build tools from +https://visualstudio.microsoft.com/visual-cpp-build-tools/. The build tools *do not* +come with Visual Studio Code by default. + +An example of environment setup is shown below: + +* Linux: + +```bash +$ source /bin/activate +$ conda create -y -n +$ conda activate +``` +* Windows: + +```bash +$ source \Scripts\activate.bat +$ conda create -y -n +$ conda activate +$ call "C:\Program Files\Microsoft Visual Studio\\Community\VC\Auxiliary\Build\vcvarsall.bat" x64 +``` + +A conda environment is not required. You can also do a PyTorch build in a +standard virtual environment, e.g., created with tools like `uv`, provided +your system has installed all the necessary dependencies unavailable as pip +packages (e.g., CUDA, MKL.) + +##### NVIDIA CUDA Support +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: +- [NVIDIA CUDA](https://developer.nvidia.com/cuda-downloads) +- [NVIDIA cuDNN](https://developer.nvidia.com/cudnn) v9.0 or above +- [Compiler](https://gist.github.com/ax3l/9489132) compatible with CUDA + +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. + +If you want to disable CUDA support, export the environment variable `USE_CUDA=0`. +Other potentially useful environment variables are documented in `cmake/EnvVarForwarding.cmake`. If +CUDA is installed in a non-standard location, set PATH so that the nvcc you +want to use can be found (e.g., `export PATH=/usr/local/cuda-12.8/bin:$PATH`). + +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/) + +##### AMD ROCm Support +If you want to compile with ROCm support, install +- [AMD ROCm](https://rocm.docs.amd.com/en/latest/deploy/linux/quick_start.html) 4.0 and above installation +- ROCm is currently supported only for Linux systems. + +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) + +If you want to disable ROCm support, export the environment variable `USE_ROCM=0`. +Other potentially useful environment variables are documented in `cmake/EnvVarForwarding.cmake`. + +##### Intel GPU Support +If you want to compile with Intel GPU support, follow these +- [PyTorch Prerequisites for Intel GPUs](https://www.intel.com/content/www/us/en/developer/articles/tool/pytorch-prerequisites-for-intel-gpu.html) instructions. +- Intel GPU is supported for Linux and Windows. + +If you want to disable Intel GPU support, export the environment variable `USE_XPU=0`. +Other potentially useful environment variables are documented in `cmake/EnvVarForwarding.cmake`. + +#### Get the PyTorch Source + +```bash +git clone https://github.com/pytorch/pytorch +cd pytorch +# if you are updating an existing checkout +git submodule sync +git submodule update --init --recursive +``` + +#### Install Dependencies + +**Common** + +```bash +# Run this command from the PyTorch directory after cloning the source code using the “Get the PyTorch Source“ section above +pip install --group dev +``` + +**On Linux** + +```bash +pip install mkl-static mkl-include +# CUDA only: Add LAPACK support for the GPU if needed +# magma installation: run with active conda environment. specify CUDA version to install +.ci/docker/common/install_magma_conda.sh 12.4 + +# (optional) If using torch.compile with inductor/triton, install the matching version of triton +# Run from the pytorch directory after cloning +# For Intel GPU support, please explicitly `export USE_XPU=1` before running command. +make triton +``` + +**On Windows** + +```bash +pip install mkl-static mkl-include +# Add these packages if torch.distributed is needed. +# Distributed package support on Windows is a prototype feature and is subject to changes. +conda install -c conda-forge libuv=1.51 +``` + +#### Install PyTorch + +**On Linux** + +If you're compiling for AMD ROCm then first run this command: + +```bash +# Only run this if you're compiling for ROCm +python tools/amd_build/build_amd.py +``` + +Install PyTorch + +```bash +# the CMake prefix for conda environment +export CMAKE_PREFIX_PATH="${CONDA_PREFIX:-'$(dirname $(which conda))/../'}:${CMAKE_PREFIX_PATH}" +python -m pip install --no-build-isolation -v -e . + +# the CMake prefix for non-conda environment, e.g. Python venv +# call following after activating the venv +export CMAKE_PREFIX_PATH="${VIRTUAL_ENV}:${CMAKE_PREFIX_PATH}" +``` + +**On macOS** + +```bash +python -m pip install --no-build-isolation -v -e . +``` + +**On Windows** + +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) + +**CPU-only builds** + +In this mode PyTorch computations will run on your CPU, not your GPU. + +```cmd +python -m pip install --no-build-isolation -v -e . +``` + +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://docs.pytorch.org/docs/main/notes/windows.html#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. + +**CUDA based build** + +In this mode PyTorch computations will leverage your GPU via CUDA for faster number crunching + +[NVTX](https://docs.nvidia.com/gameworks/content/gameworkslibrary/nvtx/nvidia_tools_extension_library_nvtx.htm) is needed to build PyTorch with CUDA. +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. +Make sure that CUDA with Nsight Compute is installed after Visual Studio. + +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. +
If Ninja is selected as the generator, the latest MSVC will get selected as the underlying toolchain. + +Additional libraries such as +[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. + +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 + +```cmd +cmd + +:: Set the environment variables after you have downloaded and unzipped the mkl package, +:: else CMake would throw an error as `Could NOT find OpenMP`. +set CMAKE_INCLUDE_PATH={Your directory}\mkl\include +set LIB={Your directory}\mkl\lib;%LIB% + +:: Read the content in the previous section carefully before you proceed. +:: [Optional] If you want to override the underlying toolset used by Ninja and Visual Studio with CUDA, please run the following script block. +:: "Visual Studio 2019 Developer Command Prompt" will be run automatically. +:: Make sure you have CMake >= 3.12 before you do this when you use the Visual Studio generator. +set CMAKE_GENERATOR_TOOLSET_VERSION=14.27 +set DISTUTILS_USE_SDK=1 +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% + +:: [Optional] If you want to override the CUDA host compiler +set CUDAHOSTCXX=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\bin\HostX64\x64\cl.exe + +python -m pip install --no-build-isolation -v -e . +``` + +**Intel GPU builds** + +In this mode PyTorch with Intel GPU support will be built. + +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. + +Then PyTorch can be built with the command: + +```cmd +:: CMD Commands: +:: Set the CMAKE_PREFIX_PATH to help find corresponding packages +:: %CONDA_PREFIX% only works after `conda activate custom_env` + +if defined CMAKE_PREFIX_PATH ( + set "CMAKE_PREFIX_PATH=%CONDA_PREFIX%\Library;%CMAKE_PREFIX_PATH%" +) else ( + set "CMAKE_PREFIX_PATH=%CONDA_PREFIX%\Library" +) + +python -m pip install --no-build-isolation -v -e . +``` + +##### Adjust Build Options (Optional) + +You can adjust the configuration of CMake variables through environment variables, which the +build forwards to CMake (see [`cmake/EnvVarForwarding.cmake`](./cmake/EnvVarForwarding.cmake) for +the full list). For example, pointing the build at a specific Conda prefix, CuDNN, or BLAS: + +On Linux + +```bash +export CMAKE_PREFIX_PATH="${CONDA_PREFIX:-'$(dirname $(which conda))/../'}:${CMAKE_PREFIX_PATH}" +spin develop +``` + +On macOS + +```bash +export CMAKE_PREFIX_PATH="${CONDA_PREFIX:-'$(dirname $(which conda))/../'}:${CMAKE_PREFIX_PATH}" +MACOSX_DEPLOYMENT_TARGET=11.0 spin develop +``` + +After a first `spin develop`, you can inspect or adjust the CMake cache interactively with +`ccmake build` (or `cmake-gui build`) and rebuild with `spin develop`; your edits persist, because +reconfiguration does not use `--fresh` and environment variables only seed cache entries that are +not already set. The corollary: once a variable is in the cache, changing its environment variable +no longer affects it -- edit the cache directly (or delete `build/CMakeCache.txt`) to change it. +The build type and compiler are the exception; the build always re-applies them. + +### Docker Image + +#### Using pre-built images + +You can also pull a pre-built docker image from Docker Hub and run with docker v23.0+ + +```bash +docker run --gpus all --rm -ti --ipc=host pytorch/pytorch:latest +``` + +Please note that PyTorch uses shared memory to share data between processes, so if torch multiprocessing is used (e.g. +for multithreaded data loaders) the default shared memory segment size that container runs with is not enough, and you +should increase shared memory size either with `--ipc=host` or `--shm-size` command line options to `nvidia-docker run`. + +#### Building the image yourself + +**NOTE:** Must be built with a Docker version >= 23.0 + +The Dockerfile is supplied to build images with CUDA 12.6 support and cuDNN v9. +You can pass `PYTHON_VERSION=x.y` make variable to specify which Python version is to be used by Miniconda, or leave it +unset to use the default, as the Dockerfile uses system Python. + +```bash +make -f docker.Makefile +# images are tagged as docker.io/${your_docker_username}/pytorch +``` + +You can also pass the `CMAKE_VARS="..."` environment variable to specify additional CMake variables to be passed to CMake during the build. +See [`cmake/EnvVarForwarding.cmake`](./cmake/EnvVarForwarding.cmake) for the list of available variables. + +```bash +make -f docker.Makefile +``` + +### Building the Documentation + +To build documentation in various formats, you will need [Sphinx](https://www.sphinx-doc.org) +and the `pytorch_sphinx_theme2`. + +Before you build the documentation locally, ensure `torch` is +installed in your environment. For small fixes, you can install the +nightly version as described in [Getting Started](https://pytorch.org/get-started/locally/). + +For more complex fixes, such as adding a new module and docstrings for +the new module, you might need to install torch [from source](#from-source). +See [Docstring Guidelines](https://github.com/pytorch/pytorch/wiki/Docstring-Guidelines) +for docstring conventions. + +```bash +cd docs/ +pip install -r requirements.txt +make html +make serve +``` + +Run `make` to get a list of all available output formats. + +If you get a katex error run `npm install katex`. If it persists, try +`npm install -g katex` + +> [!NOTE] +> If you see a numpy incompatibility error, run: +> ``` +> pip install 'numpy<2' +> ``` + + +#### Troubleshooting CI Errors +Your build may show errors you didn't have locally - here's how to find the errors relevant to the docs. + +If the build has any errors, you will see something like this on the PR: + +Monosnap Update installation instructions for doc build · Pull Request #169534 · pytorch:pytorch 2025-12-18 18-22-53 + +Any doc-related errors will occur in jobs that include "doc" somewhere in the title. It doesn't look like any of these jobs are relevant to our docs. + + +Let's take a look anyway. Click on the job to see the logs: + +Monosnap Update installation instructions for doc build · pytorch:pytorch@7380336 2025-12-18 18-24-15 + +And we can be sure that this job does not involve docs. + +Looking at this build, we can see these jobs are relevant to our docs - and they didn't have any errors: + +Check the docs jobs + +You might also see a comment on the PR like this: + +PR Comment + +We can see that some of these issues are relevant to our docs. + +Open the logs by clicking on the `gh` link: + +View Logs + +And here we can see there is a doc-related error: + +Doc Error + +You can always find the relevant doc builds by going to the `Checks` tab on your PR, and scrolling down to `pull`. + +checks + +You can either click through or toggle the accordion to see all of the jobs here, where you can see the docs jobs highlighted: + +jobs + +If you click through, you'll see the doc jobs at the bottom, like this: + +View Docs jobs + + +#### Building a PDF + +To compile a PDF of all PyTorch documentation, ensure you have +`texlive` and LaTeX installed. On macOS, you can install them using: + +``` +brew install --cask mactex +``` + +To create the PDF: + +1. Run: + + ``` + make latexpdf + ``` + + This will generate the necessary files in the `build/latex` directory. + +2. Navigate to this directory and execute: + + ``` + make LATEXOPTS="-interaction=nonstopmode" + ``` + + This will produce a `pytorch.pdf` with the desired content. Run this + command one more time so that it generates the correct table + of contents and index. + +> [!NOTE] +> To view the Table of Contents, switch to the **Table of Contents** +> view in your PDF viewer. + + +### Previous Versions + +Installation instructions and binaries for previous PyTorch versions may be found +on [our website](https://pytorch.org/get-started/previous-versions). + + +## Getting Started + +Pointers to get you started: +- [Tutorials: get you started with understanding and using PyTorch](https://pytorch.org/tutorials/) +- [Examples: easy to understand PyTorch code across all domains](https://github.com/pytorch/examples) +- [The API Reference](https://pytorch.org/docs/) +- [Glossary](https://github.com/pytorch/pytorch/blob/main/GLOSSARY.md) + +## Resources + +* [PyTorch.org](https://pytorch.org/) +* [PyTorch Tutorials](https://pytorch.org/tutorials/) +* [PyTorch Examples](https://github.com/pytorch/examples) +* [PyTorch Models](https://pytorch.org/hub/) +* [Intro to Deep Learning with PyTorch from Udacity](https://www.udacity.com/course/deep-learning-pytorch--ud188) +* [Intro to Machine Learning with PyTorch from Udacity](https://www.udacity.com/course/intro-to-machine-learning-nanodegree--nd229) +* [Deep Neural Networks with PyTorch from Coursera](https://www.coursera.org/learn/deep-neural-networks-with-pytorch) +* [PyTorch Twitter](https://twitter.com/PyTorch) +* [PyTorch Blog](https://pytorch.org/blog/) +* [PyTorch YouTube](https://www.youtube.com/channel/UCWXI5YeOsh03QvJ59PMaXFw) + +## Communication +* Forums: Discuss implementations, research, etc. https://discuss.pytorch.org +* GitHub Issues: Bug reports, feature requests, install issues, RFCs, thoughts, etc. +* 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 +* Newsletter: No-noise, a one-way email newsletter with important announcements about PyTorch. You can sign-up here: https://eepurl.com/cbG0rv +* Facebook Page: Important announcements about PyTorch. https://www.facebook.com/pytorch +* For brand guidelines, please visit our website at [pytorch.org](https://pytorch.org/) + +## Releases and Contributing + +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). + +We appreciate all contributions. If you are planning to contribute back bug-fixes, please do so without any further discussion. + +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. +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. + +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). + +## The Team + +PyTorch is a community-driven project with several skillful engineers and researchers contributing to it. + +PyTorch is currently maintained by [Soumith Chintala](https://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. +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). + +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. + +## License + +PyTorch has a BSD-style license, as found in the [LICENSE](LICENSE) file. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/RECORD b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..eb912c38b66ac56f410ec996b683cfd70b59618f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/RECORD @@ -0,0 +1,14837 @@ +../../../bin/torchfrtrace,sha256=C5K2NY85sGFbnqcl81UNnB1lNuqbNrIIK9_85YDQJx8,273 +../../../bin/torchrun,sha256=wi9JGiYafS1QDmfn0h1Oip8-Eg3CA1vyRZx9-02b6zE,252 +functorch/__init__.py,sha256=NAwGN21zq-tccaF-ROtv-VWFoPdb7y9iuAt6Hy6QCtc,1037 +functorch/__pycache__/__init__.cpython-312.pyc,, +functorch/_src/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +functorch/_src/__pycache__/__init__.cpython-312.pyc,, +functorch/_src/aot_autograd/__init__.py,sha256=SGo7gh6XGYcOxTGf5g-R8Y9AF95ICcJbQwQD6rFyrpQ,291 +functorch/_src/aot_autograd/__pycache__/__init__.cpython-312.pyc,, +functorch/_src/eager_transforms/__init__.py,sha256=kX_52fDvSX9YX9OAwo5bjvJtrxyjEBUJ1PueW8xgsuw,291 +functorch/_src/eager_transforms/__pycache__/__init__.cpython-312.pyc,, +functorch/_src/make_functional/__init__.py,sha256=b3y8s3KhtCqFB8lM4Pi48AwuztUt7NBK-VISZNJYYjw,235 +functorch/_src/make_functional/__pycache__/__init__.cpython-312.pyc,, +functorch/_src/vmap/__init__.py,sha256=k8r2Esz6tB5D7U_UA0_BCDaWoOmn8JNVrRqK7nG7_fM,467 +functorch/_src/vmap/__pycache__/__init__.cpython-312.pyc,, +functorch/compile/__init__.py,sha256=fZnNG56VBLfKlXMqX5Rj3tORQYLyxbyoA0rEoEBt3KM,756 +functorch/compile/__pycache__/__init__.cpython-312.pyc,, +functorch/dim/__init__.py,sha256=uQEKMitItfVkGFolejbBM4RhfVUe1pbCiFbC5B9bdgY,53600 +functorch/dim/__pycache__/__init__.cpython-312.pyc,, +functorch/dim/__pycache__/_dim_entry.cpython-312.pyc,, +functorch/dim/__pycache__/_enable_all_layers.cpython-312.pyc,, +functorch/dim/__pycache__/_getsetitem.cpython-312.pyc,, +functorch/dim/__pycache__/_order.cpython-312.pyc,, +functorch/dim/__pycache__/_py_inst_decoder.cpython-312.pyc,, +functorch/dim/__pycache__/_tensor_info.cpython-312.pyc,, +functorch/dim/__pycache__/_wrap.cpython-312.pyc,, +functorch/dim/__pycache__/magic_trace.cpython-312.pyc,, +functorch/dim/__pycache__/op_properties.cpython-312.pyc,, +functorch/dim/__pycache__/wrap_type.cpython-312.pyc,, +functorch/dim/_dim_entry.py,sha256=cceDVoHZemWMtW72AoGJCpZBp_lyOSDCdABJ29RLbmQ,3884 +functorch/dim/_enable_all_layers.py,sha256=xKbVnuuh2MhC7GjZLDGpk_DD-wyMT-uDBBgVU-KSuCs,5220 +functorch/dim/_getsetitem.py,sha256=8dL1J7e2wvUx7xw9r-Ffunn075fjK82CX94RHGtxbgY,19039 +functorch/dim/_order.py,sha256=0n1ew1EHEQZnpxiwC0_k7vkno5-wLiOfRkhnKhYut04,7011 +functorch/dim/_py_inst_decoder.py,sha256=OUIOiKA0zZ2C3b8iCRgD9woShn1VkHNrJRVXneJa40E,2091 +functorch/dim/_tensor_info.py,sha256=eXHojr8bOn-1N5vkWVDIlmpp7o9iwCexXxAP4vXL4A4,2098 +functorch/dim/_wrap.py,sha256=NaV0AQZx0yDRw_37U4jfSS_B_ko9XHUqdocz7XHPu2Q,8385 +functorch/dim/magic_trace.py,sha256=spyJfvOiY6sUnfiDwLGE2Pejv5DyFSnZBmbio0nh1iA,1547 +functorch/dim/op_properties.py,sha256=GpW8Ylgq1YlMilQh6cgNQ66tAiN84WRyEjn_VkbJYFQ,6687 +functorch/dim/wrap_type.py,sha256=haCYf-nAHCw236O1jh8GHjFgmzDNKrltdNvtVG7y7pU,2090 +functorch/einops/__init__.py,sha256=RB-E_A0arSGp5Jq-lSgiFNmzbFLqOLiBldHIM_mDkhU,123 +functorch/einops/__pycache__/__init__.cpython-312.pyc,, +functorch/einops/__pycache__/_parsing.cpython-312.pyc,, +functorch/einops/__pycache__/rearrange.cpython-312.pyc,, +functorch/einops/_parsing.py,sha256=yjwK7zoSov-VRwJzYZsGDQ-rBFb5RCApZ6Dln9Y2NIE,12208 +functorch/einops/rearrange.py,sha256=CteVEEZAp1ideLxH5waINiALjdjrAX6cBNC8L9UdwQo,8171 +functorch/experimental/__init__.py,sha256=qgO0Y4xqrtxucMbH-Q__wtJGvzRk9ckQIqo7E94-ROA,274 +functorch/experimental/__pycache__/__init__.cpython-312.pyc,, +functorch/experimental/__pycache__/control_flow.cpython-312.pyc,, +functorch/experimental/__pycache__/ops.cpython-312.pyc,, +functorch/experimental/control_flow.py,sha256=CyLqEoRLJT5fSnwcTrmw_3LQk9SD54fJElQ4stSD_64,144 +functorch/experimental/ops.py,sha256=kDGcckdoYwOg9fS4JqvZnsIt8Ss9O6RGeasJSyi0OUY,57 +torch-2.14.0+cpu.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +torch-2.14.0+cpu.dist-info/METADATA,sha256=bmy_3IBnqR_p-lBoGRV0yu9tBMdD2oBXB7hJOWqINPY,37280 +torch-2.14.0+cpu.dist-info/RECORD,, +torch-2.14.0+cpu.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch-2.14.0+cpu.dist-info/WHEEL,sha256=1WzRSgOsss9wFiZXQF3W2MIH5agmCQYpgJjGjVexvwU,117 +torch-2.14.0+cpu.dist-info/entry_points.txt,sha256=hnQqqq0heOm2BptofMCEZSfLcRg-0zXgLqD17YT7LgM,848 +torch-2.14.0+cpu.dist-info/licenses/LICENSE,sha256=vQGP7viCXogYHITrfjqk6vuPCKINn9bvlIVpYQxKPkM,3464 +torch-2.14.0+cpu.dist-info/licenses/third_party/FP16/LICENSE,sha256=F-T1OQJL4nSe5ynR4vAdJM7xLs6Mm_GOkaQ0m-KcgL8,1157 +torch-2.14.0+cpu.dist-info/licenses/third_party/FXdiv/LICENSE,sha256=fKwAAGElsUhqJ-SAHtZjVyNumExUC9MjlFq3tmsHjsM,1117 +torch-2.14.0+cpu.dist-info/licenses/third_party/NNPACK/LICENSE,sha256=qwnjNiH1E-vdHvaFsyTznB9r7pIh0VYAuv2VgyLfEjE,1352 +torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/LICENSE.txt,sha256=q9_YpnOLJ80VBOCR93toLbrpKDOfBAuKb1mlSCRZkaA,12483 +torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/docs/LICENSE.txt,sha256=q9_YpnOLJ80VBOCR93toLbrpKDOfBAuKb1mlSCRZkaA,12483 +torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/python/LICENSE.txt,sha256=q9_YpnOLJ80VBOCR93toLbrpKDOfBAuKb1mlSCRZkaA,12483 +torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/rust/LICENSE,sha256=4WXtd4VPR_sgiFDSPZNanwq4u0UnOBRmvusWAl4vbp4,12449 +torch-2.14.0+cpu.dist-info/licenses/third_party/VulkanMemoryAllocator/LICENSE.txt,sha256=jXDkzyqZQfZFTacc1g44SE3T40gQyCR2DVUOmCr22Xo,1099 +torch-2.14.0+cpu.dist-info/licenses/third_party/XNNPACK/LICENSE,sha256=Y_UZ4Vcm9MT4ML2Vj2lMhP7LTgpMrMUn0mlrtx75Wto,1560 +torch-2.14.0+cpu.dist-info/licenses/third_party/aiter/3rdparty/composable_kernel/LICENSE,sha256=IPO4Pf2gG9GNKF4O27nQRL5t3gTN92oewY2fxxJ5Nr8,1726 +torch-2.14.0+cpu.dist-info/licenses/third_party/aiter/LICENSE,sha256=C6yoCZJ8rUSEAbJSzjuuEmh8KYdZetcIjPNCP4ctW80,1100 +torch-2.14.0+cpu.dist-info/licenses/third_party/benchmark/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +torch-2.14.0+cpu.dist-info/licenses/third_party/composable_kernel/LICENSE,sha256=IPO4Pf2gG9GNKF4O27nQRL5t3gTN92oewY2fxxJ5Nr8,1726 +torch-2.14.0+cpu.dist-info/licenses/third_party/cpp-httplib/LICENSE,sha256=S0XL4W17cbia5hJ-JuDZCgKRmMpelYrY49C4u-02TYs,1075 +torch-2.14.0+cpu.dist-info/licenses/third_party/cpuinfo/LICENSE,sha256=jn5gY2w6oMsDVxoahBzlaX-VUf-Ss8QmwlYWE9Fa3nA,1424 +torch-2.14.0+cpu.dist-info/licenses/third_party/cpuinfo/deps/clog/LICENSE,sha256=aKFMPnmt0CPuzYPWEec_Bbi_HRaFLv6360AzqWc22p4,1384 +torch-2.14.0+cpu.dist-info/licenses/third_party/cudnn_frontend/LICENSE.txt,sha256=P8S0c6LAh2ioBmv35KWKEYUGDzrWdPLKniARvKSt8s4,1148 +torch-2.14.0+cpu.dist-info/licenses/third_party/cutlass/LICENSE.txt,sha256=rRUTypg9pzemhDNkrRnoQkpW2GBzbC2nc7jFvlJ-FHU,1861 +torch-2.14.0+cpu.dist-info/licenses/third_party/cutlass/python/LICENSE.txt,sha256=AL8YBvZkrBr-QiH18Es4T7bxym6zPvy23M9ZnrBtCLk,1547 +torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/LICENSE,sha256=EsI3DsMueBFdzXG6Is3LEpcyD9xK3oH3mBNtQjV8WLg,1535 +torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/composable_kernel/LICENSE,sha256=IPO4Pf2gG9GNKF4O27nQRL5t3gTN92oewY2fxxJ5Nr8,1726 +torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cpuinfo/LICENSE,sha256=jn5gY2w6oMsDVxoahBzlaX-VUf-Ss8QmwlYWE9Fa3nA,1424 +torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cpuinfo/deps/clog/LICENSE,sha256=aKFMPnmt0CPuzYPWEec_Bbi_HRaFLv6360AzqWc22p4,1384 +torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cutlass/LICENSE.txt,sha256=gKehi3PUH2TdnKiBrzWTj43oixjHKHAyUfTJTRKZiE0,1854 +torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cutlass/python/LICENSE.txt,sha256=Qv7GMPQQqjCPcKUaifrc0ZWG-mIPmDGjK-5SipoQAA4,1547 +torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/googletest/LICENSE,sha256=lwLefkEXqOKyDa-rEf_aWMGYrt4GZAZJa-9nDUCiITg,1475 +torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/hipify_torch/LICENSE.txt,sha256=7PgZ1VsXwvCRs7oJNNBENoqgaA2KgTdIYDBqorkaoes,1112 +torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/fbgemm_gpu/experimental/hstu/LICENSE,sha256=jJzLlsBl5wYTW2y60nm3IdphVuUfOl8nxrMymvlBbXM,1558 +torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/fbgemm_gpu/src/quantize_ops/mx/LICENSE,sha256=ws_MuBL-SCEBqPBFl9_FqZkaaydIJmxHrJG2parhU4M,1141 +torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/fbgemm_gpu/test/quantize/mx/LICENSE,sha256=ws_MuBL-SCEBqPBFl9_FqZkaaydIJmxHrJG2parhU4M,1141 +torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/LICENSE,sha256=jJzLlsBl5wYTW2y60nm3IdphVuUfOl8nxrMymvlBbXM,1558 +torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/csrc/composable_kernel/LICENSE,sha256=IPO4Pf2gG9GNKF4O27nQRL5t3gTN92oewY2fxxJ5Nr8,1726 +torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/csrc/cutlass/LICENSE.txt,sha256=gKehi3PUH2TdnKiBrzWTj43oixjHKHAyUfTJTRKZiE0,1854 +torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/csrc/cutlass/python/LICENSE.txt,sha256=Qv7GMPQQqjCPcKUaifrc0ZWG-mIPmDGjK-5SipoQAA4,1547 +torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/flash_attn/cute/LICENSE,sha256=jJzLlsBl5wYTW2y60nm3IdphVuUfOl8nxrMymvlBbXM,1558 +torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/third_party/aiter/3rdparty/composable_kernel/LICENSE,sha256=IPO4Pf2gG9GNKF4O27nQRL5t3gTN92oewY2fxxJ5Nr8,1726 +torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/third_party/aiter/LICENSE,sha256=C6yoCZJ8rUSEAbJSzjuuEmh8KYdZetcIjPNCP4ctW80,1100 +torch-2.14.0+cpu.dist-info/licenses/third_party/flatbuffers/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +torch-2.14.0+cpu.dist-info/licenses/third_party/flatbuffers/dart/LICENSE,sha256=7dmzRZvuTHm1SaXvZtBtEr0UTduNCOC0SPtCEmf0PdU,11341 +torch-2.14.0+cpu.dist-info/licenses/third_party/flatbuffers/swift/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +torch-2.14.0+cpu.dist-info/licenses/third_party/fmt/LICENSE,sha256=pl_MWhCV_DPMN-T_9pNm5J1-kvYTVYorle0bcOM3WLQ,1094 +torch-2.14.0+cpu.dist-info/licenses/third_party/gemmlowp/gemmlowp/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +torch-2.14.0+cpu.dist-info/licenses/third_party/gloo/LICENSE,sha256=KvvFcs9_YIiBWbwspIulj4rewGaCrl3oINYUSdHu6oE,1525 +torch-2.14.0+cpu.dist-info/licenses/third_party/googletest/LICENSE,sha256=lwLefkEXqOKyDa-rEf_aWMGYrt4GZAZJa-9nDUCiITg,1475 +torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/LICENSE,sha256=omrdAxB6U6YFqJcRubfb1PXdZorhk6kS4BqHk2aiOw4,1062 +torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/mkl-dnn/LICENSE,sha256=6fyHT8CYAbms80EbpyOUCYRzcE2DLXE0BLbEhhoIYxg,11607 +torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/mkl-dnn/third_party/gtest/LICENSE,sha256=lwLefkEXqOKyDa-rEf_aWMGYrt4GZAZJa-9nDUCiITg,1475 +torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/mkl-dnn/third_party/opencl/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/LICENSE,sha256=bz1ZuRA-cuXJd-7PYbJhwuFUapvimVhH4-4tMQIf05s,1609 +torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/libkineto/third_party/dynolog_headers/LICENSE,sha256=UkEte8fOQVfqYou6rLiCngqcs8WPV_mRdhJryM8r_IU,1086 +torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/libkineto/third_party/fmt/LICENSE,sha256=B1gPKjs1cJznA9Uj9EeyQvbf7HWCqMDfECx_ooSTdfg,1431 +torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/libkineto/third_party/googletest/LICENSE,sha256=lwLefkEXqOKyDa-rEf_aWMGYrt4GZAZJa-9nDUCiITg,1475 +torch-2.14.0+cpu.dist-info/licenses/third_party/llvm-openmp/LICENSE.txt,sha256=aDlRQ_IamqKbgjIWjHGJKvXsTxriUpVxzSUKccnjegM,17003 +torch-2.14.0+cpu.dist-info/licenses/third_party/mimalloc/LICENSE,sha256=gq3l19mwKQRLX7vDJiB_xHwtRO5N1x6KVZw21yghfek,1096 +torch-2.14.0+cpu.dist-info/licenses/third_party/miniz-3.0.2/LICENSE,sha256=ARVHjVZxISOM9swcDDYZJs8HpJ2eTJ5m2pf6xqAWRrM,1184 +torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/LICENSE,sha256=RFGcvnIte_CSzX4PomVYueOQW4j8pMDCeOJzOp9rTPk,1533 +torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/composable_kernel/LICENSE,sha256=IPO4Pf2gG9GNKF4O27nQRL5t3gTN92oewY2fxxJ5Nr8,1726 +torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/cutlass/LICENSE.txt,sha256=gKehi3PUH2TdnKiBrzWTj43oixjHKHAyUfTJTRKZiE0,1854 +torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/cutlass/python/LICENSE.txt,sha256=Qv7GMPQQqjCPcKUaifrc0ZWG-mIPmDGjK-5SipoQAA4,1547 +torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/googletest/LICENSE,sha256=lwLefkEXqOKyDa-rEf_aWMGYrt4GZAZJa-9nDUCiITg,1475 +torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/hipify_torch/LICENSE.txt,sha256=7PgZ1VsXwvCRs7oJNNBENoqgaA2KgTdIYDBqorkaoes,1112 +torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/mslk/attention/flash_attn/LICENSE,sha256=jJzLlsBl5wYTW2y60nm3IdphVuUfOl8nxrMymvlBbXM,1558 +torch-2.14.0+cpu.dist-info/licenses/third_party/onnx/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +torch-2.14.0+cpu.dist-info/licenses/third_party/onnx/third_party/pybind11/LICENSE,sha256=g5ZbhDuY9nDTqFvQQe1LNyyOxQ17SlmVqDrGl7pnXcs,1684 +torch-2.14.0+cpu.dist-info/licenses/third_party/perfetto/LICENSE,sha256=mmgqVs_8lSTfqbCxwNypy4GhnpbVvQeTqvAsCKle58o,14990 +torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/LICENSE,sha256=bl4RcySv2UTc9n82zzKYQ7wakiKajNm7Vz16gxMP6n0,1732 +torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/benchmark/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/LICENSE,sha256=lwLefkEXqOKyDa-rEf_aWMGYrt4GZAZJa-9nDUCiITg,1475 +torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/googlemock/LICENSE,sha256=lwLefkEXqOKyDa-rEf_aWMGYrt4GZAZJa-9nDUCiITg,1475 +torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/googlemock/scripts/generator/LICENSE,sha256=Xg34yEXHQudvL2TS2c4bfnSiQi_dvFd65qVjGQg94L8,11386 +torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/googletest/LICENSE,sha256=lwLefkEXqOKyDa-rEf_aWMGYrt4GZAZJa-9nDUCiITg,1475 +torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/utf8_range/LICENSE,sha256=WmKdK4aAgdivCLvOXQOBFvOg4uDUzprfTVPxTna2suA,1065 +torch-2.14.0+cpu.dist-info/licenses/third_party/psimd/LICENSE,sha256=mEzh4LjuidI04ouWA4HyQOA6B6gDHzUBL5wyVvVpZOI,1162 +torch-2.14.0+cpu.dist-info/licenses/third_party/pthreadpool/LICENSE,sha256=V4FKYGtND7CH2aU0kZCEtsEbWKQXTLWkrvIAGHeA3Do,1378 +torch-2.14.0+cpu.dist-info/licenses/third_party/pybind11/LICENSE,sha256=g5ZbhDuY9nDTqFvQQe1LNyyOxQ17SlmVqDrGl7pnXcs,1684 +torch-2.14.0+cpu.dist-info/licenses/third_party/python-peachpy/LICENSE.rst,sha256=5tb9v8CcnMG_xVlGypaQ3ZJ23urtK3Ksf8XHm96A_zI,1443 +torch-2.14.0+cpu.dist-info/licenses/third_party/sleef/LICENSE.txt,sha256=yb_3VziSIZPmf6cm-iJVNYcNKqEFn5FFLEEXNihK1WY,1338 +torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/LICENSE.txt,sha256=9NzvDR8FILQU1b-u7Y3wLxiOTsBcChe_HBjyX2zGYkU,1535 +torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/LICENSE,sha256=lwLefkEXqOKyDa-rEf_aWMGYrt4GZAZJa-9nDUCiITg,1475 +torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/googlemock/LICENSE,sha256=lwLefkEXqOKyDa-rEf_aWMGYrt4GZAZJa-9nDUCiITg,1475 +torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/googlemock/scripts/generator/LICENSE,sha256=Xg34yEXHQudvL2TS2c4bfnSiQi_dvFd65qVjGQg94L8,11386 +torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/googletest/LICENSE,sha256=lwLefkEXqOKyDa-rEf_aWMGYrt4GZAZJa-9nDUCiITg,1475 +torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/libnop/LICENSE,sha256=h26PdDJECXTuVUOiqhNENw7x8veUmtmKHziZz3ItVjE,577 +torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/libuv/LICENSE,sha256=Ft4MMrJly31GptO9YU8lndTWk6XiazQHsEqujXMEHww,1079 +torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/pybind11/LICENSE,sha256=mjfqVKo88Sx_MpJ5nyCCL_1Lm3FCs2p6mZeyjDkmTck,1676 +torch/_C.cpython-312-x86_64-linux-gnu.so,sha256=sJ0m53gd_98mAB9_idhfweeGbJ0kHN5-zFJ34RlQ1uA,10721 +torch/_C/_VariableFunctions.pyi,sha256=B1RVSFwjRx7zXNgXUUG35LDASl_87mEqfPaewC60IbE,1110250 +torch/_C/__init__.pyi,sha256=h4ATI83ouu4dtQJsAn6jt6hS4hlLI00RwM04xosAEOU,407552 +torch/_C/_acc/__init__.pyi,sha256=YrGID2b-0nfrv2Kqozt-brcNB3Prd_a1PPaa2TFWy5A,568 +torch/_C/_aoti.pyi,sha256=QDI3oCCd-HL8oeMcPmjwqReouT6B1oOZfJrbjzVkATk,6585 +torch/_C/_autograd.pyi,sha256=6GjkixNpnPlHb6XZ2mvnijs6bBE2GjGY__uh0bpDQYA,5903 +torch/_C/_cpu.pyi,sha256=zLjxjpuOW1VCoe99C3I-HOf7b6FzfARkPO-JktJOCcU,174 +torch/_C/_cudnn.pyi,sha256=m4nyLKmUJTRrcb-e94ghGbQ7D_Y1E7eqzueyH6QeANs,317 +torch/_C/_cusparselt.pyi,sha256=kD30gidilch4jKuIr7-ItTvDuEtt6L7vxL1l56sb_mw,32 +torch/_C/_distributed.pyi,sha256=qXyYUT8V9MPMXhx38eU0YD6CvaqS4CLvWMrEmuDqWj4,598 +torch/_C/_distributed_autograd.pyi,sha256=brb51Q-9UlMWCs4Aoy7ZLHH4hwhYq0acXm_hgfz_5HA,899 +torch/_C/_distributed_c10d.pyi,sha256=S5i4Fa2PL4rrDemYuqDrsNI1NSmxyktQf2LNwjxLRBg,35048 +torch/_C/_distributed_rpc.pyi,sha256=YFQvcIH2XK4FwGGXUQecfk2MgDgbNPAK9fZytZ__HR4,6052 +torch/_C/_distributed_rpc_testing.pyi,sha256=2cUz7bIO5y9fKUzfafx6Uh84QNO10gtP3uJXAXmE8Dk,1017 +torch/_C/_dynamo/__init__.pyi,sha256=CIA1y0klz37weU0dSBzauA40_3eYTj7GiXjgkYb-BEs,1644 +torch/_C/_dynamo/compiled_autograd.pyi,sha256=zbX2AKKVEX1yzpOsa2xIcoDBFM7YBpKSNPJjEsCOTZU,522 +torch/_C/_dynamo/eval_frame.pyi,sha256=uHkjwYfHE4h2CHwPh_IuerNZSY-0qNnFus01Eq0fDkk,3747 +torch/_C/_dynamo/guards.pyi,sha256=urmc-1jOmuZ4-f76Ei2AJjgU_nsSBdqFJbR-fOguTfE,15483 +torch/_C/_export/__init__.pyi,sha256=CUcMBKNDN_31e66pbRuZ9O8ilVR4-RSKAeMFRfRIxS8,257 +torch/_C/_export/pt2_archive_constants.pyi,sha256=tRUuDEV0jTX3T9oVh6CGEck1EKBc-kK3bvejSKHDfPs,826 +torch/_C/_functionalization.pyi,sha256=z-v6deG3dIJsP-wV8sIZ022eu18T-yefDV20qN2wAA0,566 +torch/_C/_functions.pyi,sha256=Ai74iMHvAy94srxpFLBXyVfcnmeVx5b-pXpdPbGnyIg,652 +torch/_C/_functorch.pyi,sha256=G4e-I7JCycb62mTDo8Z5bgk19BM857zU3VDi1In9rW8,3930 +torch/_C/_instruction_counter.pyi,sha256=xjwkiHBgXbvN8Iw7UNVEvE2YDJKFUU1_EoeTS4prCV8,109 +torch/_C/_itt.pyi,sha256=6fhhHGYgreXbGka-VtqX9FjjPaSznfOmDHPVC171DII,169 +torch/_C/_jit_tree_views.pyi,sha256=StShF20JIzi3BtE05CREHBAXWXGbmmMo7pWKR2EHuRw,5498 +torch/_C/_lazy.pyi,sha256=h8_ZY1JSJTiGebWekqfMvfFGZdt_g8dqFq90TG0-7hI,1015 +torch/_C/_lazy_ts_backend.pyi,sha256=YfYcEssTgLqOHQqUDYg5ZgbdB_D52mG19VETBmh7yuc,326 +torch/_C/_monitor.pyi,sha256=ND1PrgzrSUMGCBd50Hyz8M-mz2uJRNyFU_RGxSgx3kc,1447 +torch/_C/_nn.pyi,sha256=86kZpQcxqoHBkhynAgBuPUk0ZKQc5xJ0sZtID1N_ah0,9741 +torch/_C/_nvtx.pyi,sha256=MzekiGde65H1P_cJ_zER9kjXVRDW12eNtXUeItZG3WA,380 +torch/_C/_onnx.pyi,sha256=7xxwokJOBBQxnbox3lGLgMo9RkVGVgtfPBtsKcaGaTE,710 +torch/_C/_profiler.pyi,sha256=Z_Fk9UXFzuP2DVYGnVahhSrvuBu5cPkYMDPvDbVPEg0,10125 +torch/_C/_verbose.pyi,sha256=vMdQYMqABMqBFxYykp8_VD0QBaubolczBmCEv-UcA00,134 +torch/_C_flatbuffer/__init__.pyi,sha256=SdmD2nh01AdVYvwMJeo32D5BJW2Ar2pvjQTup0uBIko,544 +torch/_VF.py,sha256=XIfh8pIjzvG0ySWcOScz4E067DFoT-8TkcmAG5oYn94,664 +torch/_VF.pyi,sha256=B1RVSFwjRx7zXNgXUUG35LDASl_87mEqfPaewC60IbE,1110250 +torch/__config__.py,sha256=VCuBweOjH807O10Xrumlb_BrtWNTQMYIGjb3aw6T2po,574 +torch/__future__.py,sha256=yk9l_KWsfVIzUBx9cGr-OdtWmb-pI8ZhcROAm3a_FQw,3185 +torch/__init__.py,sha256=vUoQ_xY1ftePRar0tGzlt3H9wOhUlAIgbjJNDreSxnI,130530 +torch/__pycache__/_VF.cpython-312.pyc,, +torch/__pycache__/__config__.cpython-312.pyc,, +torch/__pycache__/__future__.cpython-312.pyc,, +torch/__pycache__/__init__.cpython-312.pyc,, +torch/__pycache__/_appdirs.cpython-312.pyc,, +torch/__pycache__/_classes.cpython-312.pyc,, +torch/__pycache__/_compile.cpython-312.pyc,, +torch/__pycache__/_custom_class_base.cpython-312.pyc,, +torch/__pycache__/_custom_ops.cpython-312.pyc,, +torch/__pycache__/_environment.cpython-312.pyc,, +torch/__pycache__/_guards.cpython-312.pyc,, +torch/__pycache__/_jit_internal.cpython-312.pyc,, +torch/__pycache__/_linalg_utils.cpython-312.pyc,, +torch/__pycache__/_lobpcg.cpython-312.pyc,, +torch/__pycache__/_lowrank.cpython-312.pyc,, +torch/__pycache__/_meta_registrations.cpython-312.pyc,, +torch/__pycache__/_opaque_base.cpython-312.pyc,, +torch/__pycache__/_ops.cpython-312.pyc,, +torch/__pycache__/_precompile.cpython-312.pyc,, +torch/__pycache__/_precompile_driver.cpython-312.pyc,, +torch/__pycache__/_python_dispatcher.cpython-312.pyc,, +torch/__pycache__/_size_docs.cpython-312.pyc,, +torch/__pycache__/_sources.cpython-312.pyc,, +torch/__pycache__/_storage_docs.cpython-312.pyc,, +torch/__pycache__/_streambase.cpython-312.pyc,, +torch/__pycache__/_tensor.cpython-312.pyc,, +torch/__pycache__/_tensor_docs.cpython-312.pyc,, +torch/__pycache__/_tensor_iterator.cpython-312.pyc,, +torch/__pycache__/_tensor_str.cpython-312.pyc,, +torch/__pycache__/_thread_safe_fork.cpython-312.pyc,, +torch/__pycache__/_torch_docs.cpython-312.pyc,, +torch/__pycache__/_utils.cpython-312.pyc,, +torch/__pycache__/_utils_internal.cpython-312.pyc,, +torch/__pycache__/_vmap_internals.cpython-312.pyc,, +torch/__pycache__/_weights_only_unpickler.cpython-312.pyc,, +torch/__pycache__/functional.cpython-312.pyc,, +torch/__pycache__/hub.cpython-312.pyc,, +torch/__pycache__/library.cpython-312.pyc,, +torch/__pycache__/overrides.cpython-312.pyc,, +torch/__pycache__/quasirandom.cpython-312.pyc,, +torch/__pycache__/random.cpython-312.pyc,, +torch/__pycache__/return_types.cpython-312.pyc,, +torch/__pycache__/serialization.cpython-312.pyc,, +torch/__pycache__/storage.cpython-312.pyc,, +torch/__pycache__/torch_version.cpython-312.pyc,, +torch/__pycache__/types.cpython-312.pyc,, +torch/__pycache__/version.cpython-312.pyc,, +torch/_appdirs.py,sha256=oTDrdoBwt0m-Vb27B8Bu3rfMYN6l7QBHeJepRqO_kL8,26198 +torch/_awaits/__init__.py,sha256=nAHROtkm0lmScDGnnEY5qGqK7W0ylL4NCutPDu3_lF4,1687 +torch/_awaits/__pycache__/__init__.cpython-312.pyc,, +torch/_classes.py,sha256=DbPcMC4o_QhQZeoog84z-kr0Brn9FDnypDHwU-mnZLk,1786 +torch/_compile.py,sha256=ssdSFpLJtFRF2DcQ3gPhYgV40s7ypu6T7Ao_rj3B0nc,1994 +torch/_custom_class_base.py,sha256=9dJuAKsMhiITy0tMS9_bVYl7vthrFa995uR9H8l5g_A,1633 +torch/_custom_op/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_custom_op/__pycache__/__init__.cpython-312.pyc,, +torch/_custom_op/__pycache__/autograd.cpython-312.pyc,, +torch/_custom_op/__pycache__/impl.cpython-312.pyc,, +torch/_custom_op/autograd.py,sha256=V2BbqTBYUK5X_L4YGClsfoEAG2Qc8SzRPuWvkzGPeC0,12455 +torch/_custom_op/impl.py,sha256=LHX_rVT1DMZhGIo9PJXqkbvPDQYhaaxmCtyUsFCf4J8,27403 +torch/_custom_ops.py,sha256=DyTzqyo_fZ582qmMiyfoLdT9-cAnor776dgqb_GhPIo,12824 +torch/_decomp/__init__.py,sha256=4e-zYz7O4WfJOaZ4pu8rK5W4W4oaoOakiXTydxMSSp4,20353 +torch/_decomp/__pycache__/__init__.cpython-312.pyc,, +torch/_decomp/__pycache__/decompositions.cpython-312.pyc,, +torch/_decomp/__pycache__/decompositions_for_jvp.cpython-312.pyc,, +torch/_decomp/__pycache__/decompositions_for_rng.cpython-312.pyc,, +torch/_decomp/decompositions.py,sha256=qZ44P0hSqORrsRgGWcUIJ9w-bJxSAiDCJmeMTr94BS4,217622 +torch/_decomp/decompositions_for_jvp.py,sha256=ZkHhVuaTGxqq3wht6vNV-MJDdYuCXVM49t2_fCz1X0o,11926 +torch/_decomp/decompositions_for_rng.py,sha256=x7Vy1XH6EuF7Gtm5CrLCYN_IhSPWl5UciigwG3Q7za8,9566 +torch/_dispatch/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_dispatch/__pycache__/__init__.cpython-312.pyc,, +torch/_dispatch/__pycache__/python.cpython-312.pyc,, +torch/_dispatch/python.py,sha256=tlR8LSP57-9WLKmyhISGRJmL-WewqtYe-krGz6x5cl4,7505 +torch/_dynamo/__init__.py,sha256=oEG5QK9f9sQP3vtQ7YjoBSd9P7CafFHWc9O_2Tlj0IA,8311 +torch/_dynamo/__pycache__/__init__.cpython-312.pyc,, +torch/_dynamo/__pycache__/_trace_wrapped_higher_order_op.cpython-312.pyc,, +torch/_dynamo/__pycache__/aot_compile.cpython-312.pyc,, +torch/_dynamo/__pycache__/aot_compile_types.cpython-312.pyc,, +torch/_dynamo/__pycache__/bytecode_analysis.cpython-312.pyc,, +torch/_dynamo/__pycache__/bytecode_debugger.cpython-312.pyc,, +torch/_dynamo/__pycache__/bytecode_transformation.cpython-312.pyc,, +torch/_dynamo/__pycache__/cache_size.cpython-312.pyc,, +torch/_dynamo/__pycache__/callback.cpython-312.pyc,, +torch/_dynamo/__pycache__/code_context.cpython-312.pyc,, +torch/_dynamo/__pycache__/codegen.cpython-312.pyc,, +torch/_dynamo/__pycache__/compiled_autograd.cpython-312.pyc,, +torch/_dynamo/__pycache__/comprehension_graph_break.cpython-312.pyc,, +torch/_dynamo/__pycache__/comptime.cpython-312.pyc,, +torch/_dynamo/__pycache__/config.cpython-312.pyc,, +torch/_dynamo/__pycache__/convert_frame.cpython-312.pyc,, +torch/_dynamo/__pycache__/create_parameter_op.cpython-312.pyc,, +torch/_dynamo/__pycache__/current_scope_id.cpython-312.pyc,, +torch/_dynamo/__pycache__/dce_extra_outputs.cpython-312.pyc,, +torch/_dynamo/__pycache__/debug_utils.cpython-312.pyc,, +torch/_dynamo/__pycache__/decorators.cpython-312.pyc,, +torch/_dynamo/__pycache__/device_interface.cpython-312.pyc,, +torch/_dynamo/__pycache__/distributed.cpython-312.pyc,, +torch/_dynamo/__pycache__/dynamo_profiler.cpython-312.pyc,, +torch/_dynamo/__pycache__/eval_frame.cpython-312.pyc,, +torch/_dynamo/__pycache__/exc.cpython-312.pyc,, +torch/_dynamo/__pycache__/external_utils.cpython-312.pyc,, +torch/_dynamo/__pycache__/funcname_cache.cpython-312.pyc,, +torch/_dynamo/__pycache__/functional_export.cpython-312.pyc,, +torch/_dynamo/__pycache__/graph_break_hints.cpython-312.pyc,, +torch/_dynamo/__pycache__/graph_bytecode_inputs.cpython-312.pyc,, +torch/_dynamo/__pycache__/graph_deduplication.cpython-312.pyc,, +torch/_dynamo/__pycache__/graph_id_filter.cpython-312.pyc,, +torch/_dynamo/__pycache__/graph_region_tracker.cpython-312.pyc,, +torch/_dynamo/__pycache__/graph_utils.cpython-312.pyc,, +torch/_dynamo/__pycache__/guards.cpython-312.pyc,, +torch/_dynamo/__pycache__/hooks.cpython-312.pyc,, +torch/_dynamo/__pycache__/logging.cpython-312.pyc,, +torch/_dynamo/__pycache__/metrics_context.cpython-312.pyc,, +torch/_dynamo/__pycache__/mutation_guard.cpython-312.pyc,, +torch/_dynamo/__pycache__/output_graph.cpython-312.pyc,, +torch/_dynamo/__pycache__/package.cpython-312.pyc,, +torch/_dynamo/__pycache__/pgo.cpython-312.pyc,, +torch/_dynamo/__pycache__/precompile_context.cpython-312.pyc,, +torch/_dynamo/__pycache__/profiler.cpython-312.pyc,, +torch/_dynamo/__pycache__/replay_record.cpython-312.pyc,, +torch/_dynamo/__pycache__/resume_execution.cpython-312.pyc,, +torch/_dynamo/__pycache__/side_effects.cpython-312.pyc,, +torch/_dynamo/__pycache__/source.cpython-312.pyc,, +torch/_dynamo/__pycache__/symbolic_convert.cpython-312.pyc,, +torch/_dynamo/__pycache__/tensor_version_op.cpython-312.pyc,, +torch/_dynamo/__pycache__/test_case.cpython-312.pyc,, +torch/_dynamo/__pycache__/test_dont_skip_tracing_functions.cpython-312.pyc,, +torch/_dynamo/__pycache__/test_minifier_common.cpython-312.pyc,, +torch/_dynamo/__pycache__/testing.cpython-312.pyc,, +torch/_dynamo/__pycache__/trace_rules.cpython-312.pyc,, +torch/_dynamo/__pycache__/types.cpython-312.pyc,, +torch/_dynamo/__pycache__/utils.cpython-312.pyc,, +torch/_dynamo/_trace_wrapped_higher_order_op.py,sha256=UVdU0Gy4SGJ5aKzD1By8V3bugAKE3Vwl-jBR3NRL9kE,10776 +torch/_dynamo/aot_compile.py,sha256=-p7rFIBPfCck1mc6_00ZRBq0pkAjkBv9lFIQxZ8f1xc,20306 +torch/_dynamo/aot_compile_types.py,sha256=dcTFIWGJx6L5jMozKsPNUIxBCms1By9qdaye6pCKKc0,8629 +torch/_dynamo/backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_dynamo/backends/__pycache__/__init__.cpython-312.pyc,, +torch/_dynamo/backends/__pycache__/common.cpython-312.pyc,, +torch/_dynamo/backends/__pycache__/cudagraphs.cpython-312.pyc,, +torch/_dynamo/backends/__pycache__/debugging.cpython-312.pyc,, +torch/_dynamo/backends/__pycache__/distributed.cpython-312.pyc,, +torch/_dynamo/backends/__pycache__/inductor.cpython-312.pyc,, +torch/_dynamo/backends/__pycache__/onnxrt.cpython-312.pyc,, +torch/_dynamo/backends/__pycache__/registry.cpython-312.pyc,, +torch/_dynamo/backends/__pycache__/tensorrt.cpython-312.pyc,, +torch/_dynamo/backends/__pycache__/torchxla.cpython-312.pyc,, +torch/_dynamo/backends/__pycache__/tvm.cpython-312.pyc,, +torch/_dynamo/backends/common.py,sha256=cHKDHVRjMBz410PANkzwHlVYNXX-IRn0woq83tKBvEk,7823 +torch/_dynamo/backends/cudagraphs.py,sha256=EnMPEDx0KYQYD9cFUPKeHbGuHCgVmK9ucDBDam9zdzk,10866 +torch/_dynamo/backends/debugging.py,sha256=4JyRoDnFM4t_KutMDxpP4J_MA7EjFoSTWJt4QnC42UY,26069 +torch/_dynamo/backends/distributed.py,sha256=n28EaALbT4WuJgTGHVwgExqmb3Lx77HY2GGkGCa1uyc,29821 +torch/_dynamo/backends/inductor.py,sha256=fSjxEorULdmCAxVxMoNcBTvTtzEpGJv-WHUTHvTE7QU,1104 +torch/_dynamo/backends/onnxrt.py,sha256=KMF_RHHh_JSV8W5pNXvtM_EiLcMdBWpfNF5iruUwyIg,1623 +torch/_dynamo/backends/registry.py,sha256=8lUCoqLayFRISw11W9MMwgFPT9C34MiiXK7C6NSdXQA,7296 +torch/_dynamo/backends/tensorrt.py,sha256=dxRCaQgNbw8Ly0SgGSOK7At2OANtvCe5mSHpAjvEqYM,383 +torch/_dynamo/backends/torchxla.py,sha256=o75DfoFrS6htTH1SfFx50Nu8xLWhT0hGvzoBnXfHpcU,1551 +torch/_dynamo/backends/tvm.py,sha256=oMaNITUEGbbV4ekYb7VCAtyAFk2MY2XmMMLRLs_5IPk,1625 +torch/_dynamo/bytecode_analysis.py,sha256=Wcuu4Ewdfc-jLvdL_fVoJ2sew9Awa2pIr6WLuF_mI-M,10307 +torch/_dynamo/bytecode_debugger.py,sha256=iZmQ1IM392E_qjcc_B10aInqZH4lMMGrco7ND1qX7E4,46824 +torch/_dynamo/bytecode_transformation.py,sha256=suPFsA9rojDIqGpfXV7_TuVpHU6yshjVIm4hqO1gRnI,79284 +torch/_dynamo/cache_size.py,sha256=AZCdKs4neYN-B_9oF6v260ybwo3wmLZoVM3WIr5X8Yg,8425 +torch/_dynamo/callback.py,sha256=nlFNcKvkWdG5FYeKY1r4zXqdjSm4rhwRKGUuQ9YBh3U,5793 +torch/_dynamo/code_context.py,sha256=MXMoP-r7lN4jFHKLUDopun0ZJE98RC1VA0St0geTbuc,1863 +torch/_dynamo/codegen.py,sha256=j6jZxSjaofOXnbVWbJdL2pnyre9MGm4dyVyT7xsguDs,34480 +torch/_dynamo/compiled_autograd.py,sha256=6r9TdBDxYzq9_pgK1VGbLvfYk0vIlPCaH3nvvT0aQJA,72260 +torch/_dynamo/comprehension_graph_break.py,sha256=0qVZDu49ApzOfFAEI5DgT4eG7Ug5G2gZJHyBaYsuj3c,24963 +torch/_dynamo/comptime.py,sha256=xvR6H8scbeOswlMbYnlb1Xa-dXOqXiTStilt4EMUsb0,15372 +torch/_dynamo/config.py,sha256=1EpBO_QnT_DOQ4T7BTjDxIqZcq-WPY8wxbFkFoku5rE,41339 +torch/_dynamo/convert_frame.py,sha256=tFPJ2IquRs-UGY1Kh6zBxY0-EVlJh5vUoy8bUWd4Ak8,102152 +torch/_dynamo/create_parameter_op.py,sha256=C7OxlS-SbxumEsNiuZ8GHWlJjj4010Sj0V4CmTS7Ty8,2590 +torch/_dynamo/current_scope_id.py,sha256=CD2PnuBjVr2ns7_oNaPg6djM5wa-qNIaJYLFA4uThUo,1433 +torch/_dynamo/dce_extra_outputs.py,sha256=u6bL5UWk2cSk4lNnBdDZLUXW_Bkre8ODQPU03sQy-j4,8587 +torch/_dynamo/debug_utils.py,sha256=WV9WqidLduQR38g2QhGG0iAKh9VqJlUuvKmqTLBUWzQ,45660 +torch/_dynamo/decorators.py,sha256=l-HI0YteaUxUUaFfJCXxh5XIfLyezDdluF48BE7ZB-w,74822 +torch/_dynamo/device_interface.py,sha256=sh0fuq6Zn-4LuYkHxE9FT3eLrGso9D9MKDKTBDggjos,24607 +torch/_dynamo/distributed.py,sha256=ikd2PFjPRpaKyYRUHkVO2HGA23bxCkqAhSoXiTqFZDU,1992 +torch/_dynamo/dynamo_profiler.py,sha256=PJ0mUIHgrp-GNB59Eon_jryBDyoNHNyVu_oPfP4akgI,15179 +torch/_dynamo/eval_frame.py,sha256=tM-xEToWgVhkcCIrXdcdfG4-BuG9ouEpwqvK33VIfnQ,120660 +torch/_dynamo/exc.py,sha256=rbFzSYrlqRfF62A1LV4idJyDPrhEpjxbv3MdvxVPoXQ,35405 +torch/_dynamo/external_utils.py,sha256=LD__Cec0CwaPFXv61bHB7kfLCwLhKx8MyYLAUxq6lWg,9079 +torch/_dynamo/funcname_cache.py,sha256=N_JK8IaQU12eNjMJcuZxdAoOUDp-UYHtnoqnKM-kFkM,2517 +torch/_dynamo/functional_export.py,sha256=ZGrsqErNSd73fcqPG8D-DvH-3AdkEYL3xl_o03qatG4,45718 +torch/_dynamo/graph_break_hints.py,sha256=iqxvoIxyIrQEVZBAgTy4wwIt7cmn1wGFhTPxTKJjtjw,1657 +torch/_dynamo/graph_break_registry.json,sha256=xC7RQgSIUqbwRjM0DqK1HIBOx2OcaKM5zZMCDhTR8PU,293242 +torch/_dynamo/graph_bytecode_inputs.py,sha256=Hhf6E3zZdQVhAkjT4Co7jlvpoOmBfyYOI2QbCtks88I,3893 +torch/_dynamo/graph_deduplication.py,sha256=GxIJDH_hlGc2m7JUcoS8296Aqap_DbO6O0ge0cRvz1c,24557 +torch/_dynamo/graph_id_filter.py,sha256=pG7WZ1q0rw7_y0LklrClbrdVTinEiheGHVJphvncFz0,16042 +torch/_dynamo/graph_region_tracker.py,sha256=zOJeZIE33UwDLyQXTwru2AOlPHa-Qnh4m_YIHP6wB1A,18780 +torch/_dynamo/graph_utils.py,sha256=GtBsKm5KiFeMfNwEhi7eDWEQcAZhHL0revRzgW-1pRw,3687 +torch/_dynamo/guards.py,sha256=PsfcAO2_YVaZbRpXqmjhbQ9A2WJ5UzkFhWfTNbZzu_k,236258 +torch/_dynamo/hooks.py,sha256=prkixNTkyo9iZjlpdftr3ang4UR0t9bgdJ3jYoN1Q7k,891 +torch/_dynamo/logging.py,sha256=ltvH1A9WYtIDZkqFODBbBVglBybJpRFDj79gyYjyclM,2215 +torch/_dynamo/metrics_context.py,sha256=pziA9nSe4cv6zBzpvB9obzKx3nMsj1vi5Pw2yYfh0ls,8965 +torch/_dynamo/mutation_guard.py,sha256=3ZYPj1bqa_-GiTvNS3aKDYhf90QliLzzI0f9rnHEm-k,5237 +torch/_dynamo/output_graph.py,sha256=AieX1oJASw-wligAf-uJ_L49Hk9ivXQJbAvbKKFeAtQ,213499 +torch/_dynamo/package.py,sha256=fG1s4h0SwdVhFi7SYEcVmzGlPmJh9PR4bVba7SKDP_s,48719 +torch/_dynamo/pgo.py,sha256=JaXNYoOyczxiUIh_2KBT3g1u6sL7aqskoc3AQi9eekU,40166 +torch/_dynamo/polyfills/__init__.py,sha256=Z5nogW0izYF-7F8Vrwu5yx-lztpRL_AKV-y2X-X7BXw,18939 +torch/_dynamo/polyfills/__pycache__/__init__.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/_collections.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/builtins.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/copy.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/functools.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/fx.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/heapq.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/io.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/itertools.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/loader.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/operator.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/os.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/pytree.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/struct.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/sys.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/tensor.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/torch_c_nn.cpython-312.pyc,, +torch/_dynamo/polyfills/__pycache__/traceback.cpython-312.pyc,, +torch/_dynamo/polyfills/_collections.py,sha256=RHkqS80la8AfbmHThq2HnoYN0BQ_HAtELrKDqWs2Bfg,662 +torch/_dynamo/polyfills/builtins.py,sha256=sil_k_6ONemzXHpACfNzq112D1DLtQ9lWgGg6yz6Rfw,5399 +torch/_dynamo/polyfills/copy.py,sha256=7SmpP5VgNQCYyw1wkx4iGY5xRJ28mts-vqH10EqUuyc,2105 +torch/_dynamo/polyfills/functools.py,sha256=EVPtypqdpBUwOqyKD5xe0coUtA29ZWJIIDKZ-pqRNWE,2047 +torch/_dynamo/polyfills/fx.py,sha256=nyQ9cjgpBs8c8KvPwfSXTs6ItDGE1swv2k3-rXhROrU,1350 +torch/_dynamo/polyfills/heapq.py,sha256=xwQLTlK-joqIDFRK7qEToXKn1NB04NmRD9gLWqkVS_E,3291 +torch/_dynamo/polyfills/io.py,sha256=s6TwlzwB9FJytYsY39ZX9M3S-LJSwWjuY7Q2y3Z_qUs,733 +torch/_dynamo/polyfills/itertools.py,sha256=BpYFaBO4siUMrP04D061NeHYPZ85GnWrGj02gmfFuEA,11438 +torch/_dynamo/polyfills/loader.py,sha256=nEEG0RhSG80xalinS-gk7OuTqTvvqdKdyyX6qMAwb8E,1440 +torch/_dynamo/polyfills/operator.py,sha256=15BVTw4hQ11oPqtDcGcZYjbrCAfK3vU7g11f6krn3Uo,4074 +torch/_dynamo/polyfills/os.py,sha256=XaGG7-4htiZnKr8cgpMClZRHqP1PFIqtjPGNaAbEJo0,1016 +torch/_dynamo/polyfills/pytree.py,sha256=NK6mneDDB3Z-eWQPdUUdp4qnDzOj9S0C_5D52G5k0sk,27466 +torch/_dynamo/polyfills/struct.py,sha256=xxkCQFcQvPwkI-tZzLovBKxIJvJRvqBWKNQPO1kUD7w,624 +torch/_dynamo/polyfills/sys.py,sha256=haOwDvxbbAK3V48lPa6Gy-T93E5TeNZsTca6IwgVkA0,947 +torch/_dynamo/polyfills/tensor.py,sha256=KboCcsFeLkwxZw3AyMUCZiKa-hKLmVWlXVnwgjQiCWo,1709 +torch/_dynamo/polyfills/torch_c_nn.py,sha256=8flz-dvgV45P7mYfEcQ4X5yg_38M8pM6Lpnk4kuDrjM,4097 +torch/_dynamo/polyfills/traceback.py,sha256=Q24-9F_v8VX7ho-xcQZeNGYggkxN3dB0g6dI_BXa-Mc,1127 +torch/_dynamo/precompile_context.py,sha256=uGnjPBMsZpoLqk6ECLxHlKsFOViyFxlAyldf-mHD5Ro,7778 +torch/_dynamo/profiler.py,sha256=2Z6-t9gAkE_Acy1VJoXoZ-h-lQ3CyqyO4lbZ8rhr2HI,5922 +torch/_dynamo/replay_record.py,sha256=qDkx5tXbIQC2eWoPrubef3jyTGmGkN_zauInCbksHm4,4837 +torch/_dynamo/repro/__init__.py,sha256=v3Fbf3JLo_gyvTNWatRvJpN7yKzS8FiIXsDtQxcc8Rs,1261 +torch/_dynamo/repro/__pycache__/__init__.cpython-312.pyc,, +torch/_dynamo/repro/__pycache__/after_aot.cpython-312.pyc,, +torch/_dynamo/repro/__pycache__/after_dynamo.cpython-312.pyc,, +torch/_dynamo/repro/__pycache__/aoti.cpython-312.pyc,, +torch/_dynamo/repro/after_aot.py,sha256=3AQFgDKSdTRDJvwF6sXodqj_0_bGOFqyYuxg-8G-kcE,63128 +torch/_dynamo/repro/after_dynamo.py,sha256=h1cwsYlx53TV2NIQAXtiWfDK3X3apcVFPxXA8nu1abg,23223 +torch/_dynamo/repro/aoti.py,sha256=4sFyetQVxzF3B4AzhUj2bVr9Z0eIHnqddOjKz7B8Q_Q,22886 +torch/_dynamo/resume_execution.py,sha256=vhvm5CW8H53SPfwur_M4fxL8jdavSNt90-k11PC2mow,32778 +torch/_dynamo/side_effects.py,sha256=F__V3SYQr8hKbzXHTM8q6eITDsgWm2f4BOKGhFpQkI0,88190 +torch/_dynamo/source.py,sha256=J4zzbwT8SQl_Hy5DGvHQbl4jHuy9-qh1U5lesNT7qCc,49422 +torch/_dynamo/symbolic_convert.py,sha256=f1lGbBS2Xz7PG7-rbI6vaJfXr0-1DUtmJ3BRF40ndL4,273382 +torch/_dynamo/tensor_version_op.py,sha256=avRdeW6tPODbAqRLY9nBKRddFLpDKv9MkUAwoNgPETU,2799 +torch/_dynamo/test_case.py,sha256=Kz1DT2La8naj-6DX6ROh5I18NxvcguF26-bxWMGjrrw,9338 +torch/_dynamo/test_dont_skip_tracing_functions.py,sha256=v8sCtPbLM_cEgEXvKUvtwoVnclOjJkaDcVDYgBWL5Ww,817 +torch/_dynamo/test_minifier_common.py,sha256=go70FmH1Nz2wiZ4SaVGwxaI806NoEiKepuhDhhCkz60,13338 +torch/_dynamo/testing.py,sha256=5K8dNyfxklahcLmFk4t5qZUb2m1pNhOwPfdPN5_2zc0,19406 +torch/_dynamo/trace_rules.py,sha256=ucc7acDFRDKEQ2AOQDi0-01UBFQyHM7WGUE2h6QO3PI,168019 +torch/_dynamo/types.py,sha256=qqzF7yyJRZ33rb3TwBVNtzVvXVOV9esl8GhOvYgNTg4,4367 +torch/_dynamo/utils.py,sha256=5VDGjJJOHAurrzH8Yp6QDB07bsvPEKqIRC05tAW3ECo,214231 +torch/_dynamo/variables/__init__.py,sha256=UqfZk-Q0tT9avjqfpU6Kn7nv6nIiKjil08rTklpZ9Jk,8849 +torch/_dynamo/variables/__pycache__/__init__.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/base.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/builder.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/builtin.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/constant.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/ctx_manager.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/dicts.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/distributed.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/functions.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/hashable.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/higher_order_ops.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/invoke_subgraph.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/iter.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/lazy.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/lists.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/memory.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/misc.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/nn_module.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/object_protocol.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/optimizer.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/script_object.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/sdpa.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/sets.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/streams.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/tensor.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/torch.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/torch_function.cpython-312.pyc,, +torch/_dynamo/variables/__pycache__/user_defined.cpython-312.pyc,, +torch/_dynamo/variables/base.py,sha256=ZQIxojb9W_6DC9iJC6UuGXQ-0bsbDBr-idyEiSLxOcU,117314 +torch/_dynamo/variables/builder.py,sha256=kA4j0_rVY2OJeW7v4YY-hh_YSMaQQN4NhN7NbgDFIUI,232057 +torch/_dynamo/variables/builtin.py,sha256=As18xLNDyHfatQnRhboPxt-IoHVwxmu6YRXt4gmGb-E,149747 +torch/_dynamo/variables/constant.py,sha256=2LEe-rZSRbQgndiaG8SyicJHkL60tRSz183CDyYKvew,44478 +torch/_dynamo/variables/ctx_manager.py,sha256=YMF_eCG56_ofuxMLriBJjfVqww003u_EE_xISWambeM,67019 +torch/_dynamo/variables/dicts.py,sha256=ZHBxDQRzGhohTshZjPmmpcsDYiVtzROeAnDWhJYEK88,69956 +torch/_dynamo/variables/distributed.py,sha256=TIOPEmC-dPudhwDz6C8RYOrzrpuCG3x_SUmQEveHVTA,9764 +torch/_dynamo/variables/functions.py,sha256=WrcJr1FDiHHRwA-OrLsz3q2D2Jk6UvOUrEppip52QQg,189800 +torch/_dynamo/variables/hashable.py,sha256=zriTTkpkZ3csgjEibfouCT2p0siETz1iSrKwieWTkmY,8296 +torch/_dynamo/variables/higher_order_ops.py,sha256=jTv-spjYG6bKMfiihW-fkwWQXVJhj8iupgMIgJbj-vs,253935 +torch/_dynamo/variables/invoke_subgraph.py,sha256=fYJ55PUkKeErMLA1Os7lpHy8WPAtjYn6PSQoDHmbzis,61487 +torch/_dynamo/variables/iter.py,sha256=JbdNs7s2v1iWeJlhhEHHM2vjexw8XVd2lF9jTC3gjy4,36657 +torch/_dynamo/variables/lazy.py,sha256=7AEHFuuokQMN9-_BGYAqYm43Q32V1w5FjfK3gd0P07I,27041 +torch/_dynamo/variables/lists.py,sha256=q_gT9oDwFBib2qB1u7Vre7BtI78zC04VsJI55eAU3w8,96898 +torch/_dynamo/variables/memory.py,sha256=1tyIFmBL6zO5zm8ftEiSTy3ObRljr-YzTxt2gXlxvJI,7140 +torch/_dynamo/variables/misc.py,sha256=yw5xKhu8Xyk3tchS9NODC6uIMDp_K9y3WxTDX2rxtro,118559 +torch/_dynamo/variables/nn_module.py,sha256=rpALNkaDJckIR-2iR7gAzvQvdqVbCyb7ckcgdMpPzrc,68423 +torch/_dynamo/variables/object_protocol.py,sha256=LV-IygpfQuwqObkK7_H_v2_XiPBJn4IV4GIXmJ1dEb8,84416 +torch/_dynamo/variables/optimizer.py,sha256=yY-WNnIPPYFkbxCVmHeyMKlyK6bJz-9TiJSU4BRWx9E,18522 +torch/_dynamo/variables/script_object.py,sha256=OJQznMNDGUU711lGh2XgBgmYo-PoeFnNO--2PDC6GRI,23729 +torch/_dynamo/variables/sdpa.py,sha256=PbSsOVJGsDL-KTanv-hMMX0Z-vjYobyrG9y1dsIcW6E,3245 +torch/_dynamo/variables/sets.py,sha256=Md6hpRHkZ8knvoDwViY3dJQt_Tn8nGNcd_KiDVw-zvc,40764 +torch/_dynamo/variables/streams.py,sha256=P10djtrOB8hRKPDnnvABUTEAydlbLcok6Th53Nlkvas,27452 +torch/_dynamo/variables/tensor.py,sha256=DOMjrlgtEmjLrzGKNmrkIk4usUh0C71V4TYZCgEZ5EM,142196 +torch/_dynamo/variables/torch.py,sha256=KOn85aQO5wOPHuhRfXN4FlWEnamaAqVgroxx6jkEKZU,187032 +torch/_dynamo/variables/torch_function.py,sha256=499CQY8FtviwY424H6wGzsdSVVGWAiLtajF81mTC3K8,29217 +torch/_dynamo/variables/user_defined.py,sha256=qBPDmwvWtrgz46uVL6ig7UY2iGY4E0Mbe9Lal1EpE7U,224344 +torch/_environment.py,sha256=pDUFrq8tC8SqJTir9Q3Vr01UbYCYH-2KEJbleFrV0FQ,133 +torch/_export/__init__.py,sha256=jHjsuXiPAKHY3YZqRsc-ir5VA109_FngyZYnE3yiQJk,6753 +torch/_export/__pycache__/__init__.cpython-312.pyc,, +torch/_export/__pycache__/config.cpython-312.pyc,, +torch/_export/__pycache__/converter.cpython-312.pyc,, +torch/_export/__pycache__/error.cpython-312.pyc,, +torch/_export/__pycache__/non_strict_utils.cpython-312.pyc,, +torch/_export/__pycache__/pass_base.cpython-312.pyc,, +torch/_export/__pycache__/tools.cpython-312.pyc,, +torch/_export/__pycache__/utils.cpython-312.pyc,, +torch/_export/__pycache__/verifier.cpython-312.pyc,, +torch/_export/__pycache__/wrappers.cpython-312.pyc,, +torch/_export/config.py,sha256=4PNaL4VRM8vwVNVcUodk1mTRn8GacVcqzxpKi5LwDq8,1404 +torch/_export/converter.py,sha256=SDZL15qUzzJ9mzQ8QzfdrVeIc9Slb_Man1M0JW3UOOU,65052 +torch/_export/db/__init__.py,sha256=a3XxW1RcNAPwEVaI2g11hpnJvSHxGUFsGmDAWfDnLP8,206 +torch/_export/db/__pycache__/__init__.cpython-312.pyc,, +torch/_export/db/__pycache__/case.cpython-312.pyc,, +torch/_export/db/__pycache__/gen_example.cpython-312.pyc,, +torch/_export/db/__pycache__/logging.cpython-312.pyc,, +torch/_export/db/case.py,sha256=nHiUtUtBGliPIKjHI07ZBUq6NE6Re4qwIZEsF66ZPpg,5199 +torch/_export/db/examples/__init__.py,sha256=PlziokXeStI1gWELwC7zX-T7ZViONPRitQ1uFWNAxL4,1648 +torch/_export/db/examples/__pycache__/__init__.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/assume_constant_result.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/autograd_function.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/class_method.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/cond_branch_class_method.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/cond_branch_nested_function.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/cond_branch_nonlocal_variables.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/cond_closed_over_variable.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/cond_operands.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/cond_predicate.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/constrain_as_size_example.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/constrain_as_value_example.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/decorator.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/dictionary.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/dynamic_shape_assert.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/dynamic_shape_constructor.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/dynamic_shape_if_guard.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/dynamic_shape_map.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/dynamic_shape_round.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/dynamic_shape_slicing.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/dynamic_shape_view.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/fn_with_kwargs.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/list_contains.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/list_unpack.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/model_attr_mutation.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/nested_function.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/null_context_manager.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/optional_input.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/pytree_flatten.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/scalar_output.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/specialized_attribute.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/static_for_loop.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/static_if.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/tensor_setattr.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/type_reflection_method.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/unsupported_operator.cpython-312.pyc,, +torch/_export/db/examples/__pycache__/user_input_mutation.cpython-312.pyc,, +torch/_export/db/examples/assume_constant_result.py,sha256=oio3YIPrefH_Ky68eu1NNDDQ4SEhxEjr26Gp_lkJR5A,511 +torch/_export/db/examples/autograd_function.py,sha256=byZs2M2TE3nU9a_UM3LMZw4gf-iFCsAok-wnqxAGah4,652 +torch/_export/db/examples/class_method.py,sha256=KM6pkWdEc1SMybUR-O2hCN1tD9Vl0B22gPI2LgDiZZ4,499 +torch/_export/db/examples/cond_branch_class_method.py,sha256=K7BquPZw2blY67krCE253lvFWHIduyLb7VXlG33H3_o,1329 +torch/_export/db/examples/cond_branch_nested_function.py,sha256=288-MIyinW2B7IMbECERfYlOcP6BepN2XwiIKWg14-g,1304 +torch/_export/db/examples/cond_branch_nonlocal_variables.py,sha256=QMk4lUb__XIXB_c-OmMuXSlt7TyI4HZkNB4haUyNTYs,1843 +torch/_export/db/examples/cond_closed_over_variable.py,sha256=iSWSxhJhumU6CsRSzXUeW7YVxbgjf-C05EDc0Foi-a4,547 +torch/_export/db/examples/cond_operands.py,sha256=gWQ39G2YkjVf83WjIlCqL09Davkxo-Zae3k2-pFRy1w,801 +torch/_export/db/examples/cond_predicate.py,sha256=6kzRsxEBKMhivTrxxb5VJPb5baS4gcUr_im5iUCpnWE,665 +torch/_export/db/examples/constrain_as_size_example.py,sha256=13bb0R9cuRWRNYgEFfSe8AkQdgf39zvf5EDvhIVXJhw,515 +torch/_export/db/examples/constrain_as_value_example.py,sha256=XtZLDWMmL1hOZPqtNbOIUYQ6FNX24_jMvu7Uzq9sXDw,571 +torch/_export/db/examples/decorator.py,sha256=U5YTo_25VfE_Hy9uoD4eYN8wKSJGpOG0dAJ1TZjL1i4,480 +torch/_export/db/examples/dictionary.py,sha256=gSkKkS68Vw_cropGQ57i61jqTleFsLECIXP6pZMqLBE,404 +torch/_export/db/examples/dynamic_shape_assert.py,sha256=5ORg04FDKJb0rEmBVlsliyeNDerTuCDANWJbHz6_nr4,478 +torch/_export/db/examples/dynamic_shape_constructor.py,sha256=68CRA-j59c0dPBc5hOBsEBmWpWz0opzovyqGIaTfKuw,396 +torch/_export/db/examples/dynamic_shape_if_guard.py,sha256=_MlWCf72Z4Mscvfg6gFLJcWPmM9s4-s_6Z2YzrD1mGI,556 +torch/_export/db/examples/dynamic_shape_map.py,sha256=XN8_Et1EVYaxmdnACPkiDAVJZ3jkYRaj9U6mU44ZntM,454 +torch/_export/db/examples/dynamic_shape_round.py,sha256=sMyW43DVXFtZa6jFO08XxVjyw06LcJ9oyuJH5jAsG4Q,525 +torch/_export/db/examples/dynamic_shape_slicing.py,sha256=Rowy_RfPf1kW1l_oCp71YVflt2ivhpP1u_HzTEupxQA,388 +torch/_export/db/examples/dynamic_shape_view.py,sha256=fEuSTQRghtJY8VcBi7qwiZTQXwd9ux8d1PRBYw6Qd6E,444 +torch/_export/db/examples/fn_with_kwargs.py,sha256=fEndpGN__D456vh3NAamoK1KdmtEyvmAsW0gZB0TExo,731 +torch/_export/db/examples/list_contains.py,sha256=lzzkGcg6YoDeFDRh7GlY6BlmQoeA8aVfSFu-1FoiMhk,519 +torch/_export/db/examples/list_unpack.py,sha256=u7tczh6wbR1PoYQxuRPpsSfxgMiGhu4VocA50ZrwKFw,568 +torch/_export/db/examples/model_attr_mutation.py,sha256=wIrxdizyoC1EGByE4THkYXbDPw6Vh86lphvh_OR9kug,628 +torch/_export/db/examples/nested_function.py,sha256=S-MXIlaFn4RGeA4GEFIEHG-pcM9WBznXN3E2k-sDlZo,491 +torch/_export/db/examples/null_context_manager.py,sha256=LM5a8DO8x0A0yaA0ZAhOVybcRIcpHy2fxCH0YoqH_2M,478 +torch/_export/db/examples/optional_input.py,sha256=JHVO8AbT5ihdUrr_ee5kZMuJOnyJZS2EdL9FYdS9Yns,447 +torch/_export/db/examples/pytree_flatten.py,sha256=MFIw36BZAXANZ-iajZi--lbPzf1EyDrcmWxPeQ_VCyA,376 +torch/_export/db/examples/scalar_output.py,sha256=_CMPbP3nbTMGzfiUy3ACOdxxoL8_F1lIEya_JH4HTZ4,543 +torch/_export/db/examples/specialized_attribute.py,sha256=GiKqGiSSPwPIL-QPinKinHNEiQvRsptBx319j7FpRfA,520 +torch/_export/db/examples/static_for_loop.py,sha256=wYtwzouoqqVC-Zsw_kHYe_Fzz-0mPxZ9zGwWrjdv8OQ,385 +torch/_export/db/examples/static_if.py,sha256=uzqQHEytorjGRbxJQQxam6nJZLHcPIPw1uzMfj7KU8w,397 +torch/_export/db/examples/tensor_setattr.py,sha256=LXED12gZiYOvhZXBzThejfW2meNYI8U-8_aIVwfdaqI,337 +torch/_export/db/examples/type_reflection_method.py,sha256=CoXAARKtqSNciuA5V7Tkx0MVhq-h6c4khPRSnxFDjcM,461 +torch/_export/db/examples/unsupported_operator.py,sha256=Y8tqzwbbN14AznoBlavyPBLPYPqQtnp9lx47rvJMQJU,399 +torch/_export/db/examples/user_input_mutation.py,sha256=KJY_YR4w_nEZ66YVMmPsBKv6PfQ7GnQwkV12NJcUCxs,302 +torch/_export/db/gen_example.py,sha256=cyFTffHUtwkSPfhk-5rKaKFA5l56JErtcR-VBPb7t_o,604 +torch/_export/db/logging.py,sha256=96gvkbZUoxwdFkzsSP2ofX9It_S2TiK_fTnfc4Wn8GI,1671 +torch/_export/error.py,sha256=OjvFCTGZVLlBtbTvaL4xDbBAizynfhwO_2fONObaISk,1770 +torch/_export/non_strict_utils.py,sha256=phufqakLuslIxYN49DU2PvXCEqcLEUl08-BKfb6Ln7U,52514 +torch/_export/pass_base.py,sha256=40qAo2W4FKvP_hXHJoFMyiTat1BCHJKO5exGn6nlZ3E,19212 +torch/_export/pass_infra/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_export/pass_infra/__pycache__/__init__.cpython-312.pyc,, +torch/_export/pass_infra/__pycache__/node_metadata.cpython-312.pyc,, +torch/_export/pass_infra/__pycache__/proxy_value.cpython-312.pyc,, +torch/_export/pass_infra/node_metadata.py,sha256=fF9lD71OeQ5HlSfR--IzjNMe7s67_N9T5Z1QvhGsa5s,771 +torch/_export/pass_infra/proxy_value.py,sha256=tIkdsWMBGdKHWtEW3vVS_6RqZTAZf7CimcY0OIEF31Y,1456 +torch/_export/passes/__init__.py,sha256=78MzFjtaVabk1z2X12WMIlmtkjYaFmgNJlDCTCepNt8,88 +torch/_export/passes/__pycache__/__init__.cpython-312.pyc,, +torch/_export/passes/__pycache__/_node_metadata_hook.cpython-312.pyc,, +torch/_export/passes/__pycache__/add_runtime_assertions_for_constraints_pass.cpython-312.pyc,, +torch/_export/passes/__pycache__/collect_tracepoints_pass.cpython-312.pyc,, +torch/_export/passes/__pycache__/constant_folding.cpython-312.pyc,, +torch/_export/passes/__pycache__/functionalize_side_effectful_ops_pass.cpython-312.pyc,, +torch/_export/passes/__pycache__/insert_custom_op_guards.cpython-312.pyc,, +torch/_export/passes/__pycache__/lift_constants_pass.cpython-312.pyc,, +torch/_export/passes/__pycache__/remove_runtime_assertions.cpython-312.pyc,, +torch/_export/passes/__pycache__/replace_autocast_with_hop_pass.cpython-312.pyc,, +torch/_export/passes/__pycache__/replace_quantized_ops_with_standard_ops_pass.cpython-312.pyc,, +torch/_export/passes/__pycache__/replace_set_grad_with_hop_pass.cpython-312.pyc,, +torch/_export/passes/__pycache__/replace_view_ops_with_view_copy_ops_pass.cpython-312.pyc,, +torch/_export/passes/__pycache__/replace_with_hop_pass_util.cpython-312.pyc,, +torch/_export/passes/_node_metadata_hook.py,sha256=L9i3p7Vzz53vG8wpirkYMi61F-Uxcn7-mnjMS09n7VU,3435 +torch/_export/passes/add_runtime_assertions_for_constraints_pass.py,sha256=bxtUJzZmGupls57lJVpZ5u6bOuRg_g6SZVXbsIksrKM,10207 +torch/_export/passes/collect_tracepoints_pass.py,sha256=3vWcN1V-hl588dQ9estymdTNxivxiex8YLA-7ZKmShs,7215 +torch/_export/passes/constant_folding.py,sha256=1xwQ9IHgsu95ySlrzzcwkRecu-Daz6nvDCHBJehgk_E,11290 +torch/_export/passes/functionalize_side_effectful_ops_pass.py,sha256=1fjMfdGrG138Lm7n5KLVkbsbAM9bGxu66BdjAwov42o,3370 +torch/_export/passes/insert_custom_op_guards.py,sha256=89yaS7aO2E-BzxllQWa3HJRmFBKwFbSg1861bAem4CI,3096 +torch/_export/passes/lift_constants_pass.py,sha256=ui07C8M6c5fwWxB0UVVxw5Qjr3w4soDYFNA1Av0bHmU,18916 +torch/_export/passes/remove_runtime_assertions.py,sha256=uyvuiO5Qy9AYVfbaOvyOYeBaZ_yUzgoPSsfJ1lDb0-g,1588 +torch/_export/passes/replace_autocast_with_hop_pass.py,sha256=D0uBUEdo2ogaitXuCm8P84kO3e8vMw0wD1cSpkiCzGs,8358 +torch/_export/passes/replace_quantized_ops_with_standard_ops_pass.py,sha256=CBrGeisZB1-XLm1N5efSCrI-XbaOkk6LM3JcsHNISE8,27635 +torch/_export/passes/replace_set_grad_with_hop_pass.py,sha256=n_gzfMgXNRmnUar7HoXPiHCqlS5exkX-QEnxB3h3miU,4939 +torch/_export/passes/replace_view_ops_with_view_copy_ops_pass.py,sha256=-8zA-otMVordLl2mWpPcutMJiTF1pZCLKS-xh2_1cjY,2380 +torch/_export/passes/replace_with_hop_pass_util.py,sha256=zF88vi3-7SozewngqRx_bwDn4KKhv1s3nwPIprDq80o,8243 +torch/_export/serde/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_export/serde/__pycache__/__init__.cpython-312.pyc,, +torch/_export/serde/__pycache__/dynamic_shapes.cpython-312.pyc,, +torch/_export/serde/__pycache__/schema.cpython-312.pyc,, +torch/_export/serde/__pycache__/schema_check.cpython-312.pyc,, +torch/_export/serde/__pycache__/serialize.cpython-312.pyc,, +torch/_export/serde/__pycache__/union.cpython-312.pyc,, +torch/_export/serde/dynamic_shapes.py,sha256=EgxY4ZeT5UOeSKVo0qCbCBm9BdIbjnQZvjhI0ko0EmQ,11752 +torch/_export/serde/export_schema.thrift,sha256=XXqURSIjrmItA6xEl_Oy98le65Ss4NQsFKtoQ-7n64k,7493 +torch/_export/serde/schema.py,sha256=VKXLq_Mr8NbRiPNKkQLoFWQjXvxUuqxhgDHEAhX4aSQ,16742 +torch/_export/serde/schema.yaml,sha256=oz48yb7FH8txlwWsE9DehcHcYBNz4JYTtkfq7klp6Ys,10147 +torch/_export/serde/schema_check.py,sha256=ZyJaxCvhs7Lb74R6L93qQVVzPdZzb68Jg4-FhGCU4Ho,32047 +torch/_export/serde/serialize.py,sha256=mXDgM498Q7F7Mo3uki08UOxFSmN4p6L2Fk-R3nvf2Ss,183561 +torch/_export/serde/union.py,sha256=yV8tNfP3SSGS4THC6MjBQL2nW_-btXkOmeJ9wfyq8HM,3533 +torch/_export/tools.py,sha256=rYBcj8Ryzz6eXbviQR91P-r4-K3rnwhL3a9qWO4oV_Y,4577 +torch/_export/utils.py,sha256=hv3SQdb4BQHiEo2TYBknEnIVjaJLY6Wa1UjMsPJoNAM,63476 +torch/_export/verifier.py,sha256=qYu6fAlwWTtminzqL2MmGar9f4iG3BZ1_kGO7MfWxL8,24194 +torch/_export/wrappers.py,sha256=gU4_aKknnnAxaqOpoIVnzQu7pldhpqPu5R3EfrrSoDo,15817 +torch/_functorch/__init__.py,sha256=a3XxW1RcNAPwEVaI2g11hpnJvSHxGUFsGmDAWfDnLP8,206 +torch/_functorch/__pycache__/__init__.cpython-312.pyc,, +torch/_functorch/__pycache__/aot_autograd.cpython-312.pyc,, +torch/_functorch/__pycache__/apis.cpython-312.pyc,, +torch/_functorch/__pycache__/autograd_function.cpython-312.pyc,, +torch/_functorch/__pycache__/batch_norm_replacement.cpython-312.pyc,, +torch/_functorch/__pycache__/benchmark_utils.cpython-312.pyc,, +torch/_functorch/__pycache__/compile_utils.cpython-312.pyc,, +torch/_functorch/__pycache__/compilers.cpython-312.pyc,, +torch/_functorch/__pycache__/config.cpython-312.pyc,, +torch/_functorch/__pycache__/deprecated.cpython-312.pyc,, +torch/_functorch/__pycache__/eager_transforms.cpython-312.pyc,, +torch/_functorch/__pycache__/einops.cpython-312.pyc,, +torch/_functorch/__pycache__/functional_call.cpython-312.pyc,, +torch/_functorch/__pycache__/fx_minifier.cpython-312.pyc,, +torch/_functorch/__pycache__/make_functional.cpython-312.pyc,, +torch/_functorch/__pycache__/partitioners.cpython-312.pyc,, +torch/_functorch/__pycache__/predispatch.cpython-312.pyc,, +torch/_functorch/__pycache__/pyfunctorch.cpython-312.pyc,, +torch/_functorch/__pycache__/python_key.cpython-312.pyc,, +torch/_functorch/__pycache__/pytree_hacks.cpython-312.pyc,, +torch/_functorch/__pycache__/top_operators_github_usage.cpython-312.pyc,, +torch/_functorch/__pycache__/utils.cpython-312.pyc,, +torch/_functorch/__pycache__/vmap.cpython-312.pyc,, +torch/_functorch/_activation_checkpointing/__init__.py,sha256=a3XxW1RcNAPwEVaI2g11hpnJvSHxGUFsGmDAWfDnLP8,206 +torch/_functorch/_activation_checkpointing/__pycache__/__init__.cpython-312.pyc,, +torch/_functorch/_activation_checkpointing/__pycache__/ac_logging_utils.cpython-312.pyc,, +torch/_functorch/_activation_checkpointing/__pycache__/graph_info_provider.cpython-312.pyc,, +torch/_functorch/_activation_checkpointing/__pycache__/knapsack.cpython-312.pyc,, +torch/_functorch/_activation_checkpointing/__pycache__/knapsack_evaluator.cpython-312.pyc,, +torch/_functorch/_activation_checkpointing/__pycache__/remat_using_tags_for_fwd_loss_bwd_graph_pass.cpython-312.pyc,, +torch/_functorch/_activation_checkpointing/ac_logging_utils.py,sha256=5yAgKsM9Nlo0nRfwsfaReYHQkgOrBdrbVteB70VW6Xw,10420 +torch/_functorch/_activation_checkpointing/graph_info_provider.py,sha256=agG5nlht2-xRTRCjIXsJOn0S1XmMhXZpXPiHyx-mTDg,12701 +torch/_functorch/_activation_checkpointing/knapsack.py,sha256=eULO3neRqPtg84WsKf57jn4thXQjxZ_oQEUdQ_6_erQ,9260 +torch/_functorch/_activation_checkpointing/knapsack_evaluator.py,sha256=ySyujb2Zil6krY1N5UTGHDFfSpHxe5Ig1hQPqAhiocs,12276 +torch/_functorch/_activation_checkpointing/remat_using_tags_for_fwd_loss_bwd_graph_pass.py,sha256=XlE9j6Tyu_G6QljHgpE10MtV9bpa3xYY44sXWL6RVPw,9255 +torch/_functorch/_activation_offloading/__init__.py,sha256=a3XxW1RcNAPwEVaI2g11hpnJvSHxGUFsGmDAWfDnLP8,206 +torch/_functorch/_activation_offloading/__pycache__/__init__.cpython-312.pyc,, +torch/_functorch/_activation_offloading/__pycache__/activation_offloading.cpython-312.pyc,, +torch/_functorch/_activation_offloading/__pycache__/offload_ops.cpython-312.pyc,, +torch/_functorch/_activation_offloading/activation_offloading.py,sha256=Bkcxw7I9fYZXZ9tKOIYysdFCFfCm6u7kE-S3yja6rjg,31602 +torch/_functorch/_activation_offloading/offload_ops.py,sha256=Xwj0xNiTLvOR-JDV9xOJtxIgOhseNqvHgvAtOsHHPaw,11273 +torch/_functorch/_aot_autograd/__init__.py,sha256=a3XxW1RcNAPwEVaI2g11hpnJvSHxGUFsGmDAWfDnLP8,206 +torch/_functorch/_aot_autograd/__pycache__/__init__.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/aot_autograd_result.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/autograd_cache.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/codegen.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/collect_metadata_analysis.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/complex_decomposition.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/descriptors.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/frontend_utils.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/functional_utils.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/fx_utils.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/graph_capture.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/graph_capture_wrappers.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/graph_compile.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/indexed_dict.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/input_output_analysis.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/logging_utils.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/runtime_wrappers.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/schemas.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/source_emit.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/standalone_runtime.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/streams.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/subclass_codegen.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/subclass_parametrization.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/subclass_utils.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/to_standalone_python.cpython-312.pyc,, +torch/_functorch/_aot_autograd/__pycache__/utils.cpython-312.pyc,, +torch/_functorch/_aot_autograd/aot_autograd_result.py,sha256=0ep0Ti2jxyFFS_UENm_n0yrTEzlKkZZm2xmBgor8Mig,28240 +torch/_functorch/_aot_autograd/autograd_cache.py,sha256=j4NXYY72Vt2EP93cCGDIfoMYJqHNazOGDn4AefUNeWI,66438 +torch/_functorch/_aot_autograd/codegen.py,sha256=z0c2A59OKQL2gvmsVINZwGgB_K5W2RGGtP3MNKeVfno,10386 +torch/_functorch/_aot_autograd/collect_metadata_analysis.py,sha256=br2azcUPEDYD1keMFHY8jqjSjAm0PML377pEyUM4jtk,45595 +torch/_functorch/_aot_autograd/complex_decomposition.py,sha256=BnY9GS_C9kpy3Y01zsfMV8PvHi-oa56xR0QbP18WkfA,4720 +torch/_functorch/_aot_autograd/descriptors.py,sha256=YJnLO9Z3M6oTq3yhzeC0e0W8EoL-DEx1op9i-9eF7Vo,28150 +torch/_functorch/_aot_autograd/frontend_utils.py,sha256=aB1HwMgXC3dGFkccIlBb1p9LRosvvGR3MUnTPWLDgCk,19902 +torch/_functorch/_aot_autograd/functional_utils.py,sha256=EEtlsOrJH6nILDdGKaBVICXvl_xpgNGHWHjwiOHZaxM,30977 +torch/_functorch/_aot_autograd/fx_utils.py,sha256=Z69mkI_QYKgCrB6PE3ZztWFMZE4nv91LoOPDsgf5sak,12647 +torch/_functorch/_aot_autograd/graph_capture.py,sha256=7dz8hy9M99xnng3ZaXYl71WQRQWEAIyKOUCp7NX2LRA,22053 +torch/_functorch/_aot_autograd/graph_capture_wrappers.py,sha256=Ip1dVXVTnyexmdg10YMU4U6Z6YxHVdRnJN7bsSaD2Mg,70539 +torch/_functorch/_aot_autograd/graph_compile.py,sha256=v3KsrYZrlaEs69ddMBDc_CqN5TO4sfg_x89TFAiCAi4,114117 +torch/_functorch/_aot_autograd/indexed_dict.py,sha256=tXYzmFA39UlhLc9x_4suTdDXgMMLXsJYhPiocutWjfw,1743 +torch/_functorch/_aot_autograd/input_output_analysis.py,sha256=ZNoqwO18cQLOXNGISSSKWmmYzXOZOA0RAfAmidABhxU,20812 +torch/_functorch/_aot_autograd/logging_utils.py,sha256=u9H_0eLOYgRbyeAVjL6BBq0xJs1s9vbxjqvb0-hgkeA,5515 +torch/_functorch/_aot_autograd/runtime_wrappers.py,sha256=14ehUgPGi1MxrPk5nwgJ0BGFMAvN4V_9aBM_7S-9ULQ,163255 +torch/_functorch/_aot_autograd/schemas.py,sha256=DAkxw9WWDPtgxweNgYXV1j94GPEPDRBBAB21uB1kVvE,67323 +torch/_functorch/_aot_autograd/source_emit.py,sha256=VpgzJrEMo-wtiona_VEQ2sdSrX_MM38smIFaniu5F7I,28799 +torch/_functorch/_aot_autograd/standalone_runtime.py,sha256=CRQbVRRz05L5LjwVTX5pplHA-feB90QAgKAi4pe0pcI,2198 +torch/_functorch/_aot_autograd/streams.py,sha256=OM7eBAzI5E0CPs84ivuIHKO7lqwzAWahG6gW5NUlGbM,41853 +torch/_functorch/_aot_autograd/subclass_codegen.py,sha256=6zod_kK9ZzPd-NWBh58rC83ILvQL5uUqRd3fjIvBZsA,23906 +torch/_functorch/_aot_autograd/subclass_parametrization.py,sha256=uWkikEt1TPA1Y2qpGgHmGonP6_Re3289vpPCB4xvnZM,5776 +torch/_functorch/_aot_autograd/subclass_utils.py,sha256=O5g0KnKYO7TWTiglEelBfv2vF9CaNPOWqMV5GThbS88,31639 +torch/_functorch/_aot_autograd/to_standalone_python.py,sha256=ApU3445mL_sf9fCjiHpAmw4OMnhXno5hAYv8G3mw8B0,53884 +torch/_functorch/_aot_autograd/utils.py,sha256=_zjVvGR1QN4zgoxebdqONsDNWwvKg64TjE3I1Uaq264,35440 +torch/_functorch/aot_autograd.py,sha256=kbXSA9X12slufMSv4moyCrWJH_cEA260FpUH9zDl3y0,79481 +torch/_functorch/apis.py,sha256=jje1tyGyHCjczl3phVL7ZuFsRFaOUTWtUksuu4ZsiCs,20732 +torch/_functorch/autograd_function.py,sha256=g4FSv3PQdBDkejmi8tdTdqO-522ALv9m75prw_jaf08,35289 +torch/_functorch/batch_norm_replacement.py,sha256=liTJLEOFiap3ed2fBoxdRUM-9iuw-6985kJSXZnUlNs,857 +torch/_functorch/benchmark_utils.py,sha256=03FAai3cgts7TxKZmRbK1iQPXdjYdg1sZz_9SjXaSEo,7167 +torch/_functorch/compile_utils.py,sha256=Eb2gXiUuIGUTGyfKEvHE7B70-E9V8uwWIw1cZV2lcvU,11714 +torch/_functorch/compilers.py,sha256=9qKEXQqMHlliqRetzCqi1sO33NRAd7Z_DE1rXjU4lvI,16717 +torch/_functorch/config.py,sha256=sQjiq1JpCg9k_cmmJMJbNJiddNAGLPFf9vVWG16hziQ,20374 +torch/_functorch/deprecated.py,sha256=SHvlwZPnuj_0sGtuj2O1WTs0Sb9-ZWvhVOJSxnJQqtU,5731 +torch/_functorch/eager_transforms.py,sha256=cgS_XKCm4A1gNlgooPw7w9SJfZ02Y4SDu44MwaT310Y,77640 +torch/_functorch/einops.py,sha256=2itgTolzB2uktVVoe-kgDdohYBPD7PBx7c232cfChoI,2772 +torch/_functorch/functional_call.py,sha256=3O5PMf1mu3ZB_BqZ3W62zPH6Hn5_PfmjQ_JKNtnbJAc,10577 +torch/_functorch/fx_minifier.py,sha256=nsUG5ncGLHsN2dsfU3sNlvlnatgOHeWy_-1nrffIvcw,20132 +torch/_functorch/make_functional.py,sha256=PVBP0fo9nphZXaGu-3wMfEdiDjPd05pWbpiqjPcHUno,24492 +torch/_functorch/partitioners.py,sha256=QqZUEEIN9EqMFqreVtsM-T3nF0g1DpPnFkCjVN61QbM,176554 +torch/_functorch/predispatch.py,sha256=C3eCFGabtmSLg1y7vrevYzrku22MSWcLIxvE7Vuvl9w,9776 +torch/_functorch/pyfunctorch.py,sha256=orEdNWO3nruuRt9zFhM8lr3aLLG_ANPZNBlTiUGf_Pg,12546 +torch/_functorch/python_key.py,sha256=ZeINkQZ4B4PAdoz-zLMNU72w6cVHzE1nObMikLI0oL4,442 +torch/_functorch/pytree_hacks.py,sha256=dWzTSKcqGhK4zHgmgJbyis2kzB69OH71GP_YCDBDbp0,698 +torch/_functorch/top_operators_github_usage.py,sha256=0iRkuZZ3DxAgsfxHfqI95sfrKYrVVk_pifo3_4REFRI,21544 +torch/_functorch/utils.py,sha256=97jBfnS9abhcLX-bGWI-Oe5CCzxHhtPoOTS2ocOAA9g,749 +torch/_functorch/vmap.py,sha256=HI05NhVtYn41AL6RKQYf7kdE5vFNsuCPfQKQKozivUY,19406 +torch/_guards.py,sha256=nmsE-Zun_QAr9YT8frHsG6clK9iOXBmtOUaGuQjJhng,59597 +torch/_higher_order_ops/__init__.py,sha256=xm4UyMbfzSigORxEhkcKwFT9451RV-M2Ds_ZTxctTcg,2953 +torch/_higher_order_ops/__pycache__/__init__.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/_invoke_quant.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/aoti_call_delegate.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/associative_scan.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/auto_functionalize.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/base_hop.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/cond.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/cudagraph_conditional_nodes.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/effects.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/executorch_call_delegate.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/flat_apply.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/flex_attention.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/flex_gemm.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/foreach_map.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/hints_wrap.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/inline_asm_elementwise.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/invoke_leaf_function.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/invoke_subgraph.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/local_map.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/map.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/out_dtype.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/partitioner.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/print.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/register_hook.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/run_const_graph.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/scan.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/schema.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/strict_mode.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/switch.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/torchbind.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/triton_kernel_wrap.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/utils.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/while_loop.cpython-312.pyc,, +torch/_higher_order_ops/__pycache__/wrap.cpython-312.pyc,, +torch/_higher_order_ops/_invoke_quant.py,sha256=igRdMRGVeX-YVwt5-kHJLUGQhtQ11s7LnP0Hq4ypxqU,1739 +torch/_higher_order_ops/aoti_call_delegate.py,sha256=X5PQDp7JY6kKbWp2smUHocCZY1v0Pp9-AsDW6RGeOZ8,6171 +torch/_higher_order_ops/associative_scan.py,sha256=d5pcpLVK7RUpsaSWXUbKIHSkyk1E2tP4FqqTNH6Xfho,37357 +torch/_higher_order_ops/auto_functionalize.py,sha256=DwTG5MqciKKyROdv3VOLh2iBnqIN6ehOJH7Ks3cRLCA,46086 +torch/_higher_order_ops/base_hop.py,sha256=6E_Q9bkQG76EfeuAw3Ewc0pYrjaB6Wef4FeXgChGOQM,10763 +torch/_higher_order_ops/cond.py,sha256=rX68GDlFp4x_h5eOMu-b59_7j2si1P484Q0OFcmiqhE,30590 +torch/_higher_order_ops/cudagraph_conditional_nodes.py,sha256=s0lGtzwrnJ6ZPP1KwxxJtCFDPtQwOVWc-jfPDv5weN0,8061 +torch/_higher_order_ops/effects.py,sha256=g1B5UWAKRH3aF64XhoWP8iacG77q1PnPwerbBA8WqYA,12068 +torch/_higher_order_ops/executorch_call_delegate.py,sha256=zwahXRYbwX5zWMNugIJcAsgztOUjVWRzfp5FL04V_U4,6130 +torch/_higher_order_ops/flat_apply.py,sha256=9Y8CsFBiaZ_dwGL11V1HahQLE0YrlPOIbTgWF5xnthU,6327 +torch/_higher_order_ops/flex_attention.py,sha256=j-P2GsfsbmLAUN4SLYFa7vbCAzk-69GrSJktdLB_8sQ,54928 +torch/_higher_order_ops/flex_gemm.py,sha256=lfTAVqiCVWyUZ7-jwEweYHq-PrVxv4Pxqqbt-aIf7FI,12604 +torch/_higher_order_ops/foreach_map.py,sha256=xEvWbG-fWPZaVF1AjLrPnG2bJ1Duwr6Uf0YmVvndJx8,690 +torch/_higher_order_ops/hints_wrap.py,sha256=GruVzBTKZq9b6HjiWkHoOXhXbi_ZcVaqXo7WTo4ubD8,4766 +torch/_higher_order_ops/inline_asm_elementwise.py,sha256=u3kAjTwycqvz795Km1yivB2xuyW97woDf7twsRx8_f4,9346 +torch/_higher_order_ops/invoke_leaf_function.py,sha256=f1YxzukMhsgIodkkWb0fEQHlJ7k-6LAPni8VBiiF-G8,35483 +torch/_higher_order_ops/invoke_subgraph.py,sha256=IMspTCjeSRQCqxmRPq5kQPWZ5FObqE9bynJ-8kJPPE4,59371 +torch/_higher_order_ops/local_map.py,sha256=2nrc12qBwRJjrkCbK3XV5NPFRDMjA3IRt8EVhRBYR4U,25538 +torch/_higher_order_ops/map.py,sha256=DJN3bt5QeKjqXsBH3ArWpYS3_b92ITdhclNYwxh6qwA,15103 +torch/_higher_order_ops/out_dtype.py,sha256=HmjkHzsjQwAFYwMEtBSAuL-nM2-AwJBM-nWcsXFkKZ8,5532 +torch/_higher_order_ops/partitioner.py,sha256=BNoN5IIDBbVKZ5M17BOTSUK09ETteR4Lc47zS0t1hOo,14233 +torch/_higher_order_ops/passes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_higher_order_ops/passes/__pycache__/__init__.cpython-312.pyc,, +torch/_higher_order_ops/passes/__pycache__/inline_invoke_subgraph.cpython-312.pyc,, +torch/_higher_order_ops/passes/inline_invoke_subgraph.py,sha256=rDpuL_2BY9LmHuq_Ql2XvZAsAlwOvXYtjRdYuUagKxM,5585 +torch/_higher_order_ops/print.py,sha256=uEJZ0N2eFAWmGFokaYP9U3ZUAaW9tvncaaTpVCBoGAU,5707 +torch/_higher_order_ops/register_hook.py,sha256=jaOHcUfOhBBj2lTmNQlznzGISc898XevzhdO_zUGdJc,960 +torch/_higher_order_ops/run_const_graph.py,sha256=VyH4UBLcPI1fagcsjPFa3QcZQx7d8cnjvE_ZW8xj3sE,2867 +torch/_higher_order_ops/scan.py,sha256=a7mA2M7s8EVab0VAAQX8HT5STGx8H5OvdUOupq2S2Hs,49270 +torch/_higher_order_ops/schema.py,sha256=QLlYoXIrDgJkiUif0hWHwpSB9jv7ClrXvn1pWdAbWqA,12007 +torch/_higher_order_ops/strict_mode.py,sha256=3gm3pcgGmfK_Okqw8lCYjMuRDgU4abMY4ui0XCJm1xQ,2835 +torch/_higher_order_ops/switch.py,sha256=rxYyYuvZaRzfMwWJ130QfpVw5wWtD-D8--_GtmWt_gY,15999 +torch/_higher_order_ops/torchbind.py,sha256=rNugK48FCUmta30Fxe-or86AOoNqIyBcekG5ugmeYRo,6482 +torch/_higher_order_ops/triton_kernel_wrap.py,sha256=pn-BeU_dia1ltzeKtUQUf_lqGGTZhXkyAr_z9xESjVs,107800 +torch/_higher_order_ops/utils.py,sha256=ALQmFGyZdLjFNnA5FPoNR3MHDuJZsrBc69mIxD8MOdg,57299 +torch/_higher_order_ops/while_loop.py,sha256=GFPjiXibd4T05ATtknUJvLtAVJwOirIDcDY-x97SUTk,39266 +torch/_higher_order_ops/wrap.py,sha256=V5VHFjY1x6L35zgNv78Qgj0FiLXL_d3MrgWjrrSWn5c,20184 +torch/_inductor/__autotune_main__.py,sha256=teBVDb5194YrCJgy05KRE1yAkfDrAfFIA2cIwYFnyRw,913 +torch/_inductor/__init__.py,sha256=vcPxDbSXoRTUC2G6X1mYN4ai0wIADkwhEUeLHwFwFUY,15989 +torch/_inductor/__pycache__/__autotune_main__.cpython-312.pyc,, +torch/_inductor/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/__pycache__/_functionalize_collectives.cpython-312.pyc,, +torch/_inductor/__pycache__/analyze_preserves_zero_mask.cpython-312.pyc,, +torch/_inductor/__pycache__/aoti_eager.cpython-312.pyc,, +torch/_inductor/__pycache__/async_compile.cpython-312.pyc,, +torch/_inductor/__pycache__/augmented_graph_helper.cpython-312.pyc,, +torch/_inductor/__pycache__/autotune_process.cpython-312.pyc,, +torch/_inductor/__pycache__/autows_utils.cpython-312.pyc,, +torch/_inductor/__pycache__/await_utils.cpython-312.pyc,, +torch/_inductor/__pycache__/bounds.cpython-312.pyc,, +torch/_inductor/__pycache__/cache.cpython-312.pyc,, +torch/_inductor/__pycache__/cache_key.cpython-312.pyc,, +torch/_inductor/__pycache__/choices.cpython-312.pyc,, +torch/_inductor/__pycache__/codecache.cpython-312.pyc,, +torch/_inductor/__pycache__/comm_analysis.cpython-312.pyc,, +torch/_inductor/__pycache__/comm_lowering.cpython-312.pyc,, +torch/_inductor/__pycache__/comms.cpython-312.pyc,, +torch/_inductor/__pycache__/comms_debug.cpython-312.pyc,, +torch/_inductor/__pycache__/compile_fx.cpython-312.pyc,, +torch/_inductor/__pycache__/compile_fx_async.cpython-312.pyc,, +torch/_inductor/__pycache__/compile_fx_ext.cpython-312.pyc,, +torch/_inductor/__pycache__/compile_fx_subproc.cpython-312.pyc,, +torch/_inductor/__pycache__/compiler_bisector.cpython-312.pyc,, +torch/_inductor/__pycache__/config.cpython-312.pyc,, +torch/_inductor/__pycache__/config_comms.cpython-312.pyc,, +torch/_inductor/__pycache__/constant_folding.cpython-312.pyc,, +torch/_inductor/__pycache__/cpp_builder.cpython-312.pyc,, +torch/_inductor/__pycache__/cpu_vec_isa.cpython-312.pyc,, +torch/_inductor/__pycache__/cudagraph_trees.cpython-312.pyc,, +torch/_inductor/__pycache__/cudagraph_utils.cpython-312.pyc,, +torch/_inductor/__pycache__/custom_graph_pass.cpython-312.pyc,, +torch/_inductor/__pycache__/debug.cpython-312.pyc,, +torch/_inductor/__pycache__/decomposition.cpython-312.pyc,, +torch/_inductor/__pycache__/dependencies.cpython-312.pyc,, +torch/_inductor/__pycache__/distributed_autotune.cpython-312.pyc,, +torch/_inductor/__pycache__/dtype_propagation.cpython-312.pyc,, +torch/_inductor/__pycache__/exc.cpython-312.pyc,, +torch/_inductor/__pycache__/extern_node_serializer.cpython-312.pyc,, +torch/_inductor/__pycache__/freezing.cpython-312.pyc,, +torch/_inductor/__pycache__/freezing_utils.cpython-312.pyc,, +torch/_inductor/__pycache__/fuzzer.cpython-312.pyc,, +torch/_inductor/__pycache__/fx_utils.cpython-312.pyc,, +torch/_inductor/__pycache__/graph.cpython-312.pyc,, +torch/_inductor/__pycache__/hooks.cpython-312.pyc,, +torch/_inductor/__pycache__/index_propagation.cpython-312.pyc,, +torch/_inductor/__pycache__/inductor_prims.cpython-312.pyc,, +torch/_inductor/__pycache__/invert_expr_analysis.cpython-312.pyc,, +torch/_inductor/__pycache__/ir.cpython-312.pyc,, +torch/_inductor/__pycache__/jagged_lowerings.cpython-312.pyc,, +torch/_inductor/__pycache__/kernel_inputs.cpython-312.pyc,, +torch/_inductor/__pycache__/kernel_template_choice.cpython-312.pyc,, +torch/_inductor/__pycache__/loop_body.cpython-312.pyc,, +torch/_inductor/__pycache__/lowering.cpython-312.pyc,, +torch/_inductor/__pycache__/memory.cpython-312.pyc,, +torch/_inductor/__pycache__/metrics.cpython-312.pyc,, +torch/_inductor/__pycache__/mkldnn_ir.cpython-312.pyc,, +torch/_inductor/__pycache__/mkldnn_lowerings.cpython-312.pyc,, +torch/_inductor/__pycache__/mock_cache.cpython-312.pyc,, +torch/_inductor/__pycache__/ops_handler.cpython-312.pyc,, +torch/_inductor/__pycache__/optimize_indexing.cpython-312.pyc,, +torch/_inductor/__pycache__/output_code.cpython-312.pyc,, +torch/_inductor/__pycache__/pattern_matcher.cpython-312.pyc,, +torch/_inductor/__pycache__/profiler.cpython-312.pyc,, +torch/_inductor/__pycache__/quantized_lowerings.cpython-312.pyc,, +torch/_inductor/__pycache__/remote_cache.cpython-312.pyc,, +torch/_inductor/__pycache__/remote_gemm_autotune_cache.cpython-312.pyc,, +torch/_inductor/__pycache__/rocm_multiarch_utils.cpython-312.pyc,, +torch/_inductor/__pycache__/scheduler.cpython-312.pyc,, +torch/_inductor/__pycache__/select_algorithm.cpython-312.pyc,, +torch/_inductor/__pycache__/shape_propagation.cpython-312.pyc,, +torch/_inductor/__pycache__/sizevars.cpython-312.pyc,, +torch/_inductor/__pycache__/standalone_compile.cpython-312.pyc,, +torch/_inductor/__pycache__/stream_constants.cpython-312.pyc,, +torch/_inductor/__pycache__/stream_utils.cpython-312.pyc,, +torch/_inductor/__pycache__/subgraph_lowering.cpython-312.pyc,, +torch/_inductor/__pycache__/test_case.cpython-312.pyc,, +torch/_inductor/__pycache__/test_operators.cpython-312.pyc,, +torch/_inductor/__pycache__/tiling_utils.cpython-312.pyc,, +torch/_inductor/__pycache__/triton_bundler.cpython-312.pyc,, +torch/_inductor/__pycache__/utils.cpython-312.pyc,, +torch/_inductor/__pycache__/virtualized.cpython-312.pyc,, +torch/_inductor/__pycache__/wrapper_benchmark.cpython-312.pyc,, +torch/_inductor/_functionalize_collectives.py,sha256=P5vZ5VFPdvMnWw1DvSNa40vJBFSMu3mi7WV-LzZGjOc,11844 +torch/_inductor/analysis/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/analysis/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/analysis/__pycache__/device_info.cpython-312.pyc,, +torch/_inductor/analysis/__pycache__/profile_analysis.cpython-312.pyc,, +torch/_inductor/analysis/device_info.py,sha256=-AVyjLWZRx_-PLSyRN9AyyoPb31t-hIfYjoEApslMYg,12346 +torch/_inductor/analysis/profile_analysis.py,sha256=kSHRdEqQgRU9x2O7DzZyxr80ZJ3KF8LVT_TCC7BfozQ,29260 +torch/_inductor/analyze_preserves_zero_mask.py,sha256=-jffj3laHHl8OLLu-3lZTEGyFqeQ3mEKrO9nEZlrJlU,5762 +torch/_inductor/aoti_eager.py,sha256=ZoATArkZE-oog6ko6sTh3U6Nfv4qGfi7koa9KSKC6pA,14954 +torch/_inductor/async_compile.py,sha256=M119cya5_lkj8y_I3hd4fZQaDyaNLL07LnuvN6SQcrY,37780 +torch/_inductor/augmented_graph_helper.py,sha256=PP23tOQXv0luJHiW_p673vOZ3qp5K6oN58IDPYwu6tI,11384 +torch/_inductor/autoheuristic/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/autoheuristic/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/autoheuristic/__pycache__/autoheuristic.cpython-312.pyc,, +torch/_inductor/autoheuristic/__pycache__/autoheuristic_utils.cpython-312.pyc,, +torch/_inductor/autoheuristic/__pycache__/learned_heuristic_controller.cpython-312.pyc,, +torch/_inductor/autoheuristic/__pycache__/learnedheuristic_interface.cpython-312.pyc,, +torch/_inductor/autoheuristic/artifacts/_MMRankingA100.py,sha256=wGZv4bFCwDlPlavBWdX4J9aKw9wRZaPTnRsqgyZnQog,28038 +torch/_inductor/autoheuristic/artifacts/_MMRankingH100.py,sha256=OQN-QYXZ2yYIZQUvGlEy-AC6fTzUVqgf9i_uxAp3ZdA,30662 +torch/_inductor/autoheuristic/artifacts/_MixedMMA100.py,sha256=odGa8EdsobbeiKoKDrzkoYmDYgICi62YDFtwHE5fzEM,7914 +torch/_inductor/autoheuristic/artifacts/_MixedMMH100.py,sha256=-ASwKTfLGuKkdoPYpszoAJOFhRZzQ5UxA_V9y-f1SXc,7863 +torch/_inductor/autoheuristic/artifacts/_PadMMA100.py,sha256=VJxvqunz6QFV25E4FrmM4O_2N2tB1svXYVgK-MIHIys,13991 +torch/_inductor/autoheuristic/artifacts/_PadMMH200.py,sha256=kwnmibiVDQ1Oh_Dl7nBd9hugqvqoJT1XrVfoFI6WpkY,8501 +torch/_inductor/autoheuristic/artifacts/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/autoheuristic/artifacts/__pycache__/_MMRankingA100.cpython-312.pyc,, +torch/_inductor/autoheuristic/artifacts/__pycache__/_MMRankingH100.cpython-312.pyc,, +torch/_inductor/autoheuristic/artifacts/__pycache__/_MixedMMA100.cpython-312.pyc,, +torch/_inductor/autoheuristic/artifacts/__pycache__/_MixedMMH100.cpython-312.pyc,, +torch/_inductor/autoheuristic/artifacts/__pycache__/_PadMMA100.cpython-312.pyc,, +torch/_inductor/autoheuristic/artifacts/__pycache__/_PadMMH200.cpython-312.pyc,, +torch/_inductor/autoheuristic/artifacts/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/autoheuristic/autoheuristic.py,sha256=BnbpaS3DJ2Phg33m7yx8c_GaJJtf3mO1Q4jOGn4FykI,12163 +torch/_inductor/autoheuristic/autoheuristic_utils.py,sha256=iIGOequmvZOkKXMsREnRV3jJBinHCcVtvxAPbR4ot3E,11322 +torch/_inductor/autoheuristic/learned_heuristic_controller.py,sha256=cLy1FwX_1ByT1VPbv6UtNjFLF3g6NLR15YAZ0QljL48,4301 +torch/_inductor/autoheuristic/learnedheuristic_interface.py,sha256=_oEC4sIE5l50zhgPutB9O7ccRomvzOaaVmf-GBeC6DI,2641 +torch/_inductor/autotune_process.py,sha256=CGXu0cxBKhBvzTxhpyzaJXDHNSFcXtMiEikewKbLWc4,57021 +torch/_inductor/autows_utils.py,sha256=2qZfGz_-HKPl7btG4yxvJwfVdWPKVD0rB2jCsKgYalc,568 +torch/_inductor/await_utils.py,sha256=dSA8QYMzzVtu6YNiKL9FeZHewAL3GNywqxULkTn7jvY,5819 +torch/_inductor/bounds.py,sha256=iLfmEXYZpsCQUgxNLvTtzGdLKZ57Fy7WBBZRpH9p98I,10319 +torch/_inductor/cache.py,sha256=WCVejf3ofSc2lvXuFrE9BbQrTo1RSMeomWri1yVSizM,14823 +torch/_inductor/cache_key.py,sha256=nzwgQpG806LtxcS4DfXHtl73bqk1L5FmqdpY2HU7kQE,3225 +torch/_inductor/choices.py,sha256=XzJTKHJRYeS2xKS_FuE_BV08KNl08KvgYa2W-eLcFmQ,32343 +torch/_inductor/codecache.py,sha256=HtrcHhIprb18b4TO9DoEwDGt1uF5O-DxK3PyJ5iWYVY,219171 +torch/_inductor/codegen/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/codegen/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/aoti_hipify_utils.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/block_analysis.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/common.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cpp.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cpp_bmm_template.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cpp_flex_attention_template.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cpp_gemm_template.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cpp_grouped_gemm_template.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cpp_micro_gemm.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cpp_template.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cpp_template_kernel.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cpp_utils.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cpp_wrapper_cpu_array_ref.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cpp_wrapper_gpu.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cpp_wrapper_mps.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cpu_device_op_overrides.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/cuda_combined_scheduling.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/custom_extern_kernel_codegen.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/debug_utils.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/halide.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/memory_planning.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/metal_flex_attention_template.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/mps.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/mps_device_op_overrides.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/multi_kernel.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/pallas.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/python_wrapper_mtia.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/segmented_tree.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/simd.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/simd_kernel_features.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/subgraph.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/triton.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/triton_combo_kernel.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/triton_split_scan.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/triton_utils.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/wrapper.cpython-312.pyc,, +torch/_inductor/codegen/__pycache__/wrapper_fxir.cpython-312.pyc,, +torch/_inductor/codegen/aoti_hipify_utils.py,sha256=IgWF_PgdtPWbWIl8qteGwSITrVvQh2tGoru4iRVvKMY,1605 +torch/_inductor/codegen/aoti_runtime/interface.cpp,sha256=dlIk6tW7Yf1Jn5CN7Irbv_K2fo2Arw8Xt-450tEXP3Y,26154 +torch/_inductor/codegen/aoti_runtime/streams.h,sha256=nZv2sunAyi66VQhtKkKt6YIKkQvR_I9fuPnsH4tyIAI,3825 +torch/_inductor/codegen/block_analysis.py,sha256=5srCtZxr66x_vMTfqhHr0-6eEhBIGccUBOO6jGvOzqQ,8300 +torch/_inductor/codegen/common.py,sha256=OyRCYpIbk2_BVs45SirkjgaLgbxiFlblI_gKPZRvRGY,114256 +torch/_inductor/codegen/cpp.py,sha256=iFtzJ56GhhgdNwbG1qWQ0HECxE6nOejBG7W-XvdYKS8,266830 +torch/_inductor/codegen/cpp_bmm_template.py,sha256=4EWGQK4Phx4iDCb9wk66pe9jUJn_V9-R2EG6B-Of3rQ,9728 +torch/_inductor/codegen/cpp_flex_attention_template.py,sha256=_uxwP8TvGjWyQ2BG_HHAAY7MgfI2tR4kJvQW2hjUhfs,58668 +torch/_inductor/codegen/cpp_gemm_template.py,sha256=iISMf0oHhJvau70GynvX7TpLgn4ms9xYMZCb99GjdgA,85608 +torch/_inductor/codegen/cpp_grouped_gemm_template.py,sha256=KV_-Y9dV_m17gKG-_mbLXHm110ogL3dNqksAt9p9QUk,22676 +torch/_inductor/codegen/cpp_micro_gemm.py,sha256=tq8UgOjoaT4e6EVqu7YhupY5t0IvoN2Q9w6oJnhMEko,79719 +torch/_inductor/codegen/cpp_template.py,sha256=wdfeyt0J46kwKReON3H-R2QUJidBvYEsmtZSLaXPBXo,5112 +torch/_inductor/codegen/cpp_template_kernel.py,sha256=sC22alBATkqjuleDI4uVmSvhBB90ZmzZgkywrHzDl-k,28427 +torch/_inductor/codegen/cpp_utils.py,sha256=jpB8SnJfSKVMzows3DgUi1uRXEF6Toz16wVYhtD3Apw,30573 +torch/_inductor/codegen/cpp_wrapper_cpu.py,sha256=0D0wMsnrB465GPcPD0S7gj7GptBIG2d-SmDOSmiyAlo,192075 +torch/_inductor/codegen/cpp_wrapper_cpu_array_ref.py,sha256=VudRrX0YszYnDdbgFdOaqtsd3o5SvpZGUemlJAo3l_A,56364 +torch/_inductor/codegen/cpp_wrapper_gpu.py,sha256=WhHatxhwUfj7wlBM54vBTVqeG-1weS2VKT2eP5ClHm4,79583 +torch/_inductor/codegen/cpp_wrapper_mps.py,sha256=DwhesAWs_0ezZceGcHoWhM06Qk72r0YrXlJfDi-Snt8,12543 +torch/_inductor/codegen/cpu_device_op_overrides.py,sha256=fa-y1cAV234gbE1qiawlGVXsufH8QtjLnJf5zgIxFzU,748 +torch/_inductor/codegen/cuda/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/codegen/cuda/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/codegen/cuda/__pycache__/compile_utils.cpython-312.pyc,, +torch/_inductor/codegen/cuda/__pycache__/cuda_env.cpython-312.pyc,, +torch/_inductor/codegen/cuda/__pycache__/device_op_overrides.cpython-312.pyc,, +torch/_inductor/codegen/cuda/compile_utils.py,sha256=_a1KbeJZsbO4m4P6t2UZJgPFJJOcEzqrxLihluQKtN8,12782 +torch/_inductor/codegen/cuda/cuda_env.py,sha256=BB3H-VM9lTs82v4l2YwQbCb2wAhqdhC91V_R4FBQgI8,1354 +torch/_inductor/codegen/cuda/device_op_overrides.py,sha256=HLava2Le8ZHaXoqhwJB71eCwC4GhLpru81ILRa99wqY,15693 +torch/_inductor/codegen/cuda_combined_scheduling.py,sha256=QNgYfqDY7fMNeAKSNqyOKiKEb2tvKdHUDKwZPb8WILI,12254 +torch/_inductor/codegen/custom_extern_kernel_codegen.py,sha256=IAdanV4i1K76cG6jPes_-dusUGMfeAm6YNntXO_p3WE,3066 +torch/_inductor/codegen/cutedsl/__init__.py,sha256=LCdU39rzLOP3q27650YlpGE3wo5SRH2IPdvEoybU6rg,164 +torch/_inductor/codegen/cutedsl/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/codegen/cutedsl/__pycache__/_cutedsl_utils.cpython-312.pyc,, +torch/_inductor/codegen/cutedsl/__pycache__/_inline_asm.cpython-312.pyc,, +torch/_inductor/codegen/cutedsl/__pycache__/aux_scalars.cpython-312.pyc,, +torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_kernel.cpython-312.pyc,, +torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_op_overrides.cpython-312.pyc,, +torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_scheduling.cpython-312.pyc,, +torch/_inductor/codegen/cutedsl/__pycache__/cutedsl_template.cpython-312.pyc,, +torch/_inductor/codegen/cutedsl/__pycache__/lane_analysis.cpython-312.pyc,, +torch/_inductor/codegen/cutedsl/_cutedsl_utils.py,sha256=AJxN6tVT7kq8-qZRgVLlThHv1z3X005eULHYOk0KLuY,1526 +torch/_inductor/codegen/cutedsl/_inline_asm.py,sha256=4Wo5kkJkWvnh2z1bvkgIj75BlViNujhZBeCBYMXX-LI,9517 +torch/_inductor/codegen/cutedsl/aux_scalars.py,sha256=k5DthwK5rRRuUnZCUzXF1yKkTL_0dD8eE88GpmH9TI4,2093 +torch/_inductor/codegen/cutedsl/cutedsl_kernel.py,sha256=iHIZ_gytlJeBSTOyl9tRLu1t7sfyHzp1cmFO8PIzq80,46913 +torch/_inductor/codegen/cutedsl/cutedsl_op_overrides.py,sha256=ns2PJbGtbEEEzgRp5l8m9JTItdhCDRnBlYJlSzYoD3s,35293 +torch/_inductor/codegen/cutedsl/cutedsl_scheduling.py,sha256=R91zqhR3OOMqsmqWTP-vWhnSboid5q_sF6sQ6FkJWME,9603 +torch/_inductor/codegen/cutedsl/cutedsl_template.py,sha256=r9odIDG4zwt7EeQQcE6oQs18yu8-gx8l0FeYkEe6_g4,10402 +torch/_inductor/codegen/cutedsl/lane_analysis.py,sha256=1y7VBpfcDS8BM1ef3z_bMSQj6n6QDJenJnah8IRPJvE,5335 +torch/_inductor/codegen/cutlass/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/codegen/cutlass/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/__pycache__/cache.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/__pycache__/gemm_template.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/__pycache__/kernel.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/__pycache__/python_evt.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/__pycache__/scheduling.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/__pycache__/serialization.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/__pycache__/template.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/__pycache__/utils.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/cache.py,sha256=i_BlJduDxq0s-OqWES5MSqWOEjA0pcifkmdTbzkRNp4,3720 +torch/_inductor/codegen/cutlass/gemm_template.py,sha256=wBupOWWUBN8HmOT8TNbvOUqN_-uBWR4fXPblbKRk8LE,87785 +torch/_inductor/codegen/cutlass/kernel.py,sha256=3i6l5vGTAzmcahRBlCcPW1JLFmJMrIyi5JxQfv_Ujjo,26551 +torch/_inductor/codegen/cutlass/lib_extensions/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/evt_extensions.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/lib_extensions/__pycache__/gemm_operation_extensions.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__init__.py,sha256=zIVQSgcv5C12tIsovmz3xGgBqoATUltX2c4-VG2e3tU,83 +torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/cuda.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__pycache__/cudart.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cuda.py,sha256=MAbpo0K0ESplc0TsHAeuOE0ty5K1SUrROdDZ8sqVvWs,314 +torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cudart.py,sha256=pkNjquWqOMt8KAnOBkHbIxpgBmdWRZqXZbpQXS7ElK0,305 +torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__init__.py,sha256=AkdGQWifQLxFzB5RR5EcXNCg_AQX446DLfp-64Q7D4I,54 +torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__init__.py,sha256=SiRBwZsGLISQfmWy5-pkpAzRopAkCy9kzx8JOjV4YX8,55 +torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__pycache__/special.cpython-312.pyc,, +torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/special.py,sha256=NcOk2HGGaIsTnV0LPyRYnBXcR3WumPqGw2rKDT4dedk,54 +torch/_inductor/codegen/cutlass/lib_extensions/evt_extensions.py,sha256=Gr9Z-LhsKkkt_HIJo27j-PX2nnl-_UtdrsZ6__0imc0,15485 +torch/_inductor/codegen/cutlass/lib_extensions/gemm_operation_extensions.py,sha256=kEP2FHNp1rXeBXOrXa8ig2YntM6reSYc-dQI1NPcFWQ,18961 +torch/_inductor/codegen/cutlass/python_evt.py,sha256=ZclBf47OAC92w2m-mjSqLb-HbCdzTPUgOhO81wn1FCk,24573 +torch/_inductor/codegen/cutlass/scheduling.py,sha256=GlrYzcllZEi966extHD3yqNnTjF6mqcqR6WUE5Jm_bk,16489 +torch/_inductor/codegen/cutlass/serialization.py,sha256=M2Q0GGA4_BMh-MrlDG7XjRYRx6CIIW7ftyUvoOqT77o,17797 +torch/_inductor/codegen/cutlass/template.py,sha256=tCt8n4akZcxoY2QnIOr696bBUuipgUs0wL8Zi6Rn1nY,14005 +torch/_inductor/codegen/cutlass/utils.py,sha256=92bbIWI1wkOl7E6xniCcVjdhRW91PGP_G5RlftLz7Sg,21046 +torch/_inductor/codegen/debug_utils.py,sha256=8YSAgVZ4sESqUHwVX97Z7NpUyGX7ZU05gcWMW5hsZBE,11376 +torch/_inductor/codegen/halide.py,sha256=yLnFZ1ULV3UAYVN3m0FklfSLqT3lVtbyS125B5ss9Ew,71341 +torch/_inductor/codegen/memory_planning.py,sha256=NvyO1WYKI3ijlJTGVUHh9pE8kUVQtZ9fF-jM1MaWGwU,28606 +torch/_inductor/codegen/metal_flex_attention_template.py,sha256=MZyt5PAE1PaHnOfgCzzBbpvmeJp8pH8BM8RCDKV3yGc,40042 +torch/_inductor/codegen/mps.py,sha256=2XNMerzu8CGnOrW6AoYtg5B7FC-sDwrKO7kCyr-k93Q,49512 +torch/_inductor/codegen/mps_device_op_overrides.py,sha256=baQAqVPlHZ0nYoMEiPSuBcqWDfGYOfhG6KDfPbkFrKA,1155 +torch/_inductor/codegen/mtia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/codegen/mtia/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/codegen/mtia/__pycache__/device_op_overrides.cpython-312.pyc,, +torch/_inductor/codegen/mtia/device_op_overrides.py,sha256=kiheZEMLdv_kwcI0oUVgf-OvZHvUMhyjYbc_muSTfiY,743 +torch/_inductor/codegen/multi_kernel.py,sha256=uP37EyUsS0NqOxTY4VveSinzcho5WM_g9bHOIfiUcH4,25469 +torch/_inductor/codegen/nv_universal_gemm/__init__.py,sha256=bI2vLJOB4OLJZYISLafB0DETtGvpG0FQmer2uXE8fHE,490 +torch/_inductor/codegen/nv_universal_gemm/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/codegen/nv_universal_gemm/__pycache__/kernel_cache.cpython-312.pyc,, +torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm.cpython-312.pyc,, +torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_kernel.cpython-312.pyc,, +torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_scheduling.cpython-312.pyc,, +torch/_inductor/codegen/nv_universal_gemm/__pycache__/nv_universal_gemm_utils.cpython-312.pyc,, +torch/_inductor/codegen/nv_universal_gemm/kernel_cache.py,sha256=QOR6fRRsjdrv7j6kASguqICwFGm3emRGzF94ObAb9s8,24949 +torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm.py,sha256=lETQ_47lPDqWpMduRQ1N4-7qLH7ncHvBt9U6QRxk5nc,40023 +torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_kernel.py,sha256=EVTJ9i4aFD7epdrsACjUps6yjcH-pAaDfR06MYrwboU,56499 +torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_scheduling.py,sha256=DvrYuBr4FIXczgUI-L6Wb8HYfGtqsVeVThhVU_y_qKo,45590 +torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_utils.py,sha256=BbaRdnj_xrCrNEmw9L9lWcZsCxZIQBvL_sUjhK5zkS0,4087 +torch/_inductor/codegen/pallas.py,sha256=rPkC3a8GeK_31ZXr216s65OZNF1nvw_Tki1sq2G2vGE,203229 +torch/_inductor/codegen/python_wrapper_mtia.py,sha256=XEIoUYldr_tZ-E1301BGTvgSsari-L2ygLOmouNNCww,988 +torch/_inductor/codegen/rocm/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/codegen/rocm/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/codegen/rocm/__pycache__/ck_conv_template.cpython-312.pyc,, +torch/_inductor/codegen/rocm/__pycache__/ck_template.cpython-312.pyc,, +torch/_inductor/codegen/rocm/__pycache__/ck_tile_template.cpython-312.pyc,, +torch/_inductor/codegen/rocm/__pycache__/ck_tile_universal_gemm_template.cpython-312.pyc,, +torch/_inductor/codegen/rocm/__pycache__/ck_universal_gemm_template.cpython-312.pyc,, +torch/_inductor/codegen/rocm/__pycache__/compile_command.cpython-312.pyc,, +torch/_inductor/codegen/rocm/__pycache__/rocm_benchmark_request.cpython-312.pyc,, +torch/_inductor/codegen/rocm/__pycache__/rocm_cpp_scheduling.cpython-312.pyc,, +torch/_inductor/codegen/rocm/__pycache__/rocm_kernel.cpython-312.pyc,, +torch/_inductor/codegen/rocm/__pycache__/rocm_template.cpython-312.pyc,, +torch/_inductor/codegen/rocm/__pycache__/rocm_template_buffer.cpython-312.pyc,, +torch/_inductor/codegen/rocm/__pycache__/rocm_utils.cpython-312.pyc,, +torch/_inductor/codegen/rocm/ck_conv_template.py,sha256=4SCS9ixBUlJz5E9Gtyaryn4MZLrRCUw7DoZqg8-4azQ,24941 +torch/_inductor/codegen/rocm/ck_template.py,sha256=bMFSlrfjHxv8GfcOycEGQIyFpqZegs45mnSzKCKrdG4,4277 +torch/_inductor/codegen/rocm/ck_tile_template.py,sha256=Qm1oW_WPVexswfI8HwL9lgfYUxEwhd4ehmDKz3AOHik,1591 +torch/_inductor/codegen/rocm/ck_tile_universal_gemm_template.py,sha256=PAm5YiEDXYF2H8MPPWyeDDe9kHF5MLYH9bAAlitg75c,32508 +torch/_inductor/codegen/rocm/ck_universal_gemm_template.py,sha256=bpYcXqQi5OvNVGE-_GJf3p2jS-Q1eLYFL5ccU3mBIbo,39870 +torch/_inductor/codegen/rocm/compile_command.py,sha256=mK5kZTig4Ld8Sj1PMDdIZJhobmGnQwFJJ-dD_1X7okU,4628 +torch/_inductor/codegen/rocm/rocm_benchmark_request.py,sha256=hAl808OEiq6FbWX5u1nM9NBYA_aTzTMfdixa7wuhjTY,5015 +torch/_inductor/codegen/rocm/rocm_cpp_scheduling.py,sha256=6uop86xOTO6HpuXMM2av7tjABvhzASClbgb5INu29vY,4688 +torch/_inductor/codegen/rocm/rocm_kernel.py,sha256=FcJyB31t1i_5Ow2iJpkrxec-67WFmIHO0ECtp7s89Ek,10893 +torch/_inductor/codegen/rocm/rocm_template.py,sha256=bOCjscLALHgYRgFOSsZ9A6EeomaTpZM_sBi4teUmBXs,6718 +torch/_inductor/codegen/rocm/rocm_template_buffer.py,sha256=UMhXlEMC2acFTLJqJwKx1btyB7uuxOe_Ftr364CzNLw,827 +torch/_inductor/codegen/rocm/rocm_utils.py,sha256=_tYJSiuN0xtpJvqM9xycWNsRRC0UzuhGxIMwp0gIHxw,336 +torch/_inductor/codegen/segmented_tree.py,sha256=BOqdDKVQtRK2h0hc6T6zkj6occ6y79Rzvdaf-xmh60k,8177 +torch/_inductor/codegen/simd.py,sha256=5p37dCTVJfvD7BWY0xj092avVTFCgrMuEuoOaUKUZdM,199313 +torch/_inductor/codegen/simd_kernel_features.py,sha256=3PRl-NHubSh044nWhff8PwVsHkf7_ZKlhbbKTE-DzOA,31025 +torch/_inductor/codegen/subgraph.py,sha256=XztjrwBIdElP-eNCV56H7Y0DUCazX33EIT8eBUibv_E,24737 +torch/_inductor/codegen/triton.py,sha256=e5JKiP6UN03A3DO15qWSxSA08RgMham69ww-B9DNCq8,350487 +torch/_inductor/codegen/triton_combo_kernel.py,sha256=DEM1BOKvDT95jPRb0B-b7ntTPPvqc6Farpk6WKuBjEo,83033 +torch/_inductor/codegen/triton_split_scan.py,sha256=fR9UbnRz65ptb-80PtAv-lQjQS7Bo94VeVdzfoKgiMQ,8005 +torch/_inductor/codegen/triton_utils.py,sha256=7AHSPKLna_R3pA2bRRG0U4yeg_xu0fXrdGYqztQAsh8,13695 +torch/_inductor/codegen/wrapper.py,sha256=1S6azHGWFaMnsk_oe4X3DeMSgmhjUf_w3I1_gOXN7-o,215554 +torch/_inductor/codegen/wrapper_fxir.py,sha256=-qTqQrDADS6OfpSr1N6BkCKjd9wVW0emeQF04K8zuIU,55537 +torch/_inductor/codegen/xpu/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/codegen/xpu/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/codegen/xpu/__pycache__/compile_utils.cpython-312.pyc,, +torch/_inductor/codegen/xpu/__pycache__/device_op_overrides.cpython-312.pyc,, +torch/_inductor/codegen/xpu/__pycache__/xpu_combined_scheduling.cpython-312.pyc,, +torch/_inductor/codegen/xpu/__pycache__/xpu_env.cpython-312.pyc,, +torch/_inductor/codegen/xpu/compile_utils.py,sha256=vZyqnsAUaXFDYD2Fl3WvMgDYNuSCYsJEcjc9Q6m9weo,4605 +torch/_inductor/codegen/xpu/device_op_overrides.py,sha256=rL5oTWtmYbhzYzV7BLLxxZ55NR70G48BfUP8fBTy0Qc,2049 +torch/_inductor/codegen/xpu/xpu_combined_scheduling.py,sha256=bB2ArVr6W7Xd9UfDTgk3Hmbfj0rm9VswU93Yc83WZjA,4934 +torch/_inductor/codegen/xpu/xpu_env.py,sha256=_PsKVlhLOP229ZgfJkKrz43NGkRglYetn_czpbG1dvw,902 +torch/_inductor/comm_analysis.py,sha256=PaMKmVZRfpnKse3IHwXmQ4TW2LvdcN0g620PuJjVsmI,30680 +torch/_inductor/comm_lowering.py,sha256=5oRMu4aUvl4s2IQD_QyZBWzq4McI1Oa9MMjPLFYhFZE,32871 +torch/_inductor/comms.py,sha256=PYi9LcNosDAGXzrfVMgy9k5ixpdRR3pVo3zs1ih_ZHo,90359 +torch/_inductor/comms_debug.py,sha256=Y_qM_qrvN4mQhSiAddBPwQCa-KX8EyB1Ho0rDP2mRwk,4214 +torch/_inductor/compile_fx.py,sha256=TltZPgGMa9b2kGJIPVJLZIIKsnI1H78HO37BGKZlmPg,143236 +torch/_inductor/compile_fx_async.py,sha256=3KoiavzQBzzHxlvsLQJAWGTng2x7MXQht_G7IrGB0iY,15411 +torch/_inductor/compile_fx_ext.py,sha256=KPELhCWIqcmIQY0BoM52w7bbtR1zfU3srp2lAK3CxsQ,25042 +torch/_inductor/compile_fx_subproc.py,sha256=lnrJKBMK9BobOevmeNhwRUJ_gvkbE_Vft2ZITLkx9b0,3035 +torch/_inductor/compile_worker/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/compile_worker/__main__.py,sha256=1YJ_If0zivc5W3SBGtj8unc6Gg3K9pfzyujMPWlCwvk,2284 +torch/_inductor/compile_worker/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/compile_worker/__pycache__/__main__.cpython-312.pyc,, +torch/_inductor/compile_worker/__pycache__/subproc_pool.cpython-312.pyc,, +torch/_inductor/compile_worker/__pycache__/timer.cpython-312.pyc,, +torch/_inductor/compile_worker/__pycache__/tracked_process_pool.cpython-312.pyc,, +torch/_inductor/compile_worker/__pycache__/utils.cpython-312.pyc,, +torch/_inductor/compile_worker/__pycache__/watchdog.cpython-312.pyc,, +torch/_inductor/compile_worker/subproc_pool.py,sha256=aVtcHffQrnEEUaqJBMXvEB4Mk94mpZHz6ZW7kVHUwOM,34034 +torch/_inductor/compile_worker/timer.py,sha256=wAUsRHP2zhQFSSADRs6AvAXY3xPFh1xx8e3CT7sikSY,1898 +torch/_inductor/compile_worker/tracked_process_pool.py,sha256=kw1Ur8UzCdTf91lbKnbNe_O4Ua5jQb58UKOINNRdku0,3674 +torch/_inductor/compile_worker/utils.py,sha256=CTa1c1h8VoDte0j4p2pgrTy_Agn8Fp-ElEO6OgIkoAg,2528 +torch/_inductor/compile_worker/watchdog.py,sha256=A0xPQdHK_pKTQn1OV18L1FmHa8DVsHi7stF1Z1Iszlw,5444 +torch/_inductor/compiler_bisector.py,sha256=2HDRccJWFPcfGm1H0MGuX-bh1QnmTbziC5OKaPAoRRY,30631 +torch/_inductor/config.py,sha256=kXHC7SSeE6GaKuItug2xTzxP4RdiEI-HyKToX5aUWwo,132578 +torch/_inductor/config_comms.py,sha256=uGA23Te_d7CHDnxG1VlKnQMVkM3qVVGEgv-huTgxgkU,3052 +torch/_inductor/constant_folding.py,sha256=1tpPJcLGz35B96SXWm8uoqYidQ3ch2kpoCp8JfmuEug,15639 +torch/_inductor/cpp_builder.py,sha256=f5dRURzRKfwpZHn4pEIdwOD6YmpeJwyppB3qVX8Vme0,109057 +torch/_inductor/cpu_vec_isa.py,sha256=k9r7VC7bnXSfZKpR7AjDOGzWhBqH5HpLK-pahO0NhOs,23424 +torch/_inductor/cudagraph_trees.py,sha256=fKubpDODBbEMeS_8c4mJi0ZiOo6HBSkoFYWBsz5BPnY,132705 +torch/_inductor/cudagraph_utils.py,sha256=YpHRa3be62a489TpdOTfDHTHSX5rxUQyRpbD1NSRSyk,23207 +torch/_inductor/custom_graph_pass.py,sha256=8P1QNmZt5Ue26q_OwnTc87F6XYdIIhj_QiUBLzx1T1s,8269 +torch/_inductor/debug.py,sha256=4TssO7GzBo13uGkN7pmSxL0_p30zwTJLV3EB3SiY_34,58197 +torch/_inductor/decomposition.py,sha256=0KZDVrluocn6Iyojt7wnIMSweJW6aXfAKX3wBBXc2fY,51170 +torch/_inductor/dependencies.py,sha256=Y7Km7_eBvtHAPW3eNmpgEayR0i-0NNaZwfQUmy_yUQg,33012 +torch/_inductor/distributed_autotune.py,sha256=fA_8ISxyv3Ea4vdMBedng0fegY2TmKN5fNeoZU8tY2c,13874 +torch/_inductor/dtype_propagation.py,sha256=hQxFEB_PG1mBTnIEVHtQnsAjdinptGOf3Y8gbTZmJHc,15116 +torch/_inductor/exc.py,sha256=SC9nsaRPsXoSD3KChd2mShQISJQlteHfoH4FrywyPBs,5233 +torch/_inductor/extern_node_serializer.py,sha256=Qi0T-ZcAHVmHS7H6bHqN1Oj_TaAPmiC3VbYMjSOVSEk,950 +torch/_inductor/freezing.py,sha256=MH72r9rcAC5959wEpiplw_K3X2qgvVkiqkG09lpvfZM,11575 +torch/_inductor/freezing_utils.py,sha256=0kQfN4H2yEI_eNXINqa0ws5Q-mm9EVT6ARcAKrz3P80,1268 +torch/_inductor/fuzzer.py,sha256=DQk7JZkoCUUpySRN4AO9DaDuX8m6uaWzqpTDdkGJNqg,37441 +torch/_inductor/fx_passes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/fx_passes/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/apply_gumbel_max_trick.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/b2b_gemm.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/binary_folding.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/bucketing.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/control_dependencies.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/ddp_fusion.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/decomp_comms.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/decompose_mem_bound_mm.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/dedupe_symint_uses.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/efficient_conv_bn_eval.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/freezing_patterns.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/fsdp.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/fuse_attention.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/fusion_regions.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/graph_view.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/group_batch_fusion.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/joint_graph.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/low_contention_collectives.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/memory_estimator.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/micro_pipeline_tp.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/misc_patterns.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/mkldnn_fusion.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/node_runtime_estimation.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/numeric_utils.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/overlap_manual_scheduling.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/overlap_preserving_bucketer.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/overlap_scheduling.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/pad_mm.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/post_grad.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/pre_grad.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/profile_guided_estimation.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/quantization.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/reduced_atomic_contention.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/reinplace.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/replace_random.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/split_cat.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/spmd_check.cpython-312.pyc,, +torch/_inductor/fx_passes/__pycache__/utils.cpython-312.pyc,, +torch/_inductor/fx_passes/apply_gumbel_max_trick.py,sha256=DsbKM0ZVUOcTyk1T740CUYSBFtNVCkZMhbLPlY1hzSw,1847 +torch/_inductor/fx_passes/auto_chunker/__init__.py,sha256=pqRDYIVNxTGFK5R54Iw0beoE31PoYA2A8fP4937t87w,2708 +torch/_inductor/fx_passes/auto_chunker/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/fx_passes/auto_chunker/__pycache__/applier.cpython-312.pyc,, +torch/_inductor/fx_passes/auto_chunker/__pycache__/common.cpython-312.pyc,, +torch/_inductor/fx_passes/auto_chunker/__pycache__/core.cpython-312.pyc,, +torch/_inductor/fx_passes/auto_chunker/__pycache__/propagate_scale_by.cpython-312.pyc,, +torch/_inductor/fx_passes/auto_chunker/__pycache__/propagator.cpython-312.pyc,, +torch/_inductor/fx_passes/auto_chunker/__pycache__/utils.cpython-312.pyc,, +torch/_inductor/fx_passes/auto_chunker/applier.py,sha256=GhljLQlE8EdEDONXzLbqok3VbQ5gf5eRYS1ebAIE7uM,18452 +torch/_inductor/fx_passes/auto_chunker/common.py,sha256=Ag3iw9050rHSB9ncK78b6ktjp6WwE46ZRbL8rRPmrUI,2277 +torch/_inductor/fx_passes/auto_chunker/core.py,sha256=bNzB1oxH0H-jxtr4sMpftEnm_lScvlrUFmtlnY-8J3o,6715 +torch/_inductor/fx_passes/auto_chunker/propagate_scale_by.py,sha256=zSUPBVGYrMFQTQmVRL-WCKGSdgh0Y7iSXuUg5_2EGo8,9207 +torch/_inductor/fx_passes/auto_chunker/propagator.py,sha256=21SuhnJwDnVivxRpSDfespec2o2jyVcnSbA8AirgxvA,35529 +torch/_inductor/fx_passes/auto_chunker/utils.py,sha256=3P5RkYJSr2Twe3rv2BpCu_M7Di4oDe_7bTOsU6HYoQA,5331 +torch/_inductor/fx_passes/b2b_gemm.py,sha256=5F8hc97gsVwcdpjELlG5NTZ48lIcPJd--OupLCMMCrI,26729 +torch/_inductor/fx_passes/binary_folding.py,sha256=FCvjn3iMobK-s6CqJXUTJIUAeAN2RwdtU-9neMHK-bQ,20649 +torch/_inductor/fx_passes/bucketing.py,sha256=xj9Kg_MyKJSNZO7qH7FHWD2OOsthhP0RTgLz7Is_BH4,58787 +torch/_inductor/fx_passes/control_dependencies.py,sha256=XpRxJUT5FbcATg6-iIJVm5lasInT7O8bapFU1dMxgqs,11227 +torch/_inductor/fx_passes/ddp_fusion.py,sha256=hvDoiA8uS94C8-DgPF2qVmEppflFWXr55xML_z74e2k,21675 +torch/_inductor/fx_passes/decomp_comms.py,sha256=r5D2crPyTks6O40fJ4kaloUxNaI0flymUbIFpFQii_0,21713 +torch/_inductor/fx_passes/decompose_mem_bound_mm.py,sha256=0THzgsrRPfs3JAmDFeHGeIQ5zKZL8diQ1RBPc-ent7E,11217 +torch/_inductor/fx_passes/dedupe_symint_uses.py,sha256=Bfuj7IhzY3DuixClyuziJM_jJ_w_zdfxsi7ULJcIxjk,2505 +torch/_inductor/fx_passes/efficient_conv_bn_eval.py,sha256=BezRvoAT9wiOgPwdGsX4pCwUwgbeoHw_KCg0s6FBj9Y,15878 +torch/_inductor/fx_passes/freezing_patterns.py,sha256=OsRRUNr2XbXUet2EazlsjEVTVBgNheMDYCs22dJUXos,9850 +torch/_inductor/fx_passes/fsdp.py,sha256=K-x1hMD9ic0BuUvnZgPDS_LRH3i4ueogPQ06ofye-LY,20616 +torch/_inductor/fx_passes/fuse_attention.py,sha256=RhXZadpkhL61Wkqc64BasLkQJVbORA2PgtQFUfj2b6w,49246 +torch/_inductor/fx_passes/fusion_regions.py,sha256=saUPk5TDQEhVff-pcGlyTUba3REeY5GfPbsTN-XsjJ4,7181 +torch/_inductor/fx_passes/graph_view.py,sha256=48ragODf9N7apGrt7rbLFq5A4vq4BfzHq6aeosxEtMQ,8992 +torch/_inductor/fx_passes/group_batch_fusion.py,sha256=3jLZanyaCH2tQ32VoeG74ZbqWF_z-cVWXkig1jMSh6k,71785 +torch/_inductor/fx_passes/joint_graph.py,sha256=BSd_lH9yzdByCXlh9zAKFenOGdbuelGY4BpPO1mfqcc,45743 +torch/_inductor/fx_passes/low_contention_collectives.py,sha256=-mUFxg2TpIeKifpduhZWyT7M6oGi3zZwmk6vZMjA5a0,11738 +torch/_inductor/fx_passes/memory_estimator.py,sha256=68tT9OScy3ptYuKCYZBeSOjT_-JDYbLu6E1i_rQoobo,17257 +torch/_inductor/fx_passes/micro_pipeline_tp.py,sha256=OL0Qr6-6caztZB_IA_SPZsVQBczihdIeDpKBMxa5ne0,49392 +torch/_inductor/fx_passes/misc_patterns.py,sha256=vhF0e_LlVvZTeX6OlIyuDW6vBjTDoeRGjMSiGza4YMg,11128 +torch/_inductor/fx_passes/mkldnn_fusion.py,sha256=R2xg9snply3i1ADFUX9CLks1iIh3BMvOJX6ttYvQoC0,64783 +torch/_inductor/fx_passes/node_runtime_estimation.py,sha256=ylKT7QPUWe7PxWz_Fe16ZQKJ8g_5sUZUYL-eUUl8yzo,14420 +torch/_inductor/fx_passes/numeric_utils.py,sha256=D2GGcTs-sZT2qoDJ1uXD434yo4EZvexjY01eg1-FH1w,7271 +torch/_inductor/fx_passes/overlap_manual_scheduling.py,sha256=nVtifioZHI4TVPZf6qQ_DhlX678_nEu8w_9oFDrH4XM,26540 +torch/_inductor/fx_passes/overlap_preserving_bucketer.py,sha256=0jQUwVLDd0kfDkE-_cdspMsYZtlgfJ70jw2NlXwIzL0,42460 +torch/_inductor/fx_passes/overlap_scheduling.py,sha256=jOaOPi--cWwS2mdlWmrsfU0H63xFgrObVFn5Z5x0xjc,80053 +torch/_inductor/fx_passes/pad_mm.py,sha256=n6CT8pdSIC9O1CFwQaMIps2th-kME3frm827Y2-5V-Q,33497 +torch/_inductor/fx_passes/post_grad.py,sha256=B5Nhb259NhKkqTVBKzgFcbR_X7fRUELIzbz8C4gnFDE,91542 +torch/_inductor/fx_passes/pre_grad.py,sha256=9IfD8zWbfdVe_-emKCPxbxeoaJ71OQmaCUYr1Q2onHU,35656 +torch/_inductor/fx_passes/profile_guided_estimation.py,sha256=tdtxgqgAEKBLjq8gdDwfyxf8WBL2Y-GY0r0f5_CLiMA,30909 +torch/_inductor/fx_passes/quantization.py,sha256=Nd6Yt4OnLS8mVfOQ0k3kNoRvAjkxurzhu7D6mFL9Djs,56650 +torch/_inductor/fx_passes/reduced_atomic_contention.py,sha256=dpusRBVs-yQkOxjMMZpTPoJsraBiCYuDeS3xEEiu69s,23963 +torch/_inductor/fx_passes/reinplace.py,sha256=xF4_0fkUflijhOIMYctvkdpSHaRoNWPmIVqfnNtFKEc,43840 +torch/_inductor/fx_passes/replace_random.py,sha256=Ucy5IkuBideFAzXMnahzi6musQ_2V_SfQo008w5Uy_4,8519 +torch/_inductor/fx_passes/serialized_patterns/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/fx_passes/serialized_patterns/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_1.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_10.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_11.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_12.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_13.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_14.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_15.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_16.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_17.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_18.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_19.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_2.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_20.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_21.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_22.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_23.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_24.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_25.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_26.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_27.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_28.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_29.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_3.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_30.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_4.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_5.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_6.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_7.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_8.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/_sfdp_pattern_9.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/addmm_pattern.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/bmm_pattern.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/__pycache__/mm_pattern.cpython-312.pyc,, +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_1.py,sha256=AoNNr6k8tirIfp301x2w8-oISpZXYFKJ-bQ4wpTE6ZA,11154 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_10.py,sha256=-cwZift7XUhwmMEtnAtdfGp6sc74QN2KjPevQOAdPvo,14543 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_11.py,sha256=u5uQRjXJCB7BXR5E6QgNxd4L3faenYXX6fcwaZuApPg,13964 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_12.py,sha256=hmzbR5NOdbdwul473BhKBYN2fhEd-Ykypv3ucAyTCT8,15234 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_13.py,sha256=F3dhppy8Tqcwx-vebm-4MIldZjbKQ3Z_8u4Te0fx9bg,2181 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_14.py,sha256=c8AZacmDBObImIGF9CGKPsW3N0HoDPEG6BGskpJVNP0,14300 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_15.py,sha256=EAueW3PXgPT6M82zEC89-0mYKiO1YT2Rui752CzWJMU,5900 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_16.py,sha256=O71wOtxC_7GJwv1oqJ_Gc1BBVIqvf9kuuZ5Jc0NvllY,43573 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_17.py,sha256=hbQN3kGA2-rEMENBWZ87DtR93O0qbR9RkSjT1duXRCE,5900 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_18.py,sha256=XT7c7xqDv3VCb-nWPEwC3sxUOq_vN4c6RjASKASwd7Y,10603 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_19.py,sha256=p80eEGbLhWxW1tzIPMOXYRMNkq6o6IhNMmy_LP9FaXo,4579 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_2.py,sha256=5eJ1a_MNV3Bm8KyWi8ezI_mLPgZpZLp7E4dBFBS6E1o,11164 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_20.py,sha256=xnq3c-rzSNi6B1pSyQW0bxMRAhPneASS8ombmX6Snsg,5900 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_21.py,sha256=Gn2jntb_YonIcDnc4p7k_cCkZu139eXL3zZ1PenJAJ4,9081 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_22.py,sha256=YV6T74jrISraFhD_76ywGKvgqVroMJnh07pS3Yomq0A,9509 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_23.py,sha256=QANz69WWaGE2h1nrA05gXqJWLFStvXAYE1ehRFg2Sf4,9447 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_24.py,sha256=9pLcizg8CHm5wQmyqxX-Hnn0CLAdWEpqrzaVBG5Jp0M,3115 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_25.py,sha256=oTqx3ghcCk1GCmh9ZklANj5fFrDrCFOVs3axLpvRbYU,27795 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_26.py,sha256=IYJsuQShH1m4HjIdW4zzkbCqZV4tk9lCksXkV6oiGEI,28471 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_27.py,sha256=kx0yedYONWaFsmsUowdgt7_W6YXWEtLy2xNBrI_eZlE,27815 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_28.py,sha256=pce9T0dg2FthW0Sz3gT0gcs3hPnmY0Wjq7v4fjpYuVM,13660 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_29.py,sha256=byqup7nCItaZ5S3NFLtdxTDIrBZyFP_G9RB-fse-pHQ,31857 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_3.py,sha256=rpaix0EQ0_a_zQpplVElFtbSYaV1-nMKyFO1Xnn8SjA,12424 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_30.py,sha256=NYpEzCmFaE1YwTbLPgvDQDCkXKnNI6F6XtklVwclYBk,31233 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_4.py,sha256=JZeg6UsoPPI0Mx6NJZvF1HvTottQ3HTALHDULHzAVUE,12388 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_5.py,sha256=QcE0bfcitRVVYFoEm05RsZ4IaVdI0KD10U-sM9Hy4LY,11490 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_6.py,sha256=P7Vl5cw1Trszja6DuckynSwkWgu-WK6XVqkGZgi-xfI,12718 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_7.py,sha256=s3Y32Aine6yhDYi60NZ68lJuNYHu7tduQhHcsQl5Dgg,15763 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_8.py,sha256=DFXY5dzQrtwhsp_r1FEPIfCgDFP1tapGkcKGsYX8rRY,14531 +torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_9.py,sha256=2ZqV888FVM0uw8JnWhWFwiK7JE7CatyFr3WDZSKVEm8,15771 +torch/_inductor/fx_passes/serialized_patterns/addmm_pattern.py,sha256=imF0MDhigt_xYbzeh8Ursun7qXEjYu9xeLKtNc7NekY,1835 +torch/_inductor/fx_passes/serialized_patterns/bmm_pattern.py,sha256=q9owbfgx-6tHvEqf33U0fovn2jHxa2W5IgSNd22p5Ok,1249 +torch/_inductor/fx_passes/serialized_patterns/mm_pattern.py,sha256=jgCxFnu-sEb7uhrgCA4OauYm8G-CMOI6fI-o2e8rxi8,1237 +torch/_inductor/fx_passes/split_cat.py,sha256=vhGKgcH1hErdyesU-q2oebmOsiPg2h2jsps8BRwNgPk,122695 +torch/_inductor/fx_passes/spmd_check.py,sha256=Z5nBoH8K6lohP4k9L8RUOdhAWCTHnxQ-e9HVY4EKyfc,7507 +torch/_inductor/fx_passes/utils.py,sha256=i_fsjWzLg1gzmktqGxiR1URHPg9iL9ov8oFHnbxFKYQ,4527 +torch/_inductor/fx_utils.py,sha256=ZbQF9el1mOycMIKiopkjCJK4HKAM_fh5M-C98bTSO6Y,38150 +torch/_inductor/graph.py,sha256=38OtmDGWR-5T8u0YpxIyYJD8CziDnVfJpIrMSNEpBH8,138264 +torch/_inductor/heuristics/__init__.py,sha256=Xm_7zylxvDXOWd-q8JYUK0xg7lnhbhdkqqKTQxQAS0A,364 +torch/_inductor/heuristics/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/heuristics/__pycache__/registry.cpython-312.pyc,, +torch/_inductor/heuristics/registry.py,sha256=zuMBot07B1cBeFoBhTqLiOi6zheTTgJt7mZ3kMcy-5k,8852 +torch/_inductor/heuristics/template/__init__.py,sha256=7xtlQXahvaaUN7xVVES_gqID__uFEPuUb9qiqpTnsXE,618 +torch/_inductor/heuristics/template/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/heuristics/template/__pycache__/aten.cpython-312.pyc,, +torch/_inductor/heuristics/template/__pycache__/base.cpython-312.pyc,, +torch/_inductor/heuristics/template/__pycache__/contiguous_mm.cpython-312.pyc,, +torch/_inductor/heuristics/template/__pycache__/cutedsl.cpython-312.pyc,, +torch/_inductor/heuristics/template/__pycache__/decompose_k.cpython-312.pyc,, +torch/_inductor/heuristics/template/__pycache__/flex_gemm.cpython-312.pyc,, +torch/_inductor/heuristics/template/__pycache__/gemm.cpython-312.pyc,, +torch/_inductor/heuristics/template/__pycache__/nv_universal_gemm.cpython-312.pyc,, +torch/_inductor/heuristics/template/__pycache__/params.cpython-312.pyc,, +torch/_inductor/heuristics/template/__pycache__/registry.cpython-312.pyc,, +torch/_inductor/heuristics/template/__pycache__/tlx.cpython-312.pyc,, +torch/_inductor/heuristics/template/__pycache__/triton.cpython-312.pyc,, +torch/_inductor/heuristics/template/__pycache__/triton_addmm.cpython-312.pyc,, +torch/_inductor/heuristics/template/aten.py,sha256=AJ3Kzcv1rkylCcizs_emRP0QnbD1dvVUVipWDIJiCG0,3286 +torch/_inductor/heuristics/template/base.py,sha256=rumnaFL9FMI9O4geUB0oxeJlBh6ju01Pga8QC-knV9c,2498 +torch/_inductor/heuristics/template/contiguous_mm.py,sha256=lRzCBWBAAAv6uspaGaaY6ugbzN3DTqdkAiZMxE5nQbA,2272 +torch/_inductor/heuristics/template/cutedsl.py,sha256=UrZMkfV8QE6sJH1wpIGKBVY8giWr4_7QXrk-z78oNfc,4480 +torch/_inductor/heuristics/template/decompose_k.py,sha256=i2NsqT9OOmtJPOitYZAM_9EsvZeL5LjKwokYC5SLahs,2422 +torch/_inductor/heuristics/template/flex_gemm.py,sha256=IHlp2dwE7MUpAwv7Odc3E-ZFtugefY1Y95Cx3YJdZow,8270 +torch/_inductor/heuristics/template/gemm.py,sha256=blJipyvRfSPnHRqXlXVkjl8x8LwK4YNMrJeBYraInpg,542 +torch/_inductor/heuristics/template/nv_universal_gemm.py,sha256=pZRKjDaRtxABNfGuON6M49_89ccEsd8N306nq5pCcvI,16416 +torch/_inductor/heuristics/template/params.py,sha256=shqTLFkq9Od8WGcRyXI-PSM7hwSmbKEgeArhsQWOSNk,1257 +torch/_inductor/heuristics/template/registry.py,sha256=VaxKVmenpDlrH72gVF2g4S4-3l28Zv4PBB9oImfZA10,647 +torch/_inductor/heuristics/template/tlx.py,sha256=R933ue99UeckJ5URuqLjwP0aytjWrclQlPEtPnCp9tE,492 +torch/_inductor/heuristics/template/triton.py,sha256=g-IWekhfjVObA-gi68LBqVMdjEl0KQQuVk8718dblAg,139224 +torch/_inductor/heuristics/template/triton_addmm.py,sha256=vG-ZmMfoj_-Jkejep0AOjF9RfYxIVjZV02-KJOM8Pm0,1086 +torch/_inductor/heuristics/triton_codegen/__init__.py,sha256=X-ggJMoPPLTwTeEn7EE9Q-AqDfCBdePo0RI923McebE,703 +torch/_inductor/heuristics/triton_codegen/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/heuristics/triton_codegen/__pycache__/pointwise.cpython-312.pyc,, +torch/_inductor/heuristics/triton_codegen/__pycache__/reduction.cpython-312.pyc,, +torch/_inductor/heuristics/triton_codegen/pointwise.py,sha256=E8Hl8hnfQk6omZq5BNuFhkzGmBBUdApPVBS0LsOQcsw,9100 +torch/_inductor/heuristics/triton_codegen/reduction.py,sha256=3Zat4fZE8pjVG7Bx5ARpZOhzCePypYVJJ163tiVesOg,26534 +torch/_inductor/hooks.py,sha256=kUoOn0_wibHB8Cn9iSU427vUlTypKYh2J9DhwkKosEQ,666 +torch/_inductor/index_propagation.py,sha256=FhBOecWhp-iqDYD3P7BMKtfpwSBynJfgPga7d2J0-BE,13783 +torch/_inductor/inductor_prims.py,sha256=FC8Sfl7ckWjLzVgDPk4mpfrrDUpuA-MtBQck7kPNqB0,13361 +torch/_inductor/invert_expr_analysis.py,sha256=qT97FY8b1OLj6rhsALOJvREc2Qi_pGva_LqzLt3NfUY,9114 +torch/_inductor/ir.py,sha256=TUEcE1OwQr7pPEXgJDUrVlYowjO3ht9UfG6aZ2yxwro,450425 +torch/_inductor/jagged_lowerings.py,sha256=JtD7PHWQ_7IK25mRiH4NAr6TshXUUmPaesddnGHoMhI,9014 +torch/_inductor/kernel/__init__.py,sha256=eNsGc7bkDyOjdr9m-1dc3kgoJCfwt6IkzGgyN56F0-8,100 +torch/_inductor/kernel/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/kernel/__pycache__/bmm.cpython-312.pyc,, +torch/_inductor/kernel/__pycache__/conv.cpython-312.pyc,, +torch/_inductor/kernel/__pycache__/custom_op.cpython-312.pyc,, +torch/_inductor/kernel/__pycache__/gemm_epilogue.cpython-312.pyc,, +torch/_inductor/kernel/__pycache__/gemm_epilogue_analysis.cpython-312.pyc,, +torch/_inductor/kernel/__pycache__/gemm_epilogue_codegen.cpython-312.pyc,, +torch/_inductor/kernel/__pycache__/gemm_epilogue_utils.cpython-312.pyc,, +torch/_inductor/kernel/__pycache__/loop_ir_cutedsl_codegen.cpython-312.pyc,, +torch/_inductor/kernel/__pycache__/loop_ir_epilogue_lowering.cpython-312.pyc,, +torch/_inductor/kernel/__pycache__/mm.cpython-312.pyc,, +torch/_inductor/kernel/__pycache__/mm_common.cpython-312.pyc,, +torch/_inductor/kernel/__pycache__/mm_grouped.cpython-312.pyc,, +torch/_inductor/kernel/__pycache__/mm_plus_mm.cpython-312.pyc,, +torch/_inductor/kernel/bmm.py,sha256=H-uOulDt29HWhI_ymUXlfm2NQTrFkm2uE8gztFRIgbo,11871 +torch/_inductor/kernel/conv.py,sha256=vAioy5FR3NV1971a_S_E1AOj7WbKl7IpA6x7DPkOJl0,42165 +torch/_inductor/kernel/custom_op.py,sha256=XfQSSnqInV1DMrotMq7Ja3cOHdGqpKtsPe3ecZQ_2yU,50293 +torch/_inductor/kernel/flex/__init__.py,sha256=_ca2fmTtYz5clo4uzQy2tbaLmypoau8LwEBJe8o5Kd0,153 +torch/_inductor/kernel/flex/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/kernel/flex/__pycache__/aux_vectorization.cpython-312.pyc,, +torch/_inductor/kernel/flex/__pycache__/common.cpython-312.pyc,, +torch/_inductor/kernel/flex/__pycache__/flex_attention.cpython-312.pyc,, +torch/_inductor/kernel/flex/__pycache__/flex_cpu.cpython-312.pyc,, +torch/_inductor/kernel/flex/__pycache__/flex_decoding.cpython-312.pyc,, +torch/_inductor/kernel/flex/__pycache__/flex_flash_attention.cpython-312.pyc,, +torch/_inductor/kernel/flex/__pycache__/flex_mps.cpython-312.pyc,, +torch/_inductor/kernel/flex/__pycache__/interval_mask_packing.cpython-312.pyc,, +torch/_inductor/kernel/flex/aux_vectorization.py,sha256=WCr4Nkce7mhmQN_Uns3kXX_0gBTp7LjTD0Nl3OthOuo,15226 +torch/_inductor/kernel/flex/common.py,sha256=0g32GAl4lU95pXbyCzKgIVWDGPDFPSx8O7gWTt-hkY0,17627 +torch/_inductor/kernel/flex/flex_attention.py,sha256=WEU6JjVb262VMiNehFX5tsIigoA9YoRm7Aa2g30Fn7k,44733 +torch/_inductor/kernel/flex/flex_cpu.py,sha256=qH09vZUu80G8XxzYLbjoRqSX0nr6eSgLSXccSZc1gxo,13162 +torch/_inductor/kernel/flex/flex_decoding.py,sha256=uIsLbl2xca9kiHx8hZWALcBH92SpufdCuRGdgY6rNA8,18293 +torch/_inductor/kernel/flex/flex_flash_attention.py,sha256=HuvSS3-iTyDuMDU-iy820Eb0UqU9u_xOJJMPsCGemW8,34259 +torch/_inductor/kernel/flex/flex_mps.py,sha256=Pl_etP3Wq4OkeW8vHZAQfZ3m_6FxNdgYhRBPu98Qi28,9570 +torch/_inductor/kernel/flex/interval_mask_packing.py,sha256=6xiNoy7M_HC3-3w7PvrUVTEej0TxJsBkp5-WKBfn0oo,30206 +torch/_inductor/kernel/flex/templates/common.py.jinja,sha256=eio_o6SuYYMC7Vf8eEMR02CXdPT6tkBsKSrtR3JRcMo,7717 +torch/_inductor/kernel/flex/templates/flash_attention.py.jinja,sha256=g5tXUWnte9YVJIv8LaEXGjDdLvYCn9lDYF9XcTpkadY,5413 +torch/_inductor/kernel/flex/templates/flash_attention_backward.py.jinja,sha256=WRxR_WqMXpeHmKg_4SpZsdbx7hPN-BqSDs7hFq9myCA,6158 +torch/_inductor/kernel/flex/templates/flex_attention.py.jinja,sha256=UJQ3tOBR49WgFn8JZ8PS4pKXitD6w3aF5HN4szkfmso,9320 +torch/_inductor/kernel/flex/templates/flex_backwards.py.jinja,sha256=OmU3_EtRlwbRvhB4TR4rMbv4zv2rBbqq4kvPkHQ77GQ,33021 +torch/_inductor/kernel/flex/templates/flex_decode.py.jinja,sha256=hQsYE1XMCMlFZBN0v-SPdyezBIZAiBVNHOlEzj5amYw,10750 +torch/_inductor/kernel/flex/templates/utilities.py.jinja,sha256=ABqDICZqCMdZI0_W4FUcBcWQ04-wp-ZmrmSA7GE-i5M,2321 +torch/_inductor/kernel/flex_gemm/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/kernel/flex_gemm/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/kernel/flex_gemm/__pycache__/constraints.cpython-312.pyc,, +torch/_inductor/kernel/flex_gemm/__pycache__/debug.cpython-312.pyc,, +torch/_inductor/kernel/flex_gemm/__pycache__/fx_cutedsl_codegen.cpython-312.pyc,, +torch/_inductor/kernel/flex_gemm/__pycache__/lowering.cpython-312.pyc,, +torch/_inductor/kernel/flex_gemm/__pycache__/quack_reductions.cpython-312.pyc,, +torch/_inductor/kernel/flex_gemm/__pycache__/runtime.cpython-312.pyc,, +torch/_inductor/kernel/flex_gemm/__pycache__/template.cpython-312.pyc,, +torch/_inductor/kernel/flex_gemm/constraints.py,sha256=X2psaXheJSXW4PyAlDSRz_uyHYAFqP9pcZdsloCuxi0,20856 +torch/_inductor/kernel/flex_gemm/debug.py,sha256=laaAcOUiT01vQFiqlYeA-LcMzZ5hM48BcwKF0C97Xr8,12147 +torch/_inductor/kernel/flex_gemm/fx_cutedsl_codegen.py,sha256=C3_Y4EDVivg7kcgtUxBLJ3bQNgrBx-7sRZqqrjQSsK4,42655 +torch/_inductor/kernel/flex_gemm/lowering.py,sha256=P95dgRTeqHodRrU_HvdxIljTXMImr7m8F9wk0mE5tRY,27217 +torch/_inductor/kernel/flex_gemm/quack_reductions.py,sha256=WOcK7kJGbOE8RJV03jgaIywVUSblAil1b2JQjFXtJZA,17504 +torch/_inductor/kernel/flex_gemm/runtime.py,sha256=8X9HHyLoOXw-y4SlFntoa9fSMiJ8XyNXKo8GwVARRE8,26885 +torch/_inductor/kernel/flex_gemm/template.py,sha256=xYRVrce9N6LP4_zWoPZhOPb5f7xZQILNke7t_WVs9tM,15087 +torch/_inductor/kernel/gemm_epilogue.py,sha256=dRwQecM5rZLaXcGC3ovhazKBfpqWFKZrYNNJw20kp9c,17010 +torch/_inductor/kernel/gemm_epilogue_analysis.py,sha256=YQzKVRZoTXL9B-mb48Ts7EV6vfZFp5-D6l0mo4n6LK8,30631 +torch/_inductor/kernel/gemm_epilogue_codegen.py,sha256=fgT9lRhVk_Xskhqtrww5lQfjGhk7O6qJJutl-EK22w0,4518 +torch/_inductor/kernel/gemm_epilogue_utils.py,sha256=AlC_BgravClMRcnhZrQYQnFw7l7OQ1ZTbixyIlPKbVo,1899 +torch/_inductor/kernel/loop_ir_cutedsl_codegen.py,sha256=RQVVxYXm3almb6XKuksGmOkpBk7yCsxJ_1mhqsls2ZI,4584 +torch/_inductor/kernel/loop_ir_epilogue_lowering.py,sha256=VfibIZdLtQEMQIxDhbRqUzPUpiy-b1yvgjzOjMxtlLo,36903 +torch/_inductor/kernel/mm.py,sha256=6VoBp7Kl6cwkAjy2u9uGTlalQZfWZDT_X3aVrRg4xY0,49470 +torch/_inductor/kernel/mm_common.py,sha256=0XRjmw6RkbwZecu3q96Y6_bK8cjV7_4wz0M6iB2ocjE,9149 +torch/_inductor/kernel/mm_grouped.py,sha256=6oDpM1lHDHlluLT09dRkyyBNW-z6lW0QfIF5FStb604,17660 +torch/_inductor/kernel/mm_plus_mm.py,sha256=rbf1k69BsaZrSVVaHM--GeIQdCFGrdkIoJTLsfrI0PQ,5966 +torch/_inductor/kernel/templates/cutedsl_mm_grouped.py.jinja,sha256=Rh7cPGbYUvaVfgLFBoinqLkQogmywspBFnH8q7GBS_Y,17862 +torch/_inductor/kernel/templates/triton_blackwell_ws_persistent_device_tma_mm.py.jinja,sha256=Gs_KWp1Jst4renR2SQp4nIAeY0P5rl2zxZTbJrtIFZw,5460 +torch/_inductor/kernel/templates/triton_bmm.py.jinja,sha256=Ss1wGE9ObX3YccAKW5Raak06zWQa1vfxo-tpAqtM-Fw,2868 +torch/_inductor/kernel/templates/triton_conv2d_bwd_input.py.jinja,sha256=cZaNserjCvTtn0wrhgWYz3PsNUnjMY8pKc0AnsBecW4,3386 +torch/_inductor/kernel/templates/triton_conv2d_bwd_weight.py.jinja,sha256=fBJo0KiqvZ2wH8ooEgXNwV-lfimNfu6yOYwGdJix36s,3254 +torch/_inductor/kernel/templates/triton_depthwise_conv.py.jinja,sha256=vniupjpzjkQIr4xuJ8z9IX3Zy_696GYnJ7UHFF1eqM8,2118 +torch/_inductor/kernel/templates/triton_epilogue_scaled_mm.py.jinja,sha256=Ia6sY7G98qTPTLvst1-vlq8X61FotuHjs9MwK3AolaU,6370 +torch/_inductor/kernel/templates/triton_main_loop_scaled_mm.py.jinja,sha256=gK43gOVrS7TS4GmyUfmggvCs6Ypn_GGi1aHLsPq3euA,6035 +torch/_inductor/kernel/templates/triton_mm.py.jinja,sha256=2ZhC5GaAPi0dzRm4-qmSrNJtyctnG466dGjBh_O5AH8,2878 +torch/_inductor/kernel/templates/triton_mm_grouped.py.jinja,sha256=Y4maui6ZW2ZTq_LdpCyCx6ve-_E68fXi-fTlG2HDqXw,12552 +torch/_inductor/kernel/templates/triton_mm_rocm.py.jinja,sha256=jZCVMvz_VGV_RjGyqDnzBRDaSDOlO7VAfQf7y5jVlzc,2815 +torch/_inductor/kernel/templates/triton_persistent_mm.py.jinja,sha256=wpK3T5UTwo7L1bC9u-1_UNDeIjmz8tU9fKB6BHgO02I,3123 +torch/_inductor/kernel/templates/triton_persistent_tma_mm.py.jinja,sha256=DdrQ3xVsQQBoHaZhVjc4bR6MJAPnDqRmL3R97-wJP_g,4645 +torch/_inductor/kernel/vendored_templates/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/kernel/vendored_templates/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/kernel/vendored_templates/cutedsl/__init__.py,sha256=JL0fKO0h8FafXYiX9rhcnEAHoxhUZhqBR30T7q6GOCI,62 +torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/dense_blockscaled_gemm_persistent.cpython-312.pyc,, +torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/dense_gemm_efc.cpython-312.pyc,, +torch/_inductor/kernel/vendored_templates/cutedsl/__pycache__/reduction_utils.cpython-312.pyc,, +torch/_inductor/kernel/vendored_templates/cutedsl/dense_blockscaled_gemm_persistent.py,sha256=-NzgCJ3DKINqmV5fM7HCeHcUuAw4L9sZu3rDEudjgno,118084 +torch/_inductor/kernel/vendored_templates/cutedsl/dense_gemm_efc.py,sha256=4iFX6S4ZWzYuJtMmbFLtNlFJ8G41MBE1k7FLCgpS3j0,121575 +torch/_inductor/kernel/vendored_templates/cutedsl/kernels/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/kernel/vendored_templates/cutedsl/kernels/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/kernel/vendored_templates/cutedsl/kernels/__pycache__/cutedsl_grouped_gemm.cpython-312.pyc,, +torch/_inductor/kernel/vendored_templates/cutedsl/kernels/cutedsl_grouped_gemm.py,sha256=BbdKBWgsAkVX2DKE4y-XPtW-Tw0aGhLHL-eCTCn36U8,94438 +torch/_inductor/kernel/vendored_templates/cutedsl/reduction_utils.py,sha256=w5czvPg0NcIRcK9tMdQvQ6vR0QhwQcRuE_0r2xSDzwE,1637 +torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/__init__.py,sha256=TerOKBfVRRZyJ09DaTmtb_IdXJS8SdkER0WPrf__160,102 +torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/__pycache__/dense_blockscaled_gemm_kernel.cpython-312.pyc,, +torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_blockscaled_gemm_kernel.py,sha256=vH8JWHXckln_rVRgt4TP_Zi4-YF0haJRaiuaPHO7UP0,26809 +torch/_inductor/kernel_inputs.py,sha256=Wh817eSYo9VH6X393gioN4I8EZXoCm0hil012tnJZi0,11283 +torch/_inductor/kernel_template_choice.py,sha256=541Ihvy5RQOc6KO2-TOUyNVNZLI74rfCG7OV3Nj1U7A,3331 +torch/_inductor/lookup_table/__init__.py,sha256=grqROhCd6DpGiI-5pQ0zDqm9wDL0-7uwQJGQXzqYoKI,877 +torch/_inductor/lookup_table/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/lookup_table/__pycache__/choices.cpython-312.pyc,, +torch/_inductor/lookup_table/choices.py,sha256=ocnhPwN0gWcHpX_NrnwZiIhm8E5vN_E1jA5S6hFVt_I,16195 +torch/_inductor/loop_body.py,sha256=ohd55NS6HOCQvguvyPuLDKCN5V9IpBB5mII4z6xfUyc,31474 +torch/_inductor/lowering.py,sha256=wuqGkumUi4IXXPj8Otn6Z-mLBMm54fulrirHeQLRjgw,331643 +torch/_inductor/memory.py,sha256=2p7mx68yrJJHW_-x0HKBuNVE7d2juuD0urEkA9hYcw4,44627 +torch/_inductor/metrics.py,sha256=08slYJRdTihMJMJyhiGgpMlernCjajGAHJKSohgMPi4,15211 +torch/_inductor/mkldnn_ir.py,sha256=I5HecBv-yjfnEDBZRamtVRy6C_3JH5JYtYlkYvjeKb4,45497 +torch/_inductor/mkldnn_lowerings.py,sha256=B96-C__mzXFZwbPpjUlWf-HmCoPCnJ28P3ir49fq2Tg,61624 +torch/_inductor/mock_cache.py,sha256=X2h5ZkbUa6docxNu_HXfYJqdaZzx6d3ubdnJylGcFm8,8555 +torch/_inductor/ops_handler.py,sha256=86oYJ8qW6cDWjjVU5INVVdYNC_7yEGyVU8s4NvUjZ-4,38222 +torch/_inductor/optimize_indexing.py,sha256=D02xC-t2v9zxywm7KOYmDu6zAqwmc0pCAJKCjkr264o,15336 +torch/_inductor/output_code.py,sha256=ZH_cpeerIUrN-CgIhdQZ78YH86ADNTpGYR5Z7Gs9j-Y,55627 +torch/_inductor/package/__init__.py,sha256=s1BQDRTTu4baQTZPdR07q8CBO_b5kUpXEp5VawAeQQI,67 +torch/_inductor/package/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/package/__pycache__/build_package.cpython-312.pyc,, +torch/_inductor/package/__pycache__/package.cpython-312.pyc,, +torch/_inductor/package/build_package.py,sha256=ZS3248m9MtGnCGG0YWrne2y7FDTIoF2ZWmKdxvIRzMg,329 +torch/_inductor/package/package.py,sha256=9jqLjM2qhr730PbmxyGGjqHeNmjvVXyFD7RUFRb3JII,4571 +torch/_inductor/pattern_matcher.py,sha256=863O8znRGV3OuM7ZQ8E1QAaYJGLZQPUIQvNYcGqRz5s,112254 +torch/_inductor/profiler.py,sha256=ojhKbg5UrOMmXJDx2nYGQKg45bqalGStB8LG7cirrqg,19717 +torch/_inductor/quantized_lowerings.py,sha256=7JlUKaC6uVVqJ_7voF8gcGTqki4EPxlIDaDd9MqQp14,6374 +torch/_inductor/remote_cache.py,sha256=aQaKtoFkuNHuvyjkVkVfZJPJ0u2XKNtLA9a2XjjNEDQ,15413 +torch/_inductor/remote_gemm_autotune_cache.py,sha256=1ixVIU_KN1XNTBGZuJolUfaJWClQJUURc9nghIp-kAk,551 +torch/_inductor/rocm_multiarch_utils.py,sha256=9JvvvTARB7jdMTDngKGyuc8edzKgpEHfo5sumt5dCc4,9049 +torch/_inductor/runtime/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_inductor/runtime/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/autotune_cache.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/benchmarking.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/cache_dir_utils.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/compile_tasks.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/coordinate_descent_tuner.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/cutedsl_cache.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/debug_utils.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/halide_helpers.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/hints.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/proton_utils.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/runtime_utils.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/static_triton_launcher.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/triton_compat.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/triton_helpers.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/triton_heuristics.cpython-312.pyc,, +torch/_inductor/runtime/__pycache__/triton_lazy_compile.cpython-312.pyc,, +torch/_inductor/runtime/autotune_cache.py,sha256=72cQ3hkMmNC20phBs6dwsRjHokcEq6R8E1NztE3JXxc,27339 +torch/_inductor/runtime/benchmarking.py,sha256=HBDRuYn06yBzb5VO8H9WQpsdFlg6NpnCglCCFdsij9E,37078 +torch/_inductor/runtime/cache_dir_utils.py,sha256=4AnLVbFVE8SNhOAtHTtJjM6Q-LM8wABpfbu8dR2S4ks,1713 +torch/_inductor/runtime/caching/__init__.py,sha256=fRIP7WF5M9w6agp6eDMrPyjRWL8p_w_3V0liSPKtpKA,730 +torch/_inductor/runtime/caching/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/runtime/caching/__pycache__/config.cpython-312.pyc,, +torch/_inductor/runtime/caching/__pycache__/context.cpython-312.pyc,, +torch/_inductor/runtime/caching/__pycache__/encoders.cpython-312.pyc,, +torch/_inductor/runtime/caching/__pycache__/exceptions.cpython-312.pyc,, +torch/_inductor/runtime/caching/__pycache__/implementations.cpython-312.pyc,, +torch/_inductor/runtime/caching/__pycache__/interfaces.cpython-312.pyc,, +torch/_inductor/runtime/caching/__pycache__/locks.cpython-312.pyc,, +torch/_inductor/runtime/caching/__pycache__/memoizers.cpython-312.pyc,, +torch/_inductor/runtime/caching/__pycache__/utils.cpython-312.pyc,, +torch/_inductor/runtime/caching/config.py,sha256=1bBNlOGURk_hDv_D8zfaFrHBU9wEx2b4zkZm9y23G4s,5902 +torch/_inductor/runtime/caching/context.py,sha256=Wp5yQx2etfH4YK3YsfGkKldmkD1agnW-sYyKYMnrsb4,10485 +torch/_inductor/runtime/caching/encoders.py,sha256=c3PE8XFfkPTlxhjkf4RukF52JxIU88Q0JTolhf8dX58,2137 +torch/_inductor/runtime/caching/exceptions.py,sha256=lTWLVXJkhktVagqgYwNDHOoRoiwmouNexQi9KSQ7elE,3463 +torch/_inductor/runtime/caching/implementations.py,sha256=s524jk8GNBLXun6FYJsvLY9p7enugEZCK70pjTP4D-c,13753 +torch/_inductor/runtime/caching/interfaces.py,sha256=d827CW6GHDkNtuyy2ThGK__0S8dZP6N2e8tTwn4t3zA,51863 +torch/_inductor/runtime/caching/locks.py,sha256=MyqtTTQ4d-0-wopXK0weXYlPzDxmT1dbypUS-tT4mhQ,7506 +torch/_inductor/runtime/caching/memoizers.py,sha256=pmnwTMuUK8QHG8GUiikvM1PUN5m-Tggjndy_KdgncGg,177 +torch/_inductor/runtime/caching/utils.py,sha256=PZiNE9MVezRbxW2rpmKV8-W6z2dYbftjub0NY7jxPp4,1661 +torch/_inductor/runtime/compile_tasks.py,sha256=4GDuDRnsrftG4zMSSBC29EtSWcp6GhCWyyw5m3D5FP8,8391 +torch/_inductor/runtime/coordinate_descent_tuner.py,sha256=XukRlBiFm9fv1im0kP9-M1UiWf_cPIpXNNO_4SViEd4,17629 +torch/_inductor/runtime/cutedsl_cache.py,sha256=Tb_1I8p1UGenAFTuTnbRc--_aeWOI3ruR-gMMKCKXFg,5385 +torch/_inductor/runtime/debug_utils.py,sha256=rzm7v02Y9RWuyGaHo64CJFyyrJP4HtAHtRvePjytx7A,4589 +torch/_inductor/runtime/halide_helpers.py,sha256=KUZmtLM-DlIPJmXIEhLbCbO0skEvJcp2VmE3lfWDZpk,4972 +torch/_inductor/runtime/hints.py,sha256=i4-r-lEA3g74sczT8f1ReLdzcPE42oAqOANZ6LID810,13899 +torch/_inductor/runtime/proton_utils.py,sha256=NfcjNIq3mHwe1ov_-rLMgquiNnrFENL7WuZrv5JFE9k,11097 +torch/_inductor/runtime/runtime_utils.py,sha256=krEP1vqp65iHglTXLIZOEwGa55mMX-HVVtfA-8xWIzw,31884 +torch/_inductor/runtime/static_triton_launcher.py,sha256=NoQVuK_TAXRS7RMuXkg2wbMMkP0GtgGEYlMoN3LYgFQ,23085 +torch/_inductor/runtime/triton_compat.py,sha256=14is2r1WkNxdozuN8o3aGLToAEyqXF8Tl-pxsPXD0NU,4396 +torch/_inductor/runtime/triton_helpers.py,sha256=ZTrXOs4FiLqHSKwEmTUwMSaPEMc5-RHLc75QJI0KjZ8,32932 +torch/_inductor/runtime/triton_heuristics.py,sha256=0xdA72ADbrBUJEgOlhzo2P1PqHDSXfTc74e_aiF0c7s,211209 +torch/_inductor/runtime/triton_lazy_compile.py,sha256=5A1vvD8KS6DscnTHqNSeoOOFKczxQAJjaxjUcRDNnv4,10275 +torch/_inductor/scheduler.py,sha256=jjygw3F6T4lzx7_kHKtSzQ3XFUpUAf2NYOg7k1iTF4w,437483 +torch/_inductor/script.ld,sha256=pYkdES4_8MJi9MkEF79gr1KFT4iPUvbMT7NlDWP7aec,430 +torch/_inductor/select_algorithm.py,sha256=h0LElZ3EnoLfU9iqNmjnuodgCLSvuN1xH78JpHjJqiQ,249832 +torch/_inductor/shape_propagation.py,sha256=9wFrIYLvpm7Hw-B6SgylX0Mpy4zwkPHrlKQRcGNP_wo,4973 +torch/_inductor/sizevars.py,sha256=i2h9s_dfqSUBqg7TNIWwjeetuTRsA2dUUr-98L0NLEQ,63366 +torch/_inductor/standalone_compile.py,sha256=_hZ1g0L4POAECgOGSKNxMVvujzh28Np1p4ZWKCjLuDY,40216 +torch/_inductor/stream_constants.py,sha256=Z19olpHrM08Q64HqJ9g10BtiDoseojEjlHZq5191GDc,179 +torch/_inductor/stream_utils.py,sha256=pzPx1vxjmM4oT2ywF4u7o6w-MJan87P6vz__tl5LwMQ,4189 +torch/_inductor/subgraph_lowering.py,sha256=XeEKYb_dA1D0-7yjAlMDGXk36QX1Vwh1LIFRDDsHZe4,8330 +torch/_inductor/template_heuristics/__init__.py,sha256=tbEoyN0ebEf08Gfzi7rfiVPTwUWzH-wEvey1Xmja2KU,1156 +torch/_inductor/template_heuristics/__pycache__/__init__.cpython-312.pyc,, +torch/_inductor/test_case.py,sha256=AWBtSqYplhcONz2Ozc2lAbmX_EeNyom9Qr2RcA7z8pY,1444 +torch/_inductor/test_operators.py,sha256=0qiHRxRoouHirpj13eTQJyWqYgzEmvjj2aWasALEV3k,861 +torch/_inductor/tiling_utils.py,sha256=wIWy5EiFaf0ustPJt5xkrQ_ExjFsfW2xCZtRxc_TQQ0,33273 +torch/_inductor/triton_bundler.py,sha256=MRQRgs6mvDJKCU0MXc4-SO9zFMCXQlb_c1WeHxfVHNs,17467 +torch/_inductor/utils.py,sha256=8mGLihdNg9CBZcCGhpKlcYu_gPV9u2qlJ1xYCoiK318,165776 +torch/_inductor/virtualized.py,sha256=KOoFZR68R1gszgkbOfNiSM6EWOi4_OYTRqdE6vdPWV4,18997 +torch/_inductor/wrapper_benchmark.py,sha256=viU1H1V4RtR9zlxhta6GO_KsLMWfBNe5VVfXGmwWPJI,16696 +torch/_jit_internal.py,sha256=66_8uQo7ToFv5hrN7qRHM3pmduLpW3Q77ESZgP3H3TQ,55178 +torch/_lazy/__init__.py,sha256=ERr3DzFfISwFo4G8RcaNlnheOyflUEU7WdQD0G-avCo,2570 +torch/_lazy/__pycache__/__init__.cpython-312.pyc,, +torch/_lazy/__pycache__/closure.cpython-312.pyc,, +torch/_lazy/__pycache__/computation.cpython-312.pyc,, +torch/_lazy/__pycache__/config.cpython-312.pyc,, +torch/_lazy/__pycache__/debug.cpython-312.pyc,, +torch/_lazy/__pycache__/device_context.cpython-312.pyc,, +torch/_lazy/__pycache__/extract_compiled_graph.cpython-312.pyc,, +torch/_lazy/__pycache__/ir_cache.cpython-312.pyc,, +torch/_lazy/__pycache__/metrics.cpython-312.pyc,, +torch/_lazy/__pycache__/tensor_factory_functions.cpython-312.pyc,, +torch/_lazy/__pycache__/ts_backend.cpython-312.pyc,, +torch/_lazy/closure.py,sha256=uSBcqTJSc9mZtIAnzrnTHX08o18IR_fMBvHqRNRQ0nw,6334 +torch/_lazy/computation.py,sha256=JDa6s-DmwY1elPhIV-BV2Ma2EI-XxyRZISM05VrfAnA,1108 +torch/_lazy/config.py,sha256=-3YMuc6MvZef7TCPIX4J-MtrHwXVsrHPKZDvdCQ6iYM,448 +torch/_lazy/debug.py,sha256=l1Y1U7hO7ArKCbncuYu1U3n5ZY3hhdWZtOH2zSZdK2g,845 +torch/_lazy/device_context.py,sha256=yYWUdeE0j4gaftF4Pqrf_jfQOC3e9Aaovov0efQnZ4g,657 +torch/_lazy/extract_compiled_graph.py,sha256=V2Qjb_kQROGLv7_b__mXxSe3nBr3Xo8cYzWPqUh7fVA,9660 +torch/_lazy/ir_cache.py,sha256=zVEItp6RXRyF1xLk47SoCp3xYbI5om8HqOhpJ9aGXOc,337 +torch/_lazy/metrics.py,sha256=7eVQEskzolkfkiFmBk6mONlSqujFv7YQOkPX8eRGje0,553 +torch/_lazy/tensor_factory_functions.py,sha256=KW7nPz4EpDx2EXNkj3lIzoJB5tO4Urej_DhLB8bS7W0,1371 +torch/_lazy/ts_backend.py,sha256=eHEAmla76TD1Usa4D9-cwX2ZhRd92tA5KpTq27ChPDE,144 +torch/_library/__init__.py,sha256=nrHN83rXP5crQ0OeQiDyqXNcyoctiW-5dOFVAPArtzs,269 +torch/_library/__pycache__/__init__.cpython-312.pyc,, +torch/_library/__pycache__/_out_variant.cpython-312.pyc,, +torch/_library/__pycache__/autograd.cpython-312.pyc,, +torch/_library/__pycache__/custom_ops.cpython-312.pyc,, +torch/_library/__pycache__/effects.cpython-312.pyc,, +torch/_library/__pycache__/fake_class_registry.cpython-312.pyc,, +torch/_library/__pycache__/fake_impl.cpython-312.pyc,, +torch/_library/__pycache__/fake_profile.cpython-312.pyc,, +torch/_library/__pycache__/infer_schema.cpython-312.pyc,, +torch/_library/__pycache__/opaque_object.cpython-312.pyc,, +torch/_library/__pycache__/simple_registry.cpython-312.pyc,, +torch/_library/__pycache__/triton.cpython-312.pyc,, +torch/_library/__pycache__/utils.cpython-312.pyc,, +torch/_library/_out_variant.py,sha256=6VWvaUbPFkMM2zSPcCxvMaItjtfFIJigvUZAsBr4PfE,6287 +torch/_library/autograd.py,sha256=IVGgpknxyPETCNpP2N2deDX7hQyxlCCch_Di5qdDZq8,11057 +torch/_library/custom_ops.py,sha256=6GZm8hkHHOj-lm2N53g8wAaAQAYcnFmhJ5xhfa_Y9xA,46232 +torch/_library/effects.py,sha256=J2p1LnF4c1CE4xYs0HTnY-6MqnkepKQkt-ck_Q2MNgM,2782 +torch/_library/fake_class_registry.py,sha256=YOHVtByZY3O1jH7Ej7jA6xNwlusOGfXdTVHn3zFktAg,20156 +torch/_library/fake_impl.py,sha256=Nq7ZY-xVcd2tlcL4Owd26ZbxZPGmAXqC8VDaHGf5dV4,9174 +torch/_library/fake_profile.py,sha256=r9KDhGjlrzh0wl8CPHKjCOiKw0H48jp928MkjKVpLRY,11555 +torch/_library/infer_schema.py,sha256=cFlk9i_4uFDWbPqja-O7R3zb19AEJNuTyyqQVpEnuvY,18415 +torch/_library/opaque_object.py,sha256=8-DYmrok0yb_sreF1AelDkDS8sVFyTQHc7F7cWmgZ_E,16628 +torch/_library/simple_registry.py,sha256=Jejil0l_NlGQmg7mX9_1iloH7zA6eB11uMwo59JQ4jE,4605 +torch/_library/triton.py,sha256=OqRL_yyEsUcqj_005FVjalZLFscK_WkVTvSyci6PjIU,25269 +torch/_library/utils.py,sha256=4NteiXfCd1RDpGvS8lHPBwh4Y-0wG2-7dtAGoM8O-FQ,24657 +torch/_linalg_utils.py,sha256=b69by-Snx-Y2iljtSOTq9GtjnweQpZDadWFGBXHhNcc,6487 +torch/_lobpcg.py,sha256=Dxas59tVVz2XvbqbncUL0I3nJM0eGQ_x2LFnWios8C4,44481 +torch/_logging/__init__.py,sha256=wTE40MPYVeohdWbp_5z_a3QBDWUYOLV_CSd0MuwP9pc,818 +torch/_logging/__pycache__/__init__.cpython-312.pyc,, +torch/_logging/__pycache__/_internal.cpython-312.pyc,, +torch/_logging/__pycache__/_registrations.cpython-312.pyc,, +torch/_logging/__pycache__/scribe.cpython-312.pyc,, +torch/_logging/__pycache__/structured.cpython-312.pyc,, +torch/_logging/_internal.py,sha256=nP0_6L5Hhwf2oieePTsbk2w_D8DiBcO8MlfrhUCoY6I,59791 +torch/_logging/_registrations.py,sha256=Tp2raBV3IcOTquN2eIVxBsvjvfzyI6bqdafCf7Cfzgk,9638 +torch/_logging/scribe.py,sha256=zAgIBA-iLeSESB9Ek4P9H_FRUvJK-781MrBir_gjYgw,2539 +torch/_logging/structured.py,sha256=LgZTqykz-WIzLI6OI0D354bBqttp8Kcyj8_TuSMBQxw,2909 +torch/_lowrank.py,sha256=eBhxRMhfi9L1h_LVjrzulAJEBHwTKzBQe_AprNFtvUg,10497 +torch/_meta_registrations.py,sha256=x_pih18_KrifULjWwpZnbVj4wGjY30v5xEkcLRBC_c4,295895 +torch/_native/__init__.py,sha256=GcfFF7hc7oEwOdymkWNKUxZk7czJblLPrkOx_90Dht4,1861 +torch/_native/__pycache__/__init__.cpython-312.pyc,, +torch/_native/__pycache__/common_utils.cpython-312.pyc,, +torch/_native/__pycache__/cutedsl_utils.cpython-312.pyc,, +torch/_native/__pycache__/dsl_registry.cpython-312.pyc,, +torch/_native/__pycache__/helion_utils.cpython-312.pyc,, +torch/_native/__pycache__/instrumentation.cpython-312.pyc,, +torch/_native/__pycache__/nvmath_utils.cpython-312.pyc,, +torch/_native/__pycache__/registry.cpython-312.pyc,, +torch/_native/__pycache__/triton_utils.cpython-312.pyc,, +torch/_native/common_utils.py,sha256=2cSGydDepD9arwnDyjfgwjYD_7j1c3jkKpnACHz-8Mc,2031 +torch/_native/cutedsl_utils.py,sha256=ukLACoLoESIX8FQcA_u8_19B813p08FIVL24TstrHO0,4050 +torch/_native/dsl_registry.py,sha256=y3wrztGWQ8AsZvmqRkV_7Wr4ugj8LDiyG9wgaIOvVUM,5217 +torch/_native/helion_utils.py,sha256=HwS9VgSnF3PsSg7_kXzaPbkuvE8vmRJHf6L7qca-omk,3670 +torch/_native/instrumentation.py,sha256=zir4_BvJ-eXNMOt3LyI-PfTkkUeikW_4VMuVhM68RL8,20058 +torch/_native/nvmath_utils.py,sha256=DExqSY-1UGPeHg44DuFfoHQ5lPry45neHsynvKuY22Y,2571 +torch/_native/ops/__init__.py,sha256=_30sIOJdh2Sz5G50Ef6fY61RN-hmue8B8FLR6EAXuHk,81 +torch/_native/ops/__pycache__/__init__.cpython-312.pyc,, +torch/_native/ops/bmm_outer_product/__init__.py,sha256=ozQ2fS1Fprp7IBbv4kXulpInSQc4wJt-KxLWoP7MNZs,71 +torch/_native/ops/bmm_outer_product/__pycache__/__init__.cpython-312.pyc,, +torch/_native/ops/bmm_outer_product/__pycache__/triton_impl.cpython-312.pyc,, +torch/_native/ops/bmm_outer_product/__pycache__/triton_kernels.cpython-312.pyc,, +torch/_native/ops/bmm_outer_product/triton_impl.py,sha256=dntEICCMjlPJqucUyUyHaxve5jx3AFJ1Jf-ltJUKmK0,1573 +torch/_native/ops/bmm_outer_product/triton_kernels.py,sha256=E0-8ZpI7pYErcBnrXqziUcEOfdhzEzWOqJeriJGcMng,2788 +torch/_native/ops/foreach_mm/__init__.py,sha256=KbT0rMeVQy5eNpysuSRHaHyZs9LllY-lMEg3_20kavk,64 +torch/_native/ops/foreach_mm/__pycache__/__init__.cpython-312.pyc,, +torch/_native/ops/foreach_mm/__pycache__/impl.cpython-312.pyc,, +torch/_native/ops/foreach_mm/__pycache__/nvmath_impl.cpython-312.pyc,, +torch/_native/ops/foreach_mm/impl.py,sha256=clMrz8tjUj2C1kS17UEE66JIm0XWBan49kobDf1VuPI,8657 +torch/_native/ops/foreach_mm/nvmath_impl.py,sha256=USSzDkFEXbhKAWiqkQrhWi_VqFxa9unMcgoxa6Z96Ac,9551 +torch/_native/ops/norm/__init__.py,sha256=EyMgJqq-9pac_gfMA0ZRZNngQsT8ew_WmXNtaD6GPPM,84 +torch/_native/ops/norm/__pycache__/__init__.cpython-312.pyc,, +torch/_native/ops/norm/__pycache__/norms.cpython-312.pyc,, +torch/_native/ops/norm/__pycache__/rmsnorm_impl.cpython-312.pyc,, +torch/_native/ops/norm/norms.py,sha256=FiDZNMOW4NsI1yEA93ooDGoSMKMy0iE-SIxAt7Z6dPU,7726 +torch/_native/ops/norm/rmsnorm_impl.py,sha256=cHAru7y2OMEi1jmHFyVU77d7M20DTOUsUgDe3cJKXkg,9157 +torch/_native/ops/polar/__init__.py,sha256=KbT0rMeVQy5eNpysuSRHaHyZs9LllY-lMEg3_20kavk,64 +torch/_native/ops/polar/__pycache__/__init__.cpython-312.pyc,, +torch/_native/ops/polar/__pycache__/impl.cpython-312.pyc,, +torch/_native/ops/polar/__pycache__/nvmath_impl.cpython-312.pyc,, +torch/_native/ops/polar/impl.py,sha256=kKWJERdVMz8HKtXsr5-DIZlVNTVF_cYqAvEzLuBvT6E,6488 +torch/_native/ops/polar/nvmath_impl.py,sha256=fePRq8xvfZB1eY7ADEKg1mzOnH4fcNpTjrmWas3Clrg,6338 +torch/_native/ops/scatter_add/__init__.py,sha256=mLVDv5Debl5e_rRvQRNRp9niSR0ejsO3cYOnyU1VTKA,72 +torch/_native/ops/scatter_add/__pycache__/__init__.cpython-312.pyc,, +torch/_native/ops/scatter_add/__pycache__/_ptx.cpython-312.pyc,, +torch/_native/ops/scatter_add/__pycache__/cutedsl_impl.cpython-312.pyc,, +torch/_native/ops/scatter_add/__pycache__/tma_kernel.cpython-312.pyc,, +torch/_native/ops/scatter_add/__pycache__/vec_scatter_kernel.cpython-312.pyc,, +torch/_native/ops/scatter_add/_ptx.py,sha256=Rsuu2woDdl0AhXBOkBpt2dkPnDQZql-oZrnMQjGFYBg,2960 +torch/_native/ops/scatter_add/cutedsl_impl.py,sha256=Q2SD247hNFsFBwNyPI6mTpIZHhccTQiqIS9O0Jzvazs,17427 +torch/_native/ops/scatter_add/tma_kernel.py,sha256=RQgYlLd_OZYQBTbr8ACVXbN-e9-K6H-a-Ywd7ioAksI,18716 +torch/_native/ops/scatter_add/vec_scatter_kernel.py,sha256=tKRZ8c3G-ABKaVxjZwtx0Y4GjNODluqE74tqZDrI8Tw,9962 +torch/_native/ops/sum/__init__.py,sha256=mLVDv5Debl5e_rRvQRNRp9niSR0ejsO3cYOnyU1VTKA,72 +torch/_native/ops/sum/__pycache__/__init__.cpython-312.pyc,, +torch/_native/ops/sum/__pycache__/cutedsl_impl.cpython-312.pyc,, +torch/_native/ops/sum/__pycache__/inner_tree_kernel.cpython-312.pyc,, +torch/_native/ops/sum/__pycache__/inner_tree_plan.cpython-312.pyc,, +torch/_native/ops/sum/cutedsl_impl.py,sha256=L1cngF87VfKb0sw3Vmegb11fxG6jGVoAYMVSwhBwnjw,9868 +torch/_native/ops/sum/inner_tree_kernel.py,sha256=ymiSfe0f4n6HXbl_yz8qKb9rjr0HMzcruoyC0ttrrXA,21393 +torch/_native/ops/sum/inner_tree_plan.py,sha256=1LJHZMkSs39_WV1owy2iR3LQdHrtU9_GmBQCzEk8bso,3148 +torch/_native/ops/topk/__init__.py,sha256=ArxrueIN0GcIEQO88MwBAQ8Aj9LNYyaHRSQxFU6Erss,90 +torch/_native/ops/topk/__pycache__/__init__.cpython-312.pyc,, +torch/_native/ops/topk/__pycache__/_common.cpython-312.pyc,, +torch/_native/ops/topk/__pycache__/cutedsl_impl.cpython-312.pyc,, +torch/_native/ops/topk/__pycache__/cutedsl_kernels.cpython-312.pyc,, +torch/_native/ops/topk/_common.py,sha256=WdYaHjjDbjVjcQpejoHE9BZ-jbZnPZ3w8uhUzlTLjtY,2328 +torch/_native/ops/topk/cutedsl_impl.py,sha256=J8upvFzLQLkO5RifiQ6nRHedgXYpor465wdE0KsWUc0,7518 +torch/_native/ops/topk/cutedsl_kernels.py,sha256=LjM4UfF3KiefdTbeWgVEJPxZ5_yXUQ59SDI8qSZnZlk,36500 +torch/_native/registry.py,sha256=8Jqrn5jkdkF7b7KgUw5dB-AT10PLEHD7U0beqQ85RIg,40138 +torch/_native/triton/__init__.py,sha256=3lheA2iZo7VjC10zcSwQ_0ESucBNjfaLHlYSZ9ZTUAA,88 +torch/_native/triton/__pycache__/__init__.cpython-312.pyc,, +torch/_native/triton/__pycache__/const_tensor_wrapper.cpython-312.pyc,, +torch/_native/triton/const_tensor_wrapper.py,sha256=RMBj8g0iMUMuLtBmKQQS7bA4VoXLPBboz34SIadfqOo,2371 +torch/_native/triton_utils.py,sha256=yl2oTSzM26JZ-VPx_fmN6oKXs-cKa0MxSyPMI15v66c,3592 +torch/_numpy/__init__.py,sha256=_Jxx8XlO6rLDkI0bP7kYY_JLbYI8kVA3eFfjesMk-qg,590 +torch/_numpy/__pycache__/__init__.cpython-312.pyc,, +torch/_numpy/__pycache__/_binary_ufuncs_impl.cpython-312.pyc,, +torch/_numpy/__pycache__/_casting_dicts.cpython-312.pyc,, +torch/_numpy/__pycache__/_dtypes.cpython-312.pyc,, +torch/_numpy/__pycache__/_dtypes_impl.cpython-312.pyc,, +torch/_numpy/__pycache__/_funcs.cpython-312.pyc,, +torch/_numpy/__pycache__/_funcs_impl.cpython-312.pyc,, +torch/_numpy/__pycache__/_getlimits.cpython-312.pyc,, +torch/_numpy/__pycache__/_ndarray.cpython-312.pyc,, +torch/_numpy/__pycache__/_normalizations.cpython-312.pyc,, +torch/_numpy/__pycache__/_reductions_impl.cpython-312.pyc,, +torch/_numpy/__pycache__/_ufuncs.cpython-312.pyc,, +torch/_numpy/__pycache__/_unary_ufuncs_impl.cpython-312.pyc,, +torch/_numpy/__pycache__/_util.cpython-312.pyc,, +torch/_numpy/__pycache__/fft.cpython-312.pyc,, +torch/_numpy/__pycache__/linalg.cpython-312.pyc,, +torch/_numpy/__pycache__/random.cpython-312.pyc,, +torch/_numpy/_binary_ufuncs_impl.py,sha256=h_xCtCyRAdTEB2T_r0AZ25G7u9IM3PRPr1mVv8Cr0qY,1871 +torch/_numpy/_casting_dicts.py,sha256=EmT0GYUz7Ii1iT1prWZgsahqtZZ069I1O0T2pzhSlOE,42478 +torch/_numpy/_dtypes.py,sha256=wvZxyub124ritRWer5fsm19YVs3lji1XvT7UhCbY4M0,11211 +torch/_numpy/_dtypes_impl.py,sha256=878WyQ_5NSSp8T22sBZrWi16ParwHA80OGkgCxcA_FA,6475 +torch/_numpy/_funcs.py,sha256=vT_F_qnfL3CJoZr_R1NEHvETRCnIoEOrNGXVP5o-5aM,2097 +torch/_numpy/_funcs_impl.py,sha256=Q8on4aGY4oO_lOJbLxqXZaPzR4lxiAtanaU4XDOsQ1c,59362 +torch/_numpy/_getlimits.py,sha256=QRUbPnrehERJA9Wk01SdUaF1F2FhksfgpewYN6SmtgE,269 +torch/_numpy/_ndarray.py,sha256=Rf4zVsiY4BluCqquLMD9HJe9st-M7kyvI0sXGKNqIwk,21895 +torch/_numpy/_normalizations.py,sha256=l7yKrnfw79UHnlKwICt1HF-yLvIsVTgRxfq0mU0ESCI,12416 +torch/_numpy/_reductions_impl.py,sha256=zEFyt5RQmN8mni949C87xoXeA9WDpi8aJVUjLt14q0c,13082 +torch/_numpy/_ufuncs.py,sha256=HbjZbhF5ZMhSTMa0tGA_8oEdUBd5rj63sfhKpVmM3Us,8283 +torch/_numpy/_unary_ufuncs_impl.py,sha256=IO2kPjYhNoKCyu_9NcMFQF57le1U9VjFmqQFbsWA3Jc,1161 +torch/_numpy/_util.py,sha256=MYns1d4kaSTe-TWMsorzHiebtXdJI2xqDl8nKxiTnUk,9057 +torch/_numpy/fft.py,sha256=DgjEmXuEbVCo5r_u2Sq5Wng0WybHYZLW5-2JVXGdrvA,4342 +torch/_numpy/linalg.py,sha256=Ceii05oTeQeYRL8h7xeyqOMAFVpQzlUkhkBvjcyB0s0,6745 +torch/_numpy/random.py,sha256=i8D7VLbdUosxWruXrUGXG00TcHpGcaio0jCw1r7HTj4,4620 +torch/_numpy/testing/__init__.py,sha256=t5Re9c4lijwKoegYKS74CFviLCfSDSWZMvw78ohKYss,375 +torch/_numpy/testing/__pycache__/__init__.cpython-312.pyc,, +torch/_numpy/testing/__pycache__/utils.cpython-312.pyc,, +torch/_numpy/testing/utils.py,sha256=Q1dFzmOhdUlXUVASdQeArz6X-pgKE1kTdfBW7D2AvhA,77454 +torch/_opaque_base.py,sha256=_pT8ZAnOhvw2PW6qO1bV38m1bRUYQ5RY3eFcwSupU_M,272 +torch/_ops.py,sha256=VeTZqGlJ1JYGSSg6Q9KgniA0D31f2Og2IWRr5YBs1yo,67363 +torch/_precompile.py,sha256=qKuDm-HotVXBgaCKjEMRhar2forADlF1kPyAktBVTkY,102420 +torch/_precompile_driver.py,sha256=2FPCM3V7n4NCGOhYNgCGafoi9C1dd47CSdpl4yZFw0g,18977 +torch/_prims/__init__.py,sha256=J77txXwsKgzIojX8OlzNrolAlxlYeScAxlbC9-DEmKA,86310 +torch/_prims/__pycache__/__init__.cpython-312.pyc,, +torch/_prims/__pycache__/context.cpython-312.pyc,, +torch/_prims/__pycache__/debug_prims.cpython-312.pyc,, +torch/_prims/__pycache__/executor.cpython-312.pyc,, +torch/_prims/__pycache__/rng_prims.cpython-312.pyc,, +torch/_prims/context.py,sha256=wMn_9XZQqJw7JOoV6d5bCSYXSQQyEvsItLi-HOpfXTY,6248 +torch/_prims/debug_prims.py,sha256=sfqX5M4dBhvQRgMrt6-o8WHTzXjvIUBehRxcwFjjHxY,2250 +torch/_prims/executor.py,sha256=6qVwYXMvV0rAsvRa4hpW3bZ7X4Pem4mzGNRWpjgtij8,1923 +torch/_prims/rng_prims.py,sha256=koJs_S97Jo40hMbotr3ivLLRvaE1-dMVL91f195Shd4,20714 +torch/_prims_common/__init__.py,sha256=6uU4anid7GqbrDEOWB0j2moLTjdRC43jVY9IEJrOxac,75474 +torch/_prims_common/__pycache__/__init__.cpython-312.pyc,, +torch/_prims_common/__pycache__/wrappers.cpython-312.pyc,, +torch/_prims_common/wrappers.py,sha256=DNHmUZj_z66M8atuh7OrvVUSaOBb6WBdvSOD2PcwJcI,19567 +torch/_python_dispatcher.py,sha256=wr9rxY-Hf1qjVPaijE0HAug2IHtJPKDEGeLN9m0MX4g,7132 +torch/_refs/__init__.py,sha256=px_hUBnWz0tcINJ19bLmnDOSS2WSXN_ePPyLgPgoDtI,237117 +torch/_refs/__pycache__/__init__.cpython-312.pyc,, +torch/_refs/__pycache__/_conversions.cpython-312.pyc,, +torch/_refs/__pycache__/fft.cpython-312.pyc,, +torch/_refs/_conversions.py,sha256=BkNyamBLOQLlKy6mB4BSdPRjAKP1ghZ5xcyQDkUs-_s,3533 +torch/_refs/fft.py,sha256=L36O9lvHZkgZ9UDec_o7_zekr4Cdxl99aSqPjUhq6u8,18683 +torch/_refs/linalg/__init__.py,sha256=z-92PaGaakd1GJB5ryumnYoSpcYJAzv4ARVJ1Xziijw,12449 +torch/_refs/linalg/__pycache__/__init__.cpython-312.pyc,, +torch/_refs/nn/__init__.py,sha256=juqd9PbXs4yg45zMJ7BHAOPQjb7sgEbWE9InBtGZhfo,24 +torch/_refs/nn/__pycache__/__init__.cpython-312.pyc,, +torch/_refs/nn/functional/__init__.py,sha256=j2kGQyR51Xk5tHPqSGPEJImuw6nRVFPRFxxu06RfzPk,44131 +torch/_refs/nn/functional/__pycache__/__init__.cpython-312.pyc,, +torch/_refs/special/__init__.py,sha256=Njxv8FI1zSzZANrqwvhVe9oD3hZsY2rgsWkHF6vwAuc,7035 +torch/_refs/special/__pycache__/__init__.cpython-312.pyc,, +torch/_size_docs.py,sha256=z2Ckk4Ufq-Ek6Av1-rs1Wcrg6OoJxTCRPYjEjhzG1Xo,900 +torch/_sources.py,sha256=8m01Tz23KVDOEeFqUDBvIF-nBJhwDSoW3qnonT3UFhc,4406 +torch/_storage_docs.py,sha256=KyxMZ6j9UPSolidRjR7WDu7gJWkYot8TFggfPA1fygI,1335 +torch/_streambase.py,sha256=NAKZfV-BhZ22Jyt_3VQDH1m4QQdIVc4G8VvUBkZ9wJ8,435 +torch/_strobelight/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_strobelight/__pycache__/__init__.cpython-312.pyc,, +torch/_strobelight/__pycache__/cli_function_profiler.cpython-312.pyc,, +torch/_strobelight/__pycache__/compile_time_profiler.cpython-312.pyc,, +torch/_strobelight/cli_function_profiler.py,sha256=2mDoxiJ97feOYWfAGL9UoWwSgHWoP8NNhKYndk-jO2Q,11775 +torch/_strobelight/compile_time_profiler.py,sha256=LmKB8TtCO1MijfGm94g0NxCN0jE4kBpm1c4dCWJXO8w,7503 +torch/_subclasses/__init__.py,sha256=7NDSoV4xw-GxCRtHasX_MFFLe_S1-1BHRFvoDcgE4J0,375 +torch/_subclasses/__pycache__/__init__.cpython-312.pyc,, +torch/_subclasses/__pycache__/_fake_tensor_utils.cpython-312.pyc,, +torch/_subclasses/__pycache__/fake_impls.cpython-312.pyc,, +torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc,, +torch/_subclasses/__pycache__/fake_utils.cpython-312.pyc,, +torch/_subclasses/__pycache__/functional_tensor.cpython-312.pyc,, +torch/_subclasses/__pycache__/meta_utils.cpython-312.pyc,, +torch/_subclasses/__pycache__/schema_check_mode.cpython-312.pyc,, +torch/_subclasses/_fake_tensor_utils.py,sha256=y9LIEBXbUtDRLKNtHpbP9R-RLWsJye-kWIZTMZXuBT8,9375 +torch/_subclasses/complex_tensor/__init__.py,sha256=kVkYnsYeU_gwqpFP6q4mj6y8gkUfLYlqwQzVBGA5Frc,313 +torch/_subclasses/complex_tensor/__pycache__/__init__.cpython-312.pyc,, +torch/_subclasses/complex_tensor/__pycache__/_core.cpython-312.pyc,, +torch/_subclasses/complex_tensor/_core.py,sha256=TbwuGeNSJrPeRi8p_lwpQbKMDAV0IRDIBAW3mOHFiqA,5712 +torch/_subclasses/complex_tensor/_ops/__init__.py,sha256=HPc4kOqkd8FEXCiI1PVOYSFp4R4KTo8hljzvMMeD2BQ,191 +torch/_subclasses/complex_tensor/_ops/__pycache__/__init__.cpython-312.pyc,, +torch/_subclasses/complex_tensor/_ops/__pycache__/aten.cpython-312.pyc,, +torch/_subclasses/complex_tensor/_ops/__pycache__/common.cpython-312.pyc,, +torch/_subclasses/complex_tensor/_ops/__pycache__/prims.cpython-312.pyc,, +torch/_subclasses/complex_tensor/_ops/aten.py,sha256=TX8EwWxVfrocoUaShT7RH7JiofcuIWqnBUdBjYs9k28,33506 +torch/_subclasses/complex_tensor/_ops/common.py,sha256=rO3C5o7ZjGfCWtR_538bFyMTYd1suKkAtRLE89qCrJQ,11239 +torch/_subclasses/complex_tensor/_ops/prims.py,sha256=qEqDoFU20-woc8B-DE9f-iKvA7-TPBxgQtUTB1QD0h0,864 +torch/_subclasses/fake_impls.py,sha256=68fZl8nZoV8gE22sGK3Uzo5JEEQIvDg8Z2HALUeOKxY,88992 +torch/_subclasses/fake_tensor.py,sha256=plBBHmp63eN5Hnoogh-_w4WEJcUEM6v21ThinhfDPFg,155552 +torch/_subclasses/fake_utils.py,sha256=-VZm_JcEPWBnA5KMJ73Zd_OXu93Nhg8pJffg1Ve2rwg,11196 +torch/_subclasses/functional_tensor.py,sha256=kf15wh6RGaUwlYUU0d6FIAmMuqj4rYz0GtbYmNBHoq0,44478 +torch/_subclasses/meta_utils.py,sha256=0J9CLJ4oyGduN-rEQBQQIGHfgOXZwj0yjOC2AB7LsiY,111540 +torch/_subclasses/schema_check_mode.py,sha256=DureFgsfEtN9IfpiwOc-dHfaHbgrq6-q_S6qeQIlVwg,9704 +torch/_tensor.py,sha256=3q1p6k54LKX2jwRhFbKm3vs8k_6P9nHZP6hNE589nzM,70738 +torch/_tensor_docs.py,sha256=nD1NC874BBNSzIfP9omAw53djFBtTo22QQrzBr1G8Yk,142677 +torch/_tensor_iterator.py,sha256=N_bEVXEJA0sYuOjbWiYDkvxktW_VbG0DObJB-uAYt3g,14661 +torch/_tensor_str.py,sha256=APGPfmVyo3qWJ-qChHLIOenAeOG_PvqYovSls-KkvMo,28051 +torch/_thread_safe_fork.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_torch_docs.py,sha256=85YqKklz59SRejs_JlkD1KU0CFNDu-QNADcoOF0ZSeU,445068 +torch/_utils.py,sha256=bxOh-skxFxWCsm2M1Su37OcBINVn_0CJ5xe7UvTYgt4,55762 +torch/_utils_internal.py,sha256=Yx2iniUjpwchwKkfaAAcGV2VNrKXrngVq3e2RXkFBBE,12701 +torch/_vendor/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_vendor/__pycache__/__init__.cpython-312.pyc,, +torch/_vendor/packaging/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +torch/_vendor/packaging/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +torch/_vendor/packaging/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +torch/_vendor/packaging/__init__.py,sha256=EhCMuCSz60IgQJ93b_4wJyAoHpU9J-uddG4QaMT0Pu4,496 +torch/_vendor/packaging/__pycache__/__init__.cpython-312.pyc,, +torch/_vendor/packaging/__pycache__/_structures.cpython-312.pyc,, +torch/_vendor/packaging/__pycache__/version.cpython-312.pyc,, +torch/_vendor/packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431 +torch/_vendor/packaging/version.py,sha256=XjRBLNK17UMDgLeP8UHnqwiY3TdSi03xFQURtec211A,16236 +torch/_vendor/quack/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +torch/_vendor/quack/__init__.py,sha256=e6uY_e2XuAfVp2K_Ezr7nIlMiQ0MKU4zBNeUfPs74bc,1486 +torch/_vendor/quack/__pycache__/__init__.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/_compile_worker.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/activation.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/autotuner.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/blockscaled_gemm_utils.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/compile_utils.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/copy_utils.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/cute_dsl_elf_fix.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/cute_dsl_mlir_threading.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/cute_dsl_utils.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/epi_composable.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/epi_ops.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/epi_utils.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/fast_math.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/gemm_act.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/gemm_base.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/gemm_blockscaled_interface.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/gemm_config.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/gemm_default_epi.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/gemm_sm100.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/gemm_sm120.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/gemm_sm80.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/gemm_sm90.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/gemm_tvm_ffi_utils.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/layout_utils.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/mx_utils.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/pipeline.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/reduce.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/reduction_base.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/rmsnorm.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/rmsnorm_config.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/rounding.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/sm100_utils.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/sm80_utils.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/sm90_utils.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/tile_scheduler.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/trace.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/utils.cpython-312.pyc,, +torch/_vendor/quack/__pycache__/varlen_utils.cpython-312.pyc,, +torch/_vendor/quack/_compile_worker.py,sha256=yBMz6IoTkPVnEyi1s1xg3xNCDluYCzowYzpOc1JNHOo,6593 +torch/_vendor/quack/activation.py,sha256=zXAG9T5yFWeGeljJZySf82tzlkN04P2jhaTnNo2zJ1g,28416 +torch/_vendor/quack/autotuner.py,sha256=RWUlcreqzzeM8VqCk84FQT5-QlT0x90Xr4At20EhIks,36548 +torch/_vendor/quack/bench/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/_vendor/quack/bench/__pycache__/__init__.cpython-312.pyc,, +torch/_vendor/quack/bench/__pycache__/bench_utils.cpython-312.pyc,, +torch/_vendor/quack/bench/bench_utils.py,sha256=OZfHYnYliR7-o1paEdakdQ8YS22ySnOwPjwxuwfXpxE,8386 +torch/_vendor/quack/blockscaled_gemm_utils.py,sha256=C0Kx_m-yGF4cj4Cp1eGz6ASTRnqRweqptelqhM0B03c,30338 +torch/_vendor/quack/cache/__init__.py,sha256=UnF1fNm0w8hFBKa0rbGRQSV328Z9s8LPQvPfPAVP4B0,9743 +torch/_vendor/quack/cache/__pycache__/__init__.cpython-312.pyc,, +torch/_vendor/quack/cache/__pycache__/compile_only.cpython-312.pyc,, +torch/_vendor/quack/cache/__pycache__/jit.cpython-312.pyc,, +torch/_vendor/quack/cache/compile_only.py,sha256=XkoF4gD4lkVvrPKQ86e3O3ARaUDMacTgwciK4G2GEu4,8711 +torch/_vendor/quack/cache/jit.py,sha256=SPchCQyrNXhW38lz8Zlydafwb6LjvPSM8wr0WQcCBuY,10878 +torch/_vendor/quack/compile_utils.py,sha256=qJ3oTsDlbAiddrJHtEO7LPYVqn_s-neNfiw-_KvfXZU,591 +torch/_vendor/quack/copy_utils.py,sha256=v3_WDRIFlrBXdJQo2DB_eAQy5mIDXRF4XVQUYFLcgGA,47958 +torch/_vendor/quack/cute_dsl_elf_fix.py,sha256=tuSrilbNQHEDCAy6GciHnoDMp52wgyKKVT6Au4kQtMQ,3805 +torch/_vendor/quack/cute_dsl_mlir_threading.py,sha256=HeJ_kh0L6LTAzmDI1dDkinrjQWpGxJMgqRJSw_bC14I,1428 +torch/_vendor/quack/cute_dsl_utils.py,sha256=KEfqL-EWPoP8Qbab4T8HY-bwPohTZRd3fZxMzM7VvxI,7003 +torch/_vendor/quack/epi_composable.py,sha256=iCA8mYu9CLXNVvWmdP7847Pk-51tUYv6U6lTb5ptgfQ,11071 +torch/_vendor/quack/epi_ops.py,sha256=71OoBXzdl2a_6oVJY-LQLv9-VcHEkI7Hg_ZkMS3WQtk,77810 +torch/_vendor/quack/epi_utils.py,sha256=aqNlSo6pohqspohXjD-Km4HviKACLfuwHpDJDnePp0E,2555 +torch/_vendor/quack/fast_math.py,sha256=4vrW_HB65rBlCyg0d6h6Y8Q4Gvjti5g74yqCv7acsxA,1020 +torch/_vendor/quack/gemm_act.py,sha256=tkPn5DW7O5LOwCKctuMrnYjAZs9qSOVLjPWVsbyVb6g,54877 +torch/_vendor/quack/gemm_base.py,sha256=0dkNWxD8qdCOuU9Gkb3eeHepw_FLdstmk_LYrFWadTc,28320 +torch/_vendor/quack/gemm_blockscaled_interface.py,sha256=5wNF0AGw8UnbS9X7dxolqlyVZNcFPJCHgoTjI9EMIyA,12110 +torch/_vendor/quack/gemm_config.py,sha256=NinZfsUbbcaFyMR-yzuBtSfF2Q6TJPd3AoxAr89I5AQ,6329 +torch/_vendor/quack/gemm_default_epi.py,sha256=5TIOqutQtqzz4OTFV6JZwjmXB1AF6dXYQ1NuMkGE3uY,3501 +torch/_vendor/quack/gemm_sm100.py,sha256=1BQRW5pBew6Ri7b8jCDf0nSAm_Sp929_fMp7CfmR3Mw,122745 +torch/_vendor/quack/gemm_sm120.py,sha256=hXieZPA1DzkgoDO0uPSXLTUqshPjH5mCkKtBUV-chvs,31520 +torch/_vendor/quack/gemm_sm80.py,sha256=M7TvP-wGJhYM2FzK-Y7jpP8Jwk050nTa9gNJ9F3nOyU,5842 +torch/_vendor/quack/gemm_sm90.py,sha256=tyiLfBICtGbcNukHNFBYIEv0sQ06vN16lhHB8kPA96U,66847 +torch/_vendor/quack/gemm_tvm_ffi_utils.py,sha256=7mUA_YSt9HEVsX7M9jcm1jnIf_a2aOi01ND9bBOGqR8,7801 +torch/_vendor/quack/layout_utils.py,sha256=MZncP1XzRhg-PShPbamPQ5Tq8U8ot2FtFH5uSeyJYZQ,16464 +torch/_vendor/quack/mx_utils.py,sha256=EPiyWvbHg1PC0UI5IRX3CqHTNk6HnjzhkUY-vkwgNSU,10940 +torch/_vendor/quack/pipeline.py,sha256=eW8rmeOEsim3jArWW6D4CYTi5nfk2K-kLym89ilUjD8,23058 +torch/_vendor/quack/reduce.py,sha256=C3x7F_wgWvuPvdSaj1WV6O2VJcuLnuanS9Z-SJVZXjk,12696 +torch/_vendor/quack/reduction_base.py,sha256=uAAm2iW49kTc9epJpFFJPPKzPFcPS12WqgGGkyukTt0,3993 +torch/_vendor/quack/rmsnorm.py,sha256=V2qbG9sXBz7Y1TbN4llymmkhLWOP4dTN6_Egjd4QFKI,60439 +torch/_vendor/quack/rmsnorm_config.py,sha256=L7RFFcQMF7FaCAMFCkz8Rmspc5cagXktp3j28E0vlhc,18360 +torch/_vendor/quack/rounding.py,sha256=E810UAfi7C4AI72OMJnA-6pRoniwCty01RmpWKeN6EE,6824 +torch/_vendor/quack/sm100_utils.py,sha256=-AkAPWzg-2cXZMwTijIVTvWWwZmk5m3bAsOJQTffzDo,4816 +torch/_vendor/quack/sm80_utils.py,sha256=0yOgRslAIq8B7MS8tIkgZuilOMIkYnJDUl7c2gjdkzg,971 +torch/_vendor/quack/sm90_utils.py,sha256=QaLZ3MLlp9dKOD-VwdhxmqEstPdq8CVGaNwffbwspNw,6725 +torch/_vendor/quack/tile_scheduler.py,sha256=m8tDRoePUtOPHlq9xgUyqOiSkQtSkDY4sAQLYc9xCM4,51229 +torch/_vendor/quack/trace.py,sha256=ZNp1UE1VYr--vFmNPe3es9t4oBl3jj-RyhIwAi7LyEI,31193 +torch/_vendor/quack/utils.py,sha256=NY8C4H5rByXqVgl5vdUDNqZWIYM4zgTeAEvvmtrpT5s,11132 +torch/_vendor/quack/varlen_utils.py,sha256=K3xDUeNqCbO0FIRXZPtcHGvVN6MGehi5SIHufQX-lv0,8608 +torch/_vmap_internals.py,sha256=TFbuX8OuGYhB91CieppnetqjkMerMZ3q_oD7SYS1YYU,9426 +torch/_weights_only_unpickler.py,sha256=-AXz_q6E_RD5Lv-ZwPiNA3PVYNkUP-Ipfw67CKnrAOk,23208 +torch/accelerator/__init__.py,sha256=3l4jREA8LduThkAUgvUqSEfaIlpVuRjDhtYI1olR5J0,11110 +torch/accelerator/__pycache__/__init__.cpython-312.pyc,, +torch/accelerator/__pycache__/_utils.cpython-312.pyc,, +torch/accelerator/__pycache__/graphs.cpython-312.pyc,, +torch/accelerator/__pycache__/memory.cpython-312.pyc,, +torch/accelerator/__pycache__/random.cpython-312.pyc,, +torch/accelerator/_utils.py,sha256=XFWOuGWu3vZQnWao4vfwkmgpFRGXB7xBtWxNLXjpotI,1895 +torch/accelerator/graphs.py,sha256=8lEdABUDNYwIj-V15ARMIYBDF41Uvf7HjvjlzcgOP5Q,6543 +torch/accelerator/memory.py,sha256=KzhBaF1wvDqwiW3o_OaoidhT5pl8rYTc2dCaDUocm3k,12137 +torch/accelerator/random.py,sha256=_1MExsRvYd3DrPc3jbdD3WpR_ADR0yZg6XnuwRY1BPc,2249 +torch/amp/__init__.py,sha256=aF4pqJDyiCzQbKC7V48k9isNZ7UYWSi8-dQWoh6bPIY,296 +torch/amp/__pycache__/__init__.cpython-312.pyc,, +torch/amp/__pycache__/autocast_mode.cpython-312.pyc,, +torch/amp/__pycache__/grad_scaler.cpython-312.pyc,, +torch/amp/autocast_mode.py,sha256=qSf1RUNbHOfPvidUwvRNoxaiNM9-qsVVqTJmcIrY2wM,22041 +torch/amp/grad_scaler.py,sha256=l8QR2gKNqvam7RXQa5sgwBdASEbbaCA74aWG4nbkQDk,31615 +torch/ao/__init__.py,sha256=IjlSW3F-e_I7LaPjnTudP8ZgPFhb2u8LIUAgUrA7cFg,663 +torch/ao/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/__init__.py,sha256=viPx3W-ac9BJhWOS_sXR9gj2x6-jvvLWQHm0ez3a0HQ,819 +torch/ao/nn/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/intrinsic/__init__.py,sha256=ITlruvBVPwekjWmQe2sjYUR9M7JGDWJOh8RjhcWGvgg,919 +torch/ao/nn/intrinsic/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/intrinsic/modules/__init__.py,sha256=iMiPdcvb2q60-eS-e3xUqyC_4iNdX3xM8RD10aH-2fo,641 +torch/ao/nn/intrinsic/modules/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/intrinsic/modules/__pycache__/fused.cpython-312.pyc,, +torch/ao/nn/intrinsic/modules/fused.py,sha256=SLik04JP3MXGwRND9lW1EjtqHSiFujwzAMmyi0-nxvo,11847 +torch/ao/nn/intrinsic/qat/__init__.py,sha256=M0iylhjuqtPcbO2pAVdDg9n9e1ET359nQ9txOEErmMo,37 +torch/ao/nn/intrinsic/qat/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/intrinsic/qat/modules/__init__.py,sha256=OIDHW4Q4Mjd_Y_eR1UWDLuPOVEIJOJJj5MbbaQRdI1A,547 +torch/ao/nn/intrinsic/qat/modules/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/intrinsic/qat/modules/__pycache__/conv_fused.cpython-312.pyc,, +torch/ao/nn/intrinsic/qat/modules/__pycache__/linear_fused.cpython-312.pyc,, +torch/ao/nn/intrinsic/qat/modules/__pycache__/linear_relu.cpython-312.pyc,, +torch/ao/nn/intrinsic/qat/modules/conv_fused.py,sha256=FHbEconqBIJUp7ymPaaMFN2H70ffSZk-ckNApY2kNzw,31861 +torch/ao/nn/intrinsic/qat/modules/linear_fused.py,sha256=iyJQ5Xir6QVzVpxImwYaValWbGEk3r09VKxDReWFiT4,6905 +torch/ao/nn/intrinsic/qat/modules/linear_relu.py,sha256=bZKak53c9vQNd_7Xnh10xeXyVZ8ymO6vVhch1TOPeeM,2184 +torch/ao/nn/intrinsic/quantized/__init__.py,sha256=AyOx7RavGaehtAWX6dEUBQcrl23h2_S3Q9ZAWYimCLQ,236 +torch/ao/nn/intrinsic/quantized/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/intrinsic/quantized/dynamic/__init__.py,sha256=M0iylhjuqtPcbO2pAVdDg9n9e1ET359nQ9txOEErmMo,37 +torch/ao/nn/intrinsic/quantized/dynamic/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/intrinsic/quantized/dynamic/modules/__init__.py,sha256=kbhh2dL33XSuVEAZNtSHMmt1papX7az6WlVALevMgZA,70 +torch/ao/nn/intrinsic/quantized/dynamic/modules/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/intrinsic/quantized/dynamic/modules/__pycache__/linear_relu.cpython-312.pyc,, +torch/ao/nn/intrinsic/quantized/dynamic/modules/linear_relu.py,sha256=ssjQbN6QOuUIfuROjVrqGupr9FiLbLGlq49fSLOQovI,2224 +torch/ao/nn/intrinsic/quantized/modules/__init__.py,sha256=8aofpYeXIA8WQaao5pvOjWtLnf4rmL9xlJO9hZ8aras,409 +torch/ao/nn/intrinsic/quantized/modules/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/intrinsic/quantized/modules/__pycache__/bn_relu.cpython-312.pyc,, +torch/ao/nn/intrinsic/quantized/modules/__pycache__/conv_add.cpython-312.pyc,, +torch/ao/nn/intrinsic/quantized/modules/__pycache__/conv_relu.cpython-312.pyc,, +torch/ao/nn/intrinsic/quantized/modules/__pycache__/linear_relu.cpython-312.pyc,, +torch/ao/nn/intrinsic/quantized/modules/bn_relu.py,sha256=5z1wesnwC49jVjLIWagOdmRW1s-Zhm41tS9tgL19tl8,3647 +torch/ao/nn/intrinsic/quantized/modules/conv_add.py,sha256=EX4p7WEeFsAkZ_4lqAi5rHaqJpBcz0Gj7i8A8j1Kaug,4821 +torch/ao/nn/intrinsic/quantized/modules/conv_relu.py,sha256=_aqBbU6SW8ddej_MH5u36vibx-QBWjS84VTbsckycBw,9575 +torch/ao/nn/intrinsic/quantized/modules/linear_relu.py,sha256=XpXdOcXMDYHN0cxE_bB02rTIZTv6EPjXagWnFxVOi8M,7144 +torch/ao/nn/qat/__init__.py,sha256=M0iylhjuqtPcbO2pAVdDg9n9e1ET359nQ9txOEErmMo,37 +torch/ao/nn/qat/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/qat/dynamic/__init__.py,sha256=M0iylhjuqtPcbO2pAVdDg9n9e1ET359nQ9txOEErmMo,37 +torch/ao/nn/qat/dynamic/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/qat/dynamic/modules/__init__.py,sha256=_5hfV0E5b71TgYVQPrPF9QZNrnw5XPuZppEwj0QItaM,50 +torch/ao/nn/qat/dynamic/modules/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/qat/dynamic/modules/__pycache__/linear.cpython-312.pyc,, +torch/ao/nn/qat/dynamic/modules/linear.py,sha256=XJJdSaclI87qBmSywWkcxmfqxqnav5M3nBtzN1ntgm0,1215 +torch/ao/nn/qat/modules/__init__.py,sha256=RmKZ7d0ds96EIRSqAGGTrDwuXVWerE_S_NCWuEuX_20,228 +torch/ao/nn/qat/modules/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/qat/modules/__pycache__/conv.cpython-312.pyc,, +torch/ao/nn/qat/modules/__pycache__/embedding_ops.cpython-312.pyc,, +torch/ao/nn/qat/modules/__pycache__/linear.cpython-312.pyc,, +torch/ao/nn/qat/modules/conv.py,sha256=p4Q_jIVoUv6Zwx6M7H1c7uCecwXjPeBEj_YFX2Pb-74,10082 +torch/ao/nn/qat/modules/embedding_ops.py,sha256=N29BQOpG7ZPrlB1H94lXEcIyXijb_N45iPMuKJNwqto,8345 +torch/ao/nn/qat/modules/linear.py,sha256=h_s7-_2lQfjymOVDJrgVVWwHicyWmcPqLCYsoYlRldY,3216 +torch/ao/nn/quantizable/__init__.py,sha256=M0iylhjuqtPcbO2pAVdDg9n9e1ET359nQ9txOEErmMo,37 +torch/ao/nn/quantizable/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/quantizable/modules/__init__.py,sha256=N6niR-YsfqqP_5a8ksCJ8BL-Ol1Mch_412g-I4Z8VeQ,145 +torch/ao/nn/quantizable/modules/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/quantizable/modules/__pycache__/activation.cpython-312.pyc,, +torch/ao/nn/quantizable/modules/__pycache__/rnn.cpython-312.pyc,, +torch/ao/nn/quantizable/modules/activation.py,sha256=XSZxfdqIWp3f2I_gl3TMDBpMl8e3LWPJ55CspHM3wLg,26225 +torch/ao/nn/quantizable/modules/rnn.py,sha256=k03thvONMgb7YVMko8CaPaAM76BYnb-GhpMTGGvvSVQ,22482 +torch/ao/nn/quantized/__init__.py,sha256=NtHecsYVtg9e1IhTCdvoXSV-oQEXRQnt54dZlScPo6I,686 +torch/ao/nn/quantized/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/quantized/__pycache__/functional.cpython-312.pyc,, +torch/ao/nn/quantized/dynamic/__init__.py,sha256=M0iylhjuqtPcbO2pAVdDg9n9e1ET359nQ9txOEErmMo,37 +torch/ao/nn/quantized/dynamic/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/quantized/dynamic/modules/__init__.py,sha256=VzgogVUFAj-yE8a5Vmjiq5TV3SP51t0wXslabLVPITw,413 +torch/ao/nn/quantized/dynamic/modules/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/quantized/dynamic/modules/__pycache__/conv.cpython-312.pyc,, +torch/ao/nn/quantized/dynamic/modules/__pycache__/linear.cpython-312.pyc,, +torch/ao/nn/quantized/dynamic/modules/__pycache__/rnn.cpython-312.pyc,, +torch/ao/nn/quantized/dynamic/modules/conv.py,sha256=Q7Y-mztiT-PVa473DKLLFR6Lg4SZp_eF4_8sitN6zH4,18343 +torch/ao/nn/quantized/dynamic/modules/linear.py,sha256=2mI1DjB2kVWl57shRpRli0wYMkB7ygqO1G45U4FBM3I,6495 +torch/ao/nn/quantized/dynamic/modules/rnn.py,sha256=c7RpiZTRAZZlo19YCsSmoYgmfGnfJmJ2LwDCChNgtWQ,51835 +torch/ao/nn/quantized/functional.py,sha256=9JpNmC6SNWIbOqyBCGSCghlWMr53Yamu7crAljJbsm8,29926 +torch/ao/nn/quantized/modules/__init__.py,sha256=Y56ItuRywBPBUWIROd3zxkrmrSr438EK-N71MT5i0Go,4661 +torch/ao/nn/quantized/modules/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/quantized/modules/__pycache__/activation.cpython-312.pyc,, +torch/ao/nn/quantized/modules/__pycache__/batchnorm.cpython-312.pyc,, +torch/ao/nn/quantized/modules/__pycache__/conv.cpython-312.pyc,, +torch/ao/nn/quantized/modules/__pycache__/dropout.cpython-312.pyc,, +torch/ao/nn/quantized/modules/__pycache__/embedding_ops.cpython-312.pyc,, +torch/ao/nn/quantized/modules/__pycache__/functional_modules.cpython-312.pyc,, +torch/ao/nn/quantized/modules/__pycache__/linear.cpython-312.pyc,, +torch/ao/nn/quantized/modules/__pycache__/normalization.cpython-312.pyc,, +torch/ao/nn/quantized/modules/__pycache__/rnn.cpython-312.pyc,, +torch/ao/nn/quantized/modules/__pycache__/utils.cpython-312.pyc,, +torch/ao/nn/quantized/modules/activation.py,sha256=C0GSs6WWHXAM4YKlZmxiYrarAonJIyjsNXqAVtkxht4,11670 +torch/ao/nn/quantized/modules/batchnorm.py,sha256=waZCeOapEFHC2pdFSFn1GYXcsEiW_uJ9nMX6xox0_fQ,4427 +torch/ao/nn/quantized/modules/conv.py,sha256=oADn2oxCFNbHlyS2k0hfpXsxfqmqpYFqSr4X-kdPdng,43809 +torch/ao/nn/quantized/modules/dropout.py,sha256=5nPYMBmjOyEzOZj0lz_CtUmJASXrrEr63YJnVytPTQs,806 +torch/ao/nn/quantized/modules/embedding_ops.py,sha256=-ZkgOJiVc7P1Ht01uo4UA-DKcEW_TTdN3FxnojdqYwM,15333 +torch/ao/nn/quantized/modules/functional_modules.py,sha256=DCA34ufixknSkyGVPySPmTcSRTb_MVLjQishnAA-Zjo,9309 +torch/ao/nn/quantized/modules/linear.py,sha256=adIyE-xeyBz14S75Yqizy7nUM4v8jJplEsdAGQ3CUVI,13689 +torch/ao/nn/quantized/modules/normalization.py,sha256=zFTgY6ABpezWNjWEoHnl09qgLGlNJVrxxznhRecYP5g,9539 +torch/ao/nn/quantized/modules/rnn.py,sha256=gH1nq8M2l5Ie2nPBaY8ap91OmPlDAYSwjc_RU98vbdM,2026 +torch/ao/nn/quantized/modules/utils.py,sha256=Oss19Ep77mjNFKzhLda5rRxiFrr-1FrTygrDKOy8vQs,4693 +torch/ao/nn/quantized/reference/__init__.py,sha256=hu3hyozMJtkc86Bu1v8tmyayuxAdeDSv0sUiOeNAr_s,284 +torch/ao/nn/quantized/reference/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/quantized/reference/modules/__init__.py,sha256=YS8MYKlqBPoA2UEBcS-MgbOzZ8_HDp-7ET4BC7KtCBk,494 +torch/ao/nn/quantized/reference/modules/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/quantized/reference/modules/__pycache__/conv.cpython-312.pyc,, +torch/ao/nn/quantized/reference/modules/__pycache__/linear.cpython-312.pyc,, +torch/ao/nn/quantized/reference/modules/__pycache__/rnn.cpython-312.pyc,, +torch/ao/nn/quantized/reference/modules/__pycache__/sparse.cpython-312.pyc,, +torch/ao/nn/quantized/reference/modules/__pycache__/utils.cpython-312.pyc,, +torch/ao/nn/quantized/reference/modules/conv.py,sha256=XxZfpM20-QJOjj6n9w6bIeSD_0LGmyl-py1uTTZIOww,16049 +torch/ao/nn/quantized/reference/modules/linear.py,sha256=oxH2CSsE_asNpObp2CUQjDsqsgSWDHeMHK9p2EF4834,2254 +torch/ao/nn/quantized/reference/modules/rnn.py,sha256=ebq8wd2VYrX7jqWcmW4BQwNMOtGSwD_9q8hE12DVzYo,29953 +torch/ao/nn/quantized/reference/modules/sparse.py,sha256=glgaM9jAtZt9FIqrCBJel32K0KDtk8p9k1K02F4Jcos,4683 +torch/ao/nn/quantized/reference/modules/utils.py,sha256=aOqOOq75IqlUgcioarrOqDGyx0i06KYi_jt6a1wD9Mc,15604 +torch/ao/nn/sparse/__init__.py,sha256=PfB-tgPOelyV_0eb_ipJK4LzPHwB5Z-wfJXeE_O3AK4,24 +torch/ao/nn/sparse/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/sparse/quantized/__init__.py,sha256=xO8RdXEcj7ggZh7-f2bReVBRO-F6PNBZjb5DBPwV52w,168 +torch/ao/nn/sparse/quantized/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/sparse/quantized/__pycache__/linear.cpython-312.pyc,, +torch/ao/nn/sparse/quantized/__pycache__/utils.cpython-312.pyc,, +torch/ao/nn/sparse/quantized/dynamic/__init__.py,sha256=lYDGtZ8rNR56jJLk6s5WOJ65E7qqQ_LFICpuD76NWYI,57 +torch/ao/nn/sparse/quantized/dynamic/__pycache__/__init__.cpython-312.pyc,, +torch/ao/nn/sparse/quantized/dynamic/__pycache__/linear.cpython-312.pyc,, +torch/ao/nn/sparse/quantized/dynamic/linear.py,sha256=ZV7BlimowKVu6jDBsDQecdlOI4JcBMwLT4X4WE650uE,6956 +torch/ao/nn/sparse/quantized/linear.py,sha256=-kpbqePTgr4lfjNKfAOYQm_7-3S9iEBRLEBD2emE_hs,10150 +torch/ao/nn/sparse/quantized/utils.py,sha256=fU0jKT2k7i8On6fgx1QEFxyzY2_3XuqjcH9Qw-PD3As,2234 +torch/ao/ns/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/ao/ns/__pycache__/__init__.cpython-312.pyc,, +torch/ao/ns/__pycache__/_numeric_suite.cpython-312.pyc,, +torch/ao/ns/__pycache__/_numeric_suite_fx.cpython-312.pyc,, +torch/ao/ns/_numeric_suite.py,sha256=fPy3eN33wImLp8FFODnH3byzxukzA-GJXQjP0hRnASc,20065 +torch/ao/ns/_numeric_suite_fx.py,sha256=FB23FPdq3xeOoV-K27ow2equHsQ3WZ-cCk3QH59h2wg,41390 +torch/ao/ns/fx/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/ao/ns/fx/__pycache__/__init__.cpython-312.pyc,, +torch/ao/ns/fx/__pycache__/graph_matcher.cpython-312.pyc,, +torch/ao/ns/fx/__pycache__/graph_passes.cpython-312.pyc,, +torch/ao/ns/fx/__pycache__/mappings.cpython-312.pyc,, +torch/ao/ns/fx/__pycache__/n_shadows_utils.cpython-312.pyc,, +torch/ao/ns/fx/__pycache__/ns_types.cpython-312.pyc,, +torch/ao/ns/fx/__pycache__/pattern_utils.cpython-312.pyc,, +torch/ao/ns/fx/__pycache__/qconfig_multi_mapping.cpython-312.pyc,, +torch/ao/ns/fx/__pycache__/utils.cpython-312.pyc,, +torch/ao/ns/fx/__pycache__/weight_utils.cpython-312.pyc,, +torch/ao/ns/fx/graph_matcher.py,sha256=_1DKursxX_YdJTq3fPwmeSN7ZxHp7UGJYlLTBSZbv9U,20047 +torch/ao/ns/fx/graph_passes.py,sha256=MuE5sjb6TFNlO4QFTvpffEG2176fA_BmPSY1Kks9ac0,45742 +torch/ao/ns/fx/mappings.py,sha256=I3ZnL73L2BTNVhhI9cR7GL-mgjjLx18f5n76XoFBt2o,18446 +torch/ao/ns/fx/n_shadows_utils.py,sha256=AhFINslb8lFBqWe_h4EqTHxE4gHdWlvE0jR0aSA0qqM,53160 +torch/ao/ns/fx/ns_types.py,sha256=8BL1eChSs_jwmCENUoe8xGmdQp5wS8qQEm3GHKa_T2U,2341 +torch/ao/ns/fx/pattern_utils.py,sha256=WtGUdI0Zq0KRyiqUrydNW9LWFHYTcJIUqGH7gD-Tp4Q,8652 +torch/ao/ns/fx/qconfig_multi_mapping.py,sha256=q4SF9lmy89wQ-YFxHJgurdwfiKBn0hRPVk1ZWCvE0nA,10197 +torch/ao/ns/fx/utils.py,sha256=uis_EdC0KkKlZD_xUgeN8o3w7hH0_462LmC925gL8Y8,22789 +torch/ao/ns/fx/weight_utils.py,sha256=mkhs5U5qrV_MIKelp_OAOaljhb1_kabt1NF_0gdVGik,12786 +torch/ao/pruning/__init__.py,sha256=dp2CA7CO_FRHTE7E0Ft495uR5IlUi8HsnG8ujLsz6OA,640 +torch/ao/pruning/__pycache__/__init__.cpython-312.pyc,, +torch/ao/pruning/__pycache__/_mappings.cpython-312.pyc,, +torch/ao/pruning/_experimental/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/ao/pruning/_experimental/__pycache__/__init__.cpython-312.pyc,, +torch/ao/pruning/_experimental/activation_sparsifier/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/ao/pruning/_experimental/activation_sparsifier/__pycache__/__init__.cpython-312.pyc,, +torch/ao/pruning/_experimental/activation_sparsifier/__pycache__/activation_sparsifier.cpython-312.pyc,, +torch/ao/pruning/_experimental/activation_sparsifier/activation_sparsifier.py,sha256=7w47yWCx7DMg0mrzK4e7Ergu6BSeL_eIrc76EoRoNe0,19304 +torch/ao/pruning/_experimental/data_scheduler/__init__.py,sha256=q_95mAMpHldGWwLAgYS-F07ReGKDLIAZLsP7BtlmgTE,92 +torch/ao/pruning/_experimental/data_scheduler/__pycache__/__init__.cpython-312.pyc,, +torch/ao/pruning/_experimental/data_scheduler/__pycache__/base_data_scheduler.cpython-312.pyc,, +torch/ao/pruning/_experimental/data_scheduler/base_data_scheduler.py,sha256=ZbwSY0XJSrlx-xMUe2t_wcg03zD8kcMcDJI5WTWUtEQ,7730 +torch/ao/pruning/_experimental/data_sparsifier/__init__.py,sha256=9ktAif-dttGBmiw745tN2WtUTOTZch0E_HA4cE1bfTo,174 +torch/ao/pruning/_experimental/data_sparsifier/__pycache__/__init__.cpython-312.pyc,, +torch/ao/pruning/_experimental/data_sparsifier/__pycache__/base_data_sparsifier.cpython-312.pyc,, +torch/ao/pruning/_experimental/data_sparsifier/__pycache__/data_norm_sparsifier.cpython-312.pyc,, +torch/ao/pruning/_experimental/data_sparsifier/__pycache__/quantization_utils.cpython-312.pyc,, +torch/ao/pruning/_experimental/data_sparsifier/base_data_sparsifier.py,sha256=vS87qKFjApFNfQCt9UjYB3dVpH9AyoEcqLAVQyhCq34,13549 +torch/ao/pruning/_experimental/data_sparsifier/data_norm_sparsifier.py,sha256=MJKZbpxBV0WbkzoGj_O3zkGDIL80hJXWVQLF8p-xB4E,7779 +torch/ao/pruning/_experimental/data_sparsifier/lightning/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/ao/pruning/_experimental/data_sparsifier/lightning/__pycache__/__init__.cpython-312.pyc,, +torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/__init__.cpython-312.pyc,, +torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/_data_sparstity_utils.cpython-312.pyc,, +torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__pycache__/data_sparsity.cpython-312.pyc,, +torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/_data_sparstity_utils.py,sha256=Vtb__BJ_qrCy7TBisG4BM8qNXzDYrl-xNDVLbHCsYIY,1636 +torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/data_sparsity.py,sha256=QBEcA2SQg7QiEwXO3jlD_uRBGnN6AZaapjpNK1KN-5o,6597 +torch/ao/pruning/_experimental/data_sparsifier/quantization_utils.py,sha256=aXP_h7BI14TBiS9K47seXwL5Bko28M64cBo1AHoBQAc,6203 +torch/ao/pruning/_experimental/pruner/FPGM_pruner.py,sha256=vrdOTXSh3-VwhHeIjk9Wu1dVgZr_hT_WclGakuqjEdo,3424 +torch/ao/pruning/_experimental/pruner/__init__.py,sha256=abfUoG48Kc6ddQZmFAkYjQH5J8Hae8xJiqxz89MTgDE,260 +torch/ao/pruning/_experimental/pruner/__pycache__/FPGM_pruner.cpython-312.pyc,, +torch/ao/pruning/_experimental/pruner/__pycache__/__init__.cpython-312.pyc,, +torch/ao/pruning/_experimental/pruner/__pycache__/base_structured_sparsifier.cpython-312.pyc,, +torch/ao/pruning/_experimental/pruner/__pycache__/lstm_saliency_pruner.cpython-312.pyc,, +torch/ao/pruning/_experimental/pruner/__pycache__/match_utils.cpython-312.pyc,, +torch/ao/pruning/_experimental/pruner/__pycache__/parametrization.cpython-312.pyc,, +torch/ao/pruning/_experimental/pruner/__pycache__/prune_functions.cpython-312.pyc,, +torch/ao/pruning/_experimental/pruner/__pycache__/saliency_pruner.cpython-312.pyc,, +torch/ao/pruning/_experimental/pruner/base_structured_sparsifier.py,sha256=8ThuyadcbX6SNuzO0gEMK7okMCR2IWxziue0xzuTY-Q,11029 +torch/ao/pruning/_experimental/pruner/lstm_saliency_pruner.py,sha256=nBliDOjjzo42r3g6yj5q9qq4tbSLg2e_bwc1KiHA9L4,2197 +torch/ao/pruning/_experimental/pruner/match_utils.py,sha256=PLY0zuh1dWLCtLwmhAgXv0h5WDzCjXJZMM7UNRFNuO4,1949 +torch/ao/pruning/_experimental/pruner/parametrization.py,sha256=STi6v3pIwXKT3nEz1h6BRYx--sVQ2d70Sxj7OEfimU8,2044 +torch/ao/pruning/_experimental/pruner/prune_functions.py,sha256=EWmB1kkbMoxubYH9Y1gvKViCduks2KwJA2bgEgUWGuw,19280 +torch/ao/pruning/_experimental/pruner/saliency_pruner.py,sha256=ZKEqH_f7dBc7cuaXodG8ddxYSHqLGfrxS_6djVKu2aw,1539 +torch/ao/pruning/_mappings.py,sha256=O9aJePj2X0nV76KTcSU93V7GA8dxEzfr5G9QvjyWOqQ,597 +torch/ao/pruning/scheduler/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/ao/pruning/scheduler/__pycache__/__init__.cpython-312.pyc,, +torch/ao/pruning/scheduler/__pycache__/base_scheduler.cpython-312.pyc,, +torch/ao/pruning/scheduler/__pycache__/cubic_scheduler.cpython-312.pyc,, +torch/ao/pruning/scheduler/__pycache__/lambda_scheduler.cpython-312.pyc,, +torch/ao/pruning/scheduler/base_scheduler.py,sha256=IipBI2JjzC5ah4ocvY5mfNjWfJMLAyzWgjyIR6BmxNM,6625 +torch/ao/pruning/scheduler/cubic_scheduler.py,sha256=9j4ifJT9lavz1pCgulfgpHgHaasvx_KkqNwqCE1_NC8,3875 +torch/ao/pruning/scheduler/lambda_scheduler.py,sha256=ztFUy3RecZ5JhkDfOUg1JNVd9qnm59LqdUxoKumVrvQ,2416 +torch/ao/pruning/sparsifier/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/ao/pruning/sparsifier/__pycache__/__init__.cpython-312.pyc,, +torch/ao/pruning/sparsifier/__pycache__/base_sparsifier.cpython-312.pyc,, +torch/ao/pruning/sparsifier/__pycache__/nearly_diagonal_sparsifier.cpython-312.pyc,, +torch/ao/pruning/sparsifier/__pycache__/utils.cpython-312.pyc,, +torch/ao/pruning/sparsifier/__pycache__/weight_norm_sparsifier.cpython-312.pyc,, +torch/ao/pruning/sparsifier/base_sparsifier.py,sha256=LTHtuO2Y87uos7Aaj8AhTfO2koh50-BNd0MtefOza-8,13963 +torch/ao/pruning/sparsifier/nearly_diagonal_sparsifier.py,sha256=vKZbWhsxPzMDfk6ZntgIBncW81Vh19DisumzDWDhLUE,2263 +torch/ao/pruning/sparsifier/utils.py,sha256=8AAWdKgY1kYp6gzclTOC5QDMwImRVaWau1mJXpHvWu0,4994 +torch/ao/pruning/sparsifier/weight_norm_sparsifier.py,sha256=gIivd_Kyop1c_g5T9hWsYoI6CWC_Mcq1qTZO1P4EKzc,9351 +torch/ao/quantization/__init__.py,sha256=NnrycxUo3xBGvFsEPvI3wjjxY7YqR29fWQvDTPVMinc,6518 +torch/ao/quantization/__pycache__/__init__.cpython-312.pyc,, +torch/ao/quantization/__pycache__/_correct_bias.cpython-312.pyc,, +torch/ao/quantization/__pycache__/_equalize.cpython-312.pyc,, +torch/ao/quantization/__pycache__/_learnable_fake_quantize.cpython-312.pyc,, +torch/ao/quantization/__pycache__/fake_quantize.cpython-312.pyc,, +torch/ao/quantization/__pycache__/fuse_modules.cpython-312.pyc,, +torch/ao/quantization/__pycache__/fuser_method_mappings.cpython-312.pyc,, +torch/ao/quantization/__pycache__/observer.cpython-312.pyc,, +torch/ao/quantization/__pycache__/qconfig.cpython-312.pyc,, +torch/ao/quantization/__pycache__/qconfig_mapping.cpython-312.pyc,, +torch/ao/quantization/__pycache__/quant_type.cpython-312.pyc,, +torch/ao/quantization/__pycache__/quantization_mappings.cpython-312.pyc,, +torch/ao/quantization/__pycache__/quantize.cpython-312.pyc,, +torch/ao/quantization/__pycache__/quantize_fx.cpython-312.pyc,, +torch/ao/quantization/__pycache__/quantize_jit.cpython-312.pyc,, +torch/ao/quantization/__pycache__/stubs.cpython-312.pyc,, +torch/ao/quantization/__pycache__/utils.cpython-312.pyc,, +torch/ao/quantization/_correct_bias.py,sha256=tTf6RanT0gwmTkNfJrPGDCfcf8yHcpyGJ5HUm7UiB-Y,5415 +torch/ao/quantization/_equalize.py,sha256=WxGUxeLX9WpaEVExIqZu9LkRl_OcjzQZqoJAwKJNJ6I,9507 +torch/ao/quantization/_learnable_fake_quantize.py,sha256=o0VkrbUsv7uMr0jDMfga2pr-xU5XLcszvtEQDiv6h9I,7959 +torch/ao/quantization/backend_config/__init__.py,sha256=lnyxe_DTaYkdoSLhxNlUcMPlck2SAngmI8GNcYDHI4M,915 +torch/ao/quantization/backend_config/__pycache__/__init__.cpython-312.pyc,, +torch/ao/quantization/backend_config/__pycache__/_common_operator_config_utils.cpython-312.pyc,, +torch/ao/quantization/backend_config/__pycache__/_qnnpack_pt2e.cpython-312.pyc,, +torch/ao/quantization/backend_config/__pycache__/backend_config.cpython-312.pyc,, +torch/ao/quantization/backend_config/__pycache__/executorch.cpython-312.pyc,, +torch/ao/quantization/backend_config/__pycache__/fbgemm.cpython-312.pyc,, +torch/ao/quantization/backend_config/__pycache__/native.cpython-312.pyc,, +torch/ao/quantization/backend_config/__pycache__/onednn.cpython-312.pyc,, +torch/ao/quantization/backend_config/__pycache__/qnnpack.cpython-312.pyc,, +torch/ao/quantization/backend_config/__pycache__/tensorrt.cpython-312.pyc,, +torch/ao/quantization/backend_config/__pycache__/utils.cpython-312.pyc,, +torch/ao/quantization/backend_config/__pycache__/x86.cpython-312.pyc,, +torch/ao/quantization/backend_config/_common_operator_config_utils.py,sha256=DBXLnB_worvNycmCu8W67LvThYsjprp2a5E4ubrJO4Y,26829 +torch/ao/quantization/backend_config/_qnnpack_pt2e.py,sha256=gWiRsH3-MsvHah9aP0zKetnb8sJLEe1L6FZD7EWpk58,6305 +torch/ao/quantization/backend_config/backend_config.py,sha256=I65caYp3oiracD9g0HKRU9b39OxD2iTryccrjy5VeMY,31509 +torch/ao/quantization/backend_config/executorch.py,sha256=15eIF4t2amjMuNMsSbxpARA9AeLdRWGBNvR5Ppiwy-E,16546 +torch/ao/quantization/backend_config/fbgemm.py,sha256=dCsGDn-PbASye1CPf_9poNM6eOMN10_NUFTQat95-0Q,4208 +torch/ao/quantization/backend_config/native.py,sha256=xKBjjC-uZ8qZsbHluftqC6Tn9vo_6ivcsVYFWLFFQtQ,8242 +torch/ao/quantization/backend_config/onednn.py,sha256=UfxrHqdF5P2S05N49BuTFaFrB43hUC035oL9zbvIKWM,18884 +torch/ao/quantization/backend_config/qnnpack.py,sha256=PkPTzCS-Q3p8MiUq6mytJlFt-Zox7AO2kxbTg5Qx-AU,5400 +torch/ao/quantization/backend_config/tensorrt.py,sha256=Drb7vD3gWVGnSa41C6rYVR7po0qA420Nu3hoOH483-A,3021 +torch/ao/quantization/backend_config/utils.py,sha256=u4IVFS4fdeQt5Aok9QcL7WlwuJ45fxny-xsvjNJrIYo,12641 +torch/ao/quantization/backend_config/x86.py,sha256=4geWLr6mkFhSEYiXFXpkB8NegS05EXhv2fYHTpajNyg,3869 +torch/ao/quantization/fake_quantize.py,sha256=N8mOXz8mzvIfcoEA101XI4ULp3laaYPbOo18UasGAbM,23466 +torch/ao/quantization/fuse_modules.py,sha256=fBhqELU4N8hFcKa2SxS31xPx3rkssxjS2Yr60C_4vAM,6794 +torch/ao/quantization/fuser_method_mappings.py,sha256=a_NvrSR1sxF-CJKIqoYm5Of0u2C__HgcjVuyJf_ibzw,10947 +torch/ao/quantization/fx/__init__.py,sha256=65h6iR_5XARcYpGS8A2qRza_2y7cvqCowqkwwziYz8M,81 +torch/ao/quantization/fx/__pycache__/__init__.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/_decomposed.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/_equalize.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/_lower_to_native_backend.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/convert.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/custom_config.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/fuse.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/fuse_handler.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/graph_module.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/lower_to_fbgemm.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/lower_to_qnnpack.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/lstm_utils.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/match_utils.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/pattern_utils.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/prepare.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/qconfig_mapping_utils.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/quantize_handler.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/tracer.cpython-312.pyc,, +torch/ao/quantization/fx/__pycache__/utils.cpython-312.pyc,, +torch/ao/quantization/fx/_decomposed.py,sha256=TLoLUJIye9Sm7S4Q6-xyeH6H0YDbUSDU3BBIeLY7D9o,44280 +torch/ao/quantization/fx/_equalize.py,sha256=bDSDlA7gVeXfyA_aTGasabM_6SgJ0jJOtcoJGXcE8K4,40830 +torch/ao/quantization/fx/_lower_to_native_backend.py,sha256=rELWM0fGLdqaZAI-McQLbVq02lqSyiNpvIc412ag9us,57120 +torch/ao/quantization/fx/_model_report/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/ao/quantization/fx/_model_report/__pycache__/__init__.cpython-312.pyc,, +torch/ao/quantization/fx/_model_report/__pycache__/detector.cpython-312.pyc,, +torch/ao/quantization/fx/_model_report/__pycache__/model_report.cpython-312.pyc,, +torch/ao/quantization/fx/_model_report/__pycache__/model_report_observer.cpython-312.pyc,, +torch/ao/quantization/fx/_model_report/__pycache__/model_report_visualizer.cpython-312.pyc,, +torch/ao/quantization/fx/_model_report/detector.py,sha256=O5tZuy6qM1fODhMN55fwSt8YbwtuLwjJiOURTz0m0Cw,76883 +torch/ao/quantization/fx/_model_report/model_report.py,sha256=C8Jlw2Z1lCRVxTD5odGWZXdTy-Cec0V_OdSz_k7gK8E,29740 +torch/ao/quantization/fx/_model_report/model_report_observer.py,sha256=BWuxgjbh5Egg1xxq9eIQt3v8gDbxM28AQmhG0N1jUG0,12084 +torch/ao/quantization/fx/_model_report/model_report_visualizer.py,sha256=_Vlgy_DwmjdJGXjGYy_ISrxkTGL5UMumeO6R0QXZXs0,32661 +torch/ao/quantization/fx/convert.py,sha256=BLUpWk2wlgArcNdYauviSk-x1fcSngIwFfY82tM11OQ,60079 +torch/ao/quantization/fx/custom_config.py,sha256=XXczvULZT7A6u8av5PMmgy94viHeOslT73lceU_8N1s,21815 +torch/ao/quantization/fx/fuse.py,sha256=pMxYdgQBYHgNrk5AUOiaaUXyJryX0NeoFJjRrJNtAbs,7396 +torch/ao/quantization/fx/fuse_handler.py,sha256=KlI4Gk2e5bc_8Whfkib45iWLffWnPSU2qvU0QA3-umw,4704 +torch/ao/quantization/fx/graph_module.py,sha256=FKt-w5-C8rL3uFTRacHpvsqugFMo-pLipybtXFankko,6593 +torch/ao/quantization/fx/lower_to_fbgemm.py,sha256=ERyoustxB5yjBVinb4V2_YTZF-76c7NaPxaVP2l_Pbs,602 +torch/ao/quantization/fx/lower_to_qnnpack.py,sha256=pSLRhkHuxXdbu7a1yEzQPbomFrepOvfiKWpg4HNqEYw,527 +torch/ao/quantization/fx/lstm_utils.py,sha256=dFESL358seHZX4XU46mGv57PouGbmJEh67Iid-cldBA,10544 +torch/ao/quantization/fx/match_utils.py,sha256=fKW4f3YavhquBHtPWdpp6aIp6AtZx17ubkRyeN29Bus,8963 +torch/ao/quantization/fx/pattern_utils.py,sha256=aMM87O63tKrgnLtuAIPEPNXApbzTxL4SIOvyWZTofJI,3668 +torch/ao/quantization/fx/prepare.py,sha256=mIWA4FNGFRmj-S3nfTu3ysZ_tm76rAzBmmSRHq9ewyI,87578 +torch/ao/quantization/fx/qconfig_mapping_utils.py,sha256=yGl3Bpb6nGqM9WswYDKlCK2kaxpJ6znTXmcxC3T5scU,15425 +torch/ao/quantization/fx/quantize_handler.py,sha256=jFTXAjdLTYb1MGic0nZDngYmEfHSh_sTbjDCJGorGUU,7325 +torch/ao/quantization/fx/tracer.py,sha256=2haqkImWeOrUUr7V_b_bgYwuIhU6GFHKEY4edqmUJ4M,1737 +torch/ao/quantization/fx/utils.py,sha256=hm0pM8Bsh_OMbUQ5MqJMPieKrL9mhvL1cM7wwo20IsM,38802 +torch/ao/quantization/observer.py,sha256=DXKVhXhwvN1IWtOBSKgWBt3pjgiHO-1Y2eFTX23To9c,80449 +torch/ao/quantization/qconfig.py,sha256=ky-hewCl0RDB76kj3ti-AXCSiZ2MZNey8VaCfLdwKWE,24629 +torch/ao/quantization/qconfig_mapping.py,sha256=PxVXgzIUuicmlxo_fMQrxK3eh3NMDsRqg0AVU4a1SDQ,14846 +torch/ao/quantization/quant_type.py,sha256=fY7JDEr_PzBFymxy9fQmnRIFKiQoL2QoKJtxZKSJsoc,760 +torch/ao/quantization/quantization_mappings.py,sha256=D4VVaBiBJFBczGu36OapTGGrFPXrBqjTz2bOUNDMYXI,13861 +torch/ao/quantization/quantize.py,sha256=uQqliXfXQQ-jkMN53lxb6ySBRYTO1Xq15_-eWVMnH8I,31393 +torch/ao/quantization/quantize_fx.py,sha256=fK1Xug8MqSc_9RSCJUakXqTe_ohppPbyqhvKUkoN8y4,32436 +torch/ao/quantization/quantize_jit.py,sha256=fFAk6nvHIxGyov6Q0eYFUQ4avFGyNMFtdL3yv-Li1H4,14700 +torch/ao/quantization/stubs.py,sha256=V-AJl3upvDL1qiTDdTBT7kJfdQ4rwFJT_UG1-A0oEP8,2282 +torch/ao/quantization/utils.py,sha256=TYHyK_JRUyGn4j6UvqpApEbDTL5X5Ni56ZAmSGXo6lI,29609 +torch/autograd/__init__.py,sha256=zgLggPy4Z_glIyqRVr8oEXge4AD4MmJI-H2YMvkiDb4,29602 +torch/autograd/__pycache__/__init__.cpython-312.pyc,, +torch/autograd/__pycache__/anomaly_mode.cpython-312.pyc,, +torch/autograd/__pycache__/forward_ad.cpython-312.pyc,, +torch/autograd/__pycache__/function.cpython-312.pyc,, +torch/autograd/__pycache__/functional.cpython-312.pyc,, +torch/autograd/__pycache__/grad_mode.cpython-312.pyc,, +torch/autograd/__pycache__/gradcheck.cpython-312.pyc,, +torch/autograd/__pycache__/graph.cpython-312.pyc,, +torch/autograd/__pycache__/profiler.cpython-312.pyc,, +torch/autograd/__pycache__/profiler_legacy.cpython-312.pyc,, +torch/autograd/__pycache__/profiler_util.cpython-312.pyc,, +torch/autograd/__pycache__/variable.cpython-312.pyc,, +torch/autograd/_functions/__init__.py,sha256=sdKJj6Dia1vNRSolyufzRKdn5qHkgCBCUI3OBm-PGW0,36 +torch/autograd/_functions/__pycache__/__init__.cpython-312.pyc,, +torch/autograd/_functions/__pycache__/tensor.cpython-312.pyc,, +torch/autograd/_functions/__pycache__/utils.cpython-312.pyc,, +torch/autograd/_functions/tensor.py,sha256=8SJkduO10ftxiPMbTlr_l8Vb9rluVnuZWQNaVBpxW0E,2496 +torch/autograd/_functions/utils.py,sha256=XSfqpnmJKm2LuoVc2FVFms4wV3hJxMhFrfbCAytX2JY,753 +torch/autograd/anomaly_mode.py,sha256=pZukS-vf8PiLaOfC6HWIzL6uwUeo_71VY5M5_utMzJs,4882 +torch/autograd/forward_ad.py,sha256=KJrfjbuZjwEfvhiYUr2flZMcD-NsEpIqrKqod7luSiM,8030 +torch/autograd/function.py,sha256=SGonUX9w4tS2Vf4oF2Nwvk9n1w8TylPoB5sTxFRcMjA,36529 +torch/autograd/functional.py,sha256=v_v5XIf2fMNkuOGiWTMrDPe4xg_tLOqZ-QsX0OA8Z1k,53402 +torch/autograd/grad_mode.py,sha256=3cMsLMLfpeIyD4yOdbfQSMdmHFjhyfcwSRSiJ0TiF38,16964 +torch/autograd/gradcheck.py,sha256=y3SPwzxWq8EVrXIwtCLCMQ02_5ag6SHlnuOlcpsQwYM,92799 +torch/autograd/graph.py,sha256=YnfmANYcD8L6qmJ8e0aQtR0dZwRfxLN1iwT8hSfMMt4,41864 +torch/autograd/profiler.py,sha256=woxjUfWZ0bWHCxurnMeCqw83XHZ36Uezh4IFzbqtf4c,56741 +torch/autograd/profiler_legacy.py,sha256=7MLdb4wNGuoalcvk-Ohj1dGVGUauo5OweEYLGmyTgeQ,12210 +torch/autograd/profiler_util.py,sha256=NCwYobuxRYXzU3iy4KcMGkyJ0L3SJk1Gaz64TyspvhI,62788 +torch/autograd/variable.py,sha256=N0cAiO8ZPZ6rtRtU-hJYH_6NVt-zun16CmO_KrZV7-0,391 +torch/backends/__init__.py,sha256=wNSGGZPEL2dEb6YLC25-l0WumRcFK31vCuvdoYk237c,3622 +torch/backends/__pycache__/__init__.cpython-312.pyc,, +torch/backends/_coreml/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/backends/_coreml/__pycache__/__init__.cpython-312.pyc,, +torch/backends/_coreml/__pycache__/preprocess.cpython-312.pyc,, +torch/backends/_coreml/preprocess.py,sha256=Nzzwas90UYSckQQuyjMWDFuzlva73YNGQd4JUCS3VKc,4508 +torch/backends/_nnapi/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/backends/_nnapi/__pycache__/__init__.cpython-312.pyc,, +torch/backends/_nnapi/__pycache__/prepare.cpython-312.pyc,, +torch/backends/_nnapi/__pycache__/serializer.cpython-312.pyc,, +torch/backends/_nnapi/prepare.py,sha256=2t_-EEWffVa7PatU-5BZ_ZiqPemCBjwBBmhbBidE-Oc,6975 +torch/backends/_nnapi/serializer.py,sha256=K6F1nNWyLX_tjrgpDMhmFt_kG_pvYibnjmHOdWvfmrY,101805 +torch/backends/cpu/__init__.py,sha256=V3lRML9bHlNvfE5iOHJP9kN-P4WvEN23SeGQLLDYEnM,314 +torch/backends/cpu/__pycache__/__init__.cpython-312.pyc,, +torch/backends/cuda/__init__.py,sha256=qjalN_H76pKSBpt7jM5Spe9MXzVLcxZUSKHKmrEW2B4,26347 +torch/backends/cuda/__pycache__/__init__.cpython-312.pyc,, +torch/backends/cudnn/__init__.py,sha256=3NBQOlus6Zh9ytFaIoYlDFSJcNHxsc3Ml1yJINB5IZ8,8614 +torch/backends/cudnn/__pycache__/__init__.cpython-312.pyc,, +torch/backends/cudnn/__pycache__/rnn.cpython-312.pyc,, +torch/backends/cudnn/rnn.py,sha256=htRqSHrfhnkLFE-Rpg67jk9OCAriEbSCAsb3VxetaFI,4122 +torch/backends/cusparselt/__init__.py,sha256=LCf7CAhlOka2FofcBZP5gh05-3bzf4VtxmwPA9IFdek,1273 +torch/backends/cusparselt/__pycache__/__init__.cpython-312.pyc,, +torch/backends/kleidiai/__init__.py,sha256=V5pt-IFG6zqGlgzrLQVDOakig9WD1QhZbl1AsfkDgTU,162 +torch/backends/kleidiai/__pycache__/__init__.cpython-312.pyc,, +torch/backends/mha/__init__.py,sha256=tUmUrm0Z3I5dnDnhSbuDgZifGDemdgPrdQdsokvVssA,718 +torch/backends/mha/__pycache__/__init__.cpython-312.pyc,, +torch/backends/miopen/__init__.py,sha256=T9aQ5QNnKy9jBHXRZZQD3E3sQ_lbPFYkYx5gX7VRGTU,1208 +torch/backends/miopen/__pycache__/__init__.cpython-312.pyc,, +torch/backends/mkl/__init__.py,sha256=knXrTfpLjP_371pp4V3Qzinf3nBw8MWrRqaLvp5taEA,1823 +torch/backends/mkl/__pycache__/__init__.cpython-312.pyc,, +torch/backends/mkldnn/__init__.py,sha256=V0rvGEXMkw59IzPQitu99ayW9nVbGaTBVx6nLZ0JyDo,4388 +torch/backends/mkldnn/__pycache__/__init__.cpython-312.pyc,, +torch/backends/mps/__init__.py,sha256=Qa1BlYQGDePexiXmS1GiRwJOh6Rj1JDGwOXnpZ8kxtI,1618 +torch/backends/mps/__pycache__/__init__.cpython-312.pyc,, +torch/backends/nnpack/__init__.py,sha256=6cApdM4SVAbns4TuVAuFI9sXskhu7piYVsmP4rqpdOA,837 +torch/backends/nnpack/__pycache__/__init__.cpython-312.pyc,, +torch/backends/openmp/__init__.py,sha256=h6ebEMpGQavTuGZ3eJVK4JMUMMUgTYcrmvHxh_Fcgy8,157 +torch/backends/openmp/__pycache__/__init__.cpython-312.pyc,, +torch/backends/opt_einsum/__init__.py,sha256=xdL9w-v1UteyrJPFvVheYlxNqeTB7Z2HLpanp5mgMkw,3836 +torch/backends/opt_einsum/__pycache__/__init__.cpython-312.pyc,, +torch/backends/python_native/__init__.py,sha256=G12WzOyeqVPDEkdW8aaPs2rtFRV4KJf-REW65Xmwdg8,13003 +torch/backends/python_native/__pycache__/__init__.cpython-312.pyc,, +torch/backends/quantized/__init__.py,sha256=vD2Ds81mKtQGrMrAYy1FAo_OPfyzvhDObF276kT_t-U,1861 +torch/backends/quantized/__pycache__/__init__.cpython-312.pyc,, +torch/backends/xeon/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/backends/xeon/__pycache__/__init__.cpython-312.pyc,, +torch/backends/xeon/__pycache__/run_cpu.cpython-312.pyc,, +torch/backends/xeon/run_cpu.py,sha256=5GiPNMIe2LHXvsfZLk2MCbNRQTMeMwuWOA4gJS06Sig,42284 +torch/backends/xnnpack/__init__.py,sha256=BNL7CNyTlaTNxu4JVDE8VZgiu16mRO6JpZeQ0Ns3Nr8,702 +torch/backends/xnnpack/__pycache__/__init__.cpython-312.pyc,, +torch/bin/FileStoreTest,sha256=euTFQqDV00jadvTDAQHX_cuXdREZylxp0ojoXtPLdJc,623896 +torch/bin/HashStoreTest,sha256=oxR2eBGXor1DT2WTFrjKh4MkNmI2oSKBoT6AhYjj_GI,629792 +torch/bin/TCPStoreTest,sha256=odGN2JSuQ48glG39s8EPMGUvyFUoVxlPClowtbB81d4,687304 +torch/bin/protoc,sha256=hmqeZqQrJ2S1-dYLy16fvTcKm7yfwKFiHNVNJFzm5wM,5463672 +torch/bin/protoc-3.21.12.0,sha256=hmqeZqQrJ2S1-dYLy16fvTcKm7yfwKFiHNVNJFzm5wM,5463672 +torch/bin/script_module_v4.ptl,sha256=3q1JkA4huwQzm_BsFJaN59KmUaNznMscjoipIJ9ugq0,2573 +torch/bin/test_aoti_abi_check,sha256=2Ghv6e8bYRDdMBOQQz2ITOWIbNBwKZlZQ-3Aq6UjlpQ,1363824 +torch/bin/test_api,sha256=QVAKsNIF5wGdhc0NPngPgXUISu3IUjewfECbsnnw9iE,15106616 +torch/bin/test_comms_id,sha256=tAATnTUNhDCx_pslnE4dxOB-_d5NxLCDaQgYWX_mBpw,677384 +torch/bin/test_cpp_rpc,sha256=vmqJJ5C17u_PjVmmSpu33fPQ2cnLw2tHjali9VOxX5E,790168 +torch/bin/test_dist_autograd,sha256=tq_DHg-RUOqVlnbJ5ElMiwGGqs1Q-AFJnkIEKVtmgRY,651136 +torch/bin/test_global_state_manager,sha256=nGYszIXSYClov0IXQc2ueO-KZWp_TfTYZ5MK7FChdgw,631912 +torch/bin/test_interpreter_async.pt,sha256=VJ0EuYpoO3nxxYMaWtkitWMxGkIWtaLCgiYYJ5A2iyE,2840 +torch/bin/test_jit,sha256=TaTHy60NnIdUX6QyWm5ysl0IqkMy89stpzfb8Grxht0,13435808 +torch/bin/test_lazy,sha256=HkuNR_DTGdulJYgGL3Xl23itTp548B-zydt1hbLEwcQ,4960104 +torch/bin/test_privateuse1_profiler,sha256=an7nS9eO5wnDv9BCV4vh0dlpveQG1FHPd0mfhIrxZV0,616880 +torch/bin/test_profiler_collection,sha256=SlAw9LYg69k8sXLcYPlp7_sdckb0tvq2vp7KaSRYJHk,1068192 +torch/bin/test_profiler_global_callback_stale_session,sha256=j5uzDcVDnKJAFoEdD9vBdRHSs3z2G-4unjN1NbyybEI,600432 +torch/bin/test_shim,sha256=2Zo_ePtLJTsh771oGDN6XvHKxHdo5UNp9E1MGbEC-_Q,630280 +torch/bin/torch_shm_manager,sha256=yICpaGNC38bJ6VOuj8gauhULODU7KNsUMh-lBdbyh6A,44208 +torch/bin/upgrader_models/test_versioned_div_scalar_float_v2.ptl,sha256=kTYN_cUF3gX6xpuXHvigait1tGjgpmzy20BPxQ8hAoE,2160 +torch/bin/upgrader_models/test_versioned_div_scalar_float_v2.ptl.ff,sha256=rMgNhL8ZD--9mU661zZBoJlznnb3hvenVJ47skYaeVA,1040 +torch/bin/upgrader_models/test_versioned_div_scalar_inplace_float_v2.ptl,sha256=T0cR8GOVmOvSJ1_9mKMt3QEIvEzIX0bBM5V6t3-Pqik,2273 +torch/bin/upgrader_models/test_versioned_div_scalar_inplace_float_v2.ptl.ff,sha256=AFxhjM-E9821goPBLiZ-ijARityCk6g9AouYmeHfKo0,1048 +torch/bin/upgrader_models/test_versioned_div_scalar_inplace_int_v2.ptl,sha256=UBPYVqJVNGrXHEtGK-OrBczNlEPGl4gZYkGXMAvoIgs,2259 +torch/bin/upgrader_models/test_versioned_div_scalar_inplace_int_v2.ptl.ff,sha256=5haGtzWjVynAv-HJ4gtavRyS8DojmPGgLui-yX0MWAw,1032 +torch/bin/upgrader_models/test_versioned_div_scalar_int_v2.ptl,sha256=sdhQyt26sMiARSkyH_uT_YpaY2NzBNhWNMlL796MsJQ,2146 +torch/bin/upgrader_models/test_versioned_div_scalar_int_v2.ptl.ff,sha256=cX28zcZlpCEnPOvBtT0sFsmyxo8o0c5Nctdm_bwIAho,1032 +torch/bin/upgrader_models/test_versioned_div_scalar_reciprocal_float_v2.ptl,sha256=fut4KaQ5c3sqCdIajhj7MswP0PzOd7ZS7sNS98YDq8s,2904 +torch/bin/upgrader_models/test_versioned_div_scalar_reciprocal_float_v2.ptl.ff,sha256=GKXhzBdS_7O0ltdY24w-UlANwkehW54P80zLtBUbVRg,856 +torch/bin/upgrader_models/test_versioned_div_scalar_reciprocal_int_v2.ptl,sha256=ZLVu4KLF7-tnRKcxKGAGra50fW6bVNZecBwpKtF_86A,2890 +torch/bin/upgrader_models/test_versioned_div_scalar_reciprocal_int_v2.ptl.ff,sha256=oab_exThmPQaDCB7yDNreoNebduAH948KEpnzloLMuo,848 +torch/bin/upgrader_models/test_versioned_div_scalar_scalar_v2.ptl,sha256=Mh2g1D6WE4vkvRArK9X95rg2wIFMp1RTPwJG4vAwp08,2672 +torch/bin/upgrader_models/test_versioned_div_scalar_scalar_v2.ptl.ff,sha256=r0P51ovrMm4Sw9AYu4GaTQ701perwBxuke4yAFucaG0,1120 +torch/bin/upgrader_models/test_versioned_div_tensor_inplace_v2.ptl,sha256=h6fFnUHQR_obxFV4FD9sahV3zuFZqQlMwruA4SYDAXw,2168 +torch/bin/upgrader_models/test_versioned_div_tensor_inplace_v2.ptl.ff,sha256=Apl70_PIw0Z-vA_RZB76kJ3hkGnwgE4GjooF9gabs8k,960 +torch/bin/upgrader_models/test_versioned_div_tensor_out_v2.ptl,sha256=zLzAlUF06BeneJGU6jDpmwnhfeFNCJ_-1-Z8Pogxlf0,2211 +torch/bin/upgrader_models/test_versioned_div_tensor_out_v2.ptl.ff,sha256=I1wZ3WTqwR6IaR_C3Dz8cT3YNOPCHZ2KXU_cK_voghw,1080 +torch/bin/upgrader_models/test_versioned_div_tensor_v2.ptl,sha256=PLt4NO5eBHlGiinZEYnmQTyBGG4l0DwSENjPsW23fHQ,2463 +torch/bin/upgrader_models/test_versioned_div_tensor_v2.ptl.ff,sha256=qKfenRh5ygRERciirbU6JNER9LzrvEp_qgMctTDgbU4,1504 +torch/compiler/__init__.py,sha256=mEPCKhJcXaaZo6vvKwj-sPvek3uot_FJnRdKjIpLUqE,37361 +torch/compiler/__pycache__/__init__.cpython-312.pyc,, +torch/compiler/__pycache__/_cache.cpython-312.pyc,, +torch/compiler/__pycache__/config.cpython-312.pyc,, +torch/compiler/_cache.py,sha256=2soT9UlLwwZ1tfvubB3m0BkynyRBNSFrrnk6B3SaHXY,11524 +torch/compiler/config.py,sha256=wzr6I95XrsdQctGk9OIcw39aCESOj4tX-hnicVrJQGo,13651 +torch/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/contrib/__pycache__/__init__.cpython-312.pyc,, +torch/contrib/__pycache__/_tensorboard_vis.cpython-312.pyc,, +torch/contrib/_tensorboard_vis.py,sha256=NHCnPKg_OGbn9EMjqkTVzALEsShQh2N2-sFsBIDGwEo,5875 +torch/cpu/__init__.py,sha256=LR_4YHxgTCLu9emPFRevb6xaAn4s8wn_ha8i6UDVaJ4,6865 +torch/cpu/__pycache__/__init__.cpython-312.pyc,, +torch/cpu/amp/__init__.py,sha256=Q_Rmzfz39fTI2sYsf0hrKJysAR3d2HHMb6KjZlKQurs,103 +torch/cpu/amp/__pycache__/__init__.cpython-312.pyc,, +torch/cpu/amp/__pycache__/autocast_mode.cpython-312.pyc,, +torch/cpu/amp/__pycache__/grad_scaler.cpython-312.pyc,, +torch/cpu/amp/autocast_mode.py,sha256=XC8Kac0XKSERFrp8Oc3W1G77_cOqrRuG_zOWKjua85I,2180 +torch/cpu/amp/grad_scaler.py,sha256=hT5iBOSV285sW4X7s00Mfg7Pi_eJ-sKCS5BT1qSrz-U,958 +torch/csrc/inductor/aoti_runtime/model.h,sha256=bXluiJ75O2FVmHAL7c3xAqTi9ZtNIvun4JN-nyzRFao,2515 +torch/cuda/__init__.py,sha256=eS9RflB_xq9IvtqgWlHDmH415mGBJiysQqZy1j9Mo2w,75027 +torch/cuda/__pycache__/__init__.cpython-312.pyc,, +torch/cuda/__pycache__/_annotate_cuda_graph_trace.cpython-312.pyc,, +torch/cuda/__pycache__/_device_limits.cpython-312.pyc,, +torch/cuda/__pycache__/_gpu_trace.cpython-312.pyc,, +torch/cuda/__pycache__/_graph_annotations.cpython-312.pyc,, +torch/cuda/__pycache__/_memory_viz.cpython-312.pyc,, +torch/cuda/__pycache__/_pin_memory_utils.cpython-312.pyc,, +torch/cuda/__pycache__/_sanitizer.cpython-312.pyc,, +torch/cuda/__pycache__/_utils.cpython-312.pyc,, +torch/cuda/__pycache__/comm.cpython-312.pyc,, +torch/cuda/__pycache__/gds.cpython-312.pyc,, +torch/cuda/__pycache__/graph_annotations.cpython-312.pyc,, +torch/cuda/__pycache__/graphs.cpython-312.pyc,, +torch/cuda/__pycache__/green_contexts.cpython-312.pyc,, +torch/cuda/__pycache__/jiterator.cpython-312.pyc,, +torch/cuda/__pycache__/memory.cpython-312.pyc,, +torch/cuda/__pycache__/nccl.cpython-312.pyc,, +torch/cuda/__pycache__/nvtx.cpython-312.pyc,, +torch/cuda/__pycache__/profiler.cpython-312.pyc,, +torch/cuda/__pycache__/random.cpython-312.pyc,, +torch/cuda/__pycache__/sparse.cpython-312.pyc,, +torch/cuda/__pycache__/streams.cpython-312.pyc,, +torch/cuda/__pycache__/tunable.cpython-312.pyc,, +torch/cuda/_annotate_cuda_graph_trace.py,sha256=CfHf9wCmUl8t6obWEjNdHyoJmgwKL79FEn_rkM4o7N4,12991 +torch/cuda/_device_limits.py,sha256=fYfWl5kv31rsLXJs8ASkz3AYrpnC1O2phMQy8zIB-aw,5496 +torch/cuda/_gpu_trace.py,sha256=OMYsQlXjF7PvEOGCaMWw__K_iwQYbilVdRV6xoJZvDI,2386 +torch/cuda/_graph_annotations.py,sha256=regVnvM1ErFQFMjLEQDtfZIFBbaaPXKpyYfbn29zfpQ,41843 +torch/cuda/_memory_viz.py,sha256=zrxkSaLTS4OsKjXPdJC6vVkHMsMDYuGNIt4YyNp8kiE,29396 +torch/cuda/_pin_memory_utils.py,sha256=uk6Tnea02s5jWmKIdD2JX7p4W4H-74xpKNf7ZryTFqs,773 +torch/cuda/_sanitizer.py,sha256=fJc3BYVYlk2B4frXL_KpBEA7LjD77pS2IddKqw5aZbQ,24514 +torch/cuda/_utils.py,sha256=8DP3astVWbq3zQFl9ta61VD2yatM6M_ymk-Erbh725Q,23230 +torch/cuda/amp/__init__.py,sha256=cyLIhZXcuKMKb54GjtdhC0GvA1r018SNByosz5S0gFg,298 +torch/cuda/amp/__pycache__/__init__.cpython-312.pyc,, +torch/cuda/amp/__pycache__/autocast_mode.cpython-312.pyc,, +torch/cuda/amp/__pycache__/common.cpython-312.pyc,, +torch/cuda/amp/__pycache__/grad_scaler.cpython-312.pyc,, +torch/cuda/amp/autocast_mode.py,sha256=sVhM2WjWcFXHOp-_6l5ycFZHOUfSsqS5ee0SsBISgYc,3477 +torch/cuda/amp/common.py,sha256=rPnt6OLsROsahVbMyX5w5Fl3R4G6VUiSl5uioKuDEFg,230 +torch/cuda/amp/grad_scaler.py,sha256=WTG3BGVvo4ifizDYTNTq18lRp_CkqVbYS7Kv5N9n6ag,1073 +torch/cuda/comm.py,sha256=DjabyiIf7WmKgD84HmP4_XYd3Cau_7X_E7dcW1UAUjg,344 +torch/cuda/gds.py,sha256=ERC0NDgLkBTwcmyA9zOp_LLpILI-2CyRyB3FeDfc54s,6647 +torch/cuda/graph_annotations.py,sha256=5Moyp7N8b_klrzqzxy63LBLNARxvupHyjC8G27KdEyg,2089 +torch/cuda/graphs.py,sha256=LOmxKxfTm7oV5PNtrApvIVP47UDdZGTQ4YgFNzK3298,74753 +torch/cuda/green_contexts.py,sha256=ftiLZlt9qlicT_m34pWitnq8yMKFCtmNacKN24BF8S0,14834 +torch/cuda/jiterator.py,sha256=X3sCoZtjRDuCe3JWeTAFZZ5uSJwseLMx8b9c3FA6yzY,6989 +torch/cuda/memory.py,sha256=7T5gaNc--dIWX3J2R2BB7lv-jxnbhj4-ERcthAgSFzs,65572 +torch/cuda/nccl.py,sha256=RkSeD2fkDLZChpX0C0jpNg8rX9wCpho1BDhlNf9BNAY,4527 +torch/cuda/nvtx.py,sha256=iK7HzZNzjL0t3NbxDti4XOfUMM_EfsPFN0ugYPOI_Yk,3702 +torch/cuda/profiler.py,sha256=aYzsY7dpmV-vGvwKl3uUPWhCC0VDiP02FmNMNkGbkAU,1230 +torch/cuda/random.py,sha256=a7N7kfaMoKKFSulZ0AQObsImnLOJK2G6-mMNLLjHhRo,5400 +torch/cuda/sparse.py,sha256=H912FRisikGM9SSVDQQq-YX5TNIilBYBZs1AwmIv3GQ,67 +torch/cuda/streams.py,sha256=KNkP1ovlno3Zow0jDn329hpLAg5uLan6iYOWkaHPztU,10658 +torch/cuda/tunable.py,sha256=5Lb0QWFZAMHYDChpOnvKmoaHOKcRbi-nCPf5A0t2u4k,33925 +torch/distributed/__init__.py,sha256=QIeq_N4QRBq3gDvyJM8D9D8Eui8duPMr81WY7qKmsTk,6451 +torch/distributed/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/__pycache__/_checkpointable.cpython-312.pyc,, +torch/distributed/__pycache__/_composable_state.cpython-312.pyc,, +torch/distributed/__pycache__/_functional_collectives.cpython-312.pyc,, +torch/distributed/__pycache__/_functional_collectives_impl.cpython-312.pyc,, +torch/distributed/__pycache__/_mesh_layout.cpython-312.pyc,, +torch/distributed/__pycache__/_meta_registrations.cpython-312.pyc,, +torch/distributed/__pycache__/_serialization.cpython-312.pyc,, +torch/distributed/__pycache__/_state_dict_utils.cpython-312.pyc,, +torch/distributed/__pycache__/_token_switch.cpython-312.pyc,, +torch/distributed/__pycache__/argparse_util.cpython-312.pyc,, +torch/distributed/__pycache__/c10d_logger.cpython-312.pyc,, +torch/distributed/__pycache__/collective_utils.cpython-312.pyc,, +torch/distributed/__pycache__/config.cpython-312.pyc,, +torch/distributed/__pycache__/constants.cpython-312.pyc,, +torch/distributed/__pycache__/device_mesh.cpython-312.pyc,, +torch/distributed/__pycache__/distributed_c10d.cpython-312.pyc,, +torch/distributed/__pycache__/launch.cpython-312.pyc,, +torch/distributed/__pycache__/logging_handlers.cpython-312.pyc,, +torch/distributed/__pycache__/remote_device.cpython-312.pyc,, +torch/distributed/__pycache__/rendezvous.cpython-312.pyc,, +torch/distributed/__pycache__/run.cpython-312.pyc,, +torch/distributed/__pycache__/utils.cpython-312.pyc,, +torch/distributed/_checkpointable.py,sha256=VqtUDzJDcTeMUFOguRIo_AvLRXg4n4U73-frKynBqo8,1305 +torch/distributed/_composable/__init__.py,sha256=SUm5fu8Tg24Upb5iHCV849oZSrrtSacaG-7T7A5L2qA,125 +torch/distributed/_composable/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_composable/__pycache__/checkpoint_activation.cpython-312.pyc,, +torch/distributed/_composable/__pycache__/contract.cpython-312.pyc,, +torch/distributed/_composable/__pycache__/replicate.cpython-312.pyc,, +torch/distributed/_composable/__pycache__/replicate_with_fsdp.cpython-312.pyc,, +torch/distributed/_composable/checkpoint_activation.py,sha256=wxXQdcVm5qS2mPRhK2F5I1RIaod8fykot65ZK1VZgU8,4891 +torch/distributed/_composable/contract.py,sha256=qfezUWwTqhPcTeyjjEXn_XjYhyRXaQaLxIhcrj6xwDQ,10447 +torch/distributed/_composable/fsdp/__init__.py,sha256=PAE0ViGvjHO65XbIe-CM5BgRx9KNsVL4xU7QRUyqL9M,169 +torch/distributed/_composable/fsdp/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_composable/fsdp/__pycache__/fully_shard.cpython-312.pyc,, +torch/distributed/_composable/fsdp/fully_shard.py,sha256=LggyTExDS-LXmmZeCoSp-GvlMKOmRulWv6k4aPyYsWM,240 +torch/distributed/_composable/replicate.py,sha256=5vcfdfr8BfkoJ-k4RkyWiXKukuNZV8R3P1DDdCZobzI,9351 +torch/distributed/_composable/replicate_with_fsdp.py,sha256=nMYPrR5CrWJsFH6maoEeWQMwZUIh4Y065ZqodwtNfV0,6485 +torch/distributed/_composable_state.py,sha256=rOKLQZE5s1TbgdfB4M9kd94AaTAmnnw-AmyqL5fxpjQ,1403 +torch/distributed/_functional_collectives.py,sha256=vbBdwS1ZitRCmRYIOZV38txAev1X0-KvWgb1UWGw004,74792 +torch/distributed/_functional_collectives_impl.py,sha256=gwLRcqtq9NGUBkXDhYElw6PpDVtDmKkWew5Bt9ZJZsc,3790 +torch/distributed/_local_tensor/__init__.py,sha256=r5u0Xdm-E1fyTKCsHRo2stXd8noEXI4jpqgecGkfTOE,85628 +torch/distributed/_local_tensor/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_local_tensor/__pycache__/_c10d.cpython-312.pyc,, +torch/distributed/_local_tensor/_c10d.py,sha256=OYuy4OeOJXF78xyg7UzcWd9ke2wUzqgwlyiCys_nH_4,42861 +torch/distributed/_mesh_layout.py,sha256=gbe1LwUgOZ3Yyie1rDDMmftQN_XHOHSDHbbxcK-wgnU,15822 +torch/distributed/_meta_registrations.py,sha256=fC3eKt9lzVU_kBGdyd0jFcnbe31cWkQg-hYM_0Ghub0,2379 +torch/distributed/_ops/__init__.py,sha256=jLQo34kgGOSuumAbVsa8rQRJtt8LZKnXvqpTvpsNSjo,52 +torch/distributed/_ops/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_ops/__pycache__/device_mesh.cpython-312.pyc,, +torch/distributed/_ops/device_mesh.py,sha256=82Fy4vP7lggJbCideZaQhdUZKfWYFhCAN_bpKuVsko0,3942 +torch/distributed/_pycute/__init__.py,sha256=7Rjy64t4ztEB5BNIFIjFPaYxv1afzff1HcKLBtnPYx8,2456 +torch/distributed/_pycute/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_pycute/__pycache__/int_tuple.cpython-312.pyc,, +torch/distributed/_pycute/__pycache__/layout.cpython-312.pyc,, +torch/distributed/_pycute/__pycache__/typing.cpython-312.pyc,, +torch/distributed/_pycute/int_tuple.py,sha256=HZegxSKHMl86jE7BRIMVPV83qdq5FQrvxp-xu3apPlU,10304 +torch/distributed/_pycute/layout.py,sha256=BD8EKXZeh4eYe1lbpEZiWkIm8QkOj5yREUctCVrhXtw,18451 +torch/distributed/_pycute/typing.py,sha256=0kzCgBGBRRt1hfAACBnwFdC9g11Ujh8dozJ5GAd9tDw,2062 +torch/distributed/_serialization.py,sha256=nXtpB29C_HiU3WCeWcEISJCAdN0FbOFNAyx3YxjUwaw,4584 +torch/distributed/_shard/__init__.py,sha256=9mrjpti4iifWb8jnGoZypHH0ovdZg3A2KQnxg6BACKI,87 +torch/distributed/_shard/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_shard/__pycache__/_utils.cpython-312.pyc,, +torch/distributed/_shard/__pycache__/api.cpython-312.pyc,, +torch/distributed/_shard/__pycache__/common_op_utils.cpython-312.pyc,, +torch/distributed/_shard/__pycache__/metadata.cpython-312.pyc,, +torch/distributed/_shard/__pycache__/op_registry_utils.cpython-312.pyc,, +torch/distributed/_shard/__pycache__/sharder.cpython-312.pyc,, +torch/distributed/_shard/_utils.py,sha256=ra_iuevX3gIRVWOz9tql3hLtLRm0JXzeREiL9vwVm14,1070 +torch/distributed/_shard/api.py,sha256=hsDn-zXLsKOR-_exVqTGkILCa-B3lSzU8u_FYaHQd2M,12365 +torch/distributed/_shard/checkpoint/__init__.py,sha256=kILV09-2Glss17itgmv1SbBq7hp2Y7HLUugCZRGYCFE,584 +torch/distributed/_shard/checkpoint/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_shard/common_op_utils.py,sha256=kj53BqGnob9GRuoRgzn1MXOAmtFRvy_7nzXdJA_1Qrg,2148 +torch/distributed/_shard/metadata.py,sha256=krJyeG9SY2KiJtVxUq4th4qDFUR4WbW5j01VA9RO8bA,2168 +torch/distributed/_shard/op_registry_utils.py,sha256=aK7aBTzgR298AvchxXB1VNdeIT6UCO5emnOoOadjM-I,1031 +torch/distributed/_shard/sharded_optim/__init__.py,sha256=23n5rJ4CKIZb1TwXlI7cX6DgOURqKO5eiM7PJbyi9aY,1863 +torch/distributed/_shard/sharded_optim/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_shard/sharded_optim/__pycache__/api.cpython-312.pyc,, +torch/distributed/_shard/sharded_optim/api.py,sha256=azG0U2MZOpi5qY2TyEy0qyFgNemadga_bSOu1ooL438,4264 +torch/distributed/_shard/sharded_tensor/__init__.py,sha256=MxpDKsM2xgJ0_mwXg9G1lDHjVkz5Z0AHuGkF2S_L63k,19233 +torch/distributed/_shard/sharded_tensor/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_shard/sharded_tensor/__pycache__/api.cpython-312.pyc,, +torch/distributed/_shard/sharded_tensor/__pycache__/logger.cpython-312.pyc,, +torch/distributed/_shard/sharded_tensor/__pycache__/logging_handlers.cpython-312.pyc,, +torch/distributed/_shard/sharded_tensor/__pycache__/metadata.cpython-312.pyc,, +torch/distributed/_shard/sharded_tensor/__pycache__/reshard.cpython-312.pyc,, +torch/distributed/_shard/sharded_tensor/__pycache__/shard.cpython-312.pyc,, +torch/distributed/_shard/sharded_tensor/__pycache__/utils.cpython-312.pyc,, +torch/distributed/_shard/sharded_tensor/_ops/__init__.py,sha256=NW4TXyw5RGFCbWfikCuxxCOrWuVIUovX06jI8PgcqNM,498 +torch/distributed/_shard/sharded_tensor/_ops/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_shard/sharded_tensor/_ops/__pycache__/_common.cpython-312.pyc,, +torch/distributed/_shard/sharded_tensor/_ops/__pycache__/binary_cmp.cpython-312.pyc,, +torch/distributed/_shard/sharded_tensor/_ops/__pycache__/init.cpython-312.pyc,, +torch/distributed/_shard/sharded_tensor/_ops/__pycache__/misc_ops.cpython-312.pyc,, +torch/distributed/_shard/sharded_tensor/_ops/__pycache__/tensor_ops.cpython-312.pyc,, +torch/distributed/_shard/sharded_tensor/_ops/_common.py,sha256=KuLeI0PylCkKm5_pnK61Qo3YQhuiFte_VwYpMxjdVG4,4276 +torch/distributed/_shard/sharded_tensor/_ops/binary_cmp.py,sha256=WCNATMbJV4byksPQDCFaGwgs1t-NA0JLcvaiSZr_NWU,2819 +torch/distributed/_shard/sharded_tensor/_ops/init.py,sha256=TdtFNapDXAcB_qL2G7MqbSKfOewocl_MwNtxbsDY5HU,6070 +torch/distributed/_shard/sharded_tensor/_ops/misc_ops.py,sha256=lp_SXuhFUagN_5bxfmZVeqY0SCMhgnGeLGxLq38qvsg,497 +torch/distributed/_shard/sharded_tensor/_ops/tensor_ops.py,sha256=oFaXL6JNjd_Vrr3_mfr_I9EVTsxVPGOtfm33OVXIXVI,7813 +torch/distributed/_shard/sharded_tensor/api.py,sha256=GsSX7J3O3wCk7R_lK5g2pUPef9w3iC_SVSbIEyjwF4U,55252 +torch/distributed/_shard/sharded_tensor/logger.py,sha256=yny64ZlZ-RzlS5DcX-SAipWqk4xcR2AQO4yl4Vf8B50,1084 +torch/distributed/_shard/sharded_tensor/logging_handlers.py,sha256=nXuxHnOEhAHqqDPhTk_-aLYIVHoZpQEYW_X4N1Qg0_Q,359 +torch/distributed/_shard/sharded_tensor/metadata.py,sha256=92isIH0O2TqPy3Li1CG00R0Ca1BZ40gGM2GHKkJraUA,2998 +torch/distributed/_shard/sharded_tensor/reshard.py,sha256=YR5hiwo7MIO7oA1Ygy86tzO_fFEKNm2BdwfwwmKU3MU,10724 +torch/distributed/_shard/sharded_tensor/shard.py,sha256=zNfIL2FIGBNwPUFcrfusf0E1R-YO04ZoOdcvY6DpXbA,2361 +torch/distributed/_shard/sharded_tensor/utils.py,sha256=Zv478F6Re2dLkYyZSwQtLrRV9SlLDXp9QYCIE9XlJno,11780 +torch/distributed/_shard/sharder.py,sha256=nErlvDuMU29IUB6oWB295FaXYj8H42FuDQJXdepvQ1E,901 +torch/distributed/_shard/sharding_plan/__init__.py,sha256=9w-j8bY8VJ0dGT_ueJR2yTfzuech180Xkq0XELn1tKs,47 +torch/distributed/_shard/sharding_plan/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_shard/sharding_plan/__pycache__/api.cpython-312.pyc,, +torch/distributed/_shard/sharding_plan/api.py,sha256=QIoc6_W1-sfxZ3f39eFNEOR6ILO0wm1GUxUdml3OcGE,3603 +torch/distributed/_shard/sharding_spec/__init__.py,sha256=hih75sKTSXPxdyUOS24Vl6K3Q3ht-74l33uAjM4I2Kw,291 +torch/distributed/_shard/sharding_spec/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_shard/sharding_spec/__pycache__/_internals.cpython-312.pyc,, +torch/distributed/_shard/sharding_spec/__pycache__/api.cpython-312.pyc,, +torch/distributed/_shard/sharding_spec/__pycache__/chunk_sharding_spec.cpython-312.pyc,, +torch/distributed/_shard/sharding_spec/_internals.py,sha256=zkNtc3MvZBIFu3fUGZPt9WaIhKUmET_MCl7sSa-hiaQ,8518 +torch/distributed/_shard/sharding_spec/api.py,sha256=bRaC5Dj1Kku9Xj2oMIvEV53u77Ky17gK8SMk2-0c9Ng,9847 +torch/distributed/_shard/sharding_spec/chunk_sharding_spec.py,sha256=jHROTK4vYlCmGn-HPFuN9MCIJRH4sWZ7eKMutc8_C2Q,9215 +torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/_common.cpython-312.pyc,, +torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/embedding.cpython-312.pyc,, +torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/__pycache__/embedding_bag.cpython-312.pyc,, +torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/_common.py,sha256=pU0FdT98noqNnNMxs9H4hBrNi_wom1SZgm4UjDGPUXg,13121 +torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/embedding.py,sha256=_N4tqOT7SFD_nGqS2V3TR9hb3zRkevdq28KBQXwZ-Eo,11210 +torch/distributed/_shard/sharding_spec/chunk_sharding_spec_ops/embedding_bag.py,sha256=MMLFzc8J3wt5tfYl0zd8M8mYN-LY4AlDwngVPc6J4bY,18321 +torch/distributed/_sharded_tensor/__init__.py,sha256=sL4DKv-CLF-9k_iqL2U689tEIJCSKgeWLsKNtjoqjdg,617 +torch/distributed/_sharded_tensor/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_sharding_spec/__init__.py,sha256=PR7htIt_o1lIdWq_dvH3aXMHA22fj59dOpLT15vx3zE,646 +torch/distributed/_sharding_spec/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_state_dict_utils.py,sha256=dWlU2U-AfnIYqif82_8SM0MO0L3ZV3hG17EiEX9Nv-A,29734 +torch/distributed/_symmetric_memory/__init__.py,sha256=TB7BLwNBhpYNgFypz7VMppE42JRVgvI8Db0Mt3gb85o,97441 +torch/distributed/_symmetric_memory/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_symmetric_memory/__pycache__/_nccl.cpython-312.pyc,, +torch/distributed/_symmetric_memory/__pycache__/_nvshmem_triton.cpython-312.pyc,, +torch/distributed/_symmetric_memory/__pycache__/_rocshmem_triton.cpython-312.pyc,, +torch/distributed/_symmetric_memory/__pycache__/_shmem_triton.cpython-312.pyc,, +torch/distributed/_symmetric_memory/__pycache__/_shmem_triton_utils.cpython-312.pyc,, +torch/distributed/_symmetric_memory/__pycache__/_triton_kernels.cpython-312.pyc,, +torch/distributed/_symmetric_memory/_nccl.py,sha256=QOX2pNQkNy8G_sSS6DJ9vSE7_URJqpFgKUAdcRqBjZE,3904 +torch/distributed/_symmetric_memory/_nvshmem_triton.py,sha256=dd251BjnTMexX4Tgn4RbDnzWYnVTqYMljgk7B_YueZE,46966 +torch/distributed/_symmetric_memory/_rocshmem_triton.py,sha256=jMY0LGksZrrV0p6pSRmqll05xWmulhzAvrNfsFIBQHE,15527 +torch/distributed/_symmetric_memory/_shmem_triton.py,sha256=_XmSP-VIS_azx2qtSL_B8BOpf4bgLpKNB7FFISioSMo,1061 +torch/distributed/_symmetric_memory/_shmem_triton_utils.py,sha256=Qbxl74PCSgb0pAXRpMhruWWIowfayUULQjiAsXI0z7Q,3200 +torch/distributed/_symmetric_memory/_triton_kernels.py,sha256=0HUMaOEaYAfMqL_ae5x_noEpwj-mnAiVDVsIKFCHZK4,927 +torch/distributed/_tensor/__init__.py,sha256=RPvZW2utGTr72ZT6s2_ckuGz_-lghkjlUTHbs5poL0Q,955 +torch/distributed/_tensor/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_tensor/__pycache__/api.cpython-312.pyc,, +torch/distributed/_tensor/__pycache__/placement_types.cpython-312.pyc,, +torch/distributed/_tensor/api.py,sha256=ptXYd9YLsHKZOZyphH_-s-3CLYa4QszeN3c9U0zUpAo,294 +torch/distributed/_tensor/placement_types.py,sha256=yyE7qAaYq7P0PERX3c08XI8Y3-bnXgw7s4MRKeQHQ00,372 +torch/distributed/_token_switch.py,sha256=znjVVz4dcqFCmZog4mmChiLe-Fhyq1W50kSJfv6q9EE,12120 +torch/distributed/_tools/__init__.py,sha256=DYVOrVO_6vBZuEuW8EaKdxsR8bFVoE16R2DiGfKo6JM,327 +torch/distributed/_tools/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/_tools/__pycache__/common_utils.cpython-312.pyc,, +torch/distributed/_tools/__pycache__/fake_collectives.cpython-312.pyc,, +torch/distributed/_tools/__pycache__/fsdp2_mem_tracker.cpython-312.pyc,, +torch/distributed/_tools/__pycache__/ilp_utils.cpython-312.pyc,, +torch/distributed/_tools/__pycache__/mem_tracker.cpython-312.pyc,, +torch/distributed/_tools/__pycache__/memory_tracker.cpython-312.pyc,, +torch/distributed/_tools/__pycache__/mod_tracker.cpython-312.pyc,, +torch/distributed/_tools/__pycache__/runtime_estimator.cpython-312.pyc,, +torch/distributed/_tools/__pycache__/sac_estimator.cpython-312.pyc,, +torch/distributed/_tools/__pycache__/sac_ilp.cpython-312.pyc,, +torch/distributed/_tools/common_utils.py,sha256=r7jsc8OPL5iEX-zjANxwNl2WwE7ydpWaAa7ZcTYCfrs,1577 +torch/distributed/_tools/fake_collectives.py,sha256=7FVey50Xy6sZ0NIYJkXKyGDbxgx7b9ZqcQ50KpAIyb4,10051 +torch/distributed/_tools/fsdp2_mem_tracker.py,sha256=Z7byziwRWdC0upMk4V2RQ8NNyvflQbBtT0EW1DISn2A,26378 +torch/distributed/_tools/ilp_utils.py,sha256=xmsBK7RtUTyKVgKMbMJ2_pVxS7kLmFT3QX8tc-CL6rY,10114 +torch/distributed/_tools/mem_tracker.py,sha256=ImCGx3bjrSsLhhg8x-LfpybeNZZEyHSk_y5rmTYr1Pg,43523 +torch/distributed/_tools/memory_tracker.py,sha256=Et-MJb93th5_MVTmNwtqcY3FN21ZJ1-YIAeqmA8FPpU,11718 +torch/distributed/_tools/mod_tracker.py,sha256=eOU3a-Dl3NSQ9bACQOcUbCE_Ga7P4UNPNpNhOe4v7-4,10262 +torch/distributed/_tools/runtime_estimator.py,sha256=uNnbcDUVKuIAg2kGyhd_4inVaotk_QAC2vy1-whVtQ0,17495 +torch/distributed/_tools/sac_estimator.py,sha256=oGAm0wxsfzry0nCbJzMgurGNCwufSuE3GbAKrWtyorI,42876 +torch/distributed/_tools/sac_ilp.py,sha256=a3fj9N0h7kBIgOTuioiUmD0dZLIyjvgrEouxr4uLGXE,11364 +torch/distributed/algorithms/__init__.py,sha256=e5HJMsdSDkPOxNWYUh9YvO26GDODG5PBedTP2-Y16Nw,43 +torch/distributed/algorithms/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/algorithms/__pycache__/join.cpython-312.pyc,, +torch/distributed/algorithms/_checkpoint/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/distributed/algorithms/_checkpoint/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/algorithms/_checkpoint/__pycache__/checkpoint_wrapper.cpython-312.pyc,, +torch/distributed/algorithms/_checkpoint/checkpoint_wrapper.py,sha256=0CETclY_Mg34hjDdVTq6l_7PPoco9Cxq_E20G2Rn8dE,12001 +torch/distributed/algorithms/_comm_hooks/__init__.py,sha256=LkI4VBMJ6_1KGG3Nz0bPxGFOO-ZjfBj-38FNROlJt8Q,131 +torch/distributed/algorithms/_comm_hooks/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/algorithms/_comm_hooks/__pycache__/default_hooks.cpython-312.pyc,, +torch/distributed/algorithms/_comm_hooks/default_hooks.py,sha256=UcSAKMMCQCuxI1WLayobqszwX6swu1D8UexcNu9rStQ,7616 +torch/distributed/algorithms/_optimizer_overlap/__init__.py,sha256=zuKlfE0DcQCZm0av9HrJZfXH6R5AzV2K3xrEAAgoVsk,52 +torch/distributed/algorithms/_optimizer_overlap/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/algorithms/_optimizer_overlap/__pycache__/optimizer_overlap.cpython-312.pyc,, +torch/distributed/algorithms/_optimizer_overlap/optimizer_overlap.py,sha256=zkw6dsk0wrK9Nj4-IYQU0q2yH2hzIL2tag5W9ccz9Oc,3753 +torch/distributed/algorithms/_quantization/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/distributed/algorithms/_quantization/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/algorithms/_quantization/__pycache__/quantization.cpython-312.pyc,, +torch/distributed/algorithms/_quantization/quantization.py,sha256=jbL_YAS9g8PVEjCk1hgi0b3A992tKevudfyndlGYWiA,5646 +torch/distributed/algorithms/ddp_comm_hooks/__init__.py,sha256=exEyXW5C9nVkMDaAnqoR-ukDrhKktL54gJNYTPSIin4,4210 +torch/distributed/algorithms/ddp_comm_hooks/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/algorithms/ddp_comm_hooks/__pycache__/ddp_zero_hook.cpython-312.pyc,, +torch/distributed/algorithms/ddp_comm_hooks/__pycache__/debugging_hooks.cpython-312.pyc,, +torch/distributed/algorithms/ddp_comm_hooks/__pycache__/default_hooks.cpython-312.pyc,, +torch/distributed/algorithms/ddp_comm_hooks/__pycache__/mixed_precision_hooks.cpython-312.pyc,, +torch/distributed/algorithms/ddp_comm_hooks/__pycache__/optimizer_overlap_hooks.cpython-312.pyc,, +torch/distributed/algorithms/ddp_comm_hooks/__pycache__/post_localSGD_hook.cpython-312.pyc,, +torch/distributed/algorithms/ddp_comm_hooks/__pycache__/powerSGD_hook.cpython-312.pyc,, +torch/distributed/algorithms/ddp_comm_hooks/__pycache__/quantization_hooks.cpython-312.pyc,, +torch/distributed/algorithms/ddp_comm_hooks/ddp_zero_hook.py,sha256=GWcWaN3itxGSijIXg5EntaXL9pftOrArRWnYjp5csKc,19832 +torch/distributed/algorithms/ddp_comm_hooks/debugging_hooks.py,sha256=i6irEBeuGy3i9Fqk10QOFwzETiPZP3TGa_AkWy3BpRM,1118 +torch/distributed/algorithms/ddp_comm_hooks/default_hooks.py,sha256=_v7QSzzDWZmzI3SrRu40IPdClkVGfTQrCsISFVy0Kus,7962 +torch/distributed/algorithms/ddp_comm_hooks/mixed_precision_hooks.py,sha256=sc2NnDmQKmSNYyZ6A83-s9DgYBV-YTfmMdrzurNouag,3254 +torch/distributed/algorithms/ddp_comm_hooks/optimizer_overlap_hooks.py,sha256=r6I_Jf1fvhmrcMOUR5y1Nk3uSSsU1RRazTcZVOGvz2A,6151 +torch/distributed/algorithms/ddp_comm_hooks/post_localSGD_hook.py,sha256=MPpCW3JHvFIqfC3frNnzuATOtlLiML6hXEgM6C8ZeGk,5150 +torch/distributed/algorithms/ddp_comm_hooks/powerSGD_hook.py,sha256=JqUe-FP7Ezbq5W570fs9XN1QNEtsH_DdFx37t_cOrEs,40556 +torch/distributed/algorithms/ddp_comm_hooks/quantization_hooks.py,sha256=jDQwXM6McOwPUH5S6Sj9H-hV2rqT-NG0c-InuuyBLsM,8318 +torch/distributed/algorithms/join.py,sha256=r29MXh8j7EhEYR7CDPdk5eiqLYh03d3HGU5p_ldscMA,13520 +torch/distributed/algorithms/model_averaging/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/distributed/algorithms/model_averaging/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/algorithms/model_averaging/__pycache__/averagers.cpython-312.pyc,, +torch/distributed/algorithms/model_averaging/__pycache__/hierarchical_model_averager.cpython-312.pyc,, +torch/distributed/algorithms/model_averaging/__pycache__/utils.cpython-312.pyc,, +torch/distributed/algorithms/model_averaging/averagers.py,sha256=sNQvYipPY_JNWeF_zqPUCFXcYR8WLHt4ohqbKQdjkdQ,5417 +torch/distributed/algorithms/model_averaging/hierarchical_model_averager.py,sha256=XRFDc9ZEynZ3jvM_drbt06S1a8hQIY0wuoMO_HytfF8,9768 +torch/distributed/algorithms/model_averaging/utils.py,sha256=_H_E5K-EQv2p5RbFiVa8LH7zjds4IlKiwl6pYMv2DAA,3087 +torch/distributed/argparse_util.py,sha256=NFxjw2asYt06aFffcu6rhJpC3FFthwKLu9wvWEm_qQU,3903 +torch/distributed/autograd/__init__.py,sha256=o1YwfjRin8NfYkCjzcdABFT0bGRGAiuYmSLEwmbmeJ4,1931 +torch/distributed/autograd/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/c10d_logger.py,sha256=t7WGbk08OEfiTz_kiPGHy9kKyUlVokqY3BDw2WyZtkk,3185 +torch/distributed/checkpoint/__init__.py,sha256=ryM9mI9s8mX2zlD9Bhlfq8LJFLSftQSZSGHkHy1iSjY,869 +torch/distributed/checkpoint/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_async_executor.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_async_process_executor.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_async_thread_executor.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_checkpointer.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_consolidate_hf_safetensors.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_dedup_save_plans.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_dedup_tensors.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_extension.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_fsspec_filesystem.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_hf_utils.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_nested_dict.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_pg_transport.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_sharded_tensor_utils.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_state_dict_stager.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_storage_utils.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_traverse.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/_version.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/api.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/default_planner.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/filesystem.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/format_utils.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/hf_storage.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/logger.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/logging_handlers.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/metadata.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/optimizer.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/planner.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/planner_helpers.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/protocol.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/quantized_hf_storage.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/resharding.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/staging.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/state_dict.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/state_dict_loader.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/state_dict_saver.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/stateful.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/storage.cpython-312.pyc,, +torch/distributed/checkpoint/__pycache__/utils.cpython-312.pyc,, +torch/distributed/checkpoint/_async_executor.py,sha256=tTpnGTOG1U8BiROCkS9JB_UPv7E6ZvLWFkOboqisMTw,1154 +torch/distributed/checkpoint/_async_process_executor.py,sha256=1xXAsKF8iCFxstp49FqptGGxTyN99b27nSo7cwAYYuo,18017 +torch/distributed/checkpoint/_async_thread_executor.py,sha256=ojp5WJc383zu1R5B1GqgXdK9acA-ctCph12HAJsRMkA,2401 +torch/distributed/checkpoint/_checkpointer.py,sha256=6EbVmuToQsNR-pEEmYMcTVmjQtckUt02aTqoIM5eXro,3784 +torch/distributed/checkpoint/_consolidate_hf_safetensors.py,sha256=BI-up1pLOlr4rVUzhic6mbyF6kBhHZJ62WdPcFmn0WU,28448 +torch/distributed/checkpoint/_dedup_save_plans.py,sha256=QP__wSP0I0jglKEyPZ_JGXrgHIKSrU6c6Gow8vQTZkk,2754 +torch/distributed/checkpoint/_dedup_tensors.py,sha256=MU2RaM-qHxvn2I-LmNTgvw1cvGwoqItiCHxhb5vNrRM,1991 +torch/distributed/checkpoint/_experimental/__init__.py,sha256=ukQ1Zu9_BedHvl_JQrJhsWKwcJ8nxEYh4_AzvevbT9k,1761 +torch/distributed/checkpoint/_experimental/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/checkpoint/_experimental/__pycache__/barriers.cpython-312.pyc,, +torch/distributed/checkpoint/_experimental/__pycache__/builder.cpython-312.pyc,, +torch/distributed/checkpoint/_experimental/__pycache__/checkpoint_process.cpython-312.pyc,, +torch/distributed/checkpoint/_experimental/__pycache__/checkpoint_reader.cpython-312.pyc,, +torch/distributed/checkpoint/_experimental/__pycache__/checkpoint_writer.cpython-312.pyc,, +torch/distributed/checkpoint/_experimental/__pycache__/checkpointer.cpython-312.pyc,, +torch/distributed/checkpoint/_experimental/__pycache__/config.cpython-312.pyc,, +torch/distributed/checkpoint/_experimental/__pycache__/staging.cpython-312.pyc,, +torch/distributed/checkpoint/_experimental/__pycache__/types.cpython-312.pyc,, +torch/distributed/checkpoint/_experimental/__pycache__/utils.cpython-312.pyc,, +torch/distributed/checkpoint/_experimental/barriers.py,sha256=57Tgfop5ZTxmx6fBaNNwOjBiFAICmNT0KWnHoFm0paQ,9134 +torch/distributed/checkpoint/_experimental/builder.py,sha256=tn8g361poE45V-G5bLhD-0-bBx8iGWx97z7sSqyi41k,6101 +torch/distributed/checkpoint/_experimental/checkpoint_process.py,sha256=sOjG5jg-50aiJfEd6yHj6CtnmGod6FsDTHhkrejttPY,13049 +torch/distributed/checkpoint/_experimental/checkpoint_reader.py,sha256=X5TtxSL7oyZZBw0nAXIeErm3ZCa42d_Xb2oatEj_S2I,8680 +torch/distributed/checkpoint/_experimental/checkpoint_writer.py,sha256=ntVXEIcTqiH74yjE3c_v7_j_DlwMr5dpdVZ3wnRZ4ls,5251 +torch/distributed/checkpoint/_experimental/checkpointer.py,sha256=EIDf-R3iJCqs6X1BxMJZfWjEuSg8GKdqWqBPqGjKRcI,11917 +torch/distributed/checkpoint/_experimental/config.py,sha256=81BcsUGoE59ibhFW0OQ05Hi4zmqJ2-v9tITPJqMQDTM,1528 +torch/distributed/checkpoint/_experimental/staging.py,sha256=4p7ae0KMQTC_6NBzxRAo2zTeKvSTajB4yb13zvCGrSw,8122 +torch/distributed/checkpoint/_experimental/types.py,sha256=8BI2ouC6nlgXa3nKOjcDPVDZaLwDb__S_f1G79hR9Eg,759 +torch/distributed/checkpoint/_experimental/utils.py,sha256=rIaJLYRF03P1FPH57lo17JUD-b8Kd0NhHer1JdpEZa0,1305 +torch/distributed/checkpoint/_extension.py,sha256=80YGomQlyg3Mh-dc6rKhLbjOmuMQzjeRiTT2ErixKvg,7736 +torch/distributed/checkpoint/_fsspec_filesystem.py,sha256=tCmbGbfIWaBkZ_bWhPCsHFdUAiiknDo0AwnPrSLhYRs,5449 +torch/distributed/checkpoint/_hf_utils.py,sha256=RoH7XHPrRd23_XcnlvobWlhPgKUrtcv7y1ifd9B7_Vw,2819 +torch/distributed/checkpoint/_nested_dict.py,sha256=IPtO0mCEYB9xT0Il5g4GW978lubbCFCj51Qo9mTDJWo,2273 +torch/distributed/checkpoint/_pg_transport.py,sha256=Dor7iQYkLmCk9PAveO3Jk_5TbKEzdP4GnmAoy9LCyLI,13268 +torch/distributed/checkpoint/_sharded_tensor_utils.py,sha256=HZOdtN7SH2D79rgdm2g7BDEacEwTxkAJWZhNtSVv6O0,4144 +torch/distributed/checkpoint/_state_dict_stager.py,sha256=3q_z9S7Klns_zsKg8Ta4nRQY12l15cpJv1uFDeAsZX4,18896 +torch/distributed/checkpoint/_storage_utils.py,sha256=adK0EQsZ7U9w-zh2qskmXkn27pmsP1uV5phseLurw68,1362 +torch/distributed/checkpoint/_traverse.py,sha256=MCJWgbzw21jbwdIVt5FpJIzY24qmJlHc0FQWltjO7fc,7199 +torch/distributed/checkpoint/_version.py,sha256=wjFuEFA3gH625gFQMVRpt55yBAUObGUHe_1iuM8xMVw,90 +torch/distributed/checkpoint/api.py,sha256=iBZAi6ydUSefDNOLzBDZs0GK7Ji5BFHaNfS5lSqbepE,1799 +torch/distributed/checkpoint/default_planner.py,sha256=UWkbMIj5eLRqJlb_6-mGOJq1Sb2zCkL2UH4I0szAtQE,28636 +torch/distributed/checkpoint/filesystem.py,sha256=lR9VwZwBxS8hnSzBLEjr44vmLsrwtXsGZyLq7e28ltY,37276 +torch/distributed/checkpoint/format_utils.py,sha256=Cp4LvqDD9mUgsjmfsXIpQuyZbaJrwFEBMphPn1yq0ZI,10733 +torch/distributed/checkpoint/hf_storage.py,sha256=vxbIuOfjLjFxJzjhtHKiSr_D9TuMDzB_sii4X9WKmGc,15383 +torch/distributed/checkpoint/logger.py,sha256=N0xKPxzuyAH2g0TyPI_ij48U7z1HvgTXgfWJxcZOO5s,3635 +torch/distributed/checkpoint/logging_handlers.py,sha256=Ky7OdEi5JzxTwc2u34Mq-tX5S-Y0MynrHAc1xe2nCEk,220 +torch/distributed/checkpoint/metadata.py,sha256=YjGicfDEgIBi1EmC9zC9-b6DQ5-tYnYtChpK0hXeHdk,5573 +torch/distributed/checkpoint/optimizer.py,sha256=LQx-FVgFZibOKYsDtxUzMimPclj6A8W-R83T-1e5Rhk,13359 +torch/distributed/checkpoint/planner.py,sha256=DUeog-o4sd3ptiv9qAisEE_Bchr_i-21Pq0ybRQ6zwg,16223 +torch/distributed/checkpoint/planner_helpers.py,sha256=SaVRHc2rvKHcOic2X_yjPfuEUyG7mIBRy65LJRqiRCk,20274 +torch/distributed/checkpoint/protocol.py,sha256=eaQn0HeVr9yPFIpurp5T0jf8mbzRRcpXDz03LKLBMyY,6160 +torch/distributed/checkpoint/quantized_hf_storage.py,sha256=Gb2mon7ZXfT7s_4-F-DeFRykbPDopiOWy0uq6V2xs6k,20167 +torch/distributed/checkpoint/resharding.py,sha256=-__qNKrjGJsRelT0t0zK1nd5O7NMlMBJr1ksGTztLVw,2273 +torch/distributed/checkpoint/staging.py,sha256=wsOIwPZrLhab8t9cy03NI4BfF_n6gf1YF_JvtPGvJ1M,19009 +torch/distributed/checkpoint/state_dict.py,sha256=OQLBvX5OxTd5uiHEqg_1mnAZeX4PzWrb7k0sTY06p0E,63321 +torch/distributed/checkpoint/state_dict_loader.py,sha256=R2mRgzaGSiXj6mJ7ZGNKIVJY-GUYgEvNHDoXqWcvWVE,14885 +torch/distributed/checkpoint/state_dict_saver.py,sha256=DneGIcqVnthJbdZir0gUNQ6xMHDfvWX4Xc4_DA2qPhg,19603 +torch/distributed/checkpoint/stateful.py,sha256=1cJTGrO_TPFeSguyQhPYCw87ph_QjJRafyAVgx9u7bI,1061 +torch/distributed/checkpoint/storage.py,sha256=2f46guqJLwyWSHzOYe0TdKGz2JVvsUl31pOaXf6SBp4,9792 +torch/distributed/checkpoint/utils.py,sha256=NjB3CRIWfeC-3njrOJfvtNCA70vW_hVOgjpaXoNxlhw,16659 +torch/distributed/collective_utils.py,sha256=WBSF7k5YyIT6Q1mE6PXDod8f0VvhGZ0dxl5ltsRNAv8,11844 +torch/distributed/config.py,sha256=KYBnbLgi9VfCjoD13e0I6N7sDknSwV39lWs7pickh04,2074 +torch/distributed/constants.py,sha256=V6gthYXMG3nf08ObvYceJaNu43yLAVCZ6LXhCGAaKMo,1198 +torch/distributed/debug/__init__.py,sha256=yum5WBYZF3tv8sHQLCjrAUUYmyEHWKsTQXKZb34aOpI,5272 +torch/distributed/debug/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/debug/__pycache__/_debug_handlers.cpython-312.pyc,, +torch/distributed/debug/__pycache__/_frontend.cpython-312.pyc,, +torch/distributed/debug/__pycache__/_handlers.cpython-312.pyc,, +torch/distributed/debug/__pycache__/_store.cpython-312.pyc,, +torch/distributed/debug/_debug_handlers.py,sha256=7NVkVwTEy_JgZshVp1VsqP6I7ExQAqVOwmq6o9St2fo,24904 +torch/distributed/debug/_frontend.py,sha256=9IkNq2lu69IHSSD6mCRtI7uNVja2fO68kGOq_xnP9U8,14592 +torch/distributed/debug/_handlers.py,sha256=k9NoN59EZUgvdL41w2qfXRvSgn_WHk_tp8HNEgSq1qQ,776 +torch/distributed/debug/_store.py,sha256=mjjNaR1pizABV2Q8w9Ap9COIewtpt76VyIiwJMXj7gM,532 +torch/distributed/device_mesh.py,sha256=ZzvKV7eLYG1dSjDn4LHMjnf9ymc6dqh6xC0OLICBEeQ,82361 +torch/distributed/distributed_c10d.py,sha256=_6PegRWclsGhBCyOK85S-2BM1-CDZ169e-2aEtnAFDs,312371 +torch/distributed/elastic/__init__.py,sha256=X9aMW4yXe5zLqRIRC74DobpSPfIftNSLby8-h-2iwWg,3651 +torch/distributed/elastic/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/elastic/__pycache__/control_plane.cpython-312.pyc,, +torch/distributed/elastic/agent/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/distributed/elastic/agent/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/elastic/agent/server/__init__.py,sha256=SysPaGhEiqz58ZWcMXuo4oG6YF7cj9vqvJycU9BmVDU,1386 +torch/distributed/elastic/agent/server/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/elastic/agent/server/__pycache__/api.cpython-312.pyc,, +torch/distributed/elastic/agent/server/__pycache__/health_check_server.cpython-312.pyc,, +torch/distributed/elastic/agent/server/__pycache__/local_elastic_agent.cpython-312.pyc,, +torch/distributed/elastic/agent/server/api.py,sha256=Yl-kzPD6K-rsTc7hrZlanStPzrpSVGz2C8lDyz8yivw,39500 +torch/distributed/elastic/agent/server/health_check_server.py,sha256=COfBo19yEdY7KRXgKJhpWiKwX22RwmDoiDoD1nwSNrQ,1790 +torch/distributed/elastic/agent/server/local_elastic_agent.py,sha256=kJqb-JKUxt9PKnQ09Sia_ndmS0todQpHB00eg2qhGUo,27389 +torch/distributed/elastic/control_plane.py,sha256=CIEn_-QwyReSAwgjBgUzzbzk8uXOFyEx-2fKdVcAc4o,1181 +torch/distributed/elastic/events/__init__.py,sha256=k83x2pO6IBwDnD-pfsC6iDKi_QGt7aN2DG53gKxMi3w,5328 +torch/distributed/elastic/events/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/elastic/events/__pycache__/api.cpython-312.pyc,, +torch/distributed/elastic/events/__pycache__/handlers.cpython-312.pyc,, +torch/distributed/elastic/events/api.py,sha256=7o8OinQr8d4hXR6tp_kVNn2EPeVTXfj3dm478Fwtyfw,3310 +torch/distributed/elastic/events/handlers.py,sha256=GVwoHQQFcpFeDW6eobtpDADBX8eIxYCN0tsiFO2pcDQ,556 +torch/distributed/elastic/metrics/__init__.py,sha256=xS6qug05is0GzU35vunqhiSUYukyqeJhNY6f50ojBoY,4880 +torch/distributed/elastic/metrics/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/elastic/metrics/__pycache__/api.cpython-312.pyc,, +torch/distributed/elastic/metrics/api.py,sha256=KGdw_W79IGlKYN7GM_qYTZ_0dGjO5CthWLxhgBY1d4E,5751 +torch/distributed/elastic/multiprocessing/__init__.py,sha256=iE8pcI-PcVytdKeZFGPbZElArfS79-pHEIRJOURgLh0,8684 +torch/distributed/elastic/multiprocessing/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/elastic/multiprocessing/__pycache__/api.cpython-312.pyc,, +torch/distributed/elastic/multiprocessing/__pycache__/redirects.cpython-312.pyc,, +torch/distributed/elastic/multiprocessing/__pycache__/tail_log.cpython-312.pyc,, +torch/distributed/elastic/multiprocessing/api.py,sha256=RQQYi7ppYc6LTro6YVWaE3Lq71vMNxAwpCnliobSEtI,40342 +torch/distributed/elastic/multiprocessing/errors/__init__.py,sha256=pj3NRgDK2CYU5b9sNzd3szVacjmNXpOnDrzJaPEnYpA,15611 +torch/distributed/elastic/multiprocessing/errors/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/elastic/multiprocessing/errors/__pycache__/error_handler.cpython-312.pyc,, +torch/distributed/elastic/multiprocessing/errors/__pycache__/handlers.cpython-312.pyc,, +torch/distributed/elastic/multiprocessing/errors/error_handler.py,sha256=Ec0bLOKyZ2B9nN9SGJQHhmI2VTbr7txvCgrTxiCd5GM,7300 +torch/distributed/elastic/multiprocessing/errors/handlers.py,sha256=ea-3iQUTQRDp_YAUhk-3hZ2HQyCPqz_2iiL5_xfD9Q8,464 +torch/distributed/elastic/multiprocessing/redirects.py,sha256=3aHUQLQUtUNGS0gZC1ERohSsEQzHX0BcebCy8tTGIaQ,7639 +torch/distributed/elastic/multiprocessing/subprocess_handler/__init__.py,sha256=pz2OzruD8OBIFFxiI1_TLy0Bd8LDBKNLowzW1_jZUSs,523 +torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/handlers.cpython-312.pyc,, +torch/distributed/elastic/multiprocessing/subprocess_handler/__pycache__/subprocess_handler.cpython-312.pyc,, +torch/distributed/elastic/multiprocessing/subprocess_handler/handlers.py,sha256=iqetloWZn4hjEoGUlefmHE1RCAP2DF1ht2MZ3Pu96aA,849 +torch/distributed/elastic/multiprocessing/subprocess_handler/subprocess_handler.py,sha256=GahJd4UoMjsdviHF_4MX-2B5_7nb1JBgXKQm-kyyqv4,2721 +torch/distributed/elastic/multiprocessing/tail_log.py,sha256=NOK1sJl6QEDZQBDFoKzOEASbIx8b2hUXWjRYW6hGyaw,5273 +torch/distributed/elastic/rendezvous/__init__.py,sha256=HqnbAbmnwHMXjz-mTv-ZndXQBrhawk1Zowkl6bGcV0Y,6261 +torch/distributed/elastic/rendezvous/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/elastic/rendezvous/__pycache__/_etcd_stub.cpython-312.pyc,, +torch/distributed/elastic/rendezvous/__pycache__/api.cpython-312.pyc,, +torch/distributed/elastic/rendezvous/__pycache__/c10d_rendezvous_backend.cpython-312.pyc,, +torch/distributed/elastic/rendezvous/__pycache__/dynamic_rendezvous.cpython-312.pyc,, +torch/distributed/elastic/rendezvous/__pycache__/etcd_rendezvous.cpython-312.pyc,, +torch/distributed/elastic/rendezvous/__pycache__/etcd_rendezvous_backend.cpython-312.pyc,, +torch/distributed/elastic/rendezvous/__pycache__/etcd_server.cpython-312.pyc,, +torch/distributed/elastic/rendezvous/__pycache__/etcd_store.cpython-312.pyc,, +torch/distributed/elastic/rendezvous/__pycache__/registry.cpython-312.pyc,, +torch/distributed/elastic/rendezvous/__pycache__/static_tcp_rendezvous.cpython-312.pyc,, +torch/distributed/elastic/rendezvous/__pycache__/utils.cpython-312.pyc,, +torch/distributed/elastic/rendezvous/_etcd_stub.py,sha256=r_XAqXKOwrTjmltbMyiKUPVsHtMe7sylfnzdVYvaVek,1998 +torch/distributed/elastic/rendezvous/api.py,sha256=7JVf9KCd8cM5hP_ZNK0LBps1WVC_0rJzQQLvB6GdK-k,13079 +torch/distributed/elastic/rendezvous/c10d_rendezvous_backend.py,sha256=OvFOYyc1t_xtr6HU-s07_PGJWIG84P_-lkENd67ajx4,10734 +torch/distributed/elastic/rendezvous/dynamic_rendezvous.py,sha256=pb-z71P_5jy6v0C2jig-X6Qqj89VA5n8GPhdOhVyEY8,49585 +torch/distributed/elastic/rendezvous/etcd_rendezvous.py,sha256=AJEL20kufZzS2HkaL7sBb5RKRpXTjBBTpcWBj9U3bhE,43554 +torch/distributed/elastic/rendezvous/etcd_rendezvous_backend.py,sha256=XZuUh07lz-BRnijj6_tjDuqym5ktM-PFwHxYkpCRsEA,7348 +torch/distributed/elastic/rendezvous/etcd_server.py,sha256=zldHbaMItTdUI74uIH3Z31q2hjKe0zNHJ_3IaLEDDq4,8397 +torch/distributed/elastic/rendezvous/etcd_store.py,sha256=CjxMeTxKCGTXZ7QwNiH8kLmZLU2LzGv1AbPWsUJpj6Y,7258 +torch/distributed/elastic/rendezvous/registry.py,sha256=uhizddahfTJgSBCIFnfbYR8-f_dl72ORAp2kl52WMHk,2964 +torch/distributed/elastic/rendezvous/static_tcp_rendezvous.py,sha256=Vni_9RgotHveIpmEOwUGcGbScwsx-mh9VwtHFr-XNPs,3652 +torch/distributed/elastic/rendezvous/utils.py,sha256=a6zE7cw46I_XvXM8oHaiX66V3Ye7bQ8T0z2rCPcZ65o,8373 +torch/distributed/elastic/timer/__init__.py,sha256=8FiqC33-LvUXVJ99aJk0KuZG81DREagN6IAL9OaiVRY,1666 +torch/distributed/elastic/timer/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/elastic/timer/__pycache__/api.cpython-312.pyc,, +torch/distributed/elastic/timer/__pycache__/debug_info_logging.cpython-312.pyc,, +torch/distributed/elastic/timer/__pycache__/file_based_local_timer.cpython-312.pyc,, +torch/distributed/elastic/timer/__pycache__/local_timer.cpython-312.pyc,, +torch/distributed/elastic/timer/api.py,sha256=Yz2EBr10AegpQNJrPvQOO7MyZ8-PHfO_6BM8GoQltpQ,9559 +torch/distributed/elastic/timer/debug_info_logging.py,sha256=6mix9Su3bo9BVTM_QXNz75c-WAbDLL8jNbojKbjdEsE,610 +torch/distributed/elastic/timer/file_based_local_timer.py,sha256=OXtzd_N19NA27YJ986lupwk4b9dRB5O5Lklzfr5VepM,16389 +torch/distributed/elastic/timer/local_timer.py,sha256=yaOwmn9FXPTMJ57ubJ0K7TYkWkAeCqY4WF9pMpjrXMg,4282 +torch/distributed/elastic/utils/__init__.py,sha256=nz8JjJdfhHqaWCDg0gTh9IGJIJ-ZJeJSOhZ2mLvNIpQ,304 +torch/distributed/elastic/utils/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/elastic/utils/__pycache__/api.cpython-312.pyc,, +torch/distributed/elastic/utils/__pycache__/distributed.cpython-312.pyc,, +torch/distributed/elastic/utils/__pycache__/log_level.cpython-312.pyc,, +torch/distributed/elastic/utils/__pycache__/logging.cpython-312.pyc,, +torch/distributed/elastic/utils/__pycache__/process_state.cpython-312.pyc,, +torch/distributed/elastic/utils/__pycache__/store.cpython-312.pyc,, +torch/distributed/elastic/utils/api.py,sha256=QMd6BGMe0lVXYnOSMLinlB3Hh_EJn2s6R3Cre2K2l0s,1705 +torch/distributed/elastic/utils/data/__init__.py,sha256=jNJBzRNbhmCOjJG3Bk4w_YYrUvBeQEDPiWfpHNRPMrM,344 +torch/distributed/elastic/utils/data/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/elastic/utils/data/__pycache__/cycling_iterator.cpython-312.pyc,, +torch/distributed/elastic/utils/data/__pycache__/elastic_distributed_sampler.cpython-312.pyc,, +torch/distributed/elastic/utils/data/cycling_iterator.py,sha256=T74d2dY-bCXqIYc0kHK0EMCFYAO54c-5otSzMHusDtQ,1643 +torch/distributed/elastic/utils/data/elastic_distributed_sampler.py,sha256=-rTvCe6GL1Ys15687nvWEgUXsF-vaIFhTV_al5o9Rzk,3074 +torch/distributed/elastic/utils/distributed.py,sha256=9jiY0nz4rd9upwVMlLnERgIex8bRBOEA6qsdJYIX7SI,5527 +torch/distributed/elastic/utils/log_level.py,sha256=1pOw0YanV5aPrMGwqkATk8OTXm6iLF2iuUYKbUf1b6Q,339 +torch/distributed/elastic/utils/logging.py,sha256=UoUWU9dJZBAlYRI833CcdGPSXtTeXt7cQ7pvIJtcFxM,2291 +torch/distributed/elastic/utils/process_state.py,sha256=uTP960rGrcNN2FnO6U54ECONGhMkA5EKzqraCYTfYCw,1801 +torch/distributed/elastic/utils/store.py,sha256=3lCBVsuMXBMCmL3HbqAEGCj3IKcR37vVBA2CfcbtsKA,7275 +torch/distributed/flight_recorder/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/distributed/flight_recorder/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/flight_recorder/__pycache__/fr_trace.cpython-312.pyc,, +torch/distributed/flight_recorder/components/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/distributed/flight_recorder/components/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/flight_recorder/components/__pycache__/builder.cpython-312.pyc,, +torch/distributed/flight_recorder/components/__pycache__/config_manager.cpython-312.pyc,, +torch/distributed/flight_recorder/components/__pycache__/fr_logger.cpython-312.pyc,, +torch/distributed/flight_recorder/components/__pycache__/loader.cpython-312.pyc,, +torch/distributed/flight_recorder/components/__pycache__/types.cpython-312.pyc,, +torch/distributed/flight_recorder/components/__pycache__/utils.cpython-312.pyc,, +torch/distributed/flight_recorder/components/builder.py,sha256=0rYMSxYwk4wToC3-9CbA7QFFOIhJiSJqnRsjNvul3B4,18485 +torch/distributed/flight_recorder/components/config_manager.py,sha256=PmiQ3g-8Av1cSEM5OTktUEoJOPI5sUVUnU_q5E2LXrw,3994 +torch/distributed/flight_recorder/components/fr_logger.py,sha256=DLnrDoW3Pgy0oBUjGpKWo_LCmiWQuJ59MyWlsv9Zknw,1528 +torch/distributed/flight_recorder/components/loader.py,sha256=4iJXoT8Kizb-dsu8mV6ivQFSD2FdnQ24iYfnKxl1jn8,3326 +torch/distributed/flight_recorder/components/types.py,sha256=Ln7u2uQo0x87WWfe5jAItd4MNCbxqvbCfWwtX2JTWpQ,23551 +torch/distributed/flight_recorder/components/utils.py,sha256=AgVS7awRS6x9HH-x7yjMBtcJjlJgw7fy4f4dmYqazP4,29502 +torch/distributed/flight_recorder/fr_trace.py,sha256=xxVNSrInrHPW7FUw4OkQ8zm2L_9AOosx4jfOtCGGChw,3066 +torch/distributed/fsdp/__init__.py,sha256=O_Vc-R5chY3IH5f9-TEA6JsGeqQovCJhFIwv-abthkM,1948 +torch/distributed/fsdp/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_common_utils.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_debug_utils.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_dynamo_utils.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_exec_order_utils.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_flat_param.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_fsdp_extensions.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_init_utils.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_limiter_utils.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_optim_utils.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_runtime_utils.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_shard_utils.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_state_dict_utils.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_trace_utils.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_traversal_utils.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_unshard_param_utils.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/_wrap_utils.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/api.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/fully_sharded_data_parallel.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/sharded_grad_scaler.cpython-312.pyc,, +torch/distributed/fsdp/__pycache__/wrap.cpython-312.pyc,, +torch/distributed/fsdp/_common_utils.py,sha256=spEi9t3f5IgXikFTJxqay2DN_MAImXALXXRm_N60mPA,29281 +torch/distributed/fsdp/_debug_utils.py,sha256=1SmIdIGZ42D8y-OWBbbTXCTvh7hf82h0jn2SbRquSc4,5818 +torch/distributed/fsdp/_dynamo_utils.py,sha256=_YtXy6KD9FUp--G1z7xpA4rrcSWFnF0bMkRtcDptpeg,2631 +torch/distributed/fsdp/_exec_order_utils.py,sha256=ABP3RPdGDXc2YGMpXAy23So3ku7ce7DXjpfaZM4EVq0,16079 +torch/distributed/fsdp/_flat_param.py,sha256=6ih_jWtk87-cHzK9BKZLFWd1aC_nuT7HORkJ2A2Q6Y4,126271 +torch/distributed/fsdp/_fsdp_extensions.py,sha256=iGFirKzsyf3OEeKV8v2fB9dkkmBP8GlSS-vg6N92AOI,4987 +torch/distributed/fsdp/_fully_shard/__init__.py,sha256=uXSibxJe0zL41WR-oTOtpzPSk6Wxq6UTSc6ge0kYO38,489 +torch/distributed/fsdp/_fully_shard/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_api.cpython-312.pyc,, +torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_collectives.cpython-312.pyc,, +torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_common.cpython-312.pyc,, +torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_init.cpython-312.pyc,, +torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_param.cpython-312.pyc,, +torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_param_group.cpython-312.pyc,, +torch/distributed/fsdp/_fully_shard/__pycache__/_fsdp_state.cpython-312.pyc,, +torch/distributed/fsdp/_fully_shard/__pycache__/_fully_shard.cpython-312.pyc,, +torch/distributed/fsdp/_fully_shard/_fsdp_api.py,sha256=G6C6spWFNMnruQUtKwzpf3EREmDhySEQTC2IaAbYBwg,7045 +torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py,sha256=vRwwoeWoUJ_fEnMJ8k6WpHDT5J3pS77Oc8AHGecRlX4,34007 +torch/distributed/fsdp/_fully_shard/_fsdp_common.py,sha256=XGjzC1DZaoXeYeZyFlvK93CK-SrkFAQnhm0Oco6sSmY,7747 +torch/distributed/fsdp/_fully_shard/_fsdp_init.py,sha256=XOy8BLFl3O-6Znm0yeX9748xkGo_2DTJfe4QcXlICRg,20750 +torch/distributed/fsdp/_fully_shard/_fsdp_param.py,sha256=jD_wDzMUJ6In3emBTq8gsxq8NKoRD_Etgq8u1Ovz0Tc,60038 +torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py,sha256=BJQN3qD3rt9MX66wULAQJ7WMXA_Z5RdJZFdVuuCYtaY,55010 +torch/distributed/fsdp/_fully_shard/_fsdp_state.py,sha256=AJBwRy3PA0s7XsmJnVnV4G_qyWG6NV_79ktc5xdq7QU,29531 +torch/distributed/fsdp/_fully_shard/_fully_shard.py,sha256=RTaryE3DQ9g_tvnHMnJYl3LBe6zzQOg6XgceJP97HF4,45213 +torch/distributed/fsdp/_init_utils.py,sha256=dtuIbViZO2AnpAlAJisVaJ_NDC3CRB7fwJA8Y7lzYvI,48519 +torch/distributed/fsdp/_limiter_utils.py,sha256=Uer7diNEpPlQG9ijdEwkh8K0d9iJl2texk_ArIz7euk,1052 +torch/distributed/fsdp/_optim_utils.py,sha256=ULmbAV6hXd71SebSAo81ta8iG-dnXiSJ0xBktyaUaLE,89773 +torch/distributed/fsdp/_runtime_utils.py,sha256=Nekjyo2EJNfbG7cbPieBrTZ9gcz2XpKvdVTfCfuVspw,66906 +torch/distributed/fsdp/_shard_utils.py,sha256=AGaV_w5lUNKQN82bixSlIYsf5f5gazKGcRg4bGyLgnU,4826 +torch/distributed/fsdp/_state_dict_utils.py,sha256=mKgkBfQRsLp5hZaLkbnDnRdY1FFmQgk1Uo8Ham1K27k,34718 +torch/distributed/fsdp/_trace_utils.py,sha256=JLa_T89INq4QDKVN1w9qQcaXtTW2-8HXqkEcxtpEUBI,10798 +torch/distributed/fsdp/_traversal_utils.py,sha256=haGRJUg9EyPuRJjUyUWfBDaRmEdJ7VOaOPi722DQ2Xg,4610 +torch/distributed/fsdp/_unshard_param_utils.py,sha256=qSz0_G8u9KmRsW4x-aKskHT6y8cPNl1SVsUeMwaFzAs,11659 +torch/distributed/fsdp/_wrap_utils.py,sha256=HTP04Ufv2Ap_RU-t6EYLoTaNchePvYOAXOFyTpVcyGc,10946 +torch/distributed/fsdp/api.py,sha256=QzyR5LX5OC6GdiPvZFq_SJbF8-UD4i07X-l_0-WSJBQ,18938 +torch/distributed/fsdp/fully_sharded_data_parallel.py,sha256=FTPIj3VJztHNVGFfe_Ke1d0De002iYt-bP5ZT4IKcs8,100777 +torch/distributed/fsdp/sharded_grad_scaler.py,sha256=tlCrjpSc0jIQQHGyAVFAKpHblbcTtZQg0enK1z_yNJQ,17057 +torch/distributed/fsdp/wrap.py,sha256=bFgUTmDiPzwF3sWm_5QpqowOVJ0uRK-PXvtBEuhtSqo,23110 +torch/distributed/launch.py,sha256=e7R-D1Wy1X98YSTVQESxOkDBA3UwCkrzpEzraXovYYc,7595 +torch/distributed/launcher/__init__.py,sha256=XUaKCldw6UZi2EJB83Ejjhwj1835SLdfAM9Tqj-qFZ8,318 +torch/distributed/launcher/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/launcher/__pycache__/api.cpython-312.pyc,, +torch/distributed/launcher/api.py,sha256=4znju2LCZUWhcrQWHLI_0BaRBI5AHjK1J9v6_A2VKfk,16817 +torch/distributed/logging_handlers.py,sha256=nXuxHnOEhAHqqDPhTk_-aLYIVHoZpQEYW_X4N1Qg0_Q,359 +torch/distributed/nn/__init__.py,sha256=Ta4l0Jr2gOK7eQR-e32stWaDKPOlV_Kii0SExydXk_Q,145 +torch/distributed/nn/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/nn/__pycache__/functional.cpython-312.pyc,, +torch/distributed/nn/api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/distributed/nn/api/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/nn/api/__pycache__/remote_module.cpython-312.pyc,, +torch/distributed/nn/api/remote_module.py,sha256=HgXhfAA32lLaByw1PLfy-jF5LPOE5HnODDnvgD6VFFg,31378 +torch/distributed/nn/functional.py,sha256=YouLTjP8tgdHCJNtw9r1MpGQgBQsqgWrp5HUZHOiqrg,18373 +torch/distributed/nn/jit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/distributed/nn/jit/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/nn/jit/__pycache__/instantiator.cpython-312.pyc,, +torch/distributed/nn/jit/instantiator.py,sha256=IhEEPfRwITTS2oQipmVr_w1So9sAgOSsPgi0ff-XrCg,6198 +torch/distributed/nn/jit/templates/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/distributed/nn/jit/templates/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/nn/jit/templates/__pycache__/remote_module_template.cpython-312.pyc,, +torch/distributed/nn/jit/templates/remote_module_template.py,sha256=D_GFa70DG1KY1GwGwFAqvCC9gE9CwZSe1BJ-jHc2YMw,3463 +torch/distributed/optim/__init__.py,sha256=HxJ6GIWc3b6uAZWNh45oePXlQLAdX9Kmu3PByAOvlh4,1440 +torch/distributed/optim/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/optim/__pycache__/_deprecation_warning.cpython-312.pyc,, +torch/distributed/optim/__pycache__/apply_optimizer_in_backward.cpython-312.pyc,, +torch/distributed/optim/__pycache__/functional_adadelta.cpython-312.pyc,, +torch/distributed/optim/__pycache__/functional_adagrad.cpython-312.pyc,, +torch/distributed/optim/__pycache__/functional_adam.cpython-312.pyc,, +torch/distributed/optim/__pycache__/functional_adamax.cpython-312.pyc,, +torch/distributed/optim/__pycache__/functional_adamw.cpython-312.pyc,, +torch/distributed/optim/__pycache__/functional_rmsprop.cpython-312.pyc,, +torch/distributed/optim/__pycache__/functional_rprop.cpython-312.pyc,, +torch/distributed/optim/__pycache__/functional_sgd.cpython-312.pyc,, +torch/distributed/optim/__pycache__/named_optimizer.cpython-312.pyc,, +torch/distributed/optim/__pycache__/optimizer.cpython-312.pyc,, +torch/distributed/optim/__pycache__/post_localSGD_optimizer.cpython-312.pyc,, +torch/distributed/optim/__pycache__/utils.cpython-312.pyc,, +torch/distributed/optim/__pycache__/zero_redundancy_optimizer.cpython-312.pyc,, +torch/distributed/optim/_deprecation_warning.py,sha256=4lon9fWNrTNS4ARfi5Dag5tvohwNyPMflHBl9VFd_0E,547 +torch/distributed/optim/apply_optimizer_in_backward.py,sha256=uTNZylxBaBVQK1teYyPJ7R45-t8aqG6joeGT3qyi0AQ,5214 +torch/distributed/optim/functional_adadelta.py,sha256=xIiXYjcpL6aMa4pKUSFzBxCHwewT3SFyor5-wNFfRDk,3882 +torch/distributed/optim/functional_adagrad.py,sha256=fQKpyh9Qg1c3arJ_BPkB0nyMlTw_jS6QU0FRg77ICkk,4232 +torch/distributed/optim/functional_adam.py,sha256=Eqk40kt87Ekryr5q5VXl08UEEhQDLkr98NmFCysaYOI,7350 +torch/distributed/optim/functional_adamax.py,sha256=tUMKjTXkL21YHloDHcnd7d9cwvZK2dRbZ6Y_VAn5K1k,4579 +torch/distributed/optim/functional_adamw.py,sha256=rFc0dtgbsVelnQBFO6uAqC4SJhOnLco9NAh0ip7nEsM,7470 +torch/distributed/optim/functional_rmsprop.py,sha256=ihYpIqmramhkg5K1yMaDRnddD9hrTfoX4xACJI6txj4,4612 +torch/distributed/optim/functional_rprop.py,sha256=Dt6oiFGsj2bAKm6H5PLbtxwnojOBp8R5FXE6GGUy-I8,3766 +torch/distributed/optim/functional_sgd.py,sha256=Ga0wtIUC0AO17UjPAB3hWo-wruex80KXuSxDqKlrl2w,5857 +torch/distributed/optim/named_optimizer.py,sha256=aNJYAGJqZ_9Yf0OGCTFQV-u0My_-WXwyIo6EdTjirRE,14191 +torch/distributed/optim/optimizer.py,sha256=MOnnevbrB7BqyUBa4Q13GcaoEADEVmR15M6Ygf6H29U,8533 +torch/distributed/optim/post_localSGD_optimizer.py,sha256=MT7Kno6EvcmnjAiQGJdsgOnKXpHXqm9Sm9QnHzV-EP4,4498 +torch/distributed/optim/utils.py,sha256=RCqwRVNFbVAzYYSSkucTMR-nMKb6r2lpeXXCQyTlTmY,2242 +torch/distributed/optim/zero_redundancy_optimizer.py,sha256=ayQZrwL27dLOSYxyNOZIYfrjphOrc7Jiq9D1jpvU6dE,73743 +torch/distributed/optim/zero_redundancy_optimizer.pyi,sha256=I-G_ysSHrYjja75Vn5DPbuSCtyE4g_Pg_Mp28EBA0Js,2852 +torch/distributed/pipelining/_IR.py,sha256=vnrAWYvQjQw7ridJthdG-nn0VqvSJZYRbDMXCyyslxg,51128 +torch/distributed/pipelining/__init__.py,sha256=ywlBKSDSFkgi5wBXXS02nJ_srC1l2ACoCkI1PtDjcDY,689 +torch/distributed/pipelining/__pycache__/_IR.cpython-312.pyc,, +torch/distributed/pipelining/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/pipelining/__pycache__/_backward.cpython-312.pyc,, +torch/distributed/pipelining/__pycache__/_debug.cpython-312.pyc,, +torch/distributed/pipelining/__pycache__/_schedule_visualizer.cpython-312.pyc,, +torch/distributed/pipelining/__pycache__/_unflatten.cpython-312.pyc,, +torch/distributed/pipelining/__pycache__/_utils.cpython-312.pyc,, +torch/distributed/pipelining/__pycache__/microbatch.cpython-312.pyc,, +torch/distributed/pipelining/__pycache__/schedules.cpython-312.pyc,, +torch/distributed/pipelining/__pycache__/stage.cpython-312.pyc,, +torch/distributed/pipelining/_backward.py,sha256=ijs_fKTNKKK96WB5zFlFqbloixPp84IswioG8Geof4A,19075 +torch/distributed/pipelining/_debug.py,sha256=dDUjgp_-XnUEsM4I-zj5-yQGxcapHbBb3JcRSdRuCqc,608 +torch/distributed/pipelining/_schedule_visualizer.py,sha256=hMEVbu-QGoWay1R9ZdGiBJ-ktVeT3ETQWhwTSNXaC2I,17556 +torch/distributed/pipelining/_unflatten.py,sha256=GUpLGbhqxbAMjcY9aDxandxUd3Rva1aXs4BRApx9Gj8,952 +torch/distributed/pipelining/_utils.py,sha256=ERy7u_9X6n5uFE870TX7W-jK_XFNPz_cCzor4vYfdx0,32666 +torch/distributed/pipelining/microbatch.py,sha256=ZgjDGZcN3epCeAlIwaHgJy_wDPI46pu_ilW1NpfuYBs,23302 +torch/distributed/pipelining/schedules.py,sha256=pSGg5FxnowE02C2GFTOIuquIjP8fOYrpsT3wvMUqes4,169582 +torch/distributed/pipelining/stage.py,sha256=osOjGrpfizke12B7nOZUi4XPhAUI2aySJ82ERAtAZK8,104491 +torch/distributed/remote_device.py,sha256=FaHtxJp4aLyH63gBkigD-p3lJ67NZCgWkYEUNPKYvok,4545 +torch/distributed/rendezvous.py,sha256=Lv1lSTbmaZHXTMtBTu6tgktrwrpEWfNDsrvk0Fk0Xfs,10905 +torch/distributed/rpc/__init__.py,sha256=8RVj5m9Xxkhqrt0oYB3IVhlomxyxTMukeUIuBkrvYIk,9929 +torch/distributed/rpc/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/rpc/__pycache__/_utils.cpython-312.pyc,, +torch/distributed/rpc/__pycache__/api.cpython-312.pyc,, +torch/distributed/rpc/__pycache__/backend_registry.cpython-312.pyc,, +torch/distributed/rpc/__pycache__/constants.cpython-312.pyc,, +torch/distributed/rpc/__pycache__/functions.cpython-312.pyc,, +torch/distributed/rpc/__pycache__/internal.cpython-312.pyc,, +torch/distributed/rpc/__pycache__/options.cpython-312.pyc,, +torch/distributed/rpc/__pycache__/rref_proxy.cpython-312.pyc,, +torch/distributed/rpc/__pycache__/server_process_global_profiler.cpython-312.pyc,, +torch/distributed/rpc/_testing/__init__.py,sha256=xSU_1OK5D0vaFTGSxPlzX6Ad4CEvsZv7DIJYY1d2Unk,479 +torch/distributed/rpc/_testing/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/rpc/_testing/__pycache__/faulty_agent_backend_registry.cpython-312.pyc,, +torch/distributed/rpc/_testing/faulty_agent_backend_registry.py,sha256=KmeZ2KHDwSWJB3mdfA06hdaabt25vKkkUU1h8SFVk1o,1639 +torch/distributed/rpc/_utils.py,sha256=tcq0ADOGMmd7OkKYFY7apu6c44VbgFLxCLOCh-aiyvU,1649 +torch/distributed/rpc/api.py,sha256=94J2hPO-_GzAWJvzlaH6YC-LHW42YkJGyFpuPy4n2Ds,37472 +torch/distributed/rpc/backend_registry.py,sha256=NS3b9B832oTUUXndwZrgpkC6bNkL6gX1k22y3vcD0Uc,16553 +torch/distributed/rpc/constants.py,sha256=AFzuxIi9gIVxb9nyZNZ6h70Is-DUMsCHZ-WEO3MOMP8,804 +torch/distributed/rpc/functions.py,sha256=9sE_wYiqlfUmb6AFBFPmOq6PApwYKxosNOnteoy_0Oc,7272 +torch/distributed/rpc/internal.py,sha256=fENvWtOvU-AdAPRg9XnpYHW_KDQVfmfAbA5-qQxj03Q,11121 +torch/distributed/rpc/options.py,sha256=uSupCGgnrJNCf3E0eIaH4hySXM7vT-1gslMx6k3ceXw,7218 +torch/distributed/rpc/rref_proxy.py,sha256=bPOl84AgbjVatkfra07qRpPmklWiOQUHpLu4pltkvMw,2677 +torch/distributed/rpc/server_process_global_profiler.py,sha256=NpQiYNSv10xOWQbtvbYrg3Q2nXdE6BuHTz82BkUyCak,8477 +torch/distributed/run.py,sha256=fUjR4op-PP9i4loD2ZXbWzry8Mc9rLm-2L5BEa7q5kA,40973 +torch/distributed/tensor/__init__.py,sha256=92qnyGAkERW0PjIbVpOSwP3gsUoPMjQJgpPnZQ9z7hs,2583 +torch/distributed/tensor/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/_api.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/_collective_utils.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/_decompositions.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/_dispatch.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/_dtensor_spec.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/_nonlinear_redux.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/_op_schema.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/_random.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/_redistribute.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/_sharding_prop.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/_shards_wrapper.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/_tp_conv.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/_utils.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/device_mesh.cpython-312.pyc,, +torch/distributed/tensor/__pycache__/placement_types.cpython-312.pyc,, +torch/distributed/tensor/_api.py,sha256=hHi1niTsTxInqDQHkHaE4176yfu5uDOVAzCWZ_uLuSk,83174 +torch/distributed/tensor/_collective_utils.py,sha256=b6S8rfTRI3x4IA05zZ5ZswvARe6i3MOduXKQj0ItgCc,23949 +torch/distributed/tensor/_decompositions.py,sha256=k2LaeM1pTZL3XRyaPXIPNFm2DLwEvLyXy8Ys0H9rXm0,13303 +torch/distributed/tensor/_dispatch.py,sha256=IxOMg7kJJvqOyKshbUY6axgJmYTQc2zR9HEqc25nDVM,37213 +torch/distributed/tensor/_dtensor_spec.py,sha256=Ui9p62cHeND1oCAT_OsQqS4MUiJEhJLKAG68ZdpSKLA,33858 +torch/distributed/tensor/_nonlinear_redux.py,sha256=UFqHX3UluSPyhbVWCSR7sXVCIuobYMSAxPO1jApHGKA,10519 +torch/distributed/tensor/_op_schema.py,sha256=jQqKdOrnbQGiA-EpQyKM_cxEplRJ15-TGOrSUra5zHk,27930 +torch/distributed/tensor/_ops/__init__.py,sha256=5XiURvQhP8A28-uRenZqyz_AKygv8gE3tqC53pnU7QM,457 +torch/distributed/tensor/_ops/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/_common_rules.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/_conv_ops.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/_einsum_strategy.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/_embedding_ops.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/_mask_buffer.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/_math_ops.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/_matrix_ops.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/_pointwise_ops.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/_random_ops.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/_tensor_ops.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/_view_ops.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/autogen.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/single_dim_strategy.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/strategy_validation.cpython-312.pyc,, +torch/distributed/tensor/_ops/__pycache__/utils.cpython-312.pyc,, +torch/distributed/tensor/_ops/_common_rules.py,sha256=CrkCzkYP1auR_JsG87__4xt5B6SdazkARwOGeQby420,12000 +torch/distributed/tensor/_ops/_conv_ops.py,sha256=_3s83N4Locvs3TN9Rb3illeuH3vcmSlBmPLFOvm0yXU,10759 +torch/distributed/tensor/_ops/_einsum_strategy.py,sha256=gGM6LUYNEqXHN_slfFCXu1zt6tXkTQHJpQcIdVYLANc,7691 +torch/distributed/tensor/_ops/_embedding_ops.py,sha256=k1Y-FNAIqqqGkSlPMVLNlReARBV4ROReTEN5-V0mnG4,3338 +torch/distributed/tensor/_ops/_mask_buffer.py,sha256=c5sml3lk7LOlKaNNcH9VIU0uVC2qAT9GPcyBY-OhYEU,1562 +torch/distributed/tensor/_ops/_math_ops.py,sha256=UScZk3VW6yU_xuGygzyKmcNkTF0FmfPNgGeuYONkb24,72332 +torch/distributed/tensor/_ops/_matrix_ops.py,sha256=_SmURKYKg8Sav-xkKbrirlwpMiqHwC4EGNhL1czo5HQ,51260 +torch/distributed/tensor/_ops/_pointwise_ops.py,sha256=slREdDyMcHzzCqo-J6my2FCln2MJ7ZPspKRmJEs6c9s,19983 +torch/distributed/tensor/_ops/_random_ops.py,sha256=bY46dd98_KOJmzno67SN0CaRJvA9lypc9fWyJh0OLy8,2741 +torch/distributed/tensor/_ops/_tensor_ops.py,sha256=ILpeD-PcMS1eHZuEmc6NJ8p4fvqc3f45k4KjIy9qVLU,55096 +torch/distributed/tensor/_ops/_view_ops.py,sha256=nny5sUhXYozDQhehBX8i10ckoQ21u2kPXTiGgEd3vq0,61964 +torch/distributed/tensor/_ops/autogen.py,sha256=2U_-dHrsNZ4-MMAmPwxW98hhkWzz1UmAnPJ3FPPBoUo,20918 +torch/distributed/tensor/_ops/single_dim_strategy.py,sha256=DrZt35wELvj1DONmE-y2LbfKfCkNoqKNieQRUtYLNrw,51461 +torch/distributed/tensor/_ops/strategy_validation.py,sha256=fMJvuqLTCRUCab3yLnRv8XKq0E5PTugjIVFDcQjlnMA,84711 +torch/distributed/tensor/_ops/utils.py,sha256=1DwMXKcz_mgi3hAxaIvgW6yPDoAjLjoUU7W6mz7ONQY,31609 +torch/distributed/tensor/_random.py,sha256=xAmvpyY8Upk0zGq2VVsMHjkyiC5cU_yvvexyUYTN9sM,20404 +torch/distributed/tensor/_redistribute.py,sha256=QCfizPH8fvJ6WZZXEi5TBm_oQj1Fy4z6OZrIU_XRvIg,89189 +torch/distributed/tensor/_sharding_prop.py,sha256=myzTpv39Kp8MP6qiWDIj-3DToK1FIl4gbkfssuUny80,50423 +torch/distributed/tensor/_shards_wrapper.py,sha256=5be9ORGMQBhHwdtCTXfdPhX2v5yabh5pnfOM-qJbvrU,13593 +torch/distributed/tensor/_tp_conv.py,sha256=YVj2L60fW24vfBJz1Fd77tXd-xWJQkfMEaNkF3pLWQU,11372 +torch/distributed/tensor/_utils.py,sha256=Li5h8e3EP7egal-4EaCJVJ7a9_aU66THc-e43Bj-0JQ,21336 +torch/distributed/tensor/debug/__init__.py,sha256=1fkt2_pt90BuM0T1H6DWeWO12P_ivEOik7x4SIvrJFY,2446 +torch/distributed/tensor/debug/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/tensor/debug/__pycache__/_comm_mode.cpython-312.pyc,, +torch/distributed/tensor/debug/__pycache__/_op_coverage.cpython-312.pyc,, +torch/distributed/tensor/debug/__pycache__/_visualize_sharding.cpython-312.pyc,, +torch/distributed/tensor/debug/_comm_mode.py,sha256=_5c5Kj0VJDk3LZaSOVtf3IW0oYOiO0b76WM6FmntgAM,29451 +torch/distributed/tensor/debug/_op_coverage.py,sha256=ZUAJ2ixcT8AQb4qOc83_cFtk0WJkkwphRX7282LUctA,3168 +torch/distributed/tensor/debug/_visualize_sharding.py,sha256=P2rXbtLlKqci4CcKe_yIlWZCN2sGwR0vg624dLylSEk,7562 +torch/distributed/tensor/device_mesh.py,sha256=MONPC_i1XphcY2E0AAte1MW668BTlUGugMSQzfJqzik,190 +torch/distributed/tensor/experimental/__init__.py,sha256=9I70AFPtyjGyKxAuaBsRfDxvHyCeM5a7o7q3X1yUe5g,1424 +torch/distributed/tensor/experimental/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/tensor/experimental/__pycache__/_attention.cpython-312.pyc,, +torch/distributed/tensor/experimental/__pycache__/_func_map.cpython-312.pyc,, +torch/distributed/tensor/experimental/__pycache__/_register_sharding.cpython-312.pyc,, +torch/distributed/tensor/experimental/__pycache__/_tp_transform.cpython-312.pyc,, +torch/distributed/tensor/experimental/_attention.py,sha256=Hz6IsHinuWEYMWAMGzQMuVEYAHiJF3VqLQjIbysMBtw,1229 +torch/distributed/tensor/experimental/_context_parallel/__init__.py,sha256=6yKCIGx9a4EB26ST6wrFUihdq8SPHvOj8wPgehrHeb0,1130 +torch/distributed/tensor/experimental/_context_parallel/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/tensor/experimental/_context_parallel/__pycache__/_attention.cpython-312.pyc,, +torch/distributed/tensor/experimental/_context_parallel/__pycache__/_cp_custom_ops.cpython-312.pyc,, +torch/distributed/tensor/experimental/_context_parallel/__pycache__/_load_balancer.cpython-312.pyc,, +torch/distributed/tensor/experimental/_context_parallel/__pycache__/_sharding_rules.cpython-312.pyc,, +torch/distributed/tensor/experimental/_context_parallel/_attention.py,sha256=B-9Z6AD266wv0dPC_B2gXq1l7G5iWuSDN5-oJVQtTgs,62986 +torch/distributed/tensor/experimental/_context_parallel/_cp_custom_ops.py,sha256=ribgJeEWOzc_GrHsfbwH7t6fqGNKAALkgw1GSCmN4Lo,2969 +torch/distributed/tensor/experimental/_context_parallel/_load_balancer.py,sha256=e045xWcAzVa3unLL-wXgbh7Q79H2iF3DdwyVw4KFmjc,23469 +torch/distributed/tensor/experimental/_context_parallel/_sharding_rules.py,sha256=aBDS1JUugeKVSuyLn4pejaI9_fkJ4IT8my4DCci_FDA,11512 +torch/distributed/tensor/experimental/_func_map.py,sha256=fgF6gYQd-g6Cx3zmyJ2WvVbeWxrCdSVsFK25g8x48q8,22731 +torch/distributed/tensor/experimental/_register_sharding.py,sha256=9R8PjVMEesw-JpIuGcFruwR3gh5T9BxQHkOKjVvWo3U,5636 +torch/distributed/tensor/experimental/_tp_transform.py,sha256=rtodmb-7vFY1XuNr4WRjVYiRLWsoWyTWoYbvd-qxEeE,21142 +torch/distributed/tensor/parallel/__init__.py,sha256=_rDiCQ0mhllWr5HSDkOV47G4Z-WAZ3L1PCyzLhjgXeU,643 +torch/distributed/tensor/parallel/__pycache__/__init__.cpython-312.pyc,, +torch/distributed/tensor/parallel/__pycache__/_data_parallel_utils.cpython-312.pyc,, +torch/distributed/tensor/parallel/__pycache__/api.cpython-312.pyc,, +torch/distributed/tensor/parallel/__pycache__/ddp.cpython-312.pyc,, +torch/distributed/tensor/parallel/__pycache__/fsdp.cpython-312.pyc,, +torch/distributed/tensor/parallel/__pycache__/input_reshard.cpython-312.pyc,, +torch/distributed/tensor/parallel/__pycache__/loss.cpython-312.pyc,, +torch/distributed/tensor/parallel/__pycache__/style.cpython-312.pyc,, +torch/distributed/tensor/parallel/_data_parallel_utils.py,sha256=toFgFzlwhtjqPA6hOJjRFW4ZYjV77KZpmu2TssdBaPw,1498 +torch/distributed/tensor/parallel/api.py,sha256=lVZWDhgtU-Hd7WAkMIl2NbyeJAgSIzdrMLhSkuAc2xw,6475 +torch/distributed/tensor/parallel/ddp.py,sha256=ES69uXY8nKFKp7je9RQ7n8tP40GwcUekLGY00qAmL3c,3756 +torch/distributed/tensor/parallel/fsdp.py,sha256=L7mV2F5zxkdwc_dN0T3ketYhLuWBeYUTne1CbQlg5J4,14044 +torch/distributed/tensor/parallel/input_reshard.py,sha256=AxlKThwPNakeWlSTvbhLHNLTc_Su2no5qxn7dIMAEAs,3785 +torch/distributed/tensor/parallel/loss.py,sha256=tA2oz9aJcXSGoOZazPh_3_wkMbGw1q4wqlJqYcWGJb8,24976 +torch/distributed/tensor/parallel/style.py,sha256=hhcKLwaetx7HaTlcZGe8X0bAj0l4jAP_gQ6xsxixIzQ,37639 +torch/distributed/tensor/placement_types.py,sha256=A7BaV1g6jj34eWtKAO8ue7Ybz5sW8_rvqjREGVBDZuI,82475 +torch/distributed/utils.py,sha256=hoaFayQn2LAAXwtpkGR1-nkBtyT7NnIO-WMib5Okm_4,14287 +torch/distributions/__init__.py,sha256=eOQPqtRO4p3hTTAIdc_iwBye_6M6sL_KvI2LL9xV4Dc,6098 +torch/distributions/__pycache__/__init__.cpython-312.pyc,, +torch/distributions/__pycache__/bernoulli.cpython-312.pyc,, +torch/distributions/__pycache__/beta.cpython-312.pyc,, +torch/distributions/__pycache__/binomial.cpython-312.pyc,, +torch/distributions/__pycache__/categorical.cpython-312.pyc,, +torch/distributions/__pycache__/cauchy.cpython-312.pyc,, +torch/distributions/__pycache__/chi2.cpython-312.pyc,, +torch/distributions/__pycache__/constraint_registry.cpython-312.pyc,, +torch/distributions/__pycache__/constraints.cpython-312.pyc,, +torch/distributions/__pycache__/continuous_bernoulli.cpython-312.pyc,, +torch/distributions/__pycache__/dirichlet.cpython-312.pyc,, +torch/distributions/__pycache__/distribution.cpython-312.pyc,, +torch/distributions/__pycache__/exp_family.cpython-312.pyc,, +torch/distributions/__pycache__/exponential.cpython-312.pyc,, +torch/distributions/__pycache__/fishersnedecor.cpython-312.pyc,, +torch/distributions/__pycache__/gamma.cpython-312.pyc,, +torch/distributions/__pycache__/generalized_pareto.cpython-312.pyc,, +torch/distributions/__pycache__/geometric.cpython-312.pyc,, +torch/distributions/__pycache__/gumbel.cpython-312.pyc,, +torch/distributions/__pycache__/half_cauchy.cpython-312.pyc,, +torch/distributions/__pycache__/half_normal.cpython-312.pyc,, +torch/distributions/__pycache__/independent.cpython-312.pyc,, +torch/distributions/__pycache__/inverse_gamma.cpython-312.pyc,, +torch/distributions/__pycache__/kl.cpython-312.pyc,, +torch/distributions/__pycache__/kumaraswamy.cpython-312.pyc,, +torch/distributions/__pycache__/laplace.cpython-312.pyc,, +torch/distributions/__pycache__/lkj_cholesky.cpython-312.pyc,, +torch/distributions/__pycache__/log_normal.cpython-312.pyc,, +torch/distributions/__pycache__/logistic_normal.cpython-312.pyc,, +torch/distributions/__pycache__/lowrank_multivariate_normal.cpython-312.pyc,, +torch/distributions/__pycache__/mixture_same_family.cpython-312.pyc,, +torch/distributions/__pycache__/multinomial.cpython-312.pyc,, +torch/distributions/__pycache__/multivariate_normal.cpython-312.pyc,, +torch/distributions/__pycache__/negative_binomial.cpython-312.pyc,, +torch/distributions/__pycache__/normal.cpython-312.pyc,, +torch/distributions/__pycache__/one_hot_categorical.cpython-312.pyc,, +torch/distributions/__pycache__/pareto.cpython-312.pyc,, +torch/distributions/__pycache__/poisson.cpython-312.pyc,, +torch/distributions/__pycache__/relaxed_bernoulli.cpython-312.pyc,, +torch/distributions/__pycache__/relaxed_categorical.cpython-312.pyc,, +torch/distributions/__pycache__/studentT.cpython-312.pyc,, +torch/distributions/__pycache__/transformed_distribution.cpython-312.pyc,, +torch/distributions/__pycache__/transforms.cpython-312.pyc,, +torch/distributions/__pycache__/uniform.cpython-312.pyc,, +torch/distributions/__pycache__/utils.cpython-312.pyc,, +torch/distributions/__pycache__/von_mises.cpython-312.pyc,, +torch/distributions/__pycache__/weibull.cpython-312.pyc,, +torch/distributions/__pycache__/wishart.cpython-312.pyc,, +torch/distributions/bernoulli.py,sha256=yU1Sf9xML4FNaN1YnNYhjKPFXQyM-2bT0w6ni1C-bEc,4762 +torch/distributions/beta.py,sha256=X7bUYY6OSy-SxJNWCXRA3A1mWs0Hn3gfGuxkhC-PhXU,4000 +torch/distributions/binomial.py,sha256=cXO378OmHHclqL_YKnBfpjH9dzCO279RFk7iiXJJ6SQ,6481 +torch/distributions/categorical.py,sha256=eU-zgx7Yp3cyWp00lNMzfr9V5Y_cFKQXLXKM3BCwvbQ,6277 +torch/distributions/cauchy.py,sha256=ZubvZlaBqfin-Yg2Qlq_R4VA4jcyEg9gLLzMm3Lsox8,3159 +torch/distributions/chi2.py,sha256=BP_QvY2zY7xvDx-M_hMmmB_Ral0eUyYd-Ak8B9W7AqI,1109 +torch/distributions/constraint_registry.py,sha256=Z49QrxE5eJqi7_84YM73khNXMNVGhM1jqb-ovWBKT-A,10306 +torch/distributions/constraints.py,sha256=y4oAhn0-_KnlZzSH1vHKsoSj_545wOgPLitNrb1Mi5U,22770 +torch/distributions/continuous_bernoulli.py,sha256=m-gMA7LVbPhqFaZNpt91opQh-VwpBX2BbdE7a5g1Ffg,9298 +torch/distributions/dirichlet.py,sha256=swXYGrzZlnmYktGw0W6Q3Tx3AATbvU5La0HOzXFHO7k,4576 +torch/distributions/distribution.py,sha256=lMaKFg5-NxEC6-f2n6_BZFd4wxkVidIhja8KcLCHtVo,12685 +torch/distributions/exp_family.py,sha256=6RYlQCzOQE7Es4sDX8xPyCHhxxB26nJu3dqrIX2poR4,2441 +torch/distributions/exponential.py,sha256=Gggg_b0qOTBaYL1sFMrJ8PeQeNxGZI7NMTlEmKefAMQ,2725 +torch/distributions/fishersnedecor.py,sha256=Rv_OyjkelKUrjdtAuVk8eMRG_cy8qiKGjXNgEENarA0,3665 +torch/distributions/gamma.py,sha256=KsGu9hVBCfYvylxYdKY6BNGqw5EtRKX5qT0Dvao8GfU,4313 +torch/distributions/generalized_pareto.py,sha256=wUgZyItbYV9m3HKBNdPzH7QVf9_0cJgr528XWZLKNrY,5831 +torch/distributions/geometric.py,sha256=RBngoQtIAckbYTSn73Id7edOLTGhdANttBsrt7YkKTI,5221 +torch/distributions/gumbel.py,sha256=62tPcwq8-w9HzSsTcCh127OGDsaPWi7NHKBBXtas_ko,3002 +torch/distributions/half_cauchy.py,sha256=Rk0IdrzwWDdh2nBVZbbxQNN4rhdiXtXSOl9qCCv6q1w,2638 +torch/distributions/half_normal.py,sha256=e9xjQP1zD7oynxyJNLVa0zk1AGrtbgQgxAAWgbrKOuM,2403 +torch/distributions/independent.py,sha256=UWRk4sveW6xR64vbrNUINOiMnCWI2oSmrcSGomExnz4,5052 +torch/distributions/inverse_gamma.py,sha256=ZflL-04IC_ZomeYgXoBs7aRzJOr5M4MRc9LGb3htg1s,2772 +torch/distributions/kl.py,sha256=0c9rm_Fl6VqUIfm0rZE-qTpF_dxGX7ysTwg_zozTIR4,31769 +torch/distributions/kumaraswamy.py,sha256=V1eHHwjIJeJHJ5iNq3QDDfV3xoptOtRI-R8nTlgyjJk,3679 +torch/distributions/laplace.py,sha256=WqwZxvW8Ur5exRGF7iu2fj_CYIgO_Ct4Vra8UH5vP7w,3490 +torch/distributions/lkj_cholesky.py,sha256=ghOGpnV_zOYgqKMAIzJSL7OJEu_2n3jrXITUDPTj6M4,6550 +torch/distributions/log_normal.py,sha256=q2OmSbopn3A8xDlSjLBignD_QFDv7eTW5Ov0mQU9r28,2224 +torch/distributions/logistic_normal.py,sha256=m7cwrUWy-EYlXB1MhpAVEQlS2IZmp4m_k-yObEsU83Q,2240 +torch/distributions/lowrank_multivariate_normal.py,sha256=AQ1mGA5FEnJ1x1MTHxfz8Q8v6UV2iYFnwXK7njly2qE,10176 +torch/distributions/mixture_same_family.py,sha256=OJPW2eOh3FdkYYJzphbUDsxAzJft2hKqJE_qlpVWKjo,8738 +torch/distributions/multinomial.py,sha256=hK7Kpynlr5Uk3hP2cbsoDZSBmcTE2fnpY9JCTUjcxZ4,5723 +torch/distributions/multivariate_normal.py,sha256=9ULfxdFNYebnSJ89RyMm44FrpmCxAc74t8qqRSe6Jmg,11322 +torch/distributions/negative_binomial.py,sha256=KFFBDY-EXa8ylxEX2FQFV6yP-4MbjW4zMNtJG5_-6NU,5171 +torch/distributions/normal.py,sha256=iP5y20oT_yDAPcDAPiITu4lnYf2TNtkKEwPO4oWAEoI,3890 +torch/distributions/one_hot_categorical.py,sha256=-PcTluwbf9UKI6m2C7OlEI4jVEIS9_uV96yjUvU6lf4,5037 +torch/distributions/pareto.py,sha256=7XmKjKbqJEOJ60IB3VoJJnvD5bOlCkwUx0yhZyc1Fqk,2522 +torch/distributions/poisson.py,sha256=ZYOXnjAC_4mQZdd3u61NDpeEf6aAS7egRa6Sc8A1vU8,2477 +torch/distributions/relaxed_bernoulli.py,sha256=Hf6XfCvXqLP3qOLnSwXOItiahS754sEvj7hjwTCMsVE,6121 +torch/distributions/relaxed_categorical.py,sha256=XhE9kz80C5X4Rjny64uPqfSS7ubWTLJm-4G_uA8M8yA,5752 +torch/distributions/studentT.py,sha256=4GT8RrqckofZWFp80AMnzmZvBLKLslH1n0XdSJN1fMM,4131 +torch/distributions/transformed_distribution.py,sha256=X3TnplWYfr3-xJN1gdz91wFGZQpGvzsTjGFCEoTvSgc,9021 +torch/distributions/transforms.py,sha256=o6B88wGTRmcKbecIMrYNs4JPIy-QvDluFWZzLmqX0D0,45975 +torch/distributions/uniform.py,sha256=Fb75o9UR1cfSb8UP04ah6OXHppJnsLOahVkJDIem2Yw,3348 +torch/distributions/utils.py,sha256=c8m_XCLFL-feHdm3X_ZCYFFBcBmH5N3levtu28FOues,7978 +torch/distributions/von_mises.py,sha256=jgwiV2-J3BzHNmgscm6XODymFuPX4A4QfpHCh8mQucQ,6507 +torch/distributions/weibull.py,sha256=3IMQkEvqGZ1cq3Z4pqixK6_7QKnDO51UQOsTXlLNA9o,3417 +torch/distributions/wishart.py,sha256=nL0hW8GV366VrJ8BODS6WcQrRwngM3noZzWDYi_spTM,14006 +torch/export/__init__.py,sha256=eySTp-zt0GuBxllN8MtcWwYAREbYhsxlCMEBXndGV-k,22123 +torch/export/__pycache__/__init__.cpython-312.pyc,, +torch/export/__pycache__/_draft_export.cpython-312.pyc,, +torch/export/__pycache__/_leakage_detection_utils.cpython-312.pyc,, +torch/export/__pycache__/_patches.cpython-312.pyc,, +torch/export/__pycache__/_remove_auto_functionalized_pass.cpython-312.pyc,, +torch/export/__pycache__/_remove_effect_tokens_pass.cpython-312.pyc,, +torch/export/__pycache__/_safeguard.cpython-312.pyc,, +torch/export/__pycache__/_state_dict_utils.cpython-312.pyc,, +torch/export/__pycache__/_swap.cpython-312.pyc,, +torch/export/__pycache__/_trace.cpython-312.pyc,, +torch/export/__pycache__/_tree_utils.cpython-312.pyc,, +torch/export/__pycache__/_unlift.cpython-312.pyc,, +torch/export/__pycache__/_wrapper_utils.cpython-312.pyc,, +torch/export/__pycache__/custom_obj.cpython-312.pyc,, +torch/export/__pycache__/custom_ops.cpython-312.pyc,, +torch/export/__pycache__/decomp_utils.cpython-312.pyc,, +torch/export/__pycache__/dynamic_shapes.cpython-312.pyc,, +torch/export/__pycache__/exported_program.cpython-312.pyc,, +torch/export/__pycache__/graph_signature.cpython-312.pyc,, +torch/export/__pycache__/unflatten.cpython-312.pyc,, +torch/export/_draft_export.py,sha256=dmihMggzyCXlWHZHx3g-DrPCFmXjGOxvd1bjT5obWDg,20922 +torch/export/_leakage_detection_utils.py,sha256=cFO_EtruWPRAksV5lS_Je9_FSREizRK6opqkHtEjYfc,3564 +torch/export/_patches.py,sha256=9KmErdrLVNPTSjWHVatH_qFtd0zYKGIo6HeVppCCLI4,11466 +torch/export/_remove_auto_functionalized_pass.py,sha256=tqaXBjtGuXcsmaq3quv444K-79sIejf_cYecxqqp410,2111 +torch/export/_remove_effect_tokens_pass.py,sha256=qtodS8DssfsXbSt8F3SBoWLXmdtpWjAf8tKYiPWl1sY,9195 +torch/export/_safeguard.py,sha256=48fjMGTWwJ26j0B6q4jZG6mOcsIO1SXDbOrgflDESuk,2098 +torch/export/_state_dict_utils.py,sha256=iYYPNWxP2lR13pFWelSIJiNt2PSB3B5CTvvnfOBgkYw,7601 +torch/export/_swap.py,sha256=Q2H8fXw7YnrRYrN9F4KqFNvj21sIkw1g--2AGKTGe44,19071 +torch/export/_trace.py,sha256=KPRqFu397Nm388HL84jmyno8U-XQ2Irega7-nELSA90,110244 +torch/export/_tree_utils.py,sha256=PFHm-v6FAcxMb5neZeiPlKH_hjW1OW39Q8S_QwmbuHc,2563 +torch/export/_unlift.py,sha256=Nfqmr0ooWpGe2NMNpVBHCDKmwVtaoLjrJeMxxmIXtBs,34425 +torch/export/_wrapper_utils.py,sha256=pAHvH2i0I5mn42Cpl4oyTBQzJz0rZjBi2siRQr2khOo,271 +torch/export/custom_obj.py,sha256=H6j0qawn-qiMlmafZDdjAuOOQY7YvQ7pbhiFW71hOMY,296 +torch/export/custom_ops.py,sha256=cxfhGIErUTn1wM4_pnmWhYcowhqnaGLkj5Uk1kWyNbI,2061 +torch/export/decomp_utils.py,sha256=3WGV86fP5QSFIe31u9jyG63N-mhnsLxS5V2mtqRBK5c,5753 +torch/export/dynamic_shapes.py,sha256=StxdL5Xvd73CzWnKBW4xohhB-usp7H7LFxYH8sOzpTM,64127 +torch/export/experimental/__init__.py,sha256=AbLXV1wSb15To0xIGgmVY3dS0sI6SUrWbEEea0TNjT0,17876 +torch/export/experimental/__pycache__/__init__.cpython-312.pyc,, +torch/export/experimental/__pycache__/_utils.cpython-312.pyc,, +torch/export/experimental/_utils.py,sha256=A17QWFUiisPCAWnuD7VGS2b8CSkcvbxwUa0oRPt0lOo,8880 +torch/export/exported_program.py,sha256=u0kIdnom-E-9wNhKNBPUgYz3-I40rkUKKfU3-PoWX_8,72644 +torch/export/graph_signature.py,sha256=diRyFDKIu5xBZC1TDYUFan_trksner3KQFG_tcf7a6Q,27548 +torch/export/passes/__init__.py,sha256=6vyfrZbM2pi3XGyRYPu-J9p9tknELWJV4JfkJs1dqP8,3337 +torch/export/passes/__pycache__/__init__.cpython-312.pyc,, +torch/export/pt2_archive/__init__.py,sha256=vYIe2lq0nWwY77PVEsuIo_0fEWuAeX5E95FhGtXmwZ8,144 +torch/export/pt2_archive/__pycache__/__init__.cpython-312.pyc,, +torch/export/pt2_archive/__pycache__/_package.cpython-312.pyc,, +torch/export/pt2_archive/__pycache__/_package_weights.cpython-312.pyc,, +torch/export/pt2_archive/__pycache__/constants.cpython-312.pyc,, +torch/export/pt2_archive/_package.py,sha256=dJ5JbDt0A4G03J7J52Pcz0RZuRzXYjnWb9xAElFLU14,44943 +torch/export/pt2_archive/_package_weights.py,sha256=nKEppUxfhlCffZixU_QZtqzM6BV5p05n_SJtrWMqdXg,8131 +torch/export/pt2_archive/constants.py,sha256=flAh8WcGm3UeLcJKz2x6mKIRvnBg85qbOafOleZCHZk,1848 +torch/export/unflatten.py,sha256=VYXtjnB2LOtU2Y_9yFYKzsbdr-04kLqSrRt4-4PmiBw,76373 +torch/fft/__init__.py,sha256=jsWUCepZh1lTLHCKhh5dF5NXhDHOmxxaeLC5UDkhSGc,55336 +torch/fft/__pycache__/__init__.cpython-312.pyc,, +torch/func/__init__.py,sha256=QWAhPM0xIlGHLP_bLmSGdjcTcnz_aPsNrYbeShWa-ho,719 +torch/func/__pycache__/__init__.cpython-312.pyc,, +torch/func/__pycache__/_random.cpython-312.pyc,, +torch/func/_random.py,sha256=GHYTd_wnaMDxBOsEFfLlbhzUpp4Y9wPHCy1Wnk7HI6Q,11088 +torch/functional.py,sha256=qzv2tt2cSSgSnakRWq0KzDUU-kXgUmNKLyM_97EMN68,90127 +torch/futures/__init__.py,sha256=FRibgVxq5rx2VBAycXQhBrV7eNdjHQkbDdnF2zkYfiM,14480 +torch/futures/__pycache__/__init__.cpython-312.pyc,, +torch/fx/__init__.py,sha256=3UU6khKhgRPJ2WaEj01tLXG-suHc5yGwGFtXLCTfLCE,4134 +torch/fx/__pycache__/__init__.cpython-312.pyc,, +torch/fx/__pycache__/_compatibility.cpython-312.pyc,, +torch/fx/__pycache__/_graph_pickler.cpython-312.pyc,, +torch/fx/__pycache__/_lazy_graph_module.cpython-312.pyc,, +torch/fx/__pycache__/_pytree.cpython-312.pyc,, +torch/fx/__pycache__/_symbolic_trace.cpython-312.pyc,, +torch/fx/__pycache__/_utils.cpython-312.pyc,, +torch/fx/__pycache__/annotate.cpython-312.pyc,, +torch/fx/__pycache__/config.cpython-312.pyc,, +torch/fx/__pycache__/graph.cpython-312.pyc,, +torch/fx/__pycache__/graph_module.cpython-312.pyc,, +torch/fx/__pycache__/immutable_collections.cpython-312.pyc,, +torch/fx/__pycache__/interpreter.cpython-312.pyc,, +torch/fx/__pycache__/node.cpython-312.pyc,, +torch/fx/__pycache__/operator_schemas.cpython-312.pyc,, +torch/fx/__pycache__/proxy.cpython-312.pyc,, +torch/fx/__pycache__/subgraph_rewriter.cpython-312.pyc,, +torch/fx/__pycache__/tensor_type.cpython-312.pyc,, +torch/fx/__pycache__/traceback.cpython-312.pyc,, +torch/fx/_compatibility.py,sha256=R37yvvOmOJ5KVkKkJm4RsVzGbhAKyoMDFba2KRpcQ-o,1110 +torch/fx/_graph_pickler.py,sha256=G1gSF-mj-oMITHdb53yizP2TZqtRwYJFGgXquzLJ0U8,34989 +torch/fx/_lazy_graph_module.py,sha256=js-mGuL1hD3HR1f-I7KITu3wCtxTKHjXL65E-HqtSJU,7642 +torch/fx/_pytree.py,sha256=yJdeitYr930buUWLRIZuTCitjhaDRskJlzV05YDcx50,3762 +torch/fx/_symbolic_trace.py,sha256=gGJ3vDAxMyBtBmESRHKnXeo8nEb7J5vMBXCnEQAPbZE,55432 +torch/fx/_utils.py,sha256=LPAYB_vKsFXS5r3kd8xBpCRzFUawKdSRjI_1yqjqbbk,1916 +torch/fx/annotate.py,sha256=Uek_AOziex8JDoBdvg2UMZcmwBglDRx6Xg8cEAwhX9I,1296 +torch/fx/config.py,sha256=L7Vy7NuLuhWYjWj8BVjra-uHIKdVCgOuTwyh3n6_fdI,609 +torch/fx/experimental/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/fx/experimental/__pycache__/__init__.cpython-312.pyc,, +torch/fx/experimental/__pycache__/_backward_state.cpython-312.pyc,, +torch/fx/experimental/__pycache__/_config.cpython-312.pyc,, +torch/fx/experimental/__pycache__/_constant_symnode.cpython-312.pyc,, +torch/fx/experimental/__pycache__/_dynamism.cpython-312.pyc,, +torch/fx/experimental/__pycache__/_size_hinting.cpython-312.pyc,, +torch/fx/experimental/__pycache__/_spec_binding.cpython-312.pyc,, +torch/fx/experimental/__pycache__/accelerator_partitioner.cpython-312.pyc,, +torch/fx/experimental/__pycache__/const_fold.cpython-312.pyc,, +torch/fx/experimental/__pycache__/debug.cpython-312.pyc,, +torch/fx/experimental/__pycache__/dynamic_spec.cpython-312.pyc,, +torch/fx/experimental/__pycache__/graph_gradual_typechecker.cpython-312.pyc,, +torch/fx/experimental/__pycache__/merge_matmul.cpython-312.pyc,, +torch/fx/experimental/__pycache__/meta_tracer.cpython-312.pyc,, +torch/fx/experimental/__pycache__/normalize.cpython-312.pyc,, +torch/fx/experimental/__pycache__/optimization.cpython-312.pyc,, +torch/fx/experimental/__pycache__/partitioner_utils.cpython-312.pyc,, +torch/fx/experimental/__pycache__/proxy_tensor.cpython-312.pyc,, +torch/fx/experimental/__pycache__/recording.cpython-312.pyc,, +torch/fx/experimental/__pycache__/refinement_types.cpython-312.pyc,, +torch/fx/experimental/__pycache__/rewriter.cpython-312.pyc,, +torch/fx/experimental/__pycache__/schema_type_annotation.cpython-312.pyc,, +torch/fx/experimental/__pycache__/sym_node.cpython-312.pyc,, +torch/fx/experimental/__pycache__/symbolic_shapes.cpython-312.pyc,, +torch/fx/experimental/__pycache__/unify_refinements.cpython-312.pyc,, +torch/fx/experimental/__pycache__/validator.cpython-312.pyc,, +torch/fx/experimental/_backward_state.py,sha256=TzC9Uin0ccyk7oG5z7HQPhRP6I0_6-HC28DOXpzUZzE,967 +torch/fx/experimental/_config.py,sha256=_uBnJqdEz4tO1po5WaB-rZYmXpcQ-ZYMjckUv9324aA,6454 +torch/fx/experimental/_constant_symnode.py,sha256=FtDX1dKB3N6QzI4gu2Gi0J7zLhBDeF3RJvlhS5AaFBY,1759 +torch/fx/experimental/_dynamism.py,sha256=d5pjCC3X4rP5nglg2Cok2UXdAgCrbmY4TPgfeCHzE1Q,4617 +torch/fx/experimental/_size_hinting.py,sha256=uItBC0EfWsPQixj6z3pD1M4Jc69VPSbd3JHvuk6sLro,21339 +torch/fx/experimental/_spec_binding.py,sha256=z3oYQqMheBbYUnmY-g3UzdGKLsk6tmZRAP4vs1e0PY0,13857 +torch/fx/experimental/accelerator_partitioner.py,sha256=dxVSkIMDOWq1EWZ0FD0qwIEZPII5dKyMmsbU2soiVHc,48708 +torch/fx/experimental/const_fold.py,sha256=HcG1u9OwkQcMFvDT3bEtisx_YsMu6axbMONcw1MTBNU,19691 +torch/fx/experimental/debug.py,sha256=i3xyFB3WsaE3k09YInW_WUMTPi9mpNNbfTbB-7jFmvs,811 +torch/fx/experimental/dynamic_spec.py,sha256=qgdMP-fQS5LhWyb7ivuQocVW6kgYsFBx0421HjL9olU,29514 +torch/fx/experimental/graph_gradual_typechecker.py,sha256=hvXTv9udkdS9mZo7Jyvt_97ciqENBQEUTb31-hu3uhE,36429 +torch/fx/experimental/merge_matmul.py,sha256=eTvu4AQG-08ewiY4e65YcpeGimv7caahmS1dw_TBa-w,6114 +torch/fx/experimental/meta_tracer.py,sha256=bVGE7DpnmXMmKE7LosKNmvPYpKA6-V9-T_1E7d4-BYo,12812 +torch/fx/experimental/migrate_gradual_types/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/fx/experimental/migrate_gradual_types/__pycache__/__init__.cpython-312.pyc,, +torch/fx/experimental/migrate_gradual_types/__pycache__/constraint.cpython-312.pyc,, +torch/fx/experimental/migrate_gradual_types/__pycache__/constraint_generator.cpython-312.pyc,, +torch/fx/experimental/migrate_gradual_types/__pycache__/constraint_transformation.cpython-312.pyc,, +torch/fx/experimental/migrate_gradual_types/__pycache__/operation.cpython-312.pyc,, +torch/fx/experimental/migrate_gradual_types/__pycache__/transform_to_z3.cpython-312.pyc,, +torch/fx/experimental/migrate_gradual_types/__pycache__/util.cpython-312.pyc,, +torch/fx/experimental/migrate_gradual_types/__pycache__/z3_types.cpython-312.pyc,, +torch/fx/experimental/migrate_gradual_types/constraint.py,sha256=FSyqmIPp2grAUcn05XkZwh_Bijf6bRKx6x0jSnPEiMQ,20836 +torch/fx/experimental/migrate_gradual_types/constraint_generator.py,sha256=U8s-TDrwXMDvmE4gEpRWX2zzXfZiwLCK_WZG52BLpcg,62336 +torch/fx/experimental/migrate_gradual_types/constraint_transformation.py,sha256=nndlD3Ba-5TtEVxKuW7VW29POWqmzg2AdpRpH7PgCZ4,46033 +torch/fx/experimental/migrate_gradual_types/operation.py,sha256=v7haImk8KCWq9XBmzu2MWoApiGGQsQY4xF-VChtRBVI,287 +torch/fx/experimental/migrate_gradual_types/transform_to_z3.py,sha256=PyLS_5n6UP2-5kLcsibcXdh9lZ3kEqiCYgiua1Eewdk,20085 +torch/fx/experimental/migrate_gradual_types/util.py,sha256=7FpQPVuVeocjt7ZC8UYSiCES-Qe-D2HQzYWSTvaR5lY,1485 +torch/fx/experimental/migrate_gradual_types/z3_types.py,sha256=9CzjT7bWhU2CUNwZrQcdI7PDY8haxTrzGBRw_V7X7dk,807 +torch/fx/experimental/normalize.py,sha256=1rKB2iKOVimOf3z1OVX3ejCJaQIV73sChhaZm0PpQ_g,5805 +torch/fx/experimental/optimization.py,sha256=WH0NC3pNYlAVeED-v9FdUQmmWznfyiNzIh8mOyNFPVM,19162 +torch/fx/experimental/partitioner_utils.py,sha256=hvyzdB-wuT1GAz-to9JhgHkbmz-eflRjzazuz3FD0o4,12348 +torch/fx/experimental/proxy_tensor.py,sha256=rHjnBCnqyCdkGrj5XZvvDKA8_odWKEiaEWkToC_XoY0,142848 +torch/fx/experimental/recording.py,sha256=XtN2cRYe5FcjlaK3Eu9CfNT9Q0Eh80lOkgTi67F8O9Q,21254 +torch/fx/experimental/refinement_types.py,sha256=vK9YKzgINmeHIsyPhNrFuVK7aBzWs3C5qIS8kuEHI7U,459 +torch/fx/experimental/rewriter.py,sha256=FrE3NfIPubdG_gF806udBCTRHg16cGfEcQ7QX8XgCfY,5934 +torch/fx/experimental/schema_type_annotation.py,sha256=_Gow8lG9U40bj-UR8Qg5DQTQAFLEldTsskjqi-4QuAg,5790 +torch/fx/experimental/sym_node.py,sha256=9sEi9cn_VR5DDtXynB9oC_OJYMvyxVnBSJfwP5zP5M4,72228 +torch/fx/experimental/symbolic_shapes.py,sha256=GWZ-7HHBujRaWIJz3hAkMpqxed4G86M9bnAdHfk1-2M,404120 +torch/fx/experimental/unification/__init__.py,sha256=E3UmEdbvYRy5_hyMCNrRrOHcG-p0YS9KFBZ7d37hDrI,154 +torch/fx/experimental/unification/__pycache__/__init__.cpython-312.pyc,, +torch/fx/experimental/unification/__pycache__/core.cpython-312.pyc,, +torch/fx/experimental/unification/__pycache__/dispatch.cpython-312.pyc,, +torch/fx/experimental/unification/__pycache__/match.cpython-312.pyc,, +torch/fx/experimental/unification/__pycache__/more.cpython-312.pyc,, +torch/fx/experimental/unification/__pycache__/unification_tools.cpython-312.pyc,, +torch/fx/experimental/unification/__pycache__/utils.cpython-312.pyc,, +torch/fx/experimental/unification/__pycache__/variable.cpython-312.pyc,, +torch/fx/experimental/unification/core.py,sha256=z2KY8NfOZxaStqSHJaG04ecGIdYEsspXDY8xTzF07co,3686 +torch/fx/experimental/unification/dispatch.py,sha256=9oSoC5tHuRoDMwgjgI7NvGVo-aW9qRrgz6SBNEnx6Lc,207 +torch/fx/experimental/unification/match.py,sha256=B5OnuXyFyFuJ_LwgSwV3HUoAYbkeBpBZaaauPiTu0Gs,4462 +torch/fx/experimental/unification/more.py,sha256=JWLb_mnlClVUWXv-se776PUq0I_cJor9FLW4es-cR6U,4172 +torch/fx/experimental/unification/multipledispatch/__init__.py,sha256=xjEjlwV6TTwkgteOREoXUJwMTiNnpJN3YfBALC9eslU,139 +torch/fx/experimental/unification/multipledispatch/__pycache__/__init__.cpython-312.pyc,, +torch/fx/experimental/unification/multipledispatch/__pycache__/conflict.cpython-312.pyc,, +torch/fx/experimental/unification/multipledispatch/__pycache__/core.cpython-312.pyc,, +torch/fx/experimental/unification/multipledispatch/__pycache__/dispatcher.cpython-312.pyc,, +torch/fx/experimental/unification/multipledispatch/__pycache__/utils.cpython-312.pyc,, +torch/fx/experimental/unification/multipledispatch/__pycache__/variadic.cpython-312.pyc,, +torch/fx/experimental/unification/multipledispatch/conflict.py,sha256=zPXAqOV1SYF8t9svqO41N9nuvIx32Ae7D50YEYVrXBc,5205 +torch/fx/experimental/unification/multipledispatch/core.py,sha256=3Zl8fUSf7ys8Fp9VgiKbGj6TmGY1dJDiNCaxq5ddXL4,3013 +torch/fx/experimental/unification/multipledispatch/dispatcher.py,sha256=ebhutzFRme5fMgyNpnpVqpP_ctjVbVwCz34ga0gbe_I,15555 +torch/fx/experimental/unification/multipledispatch/utils.py,sha256=QY0NX_ZA5uBA86yszJX7fXKswmsXMbPJeAOeiFppzlU,4528 +torch/fx/experimental/unification/multipledispatch/variadic.py,sha256=RVPfAy-zJxtftqH8Z_fdpWbUiARtZfFZZeBFMpohDho,3086 +torch/fx/experimental/unification/unification_tools.py,sha256=RqosNUIgpkciBdcJrnnis20uTp6WTk2Y1DjJpJKSlQw,12106 +torch/fx/experimental/unification/utils.py,sha256=oJRn633EKuQMviUFLZBpHheOcVRk85AoA8r1VmmF65s,3586 +torch/fx/experimental/unification/variable.py,sha256=noQrj7YfIP7oRJcYZqZv8H68PV8A9MqfCKStSXaBLFQ,2601 +torch/fx/experimental/unify_refinements.py,sha256=kcve9F5mJUB4FJDFSDNn6mgkTcT9m9Uvg7BQhXMmd24,3690 +torch/fx/experimental/validator.py,sha256=EJ2vJbzt3KU5B-r6xkDbFUXLsP3LL0K0B8r8zP-dXIE,36737 +torch/fx/graph.py,sha256=0n8qx0aW2WytBpP6piNL6h8XLGDOcybDJmZYw0ZiF0U,119266 +torch/fx/graph_module.py,sha256=gHOMvyDHQiAZUp3ocxqPbEHmjuPlmkkRB0qe1WDQG0U,50466 +torch/fx/immutable_collections.py,sha256=9OeeV5ZPLcswvuNEo7xEepwdUJsW0JYdIwaNNYCOKG4,3269 +torch/fx/interpreter.py,sha256=KJWVqlLkFFpRkZtJAiyegE1WJlVZ6LTuW2siNecQ_iU,26485 +torch/fx/node.py,sha256=7jTNzIc-kOeVX6c2oRB7eUhrgvrk7oXPDr5krOpYi24,36769 +torch/fx/operator_schemas.py,sha256=tVYsixIfddTYlHFmnQb7R9m0FqKKRvzeWTC8dXTHqeE,24060 +torch/fx/passes/__init__.py,sha256=qXzO3_W60MDLQ1l4Rymt3ZwAxtbmkQ7Plsx9kQjWIm8,263 +torch/fx/passes/__pycache__/__init__.cpython-312.pyc,, +torch/fx/passes/__pycache__/_tensorify_python_scalars.cpython-312.pyc,, +torch/fx/passes/__pycache__/annotate_getitem_nodes.cpython-312.pyc,, +torch/fx/passes/__pycache__/canonicalize.cpython-312.pyc,, +torch/fx/passes/__pycache__/fake_tensor_prop.cpython-312.pyc,, +torch/fx/passes/__pycache__/graph_drawer.cpython-312.pyc,, +torch/fx/passes/__pycache__/graph_manipulation.cpython-312.pyc,, +torch/fx/passes/__pycache__/graph_transform_observer.cpython-312.pyc,, +torch/fx/passes/__pycache__/net_min_base.cpython-312.pyc,, +torch/fx/passes/__pycache__/operator_support.cpython-312.pyc,, +torch/fx/passes/__pycache__/param_fetch.cpython-312.pyc,, +torch/fx/passes/__pycache__/pass_manager.cpython-312.pyc,, +torch/fx/passes/__pycache__/regional_inductor.cpython-312.pyc,, +torch/fx/passes/__pycache__/regional_inductor_invoke_subgraph.cpython-312.pyc,, +torch/fx/passes/__pycache__/reinplace.cpython-312.pyc,, +torch/fx/passes/__pycache__/runtime_assert.cpython-312.pyc,, +torch/fx/passes/__pycache__/shape_prop.cpython-312.pyc,, +torch/fx/passes/__pycache__/split_module.cpython-312.pyc,, +torch/fx/passes/__pycache__/split_utils.cpython-312.pyc,, +torch/fx/passes/__pycache__/splitter_base.cpython-312.pyc,, +torch/fx/passes/__pycache__/tools_common.cpython-312.pyc,, +torch/fx/passes/_tensorify_python_scalars.py,sha256=GOXsKCAVvGmOBjHyXArhHlJ8uJVWCABPg5uP4_8TK8k,19763 +torch/fx/passes/annotate_getitem_nodes.py,sha256=F6pofuCRCivrQou6o0LjIlaJUo2qjj5dJiyne5Xf2xY,3609 +torch/fx/passes/backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/fx/passes/backends/__pycache__/__init__.cpython-312.pyc,, +torch/fx/passes/backends/__pycache__/cudagraphs.cpython-312.pyc,, +torch/fx/passes/backends/cudagraphs.py,sha256=Aexhowv_73KX-WaifHSynALKyCZpS_0eiz0sSIYimPw,2342 +torch/fx/passes/canonicalize.py,sha256=8m5tagVqvZMq2T3DqfJlCopfXbaXX7PGC62on47pWms,13707 +torch/fx/passes/dialect/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/fx/passes/dialect/__pycache__/__init__.cpython-312.pyc,, +torch/fx/passes/dialect/common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/fx/passes/dialect/common/__pycache__/__init__.cpython-312.pyc,, +torch/fx/passes/dialect/common/__pycache__/cse_pass.cpython-312.pyc,, +torch/fx/passes/dialect/common/cse_pass.py,sha256=GgZsy26q2Kn-ykB8lPywpL8Eu9Knw2cSN2O5ohRjQR8,5416 +torch/fx/passes/fake_tensor_prop.py,sha256=rIdCycWO9bckjHZKacUTuxo10KixcybNKlZ3-tsJ7Bo,5052 +torch/fx/passes/graph_drawer.py,sha256=--12wEdPhgcxLkMCpB1QjE_TAIk4IEz_WYX66mHpHhs,19658 +torch/fx/passes/graph_manipulation.py,sha256=htvJBhXOzYhrzccZi4TwN7zrAZBiq_GIHJ7zayS-Lu0,4117 +torch/fx/passes/graph_transform_observer.py,sha256=Qxbe2thYuprVI9vEJCnz08KMJrint2qGNgJn6Jo236Q,8870 +torch/fx/passes/infra/__init__.py,sha256=UuBORluunUu4B8DKb0OlqkNIm71XUW_ZD_utIvqnBLs,27 +torch/fx/passes/infra/__pycache__/__init__.cpython-312.pyc,, +torch/fx/passes/infra/__pycache__/partitioner.cpython-312.pyc,, +torch/fx/passes/infra/__pycache__/pass_base.cpython-312.pyc,, +torch/fx/passes/infra/__pycache__/pass_manager.cpython-312.pyc,, +torch/fx/passes/infra/partitioner.py,sha256=bBVk7dz5MmSR8TH63rg6-oGs4OMY8M1INOxXi-rNCVg,19608 +torch/fx/passes/infra/pass_base.py,sha256=4lDJwJWcI1jmvV9C4V8-U5FKIWBZkJpBuQJVIChSeqE,2552 +torch/fx/passes/infra/pass_manager.py,sha256=InxC2MHP0vIDtIvYJac4Pt8Fu57qyUqf5KpvX_DAyUE,11115 +torch/fx/passes/net_min_base.py,sha256=Sv2y9Z6s5OZYcZmHhrK6OtdJrb0giXSgB4ZnPTas4TY,37052 +torch/fx/passes/operator_support.py,sha256=KJE2nIpV7zVOSSIQSz45SH76YA5gGXPmkPEPxvZ_G0A,7799 +torch/fx/passes/param_fetch.py,sha256=6gOQFJ-MRJF6g5sp8Typ9j6pBR9ibsVlJ50xjM2af4g,3741 +torch/fx/passes/pass_manager.py,sha256=cpKpAcX8S3vuFC5404jsvjthAHxquJEgxoGN5bho3Jc,8001 +torch/fx/passes/regional_inductor.py,sha256=d2mjEy2JnuNvmKAVfzsdrL2pp8LlzI5B64MHt_5IlTM,11643 +torch/fx/passes/regional_inductor_invoke_subgraph.py,sha256=1t1w6Bu9AkFhAnrvM0ZKzBcYFybQLD4lNwiskLfCJpM,6618 +torch/fx/passes/reinplace.py,sha256=rQvqY1AuepJxEm_Bx8TI2ztdD_k1_hkkxjC4PZn4pZg,35952 +torch/fx/passes/runtime_assert.py,sha256=VlTeL2cQW0IklOOqbw9AANRnDeEIRS_l8dTYlhtJNYg,33734 +torch/fx/passes/shape_prop.py,sha256=nvpxqhlATP3WngKmk0VkaaSLxCzdnuEJWsPLropYGM8,8340 +torch/fx/passes/split_module.py,sha256=hLGtJPEzYrgr40W0R4dBzjDHc2L2Gmu9Y8COD9CPDnA,42805 +torch/fx/passes/split_utils.py,sha256=joWxqLNp9NDHBvG3PPsv1bAcNPbZqQ3xee22w5C0DJQ,20908 +torch/fx/passes/splitter_base.py,sha256=fmB9A-5ewvpylYH403lkYg6B2RqtKwxbfIkoB-po7i8,45580 +torch/fx/passes/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/fx/passes/tests/__pycache__/__init__.cpython-312.pyc,, +torch/fx/passes/tests/__pycache__/_test_split_utils.cpython-312.pyc,, +torch/fx/passes/tests/__pycache__/test_pass_manager.cpython-312.pyc,, +torch/fx/passes/tests/_test_split_utils.py,sha256=_dC1J057wdB5fX7QckIyZoPIu5L6rxYZwgsZHTdZqAY,22607 +torch/fx/passes/tests/test_pass_manager.py,sha256=_KIwhlzOTY0XQb2WeaYYOFuBUKDtLFRqYeSxHVrS76E,1873 +torch/fx/passes/tools_common.py,sha256=iOyHcVpHKCSVsPKF7d61XeGSh_LZV7OvXVUvje60Vac,14198 +torch/fx/passes/utils/__init__.py,sha256=6xOYtGu1w_nVvuaxvBoQkSRtxkiIkPh-MzuXjmNC1hI,74 +torch/fx/passes/utils/__pycache__/__init__.cpython-312.pyc,, +torch/fx/passes/utils/__pycache__/common.cpython-312.pyc,, +torch/fx/passes/utils/__pycache__/fuser_utils.cpython-312.pyc,, +torch/fx/passes/utils/__pycache__/matcher_utils.cpython-312.pyc,, +torch/fx/passes/utils/__pycache__/matcher_with_name_node_map_utils.cpython-312.pyc,, +torch/fx/passes/utils/__pycache__/source_matcher_utils.cpython-312.pyc,, +torch/fx/passes/utils/common.py,sha256=qMLwOVZ0HAAYWRTjUJhycREbMNkj_O_FlIDKuD6CJ78,3226 +torch/fx/passes/utils/fuser_utils.py,sha256=f8CpzuxrWCueHeXyfMTwjjy8Ro1qCys5hO2fS0RFEyA,12180 +torch/fx/passes/utils/matcher_utils.py,sha256=Kz9B2WBbSRPd5QjgjhM1D5Zu2Z0aVw4FxN4teRmEoPc,18143 +torch/fx/passes/utils/matcher_with_name_node_map_utils.py,sha256=WRUl0nLxo5wWTZEEJ2wEBtjz6aybd7Vl6RUnH50WdBE,4353 +torch/fx/passes/utils/source_matcher_utils.py,sha256=n5eSgGE1OVE9kJhw7ID73yiFBhX6CSgGkSWwl5X1mqo,7318 +torch/fx/proxy.py,sha256=pL4liFQaBj84wTVWMa81YL-zKw7ioIpG7mt3szhdlu4,36775 +torch/fx/subgraph_rewriter.py,sha256=XM5S0K18wMbB7Dhr5jQS7kCNkHxJ0VMFLXyTNuJFs60,16803 +torch/fx/tensor_type.py,sha256=TceTm-HnHrjGsvRgfRWg4vs6oaZXxG0yOQY8A4ZpM8M,3442 +torch/fx/traceback.py,sha256=ykrnHLchcBL0XlBkY3lllXd9qbhSQrbbrxe_rSuJfTQ,23136 +torch/hub.py,sha256=Xn71VuJ2vG2tG5xLvICnBmlShrQ1DsaPOkV3zQlYd_8,33632 +torch/include/ATen/ATen.h,sha256=k-FMNPgadtRY0WaiI0kzfX8VVcgcFSuCbwvAJ2i7ClM,1331 +torch/include/ATen/AccumulateType.h,sha256=kzgekl85-Pf2id9qB_Uo2y5QyXxMGNcamXG-yvueh0Y,6365 +torch/include/ATen/ArrayRef.h,sha256=ofa5-yWJikSN5a0VsjvX-G2qByUSKsCE7z2Hdd1zZjE,298 +torch/include/ATen/Backend.h,sha256=rAIfvXr2KgiCtq5uAiBapYC1r3SLtupFjrmbpeXPhC4,297 +torch/include/ATen/Backtrace.h,sha256=yKbvQ16ihAHBkGQGKh-6pjm6jK-6cp6tjKAhs-3pQHI,300 +torch/include/ATen/BlasBackend.h,sha256=dM74cin5ObOdOP67BUREoUocYhMV043FeI0vom10vu4,1371 +torch/include/ATen/CPUApplyUtils.h,sha256=I1K3m6ZaNkemfzoPOTKfpXRSzeEICHWT5LWpjOBVHBM,10883 +torch/include/ATen/CPUFunctions.h,sha256=UbQ7FfyyuDj2oE7kHAhxaGD9LFUdleSeWwUHpH795fo,2208 +torch/include/ATen/CPUFunctions_inl.h,sha256=DOycja4ZgD_DSv_ylqcwKJKdUGvm1ut-4lf_5No86yM,28084 +torch/include/ATen/CPUGeneratorImpl.h,sha256=qogO5E0lj9VQz6QVdoaNKSoFFrGagDBJbXVpEnO80Rg,1781 +torch/include/ATen/CUDAFunctions.h,sha256=nwdEjF4wGGMImssj3hmzSOQ_kz4ZKSeT4WQ8UdiBj98,2209 +torch/include/ATen/CUDAFunctions_inl.h,sha256=upS7NEfaqdIQzJqk81Hi6hFsqxDJQe1QWhEZgXbwV68,33928 +torch/include/ATen/CachedTensorUtils.h,sha256=Rfo1BCyQrhFdY2tO7o2beQD8LxU-7pyZWrdjtTGIacw,1261 +torch/include/ATen/CollapseDims.h,sha256=dWXH85U4p4jsam0cS6pw0m9xunZ34HDLbF-0NR9eCQk,2814 +torch/include/ATen/CompositeExplicitAutogradFunctions.h,sha256=n7GTKOgLj3NDa9ELmt5PBi2AsqMZP26HUPD-YpGEqHQ,2230 +torch/include/ATen/CompositeExplicitAutogradFunctions_inl.h,sha256=22V0oWmSOgpX3cNN4zB8DvGjxC4dc5nASlCRJqxqXX0,41601 +torch/include/ATen/CompositeExplicitAutogradNonFunctionalFunctions.h,sha256=5fa_cZ7Y3np6u7c94LzhMe5g1F_aPAcJVDvNxL1NZcY,2243 +torch/include/ATen/CompositeExplicitAutogradNonFunctionalFunctions_inl.h,sha256=EX8Hy_a7XYo7IkRO1XpwkEtmVURDhOhU8EBT4OEzHBA,27034 +torch/include/ATen/CompositeImplicitAutogradFunctions.h,sha256=wNw8oZ66wh3uuYpxU9X-e3Xd9umlWxbhOWKqja8oE2U,2230 +torch/include/ATen/CompositeImplicitAutogradFunctions_inl.h,sha256=nvQ61RLBFiOdbmoRpCnxaTDIgAaf-UB0u5U8zUeuMwQ,33262 +torch/include/ATen/CompositeImplicitAutogradNestedTensorFunctions.h,sha256=LtEbQKDO2Ez1IEVsjvy4GT2ZzDPOaWhFmIeHimLtIPs,2242 +torch/include/ATen/CompositeImplicitAutogradNestedTensorFunctions_inl.h,sha256=ViwELt6UAz5OKrc24yLg7-VTwdrqRge4iq7K6JseUfU,1380 +torch/include/ATen/Config.h,sha256=eBANP6HIgeS7Rf9hDDIzXqVfpT2CGHS4wG4qB0vJjm8,1055 +torch/include/ATen/Context.h,sha256=YywZCS6pLnnWN-xNWoNqphBblD0Nzy6vI6l2kCEDVWY,26515 +torch/include/ATen/DLConvertor.h,sha256=2ISAPREnuTYErNVTHaq9m9URGtrnhF-WE2NNW4HrTyk,3501 +torch/include/ATen/DTensorState.h,sha256=5Tf_4vlPJcvhauK-lyQU9FI9nicxD_7DLDbA1nukmsE,1270 +torch/include/ATen/Device.h,sha256=vefXE-ivuf98uv1Px06EGn9MycHCV350yNT9g3JCxXY,296 +torch/include/ATen/DeviceAccelerator.h,sha256=3_BYDxYXhzeTAWeUWGxfWuXqq1hmDSecfJn1WITlzHc,5106 +torch/include/ATen/DeviceGuard.h,sha256=JMlpTXKWyXFaIIj_ZehQgfM5bP2EKdg4VnPbHAxy0JI,1419 +torch/include/ATen/DimVector.h,sha256=6Xv8E-rdaF4g-zRjm8aVO2AF41P61MpNjUbH-7OhL00,300 +torch/include/ATen/Dispatch.h,sha256=gCABvs9ljoUIwm5JD5CAZT3H87oemenQ0Fl11QikAB0,39633 +torch/include/ATen/Dispatch_v2.h,sha256=spV91MM7IE6FwA1gQ8KsHRBs13SK8opA1Zj28BvaBk4,58876 +torch/include/ATen/DynamicLibrary.h,sha256=578X2i8u8535Av4VGp0XYwSPY-_rbvt7B0q0QaxTYeY,933 +torch/include/ATen/EmptyTensor.h,sha256=ZL1Pz5KThapI0aPLX5VW37HLtGP5ifznxv3seu736Wc,4946 +torch/include/ATen/ExpandBase.h,sha256=51GgMs8O36068o3xhE-2NjvOTV0KwVzyDbWOglc8GCI,1168 +torch/include/ATen/ExpandUtils.h,sha256=w5Jxfx7T1i1tOYFmx15IhkxmMV3aO-bjpBK2ljKSumg,17232 +torch/include/ATen/FakeTensorDispatchTables.h,sha256=B-QaBzlvxT5C29BF6pXdzYin5y0N8O5XL97b-5W05-c,1910 +torch/include/ATen/Formatting.h,sha256=a7uH36sKyuNzq8kFdXO-214shUmRw8KmcnMt8VOTMJw,288 +torch/include/ATen/FuncTorchTLS.h,sha256=Fl4PmCDf7Sf6JM2ApHD5jbSEZBuG_ZCG_Buk_y2h8F0,2070 +torch/include/ATen/FunctionalStorageImpl.h,sha256=bVUPEJD1i5sIHC_rSqQ0WqQn_aTbu-vXWmqJZPcGGkk,10671 +torch/include/ATen/FunctionalTensorWrapper.h,sha256=x06qVIN6Tq3G7zxLasi4qgKIPxTfClpSSDMlXI55eAk,18907 +torch/include/ATen/FunctionalizeFallbackKernel.h,sha256=iBLShmf7CfYxqBS0VM6uG-cGI5rC5EGIxLDDpNVsYY0,2068 +torch/include/ATen/Functions.h,sha256=1ejnGWK11-6NUH1SX4Cwt7xlmmVtxsn3wp2Ci_oFC-c,56127 +torch/include/ATen/Generator.h,sha256=HOTLCyhKpa4uAF4taTguJPTKvRhBXooFbVKKEomg6OM,300 +torch/include/ATen/InferSize.h,sha256=RTa90ICq20CJZ-pUshTdcGLtgWMeYEi1-HRnc7WQugo,4182 +torch/include/ATen/InitialTensorOptions.h,sha256=AjYaGyhq4NcQ3eyNnj6ctamEghynIVm1guG3VFczdOQ,693 +torch/include/ATen/Layout.h,sha256=tRw-433FrW3h68PD2DQO95UHaUt8yLMdMHiydQrCv20,296 +torch/include/ATen/LegacyBatchedFallback.h,sha256=wegTT0gYFlyoX8I7IuXa7H7o8nGHxZTjI7UadTUSd64,1228 +torch/include/ATen/LegacyBatchedTensorImpl.h,sha256=fS03y5jlojJCq3738MG4YhK2ocIfH6yTdv2Q92rxax8,5817 +torch/include/ATen/LegacyVmapMode.h,sha256=lnhuI05JjTfS7uL4feKP-iLZ5C0eLja6i3WysAYOO6U,1181 +torch/include/ATen/LegacyVmapTransforms.h,sha256=b2ZRmNr3IfHKM-mTVpjYF5ti5yyUKrLZNUh5dg-7G1E,8068 +torch/include/ATen/LinalgBackend.h,sha256=eBFKPJs-zcaW1GEVbojXthxShQ404cfTV6f5VqjEWmA,973 +torch/include/ATen/MapAllocator.h,sha256=0dB-x0W0HKVhxBcTy_O6qEkIfl-YWuF4M67yKH7rLlg,3942 +torch/include/ATen/MatrixRef.h,sha256=CSsbtMITAlDwQQ7nG9REtvsZsb1Ft4xcd3s08NXiQos,3260 +torch/include/ATen/MemoryOverlap.h,sha256=E06jBGvemBeQzG5f83ZyGbyUKUiwypNqLkhkBB3M_eQ,1541 +torch/include/ATen/MetaFunctions.h,sha256=F4QJuE1qvgTMD_pxybgCc3UQH3c7GqdjNB3BdRFvMsE,2209 +torch/include/ATen/MetaFunctions_inl.h,sha256=6JEU7_ao_3Yasr_2qRmOu6AHzLARrjG8w2S3ZiWOAvk,16680 +torch/include/ATen/MethodOperators.h,sha256=LFSf9rpApnuIp2h1YFqQHzdmkyW9B2f70i8CJw7mCPg,15730 +torch/include/ATen/NativeFunctions.h,sha256=iA0f7wXrRMZ7hMe5t9YWu6tGV-mnvq-OTZcK1rRYvPo,62027 +torch/include/ATen/NativeMetaFunctions.h,sha256=2N_X1Bbge9oU2eRJsxwmN2XJk5FrwDQ0ATgdHJNZZfs,58496 +torch/include/ATen/NestedTensorImpl.h,sha256=Ut705YrlQpqGLCseQFvHVIF2zK2p1-0x504sT4NM4YU,10514 +torch/include/ATen/NodeCreationHooks.h,sha256=iWNnq2TWn6wuAL10bz3mOvB81WNGkkgRFJsmeCh2_Ok,1324 +torch/include/ATen/NumericUtils.h,sha256=_2G00rQK9KPtnW8DdqC2ckpyMhxFArc35H5ffhHBSqk,3050 +torch/include/ATen/OpMathType.h,sha256=hH-hHSohXPfov1Ce9r7uXyGur1Jlbn6RtwmYB4pdw3g,2030 +torch/include/ATen/OpaqueTensorImpl.h,sha256=-DEfs1JdJ9WEs6rpfXGJLs6atOM24dUKf7JOGWl7gbU,7069 +torch/include/ATen/Operators.h,sha256=2rGHY5KnAeb5ZSXoGD9uOMGrmqKIAANVDc_GqOn0aZQ,60058 +torch/include/ATen/PTThreadPool.h,sha256=B2QRG9BWowrxxpNvjj39vsVk3pFP54MkJJ4BAJR3mvQ,645 +torch/include/ATen/PadNd.h,sha256=UkJhEHwFKN-TZcN2i6XJEDprHoSSqUJo46diM8SttB4,380 +torch/include/ATen/Parallel-inl.h,sha256=vFqIxc3KSSdtx6Z_dkECPkgMy0AbMMhTvAd75nFvnZE,2547 +torch/include/ATen/Parallel.h,sha256=7tfhOczECJB8NB9Lc2kL5p1KVbQQKyMGksueVtBxvOk,5039 +torch/include/ATen/ParallelFuture.h,sha256=4vx_WX3OIIbFlQ4jkn44Kf3waTXNnEyd48iquBO5qVw,553 +torch/include/ATen/ParallelNative.h,sha256=p3C7kunTT9v2KvAOt6aWd1lh9p9VFPmHDBiPGxlhQvg,546 +torch/include/ATen/ParallelOpenMP.h,sha256=W6LXF3k0MoE21pu3Q7MlyI3D03-2dxHyU4c0HslE5ns,1537 +torch/include/ATen/PythonTorchFunctionTLS.h,sha256=BEvqGdM5RTFAvjUvY_fabV_SQVazUtVFWE959B-2hXk,1750 +torch/include/ATen/ROCmFABackend.h,sha256=1mY6byW5IpdUXVGZugzREWnh6QqX75B6OZfIeFReEDU,977 +torch/include/ATen/RedispatchFunctions.h,sha256=Yvgla_AAQlUkh7Hdc3xB3kq4O4vpPtDOhzPNF8z_YjQ,2198747 +torch/include/ATen/RegistrationDeclarations.h,sha256=rCqpeEUNrwwzlWNnT4UW0fWminZrdoSmJF0l1_3hP2M,905091 +torch/include/ATen/SDPBackend.h,sha256=cmXomX1RjUAY9uCh2-bSn9FzRpMjFMvUF6bWJBIUczE,507 +torch/include/ATen/SavedTensorHooks.h,sha256=c3B9NplJ5PeOU3u3por0HtEbClY_tijozi0EwK1eyx8,2740 +torch/include/ATen/Scalar.h,sha256=LSNWNrn_jf_qZSVOFXeONdYs5wdSE0uRzKfNX78c_V8,298 +torch/include/ATen/ScalarOps.h,sha256=71v1_d2-kJqm1LD1IzlsFgAY4mufIgiryxmBo3-qaBQ,1849 +torch/include/ATen/ScalarType.h,sha256=SfIfa3E8pBOkFD19qgu43TLOGKptlPIOZrTa4NmD5Pc,383 +torch/include/ATen/SequenceNumber.h,sha256=3lZRqokrZ29LTAwEAFVUso6WrxBO_ZE3rTvvN2DKqy8,587 +torch/include/ATen/SmallVector.h,sha256=gNWDIANGgC7StyDTrqVTMbA2jQSV1AWiwVx397q8n8o,301 +torch/include/ATen/SparseCsrTensorImpl.h,sha256=fO8aGBnLeU9GSEaMIvSoiUSb-x6MB2tlWwHHbKdQPn0,7421 +torch/include/ATen/SparseCsrTensorUtils.h,sha256=FbiiE9BugZ4yL7vb2ufm7muxxea1oOZn2MtlqnpmDVI,18078 +torch/include/ATen/SparseTensorImpl.h,sha256=kKIJqAu_IaFN2XQojdX4rS-9dDgrLcabsiAh9gjpLZw,15673 +torch/include/ATen/Storage.h,sha256=X1c-p8qXYDFlMsVH5Kw_dgncGyQrrKuzyA0PaY9lY-o,297 +torch/include/ATen/StorageUtils.h,sha256=_VKiR9j8cAdZAHUyT5FA0C9E7HfTDzQxOCv41tMRDNk,1562 +torch/include/ATen/Tensor.h,sha256=C6FD9cacNwOuxJD4_JqjHg34qxaDUZMXWq2GZvm2Yqg,298 +torch/include/ATen/TensorAccessor.h,sha256=zASg1wYR2DpIcYfZnGqgEd9QG8RNWhzJT0mcE7D-WWA,305 +torch/include/ATen/TensorGeometry.h,sha256=w0Jc8QcWKLFyjGWEJX-rDDpxhL9hqPEkFKTDjDHo878,4840 +torch/include/ATen/TensorIndexing.h,sha256=T_kM-fLlMh45uDQsPnGnbZhhy92LDN7tLBWmZjIl6u0,25830 +torch/include/ATen/TensorIterator.h,sha256=B4w3IM_J5LIR9cpdIebCsgaK411yNSfhOMLrIUzxMRY,39364 +torch/include/ATen/TensorIteratorInternal.h,sha256=N-f8g2bYnUwKBFz_M4gaPKC-7u7SOGjz8Waa7QT3P8U,2176 +torch/include/ATen/TensorMeta.h,sha256=Lci4YdpHmr-7qC3sMyBi1EDa2Ot8NmYfgP58Mb2GOOI,5126 +torch/include/ATen/TensorOperators.h,sha256=rFW5uIPy2FvyDhV_Cv-SX4HluU7mkR-4sbt2kGF313g,2745 +torch/include/ATen/TensorOptions.h,sha256=58KP7XEfy87cJVZ8fXD1QPvhTMLTYtcV0DUiJSo5jgs,303 +torch/include/ATen/TensorSubclassLikeUtils.h,sha256=vYN0jOsm3jMh_yNKtB3GZzbnImJa-LAthHJbhRKlkVg,3484 +torch/include/ATen/TensorUtils.h,sha256=_-KPHNuzJz-5-HdisWWhK2zbk7CoPgSEQJpymCM0kms,6212 +torch/include/ATen/ThreadLocalPythonObjects.h,sha256=whXxM7v-bwVYB8oyTtxp3aewQVBwrDHXZSdZShSroeQ,906 +torch/include/ATen/ThreadLocalState.h,sha256=COjtSWnMJI-Yh-rAC5e8-1yVOOG0NmgxD7upaLR9bK8,4739 +torch/include/ATen/TracerMode.h,sha256=zrQHJTz242lMURs7jQp5cIEMYIi-r0w0GL4LjJiqV7E,5763 +torch/include/ATen/TypeDefault.h,sha256=QaO8s30SPmSP66Npe9tk7Q0jOTxft41gTqTYL5rHUsI,671 +torch/include/ATen/Utils.h,sha256=bLoH6TfXKju5mLSMXCWSTGEPAppiheEEdly9jiVMgzw,3826 +torch/include/ATen/Version.h,sha256=gwJrgxcrcmw3WBLQ7zRzxhNoKmlF6_6nVDbaV2dYZV0,638 +torch/include/ATen/VmapGeneratedPlumbing.h,sha256=Yd6Ac_93H-R8irtR0M5i7dzBAiK5GY9_4-UNWkeDy6A,1733605 +torch/include/ATen/WrapDimUtils.h,sha256=ICeanLwAPsgdXpzErqbh3Fh8lE7str_veIpRSERuGwg,5109 +torch/include/ATen/WrapDimUtilsMulti.h,sha256=ktOVH3vp7JM5jKUy_bWisOamR-aomgs06AlRuxAg2IM,1329 +torch/include/ATen/accelerator/Graph.h,sha256=Vb1H2gPcEBbLcMVWdMbhGfIP4pqaynqwWxJICniosd0,2035 +torch/include/ATen/autocast_mode.h,sha256=Gp_Rb-DIfVs9AcDwxGwjPlNShWiMMBUN-iA995xMusQ,40459 +torch/include/ATen/ceil_div.h,sha256=ijWlLD2OVoG2d0qgrxvh9wlxYiLthVaZfLssulHBvhM,751 +torch/include/ATen/code_template.h,sha256=gR4kDQln9xFGwLqpdDISngRDAUIc5YtUzFPZ5R6odFk,7238 +torch/include/ATen/core/ATenGeneral.h,sha256=_O9V6rXClA-PYtHzn1XvolQJnfw-eIOk-HprG_O-On4,299 +torch/include/ATen/core/ATenOpList.h,sha256=bbA9vLBtbI6ExK7ZNoVXC_jIuNlASPvIZWBFEE-xU6k,500 +torch/include/ATen/core/ATen_fwd.h,sha256=Zc6Q0BUBY-A3CUN7sFhfnljHXz949myLyskUfhvSgNE,1218 +torch/include/ATen/core/ATen_pch.h,sha256=7rGDD2cMArAko5CYrAnRdqWfs8WCrck4AvhVUv-s-Ms,5208 +torch/include/ATen/core/Array.h,sha256=kVpLnzc2-eUkkMLK4KglsvpF7a7dwDFi9VFh6YKMEWU,1388 +torch/include/ATen/core/Backtrace.h,sha256=y1M82xbaY2gwML--qDHL1JbuyseD6P5UX1w3kqkcf8Q,313 +torch/include/ATen/core/CachingHostAllocator.h,sha256=99LkpsFRuS072D3hkqQFcg8ARtQKDwQPc5pTFJOfE4A,56344 +torch/include/ATen/core/CheckMemoryFormat.h,sha256=V9IvV2yN0x7ogLqw33ygmriPS-u7V91cGN9AhjqIVI8,1044 +torch/include/ATen/core/DeprecatedTypeProperties.h,sha256=dhzNJbU70lKzF-bktvSMcGVBI0JjNXhQmP6RfcVQkTw,4133 +torch/include/ATen/core/DeprecatedTypePropertiesRegistry.h,sha256=CAh7FOjK___7yRlcthPcfZJ-3PvF4LsmXsRv-YVXskw,1098 +torch/include/ATen/core/Dict.h,sha256=ep-GA0dVgLgqBeyc6bMKZpUiBV-t6gLiTdAdK5SZ6NE,13530 +torch/include/ATen/core/Dict_inl.h,sha256=FzQ-5rlxuxfEjID0s3trK3NAi2217-yUnBCHYnLRfrE,7716 +torch/include/ATen/core/DimVector.h,sha256=LVBWqI_2nHqX39SBwtuFY9hTYs1l1FZNq2UV0VMHx5k,532 +torch/include/ATen/core/DistributionsHelper.h,sha256=UeSZW5eA-Cj0f7jRg0b3PBCt5-In_AbHMP9DseleR7o,9172 +torch/include/ATen/core/Formatting.h,sha256=QADQkYtM-Cdu05j5wLuJOMPLauZcunBaRtunoQJzEfk,1077 +torch/include/ATen/core/Generator.h,sha256=BxpFxJ5G1DaK1SmeWaNpQ5NdigRNhPTqJCquwTaE67Q,6752 +torch/include/ATen/core/GeneratorForPrivateuseone.h,sha256=xRETR5JniORd3NzvcUNJnQygihErGRFB0417-wcOplw,1335 +torch/include/ATen/core/GraphImplInterface.h,sha256=-azhinQlE8Dk-13kzviLHQh5J7fZDNB2NCw-mJP_o5Y,4365 +torch/include/ATen/core/IListRef.h,sha256=bzt0QXkaVtN3tdLbfWF7-Cb0dAyl4XdlckN7U_AeXkQ,21284 +torch/include/ATen/core/IListRef_inl.h,sha256=yKTQ1K-WqJ6sXJ346fLeWY3KFyNtH2pUzvDW3mULyaQ,6460 +torch/include/ATen/core/LegacyTypeDispatch.h,sha256=KI_IJGWgHAAbcBcRQl9jvTleBMbkXSgPWaY9EReKEJI,5111 +torch/include/ATen/core/List.h,sha256=mdmo9faTv3jym9eSvvx95U-VGml4idh2VAXeVXaiA9w,16332 +torch/include/ATen/core/List_inl.h,sha256=U9r1ta3BX0QFt7dshmhrJRXY4xZT2MDZpZjfjPkPcAA,11017 +torch/include/ATen/core/MT19937RNGEngine.h,sha256=jfMpQi0pyWXxNWtRHKom8PcvdNuXsZh1Cee6-pT1dGc,6764 +torch/include/ATen/core/NestedIntSymNodeImpl.h,sha256=GE_nsax-X8ELeyu2ZYBA5gCOVEotOuRK9Z6RtPB3UPk,6214 +torch/include/ATen/core/PhiloxRNGEngine.h,sha256=YBxZwCRgyY1ci3yinbmwoFoQDFT88UmfSXYkomus-7I,7984 +torch/include/ATen/core/PythonFallbackKernel.h,sha256=H3uBekJXfQC--9X4ydMjPggK2DuWUEhpBErCOjewedw,1348 +torch/include/ATen/core/PythonOpRegistrationTrampoline.h,sha256=M4T2s3fROpzCOXJnft8tHdRGkp6g16-kC53DqNLopJw,860 +torch/include/ATen/core/QuantizerBase.h,sha256=wQAV8ECaiwW9UdEkOAKv-z_XpZGI5fpS1JdW686c_IA,2941 +torch/include/ATen/core/Range.h,sha256=zzBaUyO3CcuLvUga7QKP4H_gWeJ8wE7Ew2c1B3OedJw,672 +torch/include/ATen/core/Reduction.h,sha256=QAvMKcHeef39irdGfa4jxAmljpQe05HOxRSh3Lt4JSk,653 +torch/include/ATen/core/Scalar.h,sha256=NcGp-BNXkybOBVLuWjEFHe8G3UnAY4y2JV5BeAUaCzQ,283 +torch/include/ATen/core/ScalarType.h,sha256=MSQSYWx0IuOIFuzEBBKyPeVjYlR0xMDm72dGgs7VFqI,287 +torch/include/ATen/core/Tensor.h,sha256=Ypnx1in53tutkF7TeS4APZ7LQEZ9Yo5h6z53d4WIG3E,2599 +torch/include/ATen/core/TensorAccessor.h,sha256=1YyEt1lMIJy4ttt48lBm3RhHOSRL27C9CSKZGA5fSwQ,2816 +torch/include/ATen/core/TensorBase.h,sha256=pn3igQua0KDKCOSvvrhCpCYUg14zcWl6YNBx6EL32Ic,38349 +torch/include/ATen/core/TensorBody.h,sha256=eqyMNwrTviTuZG1vTeVO2rj5L0MkI6Opfqkc6bc3gsU,272536 +torch/include/ATen/core/TorchDispatchUtils.h,sha256=iQ3i4dTXgFFX7uEXkFnhJlN_Kmx2xvOkfEzZKZdZxMk,738 +torch/include/ATen/core/TransformationHelper.h,sha256=jv-KmUraeyjA8O2MZWTSMhYN54shG6SeSRRbxYYlkmA,7085 +torch/include/ATen/core/UndefinedTensorImpl.h,sha256=SRf1XtiwBIMCQhRqppRAfKU3prcLBdFyUrqnJnNKkFc,296 +torch/include/ATen/core/UnsafeFromTH.h,sha256=XnaiDLsTu8NRwGHbONwvtqcDupaTxr62L5F_2NqclUU,962 +torch/include/ATen/core/VariableHooksInterface.h,sha256=xGpMIaTjHHa_1bLqjTni9Ro2p2MYwvWbEFKhdj-EHn4,4012 +torch/include/ATen/core/Variadic.h,sha256=SrRuKG67BcShAjwck5fso_vUVSrSoQJQaxBpNniHIEE,2635 +torch/include/ATen/core/alias_info.h,sha256=L1ASjM52he4SEZWb-cHB1Of-wnnF2PDb1SiR40iL2g4,4836 +torch/include/ATen/core/aten_interned_strings.h,sha256=ji_IxypNucIzmunbfcdAZouIoI-j_uOfUFtUGzLfGqg,57512 +torch/include/ATen/core/blob.h,sha256=HzPJuyyhpAzgjQZNYNS_pYVZqes10TmvWp6sBe68z5c,5498 +torch/include/ATen/core/boxing/BoxedKernel.h,sha256=8v6ePtqfeqnKZtlFKsKxK9XrZYfMXwUtuezkbL89yTQ,8139 +torch/include/ATen/core/boxing/BoxedKernel_impl.h,sha256=o2BCflDZQTYfhS9bbxTd54bFbsFVczk5kdfwXrJi79U,3699 +torch/include/ATen/core/boxing/KernelFunction.h,sha256=nJ-MQX-VGIsmeGzXdZAPrVtXSGZvKkZo0GhF_FybYRU,10653 +torch/include/ATen/core/boxing/KernelFunction_impl.h,sha256=3VuTU11YZyTjgDE0yqcQRbnNnSU8tJNkrcLclm3bkMo,14065 +torch/include/ATen/core/boxing/OperatorKernel.h,sha256=QHTWNctJNO9c1k45cElj6L_vWzgwR-_UeK62y1Emip0,945 +torch/include/ATen/core/boxing/impl/WrapFunctionIntoFunctor.h,sha256=qwWa2ySrY88KlQoDVMu9TBcHcz-hbbEZzqd_oqR70hk,1582 +torch/include/ATen/core/boxing/impl/WrapFunctionIntoRuntimeFunctor.h,sha256=jlmCXnBvefaVbKn_VVpku6ICZMeP0mW6O2CXbJmcxiE,1686 +torch/include/ATen/core/boxing/impl/boxing.h,sha256=pzo7YY_riut-_W1DyzJ6xcF_M4ECGajhsbVEjhfcfIQ,13841 +torch/include/ATen/core/boxing/impl/make_boxed_from_unboxed_functor.h,sha256=EusjWuYyAumrqGEAFVLHDpqtxwJ12vRX4lIILgd6cQI,32502 +torch/include/ATen/core/boxing/impl/test_helpers.h,sha256=nz9XM9HqNklaxmKZqqvhdhKlteXJ0suYExAhwA8zyfk,4655 +torch/include/ATen/core/builtin_function.h,sha256=hcvw2w83YPTxT7bfKkVdfdOKfpLVb6CEoFNdJgFjxWI,2331 +torch/include/ATen/core/class_type.h,sha256=Q8bmJgpe_zSOlO8O_SQOTo2ODVsybsgtDeAJbZ4LnBg,14362 +torch/include/ATen/core/custom_class.h,sha256=g593lYHGtGMEi7wUutuC2qAom6hX0TmbyXJm05PxLsc,998 +torch/include/ATen/core/dispatch/CppSignature.h,sha256=GHUTygJ3aRssV9XcRTt28XyBKq_zaZ5aXLLsOWkKJ2g,2636 +torch/include/ATen/core/dispatch/DispatchKeyExtractor.h,sha256=989OlY2jEyzJ9IftqhfogHkkUnflKXOjBVEf4E3EvDw,11246 +torch/include/ATen/core/dispatch/Dispatcher.h,sha256=mRTQsvl9UTKV6NdS9TTqFdvdD9oa1pyXuXiYzKdvwsg,35239 +torch/include/ATen/core/dispatch/ObservedOperators.h,sha256=eKNoomteAbCsaQ7Qofff0buj44X4yGyrAOlAd794UFU,583 +torch/include/ATen/core/dispatch/OperatorEntry.h,sha256=xQXBXoYZummvVsuoXCVJog48F6qumJny-QfOdQXVzmU,13377 +torch/include/ATen/core/dispatch/OperatorOptions.h,sha256=Ibh7cTueyJ3FNcDS86MMprRq3uNlZO19f2yURfIu-gc,1140 +torch/include/ATen/core/dispatch/RegistrationHandleRAII.h,sha256=5sWLlO1mx9tV__IwcZcUqftnxvjJ2_CA8pmG-r6WTkk,1131 +torch/include/ATen/core/dynamic_type.h,sha256=6a7Tkj4OVKepnB8ixw5e1Pl-MZ6BZZGPPlRaFtHhZ0o,11155 +torch/include/ATen/core/enum_tag.h,sha256=DJDKXIXYyPTMVxuwHaAz_asYcI4bMuOtzKOr0O43zUw,362 +torch/include/ATen/core/enum_type.h,sha256=2si4vrOCltW7rJjlxYiuODIBy5CYgXBved82o05vhLk,3183 +torch/include/ATen/core/function.h,sha256=MF6WVKSjPmoBUVLtZbQWYfHAyxNTxo_j6iboqbzcqQE,3764 +torch/include/ATen/core/function_schema.h,sha256=7NMoBpKm9QtoQg59GkMtut4V78z1k1u5GW2P9707NTg,24379 +torch/include/ATen/core/function_schema_inl.h,sha256=pgUnnBp9VgVUFWUtZKlFg3eLFV1mz34d5E1WyKibNIQ,2325 +torch/include/ATen/core/functional.h,sha256=2YeMi9lGkXDPJTQtr9AtxErPP72ioMMLf0v5jj0TqRQ,1718 +torch/include/ATen/core/grad_mode.h,sha256=v4cKv2y2EFgAqEH2yI_D1PdoPs5_neoLiddCCwrvqrM,464 +torch/include/ATen/core/interned_strings.h,sha256=9UISASIk3uyp6M2VRiZKkzw7V3IwnIDaE3UkAa7lyK0,13584 +torch/include/ATen/core/interned_strings_class.h,sha256=rxTLcElTBOppL-iUUQitRcC-RebaQp3Ch0--85iS9Z8,976 +torch/include/ATen/core/ivalue.h,sha256=Xx4aWD1K6XrgVxCnvJwJZtWYwmb9olKI_3Pwwilxgow,53010 +torch/include/ATen/core/ivalue_inl.h,sha256=S6Ny-tjW-ANmYtRPw5rG3DtfYKe-IT6DbycqkGE6sfw,88392 +torch/include/ATen/core/ivalue_to.h,sha256=OPCshnu8WClCKdXRzuNPhnwi9dtcH7HVB7NZQf2_cLo,1010 +torch/include/ATen/core/jit_type.h,sha256=-xWECSHlMs5oCClwcpM4UEIH1rOiUjoM35nXw8BEeWc,72433 +torch/include/ATen/core/jit_type_base.h,sha256=_ZbemJj0czwJ2Rzmo8aDnL9oceAmsp5q0QHMfYw4hiQ,19409 +torch/include/ATen/core/op_registration/adaption.h,sha256=kRQiFmEFwArdI_l_F7MpAg7AzdWGanMvunJZe4hcfqQ,3470 +torch/include/ATen/core/op_registration/infer_schema.h,sha256=5IaNPUJuTtzbv-Gl591VPWrDZuaRw_IkRcsltPIY3Aw,6992 +torch/include/ATen/core/op_registration/op_allowlist.h,sha256=BKCMs9ZStEtcOJ6dlRxJWnzM6DKyknZ0l-9rgjOdh-o,6559 +torch/include/ATen/core/op_registration/op_registration.h,sha256=-4NqKDvpmQiGuNZdFFRh60u9FhvVurjVacHvH-27Z6Y,28800 +torch/include/ATen/core/operator_name.h,sha256=p9b3sJbBVw-QFa-WI51NiWhSBc3UNcwRcgr9y6H02FQ,3365 +torch/include/ATen/core/qualified_name.h,sha256=wMsJ1QY3tiLOSe04oAx-vfELuZXraI5Lpy6UQUEnXJQ,4627 +torch/include/ATen/core/rref_interface.h,sha256=mhAcftY4AYad0H3q2vuRqqZBOKu_m0yqzC-z33yl3cQ,1462 +torch/include/ATen/core/stack.h,sha256=fU2ASyaX23y_4Jp3z0iION60clPk89-XWc2QRMejP80,7355 +torch/include/ATen/core/symbol.h,sha256=Q962YzZax2ZZNIt_u4hdywo_WnEsxOafCexGM492LF4,5958 +torch/include/ATen/core/type_factory.h,sha256=R9o5Y2pdvrg3gOP-2sv82vEqqDPiMMyp1B7smfLir3Q,3501 +torch/include/ATen/core/type_ptr.h,sha256=Mby1oP4rzL07obzNnL0DD5reEEnPfBsJJI3hto8NlzQ,1483 +torch/include/ATen/core/typeid.h,sha256=eMggcfZfdVXFBl32XD_y3SL-xntu8-3vsW2gaorUV0Q,283 +torch/include/ATen/cpp_custom_type_hack.h,sha256=uRYZgQGKQRkEh6F9SnGGWDNyBU-oxzlP2vo5wQEU4io,5684 +torch/include/ATen/cpu/FlushDenormal.h,sha256=9gYBrIZWnFSzBKy4SpTo7QPFzSHi5WSkGNrBbzLjMjM,791 +torch/include/ATen/cpu/StatelessPhilox4x32.h,sha256=0UJmgxNAAOMv8XtGzANfrLVdEz-rb5FQhRhKgmykoXU,2500 +torch/include/ATen/cpu/Utils.h,sha256=9fzOipawtA_FNN5Ejy9sqTzawnJM29NCKo-qBL1_Fhg,922 +torch/include/ATen/cpu/vec/functional.h,sha256=AWcimK14Ju73ML7A0rEXLtY4C9kH2qDeN0jLCdVpklg,356 +torch/include/ATen/cpu/vec/functional_base.h,sha256=6k0KTdb6veYbBaGMjEqXa9l65Xev3uEnQCyQl_VpzqY,15739 +torch/include/ATen/cpu/vec/functional_bfloat16.h,sha256=bUDJvUshdQsBQL3q-TzY9FXE8EZrRQHJHmIYtCB0fvk,25665 +torch/include/ATen/cpu/vec/intrinsics.h,sha256=etCWzMEatbbky2AF29OWWN1owMc00LGkw50bh3CEBOQ,303 +torch/include/ATen/cpu/vec/sve/sve_helper.h,sha256=93OjzvSBUpLvypKeiO9ZBadwEpkA1512aLJRLODntf0,3429 +torch/include/ATen/cpu/vec/sve/vec_bfloat16.h,sha256=xdcm_hsk2U6rIyQkRfFEl4CbFUSLA_AxXfC-UCJGAzk,23827 +torch/include/ATen/cpu/vec/sve/vec_common_sve.h,sha256=lNA_x6FVIXPKkEXj2uiJ4z5l-By6SOupeT1XFNMISzc,8687 +torch/include/ATen/cpu/vec/sve/vec_double.h,sha256=EuC1-cuLGBjnhB8n8Ig_x5rAggD1_eKDoWzokXUrC2g,19956 +torch/include/ATen/cpu/vec/sve/vec_float.h,sha256=WA1KPiL2COrzoByVXIK33s4y2s-voJ5cImhUt7EWi50,28782 +torch/include/ATen/cpu/vec/sve/vec_int.h,sha256=EWJ_lJbGUpxA0dHYrm5V_dDB2OElWbyqU8ErknkXVV4,29076 +torch/include/ATen/cpu/vec/sve/vec_qint.h,sha256=wgQ8pam6CT8zsWyv6MASTXSPrSrM0WwZs8eviYcQjQU,19394 +torch/include/ATen/cpu/vec/vec.h,sha256=GagNXvVOqjRWeA6kvDUFj8C7U4mEpGvD0GTsPGzaGeo,1603 +torch/include/ATen/cpu/vec/vec128/vec128.h,sha256=nXYcpEQuQW3pwtUxYIS6RUGeXFZSuG0pJI2L_TRy5Ns,779 +torch/include/ATen/cpu/vec/vec128/vec128_bfloat16_neon.h,sha256=h9SKdp0Y4rlU-FhwVfg1e4hlQrdMqqjMydjGPbysgmU,26933 +torch/include/ATen/cpu/vec/vec128/vec128_convert.h,sha256=NE2RD-rdTqQi4J8ZxoYh9MAMsF1rBXqtMVuQ7JvXkGI,13492 +torch/include/ATen/cpu/vec/vec128/vec128_double_neon.h,sha256=yKkClDbtj0BtocR6Jd68h2Qa8_53APHIKaq7nA4lNJI,18325 +torch/include/ATen/cpu/vec/vec128/vec128_float_neon.h,sha256=icP4Wd3SVjWZifrz0W34cpqEyfBlwWfmWroc1bBshVI,26632 +torch/include/ATen/cpu/vec/vec128/vec128_half_neon.h,sha256=djjdpnDT8XD_i1OOjvX94Ao4abo7g9X6yCbN7O0zWPk,20628 +torch/include/ATen/cpu/vec/vec128/vec128_int_aarch64.h,sha256=4w9-6VAVidX9Y1ZL0k2XzMJR295JoDXj7cbqie4ZJMA,32389 +torch/include/ATen/cpu/vec/vec128/vec128_reduced_precision_common_neon.h,sha256=VTyCdjQtf17cd5yUhOZSd44oTL32EtajY8mq3zBZIx8,10176 +torch/include/ATen/cpu/vec/vec128/vec128_uint_aarch64.h,sha256=rU--tsxkUTKBOT4TD0XcB78AtGtT699GvcSKf1e7Cpw,21095 +torch/include/ATen/cpu/vec/vec256/vec256.h,sha256=VX77z_lxthveCbpfIcIw5D8y6UfGKNN6cU1CQ3HHu-w,12218 +torch/include/ATen/cpu/vec/vec256/vec256_16bit_float.h,sha256=0RVACZBTbAAQuJgimFMllPr-SU1STksxZTrOEZOE7bQ,29094 +torch/include/ATen/cpu/vec/vec256/vec256_bfloat16.h,sha256=ozcJO1Jp3RNJ8Vo97IxhE_GvnhFxSmabYnMTmmf3IkI,9061 +torch/include/ATen/cpu/vec/vec256/vec256_complex_double.h,sha256=kQOcpVg4p9pgs3n00pmclCKckslMUendasQ63l-bs0A,19686 +torch/include/ATen/cpu/vec/vec256/vec256_complex_float.h,sha256=xiyU3uJCAD2sg75U9MRPDK1I4IjMEBQh0UDL3n0j9P8,21806 +torch/include/ATen/cpu/vec/vec256/vec256_convert.h,sha256=sKvyirrkm4QhenxzQZYEatuzIOp1RIomJ4h8VSwo0ho,11287 +torch/include/ATen/cpu/vec/vec256/vec256_double.h,sha256=I1z6jFN67mKdyNTcg8bZnaVs8oIPdDMIDbtZUe2tPqY,15646 +torch/include/ATen/cpu/vec/vec256/vec256_float.h,sha256=LFVdY_boB02gIQRM9ZTpAjhsSUN0DOQT1ZnVdmfBUes,27827 +torch/include/ATen/cpu/vec/vec256/vec256_half.h,sha256=MKSjE6wiMvHRxr_Ci_prSCJ2eeonRFPS5IK8WNUs7Jg,8643 +torch/include/ATen/cpu/vec/vec256/vec256_int.h,sha256=UQE5w_dYMVvCPiHLDj4RYQbFJ_Hpyo4i5DAv4nUk0_w,65034 +torch/include/ATen/cpu/vec/vec256/vec256_mask.h,sha256=W4mmnWT4Eh7nI6t1JziXE3-3SP9XKEpAg5CbBlUN3B8,9026 +torch/include/ATen/cpu/vec/vec256/vec256_qint.h,sha256=hwKTKNFPoSL_oEZzK91bh7SNw3MQEbevjEC6xunKI4A,49638 +torch/include/ATen/cpu/vec/vec256/vsx/vec256_bfloat16_vsx.h,sha256=PvlK-Gb3-0MFQylPhaG-6ho72E0wN_-1gzOwbT6Xu1s,2391 +torch/include/ATen/cpu/vec/vec256/vsx/vec256_common_vsx.h,sha256=H-2vPZiGmNo-0PJmRrqOpMU4_oCzthYuwAgCGwxJThk,8395 +torch/include/ATen/cpu/vec/vec256/vsx/vec256_complex_double_vsx.h,sha256=1Zlv_6NvBQQDou_liAa7YSB51ukCxvPe4mqQxM10N4M,21944 +torch/include/ATen/cpu/vec/vec256/vsx/vec256_complex_float_vsx.h,sha256=hIwCx-teJK-sOV4SZAzRr82z9gKF06MleuXyOYJDiF8,24633 +torch/include/ATen/cpu/vec/vec256/vsx/vec256_double_vsx.h,sha256=TDRZWC1PIkRMA5B1KZpZZuz_uVOY6Fez0EpJXEXWECs,16520 +torch/include/ATen/cpu/vec/vec256/vsx/vec256_float_vsx.h,sha256=1HbtTcNYtU5K98K1JpkRC68ctNKIhwkP96pvyiBYpjI,17217 +torch/include/ATen/cpu/vec/vec256/vsx/vec256_int16_vsx.h,sha256=zcmBd6vjyMCpYvMMyimX-807-Whg-j5NL8QT1-2uyzo,13882 +torch/include/ATen/cpu/vec/vec256/vsx/vec256_int32_vsx.h,sha256=OGnNrRf1bernO1UhJKEKm411qXfJHcaG3syr65yGMl8,11697 +torch/include/ATen/cpu/vec/vec256/vsx/vec256_int64_vsx.h,sha256=5Hp-u4SPo9fHpiu7F5hfCHAoAAAyjwdwAMWefjCt7OI,9966 +torch/include/ATen/cpu/vec/vec256/vsx/vec256_mask_vsx.h,sha256=CQJIsE6joHaFwbtDr3ePX85j4NSj8U_SIGOmEFHZ4X0,1980 +torch/include/ATen/cpu/vec/vec256/vsx/vec256_qint32_vsx.h,sha256=_b98y2fVhmCjOGB-NOCn_o9ETw1vRC7dFrWGzke1FXk,10327 +torch/include/ATen/cpu/vec/vec256/vsx/vec256_qint8_vsx.h,sha256=eTyVeMAVAtDqPDWIvvh2Hp0U1hqMNQJHn6PhYZfnRMQ,17680 +torch/include/ATen/cpu/vec/vec256/vsx/vec256_quint8_vsx.h,sha256=FnNALy_yto8Of61CfNTKyPYyvBTwjkn1khUVBAhrd-M,18377 +torch/include/ATen/cpu/vec/vec256/vsx/vsx_helpers.h,sha256=uoMPqd68K1_R4jlS6vPKq245iVj-Kw_BkfQBlqdeVDs,22756 +torch/include/ATen/cpu/vec/vec256/zarch/vec256_zarch.h,sha256=0zAR5IXUaKCYI6z9vwhpmGSeKwull2Nhd3kxY1ph5Tw,102726 +torch/include/ATen/cpu/vec/vec512/vec512.h,sha256=MiuMjAZZU7G-eUN9MNQl4kOJp5L-kFWqU1WtxOHNNsA,10634 +torch/include/ATen/cpu/vec/vec512/vec512_bfloat16.h,sha256=hFMbRSTeh6UYc6k8Y-zH6lHBnr8qtQkJ8yI3KBNENfQ,66810 +torch/include/ATen/cpu/vec/vec512/vec512_complex_double.h,sha256=FV-HzkUxhfXX6lGFZr5Zj8wMY9ztBMlIJDKT3xZkgO0,24097 +torch/include/ATen/cpu/vec/vec512/vec512_complex_float.h,sha256=vBfSQH7VSPJraB-h4SUTmzMZUY7cps5o3rpNCdLZeGY,44590 +torch/include/ATen/cpu/vec/vec512/vec512_convert.h,sha256=r2BxXhwG0dzxGl7NXklUh9wU8pK2-ORQdJSAkUqzMaM,12177 +torch/include/ATen/cpu/vec/vec512/vec512_double.h,sha256=X2b0pNIcpR3syEHcEB75YWhPgJF8GeIPkfQQKgLpQNI,17426 +torch/include/ATen/cpu/vec/vec512/vec512_float.h,sha256=GsJGA976xqA1EsWGDl_RPreU38nV0vlTZs1Cji81sQI,30789 +torch/include/ATen/cpu/vec/vec512/vec512_float8.h,sha256=ae66hD9W3Vqb69iMZWn_NFV3EUECL8a6SiGUO04adfc,25408 +torch/include/ATen/cpu/vec/vec512/vec512_int.h,sha256=S16o2hsg3Jz4ywc6TYE_oCES2o8UhkeCbbbiZnWPRi0,59240 +torch/include/ATen/cpu/vec/vec512/vec512_mask.h,sha256=KC5eBIuuC14cSChSVe41Z6FtFqqRn8OVCeG0nMY-9y0,12552 +torch/include/ATen/cpu/vec/vec512/vec512_qint.h,sha256=vadu9gpZFoyKwvNUnZg7OsCtnI_DS4snTjv4Exwu48o,51145 +torch/include/ATen/cpu/vec/vec_base.h,sha256=z8IetjyMKL-uNAzrvbLmrQvXnCehDIJ14MkYj2iRH4M,50404 +torch/include/ATen/cpu/vec/vec_convert.h,sha256=KDyYj1OJ8VASEZRii8vLdwPpzIM-LDotXDH_DInw2cQ,5014 +torch/include/ATen/cpu/vec/vec_half.h,sha256=PW1nLS9MdKp_smD5_xNW7hcy0gTc9nHIwG9TrtWGT88,3748 +torch/include/ATen/cpu/vec/vec_mask.h,sha256=YYpAyn_eEKI4-2l3YiSeYz0_Shk7WpQzv8Xq5CBli24,10669 +torch/include/ATen/cpu/vec/vec_n.h,sha256=65PbUFbRex448sk8dXUH2MvQ6SZDIZClzjLEH_FPJ0k,13810 +torch/include/ATen/cpu/vec/vec_quant.h,sha256=b4rBHPDN4KwkTkoM0LtoiiLDhtdF8dvY9B19YwXu6uk,8891 +torch/include/ATen/cpu/vml.h,sha256=_biUSzcgtpOx-atj0MS8QOCFlQxHZDU2hrg7GQWgT0w,6327 +torch/include/ATen/cuda/ATenCUDAGeneral.h,sha256=Y3g0kFj0PlB9p2jUAA4XS22IQ3_R6tSGs6FEiTUBbRk,444 +torch/include/ATen/cuda/ApplyGridUtils.cuh,sha256=Y-V0zrTY1oL4SOLJzAHxz7wDiZ1hT_6H3mdi53c21Ss,1563 +torch/include/ATen/cuda/AsmUtils.cuh,sha256=Y-lJzTpDkxnblbTOX_hXt-7Ykyb7TomBsV5lv062qlk,3690 +torch/include/ATen/cuda/Atomic.cuh,sha256=eJPV1wfD9fqgFIxrryZg_zjVoI5t6y5gchpxTsLX6Ao,296 +torch/include/ATen/cuda/CUDAApplyUtils.cuh,sha256=2FO8fHZKLVe3V-IXmHU1pudlu8VpcExKOcAtzC5QSbo,20597 +torch/include/ATen/cuda/CUDABlas.h,sha256=imaj25X8DlkkCLNtoheeQo4aCVyjXzdYx4wQSYmb-c4,17128 +torch/include/ATen/cuda/CUDAContext.h,sha256=FVxhveWjVQ87qecv__fmXrFj1HVowBTGI_uBUUhEQ9A,492 +torch/include/ATen/cuda/CUDAContextLight.h,sha256=BfpO9zTt0fqMsDHN4xQK1hYzs_NMZ8-Jrrw2Q84EaZE,3657 +torch/include/ATen/cuda/CUDADataType.h,sha256=pTqigoA6b1txf7mFGuydVvKAye9vbIQ2ZOikI5upIcQ,3193 +torch/include/ATen/cuda/CUDADevice.h,sha256=ibOUWACsMvCwJkj8Vs-JaSAacLjfePU25ikYXuE0h6s,786 +torch/include/ATen/cuda/CUDAEvent.h,sha256=1n0unf9uzX68TriMIOlSv3rtmMDaCr0khuMi3pInToA,440 +torch/include/ATen/cuda/CUDAGeneratorImpl.h,sha256=GlaZMvn_YYiC15-ms2fUTNvqHXXJsqv5ktpS-BGFofo,7262 +torch/include/ATen/cuda/CUDAGraph.h,sha256=LuTLRPGRz9KVwzsqg7DZoP_aMtpaRgd310NiGtzfVzQ,9539 +torch/include/ATen/cuda/CUDAGraphsUtils.cuh,sha256=Wahj6otCRgDBglGPuVQrqwy5iirfotsxHRcmSZaj1zo,2310 +torch/include/ATen/cuda/CUDASparse.h,sha256=sRn70ExXg9HNm9pSH9f-Xm2u6jxbBZFGWyyyEdHJMTQ,1035 +torch/include/ATen/cuda/CUDASparseBlas.h,sha256=NW9_yX3WvUtCA5A-d5OZrK3Z_d5hlCRXNYncjhG7TkE,12945 +torch/include/ATen/cuda/CUDASparseDescriptors.h,sha256=6GqtUUckWOZojdaAkoqon3QLkifGy1cfZQmz9iOdBzE,8034 +torch/include/ATen/cuda/CUDATensorMethods.cuh,sha256=0XUAaYRzKUbJnw8-QsCk9huRWC_eBNqPI5rgw8m2Ecw,524 +torch/include/ATen/cuda/CUDAUtils.h,sha256=aqOrT9ciEgvqxTs6AIJ1g8AUYpuEkYDGbRDFrJHk3CY,670 +torch/include/ATen/cuda/CachingHostAllocator.h,sha256=Cubx1tn7320HVu04x0uI7uJP-UkxVma6N9Q8--xnqSM,3284 +torch/include/ATen/cuda/DeviceUtils.cuh,sha256=ckhE-i-e55aZrBmh6A0KMa0KJf_d4yan1AZ-YZCwlF8,3510 +torch/include/ATen/cuda/EmptyTensor.h,sha256=ic1E7hVwYA_iNMXuG8cFUN0j213xDHgv1wN9gsaXUFA,1460 +torch/include/ATen/cuda/Exceptions.h,sha256=U_K2WEZG41K6dCM7j75INCNlounAjX8SRhxK9uKOuJs,13558 +torch/include/ATen/cuda/MemPool.h,sha256=wGz7JyS4bl1bObFNXCwhLL7rFhNCSKXQ7p7AZaJNZtc,1539 +torch/include/ATen/cuda/NumericLimits.cuh,sha256=UED-0HPXq3bA_mqroXCxFCrUBW7n4aLTiZ2xjrsJ15w,1597 +torch/include/ATen/cuda/PeerToPeerAccess.h,sha256=3-oEtfUZnYnanTvgS1xcb96lMZzWdxgB9cLvRRehZQc,1515 +torch/include/ATen/cuda/PhiloxCudaState.h,sha256=x1KYpK2i45uMEWt3uidetR8Vyp-0vsGkcpMQdqEE_2k,339 +torch/include/ATen/cuda/PhiloxUtils.cuh,sha256=ZgBk-XiSctpyVV1_MvAlLL96WXq795w0bA_oSxqQC9I,366 +torch/include/ATen/cuda/PinnedMemoryAllocator.h,sha256=ZYJfIg5C4V3bISgVLBvk5Go_xeEcOuiu84XyZLyY2lI,477 +torch/include/ATen/cuda/ScanUtils.cuh,sha256=2z2Hqz5wfzxSwSpbzDfeuT9F4Zji2Ju3RtyCwNiggO8,2281 +torch/include/ATen/cuda/Sleep.h,sha256=GFH-xrg91qwm84BnIyb8V4-rwzBLAiTjbwaLsU3N5ws,573 +torch/include/ATen/cuda/StatelessPhilox4x32.cuh,sha256=y4xOVqat8H5jjWfUva1JpWh40i4QUnLL5Lz9yp86Y8Q,2359 +torch/include/ATen/cuda/ThrustAllocator.h,sha256=vuoo-4-S71Xy4C5lfrVttB6UChIlYxlr3Wi6inoYuMo,759 +torch/include/ATen/cuda/cub-RadixSortPairs.cuh,sha256=7ZRAJC-Wvk63eaa7XLVl5qsiOMWWrdi909yoyvWWMdY,2459 +torch/include/ATen/cuda/cub.cuh,sha256=AzCpS9kM5WUrqMrI7pi_Io-nC4Y1DR2A-uMSfWjsNjY,22994 +torch/include/ATen/cuda/cub.h,sha256=D0lN7cr8YsLXyx83xbz7CYBCwmo1J0tcKV1dSTo_JyA,4016 +torch/include/ATen/cuda/cub_definitions.cuh,sha256=mxt21GZXXqZGAfUTMkUSWpmLi-ljv18y-cDBEewzuMk,1252 +torch/include/ATen/cuda/detail/BLASConstants.h,sha256=QZwd8LVzKS61nuWpJsNvpmLlk4N9w5nn1R-V32wOBoA,431 +torch/include/ATen/cuda/detail/CUDAHooks.h,sha256=mdCiITTzHnJ8-mxedSglmjUXDj6rQ215g6GwXEYefmA,3343 +torch/include/ATen/cuda/detail/CublasLtUtils.h,sha256=sRgHTJ7jiMJLHR6UBvYpjbaVRNJsOmWDYGz8uV3FdJA,11248 +torch/include/ATen/cuda/detail/DeviceThreadHandles.h,sha256=yW1GbtigusLf7FP5EP8wUlm_dSmlyr6I3N0-m9tL7uc,9066 +torch/include/ATen/cuda/detail/IndexUtils.cuh,sha256=S-kBfp6T_yGnnfsFv-H78_iK5pHPBLi7ZLyv8XiFOII,1983 +torch/include/ATen/cuda/detail/IntegerDivider.cuh,sha256=qORRBvLTJxI54_r7S1_Yn7HftysizNWtKKSRysEHzVs,4273 +torch/include/ATen/cuda/detail/KernelUtils.h,sha256=I7_ldw6KRcc2hGcAv3Jqz1vARlHZbTMVfOdJMJla88w,1789 +torch/include/ATen/cuda/detail/LazyNVRTC.h,sha256=YvqkMO6N5dTfYQaSB2B5iv7kZaCV-dfeD4uPTu63NVg,474 +torch/include/ATen/cuda/detail/OffsetCalculator.cuh,sha256=Q8O-0N9eBPTnSDrmMQ7xvFdMvyKeB_Ig7vrigO3dux4,5112 +torch/include/ATen/cuda/detail/PhiloxCudaStateRaw.cuh,sha256=1bwPiGKT62D7Vs4llEQl4WTT75aWa3NfgNY7HBRyNvU,1612 +torch/include/ATen/cuda/detail/ROCmMacros.cuh,sha256=k6tL5XEwnHbtfFR_U2Zz9kWKIPbObHh2gBugmwCPwHs,307 +torch/include/ATen/cuda/detail/TensorInfo.cuh,sha256=KJwJRq_CHfJHX7RzpQQZshnm27T86F1k9Ry-QEOUz20,3494 +torch/include/ATen/cuda/detail/UnpackRaw.cuh,sha256=j5i7r21kCrg6SKQf_BBP_uDrii4xIup4IX4Z2pKLXno,1993 +torch/include/ATen/cuda/jiterator.h,sha256=gO2gKosxQYi4aLSupXH99e-TkBKSqifzCQNLdI1ltA8,1214 +torch/include/ATen/cuda/jiterator_impl.h,sha256=tXptkBiIXw0EkZGspe6LATT6VuqS7Z4Y02Y553MZBuc,7400 +torch/include/ATen/cuda/llvm_jit_strings.h,sha256=kJpasSteT1vKc5ujFRyDGa7whcIKnLwaOxyxtRKtkRw,682 +torch/include/ATen/cuda/tunable/GemmCommon.h,sha256=37nzKxlqgq41nliPjTqzpBHJSdKE1WldZ-1G-Ug5xC0,23639 +torch/include/ATen/cuda/tunable/GemmCublaslt.h,sha256=8HI3SvBa4x3feHsIcYt0KPSbzwhVu0avKkk5Pfp-K5E,25326 +torch/include/ATen/cuda/tunable/GemmHipblaslt.h,sha256=3rePxvs6Qwb-NpUch-QpqJWWbeZZMXGRzqeJVnw7PBs,22094 +torch/include/ATen/cuda/tunable/GemmRocblas.h,sha256=Lt-uSkHlwvZ8zjdnxBWjwDzqDJ5JZsxqikTqn42gpyA,11594 +torch/include/ATen/cuda/tunable/StreamTimer.h,sha256=vlQYiJZNrcvcuAQzqL4NZiOT8FG-QmaV6DynJbFm7Gs,1299 +torch/include/ATen/cuda/tunable/Tunable.h,sha256=kbgtQG35VJe-u70sTtackDDPXgjXig9WcY5_BHn5YOk,8751 +torch/include/ATen/cuda/tunable/TunableGemm.h,sha256=VCRZ7_4MEmb_IewSMcD-GOnIgPboJ4YAVdCMFll0ft8,10236 +torch/include/ATen/cuda/tunable/TunableOp.h,sha256=GLsN_Y3rv0UiZiVwIHlIhGdF-8_xrmaJ-OfPxa6FZvc,15900 +torch/include/ATen/cudnn/Descriptors.h,sha256=DmWD2pCzqLqxsfPCGmc4rDK6sCgmFkZPKaBcQDYEaVw,15335 +torch/include/ATen/cudnn/Handle.h,sha256=pGkiq0ZzcZLgbiGQ8ybHUvnVZmoPyLhjgsha4JNSkYY,447 +torch/include/ATen/cudnn/Handles.h,sha256=jmhakLkgV8AdF07lLAQbwsmcEeRRDi8fNcYhtYSI77g,298 +torch/include/ATen/cudnn/Types.h,sha256=HfZhdzuBc-DZ8L0ketUnMViu39Ct7jTkhhglPgzGQ2M,564 +torch/include/ATen/cudnn/Utils.h,sha256=y3Hdkk0UfdPIl8rj9NRpz-5jq11m8NJy8wK16GeHFn0,849 +torch/include/ATen/cudnn/cudnn-wrapper.h,sha256=QTBGaaa7_h2SB3HmG4U8LjN4AOx7393HWo70zI-TfGY,794 +torch/include/ATen/detail/AcceleratorHooksInterface.h,sha256=9bytpnF9OcNzUfqXbIjV66b9BQ_S25C0ByyOE6Eychc,3248 +torch/include/ATen/detail/CUDAHooksInterface.h,sha256=c2ErwgVQ3SleNNWQmUwt-z6jJHO6eB1Z1-yLOTs3Wl4,8862 +torch/include/ATen/detail/FunctionTraits.h,sha256=s_ett-iw2Qflvg9_x-aJL8VRXZS5ck2t5o-U7FZPg88,3316 +torch/include/ATen/detail/HIPHooksInterface.h,sha256=ElbrknLtR-o622AQWJz-ie4RV2jw2yY8_XgkL0P4GYo,2144 +torch/include/ATen/detail/HPUHooksInterface.h,sha256=B5GS9btNsCRr17mytiHpK5sANHxZ61T9lFIUurboGps,1708 +torch/include/ATen/detail/IPUHooksInterface.h,sha256=xXKsifzpLcI-THJRwdR_SGFgiGnVn7XcS_qL5tp0X5U,1554 +torch/include/ATen/detail/MAIAHooksInterface.h,sha256=euSv7fDYrH7cndOmuRUdRXU1vWbsS04jUrwLlhHKwGk,1470 +torch/include/ATen/detail/MPSHooksInterface.h,sha256=OPLV4-4rxB9r8IhIVTzQG-4bIBGEfx3y2CyUaK-7EbA,4114 +torch/include/ATen/detail/MTIAHooksInterface.h,sha256=qZR_N2CLJl8RD-0B6AvoTO1NSJeXTJtZ-CVWJWlnKOM,6025 +torch/include/ATen/detail/PrivateUse1HooksInterface.h,sha256=OSy0j1RhVNngvxjGtO86N6lnMnQxQt4YnQwjdr5EOGU,2743 +torch/include/ATen/detail/XLAHooksInterface.h,sha256=OkrdQgwwEDwlIs-F3ThwvMysR-VHUWqTLMADr6JwSmU,2733 +torch/include/ATen/detail/XPUHooksInterface.h,sha256=BvBT0MjzpHcfoQzIUpzEEF8QDTOQg3kr7GMLDY02_Dg,2980 +torch/include/ATen/div_rtn.h,sha256=4nvTpsu7JOVXbz2gkH7EqdYfREUw8zg3yjJLEo08IDc,465 +torch/include/ATen/dlpack.h,sha256=YtCs_UQXAPm5cO8taUvehijM1KNrC10xFZJ2g1D2jXM,23516 +torch/include/ATen/functorch/ADInterpreters.h,sha256=SimV299hZtyUMJekW7ytVKpvPW686YhuLctUjvG5Zro,1814 +torch/include/ATen/functorch/BatchRulesHelper.h,sha256=l553Ne5NOm--LGw3lBRvqTwF-cEIFsnkH16dsFcYOQw,19053 +torch/include/ATen/functorch/BatchedFallback.h,sha256=0ECOodFmirkxr_ztE34K_EToFxZ75h3pltUjnXawP1Q,3693 +torch/include/ATen/functorch/BatchedTensorImpl.h,sha256=DVopnyvInIgXGmGObzwEk77QsqgxVV21xuoWD17QyHU,6803 +torch/include/ATen/functorch/BatchingMetaprogramming.h,sha256=R8l4RZdmjefQfMPNMG1jvo3pB7RK0UVTw6AXR53ln00,5244 +torch/include/ATen/functorch/DynamicLayer.h,sha256=NMxlke8eCf9T2KSNdWT_fbifb884srNDKk6-bPdHupQ,5938 +torch/include/ATen/functorch/FunctionalizeInterpreter.h,sha256=3jU-mTn8FDBqjyd1gUfW0dAE8ACSPFDx2dAbbgArX0c,1161 +torch/include/ATen/functorch/Interpreter.h,sha256=8o8SL3qrcxjdu7zwoTfowAj-iseudhvTufnjNkj-3dg,14967 +torch/include/ATen/functorch/LegacyVmapTransforms.h,sha256=nHwpaVy-psnxBrDnAbcxedCc2iWjQ75QjUWVosg-ZWw,8505 +torch/include/ATen/functorch/Macros.h,sha256=hqjfrYvy4mqhY3MXdsNKQUXzb2y8LrkdWgColdke2bE,304 +torch/include/ATen/functorch/PlumbingHelper.h,sha256=qRDYK1BuwfrE1vr3QWGKEhSPeosHrq0lZqKOlirt_TQ,3108 +torch/include/ATen/functorch/TensorWrapper.h,sha256=kghomRRLftFFipY5vp6zZpCYAA6k1SyJOpHoXAYPYzY,4279 +torch/include/ATen/functorch/VmapInterpreter.h,sha256=egzDZVrqImPBju3_cVquUj4xKR6OSeNjKd5Gnt7dP6A,1211 +torch/include/ATen/hip/impl/HIPAllocatorMasqueradingAsCUDA.h,sha256=P71dPrMT71EerhduHcHb83JY3FYWlyyZ8Q6AYNAFDFU,7616 +torch/include/ATen/hip/impl/HIPCachingAllocatorMasqueradingAsCUDA.h,sha256=GxEcAc10s5n7pTqtIyBkOrc5desdsHkRudptU_-rg4I,2852 +torch/include/ATen/hip/impl/HIPGuardImplMasqueradingAsCUDA.h,sha256=CvUM0wbuQFlB43HQOmsYL0DmOxH75-1Hz8j8ksIjrRo,4072 +torch/include/ATen/hip/impl/HIPStreamMasqueradingAsCUDA.h,sha256=fFzzF1C-DC5hyT8e5T0kQITqNfiEfPhPxxj-0flXP2M,1577 +torch/include/ATen/jit_macros.h,sha256=5fSgWkojnHS8f9rUXh8asSKA8lxAzLinxtGbkh5muqY,774 +torch/include/ATen/jiterator_macros.h,sha256=g-vRy4Cy6UmhGVXErSsGIM_vcAtxu40vmcLA_6xPF2I,1760 +torch/include/ATen/metal/Context.h,sha256=3Sf57yULLhzLS_JYMrGeIaC99E4_0V9-G4VzeV6YjH8,936 +torch/include/ATen/miopen/Descriptors.h,sha256=Rm4ItrthpyKpBEhdu1Tzx533qgZanIF2zBw4ffYYZYI,8238 +torch/include/ATen/miopen/Exceptions.h,sha256=Yicb0z4mTJD6FSfGhKUXELkeTYOXByxGC8fJX7NPCN8,1350 +torch/include/ATen/miopen/Handle.h,sha256=N79o8e6G7CH_Lno1cT_hWY6K_P6DhZwH3h0E-jF8-uw,443 +torch/include/ATen/miopen/Types.h,sha256=sP-Ig7kjm3eN6W_My-JSBEE1yRYpaOHwctYa7m-PMbQ,524 +torch/include/ATen/miopen/Utils.h,sha256=U17pahwfbSBWMSUnA2d--b1SeHbtRjrGTSGHHLuPUvU,655 +torch/include/ATen/miopen/miopen-wrapper.h,sha256=Y1cYYpIt-bcyZLNVSgjo2Ye1OsIKfzJHs4xFP6TPX3s,1050 +torch/include/ATen/mps/EmptyTensor.h,sha256=_fvSflyj38etC3e3sL1pWP2OsuDAEsY3AwaHlY1vd98,1009 +torch/include/ATen/mps/MPSAllocator.h,sha256=HJmVe5ri6FmhOcRBdxYOrljgCAdFqoIzHbJboHEdEkE,21904 +torch/include/ATen/mps/MPSAllocatorInterface.h,sha256=pBcudmykQXs3dZQR5g8uFNSXpOxOinRG0f6gIaT9bGc,4118 +torch/include/ATen/mps/MPSDevice.h,sha256=vgygMwLIRudzY8QN5GWCqKcFt25jNfkgY08DQQ6th20,2701 +torch/include/ATen/mps/MPSEvent.h,sha256=dtNUJogYAMLEbWIm0Ek-pKHfA-N1xbzBwjbS3L7HRUo,3822 +torch/include/ATen/mps/MPSGeneratorImpl.h,sha256=Moeo7-MXtLeO1d3JsIOKcittj89_V1Xnk7q7Re5FHTo,1816 +torch/include/ATen/mps/MPSGuardImpl.h,sha256=JaSzogVHKQkpGBT1ZYBewAXOZ0XX75yrC9oQwWzZg0o,6355 +torch/include/ATen/mps/MPSHooks.h,sha256=s3vy_DsewdTcny3MMsP1buKqvEKwo6knlbYINZbwzT4,2664 +torch/include/ATen/mps/MPSProfiler.h,sha256=T0MqEaNYT2dGyShIpo-MUJ7ubxhAxINMnMxumj5lrAs,16855 +torch/include/ATen/mps/MPSStream.h,sha256=KSclVddB71MufGFm72IflCxoVO7IQzpvwTJq6qNGWoU,6044 +torch/include/ATen/native/Activation.h,sha256=5jUBzS9MrhXbg9i0cc0yWS_mG0CTYOd8FyELEqpSj9E,3769 +torch/include/ATen/native/AdaptivePooling.h,sha256=gbGBydyKyO833hfzVuf6O09uJrEPEAuNVLALm1GHfvg,2682 +torch/include/ATen/native/AmpKernels.h,sha256=NF0ckllzP6u0cuybr-a7mHBEF7iRAmdq8OtuMoomSiE,871 +torch/include/ATen/native/BatchLinearAlgebra.h,sha256=vc3DbmSXZkrkr9QfLaYUnNiENr_wLyJwzovyqaga8c0,10509 +torch/include/ATen/native/BinaryOps.h,sha256=pch_FacbYCtY8lcJWlA8r8V5DdDFH4g3PSoijpzJ0Ms,6376 +torch/include/ATen/native/BucketizationUtils.h,sha256=DNCdyntNrq3f8qbdWbcjYJEERDuBIKUeWpIlKNryyjg,8036 +torch/include/ATen/native/CPUBlas.h,sha256=JzMm7HtekP9q4HPAnv3A22UJ_0COj2O1MD97o4rxAWQ,9747 +torch/include/ATen/native/CPUFallback.h,sha256=db7ZH0Xvlxq2yFGBkdYqp-6uKZ2cKfT45H-7KklaGs0,2667 +torch/include/ATen/native/CanUse32BitIndexMath.h,sha256=8u7Fm_XJ5AqSN_h2G2jxyAlYtpxGDNR-Hdufhwu5p54,496 +torch/include/ATen/native/ComplexHelper.h,sha256=PCu5VSO3tP_NiKQ2r3WAWVnfPDxlI8JRVp2EdcijzzM,4577 +torch/include/ATen/native/CompositeRandomAccessor.h,sha256=-jQf0lb1feMo8S_HqBbpp2jY3y8ORmKNjNnT2syptUo,1130 +torch/include/ATen/native/CompositeRandomAccessorCommon.h,sha256=7edXzVXw7rpfekC5_PRaCIzexfRYEJxUm8WXUZBsmlE,6987 +torch/include/ATen/native/ConvUtils.h,sha256=riAQabSfmYMub4O_qdoQfzpwgKgHmh8oGaIokKIEDuA,19448 +torch/include/ATen/native/ConvolutionMM3d.h,sha256=G0D6p90oXpyeb2mhp_fovuRaIBWX37n6jN6q0Nxc8Ao,594 +torch/include/ATen/native/Copy.h,sha256=9mJ--HBtsJ4-gjBbG2uMgjHNN8_cOL3fEFkL-kSCQtQ,626 +torch/include/ATen/native/Cross.h,sha256=7yIZE8n6_-zcjM494HQmI2n7v7ncpJIbqx_-yzpc-gs,513 +torch/include/ATen/native/DilatedConvolutionUtils.h,sha256=_G7n9nC9fWtUw0lz4Auekj0lYLtSiCDNE17uvD9m2JA,6678 +torch/include/ATen/native/DispatchStub.h,sha256=IYLVjJZ8JVFQIrnOBaJmH4CsKGhWZoxh2CgDE9lEZFY,16717 +torch/include/ATen/native/Distance.h,sha256=z1vYpapV_W6PyHABYumrYd57ggsR1gK7vBPlf89PzTk,974 +torch/include/ATen/native/DistributionTemplates.h,sha256=v_xOgQ4M6gJQ2M7r6K5XF0rTRlKhaxH1WNQO_8MEGq8,18862 +torch/include/ATen/native/Distributions.h,sha256=TR-DV17GwxTFnxwlq5CCj_MGqrmlDHBkbCtP3w7nezE,22869 +torch/include/ATen/native/EmbeddingBag.h,sha256=dlik8mXJIeXv57OzTxGs2DpWYg3CzfPs_xMRDFCp26Y,5482 +torch/include/ATen/native/Fill.h,sha256=4RBR3xh3iiYpk0SU93MXSVuh03u0PRpQNraXcU4T7UI,650 +torch/include/ATen/native/ForeachUtils.h,sha256=tXfuRRwAAxgJTxlD9okUR0TwLPZoujKPP4qydt45RFU,15021 +torch/include/ATen/native/FractionalMaxPooling.h,sha256=NIrym6OL5oKgXOuG-jWS5Hd-37hKOypZUbXOloWqz3Y,2415 +torch/include/ATen/native/FunctionOfAMatrixUtils.h,sha256=TBbECD73rwVVPvMePLeIxZhTyQJYTvLs7p2om2EkmMQ,642 +torch/include/ATen/native/FusedAdagrad.h,sha256=xYmXlb-ICVMYCI8EVdfZ6CgoD9AbVJSn_Zaz4Gg8V2k,749 +torch/include/ATen/native/FusedAdam.h,sha256=9f7Q9Gv9DbsLRwsnhxK5Evy8_DoFMmU_MuPEQAK9OVQ,937 +torch/include/ATen/native/FusedSGD.h,sha256=m_wkHWws_x4aplWRxIS-8nWyflrUGrGpJVMSqHMFLDA,770 +torch/include/ATen/native/Gelu.h,sha256=_xxqp_o3ocmwVdwYiyJ_Zr_Ak8fTqfRQmGr80GkUlAs,1097 +torch/include/ATen/native/GridSampler.h,sha256=RAbPa6nbPgTD-8qO-e3Dol64-8WiiNYFyqOYxvQB_s0,10661 +torch/include/ATen/native/GridSamplerUtils.h,sha256=64W52B_1J0L50vR72SI4tWhVPTyzh0vlKhZnH8BXuOg,5365 +torch/include/ATen/native/GroupedMMUtils.h,sha256=CjpYnkeB3F3MXgCYPp0gbOyDnDRr-a_UL-Scj9T3KIc,9329 +torch/include/ATen/native/Histogram.h,sha256=81LzK2uszgc5Hk35lUpf7Ocuibm6nmO7hSDZdOQZ-yk,999 +torch/include/ATen/native/IndexKernel.h,sha256=z0pBirBIRp3tNWAqtvFsYlTj0tuVQt-LQqLB3yBm09U,1957 +torch/include/ATen/native/IndexingUtils.h,sha256=fNQrRf0BE5DVmf1A7LXlpb9UHbB5jToM1YpuV60EEpI,6676 +torch/include/ATen/native/Lerp.h,sha256=dM_FRmp1GtU8hHyJzcsPhYAxi9SldMaWMQnPzvNyaB0,1715 +torch/include/ATen/native/LinearAlgebra.h,sha256=UzXQ5Os6eK8E_TU2EAJpUOHjVEVpmEw6hPP4lCY5BuM,553 +torch/include/ATen/native/LinearAlgebraUtils.h,sha256=k5um8omLdExad2wIuFvE4tVraBNS8plbaeWaFqeU8_M,26719 +torch/include/ATen/native/LossMulti.h,sha256=bE__nG_H1ux0ygwp8OfxzM6DWydfHPxSscPHZxYiahM,2526 +torch/include/ATen/native/Math.h,sha256=bFzMbP38MK0WU3KilPUfQ7I0A4UTH3dPyI6ruhJs2Zc,142384 +torch/include/ATen/native/MathBitFallThroughLists.h,sha256=wF-7X-wwE0mcv_fv-IAKfp7KuC7nBNH72lZY4Ciew0Q,3972 +torch/include/ATen/native/MathBitsFallback.h,sha256=qNxqOQoXjCyZ7FXrgAxb5HwhEigG_Gm13QQB7wLLSIo,7572 +torch/include/ATen/native/MaxPooling.h,sha256=9ArUuAHT2x-sECepMiaFZ2VvcQoTENfr6aGPCERXbpg,3522 +torch/include/ATen/native/NonEmptyUtils.h,sha256=OaBD1Vyz4PTpn3Us5BQ3MZ9A7xrFiRuxWs9e_kVBQGg,853 +torch/include/ATen/native/NonSymbolicBC.h,sha256=biHlvGKtt6Ui93Ju32MmURhSEc2npmkjX-7JGsxW6oI,3130 +torch/include/ATen/native/Normalization.h,sha256=AQ5IVOcofut6ZE2l9SedS-XVD9kxQK1qOzLud2HjNi0,807 +torch/include/ATen/native/Padding.h,sha256=KGtXh2yuMsGoD_cTGRnRkz-rRdcIwwxGJGSyLGDdKf4,2315 +torch/include/ATen/native/PixelShuffle.h,sha256=LtPpsV4uTDfmEDnDNL6vxDqV8gzFa8XtCQ5pYIf4g5o,2211 +torch/include/ATen/native/PointwiseOps.h,sha256=QcuNw-z_rvR3fz5fLw9U-w9Am-akjoCIefj5doVF9bA,1035 +torch/include/ATen/native/Pool.h,sha256=dDpnk55E3K_JNA8d0kxBuh3ryqwKfWMeJG5S0unw1LI,13464 +torch/include/ATen/native/Pow.h,sha256=HAOQzKdHYhaHKFgigE4SjB6svSZSNdldUkv1Z-5WGqk,1903 +torch/include/ATen/native/RNN.h,sha256=bCssHscFNjKGORjsXhD8PjR405E9_9KNz_jhXcCAOpM,3131 +torch/include/ATen/native/RangeFactories.h,sha256=GT82Hg0DPHlPWboZA-e2myfK4wyGHaBXcPWU4Wu3HLY,608 +torch/include/ATen/native/RangeUtils.h,sha256=iinz6DDBuOGfFe4qkux7GHAqpvijIVh_mJMQRuZy4E4,2647 +torch/include/ATen/native/ReduceAllOps.h,sha256=StNDQgM49wEdfdroZvpTcll7h0hrIkqb76U0lnya_kA,651 +torch/include/ATen/native/ReduceOps.h,sha256=H0Ifl1k2tQ1d2z2tEHloAmfyKO2GJgqqjse9qy8bEzs,2108 +torch/include/ATen/native/ReduceOpsUtils.h,sha256=P0peP1HcALV8jOhpYa1Qrx2kgxTv40DIxXxZlws9CwI,16956 +torch/include/ATen/native/ReductionType.h,sha256=-84o3NlrAKdzIHf2vu5wgDikNy9-UvowgkMs9XnZINY,1393 +torch/include/ATen/native/Repeat.h,sha256=9PL6zZm_uvP-NxX7LtnszNZnv-JTOSnJPoq8giA_I8o,1906 +torch/include/ATen/native/Resize.h,sha256=sF7z5efSc0ktI8MefQ8v3pLioU8Xqqxxp-yAlUiFod4,10597 +torch/include/ATen/native/ResizeCommon.h,sha256=0e-T7mECUl-eXNEvNEcKvRCZMYLHkC7_0ro5hoDI_Sw,1984 +torch/include/ATen/native/ScaledBlasUtils.h,sha256=PYJNOQWDYUmYtyyDX7Wb4hMcq59R-YWCXpB2T22Ap1M,6390 +torch/include/ATen/native/ScatterGatherChecks.h,sha256=jh1aGzDCQQvyGmo1BqMbi2PDujCYWLkgqqSWE7emjQE,3990 +torch/include/ATen/native/SegmentReduce.h,sha256=KHETESlR7O3jxUcHvj5CD4MjAwzM8VMNM-Wv8RHfqDM,1519 +torch/include/ATen/native/SharedReduceOps.h,sha256=daa62aPH9HVyq4Jk_WZIdpfip3u5-6Gw1VXZZ6rBi14,16470 +torch/include/ATen/native/SobolEngineOpsUtils.h,sha256=pNNPAQN0x0Br2jQHikIWd2xht9D0yGU8DUg_n7pQ6IA,2089 +torch/include/ATen/native/Sorting.h,sha256=YthtMuMvduf7oy_qqfjL3hbxZH9nNbbg4c91v2BF4aU,870 +torch/include/ATen/native/SortingUtils.h,sha256=bV3C_qbVQTfKY84nXQGcCDL3xUrzprsaviBKx3vf8r4,2926 +torch/include/ATen/native/SparseTensorUtils.h,sha256=HQVciWWBvDldwO7g-RSKPldE3uOujADedTbqVuK45aI,6754 +torch/include/ATen/native/SpectralOpsUtils.h,sha256=7kQ0W1LMCA3L7jPvtQW2xM3o511KNFtDbtxFC48pX4M,3547 +torch/include/ATen/native/StridedRandomAccessor.h,sha256=PZKVO993ozr5g9IsTE5FZlDwn4yjA3kXX5VAIAFU7zU,7089 +torch/include/ATen/native/TensorAdvancedIndexing.h,sha256=wUXDM_I6v7TYYKPzg-USJF6o4mA9WzILx1M7cFjLlG8,3151 +torch/include/ATen/native/TensorAdvancedIndexingUtils.h,sha256=2njbVRTKQU0frp955K0506yonI-ATyB8Cj6KK11pezY,3420 +torch/include/ATen/native/TensorCompare.h,sha256=xYZgiLO_WTB8nrPNBsDMsTsjR9akehbFLGZe8YTNGNw,1772 +torch/include/ATen/native/TensorConversions.h,sha256=0MeFKSwGxMwjeE7kPyHTMmVog1un0SCl5hv7akwlTJM,1092 +torch/include/ATen/native/TensorDimApply.h,sha256=xCVtk1TTObjwmO4cBByaHLS16i-phVragc01PCx5WwQ,2081 +torch/include/ATen/native/TensorFactories.h,sha256=XAZXzRjPxZrBpui6emUY-UVj_QRPCkPRVCI0tHVt1wU,5673 +torch/include/ATen/native/TensorIterator.h,sha256=EGjHBhlzhM9qtyOLFTPl9Cion2Tk55izMcG7hZMIaJk,300 +torch/include/ATen/native/TensorIteratorDynamicCasting.h,sha256=gfkNvB2B9s6IFHANJR0hLWUzORb24pCEVIJmbVoJhZY,2064 +torch/include/ATen/native/TensorProperties.h,sha256=BQlo_WTYnIIFSy6PQtwSmBOcdp4BTwhzvhRkAPn6JpA,452 +torch/include/ATen/native/TensorShape.h,sha256=94C3OMr9UObeXNtrNnn3OCqcI3AHdblYgPQcpSn3Kjw,4851 +torch/include/ATen/native/TensorTransformations.h,sha256=cOkKfad87XienVW5PnqiQNCkdyQq-bSoIxo4t9BY35Q,1181 +torch/include/ATen/native/TopKImpl.h,sha256=H_JLqHjMs4FlEbo0YJ1yRyJTQsaqYXQLUZF8jKeUB6s,3713 +torch/include/ATen/native/TransposeType.h,sha256=fdgHe1LZjUL7SyFS5UojXJVJaPXJ1Ffo-rmm6y-CsKc,935 +torch/include/ATen/native/TriangularOpsUtils.h,sha256=sGk-__VAdO7bFuSwPEnIEYnVPEzOiR8ynfOqljMF3Ws,2256 +torch/include/ATen/native/TunableOp.h,sha256=yPymXCt9yWgwWEt6eRSMhbXOk8U1psUOXKPDZWlTtZ0,1906 +torch/include/ATen/native/TypeProperties.h,sha256=MJATK6vHjuCCgS8N2wde2QxDYsG0YQM_VqN8nXeMVO4,912 +torch/include/ATen/native/UnaryOps.h,sha256=8Pu91eWMl8D5PSJRA7zVp8r2XbER_LMRpAKlJ68VbM4,5669 +torch/include/ATen/native/Unfold2d.h,sha256=r5hQGu1j7sNzIaZzrn0WybL9HOtXfnXM2lXTWXas81k,1233 +torch/include/ATen/native/Unfold3d.h,sha256=9H3NktUNEnXLlSDxJQ1MsFSp9E_Ea1Xq5QiJa-jqouU,1127 +torch/include/ATen/native/UnfoldBackward.h,sha256=53PYK7KVjOHfnnDd5s5idG9soaE5y4ql5qWYilyYjC8,3347 +torch/include/ATen/native/UpSample.h,sha256=rxH1KziXhpQy4w68wn_CQNQPtZIdiAA3juaF6-paxfc,19716 +torch/include/ATen/native/ao_sparse/quantized/cpu/fbgemm_utils.h,sha256=bn3kx0zdKPRUTi1ATGIOnylaPwbH33_pFPyd3qShkHU,3234 +torch/include/ATen/native/ao_sparse/quantized/cpu/packed_params.h,sha256=wUv3YyCo_WkTQfM6o5r8VidmyAUisf_WixBEfELkvJQ,2995 +torch/include/ATen/native/ao_sparse/quantized/cpu/qnnpack_utils.h,sha256=1rAzuMEU4AdDuEvherVtCc4hK8bMoNysZNH_4-71b94,3496 +torch/include/ATen/native/batch_norm.h,sha256=DMbmfhic-MpRaWOjcvtgds0yUN9MnY6jr6hhZn3BTIE,1679 +torch/include/ATen/native/cpu/AtomicAddFloat.h,sha256=qvIVxJ0kNCzUytCrDAK1xV8aiVHDKCTpb2835FwSqJ0,1304 +torch/include/ATen/native/cpu/CatKernel.h,sha256=xgya3MDFZuSx6GvrxfEYCwzjlqhjPgwzkK9wdPvf51U,560 +torch/include/ATen/native/cpu/ChannelShuffleKernel.h,sha256=_HVvj3sFQKRmPnsn2KYuwYIrzWqOZkHU06wnXVWsd90,540 +torch/include/ATen/native/cpu/CopyKernel.h,sha256=5RtfJ5tLE8jp2azBmsxJV0xCsexHxAzmne3Uc9Ly2zw,566 +torch/include/ATen/native/cpu/DepthwiseConvKernel.h,sha256=ogyYOVvDHyWg6ACz0jTZesJs07A5pyUXdWW08UrCZ5c,724 +torch/include/ATen/native/cpu/DistributionTemplates.h,sha256=bLuHzNQ9y-tf71I35Wo1b9rb3AbpZlfZkLjzdcbQJBU,15770 +torch/include/ATen/native/cpu/Elu.h,sha256=7hsZrAQh4SmgD_4eEv8E1Mkv5PkW1IkyCEXflgByRzM,3120 +torch/include/ATen/native/cpu/Gelu.h,sha256=gLK-AVzZIUwC_hPb5mXyomsuxNkbLljS_gMf8mmbkok,3358 +torch/include/ATen/native/cpu/GridSamplerKernel.h,sha256=NcAOuHU33S2mQT1pxM-o9MZJcvMacy43GQieH4YDfCI,1077 +torch/include/ATen/native/cpu/IndexKernelUtils.h,sha256=4fRSlrdlGwhXVwnDEB9ZHL4rMrNxC-95nUTMKMU4sbM,3952 +torch/include/ATen/native/cpu/Intrinsics.h,sha256=Is00ayXygoN_okRnxej4mDi0UCHphme37N7fVKmicvs,1466 +torch/include/ATen/native/cpu/IsContiguous.h,sha256=g8a8_i1hFP8Gu34DA9IC1TuSNYL54KsNeEiB1BctEAI,2623 +torch/include/ATen/native/cpu/LogAddExp.h,sha256=z2avx_FN6ANXdonid9GMF6JpwdevZ6SzCRQlynkANl4,2700 +torch/include/ATen/native/cpu/LogSoftmaxKernelImpl.h,sha256=6yR5jf2tWdYR03lf3-B0E7qr4mm5AlX10rBKORGK_tY,13404 +torch/include/ATen/native/cpu/Loops.h,sha256=JbAFu0_vDIzVA2irFOum9g6AHiPm83F2_W_OVfMvBDM,15402 +torch/include/ATen/native/cpu/MaxUnpoolKernel.h,sha256=gRdiFBOyWHNBjsDJclEudywwpCPhLOfMBYqKUaK6DK8,560 +torch/include/ATen/native/cpu/PixelShuffleKernel.h,sha256=gYm4HRFVMcBhRCObqeGH8mZWRfj0Yeha5YKZlyy5eoI,574 +torch/include/ATen/native/cpu/Reduce.h,sha256=9yhsH6l-lll7hyiWip9jnR0X8ZE8ZJJvjkhe1XDfhU8,12324 +torch/include/ATen/native/cpu/ReduceUtils.h,sha256=bT7DEvWx_0YHMvXhqVRN01YaQ8Lm9h4D7A8kKGdIjGI,8963 +torch/include/ATen/native/cpu/ReducedPrecisionFloatGemvFastPathKernel.h,sha256=vuSKm5PeIz56Ko3ctjEvg7Gm1Aqr0euypN-cqk_VYLc,1374 +torch/include/ATen/native/cpu/SampledAddmmKernel.h,sha256=hG9d1W8jvG-36slz4ApkeDEJrPu9n7o_5_9H9ba-X5s,576 +torch/include/ATen/native/cpu/SerialStackImpl.h,sha256=Sq8zzXe7u9c3o6sLY0VBHCNK92YORvU_GvbNt-NVKQA,5710 +torch/include/ATen/native/cpu/SoftmaxKernel.h,sha256=Ll2YpX52fims5NsYPrbT8ygfZp5wk7CwC9-7lGEYpTY,1189 +torch/include/ATen/native/cpu/SpmmReduceKernel.h,sha256=85iB6aCW_bH7v5iLwb_ofq6idbS-rkdktLx0lW5PNmg,1606 +torch/include/ATen/native/cpu/StackKernel.h,sha256=IaY88AYCdMcb0c3TWdpZVaGsTTqDOc4gDj3HDNFWr3E,562 +torch/include/ATen/native/cpu/UpSampleKernelAVXAntialias.h,sha256=LMvbkoyLh6gyLxT6J9IZvAMYuDRI67o1zc2HBbi-0sI,58404 +torch/include/ATen/native/cpu/UpSampleKernelNEONAntialias.h,sha256=o5Dl4ub0lPTXAxdt-F6VxAzg4QNa9p9jG6AQSdlUpVU,16309 +torch/include/ATen/native/cpu/WeightNormKernel.h,sha256=GzLqqFhn6W_bf0MRcBPOP8kl6qGCejNbdtWMytinYEc,804 +torch/include/ATen/native/cpu/avx_mathfun.h,sha256=5xPW_GSg4DSxPyz0s7nUgfy0qw6iqSUVTuEob-Um0Ho,17702 +torch/include/ATen/native/cpu/int_mm_kernel.h,sha256=VGOuXJXQ8zVU1GSBXkH-bFVrK-8TwjPuiBLxv9cocHA,1359 +torch/include/ATen/native/cpu/mixed_data_type.h,sha256=WAxkpUy7WJoR8cwYBENYWN_o5NicWAe6UaYq518p0AA,1662 +torch/include/ATen/native/cpu/moments_utils.h,sha256=AiVFmQj3IOdLTWgU5LYXNAQrPX2yL8jJ2YqIntESbf8,7162 +torch/include/ATen/native/cpu/utils.h,sha256=A0dq7dHUPvH9NwdZnFO5buqJbzpCMkVuG40rm8n8ZKM,7770 +torch/include/ATen/native/cpu/zmath.h,sha256=pXuvamS1M8HhO81LfeVy9zLi9-X4VniQadUpAHYCoMg,6876 +torch/include/ATen/native/cuda/Activation.h,sha256=os9YOpv6tVDWxq8FsjvMEf_ip-aj-g-6XZXK7XSWb7c,790 +torch/include/ATen/native/cuda/BinaryInternal.h,sha256=3c2TDjMEUA7aOoj_LHQM17CHB49TN7ajr13BPlLU6yU,1441 +torch/include/ATen/native/cuda/CUDAJitLoops.cuh,sha256=UHtIF3HcMsFINgAfPY1HwhhMNDaxgxGUmHzRShDVz2k,12131 +torch/include/ATen/native/cuda/CUDALoops.cuh,sha256=E5d0aorsgLUKJiN_N_aXbWXYIm173AAhX-3G4_UHCy4,43175 +torch/include/ATen/native/cuda/CompositeRandomAccessor.h,sha256=ufMChPnW_wYVMaUT6MmtLvu_oX96wCMdXDyeGNGY0ms,1201 +torch/include/ATen/native/cuda/Copy.h,sha256=mcsIfjzE4YvB0opzHQzwysrCdlasG9f5PeZ4OVCIp4M,408 +torch/include/ATen/native/cuda/CuFFTPlanCache.h,sha256=2LtgY4nEnsvlXxA1lRgxQEiZ7euNwm0vdwBLskz1R00,19527 +torch/include/ATen/native/cuda/CuFFTUtils.h,sha256=OtYLhOADaUTan2QZS-K4TM0TfdBk8iIMIXnJL94GDVs,2207 +torch/include/ATen/native/cuda/CublasGroupedArgs.h,sha256=gaR6AEiieG8oIEumXApX0TLVGSp8De4pyKlvSuZL4Ug,1463 +torch/include/ATen/native/cuda/DeviceAddCmulCdiv.cuh,sha256=y_1B3yB1E43ZzHIWZiMK_d46CAavOcOoK_HBAs8Mscg,1282 +torch/include/ATen/native/cuda/DeviceSqrt.cuh,sha256=LXvb7RnB_WDeLmmRDAlc5y-I6bWJg_YBv5wxn1e6Qv4,839 +torch/include/ATen/native/cuda/DistributionTemplates.h,sha256=1VQCK26LYYgMoCx7Vy2G7yZqZJygRMZhOEuJvFm8nHg,29502 +torch/include/ATen/native/cuda/Distributions.h,sha256=sWc_6Qaj8BXxIjWCfmi7rsdLwvAq5jx1vicAqE6KXeA,895 +torch/include/ATen/native/cuda/EmbeddingBackwardKernel.cuh,sha256=TUm8dx58lh7P86KCI_wfliCtu8DKm4ybcAu9540NcpA,809 +torch/include/ATen/native/cuda/ForeachFunctors.cuh,sha256=4FHSnFIbdbBXjOQYwSquUhibdIQXhpms6YMW7z206f8,30310 +torch/include/ATen/native/cuda/ForeachMinMaxFunctors.cuh,sha256=-qBpnBW-iMbqxIWPIsXk2bEUwH91DV3vtUTVui8fzKw,680 +torch/include/ATen/native/cuda/GridSampler.cuh,sha256=wiPXUzbFGiQXF60jGAlqigEYMwrNEreGvVrlqC88a68,11229 +torch/include/ATen/native/cuda/GridSampler.h,sha256=P0YJuHG5fCMvbqJvHEYP4K8bn4i_vOvJ1NEDHwUNjxQ,1399 +torch/include/ATen/native/cuda/GroupMM.h,sha256=-L4d4RsZiACoeXzFuHkQFmvaxi8PuNx3OlILtXY-Sfo,581 +torch/include/ATen/native/cuda/GroupMMCommon.cuh,sha256=_mQeCqW2nyRjPOlompxxJKxN5wyh8WJWUhfJFRTO530,6706 +torch/include/ATen/native/cuda/IndexKernel.h,sha256=aotVt_oAfWzDL5AjtcEfCVp2lHop4KzwtQSR3SoXXvE,592 +torch/include/ATen/native/cuda/IndexKernelUtils.h,sha256=-0jrRP5sruHDsqcyxnS1Jo2tBg3XVRgXTchfFL9EEI0,3929 +torch/include/ATen/native/cuda/JitLoops.cuh,sha256=PT5ek97JOjp45YfLpfHxZz0fGwzRPb6JUqirw-a5kXQ,7161 +torch/include/ATen/native/cuda/KernelUtils.cuh,sha256=YQJQGQWoPDBvgkbHSZHA58EfJ7fQOtb5GCAELmdz9Ko,9180 +torch/include/ATen/native/cuda/LaunchUtils.h,sha256=Pbewby1CzWNCP8etqYoWS9pNYmeRrIPILujKxTywS3Y,536 +torch/include/ATen/native/cuda/Loops.cuh,sha256=FZR4RYhNe20cHnC0OQCIujb4-J2iqOhp0tNbCU5DUEU,12338 +torch/include/ATen/native/cuda/Math.cuh,sha256=6QPttyTylBy7RsAdnNwr0nirE5r4gYP5GTgWJAoflkI,123396 +torch/include/ATen/native/cuda/MemoryAccess.cuh,sha256=zXqgw4HeHjQEqPZvM9xjLAt-FyMmk4U0jb9mtn413u0,23011 +torch/include/ATen/native/cuda/MiscUtils.h,sha256=L73h_i3i-iP9aoPPfLP1PUSmpBsTQ6ED4GiBboqkVI0,1188 +torch/include/ATen/native/cuda/MultiTensorApply.cuh,sha256=lHleqHebCzystj6rcpTEMODTxQbkso_uG7WhnzAmae4,16521 +torch/include/ATen/native/cuda/Normalization.cuh,sha256=etVSd2Cmbs_7vl4vWz-mwStQ6jCRGuy5Ryip1xsMexU,76559 +torch/include/ATen/native/cuda/PersistentSoftmax.cuh,sha256=EhsgmYCq12SDIcKNB6Y7QcNjPqkL2NoQR6ZyoC-OjGY,20510 +torch/include/ATen/native/cuda/Pow.cuh,sha256=OQysVDoNrRMJqiCd-d457gjAyrDY3xjgNdAQh_Vo0RI,2408 +torch/include/ATen/native/cuda/Randperm.cuh,sha256=rMZPMF3X_t5foRCbZIjUNg7qKDxmEDtN1BBPyc8mQ-I,2362 +torch/include/ATen/native/cuda/Reduce.cuh,sha256=j44-h_P3UU2F4YUV-yFpjHgMGx0fWwPvEoioIlxVbZc,50232 +torch/include/ATen/native/cuda/ReduceOps.h,sha256=1S_nThLRx9CAF-TatBDunTqEal1ciIepo525hWzBDcU,803 +torch/include/ATen/native/cuda/Resize.h,sha256=O-FgvtF7z8UvWHqjW-VXJ89Mul9yNGKrhAJT1Qp_KTE,1917 +torch/include/ATen/native/cuda/RowwiseScaledMM.h,sha256=w1t47IiYnTc9w2lGdhWRA4Kg-TIaCKBaE0Y0rjmMl1w,623 +torch/include/ATen/native/cuda/ScaledBlasDeviceUtils.h,sha256=FzTDsWQM5jfa-S349dG0JKVl-VXd4xdPuu00TmMHGro,774 +torch/include/ATen/native/cuda/ScaledGroupMM.h,sha256=Ig4NQervFHI5rwjR6e8VZeYhz7lIr5WrEWx0uKwSNWg,668 +torch/include/ATen/native/cuda/ScanKernels.h,sha256=vFFvo1hDdUGcZ6pBJSMPuMq3d3HSvyESdQep7KOmWxU,1033 +torch/include/ATen/native/cuda/ScanUtils.cuh,sha256=fkhVq4I3tBdnxlEuXIknhd2R2Mv_BqosrchrXwHH-XQ,21642 +torch/include/ATen/native/cuda/Sort.h,sha256=Ak6nIQWuEAAmsUVIIvp7XEa8-pDKNOPBe8lY9g8J-c0,655 +torch/include/ATen/native/cuda/SortStable.h,sha256=0bVzhFzFllv-yHxlYiIrJiUMB1vkAGkuchYwUOOfI1c,693 +torch/include/ATen/native/cuda/SortUtils.cuh,sha256=oLubrKxYmHt2NSHYD6qGyn4wBi4pgEJMNbFGJBFLJsc,13465 +torch/include/ATen/native/cuda/Sorting.h,sha256=CWfKEDadWdjAy-osIW9yRNCPtpm0ifR9V0Mfy2kTrf4,650 +torch/include/ATen/native/cuda/SortingCommon.cuh,sha256=7mvhis3CPtIu6_tyCiyi_In6u-ozg-AwKWmq6Aj86HM,5710 +torch/include/ATen/native/cuda/SortingRadixSelect.cuh,sha256=1L5423YEJ4xdoe9nCPgXJrfY-scTdQ5BVZNZyi57Wb0,42421 +torch/include/ATen/native/cuda/TensorModeKernel.cuh,sha256=TLm-0Mxr3GZ2ktHf8kK8JapE0nmU0JrlLfXUeLYlpQc,14683 +torch/include/ATen/native/cuda/TensorModeKernel.h,sha256=xxQTk4ZtcEQG4EA6jVkigxUAFeL5rAgBVFgjm6vBW9g,673 +torch/include/ATen/native/cuda/TensorTopK.h,sha256=Yz2XLDh4W77eya4wUV70dJ3IqTm-r2PbN_oTOK4O67c,508 +torch/include/ATen/native/cuda/UniqueCub.cuh,sha256=5UcInlJD8-4H0pDNDw7XBTR2Lgcsf24rKZ-4p2R8VAQ,556 +torch/include/ATen/native/cuda/UpSample.cuh,sha256=ilf5bsh3nfgd421zzMPS77zv8yrCYkb3A5G_S317VXw,11892 +torch/include/ATen/native/cuda/block_reduce.cuh,sha256=rcTxhFDkP28XZafyxQfGWqHIgRecsCtHQZFA_ss4ye0,4733 +torch/include/ATen/native/cuda/cuBlasCommonArgs.h,sha256=eTaQRfMTPe7bdAnJ7ddHKXwkFbqMRtBc2He29qd2CXM,7119 +torch/include/ATen/native/cuda/cutlass_common.cuh,sha256=hVn6wIrFmMVY_DwRvPdNKpLe82ss50Do8p99w_DVXbA,1531 +torch/include/ATen/native/cuda/fused_adagrad_impl.cuh,sha256=LbnP4NqPrpXCPup_huZIMvHz-_fZt_Mgktil69vpySg,1099 +torch/include/ATen/native/cuda/fused_adagrad_utils.cuh,sha256=_GIkuYrr76j0vaT90n3b5UANfPWKtVVxjtAOO9Tbwjk,4476 +torch/include/ATen/native/cuda/fused_adam_amsgrad_impl.cuh,sha256=wnDK1DTBn9kwV3Kzybo0t9b_WEFhxg806saEN3T3wLE,1283 +torch/include/ATen/native/cuda/fused_adam_impl.cuh,sha256=33CbBaJsUWSO9nO5mvJN9XhD0sngVwemzdueL_2AQ9g,1195 +torch/include/ATen/native/cuda/fused_adam_utils.cuh,sha256=uYaphOgnWTSHuIFKdWqVSPGgwv_LvsJlswpdkFHiJeQ,19839 +torch/include/ATen/native/cuda/fused_adamw_amsgrad_impl.cuh,sha256=y00SBNCAsVlsZ1yNMvoxQVfIJyDRr0j_oK_QeKrwBK4,1285 +torch/include/ATen/native/cuda/fused_adamw_impl.cuh,sha256=NEimgkgX2RGXMO_KGfGCQ37GPrHi7NXdGeSbp-4dtLU,1197 +torch/include/ATen/native/cuda/im2col.cuh,sha256=GK-g822eCAPDyguDVMb6RIxm2jzAmbTi0d7Loj5Z_h8,9954 +torch/include/ATen/native/cuda/jit_utils.h,sha256=PvAjAx-If359TM5RqhSCdABY5Iw8tTKAYyc2BNzbGxY,7528 +torch/include/ATen/native/cuda/reduction_template.cuh,sha256=Avmacx-MWoH4rTs6AhArXYKCDHri0NbHqD8eMiIXdiE,24927 +torch/include/ATen/native/cuda/thread_constants.h,sha256=YeD3M6Aacp-WA2zYS3hkVzHRJlNPPsyXKj6R08N0FtI,914 +torch/include/ATen/native/cuda/thrust_compat.h,sha256=ygO4i_8ZDQQoJdaJTVpfNzcYuvBhr0db1tEIi6MjgUs,506 +torch/include/ATen/native/cuda/vol2col.cuh,sha256=Pm5y-TyCSSlUZCkom13iE85Efr9V141hhYcshxE3JBo,8347 +torch/include/ATen/native/group_norm.h,sha256=3u_A32TeaFVatZXYQChtc-98oSaaBZBC_m253cOhEYI,1159 +torch/include/ATen/native/hip/bgemm_kernels/bgemm_kernel_collection.h,sha256=3QNiGsAXKaS5wl9jlOUdp43uqc7ejrc2Fa4B0imnqfg,3708 +torch/include/ATen/native/hip/bgemm_kernels/bgemm_kernel_template.h,sha256=QTcgcIQ40ciKvIZjhBBXhyV_79qOTwuIYa0YRJR4rxs,6209 +torch/include/ATen/native/hip/ck_bgemm.h,sha256=2YM3vQrL0cznzCtrLD8jdyj1YfvbkZzWL4rKOIQm0sg,699 +torch/include/ATen/native/hip/ck_gemm.h,sha256=j5WmuO-ZeBqgGgdwMbXwZ7lgDhuPsw5zRGgQWzlHMSg,933 +torch/include/ATen/native/hip/ck_gemm_template.h,sha256=YyYzwlQJiv5OVoe95orPVCNOiXHVnRdljK4YRbHnEv8,15848 +torch/include/ATen/native/hip/ck_group_gemm.h,sha256=zdAmCdcA5YFBDElcsRJuh5RtKnW8vfOxFOcwzH_4vYM,643 +torch/include/ATen/native/hip/ck_types.h,sha256=afMlwkSm6I1DhOS6v5jDSwOal7C1g0Zl73nNmeiajew,1849 +torch/include/ATen/native/im2col.h,sha256=fMatUfeOB6WmPopF-fxFy_dATyP8C43su7DJaqveaXs,5491 +torch/include/ATen/native/im2col_shape_check.h,sha256=fAE2s3ZdUW2IDQWs3PuPFRtzDjv7RNwpR5PPRqDaFNU,7534 +torch/include/ATen/native/kleidiai/kai_kernels.h,sha256=_bbIJKjF-_rBeWJPMTBXV4TylwpVPt1MwEEynm3V_gg,1346 +torch/include/ATen/native/kleidiai/kai_pack.h,sha256=E0TBj6rTEgHrU0NmDCmnLcbO6G2T5XpgC_4kf8dk_qQ,3027 +torch/include/ATen/native/kleidiai/kai_ukernel_interface.h,sha256=Pnj6ZOTnfrEbIvx2Q2epTrWwqimzaUbVqgYZR35Ib5A,8379 +torch/include/ATen/native/layer_norm.h,sha256=CrOkKpzDCC-refWI5yOhnly5Xg37NjvIU2wdsn-jo1g,4885 +torch/include/ATen/native/mps/Copy.h,sha256=D73DIsU2U-2U63Tmnr4aJ4lawV_5cwbbz4rCS9NockU,931 +torch/include/ATen/native/mps/MPSGraphSequoiaOps.h,sha256=UVYxYmeX6OIZ7hr_bldow7_rzbQesuMgJEZmMZrGXQM,2345 +torch/include/ATen/native/mps/MetalShaderLibrary.h,sha256=2Txlgpy3nbVTYP9O9yJX0VSjDSLk_ux7loR4fFhs8mM,9978 +torch/include/ATen/native/mps/OperationUtils.h,sha256=fz9oZ5gL6Hr4nTZUpOL7gzBK9WtTMzHOfdbb127Ptq0,34495 +torch/include/ATen/native/mps/TensorFactory.h,sha256=8h9YbcxYmei_ZpCZo2km9xCxUsI8c-07wSqyerPFXmk,1258 +torch/include/ATen/native/mps/kernels/Activation.h,sha256=leCfxgI79PkwRDayn8hE4PkfBPRxajfRZ1KrAU-OKDE,461 +torch/include/ATen/native/mps/kernels/Convolution.h,sha256=hsclifStIFV3Hb1S2Rf-V8ylTQf0CB8dWB3mZ-3BmEc,940 +torch/include/ATen/native/mps/kernels/Copy.h,sha256=LsVCZ7cJ_GD7vEaJ8a4q2oipgde_wflZ_2tbPsvTi40,904 +torch/include/ATen/native/mps/kernels/DecodeAttention.h,sha256=ddQLKEmFZ2yn5EMqViySA8jrHLg4JPvMVTfCm0SFbbk,22873 +torch/include/ATen/native/mps/kernels/Distance.h,sha256=I3IIocNDWGhq9va2AxjIbdLbN2zWrjFz4WGxjHVPvjY,354 +torch/include/ATen/native/mps/kernels/Embedding.h,sha256=x2H8Rljij0jrytQXUskrjwSbcDlWC1u7PNv7Sk0haCA,741 +torch/include/ATen/native/mps/kernels/EmbeddingBag.h,sha256=iqVw27waBNcFgZq8_q5Wo0JSc0sq6kzF0D1MqAf40UM,1622 +torch/include/ATen/native/mps/kernels/Gemv.h,sha256=EZ1AuXTvsHlPt5mfLUd7Mj4oggVYVmz_FQVBamRIXrI,22495 +torch/include/ATen/native/mps/kernels/GridSampler.h,sha256=6b7zNTvtwTRO77pD65-r0ZOCQFW8nTfu8hVlA0fSKxo,3546 +torch/include/ATen/native/mps/kernels/GroupNorm.h,sha256=CzBeKK3TWx-3JRHEJWn4FfRNkjAVN435O4DJc3JEPuo,693 +torch/include/ATen/native/mps/kernels/Indexing.h,sha256=oFWBASP-OlYKE4vtd7DHFoyZj1GcNM26GVUuzNxKDjA,835 +torch/include/ATen/native/mps/kernels/LinearAlgebra.h,sha256=F4OHOLoT4_X-ER5Ocb8oqf9QkPWacbio7J_d-LysGZg,2168 +torch/include/ATen/native/mps/kernels/LossOps.h,sha256=U96aBY0A13PWV9pR7tfmwi2vBXT8lKL2-O0v-Pqjhgg,1232 +torch/include/ATen/native/mps/kernels/MppAttention.h,sha256=AQ40xLw3dFeYTSu-pKrMzRBiADp1WLnDucYnQdcrf8g,34775 +torch/include/ATen/native/mps/kernels/Pooling.h,sha256=5Jq00L8ud0vaXndGG6i-HYUSMRgGf2S6MG36SHgJH5I,2603 +torch/include/ATen/native/mps/kernels/PrefillAttention.h,sha256=KqnXQoU3FUIcu9l3vBiqpPih4ZlcfpGf6cj-dQCrtjc,34417 +torch/include/ATen/native/mps/kernels/ReduceOps.h,sha256=q6cacm2fGBbmk1HsnD5sKKx4Z2Nx-tVxsrS2sOttvDs,3332 +torch/include/ATen/native/mps/kernels/SamplingHelpers.h,sha256=3ne2EzzkM7GbJBWvfxTl6eZsG1UyXXV8h7DpykdtG34,1519 +torch/include/ATen/native/mps/kernels/Shape.h,sha256=a7AyZzapWbkD_liMf400jvYyJLDr8UKP57DRUv0whsA,811 +torch/include/ATen/native/mps/kernels/SortMerge.h,sha256=YizspMEfxPMrMkaxpzD3gLU4xrSFcq8HQbQ690dDAPo,24892 +torch/include/ATen/native/mps/kernels/SortRadix.h,sha256=IGs0b_6Gc2DHMI_iR0lsP1s4p3tMfA2_IWP7kInZvqU,24659 +torch/include/ATen/native/mps/kernels/SortTopK.h,sha256=aRgXGlpVlLKhzsxoQAaj09Q38dVsB_4InT8t75qanuY,20096 +torch/include/ATen/native/mps/kernels/TensorCompare.h,sha256=aSdaemSF2GiRF_7CALJZ4yktIgof63-Tah6zLnI_lV4,338 +torch/include/ATen/native/mps/kernels/UnaryKernel.h,sha256=4T2h9h9RtMfmMcxmzWtCKOWjUazXW-0urJ2KOISSK4w,603 +torch/include/ATen/native/mps/kernels/UpSample.h,sha256=uuv_dIPQcQhn4FJYkZxb7NLxCfh8-G8VoTkJZxFkSxk,1912 +torch/include/ATen/native/mps/operations/BinaryKernel.h,sha256=Ek5fMGOxQ3_wtcTk5xOBsJO4GCJJanbdHMcGzF0mkpM,514 +torch/include/ATen/native/mps/operations/ConvolutionHeuristics.h,sha256=VRh89q331Jrk46_KEcHu3vlIJLHuznT6lnXsXV43xaw,1351 +torch/include/ATen/native/mps/operations/FusedAdamAmsgradKernelImpl.h,sha256=G1xwWT0LLYyUs8aHXn7Up8sxahjir4DgGsyHqaRIXLo,1235 +torch/include/ATen/native/mps/operations/FusedAdamKernelImpl.h,sha256=OkmiF5mPsfFZToRmusrwik-P_lyvo49HskPCRq28hYM,1142 +torch/include/ATen/native/mps/operations/FusedAdamWAmsgradKernelImpl.h,sha256=Ho9opeG56HSH8yC8Hb7-wWYH9kW402dQI4NR5CeEPcI,1224 +torch/include/ATen/native/mps/operations/FusedAdamWKernelImpl.h,sha256=xXf1MVaDz2m_RUB6EsuEEYWwfWaV6Eev_cgKOdc_iCs,1145 +torch/include/ATen/native/mps/operations/GemmHeuristics.h,sha256=_IbpPyONvEBdJDxadqCya0DAnTcdj7nEPy1cs8jdWDE,2223 +torch/include/ATen/native/mps/operations/MultiTensorApply.h,sha256=C1X0CZs8erhYtI8wTpAVSTsFwdHKgdJ-4JfHw-SGCV8,17550 +torch/include/ATen/native/mps/operations/ScanKernel.h,sha256=5yN_lLVWwor6jk1Cx8ey-zQUkIFvdExF_pn3EIunWfg,456 +torch/include/ATen/native/nested/NestedTensorBinaryOps.h,sha256=NMoLtp9nf45FWGIvt451kQdx1lHmfiNRh0AtEdxEa6E,667 +torch/include/ATen/native/nested/NestedTensorMath.h,sha256=bQj336uDnNYyflProhEgl8eh2FVEPAZFBUIQG9k4uo4,2972 +torch/include/ATen/native/nested/NestedTensorTransformerFunctions.h,sha256=jqxQedHZbscjF87H0t7lcr1PWgFHD5VGOa6JcUAkB8w,3092 +torch/include/ATen/native/nested/NestedTensorTransformerUtils.h,sha256=a4vfhIgp242JzWWPVW4U4ctPGPwgSdO27Rgu8pGveYE,1652 +torch/include/ATen/native/nested/NestedTensorUtils.h,sha256=e4lUQ36ETnpdCOcxROjagsADIii2gQtqdlBbVifMhYk,15961 +torch/include/ATen/native/quantized/AffineQuantizer.h,sha256=4HhLJpNCAXkWvnW09Alk4_QCBa1igqV4X66QyNk54Us,3969 +torch/include/ATen/native/quantized/AffineQuantizerBase.h,sha256=UDX0a_eLF_a2JDVrSf-Y-VGgEk8-Ne25Z2KqmPBUl3o,1747 +torch/include/ATen/native/quantized/ConvUtils.h,sha256=8F1-pAtLWECGODsMOQGp8WcmeEns8ZxwuIO9Ilfvuss,2494 +torch/include/ATen/native/quantized/Copy.h,sha256=P3SjvRGc1TR2-lQ1TmGd0l1BzlB1NVEzm6C8LrtMXWA,410 +torch/include/ATen/native/quantized/FakeQuantAffine.h,sha256=mneUnXSFk6uTqtr8vDp8u0ARXM_qCoM2Cq0PLqe2iiI,2041 +torch/include/ATen/native/quantized/IndexKernel.h,sha256=7n0KvKky8K1dARuMLS0LrxMVfmXepTQ6qzT1VEvcdnE,834 +torch/include/ATen/native/quantized/PackedParams.h,sha256=TjRb8G6SvN_lDqEh3Gjf-lAbtJ1hmNYWJ_tWWC02g9A,4855 +torch/include/ATen/native/quantized/cpu/ACLUtils.h,sha256=gP4f8Vojx_EBJBcJ2-yjmZXegLGxJ9wYtwKpPEHxmpY,8141 +torch/include/ATen/native/quantized/cpu/BinaryOps.h,sha256=OvT3b3V7CcNXnB6iZp-GK8tT7eR9VKBiGsZ4wQSjTEI,422 +torch/include/ATen/native/quantized/cpu/EmbeddingPackedParams.h,sha256=9StMsjybpzchN6Uo0DqF4Tq7TTuQhGUDSrvmN4IR_nc,1175 +torch/include/ATen/native/quantized/cpu/OnednnUtils.h,sha256=B5IgL1L1HacqhHCUp7AelbYNPm3hOIiF7VlpWTCLUbU,16639 +torch/include/ATen/native/quantized/cpu/QnnpackUtils.h,sha256=6-_MzYedvy4fX_rBE2czxN0kdlU-3BU1yS5UpImo9yg,17681 +torch/include/ATen/native/quantized/cpu/QuantUtils.h,sha256=VhfzhjikpIX2xI4lXZEZuz68wXJqm1XWNqaaM1t_9Zg,8485 +torch/include/ATen/native/quantized/cpu/QuantizedOps.h,sha256=UFaInkdktyPSpCbbcxkmfhca2B1jxF0baSx9XZtDxQY,8864 +torch/include/ATen/native/quantized/cpu/RuyUtils.h,sha256=F7tDQoOD_kZeAHhjbQA1BuluvmbT2brbp5J7XAKYuOE,592 +torch/include/ATen/native/quantized/cpu/XnnpackUtils.h,sha256=SVBKgQeWmXRdXT2bqu3eO55rnc2LXF277HmXJoUbcWs,14618 +torch/include/ATen/native/quantized/cpu/conv_serialization.h,sha256=u33Rn54djfJ0l1E7Hi8PFsxpiRGNwoXSGr9Bz26Rszk,13142 +torch/include/ATen/native/quantized/cpu/fbgemm_utils.h,sha256=NqmpZpLfewpnwH7avgftbcP8nzmF9fLgUuEsKywqm4A,12278 +torch/include/ATen/native/quantized/cpu/init_qnnpack.h,sha256=-_t7Ge0F62TBT3YIrsEWds7bYYFjdtb-GCO0p1Xkb30,375 +torch/include/ATen/native/quantized/cpu/qconv.h,sha256=psStM1BQSlAj9alvXvxQtUVwl-Kp8hl1aU761QbAQwA,3817 +torch/include/ATen/native/quantized/cpu/qembeddingbag.h,sha256=IHc-UVtGXTW1ZOsCIAnCwUecwqtFYLzaafki8a7D5o0,1269 +torch/include/ATen/native/quantized/cpu/qembeddingbag_prepack.h,sha256=R7xEP6Xcg3gVU4ZqOMG3XWxr0kS5UE3i5lk6B4woLs0,626 +torch/include/ATen/native/quantized/cpu/qlinear.h,sha256=PQjCI3nUlNdhDs2gr8HSk_kUJO8iziAM-nRgpPvDTcw,1936 +torch/include/ATen/native/quantized/cudnn/utils.h,sha256=qrdJrTM4Dq5k1j6gbRYS8yfUaghFasD6VOdu0JMLHho,10732 +torch/include/ATen/native/quantized/library.h,sha256=68goeCvNPxaYgPVXKxldAUpXQVdtObbGtl50lJwqDZ8,443 +torch/include/ATen/native/transformers/attention.h,sha256=M9kUVQO91aN83n5pJWaHRc0JgxK7eseS6vV58nwiOFI,2520 +torch/include/ATen/native/transformers/cuda/flash_attn/flash_api.h,sha256=yAGiTLq2M_7h34TFs3zDdZXh5yyywXofluydaVqa2Bc,5643 +torch/include/ATen/native/transformers/cuda/flash_attn/static_switch.h,sha256=oh3hsokaOuamc3t3wnjbWVaw-3jMwU7FdizCHDw2hFQ,4021 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/debug_utils.h,sha256=hxFI0_GO_WCTXvNcbXDw6JLd1ZdRV7SczH8B4x7mt_8,10508 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/epilogue/epilogue_pipelined.h,sha256=oBygv63GlhEVVSGPJX_SA6ClKGdnjg9tKPLD0wRlirw,22541 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/epilogue/epilogue_rescale_output.h,sha256=aaF13g1a-GpjSSnkWlGSmbdyi6I3OCVoiREPLEEn_Vc,8036 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/epilogue/epilogue_thread_apply_logsumexp.h,sha256=EiwYb10Y3xRNcSyJYe7B5F8e5fq9JJKkBfMAiNesjrY,6233 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma.h,sha256=ODUdD2YzVUUDgp0bUyIW6a7IfKJ5xBrX8VGgiTzD-t8,2745 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma_base.h,sha256=CZnj6_RVJOuf0L2qqjhBg3610A4ZOsqpTnsu6TlVEHo,6495 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma_multistage.h,sha256=_kvJ_lQvprby69IWo9YgYtlqIM02u95wg-FACAZWqjY,27535 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/custom_mma_pipelined.h,sha256=j0leQxb_tkfXkUy6nmpGo4Un_j2W9iIvXe9a2BHmgcI,14399 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/find_default_mma.h,sha256=u2YDMC6WhwawOznVd-hUHEz87Tbn_vxTdcYztSPmnvk,5430 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/mma_accum_lambda_iterator.h,sha256=Yl5F-XCv26rf4XfSVXcEwAiqBbGMXGYHlvMkb-3AuvE,12604 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm/mma_from_smem.h,sha256=MQKS3DmL_g3dyCKrwyx-N_vHb9c5vRau2pR9YGF-ew8,69054 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/gemm_kernel_utils.h,sha256=wn2ztO-edcilD3LtE2p1Y5hTRrk34T5iXyZXGtAwJvE,9609 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/iterators/default_warp_iterator_from_smem.h,sha256=_QDBg3mpYTLvkm6QmMPvCnlXKH-6q5UBgxjFnjDbeDs,6081 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/iterators/epilogue_predicated_tile_iterator.h,sha256=ji1fnnW6YcwUF0-PZ46XcVX-PiOmhc6V8GLk_TM383Q,24110 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/iterators/make_residual_last.h,sha256=5TwEgMXnapiI8dXgSD2qKaZaTHdTmu4k5OEiIl8Iaok,1904 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/iterators/predicated_tile_access_iterator_residual_last.h,sha256=t1ZDqOd92TNY7poZz8aWKgxcEYxo5UQZ6Lr_trMdpKU,64720 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/iterators/predicated_tile_iterator_residual_last.h,sha256=gp7am6w0DCJEhboAUVzw5hXDASCxHIh-6bIOWxERn_A,64753 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/iterators/transpose_warp_iterator.h,sha256=a4X84U9_G20Fc_XFD3fCkfjvzo2a7ako4AS44pj8ngE,1215 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/iterators/warp_iterator_from_smem.h,sha256=xh58eUP15rAToajIZdPtEldFhQaezl8YbF3vKyHW4rw,10309 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/kernel_backward.h,sha256=SONL8F2lokBd5EsKhUh4hFsfNSHESa-lG2oRZX60Nsg,100522 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/kernel_forward.h,sha256=_L-gfwvEjiOeTYxFAl1dnmX_AX0A6d1meRjgMXJjdlA,55134 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/kernels/cutlassB.h,sha256=fE6YB0JhXGXoaybYqbJG_kyv1wtGkarMIcCQhUrV800,95653 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/kernels/cutlassF.h,sha256=xCBo8Ic7gnlqjXZhcFMIK2d40oZMRhpXY_h4zS-fDNs,26210 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/pytorch_utils.h,sha256=elA-QEGbaRvCdvmzJBgImCcDhyGyOb4f1shhYMiQ-as,1214 +torch/include/ATen/native/transformers/cuda/mem_eff_attention/transform/tile_smem_loader.h,sha256=tf0MqYkM9JIaMj88yQfIWgzaBMfaIPKMAojAtJgze_E,2406 +torch/include/ATen/native/transformers/cuda/sdp_utils.h,sha256=tKEObbTqcjymnIcMxddGMVbCswGt5GY-5o7r5kVzWxY,935 +torch/include/ATen/native/transformers/hip/aotriton_adapter.h,sha256=wswyUFNhrXc6iUMdqXAZ6as_IeR7qWuVyX7gK3lLczk,6549 +torch/include/ATen/native/transformers/hip/aotriton_versions.h,sha256=W8Fg0hIeYwddLZFRFFr5jWYP4sO7ZRg6Zi7UgpaJENA,847 +torch/include/ATen/native/transformers/hip/flash_attn/ck/me_ck_api.h,sha256=2Au0JqJZmYLlAovY6rD_-qFrnp06USJIMe58wDfDRak,2021 +torch/include/ATen/native/transformers/hip/flash_attn/flash_api.h,sha256=U4mNQNV-HAUAEd1Cirn5VB8qMkbdOcylZ6LiWXOGpz0,21108 +torch/include/ATen/native/transformers/hip/gemm_kernel_utils.h,sha256=2r4RXOKhLO517Ex4Vrt1Asa2xU54DqV6mi2t7uChnoY,1729 +torch/include/ATen/native/transformers/sdp_utils.h,sha256=g0V9b6B0GnpezL8TMQpO6a49pwUeKx8onydtOM08Nk0,3471 +torch/include/ATen/native/transformers/sdp_utils_cpp.h,sha256=-ZQ1xIa0xfKbhKKamHD-bAbVk9ugPlsL3A9QtQp_4Zo,19889 +torch/include/ATen/native/transformers/xpu/sdp_utils.h,sha256=TJP33v_Umxffcwa04qphK2N93jnnpWKMDp9hujoTO4c,754 +torch/include/ATen/native/utils/Factory.h,sha256=4dD3UfsbIm67hVZUejjcQNBCllVt2gOaE_6ucn6l1uY,697 +torch/include/ATen/native/utils/ParamUtils.h,sha256=rFmuGBcCV_IxqcQKUFycJhjD21rHFgXa_a4VM2ZeNLc,1463 +torch/include/ATen/native/utils/ParamsHash.h,sha256=vQO1aftMAZP6KS9_10QogPZ3W9vljb3FFUz0wW3lkOo,2794 +torch/include/ATen/native/verbose_wrapper.h,sha256=tSL4joW3TAZdsqba7Y7Cauyq0Jp3G9C4116lGmdTs6c,447 +torch/include/ATen/native/vol2col.h,sha256=zAA7LrKdvrCGsuitLlcWXHMD7V75Gh0C21r6-wW17oM,3809 +torch/include/ATen/ops/_adaptive_avg_pool2d.h,sha256=VKv9hXeA4KAtFD4NCgbXz8wfdejTzHII8vcP5_D4oJA,4395 +torch/include/ATen/ops/_adaptive_avg_pool2d_backward.h,sha256=8Ubr9PuqM_27gN2Yyk03vq3RrO8Hwovqoy2VVBrxIuc,1706 +torch/include/ATen/ops/_adaptive_avg_pool2d_backward_compositeexplicitautograd_dispatch.h,sha256=mLkVi1HCGh9nSBkKESDUAqtfRaZ0Z-00rW8-UgIq554,1231 +torch/include/ATen/ops/_adaptive_avg_pool2d_backward_cpu_dispatch.h,sha256=OsC_c6UUjet4H_zYi7IIZw0sKrzC0V9ztHGk9pjFhnQ,1029 +torch/include/ATen/ops/_adaptive_avg_pool2d_backward_cuda_dispatch.h,sha256=6QcvbVmZky7Q0hbelPJyv3I10D1R0b0aaVfPp7bNaww,1031 +torch/include/ATen/ops/_adaptive_avg_pool2d_backward_native.h,sha256=r7HHxy8BF7Ou5o3Z3lS0FGx3j-7zaNeMUlVzix4fHHw,1034 +torch/include/ATen/ops/_adaptive_avg_pool2d_backward_ops.h,sha256=BhB-sEfb_DaxKIKckF_68PuVI-wCY_fOjgGMYehQG-s,2147 +torch/include/ATen/ops/_adaptive_avg_pool2d_compositeexplicitautograd_dispatch.h,sha256=k7uR9x4eqtcgWoutyVO4IR9WdCp45_k52Zjb0rLgbLQ,1472 +torch/include/ATen/ops/_adaptive_avg_pool2d_cpu_dispatch.h,sha256=lp8Ne9a25VTEcrtpsYruG9qlsSKA9PlJ320oGoEubdY,1125 +torch/include/ATen/ops/_adaptive_avg_pool2d_cuda_dispatch.h,sha256=NuLYus9z6EKbte63g72zIR_z5zHzz0VaSggJ45L_54o,1127 +torch/include/ATen/ops/_adaptive_avg_pool2d_native.h,sha256=yQB5NsFghSasLHbkDz-XawSCqyHzjQVxamL0UhK5ehI,1230 +torch/include/ATen/ops/_adaptive_avg_pool2d_ops.h,sha256=99HZh1i09c0SA5KV64nk-VTPK4vaeIEOzjW5jY6-BBg,2105 +torch/include/ATen/ops/_adaptive_avg_pool3d.h,sha256=v2a_8P7iuJ06UvQKIWKYI5_HxhaIOSnfo_RlAO_gUu8,4395 +torch/include/ATen/ops/_adaptive_avg_pool3d_backward.h,sha256=3cVh_GUjUbgLPJLRTW2e3Ta97b6bggisWhNN2k79_FM,1706 +torch/include/ATen/ops/_adaptive_avg_pool3d_backward_compositeexplicitautograd_dispatch.h,sha256=43DpFO1vxssk3yj7QYLBfdY6-jrjwVZmjrmBgPmc9GI,1231 +torch/include/ATen/ops/_adaptive_avg_pool3d_backward_cpu_dispatch.h,sha256=UM0xvlbTYxwnsDKzEOqaosV9s3cNUIWYt29gwQqOnbs,1029 +torch/include/ATen/ops/_adaptive_avg_pool3d_backward_cuda_dispatch.h,sha256=_350PXjjuL0GNI753yx8iKuZwKQ2Uh9c6zLWjih2uXw,1031 +torch/include/ATen/ops/_adaptive_avg_pool3d_backward_native.h,sha256=KCwuX9lPBO2jfosSnOiPqNJ9o8uXg8GSPXKtEDUXnGY,1034 +torch/include/ATen/ops/_adaptive_avg_pool3d_backward_ops.h,sha256=4K6JCalwtIBYas68HT8fgERDxVShrbLhhZbTP791-co,2147 +torch/include/ATen/ops/_adaptive_avg_pool3d_compositeexplicitautograd_dispatch.h,sha256=t-Iy_nYO5oxgcoAEZtM8bUZymZwR8aeBdVWHimIff38,1472 +torch/include/ATen/ops/_adaptive_avg_pool3d_cpu_dispatch.h,sha256=uJjRa0Koz3qaFx-e9SlGZ3io2is7smRWro2zH5KSxK8,1125 +torch/include/ATen/ops/_adaptive_avg_pool3d_cuda_dispatch.h,sha256=3iRhAMZ1qyofZpU8uIIKN5adBjekHe6upXAwr55SgTY,1127 +torch/include/ATen/ops/_adaptive_avg_pool3d_native.h,sha256=XtGD7YLyX-gz9KqSHVRAhk2D8PlBytuEg332Xg0APTM,1119 +torch/include/ATen/ops/_adaptive_avg_pool3d_ops.h,sha256=EXAipK5kpqItDp0H81q9hS8TnA7goCYh-iwBeZErOyM,2105 +torch/include/ATen/ops/_add_batch_dim.h,sha256=VIz0gGHwr_Sye4buLvGsa2nTXtotVQNl1qne_Bub-1E,1001 +torch/include/ATen/ops/_add_batch_dim_compositeimplicitautograd_dispatch.h,sha256=ZfoHh_My_mxOKUlNz8nNDG1aFL_oWJiLtMwwV_Xay-A,1060 +torch/include/ATen/ops/_add_batch_dim_native.h,sha256=h2Kk9wSX8FFzZCjJh76H6TyJg9gXcP_bQIcpkn8T2zs,772 +torch/include/ATen/ops/_add_batch_dim_ops.h,sha256=0y0o7r6MA1vnR77n2LsW5ukEaHIqxx-uzeE-ZMD8DFs,1347 +torch/include/ATen/ops/_add_relu.h,sha256=vnceR2sZ-FMjyE00C_I_vwd_SKNHuKrtT3XjEuFloaY,3035 +torch/include/ATen/ops/_add_relu_compositeexplicitautograd_dispatch.h,sha256=hUNyJx_nMiZwYeb5i75UP5uLcN9UFLIjxsx1jVHl0Oc,1233 +torch/include/ATen/ops/_add_relu_cpu_dispatch.h,sha256=REC2x8KKagTEtAwbtfHN4RtIjXIONz5eelHVd86rG-I,1627 +torch/include/ATen/ops/_add_relu_meta_dispatch.h,sha256=JLWkg0N4MNaLrhV7J0PNevRi3P2XVcA56XSNDZRLKfc,1138 +torch/include/ATen/ops/_add_relu_native.h,sha256=ptS5iBg9uD4tzaRHGaOtFCIEC4eYGx8mwqoAyn_5PBA,1382 +torch/include/ATen/ops/_add_relu_ops.h,sha256=0iMn3D4ZwCoKsi_9CDvGIpkfZOiLnApPTDQ8hDFnJt8,5094 +torch/include/ATen/ops/_addmm_activation.h,sha256=NFXY6zE8pZJ53l0hwyQTFPJPbbD9fVS4iNZNQUwCywQ,2101 +torch/include/ATen/ops/_addmm_activation_compositeexplicitautogradnonfunctional_dispatch.h,sha256=zc4M5jyoTUOOvCUdQ7DFlFzvsy8hd-u8sHt0ahifELo,1181 +torch/include/ATen/ops/_addmm_activation_cpu_dispatch.h,sha256=QFoZ5pSn68aAgyxyCXBq6CGRCEhBVIESOCloETpWfg4,1532 +torch/include/ATen/ops/_addmm_activation_cuda_dispatch.h,sha256=x-ArIRqgPH9MaWVhIWPt2PPgTuYJucA2NjkQwLa5Bnk,1534 +torch/include/ATen/ops/_addmm_activation_meta.h,sha256=zQs0DP6jEuXc131wioxiuLSx7f57u2GB6xYySqzErbQ,948 +torch/include/ATen/ops/_addmm_activation_meta_dispatch.h,sha256=LJ-qSa6F7dtiale1qdWtblQDpyNQ0qCohC7DI0bcUZw,1534 +torch/include/ATen/ops/_addmm_activation_native.h,sha256=9KrUGdrLmXNecFwyiGaXDeU9XMBlAA0ostjW9jnQmHo,1285 +torch/include/ATen/ops/_addmm_activation_ops.h,sha256=cDCyYLEx9WwDg1ymxPYEUvB_FdmXqphuzTD9Af138-U,2662 +torch/include/ATen/ops/_aminmax.h,sha256=_JKA35j3Hw6HhCJqbcqHKACzDK-dEaerEL_nvQnLbAU,2504 +torch/include/ATen/ops/_aminmax_compositeexplicitautograd_dispatch.h,sha256=-UB2ENjtdZhPT8vTj4fd-XWhNI444dgmGccSVJtNxEk,1534 +torch/include/ATen/ops/_aminmax_cpu_dispatch.h,sha256=JfDl8NSKZ_KuT8advdH0RUiGvkQroIbrypcYO0zoBhM,1115 +torch/include/ATen/ops/_aminmax_cuda_dispatch.h,sha256=cbjKuLphT7N66jabChNFqo2oWbbFKAyg8t5LIiePLf0,1117 +torch/include/ATen/ops/_aminmax_native.h,sha256=M48NN_OtbMGf9bYDJEXlsHyBDWfrMm4edOtFaMR5YpI,1160 +torch/include/ATen/ops/_aminmax_ops.h,sha256=xW39vDxpi23hwdnGEszwL5oRNUY8CNFnJxh2ijS83_M,3638 +torch/include/ATen/ops/_amp_foreach_non_finite_check_and_unscale.h,sha256=e8CuktcHI7bn87uBRzuJtg5WQSO76KpjBrWzHOlA_Tg,2377 +torch/include/ATen/ops/_amp_foreach_non_finite_check_and_unscale_compositeexplicitautograd_dispatch.h,sha256=VXLsaOjSRF2B2xQph85eMtcePFfWzGhVZukvnTjG2II,1464 +torch/include/ATen/ops/_amp_foreach_non_finite_check_and_unscale_cpu_dispatch.h,sha256=TfYb0wqSIp7wJvieB9xHFAGsFhlKi8nGgRTk2JVCSAE,1054 +torch/include/ATen/ops/_amp_foreach_non_finite_check_and_unscale_cuda_dispatch.h,sha256=mGRzwu0aolPlbO2Nho0ibcuLp86DH54hsB38PyH92w0,1056 +torch/include/ATen/ops/_amp_foreach_non_finite_check_and_unscale_native.h,sha256=X5k13v-pQX-wkr3HSkBRbrPuplybZ5W8OjVlEwkaVsU,1295 +torch/include/ATen/ops/_amp_foreach_non_finite_check_and_unscale_ops.h,sha256=PH3IpIBYawlq9GeRIIMUxOGm4_q2yQE32TxLvHrY0vM,3262 +torch/include/ATen/ops/_amp_update_scale.h,sha256=m5NSz43QaTDRqAyEvKOya71WqTwK5mdUloeH0puemx8,3018 +torch/include/ATen/ops/_amp_update_scale_compositeexplicitautograd_dispatch.h,sha256=q-KqXU0UiXyiHAvsA91rq8ZUYka3gtrHxWi6mKve1iI,1662 +torch/include/ATen/ops/_amp_update_scale_cpu_dispatch.h,sha256=7N15m6iQbPylF_iCg-KTrs-v0WvXI2LydzfinzIM90o,1123 +torch/include/ATen/ops/_amp_update_scale_cuda_dispatch.h,sha256=yNcvckOdIf88VDGvYUV0ZfBbJ6sTEq5Wzwl4RgAGPGc,1125 +torch/include/ATen/ops/_amp_update_scale_meta_dispatch.h,sha256=8VDbSMIA53C_Wex35_MHAGxgyHoTnzk7MY2Udclp54s,1125 +torch/include/ATen/ops/_amp_update_scale_native.h,sha256=-3IT4l-Se22BUw52HnDiT7knBPUR9Fkiu3rGcidtXv4,1558 +torch/include/ATen/ops/_amp_update_scale_ops.h,sha256=7pt7ckvF4x80pmTtcZI0sF_l0llEWq6D16HCnxkf_4Y,3903 +torch/include/ATen/ops/_assert_async.h,sha256=NU64JdJs9kO2GaC3hDE8oJJAqkzPU3rjWDeLGaq-I4c,1120 +torch/include/ATen/ops/_assert_async_cpu_dispatch.h,sha256=8TWiV4wTxBGib2X21PnqM6xcyyBKpTATUiCspwkXo9I,1059 +torch/include/ATen/ops/_assert_async_cuda_dispatch.h,sha256=hb89YSZIwi1MDNAWXDaIaNCKKopZnmOlF_Q4mWu8GPo,1061 +torch/include/ATen/ops/_assert_async_native.h,sha256=Suv-5Ls1siFxFXjhIIHMjl10UXTM5Wxx143C2mQ3FcQ,980 +torch/include/ATen/ops/_assert_async_ops.h,sha256=qlkmiPuJ7jmlQPWenFdY2WGtWYGki3WjPkeWI8OtFsw,1812 +torch/include/ATen/ops/_assert_scalar.h,sha256=cuff-IVFPf2VkAJ-hpG9D8MRCmrc8Dq3vQjr4oISYIg,970 +torch/include/ATen/ops/_assert_scalar_compositeexplicitautograd_dispatch.h,sha256=TtEYQMZ69qKusuxsf-aeOjJUP31rCsguWCOkI5AV4pI,1049 +torch/include/ATen/ops/_assert_scalar_native.h,sha256=XTx6IF8VVQ-cq9oZCDlLwmPbg4BNjtSGiaRPrnCVS1I,761 +torch/include/ATen/ops/_assert_scalar_ops.h,sha256=jU1JJNn4_3UGgtEJnUqtzM-nQquVmUM-MMmTXlnoSno,1305 +torch/include/ATen/ops/_assert_tensor_metadata.h,sha256=cXDhhq656r4YDYdFinLYOn9eu3Z13H_kloP5GEg0XvQ,3272 +torch/include/ATen/ops/_assert_tensor_metadata_compositeexplicitautograd_dispatch.h,sha256=qQkLHdbYoBWq3jM7pYTD9Zu_nDffN68TEL23cDp0Pm8,1597 +torch/include/ATen/ops/_assert_tensor_metadata_meta_dispatch.h,sha256=pA9v-ov8VAO5wUQ-grfgzxy7x638CTqDyIN11LuBexw,1555 +torch/include/ATen/ops/_assert_tensor_metadata_native.h,sha256=7h-X_m5RsMAC3QPX7fyrEVio1fFmIA_6X4cRPluwHoE,1314 +torch/include/ATen/ops/_assert_tensor_metadata_ops.h,sha256=t4gkCXNhLgte-i0jz5ATfwzzZinlnVBq0YPS0Xt4XsY,1849 +torch/include/ATen/ops/_autocast_to_full_precision.h,sha256=3F4Q2TewdBXsSFSg6MTL4AVbvLlq4-mqQZ6qElUvQh8,778 +torch/include/ATen/ops/_autocast_to_full_precision_compositeimplicitautograd_dispatch.h,sha256=ZV6rFidwsaHXWOWQNPPkpkYZbGny9fPDeoEvsbo1lhY,1076 +torch/include/ATen/ops/_autocast_to_full_precision_native.h,sha256=5G8Jeejaliid0n7xxs8i3zeyQN-NonRM44IfjD8pJSc,788 +torch/include/ATen/ops/_autocast_to_full_precision_ops.h,sha256=_wouMqdvfFJL4-TrK7eLXcyTCri_u33NpQmUmT2a_es,1403 +torch/include/ATen/ops/_autocast_to_reduced_precision.h,sha256=cgqPSA-IAKKYs_xsrri3-UburVPSvZJWxhfeO8POkWE,781 +torch/include/ATen/ops/_autocast_to_reduced_precision_compositeimplicitautograd_dispatch.h,sha256=i13BWqXPk8hFtzXQNZg7YsSmj9gMzwc-34_l8O5GvdU,1132 +torch/include/ATen/ops/_autocast_to_reduced_precision_native.h,sha256=MFscclOIoT5hAlHdZ2ewIyd0gCzFbz8icgT5pzqO7qY,844 +torch/include/ATen/ops/_autocast_to_reduced_precision_ops.h,sha256=G-f_alHvPgQjuPz5O3EAWBzITSTrcPilnaPzMxyOMvo,1595 +torch/include/ATen/ops/_backward.h,sha256=BW07CJoOliQbp9F42ephO8cNvgorce3PNcOs3rPNA48,760 +torch/include/ATen/ops/_backward_compositeimplicitautograd_dispatch.h,sha256=jA9epTU1M9w1Evm03JmVCoJaQuF7rnacxhpvOWKXGHM,1163 +torch/include/ATen/ops/_backward_native.h,sha256=-AbG5eqnAl3djIXSiRej_apsXFGRYUb1nEyP45S3GkE,875 +torch/include/ATen/ops/_backward_ops.h,sha256=xm_Nte-p1bAnRZZgtubHW9C2jNRb7Z7iY20P-4VS4tw,1618 +torch/include/ATen/ops/_batch_norm_impl_index.h,sha256=f-cwCC2OOt3JCgQglZmh0PQMzRl7XlKMGViMMs5Od78,1509 +torch/include/ATen/ops/_batch_norm_impl_index_backward.h,sha256=7Bp5xP1DZIC75Gs_rXx5mCQMYr2Cmwcgldagep6c4FQ,1777 +torch/include/ATen/ops/_batch_norm_impl_index_backward_compositeimplicitautograd_dispatch.h,sha256=2BJgAze5zGVOeP4HQqulXhKipOJ0pKA13qPze50RmoM,1470 +torch/include/ATen/ops/_batch_norm_impl_index_backward_native.h,sha256=xUnZjUpfRL6POftgbtMH2t9VI03OUtkMN0ssS-vdtsI,1182 +torch/include/ATen/ops/_batch_norm_impl_index_backward_ops.h,sha256=2r5mtBrLVtKMpAjvylJWAIIhT438oBVYVcvV6F7hO3M,2673 +torch/include/ATen/ops/_batch_norm_impl_index_compositeimplicitautograd_dispatch.h,sha256=Ewr-XGnFSikwRYpyGOZk7frC9eYHd4dNAsgXqX5ZCPc,1339 +torch/include/ATen/ops/_batch_norm_impl_index_native.h,sha256=tAoprCXpkL45Y-SL5mOVMYXH6dRuodGSvpdwP-0TZzY,1051 +torch/include/ATen/ops/_batch_norm_impl_index_ops.h,sha256=PBqZ6dNJtPu5W8llYfCmbzPpCBmY12o2ULUWiO2TWVs,2267 +torch/include/ATen/ops/_batch_norm_no_update.h,sha256=0q26fQ4TkGIFBOQ-1rXmiqQhbQKFK1qD0XF-tunPhWs,3063 +torch/include/ATen/ops/_batch_norm_no_update_compositeexplicitautograd_dispatch.h,sha256=HAxsh33mQ4H9sQSN7DQqyKXJvjvEC02aGTyOQb9JxQo,2134 +torch/include/ATen/ops/_batch_norm_no_update_native.h,sha256=rAUyAzEl9xsqjUaEHtQ3raTYnUNaBlBziQWwW-MC8fM,1426 +torch/include/ATen/ops/_batch_norm_no_update_ops.h,sha256=TILf3FK6lm-ASfHLmEy1XnWDAcrz05Y0JDzBKQX48_E,3855 +torch/include/ATen/ops/_batch_norm_with_update.h,sha256=N5fMIXovPnpBDuIGeCqG_4o0mjgtiqr4bGe_8VV9lqQ,3747 +torch/include/ATen/ops/_batch_norm_with_update_compositeexplicitautograd_dispatch.h,sha256=aEJAQBBW8f33iIXBeiuGCLxYYxrhCnVmSaOlwETCWTU,1296 +torch/include/ATen/ops/_batch_norm_with_update_cpu_dispatch.h,sha256=wuN1YbE3ujiNhjHf5YYDGJztIOEiklZpOSWGthNdPQ0,1986 +torch/include/ATen/ops/_batch_norm_with_update_cuda_dispatch.h,sha256=Rp_AgdR8ymgAexMLxz4rq35snL7UXDSmsz7WIX60QBA,1988 +torch/include/ATen/ops/_batch_norm_with_update_native.h,sha256=5mzx_xP-eoAOx77l3X399JlsntboLI2ZD9DdsDikwB8,2672 +torch/include/ATen/ops/_batch_norm_with_update_ops.h,sha256=IVRgqFcs55zMdv8aTuF35iEkMOQhKnaLih7S75i3Q_U,5102 +torch/include/ATen/ops/_cast_Byte.h,sha256=iUEt6J2gNyETwvNPufNb3QXf1B0Lk82uI9IbBYJre0c,971 +torch/include/ATen/ops/_cast_Byte_compositeimplicitautograd_dispatch.h,sha256=GAMd54TpuYLJqla4jkgSncD36gAk9jrZC5oF4gAmJ9U,1047 +torch/include/ATen/ops/_cast_Byte_native.h,sha256=r3Cz2B1FnuwiG3OYBrNMwqrI21-O0E8P1Tt9NuMC8-4,759 +torch/include/ATen/ops/_cast_Byte_ops.h,sha256=uw1XDJr8AEx3Y9cKkB2TRJxVpV3dCegCuVaYUL_7_Fw,1292 +torch/include/ATen/ops/_cast_Char.h,sha256=W8CCak9jEOtwzrrxHEHjmRA4ZRF0pXJSEIMCuKhUddg,971 +torch/include/ATen/ops/_cast_Char_compositeimplicitautograd_dispatch.h,sha256=QCN2swYd6xNMS2rFKyre_D4tdZ8Ys-e5dych1VyHHL4,1047 +torch/include/ATen/ops/_cast_Char_native.h,sha256=tmhgYowjNN_Z4h8JL9DeVce9zq5xtWwSu8Qt6KD_cEc,759 +torch/include/ATen/ops/_cast_Char_ops.h,sha256=IJJww6lMEhtzi7AaE9KJ8oXfwqjJlx8SSKSP2u2vDwk,1292 +torch/include/ATen/ops/_cast_Double.h,sha256=qfyoNBLnGsT6T-w7U_5d8o_v3so49U-E7yn4du8mnFg,979 +torch/include/ATen/ops/_cast_Double_compositeimplicitautograd_dispatch.h,sha256=MSiiUBlIJjbi-9Vi1i9mbrco6KKsh1zXG8hHemVUQlU,1049 +torch/include/ATen/ops/_cast_Double_native.h,sha256=5UQdbXBOdrut4ZBXlcICD5zplBm1YQoT8HHHLrM1nTU,761 +torch/include/ATen/ops/_cast_Double_ops.h,sha256=ZsbiOn9mzLE8db7ubpoVpWvtCFoKqc1aFNUfAz2_n6o,1298 +torch/include/ATen/ops/_cast_Float.h,sha256=tATJSdY3Alki6EbaIOZROvlWrOICxXbSiSM-BqJh5f4,975 +torch/include/ATen/ops/_cast_Float_compositeimplicitautograd_dispatch.h,sha256=OWeqPDgm426C6d3TjMJpuU6XYqk46qV9mu9TCcwHGQI,1048 +torch/include/ATen/ops/_cast_Float_native.h,sha256=pdAGU-5aIjQv8NzKIeXlTU1Y6o3A8aMIW2zOAlNGQs4,760 +torch/include/ATen/ops/_cast_Float_ops.h,sha256=p5kNK97whfzBZuCso0s-l_sYOy9eXR4TZ_Kfqmk5cOg,1295 +torch/include/ATen/ops/_cast_Half.h,sha256=TaqI_D3YLGhwLX6zkNz8Ioo7E988i_L0aBNx8KhbFbw,971 +torch/include/ATen/ops/_cast_Half_compositeimplicitautograd_dispatch.h,sha256=Daf1_C6LfpVL7nr16k_oatRAk_iupE4LU84-HNBVKu0,1047 +torch/include/ATen/ops/_cast_Half_native.h,sha256=koynLsIimWLnvFTbh_OUtbb-j4Sk_YN2W7_p1erjdP4,759 +torch/include/ATen/ops/_cast_Half_ops.h,sha256=Cnp7hvpq5cCmyGEbYXY_V7i10SIirxxF3nAeLIKUWKo,1292 +torch/include/ATen/ops/_cast_Int.h,sha256=_i0h3Hcwxovwfnb80Y7_SxsU-fMCV-d9uZM3QdabIDs,967 +torch/include/ATen/ops/_cast_Int_compositeimplicitautograd_dispatch.h,sha256=qyJwe6vAd06IDjhj3IFdRj_csh4jLT6vnzllcbvuCt4,1046 +torch/include/ATen/ops/_cast_Int_native.h,sha256=fU7d7ep-emIz4Wj8auNcBgjgRCgm68UDvguodGoYCVE,758 +torch/include/ATen/ops/_cast_Int_ops.h,sha256=Gnq8WunEMadHatpIRAb972UB3aw1f891pBHKujTTOnU,1289 +torch/include/ATen/ops/_cast_Long.h,sha256=VZweppx4HFvooEZpt3K-8-PsRyEPSV5PP98OugsNjtY,971 +torch/include/ATen/ops/_cast_Long_compositeimplicitautograd_dispatch.h,sha256=JDWTNIDQ_BB4MFnSOuudgxHb4dF1Uq2DepBI4KCUk_U,1047 +torch/include/ATen/ops/_cast_Long_native.h,sha256=8YBfwMAvxCeQXyXDgdP3-Ix8XZHzZokD135VxjOijMc,759 +torch/include/ATen/ops/_cast_Long_ops.h,sha256=QszCLEyc2Ez62bHrt0JlEUfxibnaUZMs-2TCLkfHPQY,1292 +torch/include/ATen/ops/_cast_Short.h,sha256=GgjfVe2S0RgVpZgHo6Kau1qbwNiE9DfWFkA0l0pavfc,975 +torch/include/ATen/ops/_cast_Short_compositeimplicitautograd_dispatch.h,sha256=VLVdL13yRlMSxSJZyG-1Xr4Ytct4rqObuz-G3_xUXsE,1048 +torch/include/ATen/ops/_cast_Short_native.h,sha256=It3CgornyGV7rnn9TZzwh00Jy6m7ToEubFrsyNbLf-Y,760 +torch/include/ATen/ops/_cast_Short_ops.h,sha256=79_EaptGAYz4X7YfPzd-QC1hzm9RG8gT2t2dh8RW08E,1295 +torch/include/ATen/ops/_cdist_backward.h,sha256=11_2l5uYRo4xBZDZ_t3Q7c9o0sWcKWVcyKMzNLq2duw,1869 +torch/include/ATen/ops/_cdist_backward_compositeexplicitautograd_dispatch.h,sha256=vEXq-MjZTJqOUuhkKKz4Szr09aui4jC1Hgk8DXd0HqY,1317 +torch/include/ATen/ops/_cdist_backward_cpu_dispatch.h,sha256=xAgv_CyzuEDifsOu7EhaHdCfK_zsTEUwncMtmcSClZA,1072 +torch/include/ATen/ops/_cdist_backward_cuda_dispatch.h,sha256=Tixt50G6jOSYtzeL9jvXy0MHkXCEk2VvM2E2YD0qpg4,1074 +torch/include/ATen/ops/_cdist_backward_native.h,sha256=1DH0yw9TnHxbWswkLHItyyF5cpyGG25nG_O2b8AN_K0,1004 +torch/include/ATen/ops/_cdist_backward_ops.h,sha256=QIjgjrHTaxLSE30fQriYz9cEwuTeWN4-FmrGk0RCJvQ,2451 +torch/include/ATen/ops/_cdist_forward.h,sha256=KZ6DmmHw3jPvtB4VfYYGT0nMshTKcveu0LbPa4N4GQY,1739 +torch/include/ATen/ops/_cdist_forward_compositeexplicitautograd_dispatch.h,sha256=UgQS0ZUGuf1ats_zIuSZdP3_-LyY31AeS6zWPhn3SIo,1277 +torch/include/ATen/ops/_cdist_forward_cpu_dispatch.h,sha256=8FlF-PXLzmcNcycd3w3fYKgjg-vri4Rx_KHkqp2-F3A,1052 +torch/include/ATen/ops/_cdist_forward_cuda_dispatch.h,sha256=Kf6jo1ZPTPWiAQLmrzV5gOeuPMDhBOTAIVKvK0YCMNo,1054 +torch/include/ATen/ops/_cdist_forward_native.h,sha256=-MG8DF1QwsiAjRyiqCDwul9HJlMYbwxgkJVsLashk44,964 +torch/include/ATen/ops/_cdist_forward_ops.h,sha256=hzMkV3q3BzgWMwPV5mqS4S4ylU2M5-IpmHVxhFx_uCk,2311 +torch/include/ATen/ops/_cholesky_solve_helper.h,sha256=WSC4_9F4Bbap4noFpACrORmdYLxiG-CJJOpoACP1uD8,1639 +torch/include/ATen/ops/_cholesky_solve_helper_compositeexplicitautograd_dispatch.h,sha256=BO5o1jS9T-kkw9ZdcO_9rer3ha3YLXSBz2ag7CUWRJ8,1221 +torch/include/ATen/ops/_cholesky_solve_helper_cpu_dispatch.h,sha256=ObB-pLnODn4w45B_mfDplqdqj01b62iItFJ8z3Y4Y1E,1024 +torch/include/ATen/ops/_cholesky_solve_helper_cuda_dispatch.h,sha256=zOBtWBt10BPpa_6jylzVjFCReQDaGfK-CcSTx6wSTmE,1026 +torch/include/ATen/ops/_cholesky_solve_helper_native.h,sha256=yeiQt30yfDz94JoDHqzSy9eDJgLhKzOVg2ILDAIhVcQ,1021 +torch/include/ATen/ops/_cholesky_solve_helper_ops.h,sha256=xJqu_YSMiUtyBKhaDL5w0uF0v6HjtRKbWwi_ft9c7uo,2129 +torch/include/ATen/ops/_choose_qparams_per_tensor.h,sha256=B8FYNi4YNh5HVA6orsR7bBHngPmiHsrofnaFvjXWP0A,1059 +torch/include/ATen/ops/_choose_qparams_per_tensor_compositeimplicitautograd_dispatch.h,sha256=RJKzWLBY7okEhWlnEb1F_nx4kuHt8dlzufG-niQ_3gg,1081 +torch/include/ATen/ops/_choose_qparams_per_tensor_native.h,sha256=vAQvomoawvPD0d7jpIjwNbbhVrGXSwToK_e5ZZ2Ygv8,793 +torch/include/ATen/ops/_choose_qparams_per_tensor_ops.h,sha256=y57Z7uuQUQF2cG_UBZPLi7hmTNHorPvE2gBnYEXrAm4,1400 +torch/include/ATen/ops/_chunk_cat.h,sha256=T9pTGfyJy52r7bgPJlpOsRVmbBKWO9Su_1OV8l8zYYE,1567 +torch/include/ATen/ops/_chunk_cat_compositeexplicitautograd_dispatch.h,sha256=epexgL_T4kVC7Hi8cFbmsmtE08AaK4NQn4NtdUxIw2s,1283 +torch/include/ATen/ops/_chunk_cat_cuda_dispatch.h,sha256=VTrX11jLlT5B9zTPYTD49ZLwQ9LC3N-fHc_tcDTBb8k,1241 +torch/include/ATen/ops/_chunk_cat_native.h,sha256=e7J_6_g0BvWrt93V3-yid2-3RQe_kgVHu-pyxaSG7Ic,1094 +torch/include/ATen/ops/_chunk_cat_ops.h,sha256=CWggP0xIMY8ssvXBfyIo7DACCgC6CSpq7Nblp-4s0-k,2041 +torch/include/ATen/ops/_coalesce.h,sha256=N0BSrvTZjla5WLys7UM5t0KkaOIMEXZju3kVyWhdpDI,1311 +torch/include/ATen/ops/_coalesce_compositeexplicitautograd_dispatch.h,sha256=Hwc44Lu6xmDsoNlFToxCyooWSqO4qkEXeBIBO7Npqu4,1127 +torch/include/ATen/ops/_coalesce_native.h,sha256=IZzOMWVpLqWR3S1R_pxXZaeiOsgvqQ-WmWg6UcQW0Ng,894 +torch/include/ATen/ops/_coalesce_ops.h,sha256=182XiGHaPEqjvqZVVpVh-7041I6k-_04PJCIOAg3cw0,1819 +torch/include/ATen/ops/_coalesced.h,sha256=6upz2I_Cz6AAj-noGFu9fytzrasEoHmcEFfSG68eisQ,1450 +torch/include/ATen/ops/_coalesced_compositeexplicitautograd_dispatch.h,sha256=bQAOq--qjPQXpU458gmtCIjRv--1tm4XQUigqo6vqbI,1235 +torch/include/ATen/ops/_coalesced_meta_dispatch.h,sha256=uoZYnRD-za2B4bk6wcPbPORdR8_OGloko6sYx-a18Zk,993 +torch/include/ATen/ops/_coalesced_native.h,sha256=dbrXtbdzfRU3cu3oNWd6CYKSzkDdsIDMgg7i-UTKlHo,926 +torch/include/ATen/ops/_coalesced_ops.h,sha256=hgewfg3wKaUot6UiGPjWg78VhXXwOO8MhmJikYCrg-8,2498 +torch/include/ATen/ops/_compute_linear_combination.h,sha256=8wGZlGnNfIWISMCvVzlL7ROCjl47pdwCqTQemYqLTEc,1704 +torch/include/ATen/ops/_compute_linear_combination_cpu_dispatch.h,sha256=Ajtd3CjthKwJ7V3qtszHnv0FuF_hlxYnDNSu-Iqs7jo,1296 +torch/include/ATen/ops/_compute_linear_combination_cuda_dispatch.h,sha256=n3HM0-oJNiu5YSsbZ6YG8I8VgTIH4JjhZ8jE1yyBvcQ,1298 +torch/include/ATen/ops/_compute_linear_combination_native.h,sha256=za2Y3ia5OKIs36aqoDm1ag4Dbsjb3C8kt3s_Z30Gnno,918 +torch/include/ATen/ops/_compute_linear_combination_ops.h,sha256=5jNsiFzBxgyO9_odc7t1rhyTzuud2mtonfsG9oThVXg,2147 +torch/include/ATen/ops/_conj.h,sha256=Vqqr4_E1xNeHHWsjX6zD5djPF0Xax7K-aDugkARvXVw,893 +torch/include/ATen/ops/_conj_compositeexplicitautograd_dispatch.h,sha256=4OMPve0UexbWAY6l-772oFDMRBkiSbsdRzvioc4IXBk,1017 +torch/include/ATen/ops/_conj_copy.h,sha256=YhalmUTfwScRx01_Ywimk54DfAryQyWWdrFWJN9XKms,1321 +torch/include/ATen/ops/_conj_copy_compositeexplicitautograd_dispatch.h,sha256=EJc9ItHLNPpT3LSrqgX7PVEfvD6qT3zYODWbmMar30Y,1129 +torch/include/ATen/ops/_conj_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=CsDc8Mfo_u67sRUvY9K4tWqghj8hhltsiyODNkkw_Pg,1048 +torch/include/ATen/ops/_conj_copy_native.h,sha256=9f_Okj59riaDKjCf-0kYFu0o4xb_IsFG7A48r6Iq_b0,816 +torch/include/ATen/ops/_conj_copy_ops.h,sha256=D3FDjoHVKA4ftBmATHt-ZX4q3dfiHcUWgiM2sn0OHRE,1825 +torch/include/ATen/ops/_conj_native.h,sha256=cSdPVDZuBSqhVVlgYyL7uBIhg1d95B-J8PhC-wEPbbI,729 +torch/include/ATen/ops/_conj_ops.h,sha256=5FxQr6pCdhZw0fHu-A0LEMvh4q6CVTY0A9zi7dKJWj4,1214 +torch/include/ATen/ops/_conj_physical.h,sha256=UAzAku0g6WDKOs19vYlnNCOWjiRO6phZsMpVC7Xp9Jo,1361 +torch/include/ATen/ops/_conj_physical_compositeexplicitautograd_dispatch.h,sha256=M8f53piexBsVfRHMrzQE3sIzHbVfBXYAlfg-fcDcUiU,1199 +torch/include/ATen/ops/_conj_physical_native.h,sha256=hGW_VDV9utF3Y4DB4SP4FVqEstX82rQJVOfvgrKsQoQ,896 +torch/include/ATen/ops/_conj_physical_ops.h,sha256=121AJUJBjTeTuw4qPQfhhXC5lH8SWW9tRPhKtblECNs,1849 +torch/include/ATen/ops/_conv_depthwise2d.h,sha256=C0OEfvrPKN24-7iz1PVVb-nbajfwmtko7py41yx4Q04,7578 +torch/include/ATen/ops/_conv_depthwise2d_cuda_dispatch.h,sha256=9Uulq3grbRQKSzhRLMAyfJ6r32iAn7E9rg_F2ECCP_M,2517 +torch/include/ATen/ops/_conv_depthwise2d_native.h,sha256=TL4CMRMhGgk8vvIoeeKpkvZ9sJiN9ifBMBwdQwbVumQ,1184 +torch/include/ATen/ops/_conv_depthwise2d_ops.h,sha256=yYdFvBUWT4TWShQLvbDHSMmqCcj0ajzYv6aMTUt-XnA,3123 +torch/include/ATen/ops/_convert_indices_from_coo_to_csr.h,sha256=y6F5QIzN4lmg88sOsLH-AkL7Orbx-j-EhYl2MRTojfw,1793 +torch/include/ATen/ops/_convert_indices_from_coo_to_csr_compositeexplicitautogradnonfunctional_dispatch.h,sha256=VmRCUDmcdWiwHnyO89Q0-0KFFSKTTxjXHa1jED7qj3k,1106 +torch/include/ATen/ops/_convert_indices_from_coo_to_csr_cpu_dispatch.h,sha256=5ZLNV4BXw96cIfwPGyO9CguDVHrq521NOnFEn_zjgiI,1311 +torch/include/ATen/ops/_convert_indices_from_coo_to_csr_cuda_dispatch.h,sha256=uiCx_mveYp1ax36n22hj-r4_tc7CQWCJq9NnG_mNpfo,1313 +torch/include/ATen/ops/_convert_indices_from_coo_to_csr_meta.h,sha256=rvq_cGMN7RQoAGSrq9n6DoukTAlHCW6sTY2CNpDxcmY,877 +torch/include/ATen/ops/_convert_indices_from_coo_to_csr_meta_dispatch.h,sha256=B0k5XWC6aDpEwJ77xLG2u7jnHFyPZRALFHIJKTqjWls,1313 +torch/include/ATen/ops/_convert_indices_from_coo_to_csr_native.h,sha256=QWU5T6PNeQBX1BthUMVammhscFQaN9cyzlAAZBqtqcg,1204 +torch/include/ATen/ops/_convert_indices_from_coo_to_csr_ops.h,sha256=Sm5n8A2hp3wijgyR5nWiJ3eSbVPVRz4VijSRvWU0Ldw,2174 +torch/include/ATen/ops/_convert_indices_from_csr_to_coo.h,sha256=OD3B0dwhrRbq1itJQCDaJgWFXs-9pMgW-DdYKGdMK8c,2129 +torch/include/ATen/ops/_convert_indices_from_csr_to_coo_compositeexplicitautogradnonfunctional_dispatch.h,sha256=OFI4r1IM6gYL2h4JCpPY6IRP9lQeJXqbLbQYdicR6Io,1154 +torch/include/ATen/ops/_convert_indices_from_csr_to_coo_cpu_dispatch.h,sha256=PtqQQ5ubZTicTR3kKiaq4JaZXmsJF4hDfLaYh0HQDAg,1449 +torch/include/ATen/ops/_convert_indices_from_csr_to_coo_cuda_dispatch.h,sha256=G8ScbUetSbvFVF8KdWrbfxHITiJRT6RTbmLGRbKOZFY,1451 +torch/include/ATen/ops/_convert_indices_from_csr_to_coo_meta.h,sha256=pxEZUmYTv3XycK7htukyU_bdTD60FgF07sqFbZsmfV0,919 +torch/include/ATen/ops/_convert_indices_from_csr_to_coo_meta_dispatch.h,sha256=Vm331Z7hvxirfJqdEL6u-yqpsFexuH-rFxiljX3tykE,1451 +torch/include/ATen/ops/_convert_indices_from_csr_to_coo_native.h,sha256=-LZJCtnRrdBLa_fh8xvNfTBLf7zt5h_d-yKlWMN-rWk,1288 +torch/include/ATen/ops/_convert_indices_from_csr_to_coo_ops.h,sha256=q43U78gVKNtouUgPVdjU2Nc_0N8ltIc4HVbTowJEI3k,2456 +torch/include/ATen/ops/_convert_weight_to_int4pack.h,sha256=clAs63Ym8Z6fS3RV8yWCkVEK8mDwiMObipkHT7vMPkI,1026 +torch/include/ATen/ops/_convert_weight_to_int4pack_cuda_dispatch.h,sha256=gJmUQtj4btzKA71uQALoSxcB5SwejJG2Q3xO52a-ckI,1018 +torch/include/ATen/ops/_convert_weight_to_int4pack_for_cpu.h,sha256=PJ2yIS77nZIuJqeA3BcjL34HWF4ysq_Y6tGAPuF9rQ0,1058 +torch/include/ATen/ops/_convert_weight_to_int4pack_for_cpu_cpu_dispatch.h,sha256=crWsYSxqmoCOgj5VOWoUkp0BrW78R2p415tGkKKqbNw,1024 +torch/include/ATen/ops/_convert_weight_to_int4pack_for_cpu_native.h,sha256=fofPdIl8fBJmdddCQzyaWX5VdRTwHnmRwubMte4H8Iw,776 +torch/include/ATen/ops/_convert_weight_to_int4pack_for_cpu_ops.h,sha256=Gxq8mfMMczVVXCyf6VqX4ZQRSXQkW7gHRRc66fxleME,1366 +torch/include/ATen/ops/_convert_weight_to_int4pack_native.h,sha256=sHaYxqPr2SWJb74zbpqL2ECuKgYS8DM0duAQvoOZoQ4,777 +torch/include/ATen/ops/_convert_weight_to_int4pack_ops.h,sha256=Y2bhIULr9GBS96v9m3HKWvZ2pVT1--siycwbmwVLJsc,1342 +torch/include/ATen/ops/_convolution.h,sha256=3auCvvpmqx0E3g1ByQB-sVS1IW-ZD0PL6iNAv0ZMjQw,13232 +torch/include/ATen/ops/_convolution_compositeexplicitautograd_dispatch.h,sha256=RvzdIzZAg8olya3lONwzCC9NhoYy-tIOMqUOV4UZ2nY,3201 +torch/include/ATen/ops/_convolution_compositeimplicitautograd_dispatch.h,sha256=n4Gk9OcpOYERvsmJ7rj3OEujPyFnkf7ROxCQM60UPKA,1639 +torch/include/ATen/ops/_convolution_double_backward.h,sha256=_d8lQqr7QeWHcW49ZgkF2UUO0ZAnt21semHW6hj0Hac,4289 +torch/include/ATen/ops/_convolution_double_backward_compositeimplicitautograd_dispatch.h,sha256=3MP4QuWcx5N9tIwlsCMWFPizxWU_9tOB6EqZPke0rcY,1909 +torch/include/ATen/ops/_convolution_double_backward_native.h,sha256=CL3sWzZYuj-thybC1EDA25szJppDWRK1kiT44Dad_TU,1135 +torch/include/ATen/ops/_convolution_double_backward_ops.h,sha256=Yf4rrQMZlDleevdEdS2ANOAslAl1CXyrKw23BTbNpsM,2610 +torch/include/ATen/ops/_convolution_mode.h,sha256=6nDUoGLHi7vHwEA6IdaZNOvGZo4oM-hoL4u0NB5_To8,2710 +torch/include/ATen/ops/_convolution_mode_compositeimplicitautograd_dispatch.h,sha256=I-SFmVpM5P64X59qw_lyf9ORMJxhijOyg_2fwCp8xhU,1437 +torch/include/ATen/ops/_convolution_mode_native.h,sha256=mrxLJmT8HQZMGokfQ2KF3eI2tOhfyOgUS7bvYKEhDo0,922 +torch/include/ATen/ops/_convolution_mode_ops.h,sha256=jXbkXUt0XhqpcV1ICWfbrbyIjjkGxIEHuqiJDuPr3nA,1816 +torch/include/ATen/ops/_convolution_native.h,sha256=6mrBYsun3KF8GVe1iQQ5SAIzeWW7_fRe3rAxle4Rv0E,1739 +torch/include/ATen/ops/_convolution_ops.h,sha256=Bd3M7Ww3z4Kxa8QKSsmLE4ZRjxkwccGlGCEX8kL2Vxk,5327 +torch/include/ATen/ops/_copy_from.h,sha256=pDJW1q2oJddNVYBbH6Khi-D7WoSraBu1TGAVyUSd30g,1630 +torch/include/ATen/ops/_copy_from_and_resize.h,sha256=8udbMt8r-DoM-Y6YFXn86kUXPUDM7CWC5ScKD4Hu-i0,1554 +torch/include/ATen/ops/_copy_from_and_resize_compositeexplicitautograd_dispatch.h,sha256=szedXNusDjSX5t-Cfxz24hTN54tB7dZjQM_33L22_bU,1199 +torch/include/ATen/ops/_copy_from_and_resize_native.h,sha256=PaLHyphbbxbd2eQ2tttTnUOiHrbrk69slap1McuzECk,793 +torch/include/ATen/ops/_copy_from_and_resize_ops.h,sha256=Q02ezptAzTTRSotMbaOPosW5f4tywYkVh8AaNce9hyw,2051 +torch/include/ATen/ops/_copy_from_compositeexplicitautograd_dispatch.h,sha256=i7_6r8WmqkVWCVKVT3UEKUZgZsfOVs2xZq2lYzVih-M,1221 +torch/include/ATen/ops/_copy_from_native.h,sha256=pt_tBlRzrTiWX2DFeXj5EOUMYVpmAE7HQ-tJTaiCfbE,801 +torch/include/ATen/ops/_copy_from_ops.h,sha256=Tsegewq3PeolieA3ynHK8vmbye625Pqivg9xkEifdeo,2123 +torch/include/ATen/ops/_cslt_compress.h,sha256=qTrF7uvH9q7PXTCMyHWuk1qL6qTgeTmZR3cJMLaJOX0,926 +torch/include/ATen/ops/_cslt_compress_cuda_dispatch.h,sha256=-4ZSi06rU-L55Wu-8LxXTGr1u2MRItxo1eTvYFqIUUw,985 +torch/include/ATen/ops/_cslt_compress_native.h,sha256=BVEnYUmbQpcKk4i1_zxkR6YUlJT4vigw2U2qIOs5UFI,739 +torch/include/ATen/ops/_cslt_compress_ops.h,sha256=D7Nqx2ZSGn8r36tFVtnLFiSwPIqSZY-blp9NN_1IqKs,1238 +torch/include/ATen/ops/_cslt_sparse_mm.h,sha256=rA6OUpZpjv6ARg30nrq9Lh4nQkmvro_qW7-n-EqXWnU,1463 +torch/include/ATen/ops/_cslt_sparse_mm_cuda_dispatch.h,sha256=V8DiN2dfGhFs20FPkM3fUg1M3RVeMvwku0E0O9cMX_w,1261 +torch/include/ATen/ops/_cslt_sparse_mm_native.h,sha256=AeTRHqCUFWaIyYf_fjTt465KRij9hzYkBiFCgG1HCis,1015 +torch/include/ATen/ops/_cslt_sparse_mm_ops.h,sha256=shSaNCBa5K1zQL-Lpy77l9BLIO_-TLnhOU-Pwr3TFIo,2052 +torch/include/ATen/ops/_cslt_sparse_mm_search.h,sha256=6GtENsF_a2eXdkQdYHcgrM3j8JwI5SGFofE3qwZYTNI,1342 +torch/include/ATen/ops/_cslt_sparse_mm_search_cuda_dispatch.h,sha256=dJGjzjCsXvBaKotlwl4dh59LIpwvvMatDzMAMeYj_uE,1203 +torch/include/ATen/ops/_cslt_sparse_mm_search_native.h,sha256=lEuNQVGKAsgM_Ciii5MKDfEmUbZQMOwPRrNCQ1QoxBo,957 +torch/include/ATen/ops/_cslt_sparse_mm_search_ops.h,sha256=zDzWYINV3cnFXCAdvJ0uuS4u1niPwzkAtbhp01aN4XM,1874 +torch/include/ATen/ops/_ctc_loss.h,sha256=hxqHNrx2XCzsh66yks_dGkvo4bEA4FcAcGzq118kASg,4181 +torch/include/ATen/ops/_ctc_loss_backward.h,sha256=u1xL7bKDbN5I5eTm8rUzI6zyuUbN_me-rLhhfQ2SydU,3564 +torch/include/ATen/ops/_ctc_loss_backward_compositeexplicitautograd_dispatch.h,sha256=2uAknJCSIhVo3l3yqkkkZVwdg1DNGrJum5d75uG5iPA,1601 +torch/include/ATen/ops/_ctc_loss_backward_cpu_dispatch.h,sha256=tQvxXUJqOC1khhpyuUIGPUWnQ6SWxecCYjIwQOVtZc8,1520 +torch/include/ATen/ops/_ctc_loss_backward_cuda_dispatch.h,sha256=1hqPL0Pc8KUXJqwBpqzgAV7dRyMuNTflUjKV8j4PC40,1522 +torch/include/ATen/ops/_ctc_loss_backward_native.h,sha256=juUH-nqtsgW7cIcVMVXgXkCAnAhofVIWRQBn5Kkko-I,1900 +torch/include/ATen/ops/_ctc_loss_backward_ops.h,sha256=YccJeFoP1gQ4g4FYGH2SgrzWNndJGCUWtJSklpt_ZZc,4663 +torch/include/ATen/ops/_ctc_loss_compositeexplicitautograd_dispatch.h,sha256=J_4ShbyWtk3RubHjuPFhcXKC9VWBxiyFCAVF7kTSnC8,2030 +torch/include/ATen/ops/_ctc_loss_cpu_dispatch.h,sha256=KRPTeCeJ9nWdgK-FIsvmqvtJLCmb2JQEzJF4ccKHRTw,1368 +torch/include/ATen/ops/_ctc_loss_cuda_dispatch.h,sha256=E_GQ51VdoSHuIIKCyK7LxSCgzWZJRzoQY9-jnVB6DPk,1370 +torch/include/ATen/ops/_ctc_loss_meta_dispatch.h,sha256=W73IJbx1BT4OC9yeF9BaqQcoBMVRPh5mOs3xHts0BsU,1143 +torch/include/ATen/ops/_ctc_loss_native.h,sha256=fNlM1OaZdffvlgiTUrFeLjTKVGOjCrBij_u3E6PTKCE,2113 +torch/include/ATen/ops/_ctc_loss_ops.h,sha256=0Xd4cwR12xsf0ltk6FvnLMLqv3Sbk0WCrG3w-M-55jw,5248 +torch/include/ATen/ops/_cudnn_attention_backward.h,sha256=OzaadgOnD2VVZiUKo3Lyt_iqSDQic3fJLhYMGZD31Dg,4508 +torch/include/ATen/ops/_cudnn_attention_backward_cuda_dispatch.h,sha256=q6zIR38mHzaY9eH71ozTOv8-WLEtkgvGBzKwi1qG1LA,1955 +torch/include/ATen/ops/_cudnn_attention_backward_native.h,sha256=Pft_AcyOQgxgw521KMUZCuWryx9HfL91NwHt5YH9LSw,1185 +torch/include/ATen/ops/_cudnn_attention_backward_ops.h,sha256=lVenysf5Um5_aGWv2dOruaDNlyRa9qupWbQdQvW2w2w,2698 +torch/include/ATen/ops/_cudnn_attention_forward.h,sha256=9DJdeNvc7xPrQNuq2slad7AZXnRAQcFpC1ZRYttOkLY,5417 +torch/include/ATen/ops/_cudnn_attention_forward_cuda_dispatch.h,sha256=xRPnJWTYIc5zj3dbYiH-1L-vWP_tQhZgS4FN7PEFId4,2227 +torch/include/ATen/ops/_cudnn_attention_forward_native.h,sha256=_20Vjw_j0ADzAeyRxNQCsyje_FJf-uSJ_BXhZvceQn0,1321 +torch/include/ATen/ops/_cudnn_attention_forward_ops.h,sha256=mnnWBQ2_sOHSe-RYi2lGuSi01E77TBU8knL75SWcwCQ,3198 +torch/include/ATen/ops/_cudnn_ctc_loss.h,sha256=nAgADceZjhVsA8XgoLe_q4TXhMHovuw3J8dwKdKNc3E,3189 +torch/include/ATen/ops/_cudnn_ctc_loss_compositeexplicitautograd_dispatch.h,sha256=QUF-5of97XiGsDqL_h7KL5v2ctGfv33TFhJDb5du2ig,1535 +torch/include/ATen/ops/_cudnn_ctc_loss_cuda_dispatch.h,sha256=43FN93b7zLxCw3N6jX4fuJWnBH9mTsKpSGRBS69isVg,1406 +torch/include/ATen/ops/_cudnn_ctc_loss_native.h,sha256=t8ayfKbh2QizjHxt0cC6XVyqJel7eCDlYs7GUfHowhg,1452 +torch/include/ATen/ops/_cudnn_ctc_loss_ops.h,sha256=KCpHIHOnTUt7cdvEnBctpoosuhCRLo94PbFqkgpDXsw,4235 +torch/include/ATen/ops/_cudnn_init_dropout_state.h,sha256=hJyo-naI6KsTKGSZa7rnxrdCfReBPfUrqLydQB7XyaI,2503 +torch/include/ATen/ops/_cudnn_init_dropout_state_compositeexplicitautograd_dispatch.h,sha256=yJLLK4yefNBK9RGsZHCpqOQhl2sO2FvSrrC6JWPvwQ0,1209 +torch/include/ATen/ops/_cudnn_init_dropout_state_cuda_dispatch.h,sha256=L4EaPrI__6ShcU5YaHpCAmg258C3ztxYCJu8crGAx7o,1290 +torch/include/ATen/ops/_cudnn_init_dropout_state_native.h,sha256=R9LqorAehoTFWS2kVkzOlacz9BLhdw-5S6oTnlIcjgw,1053 +torch/include/ATen/ops/_cudnn_init_dropout_state_ops.h,sha256=h7vcoHuTjB8Oqx25E9AVZgFtQ42SeoQOF_weLiUgtmk,2582 +torch/include/ATen/ops/_cudnn_rnn.h,sha256=_9h24m4R8CcUzV-oHQLwwFYs4Q95c8n7hMLN2QhSqJA,13597 +torch/include/ATen/ops/_cudnn_rnn_backward.h,sha256=6MPc7MQ7WB-Ypc3lQMlyPhK_vXZmMJKXBqwOON6jFnA,16712 +torch/include/ATen/ops/_cudnn_rnn_backward_compositeexplicitautograd_dispatch.h,sha256=CFMxzWsbRdZ9YCESUaleDp_ayJ9MTKN9lzbkbJh4fNI,3936 +torch/include/ATen/ops/_cudnn_rnn_backward_cuda_dispatch.h,sha256=N7ysay-6ViX1RxiO16TF4se-Xd6fQwPFN9tCh2srPMM,2379 +torch/include/ATen/ops/_cudnn_rnn_backward_native.h,sha256=ArkPkbugVJfW10oONGQ4fye0_h8ZBNfdAREow9YnJpw,2147 +torch/include/ATen/ops/_cudnn_rnn_backward_ops.h,sha256=dGt8jwIWS-bugalOABRzrWhHWJsPjI0t76u0XD-ow68,6215 +torch/include/ATen/ops/_cudnn_rnn_compositeexplicitautograd_dispatch.h,sha256=QaQv-hyg1U9y1OD0MHC3KIE7CfeSWm5tWQItG93kXyU,3420 +torch/include/ATen/ops/_cudnn_rnn_cuda_dispatch.h,sha256=oOwpaV-RHiGDcH1m4bxFuzCb5FNP7ZOF75eG11f9LdU,1931 +torch/include/ATen/ops/_cudnn_rnn_flatten_weight.h,sha256=og2KovZnaRrnbEBQCeLPCrS6k3QrX8BqdyzGofik1vw,7838 +torch/include/ATen/ops/_cudnn_rnn_flatten_weight_compositeexplicitautograd_dispatch.h,sha256=rn5EvbHxUswehYnNUjm4pYYU6zHyKsSZ-fgv_zuRgvg,2024 +torch/include/ATen/ops/_cudnn_rnn_flatten_weight_cuda_dispatch.h,sha256=w3407R86rGJiE-XL5WyNj_LtIp9fm06qw9Mc5Ml8ofc,1403 +torch/include/ATen/ops/_cudnn_rnn_flatten_weight_native.h,sha256=9284SeZWDMCOh2OfqWpZ-CpBv5St7tRtN7ls-Hp94Os,1181 +torch/include/ATen/ops/_cudnn_rnn_flatten_weight_ops.h,sha256=4cFcdJbq7Kuz_C6gweag5kOBVaANNuw4T-NkvzVC7GY,3041 +torch/include/ATen/ops/_cudnn_rnn_native.h,sha256=jL4LxWlkeT7ys_3vy-kp2fOXnqYSzjLCgnlhPn3RGXo,1794 +torch/include/ATen/ops/_cudnn_rnn_ops.h,sha256=OsVPj2AqRBfeDWxugUUFiHMQsu-yhkqm6zjLDgNMSVU,5128 +torch/include/ATen/ops/_cufft_clear_plan_cache.h,sha256=ZZC4WBBuxAITnBhD3UGB2VPGk4ia-1DFGbpZLo35VKg,975 +torch/include/ATen/ops/_cufft_clear_plan_cache_compositeimplicitautograd_dispatch.h,sha256=wOA17ABLp4_Lu5R6ILOdAtI5OmsloBxhosD3WlKWcrc,1034 +torch/include/ATen/ops/_cufft_clear_plan_cache_native.h,sha256=U4chjMHkmSw1chMIPO4BhjQIEkHCHjST8CG39bYnQB4,746 +torch/include/ATen/ops/_cufft_clear_plan_cache_ops.h,sha256=gGAH1J-EfcXJ48t_8DdFIycDDb2AGMSDnBsSsLgQI2Y,1260 +torch/include/ATen/ops/_cufft_get_plan_cache_max_size.h,sha256=ymozapyrEoZqfcAXp5J7jTrIw_LLlaTlfhncSVwIP4g,1007 +torch/include/ATen/ops/_cufft_get_plan_cache_max_size_compositeimplicitautograd_dispatch.h,sha256=q4bkX5P29uU9IzWHj-cuI6568WwK9euGiKAzf1kOOtE,1044 +torch/include/ATen/ops/_cufft_get_plan_cache_max_size_native.h,sha256=TjXJSwsOzS6vRXxtyjVIqgla6PzeCkQ5SF_IH6GmepU,756 +torch/include/ATen/ops/_cufft_get_plan_cache_max_size_ops.h,sha256=verPE2PINzX8oiC3hknhMJr2RZZPeVkF3izyGwu97QI,1291 +torch/include/ATen/ops/_cufft_get_plan_cache_size.h,sha256=-EZ0PTwuwqcKBzjmPNwhs9QTxm5DDcCXqX9UJhnjfEo,991 +torch/include/ATen/ops/_cufft_get_plan_cache_size_compositeimplicitautograd_dispatch.h,sha256=W_Wt4a9r0eAvQL0OC2ffXdx452RU3VzAdgiAIdcNhB0,1040 +torch/include/ATen/ops/_cufft_get_plan_cache_size_native.h,sha256=dSzhi1Y4jkQDuh-6EkfJrrx_qyq7-IhhErI5eqa9KKs,752 +torch/include/ATen/ops/_cufft_get_plan_cache_size_ops.h,sha256=ZC1gL0T01MAIPte9nPZaXdyxpJf-XiVNowkwwI6DPqA,1279 +torch/include/ATen/ops/_cufft_set_plan_cache_max_size.h,sha256=ys2B7AIeGCnoyZYwz-YzO3vrJrm4R7yUW9RRDT1XIq4,1045 +torch/include/ATen/ops/_cufft_set_plan_cache_max_size_compositeimplicitautograd_dispatch.h,sha256=OVP6gALGbiO_BxkxjJc4sxI7E76r93VeNTw4cDe1WyY,1059 +torch/include/ATen/ops/_cufft_set_plan_cache_max_size_native.h,sha256=FL4dZmSLhg_7xhR_G5oPKtnMytQg2ABKzeI6-F9SDBo,771 +torch/include/ATen/ops/_cufft_set_plan_cache_max_size_ops.h,sha256=qBoYdkhCWS5ENVpJkHdkRygcmWd9Mphs0Xb5CQFyshg,1340 +torch/include/ATen/ops/_cummax_helper.h,sha256=It9F836ziJSYsDsAu3h5vhtS96tV00nKbAXmVNudlZk,1039 +torch/include/ATen/ops/_cummax_helper_cpu_dispatch.h,sha256=IVGL2jYSDP2txe08RD30GyVr-Joo4ufuyLS8rAGqgco,1032 +torch/include/ATen/ops/_cummax_helper_cuda_dispatch.h,sha256=UO02t4HF8bfgXL1HiyN4RZfmFOFLhjDzC8aUVGSAbC0,1034 +torch/include/ATen/ops/_cummax_helper_native.h,sha256=_VR9YcSzmE9UpdqgSPKylv6EPl26ktrXnd-wF3ncR30,907 +torch/include/ATen/ops/_cummax_helper_ops.h,sha256=oLOa9MUc5Q6huIoOqhNlIhwBotGQESnN_wanw74ZOho,1410 +torch/include/ATen/ops/_cummin_helper.h,sha256=yCIFnbdBIL9rlO4WMGLvLGky01t-W6bdl6CR9MVUgyo,1039 +torch/include/ATen/ops/_cummin_helper_cpu_dispatch.h,sha256=pnqYF6bxThbn_3IHjfnKIN74MR_RtOKO9oEmaKar9ms,1032 +torch/include/ATen/ops/_cummin_helper_cuda_dispatch.h,sha256=nefInjgToYo5_bj36-LOtSx9T37hpZMeQ2SI8rKjmLE,1034 +torch/include/ATen/ops/_cummin_helper_native.h,sha256=k8EbJNzgjSXf6StEOvgBtLEiXnpfpYbaPZHT_wlEpD4,907 +torch/include/ATen/ops/_cummin_helper_ops.h,sha256=jKAW2klA7MjFUFLwEHVRx513RWunsmuks3YaTxNUmhU,1410 +torch/include/ATen/ops/_debug_has_internal_overlap.h,sha256=odlifVaXZdMqmkcQJM9kDLSfKG2ZBFhOJm8vJeQvIpE,969 +torch/include/ATen/ops/_debug_has_internal_overlap_compositeimplicitautograd_dispatch.h,sha256=zo2r-ziwiqKyQ7JB07Ow84GWmPfAg1Qvll8Ks_d2mEc,1036 +torch/include/ATen/ops/_debug_has_internal_overlap_native.h,sha256=uGLy0kkJHzgaU-PulXTxQFvXvU9cwpPqqYFpXFFtwBQ,748 +torch/include/ATen/ops/_debug_has_internal_overlap_ops.h,sha256=s7zczZwzKw_Gm3OtriKUFNXbjwytoVgLTC3CYJ6Pww8,1262 +torch/include/ATen/ops/_dimI.h,sha256=Cx62L7zqnJ3TIcWzT69IrOdxL_-hkuSRqRjgnSLDbeY,756 +torch/include/ATen/ops/_dimI_native.h,sha256=F-t3aPIhLO10H32AqEO27rLoWvHcJ512pSK09Lwqf0Q,738 +torch/include/ATen/ops/_dimI_ops.h,sha256=4vxt9zoyzka_YA9uy_anw9wmijp3z26o8PuIHPurx14,1196 +torch/include/ATen/ops/_dimV.h,sha256=IF5xJLSAwkwPmFgMeiU6WJSbbfKRYDx97L4VipjK3oE,756 +torch/include/ATen/ops/_dimV_native.h,sha256=U0yalBhDzUVuQ-E1QnVSH2smn3nJnlRO9BQKsIhxh2g,737 +torch/include/ATen/ops/_dimV_ops.h,sha256=LNnX6fTC8jG_IaO9S9h9gvy9Dh_6Z0jVzdPcPdW7VEw,1196 +torch/include/ATen/ops/_dim_arange.h,sha256=50Va0IxTAjs9UPuOA2qHugOTRDEws_xgbPkmmtagkXo,938 +torch/include/ATen/ops/_dim_arange_compositeimplicitautograd_dispatch.h,sha256=ojMc5z0W0_9nRgI4KCcTUl4Qp_tqlvG5W3lZhiBQoIk,1036 +torch/include/ATen/ops/_dim_arange_native.h,sha256=-3e4A0sXzfZB-y8gvGbG1S2hR2cCd2Jkk2IfPX5LmZw,748 +torch/include/ATen/ops/_dim_arange_ops.h,sha256=CEremvxrEYml_NqzZWqzxEEfxKgxzf4Zdfsh6rt-XZw,1270 +torch/include/ATen/ops/_dirichlet_grad.h,sha256=qVuIXEe_nijryVN3K2HAk-1VC_OuNvXOL5IVka31vuU,1626 +torch/include/ATen/ops/_dirichlet_grad_compositeexplicitautograd_dispatch.h,sha256=H65Fllj3pol3go4cBOxdqHp83gWtZcuQg5sVoIO-_XU,1237 +torch/include/ATen/ops/_dirichlet_grad_cpu_dispatch.h,sha256=eav3KrAAS2FUim-nebCTnIUlOTi6NDujp_H4d6Lyrtg,1032 +torch/include/ATen/ops/_dirichlet_grad_cuda_dispatch.h,sha256=UzHzrCRJz4w4X1V9ZA31goGMmICizge_g3a-bqLSmmk,1034 +torch/include/ATen/ops/_dirichlet_grad_native.h,sha256=aTVnxksJA3NbWO4yqmcYulnZtBHcS5XaOdvnheFCJN0,1045 +torch/include/ATen/ops/_dirichlet_grad_ops.h,sha256=mb88CbtgAAbY3N4Z4CsjQosY1eFQA6xtnmT4_izMyds,2181 +torch/include/ATen/ops/_dyn_quant_matmul_4bit.h,sha256=CuW3ucyBZkGAhBw5J0hkKjYpPNeiwcWlgJjwCaLBuJ8,1179 +torch/include/ATen/ops/_dyn_quant_matmul_4bit_cpu_dispatch.h,sha256=Jjg6SbeD7EUpzv8XCiOPghwl4Z_sABrMi1DhE6bN1qw,1087 +torch/include/ATen/ops/_dyn_quant_matmul_4bit_native.h,sha256=_FtksKJhpqqFkrluXxrkEo4WcTD5I6-oOm95b_lcSgE,847 +torch/include/ATen/ops/_dyn_quant_matmul_4bit_ops.h,sha256=G0eRfu340uhLQkecwQKJukV7-awcYgov1QWmvh3BHmA,1573 +torch/include/ATen/ops/_dyn_quant_pack_4bit_weight.h,sha256=OWObLMDe7Ux7PbzSrIWLOpNxLgQ7CIdUS9KiUwKy7Vs,1267 +torch/include/ATen/ops/_dyn_quant_pack_4bit_weight_cpu_dispatch.h,sha256=ayVeu3na6MVdsyTDNMipiAX2i6sSh0sb95M6tL9otNs,1136 +torch/include/ATen/ops/_dyn_quant_pack_4bit_weight_native.h,sha256=iKQkYVRsHNGiZcNE4VxWBhw041_sMsPnITh-tPiJrCs,896 +torch/include/ATen/ops/_dyn_quant_pack_4bit_weight_ops.h,sha256=M7LD3PzL9U0gzWKlCzjkaPjTdMF9Uyn01j1rrDZh7LY,1729 +torch/include/ATen/ops/_efficient_attention_backward.h,sha256=MVnKPjlpEf1wKxVC9sxhBJEE-mJEO0uVARpmiWSZE0U,6238 +torch/include/ATen/ops/_efficient_attention_backward_cuda_dispatch.h,sha256=XUMj2TNH42Yvw8D9qbMWrfsO2BtLCPNYCTbaUpwAxKA,2475 +torch/include/ATen/ops/_efficient_attention_backward_native.h,sha256=z-V_tH8B6yhH9-V3kG3ICw_SVEHq9ELxt1I3Py5q_54,1445 +torch/include/ATen/ops/_efficient_attention_backward_ops.h,sha256=bFYFkY5NCtNsdoGpWbuiF7_IMoywCFzvku0fRp4pJrk,3420 +torch/include/ATen/ops/_efficient_attention_forward.h,sha256=cHYPjuU2GxQWwCC__rLYYf3B6l7TySf6lL--kSlQ5fs,5659 +torch/include/ATen/ops/_efficient_attention_forward_cuda_dispatch.h,sha256=9tQLaJ59jwwgUFhcu94KMcLh1gccpfUL6jRqcsSVEbQ,2219 +torch/include/ATen/ops/_efficient_attention_forward_native.h,sha256=BZIphbOtsVo6Q6Au_hR3uw9-B8bAdNVRr3XhXmaPWGY,1317 +torch/include/ATen/ops/_efficient_attention_forward_ops.h,sha256=TFeiO38vvhRifGl0mHDKdrwgeSLnsBaUSUXXCcax1RQ,3128 +torch/include/ATen/ops/_efficientzerotensor.h,sha256=9Q3R0P_EnmdX27hy_SMN5Rmb6c7BI7RbmF90YUy1Ve8,6294 +torch/include/ATen/ops/_efficientzerotensor_compositeexplicitautograd_dispatch.h,sha256=62zWmeMSVAC7xEYI0lbcK_OcGfjpwdV2JoUGjJLAeJA,1344 +torch/include/ATen/ops/_efficientzerotensor_cpu_dispatch.h,sha256=eFrsnXh8Ehz0nrZV-_u6lemsOo6FKIyv0tGjh4KIrTM,1552 +torch/include/ATen/ops/_efficientzerotensor_cuda_dispatch.h,sha256=E0jAaKF067A7ehNcSxkc_u5AXoDKs4JtEtCH1z-P4Tk,1554 +torch/include/ATen/ops/_efficientzerotensor_meta_dispatch.h,sha256=vdpSqeBXNIufJ0E2f8-rv8TuvBJWVN9dXT3tRC09HFk,1554 +torch/include/ATen/ops/_efficientzerotensor_native.h,sha256=5AnXWOnBkqQTlT8ELj0pIkiilGQpymcEveELZK9ojZI,1463 +torch/include/ATen/ops/_efficientzerotensor_ops.h,sha256=x01MQTGXpxy5CDpFEVs7x8AWz334sWa5kO2BFvEysmU,2391 +torch/include/ATen/ops/_embedding_bag.h,sha256=-GZ6pdJ7VgIklM6PjzNeDYFvkzqJYWGf-eTzh4h6I-s,3432 +torch/include/ATen/ops/_embedding_bag_backward.h,sha256=NJ5Sw_KxRhU2G5PQ9K6vzVdOF50ckh515nyxreWBdpI,3804 +torch/include/ATen/ops/_embedding_bag_backward_cpu_dispatch.h,sha256=xrvnd9GImT7-v44gRFBCb6n6xZq6obYA53ChV4_hOsM,1683 +torch/include/ATen/ops/_embedding_bag_backward_cuda_dispatch.h,sha256=r6CUqnPsatki51BarUvtr6xAWm8WcNFQbUC8PaCSxw8,1685 +torch/include/ATen/ops/_embedding_bag_backward_native.h,sha256=Rw7xGFq0385Y4ggVKNRLcG0lj-biH2ROXCNLdYHUuVY,1063 +torch/include/ATen/ops/_embedding_bag_backward_ops.h,sha256=blLpnpU2cq60urzf8zbibegGVMcb6Qt0RKCzzdpT6IM,2262 +torch/include/ATen/ops/_embedding_bag_compositeexplicitautograd_dispatch.h,sha256=FNXwLTAmUkwgJGN9YQF5fB1hLRRc7vWY-QIGCo_GjvQ,1811 +torch/include/ATen/ops/_embedding_bag_cpu_dispatch.h,sha256=ZhCQc6e_4m0iLXZ6i_5YK7qfInVIBFYxbvX7fYmfUbc,1268 +torch/include/ATen/ops/_embedding_bag_cuda_dispatch.h,sha256=Sl9BH3udbP7b-wuLZEMULarvWIlfGJbsMbnnvQvWJak,1270 +torch/include/ATen/ops/_embedding_bag_dense_backward.h,sha256=MJSUI3hNDGkQ4jOCT-wmy4KkvYuvOVxripcHn6CcrlI,9546 +torch/include/ATen/ops/_embedding_bag_dense_backward_compositeexplicitautograd_dispatch.h,sha256=GhgIbw42JGRTvNuZGxpzbVKzEw9VD0vPclbgKcM0l38,2442 +torch/include/ATen/ops/_embedding_bag_dense_backward_cpu_dispatch.h,sha256=TCeNyY4_qFGMftZ_qLcmDm1f1O1IP1G3HcovYrIqXNo,1613 +torch/include/ATen/ops/_embedding_bag_dense_backward_cuda_dispatch.h,sha256=_PbwxBjfEh-qskR82LUAzeIQZ5wLYj_N04g5ldWG7MM,1615 +torch/include/ATen/ops/_embedding_bag_dense_backward_native.h,sha256=Hd7SnZ--9ooRW_85oifDn6OxZjUh4V2v4k_8fXTRW0U,1740 +torch/include/ATen/ops/_embedding_bag_dense_backward_ops.h,sha256=FZ4L2Od9jrAEolD3GpLTayvlq6ZdodFC6ztaHaJOn4s,3665 +torch/include/ATen/ops/_embedding_bag_forward_only.h,sha256=GPYXLnAS0l-eWm6kC1GDRuP88GOSR0N85gvs9SlfPkI,3562 +torch/include/ATen/ops/_embedding_bag_forward_only_compositeexplicitautograd_dispatch.h,sha256=_gJsOl0wDQhQvNaINsHtYxiFiD8POIelOzsR9jp8WpQ,1837 +torch/include/ATen/ops/_embedding_bag_forward_only_cpu_dispatch.h,sha256=C-RFxQqYC3qxaAw_L3nI-5Meq7XEkog7f1aFZVWB3MI,1281 +torch/include/ATen/ops/_embedding_bag_forward_only_cuda_dispatch.h,sha256=0JYuvVYoH0XmTPHYi8uZBvtyGd_6nrEsh0F61cF8MDA,1283 +torch/include/ATen/ops/_embedding_bag_forward_only_native.h,sha256=mhpf3kXa4tEPOH-RFd3Ghd9WNCdDx4kcCDBBx8YGEWQ,1830 +torch/include/ATen/ops/_embedding_bag_forward_only_ops.h,sha256=xSvOM0TI-v7qDhQGdncW_XafU7OE1luBjcSqf4-YbX0,3941 +torch/include/ATen/ops/_embedding_bag_native.h,sha256=pzuBiDXZZG54qIbFmylElJwE-B1ipJqh9IcNTUURBVY,1791 +torch/include/ATen/ops/_embedding_bag_ops.h,sha256=3fSeu07m5HCNrXE_N-qWmgsumeUElpDwArGBXU8754g,3863 +torch/include/ATen/ops/_embedding_bag_per_sample_weights_backward.h,sha256=tdZxxvkkSwc2Jb7S9YvFKILki_tiMQ9wpJCGQvR7TC4,2553 +torch/include/ATen/ops/_embedding_bag_per_sample_weights_backward_compositeexplicitautograd_dispatch.h,sha256=ZLQt0xFlv_ahOMYd_m8hy_G417OIYgaPnPTKe6DsxY8,1494 +torch/include/ATen/ops/_embedding_bag_per_sample_weights_backward_cpu_dispatch.h,sha256=EL34PhlVUOCs10Mg9rVA04VaiUPeCXcjvV_ghLw-lMs,1162 +torch/include/ATen/ops/_embedding_bag_per_sample_weights_backward_cuda_dispatch.h,sha256=XDlOD1I-ZDH096Opw9HobMj-Groz_QlL9cde2gLoXRA,1164 +torch/include/ATen/ops/_embedding_bag_per_sample_weights_backward_native.h,sha256=c-uiha-2DiY0L0xGUm-6rT93mbeSbmhpqdyRV4Eezrs,1432 +torch/include/ATen/ops/_embedding_bag_per_sample_weights_backward_ops.h,sha256=s7sXZWM8OnhCiEAT2yZQynwZe8eYjV4OyHOLzEF9uGo,3001 +torch/include/ATen/ops/_embedding_bag_sparse_backward.h,sha256=NTiAVTGLW4GPfjzQK9AfaNx3f5GVREv4PXvhbsxgQx0,3511 +torch/include/ATen/ops/_embedding_bag_sparse_backward_compositeimplicitautograd_dispatch.h,sha256=IFx_v4S7J_8ckaT1Arct3PXxxCcsKcaJcP1B5x8VDJQ,1643 +torch/include/ATen/ops/_embedding_bag_sparse_backward_native.h,sha256=sTHY4G8VfeBT3T4umm7iMH9BqZvUdMd2RFjDSrhzZsk,1021 +torch/include/ATen/ops/_embedding_bag_sparse_backward_ops.h,sha256=oEmN4eprf_CxlAA5mkyEE2mNe3Oiq1ymUMBUY7Vujq0,2122 +torch/include/ATen/ops/_empty_affine_quantized.h,sha256=4LyPSMoy-FwF-uZCo7IQJABNhyhdV7qsP5CVtQ6T7lg,9473 +torch/include/ATen/ops/_empty_affine_quantized_compositeexplicitautograd_dispatch.h,sha256=q3f5beVH5kQqLp_jxFejar6YtvYHWZV10Jh3nsVCv84,1756 +torch/include/ATen/ops/_empty_affine_quantized_cpu_dispatch.h,sha256=GBzcPHvSRpDo25VOic0dD7fy8Gpe_ERxdYLzOslP5Zc,1964 +torch/include/ATen/ops/_empty_affine_quantized_native.h,sha256=NYKnX5S6yRHvhIgfNe2grdf14YXnw8iPOqUJrrq2QT0,1564 +torch/include/ATen/ops/_empty_affine_quantized_ops.h,sha256=DtaVTfee2CL_sHPG0k0J_UxU_iaclVymshoveaKdSzc,3005 +torch/include/ATen/ops/_empty_per_channel_affine_quantized.h,sha256=tCRs5RrCO7pd_KqtE87N1Im4nXUrUKg3u414CtRTVV0,10781 +torch/include/ATen/ops/_empty_per_channel_affine_quantized_compositeexplicitautograd_dispatch.h,sha256=eYsRCX0CCUEpUWIi7AYslCxR7D9lqgMyRvWmsUZ88XI,1952 +torch/include/ATen/ops/_empty_per_channel_affine_quantized_cpu_dispatch.h,sha256=PgAWsJGHWAp4Rk-WU6PbQgQ029gWZVJDfEOzo3ol3So,2160 +torch/include/ATen/ops/_empty_per_channel_affine_quantized_native.h,sha256=ReCG3ckv-uPpPWsZiqxRukdL-Rhslgof9X6OYAGz_x4,1709 +torch/include/ATen/ops/_empty_per_channel_affine_quantized_ops.h,sha256=c5QBjpab_cKDm7VxIb_s4fh9K5ht0xvu5i1hwSw2OlM,3321 +torch/include/ATen/ops/_euclidean_dist.h,sha256=XPELByV84weaRT5wb2NnFU19LlGbWMhDhNyVjltiY74,1467 +torch/include/ATen/ops/_euclidean_dist_compositeexplicitautograd_dispatch.h,sha256=st9pYJzsV0ja8IEEuPtQGB3nnpkYDPgxd6eaPdsn1Iw,1265 +torch/include/ATen/ops/_euclidean_dist_native.h,sha256=OPNt5RmKW-2qrLTNOLrY57bcgPiifNmmXJ-3RuDGYuQ,868 +torch/include/ATen/ops/_euclidean_dist_ops.h,sha256=J9XjRcmvZEkoR_slwFGZgXPIWlyyLWxmiWSLbyA3sa0,1997 +torch/include/ATen/ops/_fake_quantize_learnable_per_channel_affine.h,sha256=ZJGPuaSavLVzgpOG7gxbdNchhiQNE9_ybk001tPctyw,2514 +torch/include/ATen/ops/_fake_quantize_learnable_per_channel_affine_backward.h,sha256=hHw5MALf5AB_O3X5YoobKltAnfJmqdUI9SL_IEYiRac,1462 +torch/include/ATen/ops/_fake_quantize_learnable_per_channel_affine_backward_cpu_dispatch.h,sha256=YxYavfm4XyFlyePswco2f5Jv_3waaIFguDToWDam0o8,1214 +torch/include/ATen/ops/_fake_quantize_learnable_per_channel_affine_backward_cuda_dispatch.h,sha256=QpFbTiLiFR_VHOiUive07zO323W5fSD0sOk8D7Uh2rM,1216 +torch/include/ATen/ops/_fake_quantize_learnable_per_channel_affine_backward_native.h,sha256=9D9FXJ8vykwyoQScen8J6R1KSYBeLOiwtFswsbZWAB4,970 +torch/include/ATen/ops/_fake_quantize_learnable_per_channel_affine_backward_ops.h,sha256=MpHWhN5M0HzQ188h0NERVGPgwaLVsl2Y3k7OAb-i9A0,1987 +torch/include/ATen/ops/_fake_quantize_learnable_per_channel_affine_compositeexplicitautograd_dispatch.h,sha256=VhI2U3Ezz9nTRmCcqGHAAtyby-7qwZ0ZWiU070ZD9vA,1457 +torch/include/ATen/ops/_fake_quantize_learnable_per_channel_affine_cpu_dispatch.h,sha256=v4N9BDpFenkmLT-gMiEWhRdtI7pWlg_EsNK8is4-vHo,1144 +torch/include/ATen/ops/_fake_quantize_learnable_per_channel_affine_cuda_dispatch.h,sha256=-vrAKuz3HHpzjyZLT-OsPNlwaZDUBGUkPqJMYKbo8IA,1146 +torch/include/ATen/ops/_fake_quantize_learnable_per_channel_affine_native.h,sha256=57dwJvkMruko0G3Aw767Faz3fbFktVo4Cobvc-jd_ls,1144 +torch/include/ATen/ops/_fake_quantize_learnable_per_channel_affine_ops.h,sha256=Mivsy0rLR2NDv5xVkRTfbNSP1f5Tia7_D7a1y2FAe84,2881 +torch/include/ATen/ops/_fake_quantize_learnable_per_tensor_affine.h,sha256=as4jcG_npOdTWLIlwIIsydqi5TyG6zMn1DEipQKYEJE,2414 +torch/include/ATen/ops/_fake_quantize_learnable_per_tensor_affine_backward.h,sha256=HB5GrByPw-ayrBxSsorhb8BRCI7jgG_pj63Qsfp4EGo,1428 +torch/include/ATen/ops/_fake_quantize_learnable_per_tensor_affine_backward_cpu_dispatch.h,sha256=LW4QWW9iiHe84LkOBxYDrlcIwi1G41TP6M-ING6yQS8,1199 +torch/include/ATen/ops/_fake_quantize_learnable_per_tensor_affine_backward_cuda_dispatch.h,sha256=Ezc77DMKXV9E0XAAIIIC_3xtOcaYbze52pWt1jrl2Vk,1201 +torch/include/ATen/ops/_fake_quantize_learnable_per_tensor_affine_backward_native.h,sha256=Cxv-XMyYZoTVIX7eDCMfEH_JVu16X9VgEW2MrJx7tCY,955 +torch/include/ATen/ops/_fake_quantize_learnable_per_tensor_affine_backward_ops.h,sha256=x0fQggJ-WcY4Jx_5fH1Im1if3UqZq8wKtgMr3jedp90,1937 +torch/include/ATen/ops/_fake_quantize_learnable_per_tensor_affine_compositeexplicitautograd_dispatch.h,sha256=RyY2XkPaq556mq6vm51XmtVByEuGrMYH0aTo7n3EDlY,1427 +torch/include/ATen/ops/_fake_quantize_learnable_per_tensor_affine_cpu_dispatch.h,sha256=pEZLfN2mtqQ2xzHQFMOeT5mDWrUE_yijT0_a1YRsmdk,1129 +torch/include/ATen/ops/_fake_quantize_learnable_per_tensor_affine_cuda_dispatch.h,sha256=yn9e9wBdeYLLD3JBld7-RypHxXW4LejZeSouq_F_6Ws,1131 +torch/include/ATen/ops/_fake_quantize_learnable_per_tensor_affine_native.h,sha256=GWdKLVqgzmKl_QzULxxobEDuqMGvX47ICYgdDK5cunM,1114 +torch/include/ATen/ops/_fake_quantize_learnable_per_tensor_affine_ops.h,sha256=vfCXW13QszoJtoHlLSdMTBQlLnIitFw1DdrlNWJ4SGc,2781 +torch/include/ATen/ops/_fake_quantize_per_tensor_affine_cachemask_tensor_qparams.h,sha256=dDW6dGNEMXPhWkzcxVcZgacp_GbraVSgZE3gwhhaCtA,2865 +torch/include/ATen/ops/_fake_quantize_per_tensor_affine_cachemask_tensor_qparams_compositeexplicitautograd_dispatch.h,sha256=TKvt0C08H8uhvYzRdYaPMINTx0hz7LChgCKwE3uD0uM,1585 +torch/include/ATen/ops/_fake_quantize_per_tensor_affine_cachemask_tensor_qparams_cpu_dispatch.h,sha256=mSrS2uFM9DlRW6OrhUjPyHyHtx519hIo12zfSvbdMEY,1184 +torch/include/ATen/ops/_fake_quantize_per_tensor_affine_cachemask_tensor_qparams_cuda_dispatch.h,sha256=AOR5lDHkbWNWGgxR2G5fCjCGhbEdyMeNtayR3JR-h14,1186 +torch/include/ATen/ops/_fake_quantize_per_tensor_affine_cachemask_tensor_qparams_native.h,sha256=JypsTHDOmK1eDCYhHLQT0vBQ5mHi5j0USc-ZpGMK8jA,1250 +torch/include/ATen/ops/_fake_quantize_per_tensor_affine_cachemask_tensor_qparams_ops.h,sha256=pG5BsRaOxwDB1YdahNx8-w_rwak209X6ooimtK_HExQ,3243 +torch/include/ATen/ops/_fft_c2c.h,sha256=t9eZZrQJSWQPbKAasRDof6LD9jiahSboAyG4LxUeaIA,4707 +torch/include/ATen/ops/_fft_c2c_cpu_dispatch.h,sha256=9MK-rivL7BM3Zpvk35ztxOkjuiJb3MrjspFB5VAqvFI,1735 +torch/include/ATen/ops/_fft_c2c_cuda_dispatch.h,sha256=YfG7ep5cn9YFVJZdCWF95AFcwujFaOH9iKG2M5eiaYA,1737 +torch/include/ATen/ops/_fft_c2c_native.h,sha256=mWU7grU5WQgaUbbhpJ0gRLQpOB7TN17wTleZVROJUP0,1200 +torch/include/ATen/ops/_fft_c2c_ops.h,sha256=hgnrV6Gl4N7Yq-EjG8lhd79E1hMHRQqtlVkxAzEqPE8,2227 +torch/include/ATen/ops/_fft_c2r.h,sha256=sMbYev1IASIs-bpqknrFwXOjZgTIHYRoYfCPz9i9TkQ,4761 +torch/include/ATen/ops/_fft_c2r_cpu_dispatch.h,sha256=JrQQ6k3VhhGqj8a7SHnuLEclmmOOomueaWeuUxnaT4E,1789 +torch/include/ATen/ops/_fft_c2r_cuda_dispatch.h,sha256=LaxvuxAHWJxvtcee1REoNsi9g-pP7T7pDVaEo6Vx3lg,1791 +torch/include/ATen/ops/_fft_c2r_native.h,sha256=OXdFhtOZ7mKVQ8E_jXWrwK8ukH31bAnIsrXj1-Mz3Wo,1236 +torch/include/ATen/ops/_fft_c2r_ops.h,sha256=si7oZH1F5gfVyhf6vQ4vX66xo7MaltbkLLfvRvMzp48,2279 +torch/include/ATen/ops/_fft_r2c.h,sha256=sPc9kbqy7k2AlQ9wieVzTIT1jtaKHP8H2JbbRNOcmFU,1703 +torch/include/ATen/ops/_fft_r2c_cpu_dispatch.h,sha256=IcILr3PMvEioM6-NY3phWeUnG9MmZvHqub5LN1N9J08,1314 +torch/include/ATen/ops/_fft_r2c_cuda_dispatch.h,sha256=3eIssSqvb3L5rMO18fMIGBo_wtvnC4TU-8_6iWUh8Qg,1316 +torch/include/ATen/ops/_fft_r2c_native.h,sha256=vyvmL3RnX-5GrSdifgKasIg_kllEKzSzbxGMwMKaOes,1204 +torch/include/ATen/ops/_fft_r2c_ops.h,sha256=QnjqS5dgWxprVfU0bsmhYCFG4t_8Mr0aT43IWEKh0VM,2203 +torch/include/ATen/ops/_fill_mem_eff_dropout_mask.h,sha256=ui78K-IOF5CCQQcP_NBPdlp9R3-TXYpFeQ3jMZFKhDo,1090 +torch/include/ATen/ops/_fill_mem_eff_dropout_mask_cuda_dispatch.h,sha256=z6FZ0tvGQ_0PhcfB-nF0Ycwte1CclFSfxc11OCVdClE,1041 +torch/include/ATen/ops/_fill_mem_eff_dropout_mask_meta_dispatch.h,sha256=yq7ecW0HOo7zoVhL8QsdA9FFirnhITPag-Urtw18XxI,1041 +torch/include/ATen/ops/_fill_mem_eff_dropout_mask_native.h,sha256=-ku1Qi-aNyOn4mejeWQZ7czydboWWf7Wljv0HX8U1Sw,795 +torch/include/ATen/ops/_fill_mem_eff_dropout_mask_ops.h,sha256=lzJy6QpsfC-nUQDq5LWIVBgzQ7_hHJZUCcJ6t1owJuQ,1431 +torch/include/ATen/ops/_flash_attention_backward.h,sha256=mL4YZFPTHDLs-RIe7uo6LSYDaKZ3Cl9cgrFencVqBhs,5314 +torch/include/ATen/ops/_flash_attention_backward_cuda_dispatch.h,sha256=RAv8Vk5LcMUknovqNroXI5JnN-M_p6zceEtotMD8iIU,2119 +torch/include/ATen/ops/_flash_attention_backward_native.h,sha256=0m3B_3vJ45JneH-4XbFxQgYuyIt-PW8bhq0v-vHzDwY,1263 +torch/include/ATen/ops/_flash_attention_backward_ops.h,sha256=Rjg6IlgQFkpVa2pfe-bxIHVD7AZ9iGLDzIIKCKTx9aw,2886 +torch/include/ATen/ops/_flash_attention_forward.h,sha256=ODLgqoQLjEfgUkLd13Ln87l0pSe7E-D9oY6Ras2wXFI,11934 +torch/include/ATen/ops/_flash_attention_forward_cuda_dispatch.h,sha256=rh-TZV1QZIayHqg8R1cBUDRUDvFnzzlW9jwbeGHQ7WM,3974 +torch/include/ATen/ops/_flash_attention_forward_native.h,sha256=aU8DmvthZn8j6DmkKUO_PzqpRBYUEg7W3-ilShO4518,2189 +torch/include/ATen/ops/_flash_attention_forward_no_dropout_inplace.h,sha256=pJApA3sEKn8V70Lfcj6x4tCfn6mfSQyeMF9abW5ch50,6178 +torch/include/ATen/ops/_flash_attention_forward_no_dropout_inplace_cuda_dispatch.h,sha256=n110ANswz4Qy7o1sfzPBYPFS7nTsibcQsLHAt5ow0mE,2369 +torch/include/ATen/ops/_flash_attention_forward_no_dropout_inplace_native.h,sha256=gfo3SPKcH10DbKTLenWuFllqYpoZtjXrww20osOutb8,1388 +torch/include/ATen/ops/_flash_attention_forward_no_dropout_inplace_ops.h,sha256=LB0pSUQ-uyGy2rHM1qtStEqOYzvaC2HwVN8ks_6o2S8,3222 +torch/include/ATen/ops/_flash_attention_forward_ops.h,sha256=b7YHts8y7DsJ1ezIiQcz5_aTtFA1JqV2BZL7MoLNTRc,6179 +torch/include/ATen/ops/_foobar.h,sha256=OHMlqMu7z_V4xehj__H86Qlz94UKxH6zwuwNszYpieQ,1621 +torch/include/ATen/ops/_foobar_compositeexplicitautograd_dispatch.h,sha256=EX9OMnCcQbR3_-Elc5NgubLUL6nCDlYTgqDDjQiu6-8,1204 +torch/include/ATen/ops/_foobar_cpu_dispatch.h,sha256=reCzEZ9MnpHtxpygrwLN2iqudL9AA20ne7mKiWGIMUg,1023 +torch/include/ATen/ops/_foobar_native.h,sha256=0GVP3RRBvPBHFUlZrABKnqKztv3wL4DCRR6Xwaem_tA,890 +torch/include/ATen/ops/_foobar_ops.h,sha256=YrlYfACiQX7WOTqaaHNWCVODX8GJbPZte52UtzMtisE,2074 +torch/include/ATen/ops/_foreach_abs.h,sha256=H863vI7g-07E_lUN5pDSIGAeZmL6RGz6pp6rPORYeoE,1476 +torch/include/ATen/ops/_foreach_abs_compositeexplicitautograd_dispatch.h,sha256=sqUV-WF32oTQGLusgnH26uIVUK409aiJ22pzGkMXG3k,1235 +torch/include/ATen/ops/_foreach_abs_cuda_dispatch.h,sha256=cnAXMVAXFd8FgOkgZt3xAb8mJIRQ6v6jJ8OcL9okebE,1044 +torch/include/ATen/ops/_foreach_abs_native.h,sha256=cHEe4iXe0JX6QUwPlWOxjK7CFkB_EraPu3dn0zjbXUw,1038 +torch/include/ATen/ops/_foreach_abs_ops.h,sha256=_pTuqBnMrUVhGDTD0pInq3870ObN1TSdpJbtJF6DFT8,2333 +torch/include/ATen/ops/_foreach_acos.h,sha256=mm2QP92RDiVeMpNegL19Ghu0dPkGRQ-0BEPO7RL3o9U,1489 +torch/include/ATen/ops/_foreach_acos_compositeexplicitautograd_dispatch.h,sha256=uSrz49WDHwSExLYI3Pl6BZrivhIstkeKPtaTwZdgzlg,1239 +torch/include/ATen/ops/_foreach_acos_cuda_dispatch.h,sha256=AEVicWLKkERE-cwbkK138wLCqgEO76tMNXnl9L0lt50,1046 +torch/include/ATen/ops/_foreach_acos_native.h,sha256=85Orh43GvNVmePYlaG2q6Jppw6gnCsZzOvkZketB7LI,1043 +torch/include/ATen/ops/_foreach_acos_ops.h,sha256=XeKTKWYH07s8SElwwn_7f29XlYONtQS0wIzfhaBMce8,2342 +torch/include/ATen/ops/_foreach_add.h,sha256=r7_hg7RPm74YE095Fqgx3A0-dvhZLlTcu_4khQPzkYQ,5086 +torch/include/ATen/ops/_foreach_add_compositeexplicitautograd_dispatch.h,sha256=KDGfuajqUsUqiEyltzNlke8Q-765o7X3wh7j_mRFSiw,2704 +torch/include/ATen/ops/_foreach_add_cuda_dispatch.h,sha256=Lmycadk-Ljhl3Jp_UEH7JgHwQpxg_Hxnlj8dAYTB5Hk,1740 +torch/include/ATen/ops/_foreach_add_native.h,sha256=uDNupOwbM9fNIKA_9x74-9faOJLadBAeFEMW777wFTE,3207 +torch/include/ATen/ops/_foreach_add_ops.h,sha256=PVe2D0-WNu9HUmPKoLqXGhLjjlqQixOm5HJz4ocIODo,9090 +torch/include/ATen/ops/_foreach_addcdiv.h,sha256=QdqMWlv6rWisZoQS9CvaqclJUE57ALaX3VPlFtXcbnI,5134 +torch/include/ATen/ops/_foreach_addcdiv_compositeexplicitautograd_dispatch.h,sha256=L_iSOvJkfX6mGoYADBsptgFWVPtT4n4lWQjYEkY3RQw,2759 +torch/include/ATen/ops/_foreach_addcdiv_cuda_dispatch.h,sha256=Zoe0yN5WPdWYMUhrl-v8AQWNGfdMQpVFSje1mT6cjwc,1780 +torch/include/ATen/ops/_foreach_addcdiv_native.h,sha256=gtnxGvk5WWVgewh9zNN7XafmUo873UtiKr-SZE6s7zk,3115 +torch/include/ATen/ops/_foreach_addcdiv_ops.h,sha256=DPPJbw81OAROJtSFLUtoEf3qoW3pgAyXHPM8ObMk8l8,8256 +torch/include/ATen/ops/_foreach_addcmul.h,sha256=NRegWHyCzqk_CywgC5NYaVIdHtc7pAHu4qeu4Zc-7ao,5134 +torch/include/ATen/ops/_foreach_addcmul_compositeexplicitautograd_dispatch.h,sha256=vZduFS7dP9mR-KEiNl9U_p1W73mswv081Y_a6uedi1U,2759 +torch/include/ATen/ops/_foreach_addcmul_cuda_dispatch.h,sha256=sFZfz5V_mKVm3te-V9JIDEmg8BGSVtqgYoY_GACuj74,1780 +torch/include/ATen/ops/_foreach_addcmul_native.h,sha256=TMluaUjl6WJSdGnfc7_AfCVzAqY3b7jKJni5MLuxbSk,3115 +torch/include/ATen/ops/_foreach_addcmul_ops.h,sha256=qIfClJLemXQcb25qQmoFHcAiN-kR-0EgFrT3X-tgjAc,8256 +torch/include/ATen/ops/_foreach_asin.h,sha256=AZ1lCR5Ly7qkoJdkFvDCUYlLmumyUc1cZXOtSlsDbAg,1489 +torch/include/ATen/ops/_foreach_asin_compositeexplicitautograd_dispatch.h,sha256=MXVA17N5xbhb_Fv1yBOfk_3pq-TbvKlHCct5XqbtgtM,1239 +torch/include/ATen/ops/_foreach_asin_cuda_dispatch.h,sha256=ycthJAtsYQ78QvhDddarb9P8pBYnXYSffz4xFEprFxs,1046 +torch/include/ATen/ops/_foreach_asin_native.h,sha256=xQnFUvkaVhBrqmajLDp2jeXmsz8slaSfrz1mw40phXc,1043 +torch/include/ATen/ops/_foreach_asin_ops.h,sha256=zia9gGDBjxTixjApN7K5XpcYQ-x3vLMOICtMBZYal1E,2342 +torch/include/ATen/ops/_foreach_atan.h,sha256=ly38qb46pBtJezAfJwZFTzQ4qHWlAIubPFMu1inaBAA,1489 +torch/include/ATen/ops/_foreach_atan_compositeexplicitautograd_dispatch.h,sha256=RsAVr5mF-RBdMFzWfmApC5HPq5J3trFPFIM-4OrHbMA,1239 +torch/include/ATen/ops/_foreach_atan_cuda_dispatch.h,sha256=3FRgTZh7vbGRUHOuKDV92XTj4uyCsN0ujg7mj6rrxhk,1046 +torch/include/ATen/ops/_foreach_atan_native.h,sha256=A70eF0bj1fPT9WZCVaDjB-PKleXIOd-rVLXVQuP2uoM,1043 +torch/include/ATen/ops/_foreach_atan_ops.h,sha256=vj9Jw3ulFiad6XNtXs6Bi4vZ4OeOriH2kEj1-uogXaE,2342 +torch/include/ATen/ops/_foreach_ceil.h,sha256=ylomgp_WfsCcSnGg5_uY0FxlMiKm-dwO5OXqwH9ISOw,1489 +torch/include/ATen/ops/_foreach_ceil_compositeexplicitautograd_dispatch.h,sha256=Sgfo4Qje1tT-mCeKExLibph112avchPLsYOO6-CBp1M,1239 +torch/include/ATen/ops/_foreach_ceil_cuda_dispatch.h,sha256=U28q_9kLOCWLewRuyozP3rveOjIml1PyAaJ-AagJZEk,1046 +torch/include/ATen/ops/_foreach_ceil_native.h,sha256=2ttSNiQU5mEDR4Pr20fADYyAK99ftB6A2oPfWS-gBhY,1043 +torch/include/ATen/ops/_foreach_ceil_ops.h,sha256=nTB0u2b404gCrZooJtHkk9WFFLuqZw3EDu9ovr9YkIg,2342 +torch/include/ATen/ops/_foreach_clamp_max.h,sha256=a_BW0FS6OZsX_Yibdamiuhz2xChrHZ7DnOBq7W4_-bM,3934 +torch/include/ATen/ops/_foreach_clamp_max_compositeexplicitautograd_dispatch.h,sha256=QHEHN5oNSJO-E0R7sYNh5V_D6Pqg9XfgI5Jfq5z_1-g,2181 +torch/include/ATen/ops/_foreach_clamp_max_cuda_dispatch.h,sha256=e2y109ojK3XojCHM2fVsqBOzXMlLfs4ihR3XdMMY5VA,1490 +torch/include/ATen/ops/_foreach_clamp_max_native.h,sha256=AAwI5fVIlYOOXIqcs9l8fVnNPjYr-Sz93w4VYvwtg4k,2466 +torch/include/ATen/ops/_foreach_clamp_max_ops.h,sha256=kaJdwnosGzpEEBLEGNLx4mrpOdLmDe7HfnFr0XcXS_A,6771 +torch/include/ATen/ops/_foreach_clamp_min.h,sha256=25dLVXkKbBf11Bvq9-GT2e1Bsfo-XPgDHlnHZr5CMl0,3934 +torch/include/ATen/ops/_foreach_clamp_min_compositeexplicitautograd_dispatch.h,sha256=94KOoii2md9z6kpDv5S2-xlymZFn2SYbEXXNb-klVRk,2181 +torch/include/ATen/ops/_foreach_clamp_min_cuda_dispatch.h,sha256=ENO8mCycIXkuVtCfAhqz8M6leW9HXX3PDjxARxzuwso,1490 +torch/include/ATen/ops/_foreach_clamp_min_native.h,sha256=MPxdF1l-17q5a5_I6wGSL_mM_jxo8hGop2Ae-pf1drs,2466 +torch/include/ATen/ops/_foreach_clamp_min_ops.h,sha256=1qloDHuRonStj0x3gSbCwihO88zzSztUJvonsMRY3q4,6771 +torch/include/ATen/ops/_foreach_clone.h,sha256=HLc2MEtcovJQjY34w_1tyd0QVrUo0KUTRDGZDTUrU5g,1675 +torch/include/ATen/ops/_foreach_clone_compositeexplicitautograd_dispatch.h,sha256=JytNs_w0-4iO8hVrEfwpWvaj5QDiQQoTUORVFLkbFuw,1367 +torch/include/ATen/ops/_foreach_clone_cuda_dispatch.h,sha256=Fz2a3wqdZEB7a-psnIEhwtVQYqkuh4JoMrGVkNWMoEc,1059 +torch/include/ATen/ops/_foreach_clone_native.h,sha256=JOOmm5xJIS5icSANI-KyvY5J2_ZlS4Km_5EHsGE0uOs,1097 +torch/include/ATen/ops/_foreach_clone_ops.h,sha256=SgNgQqAP1Rl9v8jD9EznDaKrMwUvBVtS3p4Fwq6wtFc,2189 +torch/include/ATen/ops/_foreach_copy.h,sha256=Pk8drkCVEwKYrKsIFHTTnZ__UM-0m3kCenUguFpRz8I,1904 +torch/include/ATen/ops/_foreach_copy_compositeexplicitautograd_dispatch.h,sha256=XyUYvtKdm_QVO04rJFQ1T5oePEkv3Nhus0ii8TN5eqQ,1413 +torch/include/ATen/ops/_foreach_copy_cuda_dispatch.h,sha256=0P4FLaXGMQR7RxKYIcQ2gdEDQiZK2-uEu-CdMHGDNUs,1019 +torch/include/ATen/ops/_foreach_copy_native.h,sha256=iEqLLaHxqf2n7WPXIcO81FoXDlA86j8SKrAaET8kKcE,1147 +torch/include/ATen/ops/_foreach_copy_ops.h,sha256=IidO_pI1qQMx3fOAEzFGOR3Aby52ZhFXmYpQovS3zHc,2768 +torch/include/ATen/ops/_foreach_cos.h,sha256=mm-lR8hp6b5T36aK_DY_UxXpDCRs_3t6M6UkPc1Hp7A,1476 +torch/include/ATen/ops/_foreach_cos_compositeexplicitautograd_dispatch.h,sha256=NZ8xb3dOpyrV2Lr66YJG_8nD8x5urxwj-Pxje7HDH9k,1235 +torch/include/ATen/ops/_foreach_cos_cuda_dispatch.h,sha256=ljip2w81ew2OU03AQQUJ_OACs5PviAwic5qZSFsZuic,1044 +torch/include/ATen/ops/_foreach_cos_native.h,sha256=BXp97JJxUDwVJJQRKhFZ3juoOmiGCS_llHzWtGw8U6I,1038 +torch/include/ATen/ops/_foreach_cos_ops.h,sha256=RTVTtHJzHIsJcOLGdLbELjZOFsk0YSb23vVz6mPqxCw,2333 +torch/include/ATen/ops/_foreach_cosh.h,sha256=iV57AAPWDrqjDevEuddigjyr-XGisCr9ZzQPtfNzFas,1489 +torch/include/ATen/ops/_foreach_cosh_compositeexplicitautograd_dispatch.h,sha256=EdOnWqAsggtDIyNned5ApVuvSZ0TfsgN1wxjOAdQ_3Y,1239 +torch/include/ATen/ops/_foreach_cosh_cuda_dispatch.h,sha256=HOYIU5vfN7me-70xM7oygwC-eDrYPQTs_7mpL7W_Cy4,1046 +torch/include/ATen/ops/_foreach_cosh_native.h,sha256=elnAgkI38rrJiUK3epdWCdd3GaWOQreIClYT9NKyaXs,1043 +torch/include/ATen/ops/_foreach_cosh_ops.h,sha256=5l8mNInBPwZIzBMKAv-HOqrl2e5pDz0fHj55U5g83oA,2342 +torch/include/ATen/ops/_foreach_div.h,sha256=7tL_jzBZYVATEXYxAg0uhzf0REpuwZ-nr_seV4Tu8wo,4670 +torch/include/ATen/ops/_foreach_div_compositeexplicitautograd_dispatch.h,sha256=o23HPAV0dtqoJPBkR9UU7RQkVlsPUS9JFf0XIzcvCOY,2484 +torch/include/ATen/ops/_foreach_div_cuda_dispatch.h,sha256=2WEVSD6Ed2X3J6Kc6S3kqA4iWGBMmxr1Ywp2g0yxaEw,1628 +torch/include/ATen/ops/_foreach_div_native.h,sha256=r9iNzytjGfIHJGu-bllTYwU_9vzv_WD_9zyHAtGR9fc,2931 +torch/include/ATen/ops/_foreach_div_ops.h,sha256=2ePX4pNpCpgj_wDF7rvJsG0b3q4VoO59NI1WLMBGwSk,8550 +torch/include/ATen/ops/_foreach_erf.h,sha256=38gYf2ysFed8ObLjQVPr0SSRAUP908l6dEInrooYr2c,1476 +torch/include/ATen/ops/_foreach_erf_compositeexplicitautograd_dispatch.h,sha256=h4bCyke1qDQ-mJKocKU-YPZR4WkllMqNg4Fc13wvRuo,1235 +torch/include/ATen/ops/_foreach_erf_cuda_dispatch.h,sha256=lKyNusBh-1YZaCxM0u1Nhkbr4DBtoQCGjiRvNO9HCJk,1044 +torch/include/ATen/ops/_foreach_erf_native.h,sha256=2ayNv2c2WZrPYtkQgxOlX0SAbf6SfVUvd4CqHe5yQYI,1038 +torch/include/ATen/ops/_foreach_erf_ops.h,sha256=QTae0NNBZIoBVPKrPFAxCqStOmRQdU9dCOjmUVts-qw,2333 +torch/include/ATen/ops/_foreach_erfc.h,sha256=Od5r6R7pJQk9hg3uE29In2eCBcKWMD9yvcGY4CvbA_k,1489 +torch/include/ATen/ops/_foreach_erfc_compositeexplicitautograd_dispatch.h,sha256=14iV6dmI5YIyq4p03Nb-cXUEyM7CPvNylnJJy94BrdA,1239 +torch/include/ATen/ops/_foreach_erfc_cuda_dispatch.h,sha256=z_R1wxaVb0MPM3mx-543rITbyIxRM4vgDSsWNPn89to,1046 +torch/include/ATen/ops/_foreach_erfc_native.h,sha256=ddQnOPmpzhDhClzOjANPs6umcQbafJH1fhZH5prBuws,1043 +torch/include/ATen/ops/_foreach_erfc_ops.h,sha256=OdnSirkkA0W-cIbte2iEnHx3FVdSdGNgcLJQDqfA424,2342 +torch/include/ATen/ops/_foreach_exp.h,sha256=Vd0LWgNOjrenImwVhuJpuITyNr55VN_HSNtwB4lWS80,1476 +torch/include/ATen/ops/_foreach_exp_compositeexplicitautograd_dispatch.h,sha256=bPe0PDDhV6uJEl7WjZzRRxcBaA1MU7nA2eDOqJLqjq8,1235 +torch/include/ATen/ops/_foreach_exp_cuda_dispatch.h,sha256=Qt8Ll-En7IogavZKZeiuILHbZODYP7dS62gRPBAUlDo,1044 +torch/include/ATen/ops/_foreach_exp_native.h,sha256=177rueOWuMS_umUOb_BVByeqzQ0Q6mMTmjyiEGZ3HFg,1038 +torch/include/ATen/ops/_foreach_exp_ops.h,sha256=VaQaevTmB8qKgwTwT8rjVuiPuBikpneCrtYMVUC2pSg,2333 +torch/include/ATen/ops/_foreach_expm1.h,sha256=zuvcpuiReWSzhGlTElAVX3-JJK6FDnrgwnl8x7o4k4Q,1502 +torch/include/ATen/ops/_foreach_expm1_compositeexplicitautograd_dispatch.h,sha256=1Q0qBTfhFLEwMTOyfpK5P9zO3jizX5ZUc3u-hEmHLWM,1243 +torch/include/ATen/ops/_foreach_expm1_cuda_dispatch.h,sha256=l-4ROJhUnVdM8zMF4A83BuqbJYdSrzyzySzZM91GQQk,1048 +torch/include/ATen/ops/_foreach_expm1_native.h,sha256=WRbWVaF5d2ZITLWpck7hpTSIN7jlRUHjgZqgRMXoiI4,1048 +torch/include/ATen/ops/_foreach_expm1_ops.h,sha256=iX071mcf9zuE_kZMmhHgPsJBpt-MztQ03yhqmktuiiQ,2351 +torch/include/ATen/ops/_foreach_floor.h,sha256=Hm7ephKM9iyKPGm6pjjM0Gre6AowCt2yXOfe577wNOQ,1502 +torch/include/ATen/ops/_foreach_floor_compositeexplicitautograd_dispatch.h,sha256=A9B6UJ-4FXFEMvSw3LBE4whsScVNTEVEIVB1SpWPmDE,1243 +torch/include/ATen/ops/_foreach_floor_cuda_dispatch.h,sha256=jnloWHKWy4z3qtHnFx8EfUbEuOI08wRSeTgQXxHdDsQ,1048 +torch/include/ATen/ops/_foreach_floor_native.h,sha256=pDEWkpjrZSFDo6YHvJdOUCxHDxMfIUCM50AtfmVS_yM,1048 +torch/include/ATen/ops/_foreach_floor_ops.h,sha256=qVdoWm1oEkVltP6jddpF2_Wl4zrb_msDd2OFNLJndbk,2351 +torch/include/ATen/ops/_foreach_frac.h,sha256=rOl9T4TYEZsLsB-oKszqGWWjS8t8XTnYLskhbaC1iJ0,1489 +torch/include/ATen/ops/_foreach_frac_compositeexplicitautograd_dispatch.h,sha256=FPwx5X7NPsDzKtqHe4oSlHPaw17hXZTeshkKsqjP1fk,1239 +torch/include/ATen/ops/_foreach_frac_cuda_dispatch.h,sha256=TwHTX5rcTITTdaaTZoImvSnsbIcSK1A9K3W6NR2Dn-I,1046 +torch/include/ATen/ops/_foreach_frac_native.h,sha256=6MxCgTD3_51OdyNmJTjfZf_x0CvAT4i2LhEiKj6J4NQ,1043 +torch/include/ATen/ops/_foreach_frac_ops.h,sha256=42VbxkwtYQy_qSpJfZ7KXqGWJrn2DmpRBZMkR3PRQKc,2342 +torch/include/ATen/ops/_foreach_lerp.h,sha256=AZtgGbGwOQetDEeTmc7k_lQCSQspkg09CThinZKkWu4,4409 +torch/include/ATen/ops/_foreach_lerp_compositeexplicitautograd_dispatch.h,sha256=Lvhy_KhTgnQ9Ue7ovMj8W6J7EffJ95bmmyYv6uvRnCw,2425 +torch/include/ATen/ops/_foreach_lerp_cuda_dispatch.h,sha256=5cy7EWDwxXs8KZyAEg6P-mDnbrCZ6bS0iPpr09cTx5g,1612 +torch/include/ATen/ops/_foreach_lerp_native.h,sha256=aZOu9iAB40q1Dg_1JqmF2SwNOGphBK8FXMJx0Xp4OBI,2719 +torch/include/ATen/ops/_foreach_lerp_ops.h,sha256=vM8Wfx03t87nRzmynTp_zLCESE_3wDNMiVdaVk3I6Xs,7410 +torch/include/ATen/ops/_foreach_lgamma.h,sha256=4iHn8HKc7QwX9c_8uxRWUNUVHQ4gyGwHKCbtKQ5Ev1s,1515 +torch/include/ATen/ops/_foreach_lgamma_compositeexplicitautograd_dispatch.h,sha256=OReicr7ulgPTvspPJ1Di2piOD0BaxesLoa0h6_yueLs,1247 +torch/include/ATen/ops/_foreach_lgamma_cuda_dispatch.h,sha256=PHVTDRpFsU_g2xDZMkSr3tfqMd7VAD06GN2TiuNHnUI,1050 +torch/include/ATen/ops/_foreach_lgamma_native.h,sha256=JX4E9KlG5tyw0OqsL4VROsSq3VorJIK4pwUrnbgpMgU,1053 +torch/include/ATen/ops/_foreach_lgamma_ops.h,sha256=2LZwYWbvbiGPUOFsWrkgcFCUtw16N1SSnN0C5vGnvMM,2360 +torch/include/ATen/ops/_foreach_log.h,sha256=STsM_GXWdN-7Mk2N0WfbCsqkD_JTwU3AcPt7wA0Y9A4,1476 +torch/include/ATen/ops/_foreach_log10.h,sha256=qm2nxgsfzw82xgRX1dCUL_7Efa8M-B8vCikcV-kyNxA,1502 +torch/include/ATen/ops/_foreach_log10_compositeexplicitautograd_dispatch.h,sha256=PrPQgoqCgTqNQTvZDhn8TL_OMhD9Ir51zJiNTiMO2Nk,1243 +torch/include/ATen/ops/_foreach_log10_cuda_dispatch.h,sha256=hFhB8DaVRBMpGl6-LYzcW6MYH2PE0lldhXoRcPMkzGU,1048 +torch/include/ATen/ops/_foreach_log10_native.h,sha256=3fb7wnkKIwolFx-Ccjl8vLXhxK687_HYofdRq7e4Iu4,1048 +torch/include/ATen/ops/_foreach_log10_ops.h,sha256=yinh1BipcB_2KqB_nK8sIfIJLN6WSYyfrsMjQSNaYC8,2351 +torch/include/ATen/ops/_foreach_log1p.h,sha256=C9-W3fYHFRh7dSmMH0Pyvngc1GbsJI4inm1wYEr3Jh8,1502 +torch/include/ATen/ops/_foreach_log1p_compositeexplicitautograd_dispatch.h,sha256=hMvNDcEimHAbuipN1B6pIqYBkTZHttmCR47aVBHR03k,1243 +torch/include/ATen/ops/_foreach_log1p_cuda_dispatch.h,sha256=WnaJJRWgOz1AE73IttiO5PFL6X32zSTYrvEhAaQSBao,1048 +torch/include/ATen/ops/_foreach_log1p_native.h,sha256=WlxuK1Es7YX3X6gB33AapX6ENjnSywifTn7CKOP4IUo,1048 +torch/include/ATen/ops/_foreach_log1p_ops.h,sha256=c7qCg3AEFkLjVBqFuwaRNVznXrwAkXMEV-ER8cPqF1s,2351 +torch/include/ATen/ops/_foreach_log2.h,sha256=V1jZHttgoka1gKa9L92tB0eeh52xWYHG0djnuH_eGHg,1489 +torch/include/ATen/ops/_foreach_log2_compositeexplicitautograd_dispatch.h,sha256=OdGW9UwPYRwEtA9t6bHAAImzW_TOJT693SIFXXc-bEE,1239 +torch/include/ATen/ops/_foreach_log2_cuda_dispatch.h,sha256=HiuoNRGvHtxoa_KSujZQdVvAl7KyetiEEoFVpwDdzqU,1046 +torch/include/ATen/ops/_foreach_log2_native.h,sha256=IKBnVWLN5mQKdAyWEplc4qSlnXuzcAhsBaBaoeu8Xq8,1043 +torch/include/ATen/ops/_foreach_log2_ops.h,sha256=oSwZVFS6K9mT9XlaLlyyORrdZwVqo_Jk3xIGaiMRMqU,2342 +torch/include/ATen/ops/_foreach_log_compositeexplicitautograd_dispatch.h,sha256=uV7YAY7SYPr19EfPIxwiQdK4TaDo_WFgHeEbXnCHC-g,1235 +torch/include/ATen/ops/_foreach_log_cuda_dispatch.h,sha256=LloA_WZ00FnhlE-Kv2eSbYzHKZw7wuvD868_MMMxSpY,1044 +torch/include/ATen/ops/_foreach_log_native.h,sha256=nSaNq7XU5aoS6NmM9Rm10fxV819GGhqsAXcMAomGjxs,1038 +torch/include/ATen/ops/_foreach_log_ops.h,sha256=5Z1RG81knsJ4gCECyv7LqIiaBsqdy8718HRv-0EOns8,2333 +torch/include/ATen/ops/_foreach_max.h,sha256=a0wbuTvV2pvD9TNq-V4OgtBBWjLdX77JiEFKU18DxtU,1328 +torch/include/ATen/ops/_foreach_max_compositeexplicitautograd_dispatch.h,sha256=a8VHMeSCtgmpP5AP9rPGP3lzdzThPOixu4XBxbxArHA,1184 +torch/include/ATen/ops/_foreach_max_cuda_dispatch.h,sha256=QeiCSqUg8WbtaQEYR2B9OY9mb4ENmOyCEXvKYXAgxpM,993 +torch/include/ATen/ops/_foreach_max_native.h,sha256=4S_VvDyRgMW7xhpIXonJecOYZIpzINDYlqFHAfRBRbo,914 +torch/include/ATen/ops/_foreach_max_ops.h,sha256=0EWp4GXeELrHig2xuH8iF_aCIEPLaMTcVlmcfmvhP7c,1840 +torch/include/ATen/ops/_foreach_maximum.h,sha256=Mp5ZcMzfg_gl0_7teXFg_ojdSbn1IRqGwBSS5EBkuGg,3860 +torch/include/ATen/ops/_foreach_maximum_compositeexplicitautograd_dispatch.h,sha256=W-Gf1WH1rstCKwKHtvwWXkbilUnHmKszC3CX06jajFY,2157 +torch/include/ATen/ops/_foreach_maximum_cuda_dispatch.h,sha256=uo3AoRyJzybbQGmZ_fHk0xC8X6nmZWEtMGIMbjq9TsQ,1478 +torch/include/ATen/ops/_foreach_maximum_native.h,sha256=k_7sTfeOZm4ReqeWuX2Lcju13fPOZv099Oxig3bhoNw,2460 +torch/include/ATen/ops/_foreach_maximum_ops.h,sha256=EItwNAP5KlKCl66TQvgUVnhtlbNTbULvImqMUeOvZAg,6717 +torch/include/ATen/ops/_foreach_minimum.h,sha256=RffEwCJCcpuaT_dJU3AA46FJEHe7XtibFx11xGlI_jM,3860 +torch/include/ATen/ops/_foreach_minimum_compositeexplicitautograd_dispatch.h,sha256=qAP5EzKdl3nrptdjNsluWgy5SLMctgxN--8GQUaKsVU,2157 +torch/include/ATen/ops/_foreach_minimum_cuda_dispatch.h,sha256=t_XFkxwi2sGv4KFL5fr_-DgOQQOWlfAIyGZ_qUd58ZE,1478 +torch/include/ATen/ops/_foreach_minimum_native.h,sha256=k3kHt0HHhA7xfYZtELtOWpb7rAOVTmdbRjumVffQ9qQ,2460 +torch/include/ATen/ops/_foreach_minimum_ops.h,sha256=zFiblbn0l07Wt8Rj9rVPYbSycPOyx2qQOZqpTWcGzoQ,6717 +torch/include/ATen/ops/_foreach_mm.h,sha256=6n_PSomVmqro_Vb8LYTmWmQCYoXMc9ON0p6Si11Sskc,968 +torch/include/ATen/ops/_foreach_mm_compositeexplicitautograd_dispatch.h,sha256=wqstnG2kKcXK11ZvP5if39gOeu_dmIMV95oAxUKEKxI,1055 +torch/include/ATen/ops/_foreach_mm_native.h,sha256=6pnDvF-4S6ZShZnmghNaCpWqN8PhZe4ybhZaaI185rE,767 +torch/include/ATen/ops/_foreach_mm_ops.h,sha256=NICovbHrqOYznSeuJonmfrbhf2VCoIVCJHmYX2UIfFs,1336 +torch/include/ATen/ops/_foreach_mul.h,sha256=9ajVCQvTXsBcfeSSZhjtyGegYyCkIE5WR2A1RzqRLnA,4670 +torch/include/ATen/ops/_foreach_mul_compositeexplicitautograd_dispatch.h,sha256=TNAKI_Km56tWjXvYtXWPTwEazRcCxYmB1hUVxsqcNGY,2484 +torch/include/ATen/ops/_foreach_mul_cuda_dispatch.h,sha256=kRUdpZ0dLpF5-CCZOFZ6ep7jGsshIdXQRGdhvvYcw7E,1628 +torch/include/ATen/ops/_foreach_mul_native.h,sha256=Drr3pJ_BqXrFLdsDlM59M2Hl0zj4SWBNT7DG-IPRD5o,2931 +torch/include/ATen/ops/_foreach_mul_ops.h,sha256=p2YHSMBZgghntRmjcqc5LXy7mkB-YYdk5WZRp-DY2Qw,8550 +torch/include/ATen/ops/_foreach_neg.h,sha256=f2x-pvcxiYFg4vG4NwlktlEmTWk3YVv4Cl-6qJ8yva0,1476 +torch/include/ATen/ops/_foreach_neg_compositeexplicitautograd_dispatch.h,sha256=XywtYFHU-u8yArCKnE4vfjnVSIVun_5O1wOEGP_MVDQ,1235 +torch/include/ATen/ops/_foreach_neg_cuda_dispatch.h,sha256=LPVYNaE-gBkG-rPj6SfEA6GMq2HyV9aSqUG715zh27Q,1044 +torch/include/ATen/ops/_foreach_neg_native.h,sha256=uLsNgz0OpcMZs9a8xdvLQQqNZyOS1nZB0uSed5uAxFo,1038 +torch/include/ATen/ops/_foreach_neg_ops.h,sha256=xpcJUIDkpQDJ1MO6-_Je5_iU4qXUmNib_fUwU_ft_eI,2333 +torch/include/ATen/ops/_foreach_norm.h,sha256=W-1qQrogPdbIAnCBm1dV4LZzsJ1ga055wnIZWlyWGkA,1753 +torch/include/ATen/ops/_foreach_norm_compositeexplicitautograd_dispatch.h,sha256=4mJ1ag9PjJRAyVvh8Xnk1W6_KAKIWAPW4UaM8-Oq4OE,1410 +torch/include/ATen/ops/_foreach_norm_cuda_dispatch.h,sha256=VdTC_m4xcvd4LWKbu6RMXE2cPpRna40LstMqA7Gbz0w,1074 +torch/include/ATen/ops/_foreach_norm_native.h,sha256=-L3O42cEqG5eD0131Z3pgRxThv1SmUtpfkhGTJQgu6o,1147 +torch/include/ATen/ops/_foreach_norm_ops.h,sha256=N-jKDjNpmoRnGm4jDOgtRQJPz9o78QXnYu-3M2DYoq4,2321 +torch/include/ATen/ops/_foreach_pow.h,sha256=-lKiqGD6SqjLc2BOE9j5vRtzupA04WUdi3CEYneRudk,4040 +torch/include/ATen/ops/_foreach_pow_compositeexplicitautograd_dispatch.h,sha256=GTRYb9tsFgcu3Q3PvwAvPVn5askjon87TOCDCv3xx6o,2233 +torch/include/ATen/ops/_foreach_pow_cuda_dispatch.h,sha256=22HIk8rUtUf9jMnsTFb6MMl3hoCA9V265ezAxQMU5tI,1566 +torch/include/ATen/ops/_foreach_pow_native.h,sha256=_RhdTs4jarBm9fcDJjJdQohp8YAGs_1_oll_W6nLBJY,2652 +torch/include/ATen/ops/_foreach_pow_ops.h,sha256=iphu4rfr_pz7fukCdZgLII1Kk-bofPyl5g5M_cFd_qE,7360 +torch/include/ATen/ops/_foreach_powsum.h,sha256=F9SaXsEZwRKP0A0oaJoU7AIHlPnN0I2NaYWqPinAi5M,1773 +torch/include/ATen/ops/_foreach_powsum_compositeexplicitautograd_dispatch.h,sha256=0-C3mgbUrxDgztpICH1IA4jnPEorpefubFsmfk9Ktsc,1416 +torch/include/ATen/ops/_foreach_powsum_cuda_dispatch.h,sha256=CrGd_oUTmn2j6Wd8H9uqiUPOSkrQX4AbLmlhMu2JK18,1076 +torch/include/ATen/ops/_foreach_powsum_native.h,sha256=agrvpx5O4etWwH7PbLl4zYFjLZl8rhNCZd5NMLiHCZM,1153 +torch/include/ATen/ops/_foreach_powsum_ops.h,sha256=VKKf-rmtlwEQdXqDkMW--IfACrMP-eK6cHIxxKJO1YE,2333 +torch/include/ATen/ops/_foreach_reciprocal.h,sha256=zrp2-TrifV9HJLgA3bRNtgZ2tLJu22OHGXxz-bzZYQI,1567 +torch/include/ATen/ops/_foreach_reciprocal_compositeexplicitautograd_dispatch.h,sha256=YuUJdFd9vvITYxj4yG-26R7_fU-_elBZpyJxcUaF7G4,1263 +torch/include/ATen/ops/_foreach_reciprocal_cuda_dispatch.h,sha256=g1ZQKR08zNfyoaHTmZf6sp49AYmN94urcTpAEzUhya0,1058 +torch/include/ATen/ops/_foreach_reciprocal_native.h,sha256=_FZB-q2w_tZADF5FQlupTiQXt6Echx6E0luOzUIgZ7o,1073 +torch/include/ATen/ops/_foreach_reciprocal_ops.h,sha256=dgcEk2YLh4OeeQLXrHwu67bYWbCWlw7cPJLxrTnyKR0,2396 +torch/include/ATen/ops/_foreach_round.h,sha256=HO8iLDuX1cW-uLKq4kTmLzP--J_I_XgBgy7ItM19fk0,1502 +torch/include/ATen/ops/_foreach_round_compositeexplicitautograd_dispatch.h,sha256=r5ovquR7UP-MNtEm9SQZQ9Hd-5W_pKTS8jEYSMLPlyo,1243 +torch/include/ATen/ops/_foreach_round_cuda_dispatch.h,sha256=H1_XxtOTnBIQEg0pWjipGH3sMwJT6a4MO7pjwuneqRo,1048 +torch/include/ATen/ops/_foreach_round_native.h,sha256=358Bq56dXVg-R8BIGK-mW2Sklg3OfEr9Idr0V0mpfQE,1048 +torch/include/ATen/ops/_foreach_round_ops.h,sha256=2rogSekI7iktty6J_FT1v5hfGpXz829rtQZOXUGQD-M,2351 +torch/include/ATen/ops/_foreach_rsqrt.h,sha256=JV8xRQv5qWIa_yFkKdtmAWB4vRTjJvCWo9BpLA7lcNg,1502 +torch/include/ATen/ops/_foreach_rsqrt_compositeexplicitautograd_dispatch.h,sha256=LVMtWef5OtXMniZwpf9yfaOl9JprNMqpWv4iWT0_TkU,1243 +torch/include/ATen/ops/_foreach_rsqrt_cuda_dispatch.h,sha256=IbgBwe_VNVo-_muQ32MCrcQfpQQuzvA7L_FkTqmoTDg,1048 +torch/include/ATen/ops/_foreach_rsqrt_native.h,sha256=jOdnUZW0xZ8relwXMg9wk3FXHG0dQzPf3LrZz_0N6jI,1048 +torch/include/ATen/ops/_foreach_rsqrt_ops.h,sha256=sjeT527-oIAxOCjr_7Kui-MA48HvYttPFuMztn2cSPI,2351 +torch/include/ATen/ops/_foreach_sigmoid.h,sha256=Di4wPgfzzXTJUIiaGYAJX4basJJfqvELEA4KOIgrfVk,1528 +torch/include/ATen/ops/_foreach_sigmoid_compositeexplicitautograd_dispatch.h,sha256=6WbOVDA-iu9pUFKR1N5Qlbh7BUChar5ztZo_cXcGWMs,1251 +torch/include/ATen/ops/_foreach_sigmoid_cuda_dispatch.h,sha256=myuRlVqZK9iKugcTgT0Fio_ueR9hirPVTxjuDX26fnI,1052 +torch/include/ATen/ops/_foreach_sigmoid_native.h,sha256=UnmVWKMao1vjORYmmdC1IiPQId_gevnufam_Gsy407o,1058 +torch/include/ATen/ops/_foreach_sigmoid_ops.h,sha256=CYhginFUzrmqTgcQhfOTmxCwoZrRCFr1xBDCzKPlpZg,2369 +torch/include/ATen/ops/_foreach_sign.h,sha256=4-ZaVDCZx7gONguObU9Q68EwkPpWTA3iVtHuR_DC530,1489 +torch/include/ATen/ops/_foreach_sign_compositeexplicitautograd_dispatch.h,sha256=cedUDCe5TEh-T1JzUlgf6Gc_aMoOFrhXTVBJ2qSbjbw,1239 +torch/include/ATen/ops/_foreach_sign_cuda_dispatch.h,sha256=aRNfBqg3kvHyQC-n8sQIVs1kBkbsNkALxdZ-vKLwPOc,1046 +torch/include/ATen/ops/_foreach_sign_native.h,sha256=n8Tzx2_rSx9QL-ktFIz0dHkLp96paPcUEp8RcdKE4YI,1043 +torch/include/ATen/ops/_foreach_sign_ops.h,sha256=y64JnpNYl_T7swUVMmHc3XcmxGHtWEvdULoSXAazSwg,2342 +torch/include/ATen/ops/_foreach_sin.h,sha256=lF-jF7TQJqcPLDw9VUf4ljOJ890UkaZBpSL094q7gUg,1476 +torch/include/ATen/ops/_foreach_sin_compositeexplicitautograd_dispatch.h,sha256=1uCQUdqUZLZxhAzQwg1sRlI5aisMdSoeem7m3rUWkeM,1235 +torch/include/ATen/ops/_foreach_sin_cuda_dispatch.h,sha256=LA3hhqnAjtlNtIYuCfDz56qaQWoe6k4QXmSqJt8QE6U,1044 +torch/include/ATen/ops/_foreach_sin_native.h,sha256=3YAAZVODEwgTFPY3EntwnmgBrUD6xN69iguJ1lnhOQQ,1038 +torch/include/ATen/ops/_foreach_sin_ops.h,sha256=x8yLT729lln4-6XjWg2hN3pF1wkDIl6fxD0TlvtQ5-I,2333 +torch/include/ATen/ops/_foreach_sinh.h,sha256=EZtu8CFHTc92qEo89KsENz9gWM1Gvwt38lpbVrqzm08,1489 +torch/include/ATen/ops/_foreach_sinh_compositeexplicitautograd_dispatch.h,sha256=DqYfQBn55qXnoUBwiaiW0T8dptpB_NeTRAaXICp8PtM,1239 +torch/include/ATen/ops/_foreach_sinh_cuda_dispatch.h,sha256=ZR9siY3t5T0yGh8baMRDyDfem1QXOv41MfYjsWW5GB4,1046 +torch/include/ATen/ops/_foreach_sinh_native.h,sha256=PcA16H8nhg9eLcQlAKH0AT037Gl4n1VDUfWOtwPAFv4,1043 +torch/include/ATen/ops/_foreach_sinh_ops.h,sha256=AyD3tG1OHOVosobFXw7cj5e55z1J-HL2FTOV2hEe3xg,2342 +torch/include/ATen/ops/_foreach_sqrt.h,sha256=QGJyYtGx5_pK38TJ4kAaTW00i3cOD5ALRluZijG42yg,1489 +torch/include/ATen/ops/_foreach_sqrt_compositeexplicitautograd_dispatch.h,sha256=KCDYeq0eRSsJrdNBsKg-xgjw4TWs0Z4w59G7NcIFxZk,1239 +torch/include/ATen/ops/_foreach_sqrt_cuda_dispatch.h,sha256=qn6bQS82-PJid6yksU19GEupBm4JhB6z8YFsHEYVdCE,1046 +torch/include/ATen/ops/_foreach_sqrt_native.h,sha256=Hu0L_QWZk0rO30Ox9ASrVHWAtWgkYLGcR3UrPIl44-s,1043 +torch/include/ATen/ops/_foreach_sqrt_ops.h,sha256=dM_VJreHXO5U6z9b55UnyguccJ4Hf7OHTIFtuYnkTG0,2342 +torch/include/ATen/ops/_foreach_sub.h,sha256=_EbUgHyvVYfGyVoRClzEcRmVITxetnpP56YrMyJKbsI,3920 +torch/include/ATen/ops/_foreach_sub_compositeexplicitautograd_dispatch.h,sha256=hOKkh-18w6BOFIEA4SEoODYkGC5O4cAduN_w_jyOZ3o,2219 +torch/include/ATen/ops/_foreach_sub_cuda_dispatch.h,sha256=F5NRnKE-5ErGvpGjkhKb_XVEZAlgb231zS-phJDyM-g,1510 +torch/include/ATen/ops/_foreach_sub_native.h,sha256=lvR_Nmh6qAlRXLLEwGWxEEM64fmL0dhryFGdYx9Lm6I,2514 +torch/include/ATen/ops/_foreach_sub_ops.h,sha256=_cKVdFUp75SwFKHF1JWlxwvkhbwnMzH_WUkq4okQO2g,6879 +torch/include/ATen/ops/_foreach_tan.h,sha256=_7I0j7mDxBRR3kSaq75qmFwr8vPmoN-JUbTHvVJMTVM,1476 +torch/include/ATen/ops/_foreach_tan_compositeexplicitautograd_dispatch.h,sha256=lLY4NItXa8VBF5uabl7kZuknRSiqHNkGUXbLMGIXuDY,1235 +torch/include/ATen/ops/_foreach_tan_cuda_dispatch.h,sha256=ONrhGzHeYoee8g8XYyPAffn4sTaKIwEcZhrlWM9TunU,1044 +torch/include/ATen/ops/_foreach_tan_native.h,sha256=N5Ohc8bIxv-RvId_TFlq7bd0WbthQE8iv-oI7OxRt5M,1038 +torch/include/ATen/ops/_foreach_tan_ops.h,sha256=9SjxsWf2S-D3MPwnY-m7QSUbAxWXRq08JbvMSzmmRns,2333 +torch/include/ATen/ops/_foreach_tanh.h,sha256=-JOTdt54l6vCKVREf_O9QaPnFYjT_Si3Eagb6Wq35wI,1489 +torch/include/ATen/ops/_foreach_tanh_compositeexplicitautograd_dispatch.h,sha256=yStqmJpT4WVLZVMl1j_TFBWalCd___Owouoc2BNNoXo,1239 +torch/include/ATen/ops/_foreach_tanh_cuda_dispatch.h,sha256=q5k2GcVxPZBFxVDrcgnY46_B08v6nGnGSdv9pEG2Uhs,1046 +torch/include/ATen/ops/_foreach_tanh_native.h,sha256=O9X9kSNDxjuwt1m-lJaeXuEdnvrPa5_PhsPqnYLNAbk,1043 +torch/include/ATen/ops/_foreach_tanh_ops.h,sha256=Y0m_yTJt3l4XBpSABsPgvxb8dHHtrM3W6KvP5h1_cFQ,2342 +torch/include/ATen/ops/_foreach_trunc.h,sha256=H-_8HPF6s-GcQyWa1UIsYGpGwujl4frkPNgXeUfydGY,1502 +torch/include/ATen/ops/_foreach_trunc_compositeexplicitautograd_dispatch.h,sha256=CggimwSCuqV-garTGnMa-8J6cCV88wRb9BF45RbIovg,1243 +torch/include/ATen/ops/_foreach_trunc_cuda_dispatch.h,sha256=sJSlCjErUBZnEN7xlegy38O1v2x45nDmBOp6xUjb1CM,1048 +torch/include/ATen/ops/_foreach_trunc_native.h,sha256=u9-q21wCzFGTxS7pA-hMXqJI1Z5pjl4dnM_csv3lAJo,1048 +torch/include/ATen/ops/_foreach_trunc_ops.h,sha256=7Ic71FFdspzGbqwphxfdp8XhjQQ3d1Awlob1qsl_ab4,2351 +torch/include/ATen/ops/_foreach_zero.h,sha256=7aYbFms3Uq2a_hGDBss2HnSASvdYSbPvB7BGYf9trBs,1498 +torch/include/ATen/ops/_foreach_zero_compositeexplicitautograd_dispatch.h,sha256=_Go_fWuNKmEnWtwKqJaJ0bzx3zSjrZy2INDJgOhUkRI,1239 +torch/include/ATen/ops/_foreach_zero_cuda_dispatch.h,sha256=qV4RIuX7YDd2QnaWNeFI3V2__GzzfBMzOGI-3dI4F7s,974 +torch/include/ATen/ops/_foreach_zero_native.h,sha256=v_AuTLkkmt3Rf3XGSsmBbnZ2OfhsSCoYBwZGneO5zVM,949 +torch/include/ATen/ops/_foreach_zero_ops.h,sha256=mW19R0-S7SvWKnCNi2iKOuiSblnRYjLq9F6-UxtFHS8,2351 +torch/include/ATen/ops/_functional_assert_async.h,sha256=W6HDTE5JmdmJijszzDMKXVcoTwNzH620DjIEck0cpZ8,1087 +torch/include/ATen/ops/_functional_assert_async_cpu_dispatch.h,sha256=nhBcOZ4gZZckPfaUCYVo-tS5oCb_rapoJbI-L63C2yI,1051 +torch/include/ATen/ops/_functional_assert_async_native.h,sha256=BEZoN2QPpAhRxhHvq5ed_foEIeKnRCLi0t3bv9okUTA,815 +torch/include/ATen/ops/_functional_assert_async_ops.h,sha256=Lt0WTqU8kGmMGdaMUxycYAj6EY5D10SMsWKBtUaVPGo,1466 +torch/include/ATen/ops/_functional_assert_scalar.h,sha256=wXUJEP5VjMC-O_0mRidnwFg-H7dfQSJLLi9n3KqNecw,1083 +torch/include/ATen/ops/_functional_assert_scalar_compositeexplicitautograd_dispatch.h,sha256=kB5oy61fM8HprD-QAuiwnabEolmjhAPtdAbBblfCDys,1096 +torch/include/ATen/ops/_functional_assert_scalar_native.h,sha256=y_MoX99UnZvdpCzWghOAI3tzKZJfPKmMay0ZYK40tEY,808 +torch/include/ATen/ops/_functional_assert_scalar_ops.h,sha256=UUrhCEyPGBa2po3N5Zamd4DHZ5b9wMi7coca3KrqpQU,1458 +torch/include/ATen/ops/_functional_sym_constrain_range.h,sha256=GUUOhmT0c_ukEp6TAHVcoLwJYeAHrpR7PQydxspTL3E,1140 +torch/include/ATen/ops/_functional_sym_constrain_range_compositeexplicitautograd_dispatch.h,sha256=_Sj45uWlcBgpSP6ZL5HduisY0SJFfQH8rp7ObaBJssY,1133 +torch/include/ATen/ops/_functional_sym_constrain_range_for_size.h,sha256=Je4Y86981gJGLUhJXcsLXL4Vf8opJliaWtkf9e2t3GQ,1176 +torch/include/ATen/ops/_functional_sym_constrain_range_for_size_compositeexplicitautograd_dispatch.h,sha256=OuZ9Bj3usdVqxugoYrje7i32ICHq8oQvkWfstcW6vHU,1142 +torch/include/ATen/ops/_functional_sym_constrain_range_for_size_native.h,sha256=dVKydlWzUtCkLlIigDI1-x0H0lQgz4q7W0nFtkR3-Nk,854 +torch/include/ATen/ops/_functional_sym_constrain_range_for_size_ops.h,sha256=EGIIdkAl_8JeO_I47n18PvjWqzJ01ocid82_fHMrPoY,1603 +torch/include/ATen/ops/_functional_sym_constrain_range_native.h,sha256=bx_QtLkDAJ3hgEDXJh9LcyjfaW8H5mepoI4115yxLMI,845 +torch/include/ATen/ops/_functional_sym_constrain_range_ops.h,sha256=r-3S0vkU-qb3qt2D93aWomcy3p6c1dg5X63BYVWQSSk,1576 +torch/include/ATen/ops/_fused_adagrad.h,sha256=m_RygKv8bERhR8fC1smEKkvcfVDcm0SGWxDjIdL1bAE,6984 +torch/include/ATen/ops/_fused_adagrad_compositeexplicitautograd_dispatch.h,sha256=GKMJr9vxK7Jx3_h48dovgRo_r-kqYAMu3mYfrDGn5oY,3122 +torch/include/ATen/ops/_fused_adagrad_cpu_dispatch.h,sha256=K-5jeNGchNTjQar7CyrpkIH7wolF2XzQISR5JYFYcNI,1546 +torch/include/ATen/ops/_fused_adagrad_cuda_dispatch.h,sha256=Ssu2ujMcrLLilFm_KTZFRbshE9kN1BSPhG1VhVMak6M,1548 +torch/include/ATen/ops/_fused_adagrad_native.h,sha256=Rd2-cIuFk4iAZh8c5SwtSq1U7fZ1EiZVtnnn_YZl1pk,3468 +torch/include/ATen/ops/_fused_adagrad_ops.h,sha256=uqpMtJzCSfY3RU9KPVzTzLpq2pDXXJ-HCw9JVo9MB98,9870 +torch/include/ATen/ops/_fused_adam.h,sha256=4gu7b8llgCs-MKBqdfhT2Gi4eK2uZXeiV-3x6vxZk-I,8657 +torch/include/ATen/ops/_fused_adam_compositeexplicitautograd_dispatch.h,sha256=MkeYXsYf3P7p1ql2q88jJe44WuQbs8fh_0Wa74Syh38,3680 +torch/include/ATen/ops/_fused_adam_cpu_dispatch.h,sha256=gAqHh0CTO7D0BDpnkIwMonn9Zgc1At8562mfd0YCctg,1706 +torch/include/ATen/ops/_fused_adam_cuda_dispatch.h,sha256=AnSRyMEDkoCayIRY_1QTbU9HPS35WtoFRTSeka8sqUE,1708 +torch/include/ATen/ops/_fused_adam_native.h,sha256=KMRl1U7-wuGu1Oa8MxYhhA8VKtUMRoFkCf1MqDJJWOg,4186 +torch/include/ATen/ops/_fused_adam_ops.h,sha256=0er_m6NFg3gGlz4AfvbmNgzq7CWrNdlafTL1mN6XAlc,11848 +torch/include/ATen/ops/_fused_adamw.h,sha256=gjcLKnseiuOg1DjEldDdxeumsWBJdmcmt3KW4iS1_2M,8682 +torch/include/ATen/ops/_fused_adamw_compositeexplicitautograd_dispatch.h,sha256=pRd-OIed7QKpcRGw_26CtP7sAx5Hq4nHkemonbGbJew,3686 +torch/include/ATen/ops/_fused_adamw_cpu_dispatch.h,sha256=T3-O1luEVQZE-7Oi8CyvV0lUrmPgep_UduNsyTMzyNg,1708 +torch/include/ATen/ops/_fused_adamw_cuda_dispatch.h,sha256=uf92VyZ13criF2iWdLabMYGg_uTrmCxQb8-r0ovRLQ4,1710 +torch/include/ATen/ops/_fused_adamw_native.h,sha256=kestFLIiQQnc-1OBlgZsqVlA_roPQInMAwKk_Co1gIw,4194 +torch/include/ATen/ops/_fused_adamw_ops.h,sha256=SFRU5tI9ZXYpEThmlfQzOXUkQ0AOAGfKr7gbwrYXWQ4,11866 +torch/include/ATen/ops/_fused_dropout.h,sha256=NZmoa_Pzhz_doB-Mw6O_9PFAacxLXXIsMFRjEgCcFIM,1904 +torch/include/ATen/ops/_fused_dropout_compositeexplicitautograd_dispatch.h,sha256=_2L2YkqjQNGbJsAGg1K5f11MvRoKqpEATL6jTTdrA0A,1350 +torch/include/ATen/ops/_fused_dropout_cuda_dispatch.h,sha256=Meiu-cfclgDAa-Kw0Sh9Wefnld2FYAlMQok0uaArnzk,1076 +torch/include/ATen/ops/_fused_dropout_native.h,sha256=BOHrkLwgDv_FAdEVQnPXk4SkzEhYEH3h-ubGm3TLKWQ,1019 +torch/include/ATen/ops/_fused_dropout_ops.h,sha256=7djoXYEL90MSOB0PEs89tonh7QZO4hYuEwDIkHDnc4k,2461 +torch/include/ATen/ops/_fused_moving_avg_obs_fq_helper.h,sha256=NVf_adVLWAUqxqNu7AnxvjEDM_DGAZhsI32GlNDiIiQ,5029 +torch/include/ATen/ops/_fused_moving_avg_obs_fq_helper_compositeexplicitautograd_dispatch.h,sha256=TA3YjyVb7hYBuZ0c3G_7AW11HfJfSDOifddUMdK7xDs,2339 +torch/include/ATen/ops/_fused_moving_avg_obs_fq_helper_cpu_dispatch.h,sha256=1R_GDqoo9w3O_9Iozqo2WsSdAAq0M8RN_59lW3LJCe8,1325 +torch/include/ATen/ops/_fused_moving_avg_obs_fq_helper_cuda_dispatch.h,sha256=7QOJ3Oe2OmUakqOaPCbVsZs7IzHh8yDM_Jwqs20Z5DI,1327 +torch/include/ATen/ops/_fused_moving_avg_obs_fq_helper_native.h,sha256=yO2HLpfvuro99T8ygD8_BJ6PBz1javZPxP4q5uc7fQ8,2418 +torch/include/ATen/ops/_fused_moving_avg_obs_fq_helper_ops.h,sha256=V6ywNUALozA4Q_D5puIT3P_r8hgwmJOmmYLJUwPvdaI,6128 +torch/include/ATen/ops/_fused_rms_norm.h,sha256=GOt2xf3p0Nd53N83eXAowzyXj2dI-1mEP4MQ2n07wfQ,1155 +torch/include/ATen/ops/_fused_rms_norm_backward.h,sha256=Nuf4HhveJzXXyqs3IV65tt8ivgpsL1O5SgAWYcnUg3Y,1313 +torch/include/ATen/ops/_fused_rms_norm_backward_cuda_dispatch.h,sha256=57IUFwQsfPEfaKU4sPn9Fz4tUvIzUnHrNEsFgfH7l8M,1186 +torch/include/ATen/ops/_fused_rms_norm_backward_native.h,sha256=ZZNH4XLvDUU7L--pgo4qascNVAnTBCkw6ZptrVBmWhQ,945 +torch/include/ATen/ops/_fused_rms_norm_backward_ops.h,sha256=n_I3yJ0jlX65-DYDGjjVqnPESnxmc0QEdVr8bLr5e6E,1892 +torch/include/ATen/ops/_fused_rms_norm_compositeimplicitautograd_dispatch.h,sha256=mt-FKhSXc4s3WrDg-YIV4RVjsc7in3tT4Q2Ju7At7fE,1160 +torch/include/ATen/ops/_fused_rms_norm_cuda_dispatch.h,sha256=aq7kf92EtEoo5v_AZn8lO1hU1-erwRw6Nj_1lvt1OI4,1118 +torch/include/ATen/ops/_fused_rms_norm_native.h,sha256=_I8UfSoAXZtYXYTnlzwpD64VIcIWBZmm6I59DHSpk1w,1076 +torch/include/ATen/ops/_fused_rms_norm_ops.h,sha256=2XT_ijz0-BLZpO2E_NHDk-cH-DYf7g3Ih7yutXDP_gk,1671 +torch/include/ATen/ops/_fused_sdp_choice.h,sha256=_HEFRv_VRlLRIAoAyRVHjVSUT1FgYIpbNQCCHhz7hV4,1347 +torch/include/ATen/ops/_fused_sdp_choice_cpu_dispatch.h,sha256=aORjujP3gbUp4GtzJ8i7Nks5x4_BZFBqyaGT-C3sW1M,1196 +torch/include/ATen/ops/_fused_sdp_choice_cuda_dispatch.h,sha256=Cu9tZ73xM32Rd5xXD89LUophfZ-EhWZyQVDoUqG3eoA,1198 +torch/include/ATen/ops/_fused_sdp_choice_meta_dispatch.h,sha256=liX_lECLD9EhJbEdSxZXwUEqoc8SVq5yE0AsT6H-WVE,1198 +torch/include/ATen/ops/_fused_sdp_choice_native.h,sha256=VB43OsQZq_zFD2XcsIWclu77TLeUqnpfyppCP-gePaw,1518 +torch/include/ATen/ops/_fused_sdp_choice_ops.h,sha256=3IThPWmUDTbjFeFgtiiErqcdIPv_L4WGtXRFnBYygS0,1853 +torch/include/ATen/ops/_fused_sgd.h,sha256=92RH6gah9UQ13vQk6Ivw1OWA7YfhxWI4-APYavBwEBA,7480 +torch/include/ATen/ops/_fused_sgd_compositeexplicitautograd_dispatch.h,sha256=s3wzfP7iGYLfWyUbicFriGOC2_DK81VJz2NPunVB71g,3210 +torch/include/ATen/ops/_fused_sgd_cpu_dispatch.h,sha256=rPLpZowdauA6q7UbgoKb2FzHK5AMN9kqUxZmLsclxCU,1584 +torch/include/ATen/ops/_fused_sgd_cuda_dispatch.h,sha256=kJv-9IWn3Vx-CT_y8SYTDcg7xvpfKYhGwl9I7AV2Snk,1586 +torch/include/ATen/ops/_fused_sgd_native.h,sha256=sJgU4NMnCQAozx9UTDqJ74befOYo00Sjyw9-vJP7JF0,3594 +torch/include/ATen/ops/_fused_sgd_ops.h,sha256=RU2ZpSyTrED0K7FO5oFc2ailR951pwMA3E1_PcaIRxM,10132 +torch/include/ATen/ops/_fw_primal.h,sha256=eqnSVoaz_S1dGjcflCN7C3SDn4wMk84GlECSG7h7X7Q,761 +torch/include/ATen/ops/_fw_primal_compositeexplicitautograd_dispatch.h,sha256=byVDwgcrFjUY_7-vwtuO5cM3HGhNKnyxF3Cdpq-LvIk,1037 +torch/include/ATen/ops/_fw_primal_copy.h,sha256=EPEcdpjDqsfuOYmrSXlzF59IWbxdrdTUkcPxQV9pc2g,1470 +torch/include/ATen/ops/_fw_primal_copy_compositeexplicitautograd_dispatch.h,sha256=xljGBzOGRheaqvv8CsMovYmard6RU1bfuEElvX0fx7I,1169 +torch/include/ATen/ops/_fw_primal_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=eWCHGSGN23_AouEUgK55Bx8bmY7S2StCo3BAvcy3tpU,1068 +torch/include/ATen/ops/_fw_primal_copy_native.h,sha256=3COu1iUg5bUftO7xZFq7IjBnHo-MIPfKPoxsPkhjK8s,856 +torch/include/ATen/ops/_fw_primal_copy_ops.h,sha256=BqPn0y-ejD9W_kihe-AMQUNNtMnZRiFkHttyO-iUurc,1955 +torch/include/ATen/ops/_fw_primal_native.h,sha256=1hgOMQ8BKAJvouhw1jmoQBjPirudECnFhFovpKzGKtg,749 +torch/include/ATen/ops/_fw_primal_ops.h,sha256=xlvOAkCdGyh5vDHfiWgt4HkytX3h4P-3ICdZf13iVQw,1279 +torch/include/ATen/ops/_gather_sparse_backward.h,sha256=OsMhYE-vtK8MmzizCLwyv_I1wcUrCPPyLrRQd-TvO7o,1077 +torch/include/ATen/ops/_gather_sparse_backward_compositeimplicitautograd_dispatch.h,sha256=WlxYG619OdDjb6h7qXMC84sINUC11CFXhwintaKzxS8,1099 +torch/include/ATen/ops/_gather_sparse_backward_native.h,sha256=Q5mHqsWbalZR7Qz4lMR85b1f8NBzQoqpo8rXEPFQqy0,811 +torch/include/ATen/ops/_gather_sparse_backward_ops.h,sha256=4P-fVu4UPm9K6xXA4ujhTfuAyCDy7rl04P2CsNq-0hw,1475 +torch/include/ATen/ops/_grid_sampler_2d_cpu_fallback.h,sha256=3AGo7iv7NQ-mVBF_e04qljzyNgJ0Gp6aiY4R0AtLDZY,2195 +torch/include/ATen/ops/_grid_sampler_2d_cpu_fallback_backward.h,sha256=JjkgzSbPqWNM6510ku26ajgU6il0TtHpP7ZzvIdW3Z0,1347 +torch/include/ATen/ops/_grid_sampler_2d_cpu_fallback_backward_compositeexplicitautograd_dispatch.h,sha256=BF5HPp-pY2tsVUqI19Q60iQR9JkwrS02gcNYA3TBjQc,1203 +torch/include/ATen/ops/_grid_sampler_2d_cpu_fallback_backward_native.h,sha256=dinXnigeucoYbz-iQ29Rvx-DuTWHhy4KJQEj8keo3XA,915 +torch/include/ATen/ops/_grid_sampler_2d_cpu_fallback_backward_ops.h,sha256=0Fn7oGVShuglrhzNjfscLsc83xiJiondgoJMCE3Td0o,1808 +torch/include/ATen/ops/_grid_sampler_2d_cpu_fallback_compositeexplicitautograd_dispatch.h,sha256=4xPbK_VCXWXbku8LGhy_EQ8rHjF-qXGVxQWm5iBeuEA,1532 +torch/include/ATen/ops/_grid_sampler_2d_cpu_fallback_native.h,sha256=F2bv-kkWS8LtG985EK7-rFfv7dzPnQkKoVsY43xWOBM,1046 +torch/include/ATen/ops/_grid_sampler_2d_cpu_fallback_ops.h,sha256=b5BtmpGqmN7zGhZCp4H_Tlm92EzWt4Nwf3BfHYTfm20,2563 +torch/include/ATen/ops/_grouped_mm.h,sha256=Oknxhi_RW3urjNu3gLQSruaE2B6MhgYU1l7UgEJXDYU,1192 +torch/include/ATen/ops/_grouped_mm_compositeexplicitautograd_dispatch.h,sha256=-GLNHx9IRx864cXNkMEl-tE5VyOnHiEWYdoS7njmAtQ,1196 +torch/include/ATen/ops/_grouped_mm_cuda_dispatch.h,sha256=vrJzHv9jE17zK1iXs7LvmZj6b39NVtmv6qRRKUEST5U,1154 +torch/include/ATen/ops/_grouped_mm_native.h,sha256=KihZtmkZ6QCB0XANpp5Ek3Kqyo8vwGzLdPWonsUKAe4,1145 +torch/include/ATen/ops/_grouped_mm_ops.h,sha256=WHjBMKMfSyAJuDK-we8TZVcti6doLlEiGVvIcJkAAdA,1736 +torch/include/ATen/ops/_has_compatible_shallow_copy_type.h,sha256=JvzVYninQkma7cCLj7A9Ovm-6gB0INlSFDtXPMGAv18,1035 +torch/include/ATen/ops/_has_compatible_shallow_copy_type_compositeimplicitautograd_dispatch.h,sha256=A1ugji9dhSaxQBwA62uN1QkZakN4DBbZyPC99cEmhYE,1064 +torch/include/ATen/ops/_has_compatible_shallow_copy_type_native.h,sha256=lPEEEyzCgCD6u7MJyB4hxR96aOWkYv1jW5h1H7eFQm0,776 +torch/include/ATen/ops/_has_compatible_shallow_copy_type_ops.h,sha256=y1SQrcX2Hhz77UqvYsir5XBF8hvj2jDTG20N_qN7oA8,1355 +torch/include/ATen/ops/_has_same_storage_numel.h,sha256=JsIte5GuSkCizr-dzT3Y-qpPEnTnpmKt1czMJTT8wMU,998 +torch/include/ATen/ops/_has_same_storage_numel_compositeexplicitautograd_dispatch.h,sha256=yk48siOtnOPaKdXKj8frEKZ671d0YARYf3HvYu_vjiw,1055 +torch/include/ATen/ops/_has_same_storage_numel_native.h,sha256=XBykH_i69Vo2mSYsdX5vqR5K97Jrj39_FQTs1amdzjM,767 +torch/include/ATen/ops/_has_same_storage_numel_ops.h,sha256=gDmTLhUD91aM48v_e6_xkqbHbq8LRFNjAMvqidR9Z4A,1328 +torch/include/ATen/ops/_histogramdd_bin_edges.h,sha256=zGcwlj0CPYmN-MjKFr1NvKIRaurObaVTlzv_AW8Grkc,2172 +torch/include/ATen/ops/_histogramdd_bin_edges_compositeexplicitautograd_dispatch.h,sha256=xC4THPV4Q5X53wg7diS--cg7g35rkBDjhVJXBel6hto,1415 +torch/include/ATen/ops/_histogramdd_bin_edges_cpu_dispatch.h,sha256=iBRVd-tGILfHi0Ya6o7Y3Bo_SHVArwotMbFiYwQnsIs,1154 +torch/include/ATen/ops/_histogramdd_bin_edges_native.h,sha256=zUCxrJaZfkmMbXncGENEN2ob2wger14G4MMgZbyHy0k,1122 +torch/include/ATen/ops/_histogramdd_bin_edges_ops.h,sha256=drxSaAGdAH93INVP456MKlYT8EpE1_sxKZ0_GO85Q9E,2769 +torch/include/ATen/ops/_histogramdd_from_bin_cts.h,sha256=In6rhp37etcyN2SGp370g7BIeER6eXnamicm9NP9RpI,2209 +torch/include/ATen/ops/_histogramdd_from_bin_cts_compositeexplicitautograd_dispatch.h,sha256=DRf3RHIugrMTu2KEQ26ub3wiX9X5v91yeZIMOrFObZ8,1433 +torch/include/ATen/ops/_histogramdd_from_bin_cts_cpu_dispatch.h,sha256=hyTkeFAqjh8eAYDp1tytyedRukkstmq6EemWf6Rq0e4,1142 +torch/include/ATen/ops/_histogramdd_from_bin_cts_native.h,sha256=D4Jr4I1_Jw1YUx5El3AKhrRoD6LZQ_fo1Vuz2-bt4Po,1107 +torch/include/ATen/ops/_histogramdd_from_bin_cts_ops.h,sha256=t-ryxmvxK6SgkDNCfat7NNECgqdOpfzcaY53d23BtYQ,2764 +torch/include/ATen/ops/_histogramdd_from_bin_tensors.h,sha256=XXi3LjXFtO86-EVHXkjK1vedEgDRcs_dtfoOX_7wa2o,2006 +torch/include/ATen/ops/_histogramdd_from_bin_tensors_compositeexplicitautograd_dispatch.h,sha256=qC6e9ppTsrpaTPH5_w38avOMRc8nOcl-Wni-nPLihPg,1334 +torch/include/ATen/ops/_histogramdd_from_bin_tensors_cpu_dispatch.h,sha256=5U3Eq_9aVTfxpTcFux73HC2PSSSM8XgRcVQkfw2I2I4,1085 +torch/include/ATen/ops/_histogramdd_from_bin_tensors_native.h,sha256=CWTma5YlLtHjOW6UNldw6SADVVI9lwVVFZQftca_Peg,1004 +torch/include/ATen/ops/_histogramdd_from_bin_tensors_ops.h,sha256=CSj5COc2SiQNRP28-Ijn_rB0FVylF_0mEh7BKf_8EaQ,2488 +torch/include/ATen/ops/_index_put_impl.h,sha256=yLwFi2tr1vKi3ldSW9AAPMy-pI7HaGMtrPOjZ0FdSgU,2480 +torch/include/ATen/ops/_index_put_impl_compositeexplicitautograd_dispatch.h,sha256=ZdxPYVQN11B2vzRQnVuKHZGjfZX4S6frTHbs-oHjCHM,1565 +torch/include/ATen/ops/_index_put_impl_cpu_dispatch.h,sha256=Eckm0NE-gWbQ0Zn44L4d8Y2Dz3qT3u8X19hh-cDUaC0,1105 +torch/include/ATen/ops/_index_put_impl_cuda_dispatch.h,sha256=51gizcWyfrNX9rKTxHlpJPG0b9kwWzllj7WQtu2pR40,1107 +torch/include/ATen/ops/_index_put_impl_meta_dispatch.h,sha256=uL4nByEuc-KdpaN84KzyUQeO1oMu7NDNdTIAaX5m4Ag,1107 +torch/include/ATen/ops/_index_put_impl_native.h,sha256=HAe0daZdssepvdISf4C51B4-MEfH2Qv_BMtmE46FTMM,1648 +torch/include/ATen/ops/_index_put_impl_ops.h,sha256=-EiIDOjLsULTswoDTDw0D3YuDhis1dA9iLnCFuvUKUw,3527 +torch/include/ATen/ops/_indices.h,sha256=B9bgDB6Hd_qIyHiyX0M52n0QoxAxMcbyZZ17MwT1ahE,759 +torch/include/ATen/ops/_indices_copy.h,sha256=jTYE9cJGJHvQK6ykNMDVU9vdNg1L4HEgzZiYEShcmJk,1351 +torch/include/ATen/ops/_indices_copy_compositeexplicitautograd_dispatch.h,sha256=QgR3pNQjcVbUAgB1S4D1qmC8Pk681CP90LAnVBY7UJc,1135 +torch/include/ATen/ops/_indices_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=2nZ49beNBblP71sAv06BwTiGddig-K0EKRsHlye4Fqc,1051 +torch/include/ATen/ops/_indices_copy_native.h,sha256=lvpN2CAOPXdpfRVS7VW2EzhaCtDL-tLCnSGtE2R4xuM,822 +torch/include/ATen/ops/_indices_copy_ops.h,sha256=5ABJhQinJjUS0SGVDeLJ7Mq72a_BRn1CFjtAObVCYlw,1843 +torch/include/ATen/ops/_indices_native.h,sha256=Bviu9rgkpNQsO54VIvqXwxB03TNrnL1rl-cPc6weVQA,739 +torch/include/ATen/ops/_indices_ops.h,sha256=XEzlLxcR26JtHM4DNJl1AdOL6v5sKTxqOrThUaXwkS4,1223 +torch/include/ATen/ops/_int_mm.h,sha256=vP6kGVBO0FozEkwDY2wr5MoZND_axEJ1PmSpihIJakw,1423 +torch/include/ATen/ops/_int_mm_cpu_dispatch.h,sha256=O-kSdVrNEN3K2hAUmU1M3FJTQ1oEvYVDdL9JOSciC-8,1209 +torch/include/ATen/ops/_int_mm_cuda_dispatch.h,sha256=Upp3HbSSNqd9Dfo1XsegSfge29olCIZiOMyz0Zti9i4,1211 +torch/include/ATen/ops/_int_mm_native.h,sha256=qvUnlJjpTFYJNQzC-JpEo8l-GD2wBdjG0L0r9ZgIzgA,1062 +torch/include/ATen/ops/_int_mm_ops.h,sha256=uzON3HOkVfn-VaHs7Uit0oBm5ZK_vJzNAQaVZiy9-lU,1973 +torch/include/ATen/ops/_is_all_true.h,sha256=7HwG7ClGkY-kMz_dV5rFMnI_mnvuB2Ut2uGGjdV4v2k,915 +torch/include/ATen/ops/_is_all_true_compositeexplicitautograd_dispatch.h,sha256=8dGqPyH1aZXRypFevFfh5i_ku2N7L7Ty0M6QlxCXGsk,1024 +torch/include/ATen/ops/_is_all_true_native.h,sha256=WxZLnnRxQKJCuCvlHPhdGVROUJdc3s8n4ZfGMXRW8B0,736 +torch/include/ATen/ops/_is_all_true_ops.h,sha256=oMy7qgZVxPPzYslsvladgqsUWZG29yn9URUI7ODGLgM,1229 +torch/include/ATen/ops/_is_any_true.h,sha256=KZni9CoGBeA812_m_Sy1sLh79a0gHtt_1tb1G6bfMV8,915 +torch/include/ATen/ops/_is_any_true_compositeexplicitautograd_dispatch.h,sha256=GDp3leGCp9Pk18PoJPnehQHpgo4wEulydPMBKr13DSc,1024 +torch/include/ATen/ops/_is_any_true_native.h,sha256=Qfw9XCWtC3ds_cSjW3HEyHJ7GNjAymuospkoEPs9FhE,736 +torch/include/ATen/ops/_is_any_true_ops.h,sha256=mccte8AhGJ8imAiIRogXRVg_Ae8Ov9g_DQ_8ehDAQaQ,1229 +torch/include/ATen/ops/_is_zerotensor.h,sha256=z1izUiqfNhXX6O-8TUfS5F2dWcfz1uqmbvN97yqN4FI,926 +torch/include/ATen/ops/_is_zerotensor_compositeimplicitautograd_dispatch.h,sha256=RQ2qriVDEWDI96lqyzc_dw4Zlk-dKRjGnNwjEQ7uF08,1020 +torch/include/ATen/ops/_is_zerotensor_native.h,sha256=8M3z83uvLl285t7mhTmotaobg5jq1ePFP8saUIIzlUs,732 +torch/include/ATen/ops/_is_zerotensor_ops.h,sha256=aK9Vwvof9XrPNNaPCy7G1Lk6RWe6TiSfDNOwLjTe1xE,1215 +torch/include/ATen/ops/_jagged_to_padded_dense_forward.h,sha256=y14xK8qzPSQHFtF0waSlBczdikPWmpYMgzlqhtl7Wu8,2374 +torch/include/ATen/ops/_jagged_to_padded_dense_forward_cpu_dispatch.h,sha256=62WMJ-oBtP_AI_9A3tGiF8Hqr1fYQNrceLxb-HOwPV4,1251 +torch/include/ATen/ops/_jagged_to_padded_dense_forward_cuda_dispatch.h,sha256=tGGkmrpliFrP_qc8kimo2rDV6sRw17SnYSKPTpJpGw4,1253 +torch/include/ATen/ops/_jagged_to_padded_dense_forward_native.h,sha256=QdOdnQGTpkkL8uJTOPbcT0eMkkD-eWsRET8LPshguo0,1007 +torch/include/ATen/ops/_jagged_to_padded_dense_forward_ops.h,sha256=_EqMYg0vBmrseAg--3FthFdEx4FOamOi8oxbkCk3RLU,1560 +torch/include/ATen/ops/_lazy_clone.h,sha256=y_BJD4U-ki-BqnrvgqTca4LYQi1dCiRmpwKs5s3WtB8,911 +torch/include/ATen/ops/_lazy_clone_compositeexplicitautograd_dispatch.h,sha256=3Uc8hTM0lw3nM9r3SN1rbsFpr7-szP3ZuIcYjXipa1w,1023 +torch/include/ATen/ops/_lazy_clone_native.h,sha256=-KVgQ1ouT7TjUWaTcFBeJbk0GqhM1vLT-quBbIVfbHM,735 +torch/include/ATen/ops/_lazy_clone_ops.h,sha256=Opv7LelkqSvBnwXj8cAYFSQP9pjaLJCppzpIKe4y_k8,1226 +torch/include/ATen/ops/_linalg_check_errors.h,sha256=nN8ew-8Jee5DaXtUGNb6tZtD7v5FK1pvPjlUq2FlojU,1034 +torch/include/ATen/ops/_linalg_check_errors_compositeexplicitautograd_dispatch.h,sha256=Jn6cmdryebetzoNUxd2GbA6Clx_uEDFYhLBVaHjj-fQ,1069 +torch/include/ATen/ops/_linalg_check_errors_native.h,sha256=apqCF9Nk8pWEzLbsNaEoPhhaUgselsBBp1gH34S1f04,781 +torch/include/ATen/ops/_linalg_check_errors_ops.h,sha256=AU7t6aeSziKIFe4qyTGpRMk4bowjBWHuzFdlbOOyzR0,1374 +torch/include/ATen/ops/_linalg_det.h,sha256=7OAdq-cnH1tOx2qHxRBm4FxoUNJpbU5keNnrYBjTDc4,1739 +torch/include/ATen/ops/_linalg_det_compositeexplicitautogradnonfunctional_dispatch.h,sha256=bKs74yufkRN8TSAEprisvYxHfAdNEb0ZT4oCoeKEWeI,1082 +torch/include/ATen/ops/_linalg_det_cpu_dispatch.h,sha256=orTSclzAkSEuVAIKfJZSMP5F7BVvLx_Lh7ESxOHiN5A,1335 +torch/include/ATen/ops/_linalg_det_cuda_dispatch.h,sha256=tv0iyI66MeotWwWbUi0kMVDhSAXpiPdczKG5cFGGtTQ,1337 +torch/include/ATen/ops/_linalg_det_meta.h,sha256=f1gRAY-pVAFngq2-9844Utz8ck9F_clnXeYbVSVXPXU,823 +torch/include/ATen/ops/_linalg_det_meta_dispatch.h,sha256=VkszfbK7XhaY8_omQxtXhr4S_-OdCCoTbhHb9cajuEY,1337 +torch/include/ATen/ops/_linalg_det_native.h,sha256=dJtiMdRi6W9cxhYUccW6XUJ5ZhWZqlXFFtd5N1tT67c,915 +torch/include/ATen/ops/_linalg_det_ops.h,sha256=UexIu5Ngk5t5hCtvGPzunB_0TFO9ALM_46HiDS7pGDc,2275 +torch/include/ATen/ops/_linalg_eigh.h,sha256=pRgxxSyESWhwCzqE3vy7Eincef9iAhU0pYUOhBiT4KU,2009 +torch/include/ATen/ops/_linalg_eigh_compositeexplicitautogradnonfunctional_dispatch.h,sha256=beXmcF-FRIQUi4G_ATVYBpUHlG8iHdKKXIpvoABg4FM,1120 +torch/include/ATen/ops/_linalg_eigh_cpu_dispatch.h,sha256=oXCjYSY9MDYZvrQg9r_LYGw6yO_u9uU8bu7Ut6-sQJ4,1424 +torch/include/ATen/ops/_linalg_eigh_cuda_dispatch.h,sha256=3ECkpLJwdCXaklrZu6m3_xeQa0TOJceBphGOvvIPpdc,1426 +torch/include/ATen/ops/_linalg_eigh_meta.h,sha256=IVjTv1swP6esVMlYBJYmkjSTFD4lJnJVkOMchtHdfMg,863 +torch/include/ATen/ops/_linalg_eigh_meta_dispatch.h,sha256=6BXt1HovirmqvMYO5-hjX9aVyZv8jPKKx6PTH3UZ_Gw,1426 +torch/include/ATen/ops/_linalg_eigh_native.h,sha256=TYq7E-8EwVBrZHz_sKPIV38qg8yUxZ7Sb2N3y466QxY,945 +torch/include/ATen/ops/_linalg_eigh_ops.h,sha256=leg8vw1gKVwoen9nI0HKAYYGtYIfKiCbTQg8A-FjB6E,2468 +torch/include/ATen/ops/_linalg_eigvals.h,sha256=T9GN8LIoVrqq071U2NlrNf81IZ7ucgp8yvtb9Zea5VI,927 +torch/include/ATen/ops/_linalg_eigvals_cpu_dispatch.h,sha256=G8NZm4VDaffheSe3GIrnOCa8yzthMvhZJnmmBc39H28,983 +torch/include/ATen/ops/_linalg_eigvals_cuda_dispatch.h,sha256=lTah4XbL8EqrVXrhmHMMrXMSw3pKObt38mgstUQrzPM,985 +torch/include/ATen/ops/_linalg_eigvals_native.h,sha256=uWniTMiY4vVBx3049rzStty0vBDSi48eCFV-_rUh6VY,739 +torch/include/ATen/ops/_linalg_eigvals_ops.h,sha256=m45gYnwjVooaMSq_u-m814LxQ_GNVHERlDC6fy1WVZ4,1238 +torch/include/ATen/ops/_linalg_slogdet.h,sha256=3sAUHeQZBLIvdEfexYshSjyQxSdKQuApc5A34pAyunc,1966 +torch/include/ATen/ops/_linalg_slogdet_compositeexplicitautogradnonfunctional_dispatch.h,sha256=U-YcUlJxCBR6QfUG7p1cAURY7P_giSJdfUsFh77rYIU,1097 +torch/include/ATen/ops/_linalg_slogdet_cpu_dispatch.h,sha256=IusECkYHKucwoYHVxUzncB5YNROOjVJl--glLSadwPE,1428 +torch/include/ATen/ops/_linalg_slogdet_cuda_dispatch.h,sha256=rx0PrV1M5h-NS9e13oMgjq5EjI43VwOJG475LTFP0OM,1430 +torch/include/ATen/ops/_linalg_slogdet_meta.h,sha256=uyrjqpym_MBMCBulrbwZmwt4KCylcEdLI2Iz_XyqTbY,827 +torch/include/ATen/ops/_linalg_slogdet_meta_dispatch.h,sha256=Wk7bilFLzFAQURTXnLsHlHs2dQZAR0ErPIxmIjNKxeM,1430 +torch/include/ATen/ops/_linalg_slogdet_native.h,sha256=UeJc2hENJ6S862TDnP6SnQm_8lGEorqharLmWPSVVIg,955 +torch/include/ATen/ops/_linalg_slogdet_ops.h,sha256=sALoNjfl9hSjX5NWMzJkdBv560NgMP_ZR9STrWlEBdQ,2479 +torch/include/ATen/ops/_linalg_solve_ex.h,sha256=dFYgvtzzgEDJQJy1w_isoXUR900CGivuSdjlkTgUALs,2360 +torch/include/ATen/ops/_linalg_solve_ex_compositeexplicitautogradnonfunctional_dispatch.h,sha256=xRoO0ptz9eb3VL6KLzuMokk9mKwuN2qc39mgWYX4gaQ,1161 +torch/include/ATen/ops/_linalg_solve_ex_cpu_dispatch.h,sha256=oajvVMzPYPDSWaZNCaPEKH7TjQolwRnG2c62BfXVMXs,1603 +torch/include/ATen/ops/_linalg_solve_ex_cuda_dispatch.h,sha256=XZzsQrJYUa5NpXGFjAFAwV_oTB3pfhRMV93CXjvrMs8,1605 +torch/include/ATen/ops/_linalg_solve_ex_meta.h,sha256=zjTWANQOPPa5oUklsIQv4DLWCWb0s3X9mUcLWq2C_gE,880 +torch/include/ATen/ops/_linalg_solve_ex_meta_dispatch.h,sha256=xyp25fmuR2ZxonzHqqRMLpaNXdDnewcf4F4FsWdCCEM,1605 +torch/include/ATen/ops/_linalg_solve_ex_native.h,sha256=7Bo6VLU6GULd681DXVVz8vHDQLofuCD2nruWDHYcVUY,1007 +torch/include/ATen/ops/_linalg_solve_ex_ops.h,sha256=dW2Z_nCry3rR65vH3ZuN5BqYTyrhHna5wQVMIFbHw2Q,2853 +torch/include/ATen/ops/_linalg_svd.h,sha256=rNbYo18rgipCI1IRuGBhrnJ3zEZ0kX8amTfIyGuEUVE,2224 +torch/include/ATen/ops/_linalg_svd_compositeexplicitautogradnonfunctional_dispatch.h,sha256=nzl8wivTY3HCfFtAqobddkPz2H7UJhpkXnfrOJwO7HY,1187 +torch/include/ATen/ops/_linalg_svd_cpu_dispatch.h,sha256=OW1qhWXr2EKS4p6R3SnE831kldRJSHMfJUudywrO79c,1604 +torch/include/ATen/ops/_linalg_svd_cuda_dispatch.h,sha256=grQTlXIQU9rWvdsiBc5y3JieZzwdS-NLJMwaWgRhMLw,1606 +torch/include/ATen/ops/_linalg_svd_meta.h,sha256=PAJddROtT27cyo1bPzNE3E15nrqliYQRCE44Pd2wXKg,902 +torch/include/ATen/ops/_linalg_svd_meta_dispatch.h,sha256=OqF4rnwzKOJUq1Uo8ZQwe6prqyhwo8EWwVs-0e9vK-s,1606 +torch/include/ATen/ops/_linalg_svd_native.h,sha256=BWyvEaKXH5ehBTbEYQiulTqrXNzKaTTYB7Pojg6tlAs,984 +torch/include/ATen/ops/_linalg_svd_ops.h,sha256=AT7NxPanqKGUyycJ0dGS8t8yo63SmMwRb9KEqiLcmcs,2755 +torch/include/ATen/ops/_local_scalar_dense.h,sha256=YdQi4kyJSjnkOxmDgn58MVsByVP34zT6kbhxdOhUxqo,943 +torch/include/ATen/ops/_local_scalar_dense_cpu_dispatch.h,sha256=B4RkqORNP85-ldpilHuVkSnglFod9vSkXvlXBcyAS1k,987 +torch/include/ATen/ops/_local_scalar_dense_cuda_dispatch.h,sha256=SJLgmAc1nEEO8_JOc0LNeCjakVubV2gxI0cGkcX8Gz0,989 +torch/include/ATen/ops/_local_scalar_dense_native.h,sha256=IGmKiqohSHMVzGSGZI48oyDqilpmkGxWKTQbV7Vzwu4,819 +torch/include/ATen/ops/_local_scalar_dense_ops.h,sha256=JocN89AMOnwG7MlkC8N_P5zJjXqMjAial5wlvp4IfRw,1250 +torch/include/ATen/ops/_log_softmax.h,sha256=Vc17KWDatvvzl_jFAiDtSib5rKPaNJOScIWSRAEJboM,1587 +torch/include/ATen/ops/_log_softmax_backward_data.h,sha256=cENGT2LAJCsZuaV3qTr2DgI8kxQixrl9BRo1nH9VTzg,1970 +torch/include/ATen/ops/_log_softmax_backward_data_compositeexplicitautogradnonfunctional_dispatch.h,sha256=31ElJCAOKNJOT9j6ScR1aADbeWtcGR_rZX8-wWLI-Ho,1139 +torch/include/ATen/ops/_log_softmax_backward_data_cpu_dispatch.h,sha256=Da92Ve5wa9zL1poYggLwMNMafOjZOwxsNnVhOqlwj2A,1416 +torch/include/ATen/ops/_log_softmax_backward_data_cuda_dispatch.h,sha256=kq12AV2s0b0g51RsYhVE_59tGSfi_axRN_GK_InDxxc,1418 +torch/include/ATen/ops/_log_softmax_backward_data_meta.h,sha256=RevOxSYwpFwekZx6a4t38aH-7nTFT_eb8SZ_AAVCD5w,916 +torch/include/ATen/ops/_log_softmax_backward_data_meta_dispatch.h,sha256=GxbPLRJwDak0NB8zPNjxu1gjf0X3xrUrqOSoWv9PssM,1418 +torch/include/ATen/ops/_log_softmax_backward_data_native.h,sha256=54HTvaEO-PloYuHc4NsYNc5G67oJuHbV9k2M1pKfqT0,1238 +torch/include/ATen/ops/_log_softmax_backward_data_ops.h,sha256=7AR2cy_pkPWl0H5q1t3uv-rLLlZZSvD9QfITzxrhgb0,2421 +torch/include/ATen/ops/_log_softmax_compositeexplicitautogradnonfunctional_dispatch.h,sha256=bfKJtzt_jZ_HHW_KjGEeoMFMM-cMAjz6-rbCTtufgzI,1083 +torch/include/ATen/ops/_log_softmax_cpu_dispatch.h,sha256=iGpInGk53v4qMD1ti-0Lsptov0pjY8tWmPVq6q3M83w,1248 +torch/include/ATen/ops/_log_softmax_cuda_dispatch.h,sha256=VC_ulzLlh443M41Ba5uOVDD4LK3Hf2lG1S2ULps3jdc,1250 +torch/include/ATen/ops/_log_softmax_meta.h,sha256=cQDb6O1X-OksB9qIQMj3iMrFkyRevOVCCsP_W0No4gM,860 +torch/include/ATen/ops/_log_softmax_meta_dispatch.h,sha256=xl3kcn8NY_8mPCD3z2bfxS_BEEKBIYD71LyUORkKS1A,1250 +torch/include/ATen/ops/_log_softmax_native.h,sha256=laZ31Pmq6KA045SMNjHp2Xi2wl5TBs-oqDQ9TPv_0g8,1094 +torch/include/ATen/ops/_log_softmax_ops.h,sha256=dcDZPT41LhVi8xoPJwsx6vIMrG2zYUyq5c5o-ars9n0,2057 +torch/include/ATen/ops/_logcumsumexp.h,sha256=k1kTuCmZWazs-DrmDS-NWlpflZKZ2r_O-CCGxk6LMg8,1432 +torch/include/ATen/ops/_logcumsumexp_cpu_dispatch.h,sha256=xOQdURtU8lDYB9qoa5IWk5c2dFWyIAvQb8z0EHIHLr8,1191 +torch/include/ATen/ops/_logcumsumexp_cuda_dispatch.h,sha256=TfCloLY4vg-Xun6dMYv31tNQdfuLsw66VpWmga77WUE,1193 +torch/include/ATen/ops/_logcumsumexp_native.h,sha256=Rm-xxbppAG4ZkMUZbcR5wj7W4clKvmggfLHFr9ljDjs,1038 +torch/include/ATen/ops/_logcumsumexp_ops.h,sha256=eyCNGjqtjok3vbXjJcw436KisudTv8C6jEZeDXu0-p0,1931 +torch/include/ATen/ops/_lstm_mps.h,sha256=Q8q4tEYEna7gGmLQZWkymWXC6Y1Fk6xVI9RanVHS1F0,3198 +torch/include/ATen/ops/_lstm_mps_compositeexplicitautograd_dispatch.h,sha256=veskHXK-6LMES7KxDpiCVjpQG_xA4VhcGS-3XCX8VAs,1769 +torch/include/ATen/ops/_lstm_mps_native.h,sha256=-si0UsLrZdgtcgTosZhKkcRVjfKoHQ5TJgcegPdp2Pw,1078 +torch/include/ATen/ops/_lstm_mps_ops.h,sha256=OAP9-bU8ddOeLRuDHIavhyyeK8pMXYCJY7d-eArn8HU,3703 +torch/include/ATen/ops/_lu_with_info.h,sha256=bAzbZk274x74UBS70O7zYWFpM0tZLjcidN1hkvQBsWI,1091 +torch/include/ATen/ops/_lu_with_info_compositeimplicitautograd_dispatch.h,sha256=pprMtCFldmT7wZ5VLhzDukxs74S7ZP9ton1aaZ8vioY,1102 +torch/include/ATen/ops/_lu_with_info_native.h,sha256=4UmSNjUC3z80AMPEsBspYd4gDQd3bokM3mlUvaf9u14,814 +torch/include/ATen/ops/_lu_with_info_ops.h,sha256=EPoJ9siquxaVIpnE8CpuXCg6yDjSJziMK-9sneuQ_M0,1488 +torch/include/ATen/ops/_make_dep_token.h,sha256=L4RMR-RO4zC7Aq0VldcN5WoMQZZ9YdCfo4XR7rW4Zvk,1797 +torch/include/ATen/ops/_make_dep_token_cpu_dispatch.h,sha256=aSM4FB2peO1e0nita16J7I9ON3qOWJd62N4OJCsufXw,1284 +torch/include/ATen/ops/_make_dep_token_native.h,sha256=f-1ezQBz8VLD9t3hDX3gv2zX0CVA8bGvCqyr0txeNTI,939 +torch/include/ATen/ops/_make_dep_token_ops.h,sha256=CjR3gH5mAK7DvPeMaYcaD9U9m-du5F4YfcuA5NyLxhQ,1818 +torch/include/ATen/ops/_make_dual.h,sha256=kShiyoMAx4XfV722yNcvJRqVkrL9dSZG9eDj0O-JIOk,1005 +torch/include/ATen/ops/_make_dual_compositeexplicitautograd_dispatch.h,sha256=_5LzYcN2OtDkOnxlHaGTUs8pQU1vYMPSiklhLw_QZrQ,1067 +torch/include/ATen/ops/_make_dual_copy.h,sha256=gvng4RVbzjFRg2cbfFIxoe5bDZfDYEpfsGZYSToTzQY,1647 +torch/include/ATen/ops/_make_dual_copy_compositeexplicitautograd_dispatch.h,sha256=iL8tCYcu0SelFb5FIs6kQZpsWiMZvvAimWeqBojnb8I,1229 +torch/include/ATen/ops/_make_dual_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=QciZdYPYQHzO5ITk-3_BNgLFiVlAPpcCga1uV0fc3KI,1098 +torch/include/ATen/ops/_make_dual_copy_native.h,sha256=46emE78H2drJ1kU2hAr0a7niFnkSyCcrSGHljHSGXtk,916 +torch/include/ATen/ops/_make_dual_copy_ops.h,sha256=F21kvgkZxmJkJINPnF1duFWK4YJo56QxGqZNc57-TUY,2151 +torch/include/ATen/ops/_make_dual_native.h,sha256=PmcU0bylU7qk6ArXzWZsAa0wEeDDCgjrKe1BjKtzRlM,779 +torch/include/ATen/ops/_make_dual_ops.h,sha256=_-9UOxoXCUdh_Pu7PgNIUH05cCqz4-wVt26rUANLl0M,1377 +torch/include/ATen/ops/_make_per_channel_quantized_tensor.h,sha256=Nlm-3RbfYmYBuzosO9Doo7whGxir74q4q6lZf5j2LI8,1978 +torch/include/ATen/ops/_make_per_channel_quantized_tensor_compositeexplicitautograd_dispatch.h,sha256=ub6HPt7XX-MKCXTfAL70BWI7Scs9k8hXoSGKj2Yxjf0,1319 +torch/include/ATen/ops/_make_per_channel_quantized_tensor_cpu_dispatch.h,sha256=SCf4HJ2Im114u_Bq1wzvvyl29lBfoKkllpOhsJb9zSg,1073 +torch/include/ATen/ops/_make_per_channel_quantized_tensor_cuda_dispatch.h,sha256=6mLl-TQM8YIUriwhJoGVhe7rKe1uq7L6NtjRY3lEL2A,1075 +torch/include/ATen/ops/_make_per_channel_quantized_tensor_native.h,sha256=ZfAJxbGdz1eD4iiaZ8Casp1yI5Tu39cYiM_OypYMOzM,1166 +torch/include/ATen/ops/_make_per_channel_quantized_tensor_ops.h,sha256=HsnKiZ4jnftpDi4LYEiOKELDKsZTqgbpnSYBqyoB8CE,2437 +torch/include/ATen/ops/_make_per_tensor_quantized_tensor.h,sha256=eW6yd2Yu7gndltfIQVWPar92bhA1lXi-C7rFcdnygKQ,1797 +torch/include/ATen/ops/_make_per_tensor_quantized_tensor_compositeexplicitautograd_dispatch.h,sha256=mancFkP3TRUbu4vM2Eeems9-OoZD-RPbSOGhHy-SVJY,1243 +torch/include/ATen/ops/_make_per_tensor_quantized_tensor_cpu_dispatch.h,sha256=MZXM5SWZCJVWO8jjfZp1_isKyp83bzP3CovSLx0UZug,1035 +torch/include/ATen/ops/_make_per_tensor_quantized_tensor_cuda_dispatch.h,sha256=Sacy14ZrAHsZTeWpscCnTS34ZHfUZ8jwSOdm3BtxI1Q,1037 +torch/include/ATen/ops/_make_per_tensor_quantized_tensor_native.h,sha256=odWNKoJcIz6RAw76S-YuHKb_GR3zy7EVLGxspffxwNg,1052 +torch/include/ATen/ops/_make_per_tensor_quantized_tensor_ops.h,sha256=lbdp-9kHyX5-N53dtXG8bRDj-expygmvKS8JENwNN74,2191 +torch/include/ATen/ops/_masked_scale.h,sha256=2l0PqbGWQO_CpqhyEpXltfmyAa99oBH4qXiTHG2iS8Y,1585 +torch/include/ATen/ops/_masked_scale_compositeexplicitautograd_dispatch.h,sha256=CbCAXOjrQSx4NE904hBOGVejXfLxIj4j1Xt2OWXoyts,1213 +torch/include/ATen/ops/_masked_scale_cuda_dispatch.h,sha256=09MMY41P8TkQESTMppFHDy99lCGM_H0LsyI_-UdWH14,1022 +torch/include/ATen/ops/_masked_scale_native.h,sha256=glMoa-DUeZjO4l-zd7wbpNbP6VzzHtOkGJaH-H2kT4Q,904 +torch/include/ATen/ops/_masked_scale_ops.h,sha256=KJnnCB5izfAv0SEdBb09XryasK1bkqo38fQFiApS9n0,2107 +torch/include/ATen/ops/_masked_softmax.h,sha256=hif_h_cXz_HLZrm5MBR0-8CJsYw3UR0ocuMm0ElIbmQ,1917 +torch/include/ATen/ops/_masked_softmax_backward.h,sha256=dNeFW72xVQiuOaOHhVRGpcV6PeGYSo2fC6yrmqd9cI0,1986 +torch/include/ATen/ops/_masked_softmax_backward_compositeexplicitautograd_dispatch.h,sha256=QYfH6D1cLPzb1TWcxCI1Qq7y_qlDKcb8jpsXeVyMuec,1350 +torch/include/ATen/ops/_masked_softmax_backward_cpu_dispatch.h,sha256=O-F-uzYX3b3Y-5ArdAcAAU6R2CAbOwdNhkMiHNw0b9k,1096 +torch/include/ATen/ops/_masked_softmax_backward_cuda_dispatch.h,sha256=hN3CgsvM4rxDBeMzkpIp00PS_EZK8YIygocw5UqE98s,1098 +torch/include/ATen/ops/_masked_softmax_backward_native.h,sha256=-scXyc1NA9QFNW1mUqDpCpFYkORstxazi29e4q5BQUs,1220 +torch/include/ATen/ops/_masked_softmax_backward_ops.h,sha256=7F_9wVT4_BfGX_TAHF-tCiWO91qBhWU1_p9JbWeiD9c,2497 +torch/include/ATen/ops/_masked_softmax_compositeexplicitautograd_dispatch.h,sha256=-zRxlmj8qQPkIAxQJk4B6gLxRDXej_d6M0ofM9HLV6Q,1351 +torch/include/ATen/ops/_masked_softmax_cpu_dispatch.h,sha256=8J5e6cVoL56S5v5ZHxY1oSSPsS877OCydHQhc8jA8-o,1104 +torch/include/ATen/ops/_masked_softmax_cuda_dispatch.h,sha256=fwISicEL5mnjA3w1UmCrGocbDbHA5b0UdWcWN_Emvuo,1106 +torch/include/ATen/ops/_masked_softmax_native.h,sha256=7CvF2U2YXTC0anqzpI14R8TEFoeEF8_82RVOBwJU2jc,1229 +torch/include/ATen/ops/_masked_softmax_ops.h,sha256=aoI36gcmhfoHhy-uRUtH7PucjBf-bE2oy5K70ZEpoh8,2461 +torch/include/ATen/ops/_mixed_dtypes_linear.h,sha256=7qVLBSmVjZQbsqjAyHfn26Kw0kIx8p9qoYajUjqnz0I,1215 +torch/include/ATen/ops/_mixed_dtypes_linear_cuda_dispatch.h,sha256=DnWTWYlSCjRjcxY7DjwmCHYW_U2j_nDZvRfqN-bsHwM,1150 +torch/include/ATen/ops/_mixed_dtypes_linear_native.h,sha256=ZM_2YNgYIAQDjIlwDJx1ZHJSk6_Lb6h9tZlVJBCiw08,904 +torch/include/ATen/ops/_mixed_dtypes_linear_ops.h,sha256=sZd6bOLHXTUUyVqG0NSCyvI5uJeVY7oVbMxcC19MjTA,1723 +torch/include/ATen/ops/_mkldnn_reshape.h,sha256=X6ifDS83CzjgdFdaQgb-YB4cyW-NKV4yfXmI-gMWiTs,1500 +torch/include/ATen/ops/_mkldnn_reshape_compositeexplicitautograd_dispatch.h,sha256=9fdIyoMF2So9lhmv0XYnz-pFXiSiBNL0V80YjrO3Wmw,1185 +torch/include/ATen/ops/_mkldnn_reshape_native.h,sha256=dYQO5_IxIAOTPpNozsd4pCi4_EWjXuNbl_76qb_Cjj4,871 +torch/include/ATen/ops/_mkldnn_reshape_ops.h,sha256=a2FMs-xL1Ff3Yuz95cpOfkBGB6kghL3daVbxwBHbXLs,2007 +torch/include/ATen/ops/_mkldnn_transpose.h,sha256=DLH5rxwrtcKSUvD1rop6x4vjybnbMC8YWHCyIISGuNs,1806 +torch/include/ATen/ops/_mkldnn_transpose_compositeexplicitautograd_dispatch.h,sha256=fdvNDAUeLrJW7BYvsAhCiSr0l53PhnLaWmYm-YZmq1I,1199 +torch/include/ATen/ops/_mkldnn_transpose_meta_dispatch.h,sha256=aAWHv7QMsJGJRadz1hoLQ-nOhjn4RD8udT5PbthVMrI,1012 +torch/include/ATen/ops/_mkldnn_transpose_native.h,sha256=S-2LxbWOFrjLANO3X1vxNF1A_lHli4snraD3PKlMMV0,974 +torch/include/ATen/ops/_mkldnn_transpose_ops.h,sha256=OyJQOpMbEOla-IvUjltnFnHT-56teDq9HkYvaxclG5Y,2681 +torch/include/ATen/ops/_mps_convolution.h,sha256=WOXceZcaOz2AurYWbUn3DPCkUWDpzMx8q0aOjmf3GCc,7109 +torch/include/ATen/ops/_mps_convolution_compositeexplicitautograd_dispatch.h,sha256=Hpf6-vaCasZA5SuiH_xCYnxVPgvgvJkRugS-fhfe-z0,2004 +torch/include/ATen/ops/_mps_convolution_native.h,sha256=N7hCaItIiY-LZeJJMNfu9yUnVeNBKshnUzeC70tdD70,947 +torch/include/ATen/ops/_mps_convolution_ops.h,sha256=SxGn8w9cM6HVfUDKBMER99ecpTcUBD4eTgRmeGo4J_o,3027 +torch/include/ATen/ops/_mps_convolution_transpose.h,sha256=7rDbr402p4OQrfzU7K-vpbwFtVzMQ1NRR5aj50f1T8M,7665 +torch/include/ATen/ops/_mps_convolution_transpose_compositeexplicitautograd_dispatch.h,sha256=yev_85hfQeZSFMql1Lm_Y-nV_LKXPsCwUYsRoaa6NPQ,2012 +torch/include/ATen/ops/_mps_convolution_transpose_native.h,sha256=sCoee66jIuAgDSTmqebXxxrkB4CmpFrlEcSNB2sAiPY,951 +torch/include/ATen/ops/_mps_convolution_transpose_ops.h,sha256=8XIIfGfZR_x1tamDqpVJ0oFR0pEmjQpqtYsJa_cEZys,3053 +torch/include/ATen/ops/_native_batch_norm_legit.h,sha256=Piv9Qzj77TBu3ZZYn4C-x4Lfp2C1RCTjZa2-c-XqZKw,5629 +torch/include/ATen/ops/_native_batch_norm_legit_compositeexplicitautograd_dispatch.h,sha256=LZoJ3rEVP7f0kzlpCsLBN-ETh__BgILrCDGKovFWYOY,1301 +torch/include/ATen/ops/_native_batch_norm_legit_cpu_dispatch.h,sha256=9bBXrY0yYBwv9vSjsOvxWRIxLKIbT585xYC9JPEUU7k,2827 +torch/include/ATen/ops/_native_batch_norm_legit_cuda_dispatch.h,sha256=uP7iwdONIPLFU9MA5Kev2JD5LzvDaTv--HDZz5dFVKI,2829 +torch/include/ATen/ops/_native_batch_norm_legit_native.h,sha256=dLHhP24L4Pb8wKx269ju3URq5dlwm43yAdp6GLrREbA,4005 +torch/include/ATen/ops/_native_batch_norm_legit_no_training.h,sha256=40_UY_kSvZd8eWfDtghDl9CAZHcZHFWgPAoDjKuz-2I,2952 +torch/include/ATen/ops/_native_batch_norm_legit_no_training_compositeexplicitautograd_dispatch.h,sha256=4mexEc_nSHC7KN5aSO6m8Utqf2AcIJi0RpjIxRaAoo8,2002 +torch/include/ATen/ops/_native_batch_norm_legit_no_training_native.h,sha256=ZeA9PDWZcIbwgBO2Y34Z1e48yqJnqrpN9GouLwlc1tk,1338 +torch/include/ATen/ops/_native_batch_norm_legit_no_training_ops.h,sha256=iWJJLKTjtfey9lbDR97TTqVMhURqazBwJi9CRMvkcHU,3576 +torch/include/ATen/ops/_native_batch_norm_legit_ops.h,sha256=Ig2LpSR-assOsIkywsYFSuHSxliMa0YEvLXnZnluREA,7612 +torch/include/ATen/ops/_native_multi_head_attention.h,sha256=7ChUggNS4MauHuDhmoA6AXG-7RRGDrE5eYWdGetW55M,3843 +torch/include/ATen/ops/_native_multi_head_attention_compositeexplicitautograd_dispatch.h,sha256=2DPz1ZIw_wXaqqXHLIcauzHkRrXoDrIAFICgBYA4egI,1955 +torch/include/ATen/ops/_native_multi_head_attention_cpu_dispatch.h,sha256=xn53Go1cIV3oZOGa521HlsXAwiNFzh7opb8Zl3ptv5A,1383 +torch/include/ATen/ops/_native_multi_head_attention_cuda_dispatch.h,sha256=iaiZ3v6VXOPpS9v8fE_WbkYsucI3Z_CO8mJmCVSqeCs,1385 +torch/include/ATen/ops/_native_multi_head_attention_native.h,sha256=0y0nK_orB9mfl36OyifNQbFZuY70LZdJkcA4MZPycCA,2090 +torch/include/ATen/ops/_native_multi_head_attention_ops.h,sha256=Z5sIbRr50PEYV5B19-mwB2D9A2Y_FS6dtkyc2US6nrY,4399 +torch/include/ATen/ops/_neg_view.h,sha256=p7o-UzQA_Dn32bEOK__65k0ibZ13Iqa6hLOStPG33H4,909 +torch/include/ATen/ops/_neg_view_compositeexplicitautograd_dispatch.h,sha256=Ex6ZBQqWqarYoFbdcZpsrXs9PQRJg-xWwEuEISKpwL4,1021 +torch/include/ATen/ops/_neg_view_copy.h,sha256=sWVQ2X9Zy0CBuDCybbd6xYyCOvPX67t_CXC9XTK-m7c,1361 +torch/include/ATen/ops/_neg_view_copy_compositeexplicitautograd_dispatch.h,sha256=pDPtjQhbYYa-yTf1PMUz-u61Kqq4HtkMZ2LHlBXhejc,1137 +torch/include/ATen/ops/_neg_view_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=078FA_mJpLZmv5GTNNTO6unMJ9y85yQv-JAA-MrcmhY,1052 +torch/include/ATen/ops/_neg_view_copy_native.h,sha256=fvwXd21CjdtNsUMNaURx3po0Fvp48gW7zdRV5ekONGs,824 +torch/include/ATen/ops/_neg_view_copy_ops.h,sha256=eMEN_ebhUr1DTYPmJr6zd3K74mBHdEXIT5T7evPdEx0,1849 +torch/include/ATen/ops/_neg_view_native.h,sha256=BD2ddBGe-P4PZ5ZMQ5LjKxRP335jrmYBxOnd5ouQBw8,733 +torch/include/ATen/ops/_neg_view_ops.h,sha256=bljzYKV-uoFUsGm3B9tief60GpoGlKjwRfqV1Ul3E_U,1226 +torch/include/ATen/ops/_nested_compute_contiguous_strides_offsets.h,sha256=eJz39LIIOscRhVZYQtZibgoDz9o6kBguyX4UBL2h52g,1091 +torch/include/ATen/ops/_nested_compute_contiguous_strides_offsets_cpu_dispatch.h,sha256=E0AQGIcTB7jxSksViD8VaeGGXwemIWzkE6Y8gE_pHfE,1042 +torch/include/ATen/ops/_nested_compute_contiguous_strides_offsets_cuda_dispatch.h,sha256=p2rDWVcVbQpc8-pm6k9o2ElJFmgIXgDG_lPkD5yjc2k,1044 +torch/include/ATen/ops/_nested_compute_contiguous_strides_offsets_native.h,sha256=S8gaFsTR150w-fNgrTBcibUh6Px8wsllYhKbhO4b4eI,798 +torch/include/ATen/ops/_nested_compute_contiguous_strides_offsets_ops.h,sha256=zUlSz4sUYEkhQW3mH1HZUFN8S4wmIZPCBhVkjWfhT3I,1425 +torch/include/ATen/ops/_nested_from_padded.h,sha256=qbPDTatCYiUIFUGOOgWIQdxL3n-2402UY2uEI8blr20,1990 +torch/include/ATen/ops/_nested_from_padded_and_nested_example.h,sha256=MwsHQ-RjZyiOPzdWVv0NaFX3Jan7ghsaS9a2iPyheS4,1805 +torch/include/ATen/ops/_nested_from_padded_and_nested_example_compositeexplicitautograd_dispatch.h,sha256=EEfOuSpqFC1OI_b_rc6PnWXYVnOV_5ZYYZmQ8ztvkJo,1251 +torch/include/ATen/ops/_nested_from_padded_and_nested_example_native.h,sha256=GClSqEA2CKgxbj5tbWc-M3dKrzyvvnwH76RAM8qoUNM,943 +torch/include/ATen/ops/_nested_from_padded_and_nested_example_ops.h,sha256=OW0dR3yqWtc6kohw6esBAA_1ZRfFikNsl3meXbhynRI,2207 +torch/include/ATen/ops/_nested_from_padded_compositeexplicitautograd_dispatch.h,sha256=fhCMm5O1pPZAuNxiflhVEcUpBh-yrnww-dyXu2KJpsc,1299 +torch/include/ATen/ops/_nested_from_padded_cpu_dispatch.h,sha256=y259uoH0wavd5fhAeGUHPvwNfAnTqAPUWfqNIMWxi5g,1066 +torch/include/ATen/ops/_nested_from_padded_cuda_dispatch.h,sha256=mKaHoc_6LuuywBKrMAwFllxj8b_KS7Tm69Z1T-aruFI,1068 +torch/include/ATen/ops/_nested_from_padded_native.h,sha256=GB5KLo-ARcVxt3GNUk8KaA0IbuLt95QTkOUihO4p-C8,1143 +torch/include/ATen/ops/_nested_from_padded_ops.h,sha256=w1O1u_hnp4q4i28qdp6gX9QCBXa_Peo__phlB-rbVoc,2357 +torch/include/ATen/ops/_nested_from_padded_tensor.h,sha256=vL_QabkoP93d0va5WPoo9uKY8CL7kv2IiPXOWg6pJDI,3191 +torch/include/ATen/ops/_nested_from_padded_tensor_native.h,sha256=0SAoE4aPf5nZIVqujS9jFASmof4GFAJst2Lcyq_eobA,676 +torch/include/ATen/ops/_nested_from_padded_tensor_ops.h,sha256=UG33LDfo_u6hJbCqaVR6Vtz___z-ocwZ-z2ulXiFLsc,1960 +torch/include/ATen/ops/_nested_get_jagged_dummy.h,sha256=u0t9Dp8KGzMZt6c2BrnuuflNqBzdGtX0pJ3DYrh77XY,960 +torch/include/ATen/ops/_nested_get_jagged_dummy_native.h,sha256=0SAoE4aPf5nZIVqujS9jFASmof4GFAJst2Lcyq_eobA,676 +torch/include/ATen/ops/_nested_get_jagged_dummy_ops.h,sha256=txHoQqMUEOrTWo620X4dXvh9tgSeFmJ51xshJJZ_bsQ,1262 +torch/include/ATen/ops/_nested_get_lengths.h,sha256=0TiBIJyyCdg5tExL3WnB18xRet0P1gaji7c1fFejr3c,943 +torch/include/ATen/ops/_nested_get_lengths_native.h,sha256=0SAoE4aPf5nZIVqujS9jFASmof4GFAJst2Lcyq_eobA,676 +torch/include/ATen/ops/_nested_get_lengths_ops.h,sha256=D43NKE_z8wB0-j8jozy_HyeiLyzoxbsgz2RcNTihqag,1250 +torch/include/ATen/ops/_nested_get_max_seqlen.h,sha256=nzZbB18DiKvmKWAw79alg6_ikm0QXkqpy-chSj87FWU,955 +torch/include/ATen/ops/_nested_get_max_seqlen_native.h,sha256=0SAoE4aPf5nZIVqujS9jFASmof4GFAJst2Lcyq_eobA,676 +torch/include/ATen/ops/_nested_get_max_seqlen_ops.h,sha256=Z73wu4YKRc05gORZcuuj_pV_8_o0BMmOgw28lkBGsgE,1259 +torch/include/ATen/ops/_nested_get_min_seqlen.h,sha256=syxLMrzaRafldlb72DYVtRNuX9hj61-BNZMA0mhJVWw,955 +torch/include/ATen/ops/_nested_get_min_seqlen_native.h,sha256=0SAoE4aPf5nZIVqujS9jFASmof4GFAJst2Lcyq_eobA,676 +torch/include/ATen/ops/_nested_get_min_seqlen_ops.h,sha256=22dLbSFfiEMotNaEDqq_vr_HYWLDBxzVVYenVLx_DVY,1259 +torch/include/ATen/ops/_nested_get_offsets.h,sha256=Zq67eFwT3BN5qC-tFC8lNg53m_bmUOdf3xt1lkSXUmo,943 +torch/include/ATen/ops/_nested_get_offsets_native.h,sha256=0SAoE4aPf5nZIVqujS9jFASmof4GFAJst2Lcyq_eobA,676 +torch/include/ATen/ops/_nested_get_offsets_ops.h,sha256=Lixu-4IOsN0o9Ng_rEVezkVkd8pIn1weKPfqZ8s-mTI,1250 +torch/include/ATen/ops/_nested_get_ragged_idx.h,sha256=4m0HMSdv6asF1mFwBx3otAqvv8T8rnomhgCFZykdEXk,949 +torch/include/ATen/ops/_nested_get_ragged_idx_native.h,sha256=0SAoE4aPf5nZIVqujS9jFASmof4GFAJst2Lcyq_eobA,676 +torch/include/ATen/ops/_nested_get_ragged_idx_ops.h,sha256=nrxTrL-h-PqazlXSFu5kHzUEXzA0v93QBoahEAk5q7k,1247 +torch/include/ATen/ops/_nested_get_values.h,sha256=r_ni-_UlF_M3fXAc0E5A3qPQ1bQzNHpi1KDFm9j_WwE,945 +torch/include/ATen/ops/_nested_get_values_copy.h,sha256=IGi1nzacRvkXiAbKdOth_axdtF6mMgcRdo-NGmabOqQ,1451 +torch/include/ATen/ops/_nested_get_values_copy_compositeexplicitautograd_dispatch.h,sha256=wHk_loD_qpswu7pBICrJs5G8ZE74eU3iAUhufPGzSXY,1155 +torch/include/ATen/ops/_nested_get_values_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=1l3lpyfq0q9IwynINogr7fsDGU3XWb5XZcNmJ_XyZU4,1061 +torch/include/ATen/ops/_nested_get_values_copy_native.h,sha256=g6noUV2MhXFSbDsHqL5gcjIFLyYCs5xhtJqIzMXAxnM,842 +torch/include/ATen/ops/_nested_get_values_copy_ops.h,sha256=sYjF9AxHizL4ZLmsCpUC5FaeFWvqz0DPV6jMLoxoJLY,1903 +torch/include/ATen/ops/_nested_get_values_native.h,sha256=0SAoE4aPf5nZIVqujS9jFASmof4GFAJst2Lcyq_eobA,676 +torch/include/ATen/ops/_nested_get_values_ops.h,sha256=qKjIL9j2liwOY93UXYDjiYu7ctUuQa_f-WYWC1ZPhkE,1253 +torch/include/ATen/ops/_nested_select_backward.h,sha256=tcQkdS4RMMmOHU92vqMTT1WSxSMvVGXsX7AzZonwKt0,2046 +torch/include/ATen/ops/_nested_select_backward_native.h,sha256=SF90xp5J-pGQ53Eet8pI1h4mwryadrqCQf59b4jXlyI,818 +torch/include/ATen/ops/_nested_select_backward_ops.h,sha256=Lcb-XM1bIG4DVKkG_3EqdJII19NEtibzhU0bx7BtODE,1475 +torch/include/ATen/ops/_nested_sum_backward.h,sha256=6uiixQaF-kPYwuP9QRfPzP0vgTy1FetkCzLLspewfcE,1087 +torch/include/ATen/ops/_nested_sum_backward_native.h,sha256=ZWqtD1k7li6LxgVdjoh-iMwXG5dbcHLtjwKxV2EJs7U,822 +torch/include/ATen/ops/_nested_sum_backward_ops.h,sha256=RIx-yj5qGlPyOz35NA-Ibv0qzh8emnw8PK4yJqP8rYI,1486 +torch/include/ATen/ops/_nested_tensor_from_mask.h,sha256=6uMwnpvqUOrTkupzZwhGz1W_D2sbf2Hj_BgoD6umLm0,1729 +torch/include/ATen/ops/_nested_tensor_from_mask_compositeexplicitautograd_dispatch.h,sha256=cJP7mz1eINDE5jdsVk0JssHY6F05QBlJ-6ovE5e1XzI,1240 +torch/include/ATen/ops/_nested_tensor_from_mask_cpu_dispatch.h,sha256=d7FQymcdFUYborzyVmSU34CIj-aoAR15ngVMLx2ISzg,1036 +torch/include/ATen/ops/_nested_tensor_from_mask_cuda_dispatch.h,sha256=tr2JMVq7Wuu0Fktij3qAoxu0GIXW26qkyX0J3HcJH_k,1038 +torch/include/ATen/ops/_nested_tensor_from_mask_left_aligned.h,sha256=m-8mI_HgKjNJPbU9cw4aT_kTxez4ELY5TrjlyQcfUKM,1042 +torch/include/ATen/ops/_nested_tensor_from_mask_left_aligned_cpu_dispatch.h,sha256=B8SdezwPYv43KzjKyLIJrfp7yNPhwKggJeC9PbDN9Zk,1021 +torch/include/ATen/ops/_nested_tensor_from_mask_left_aligned_cuda_dispatch.h,sha256=tEgesJtiiPNZ0jsWuGT7HpGiSxETG7ka-SvNHjGhCw4,1023 +torch/include/ATen/ops/_nested_tensor_from_mask_left_aligned_native.h,sha256=mcULN7xoyoZ2TRsZtF7D1Mwh61SfuceE-kY3KedFK04,789 +torch/include/ATen/ops/_nested_tensor_from_mask_left_aligned_ops.h,sha256=qymThN3IylZFHM4tIz0yg5vBDMIOevQ1MzTSMnYyvDg,1358 +torch/include/ATen/ops/_nested_tensor_from_mask_native.h,sha256=CsMBroXHC5BVXFNxPZG43qgR0ZY3T86-fSRErRK6JuA,939 +torch/include/ATen/ops/_nested_tensor_from_mask_ops.h,sha256=ocK5ESPILoqEWMpW79BrN7YJs_4X1-25VcHIlBE5RLY,2181 +torch/include/ATen/ops/_nested_tensor_from_tensor_list.h,sha256=iXinPceFxSheZpC773jdPI2VAeRFkfeUBgjySEGCsqU,2452 +torch/include/ATen/ops/_nested_tensor_from_tensor_list_compositeexplicitautograd_dispatch.h,sha256=S9NnU5P1toJ9CCt3w3fkPo7un8mtgwZLqj5lzAzPGtw,1793 +torch/include/ATen/ops/_nested_tensor_from_tensor_list_native.h,sha256=4beD9th12gVvJSNrIFCT4A-xRSpIHXLCHwzUy_0weAg,1200 +torch/include/ATen/ops/_nested_tensor_from_tensor_list_ops.h,sha256=p-m3FksJlwvyvMW2UpmgcFyXEvB2sM4ZBO25uKibD8I,2917 +torch/include/ATen/ops/_nested_tensor_size.h,sha256=TOcJ4zjcHmWDlL96sl-E1Ic7Hvuv1lbXr6GZUqAspO0,1237 +torch/include/ATen/ops/_nested_tensor_size_compositeexplicitautograd_dispatch.h,sha256=Ys0d2nB5aY_diK5HbZgPLSjz-jfcLxA8ejl4oeEd2_A,1147 +torch/include/ATen/ops/_nested_tensor_size_native.h,sha256=Dve5Q3AsGvOC-FEzImBACLfgCczuqQ0La-edLOMGPpk,834 +torch/include/ATen/ops/_nested_tensor_size_ops.h,sha256=ZZYqACzwLvOARnQagYpWJ31uuAwIYja7Y0dhLsH1g1U,1879 +torch/include/ATen/ops/_nested_tensor_softmax_with_shape.h,sha256=RXMJtTEl-8ngq4LRo-Gpq7oJ2VrDGtFx9sbxLoZp4Wo,1046 +torch/include/ATen/ops/_nested_tensor_softmax_with_shape_native.h,sha256=NnTWSLC0aXIy2R0rq6vYqoDHS0ncz1nJiMbcVQlELAA,885 +torch/include/ATen/ops/_nested_tensor_softmax_with_shape_ops.h,sha256=m4Js9TZNsoCMa5g6DIzUoN2iPy-s9DQVtBMxDhQ_bl4,1378 +torch/include/ATen/ops/_nested_tensor_storage_offsets.h,sha256=gYtJHftdPs9l-t0VVoV22usLk1vDWvQaJmzgDyEjXuQ,1314 +torch/include/ATen/ops/_nested_tensor_storage_offsets_compositeexplicitautograd_dispatch.h,sha256=DDs78gyojwTRBzMgZqoCUna68UU17j3dLyKbpK08doQ,1169 +torch/include/ATen/ops/_nested_tensor_storage_offsets_native.h,sha256=9wWVxOIb5VwFQbWZa1BfPMh73UME_IwCF4XTLj5bVmY,856 +torch/include/ATen/ops/_nested_tensor_storage_offsets_ops.h,sha256=4JYMSYdsHWrJq3WobN89kGdr94iymE3tHhWs6P_GBdw,1945 +torch/include/ATen/ops/_nested_tensor_strides.h,sha256=T7UZLFrXgE8wWkfmK6snp7cD7iANCSbUasVvwrTJHAw,1258 +torch/include/ATen/ops/_nested_tensor_strides_compositeexplicitautograd_dispatch.h,sha256=HYJ_89DTAS-K2hnivmLYl7bf1pzqqSfwHZVH7bXsYIo,1153 +torch/include/ATen/ops/_nested_tensor_strides_native.h,sha256=M1JxPb1uml6NQmMfBmuKWmezNo8Q-xCf_7sHegs2NzU,840 +torch/include/ATen/ops/_nested_tensor_strides_ops.h,sha256=yyO8U40gG65-21vidpDZ0a6idrSwP92gtQmhoQbpFcQ,1897 +torch/include/ATen/ops/_nested_view_from_buffer.h,sha256=2F05MotFQrLut8-9WXxn-f6YD2ae6x1GAIq3D-C6f1s,1161 +torch/include/ATen/ops/_nested_view_from_buffer_copy.h,sha256=-cezMkB4XzvtENbv8YAfAJhkpEqE4V5lZlr-JKzwgmM,2087 +torch/include/ATen/ops/_nested_view_from_buffer_copy_compositeexplicitautograd_dispatch.h,sha256=dUk1mGiyIxE3pSNl1uDtfVvRzmhTHqlHGs7jSF_ivfE,1357 +torch/include/ATen/ops/_nested_view_from_buffer_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=NSg5ojU4IYoRSRHjGwrnteUVoRIsxKuWY8upXAoGkuY,1162 +torch/include/ATen/ops/_nested_view_from_buffer_copy_native.h,sha256=4h7sHjtAMEWcZJW5tOntNhhu5p4rPXJivsqmI1-yr40,1044 +torch/include/ATen/ops/_nested_view_from_buffer_copy_ops.h,sha256=mp3RQDugyeEmnfoDvDQeftoQr7H6iPaFgj1aSnqLXkY,2557 +torch/include/ATen/ops/_nested_view_from_buffer_cpu_dispatch.h,sha256=noEMqKx5oBcIg4JfjD4A-R6LgS4nxaj9yGINfrV66Ds,1087 +torch/include/ATen/ops/_nested_view_from_buffer_cuda_dispatch.h,sha256=0SOfAqLY0jjyhrxvHlRzTmJhsB9201XQqeXQw5YDH-U,1089 +torch/include/ATen/ops/_nested_view_from_buffer_native.h,sha256=yK0-7yVCHR0z2C6BwDTfC6LKsX8YicPMcrHa-iGtBsE,843 +torch/include/ATen/ops/_nested_view_from_buffer_ops.h,sha256=cC0HgQLdMlsJ2Erv1xEJc-zyA8hOmzmGwHH9tcpKLjQ,1580 +torch/include/ATen/ops/_nested_view_from_jagged.h,sha256=HBSJCZQSB2m22oJFdIcd0WHOWWX7vf9A1P7LdFp89ho,1376 +torch/include/ATen/ops/_nested_view_from_jagged_copy.h,sha256=EIfzBk1_wizg39QzGP_gTfenokRA7FSO3tnA8nLblvE,2721 +torch/include/ATen/ops/_nested_view_from_jagged_copy_compositeexplicitautograd_dispatch.h,sha256=oneV_O0u2la4ZjSa7f8oXiLAtcnkZSMtnbc1gmkuCD8,1608 +torch/include/ATen/ops/_nested_view_from_jagged_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=n1oP1N01iBEYfOVatzEKEI19OXpr7KoQmnD8I45CDB4,1293 +torch/include/ATen/ops/_nested_view_from_jagged_copy_native.h,sha256=NA8Z06s0On7_YpOLNaY3pYc-m3oJPR53L-5Exsp6dgk,1295 +torch/include/ATen/ops/_nested_view_from_jagged_copy_ops.h,sha256=ds2eLXsd6Lm2bIBUGKQtS4yK_GmKCud3gLEji3GmI7c,3359 +torch/include/ATen/ops/_nested_view_from_jagged_native.h,sha256=0SAoE4aPf5nZIVqujS9jFASmof4GFAJst2Lcyq_eobA,676 +torch/include/ATen/ops/_nested_view_from_jagged_ops.h,sha256=2J2NFfl9yby6482uSund9MMbmUjwvhRa4Q4dHYTUpf0,1981 +torch/include/ATen/ops/_new_zeros_with_same_feature_meta.h,sha256=dIlT3WxZdEP3gsDxcoY2TIHhPClg_TsnFXqAxQS6vnM,1930 +torch/include/ATen/ops/_new_zeros_with_same_feature_meta_compositeexplicitautograd_dispatch.h,sha256=qNdZue4vTN725RTTbSBVeCYes1i_8XRBhgTZa295VAg,1425 +torch/include/ATen/ops/_new_zeros_with_same_feature_meta_native.h,sha256=21dyGksOg9JVquqobYotzQQKTPQ8hDKdxmMJiB_dDx8,974 +torch/include/ATen/ops/_new_zeros_with_same_feature_meta_ops.h,sha256=FiTwAT05czcmKiUQqT_J33iwX39vzd0ex15KAVmIhOM,2326 +torch/include/ATen/ops/_nnpack_available.h,sha256=oV6goa4QfSK2ZnP0YkUj-htxuPMbpkTqCZ6ev0aal2U,889 +torch/include/ATen/ops/_nnpack_available_compositeimplicitautograd_dispatch.h,sha256=nwl_jrYLOQJNF_Nf4Bsde1Y9YjwmLe_z32DdmxZa4jc,1000 +torch/include/ATen/ops/_nnpack_available_native.h,sha256=OJdl_W9li1i9IT0aq4sSRqlRqTVeTZqp3-5dwOd-zsw,712 +torch/include/ATen/ops/_nnpack_available_ops.h,sha256=cPDJhQBUZgS5-bmdylCEzFvkuLOqJ4fwXHqpiqUhhho,1147 +torch/include/ATen/ops/_nnpack_spatial_convolution.h,sha256=2xPWYvPZyNLoJUjU4ILOwD17DDSyJAo8RAmpl0OcIS0,6444 +torch/include/ATen/ops/_nnpack_spatial_convolution_compositeexplicitautograd_dispatch.h,sha256=qhSqoJQDRGtq7APTeOT8T0-GVJ3oinWkJaccLj6S3v4,2305 +torch/include/ATen/ops/_nnpack_spatial_convolution_native.h,sha256=EJBcEcar35qUtvANNl2NHnNJNh9fHkAo_6ea94bCbHY,1105 +torch/include/ATen/ops/_nnpack_spatial_convolution_ops.h,sha256=mBA7eDU5ysJdVpDZVUKoH9-84A_ioFb-dfrRo8dywrM,2771 +torch/include/ATen/ops/_nnz.h,sha256=1lhtBgMlJLNkXzhrmiBSMKlTdO_ElbjumibHEQWwPFM,755 +torch/include/ATen/ops/_nnz_native.h,sha256=MghWvuHpTXpKNlv5O9WMKJPd8eF2EKjHDRR6jGsz2aY,792 +torch/include/ATen/ops/_nnz_ops.h,sha256=tO21m1z6ovn14GY2KpuCjYsidQY9oROtax81ef13zys,1193 +torch/include/ATen/ops/_pack_padded_sequence.h,sha256=VAzBB43qgvNRqR_MWqqA_f1bhhAnobizbcVWmTwoZWc,1953 +torch/include/ATen/ops/_pack_padded_sequence_backward.h,sha256=aHHcQJlth0ZXzfhTvezDUoOJ1CXMnlDjtxQVQg9rZ5A,2331 +torch/include/ATen/ops/_pack_padded_sequence_backward_compositeimplicitautograd_dispatch.h,sha256=D3Edg-_Dm_2YabwbbCPUEOruFbb5DYMAHsHwVIfpEaQ,1287 +torch/include/ATen/ops/_pack_padded_sequence_backward_native.h,sha256=OyFkYMzbnQcIzlLBfSUASwTjAEKjsRWByc3ZY7BW-MU,843 +torch/include/ATen/ops/_pack_padded_sequence_backward_ops.h,sha256=XneV5fcPXUjXcs3x_Ls03vu3Fl3EJX_sxgmbBSX8VDk,1553 +torch/include/ATen/ops/_pack_padded_sequence_compositeexplicitautograd_dispatch.h,sha256=hOG9jRikNJXBqYLi71HXSvdohCRAEIlT54JGVbEIgvg,1480 +torch/include/ATen/ops/_pack_padded_sequence_native.h,sha256=PI7qNyx_QLPnYEnHrgy7WRp1tjFxrmQiaPwI12S2L8k,1004 +torch/include/ATen/ops/_pack_padded_sequence_ops.h,sha256=JabqY2LKAhiaeudwRjm0VSXAtS0N1jHBr9H5dISK_zU,2453 +torch/include/ATen/ops/_pad_circular.h,sha256=o5ucFDdsd1JISu64r-rPDXKIjxgQlbY-Ciuqs7vuUYI,1694 +torch/include/ATen/ops/_pad_circular_compositeimplicitautograd_dispatch.h,sha256=AgoYwD5vcDecPJI4HGsTU1KRZet5m-zlyIDwA5IKdxk,1139 +torch/include/ATen/ops/_pad_circular_native.h,sha256=vnkhNRGw30N893xxiI_dAqNu1Inov2PE9MqGL2DQU0o,769 +torch/include/ATen/ops/_pad_circular_ops.h,sha256=cN5RmjIHW6BPUNvE3DmXRIzUb_u7wn4mt_EpS62cb8A,1317 +torch/include/ATen/ops/_pad_enum.h,sha256=cheoBM9BGnVmhgPYVw0nqgtpmF795qOqqthOmAWheI4,2000 +torch/include/ATen/ops/_pad_enum_compositeimplicitautograd_dispatch.h,sha256=_85vUmAnX-QvMUCH9z0K49jPHJm7bJfg8uuH9ydPU34,1251 +torch/include/ATen/ops/_pad_enum_native.h,sha256=NnBsHt8oH95te3tKnLz1hbJi1EJY4IqEKI42Hzl5_6Q,825 +torch/include/ATen/ops/_pad_enum_ops.h,sha256=cImMByfi56IM9G0cpBewab1Z-9kh5M29PJ-7fqyMUyM,1458 +torch/include/ATen/ops/_pad_packed_sequence.h,sha256=_wyjVZx-ohpIF2dD9iTbPnrszIFcIhAFhzTgmnOBmLk,1221 +torch/include/ATen/ops/_pad_packed_sequence_compositeimplicitautograd_dispatch.h,sha256=knDvQ9I0JD2ZNbwn0nmSYqzGd4nPHxUviC3OLaCxCq4,1163 +torch/include/ATen/ops/_pad_packed_sequence_native.h,sha256=cKQKcsCkqSX3BEQ96PdJUus9m3WADoiw6bnKCacpiEs,875 +torch/include/ATen/ops/_pad_packed_sequence_ops.h,sha256=13sTUuiUZaS4U1LFjCx9Ymskk00jqCe3CvNEs31KHiA,1683 +torch/include/ATen/ops/_padded_dense_to_jagged_forward.h,sha256=lYAKhkELvNpDruD83Ylvzf57qJPjFCyzuVHDkSpaP00,2312 +torch/include/ATen/ops/_padded_dense_to_jagged_forward_cpu_dispatch.h,sha256=rF9of2-Su4dYaVHQg80s5oEq5Y3psbsVepw623FUOuc,1237 +torch/include/ATen/ops/_padded_dense_to_jagged_forward_cuda_dispatch.h,sha256=yT4E2vcxrIlp4tBy1ixfMDksUgGz9ERgVSCr7EqfBSE,1239 +torch/include/ATen/ops/_padded_dense_to_jagged_forward_native.h,sha256=VNMKk3iUGeb9gzTbloNRnDs4ExnvkjFUBaBBXpgXYto,997 +torch/include/ATen/ops/_padded_dense_to_jagged_forward_ops.h,sha256=PfoDrDSwS2kDzs-xqQVtbDLXM-IO42fXupICwitz_Vw,1499 +torch/include/ATen/ops/_pdist_backward.h,sha256=6ji7CJb_oj3-12CoZqmIRmEYoshdtoGsvI8zimGWS3k,1773 +torch/include/ATen/ops/_pdist_backward_compositeexplicitautograd_dispatch.h,sha256=-AMjONaE0r-P-czErpCElnW7bV20nDPDG6NdlrbecHU,1275 +torch/include/ATen/ops/_pdist_backward_cpu_dispatch.h,sha256=BdNphY7oVe1ZBHevdIpFZneXYeSOPCXoERdTekHBZqA,1051 +torch/include/ATen/ops/_pdist_backward_cuda_dispatch.h,sha256=IrzIEhWsFcCYD7CZAxs6C56A3CjlZdFeHU06vw-tA5Y,1053 +torch/include/ATen/ops/_pdist_backward_native.h,sha256=_BaeWqeqFi_Crw_zOJy6ejrDK-H1_y7g_J5UALkdF6w,962 +torch/include/ATen/ops/_pdist_backward_ops.h,sha256=sxXkdCIv1Q3hUEm-3Wa3cWXeWnQ0vTVOJDiPBfv18gw,2309 +torch/include/ATen/ops/_pdist_forward.h,sha256=SAhfuJiC_sSJ4CBTJjbYNuGiKtAd3FMUqCG4JFMyq3w,1437 +torch/include/ATen/ops/_pdist_forward_compositeexplicitautograd_dispatch.h,sha256=oZkc-g21inrOivY3kypbp_-5LOQ08eX_iz4YLl-8gD0,1159 +torch/include/ATen/ops/_pdist_forward_cpu_dispatch.h,sha256=w_y6YucqwE2ESCC3CVXXkpAUbNCFZT1i-RF4bUMRZCs,994 +torch/include/ATen/ops/_pdist_forward_cuda_dispatch.h,sha256=BbKWrdPU5JUJWpMKX0Hx-O9MgzFoIuwsxdoh64XXecY,996 +torch/include/ATen/ops/_pdist_forward_native.h,sha256=DJV2ETpnGpK2KTwEBSkI5QKrelauXuUvVJ73Zm0jdhQ,846 +torch/include/ATen/ops/_pdist_forward_ops.h,sha256=gZA3SmdXe3Z1WQ0ezUuK2ns26vBcCP_JhZuJFYysidA,1927 +torch/include/ATen/ops/_philox_key_fold_in.h,sha256=gteafgcuLShFGLXoTY_XyOC9uyGyAjgh3g6j8ETDMNg,1199 +torch/include/ATen/ops/_philox_key_fold_in_cpu_dispatch.h,sha256=KgUwX9wzWKfuG7CDVr4pvrQBWqCkPADl4N-ZjUj4SF0,1091 +torch/include/ATen/ops/_philox_key_fold_in_cuda_dispatch.h,sha256=GaZo9fG6ZtFC_Emm45q6IlvZxcexHDGuw5Qx7c-44aM,1093 +torch/include/ATen/ops/_philox_key_fold_in_native.h,sha256=az1HAvrxbhPQlUyDuhurL-8Qdi10Zk7XQaOC3MLBtqc,1050 +torch/include/ATen/ops/_philox_key_fold_in_ops.h,sha256=cv8ZCEfTsvQPLNg3eiRsOSlgFpsBErG3Ls8kBZNdNz8,1933 +torch/include/ATen/ops/_philox_key_split.h,sha256=NyOXbkQ_Oz5qC_OZUVBzARiw80aFd2NPYtiG4BKloP4,980 +torch/include/ATen/ops/_philox_key_split_cpu_dispatch.h,sha256=XqvVoL-sPd_EA42Oh9nQO7txi5kC1ZPW6I_aMrGpBqE,1004 +torch/include/ATen/ops/_philox_key_split_cuda_dispatch.h,sha256=hJlklv_LxpbMyPgJGgCMI0SyoBPUsLTbisz7tvP_bW4,1006 +torch/include/ATen/ops/_philox_key_split_native.h,sha256=5sIAs9tJ6g5xwL0vOPMGImRWG2MDk8a6I3ZLdnKZ59o,853 +torch/include/ATen/ops/_philox_key_split_ops.h,sha256=szHQlgJ6LZMlzi-UvIybgPhVbSnhYqKmxGOVwyCerxU,1306 +torch/include/ATen/ops/_philox_normal.h,sha256=-WtAEdtt1l5hOgT1wwXA24rZ6wchCmG-wcS7mjKO-aE,1955 +torch/include/ATen/ops/_philox_normal_compositeexplicitautograd_dispatch.h,sha256=u8EsO8EftjTQyh8ClN1jGKaoRfKcyaZn4L404wb0nT8,1354 +torch/include/ATen/ops/_philox_normal_cpu_dispatch.h,sha256=0yNL70szuauVAWOgstYazjB7kP_K-joCSE41YdqnZD0,1032 +torch/include/ATen/ops/_philox_normal_cuda_dispatch.h,sha256=4nIRL22APCCfXqyBvY_eOLISnPpcVyHCVUqy1cILgxU,1034 +torch/include/ATen/ops/_philox_normal_meta_dispatch.h,sha256=hP2HbUnUblle_WQXWPVb6VEy9K_XcVMd018t_QqoDT0,1034 +torch/include/ATen/ops/_philox_normal_native.h,sha256=ZDXjKO2hzkBNamg0Z2hLx9iPKLJiF7ch4x9BdQbhS5U,1159 +torch/include/ATen/ops/_philox_normal_ops.h,sha256=C0CU-zUx8hOPSyjWCLV1flIhxssTY5faeUia7lJB7SY,2891 +torch/include/ATen/ops/_philox_uniform.h,sha256=PjZdF0-IymC79edE4V-meHEs1yIpl5yw3ZAAuF02YVo,1968 +torch/include/ATen/ops/_philox_uniform_compositeexplicitautograd_dispatch.h,sha256=dKc7YLdYx-GAUu92hPZQCDjujFglN9mq31TcRWPREn8,1357 +torch/include/ATen/ops/_philox_uniform_cpu_dispatch.h,sha256=p-gtsGDhN3sJyXPXJHPqr7sasmn6XJ2wxmHHBf6uEck,1033 +torch/include/ATen/ops/_philox_uniform_cuda_dispatch.h,sha256=V0BFcdl1BKxSNG80SjWf24xK0x5UBvvWHyhPXjaN-sk,1035 +torch/include/ATen/ops/_philox_uniform_meta_dispatch.h,sha256=FOiOLxx2ZY3LxUITZITYESVHtXzS_cY6vvP9NNHPB98,1035 +torch/include/ATen/ops/_philox_uniform_native.h,sha256=Cl9vxWiaFxv5_mdcNFXtpWn_bBUOSDLOa64qeBKRkFo,1163 +torch/include/ATen/ops/_philox_uniform_ops.h,sha256=DhO5HlCHjPagpCc1KWhZsdGoH4uqILICeMTuHCCAxPw,2900 +torch/include/ATen/ops/_pin_memory.h,sha256=f48BJC7C9RGchaYMBreKLAAnOWt7lUZ8tO528RCEJGY,1556 +torch/include/ATen/ops/_pin_memory_compositeexplicitautograd_dispatch.h,sha256=2pR4TFh4mLg8JIbNPjmZlnouvrlVFNx79nqrOtGINnI,1328 +torch/include/ATen/ops/_pin_memory_native.h,sha256=GVWmoFeYHgQsUV2vKkkBY_0PB_-J6o8eOCfizizp3VM,1271 +torch/include/ATen/ops/_pin_memory_ops.h,sha256=DRrtsUcd52KFy3fBCF0bRCLTbRw2o7xClb5sl6z6JsY,2075 +torch/include/ATen/ops/_prelu_kernel.h,sha256=t9cVX2B3sJE5L8U6qDuF226d9qHbcgw4Cb6c1nhwyLk,969 +torch/include/ATen/ops/_prelu_kernel_backward.h,sha256=houKbWxWPT83Ni-v4qOVAdvvXhO48VFyPJZRT0lzHxQ,1105 +torch/include/ATen/ops/_prelu_kernel_backward_cpu_dispatch.h,sha256=8Pov0cexygKx5Hjc9FwHN-I_qyOl1sZA8ZkEOuCVtHI,1074 +torch/include/ATen/ops/_prelu_kernel_backward_cuda_dispatch.h,sha256=3OnRK62T-H-oEtFdfGcAAJXZ1wKn1qetfaSzz-5bns0,1076 +torch/include/ATen/ops/_prelu_kernel_backward_native.h,sha256=GESj8stQzse6y6RE_CecxT1-CUfie7y1QStXmDp5G3s,983 +torch/include/ATen/ops/_prelu_kernel_backward_ops.h,sha256=qN2pj58EOAhRhqdDMpwzQ5pHJVSN7acrlzt_Dl2LfjQ,1537 +torch/include/ATen/ops/_prelu_kernel_cpu_dispatch.h,sha256=804eCC9spcycAV9wPsigRLg2YuANH_hxF4i4PaTMsgg,1008 +torch/include/ATen/ops/_prelu_kernel_cuda_dispatch.h,sha256=SmM1Ll432iY1i285LPsdEfb0ciCa2bj6Haug1fSzy0Y,1010 +torch/include/ATen/ops/_prelu_kernel_native.h,sha256=6iZiOIuIG_fdMZjmYbAw2SCGEjABiYosFpKO19kpFj8,953 +torch/include/ATen/ops/_prelu_kernel_ops.h,sha256=3EI2ZjI9LjgB4eSXrv-og899JycdyKr04_mlVnlPRuc,1321 +torch/include/ATen/ops/_print.h,sha256=5OFA77nJYf8LkC-rSZ2KGkTQZiXBpmbUdR-3MJOto_o,867 +torch/include/ATen/ops/_print_compositeexplicitautograd_dispatch.h,sha256=zl_WKOQf4zPyxUUhBPK68ujxSzFQIQzG8_CC8Hs42Yk,1007 +torch/include/ATen/ops/_print_native.h,sha256=eCprfTdpT5-nMOcNXP-_tWir1um52cHjaGAawJSO3rs,719 +torch/include/ATen/ops/_print_ops.h,sha256=zkvwZygubiiO8XzYUrStY762cfrUzRsOITK0HYviVZ8,1171 +torch/include/ATen/ops/_propagate_xla_data.h,sha256=6Jo_dbF13X7oQr7NmtU7rjd3IYrgAsOdIJmUWX5SxVs,986 +torch/include/ATen/ops/_propagate_xla_data_compositeimplicitautograd_dispatch.h,sha256=ps64PnUTXuRhjL1hILg9AehyosHnrB_EAhN3-3l4OYg,1053 +torch/include/ATen/ops/_propagate_xla_data_native.h,sha256=gZ88nHqN9B6w97UnbbrRRWhy6II8UDb4s_7hPSVkgm8,765 +torch/include/ATen/ops/_propagate_xla_data_ops.h,sha256=3xnHo-pSDPbfE1QYDMoeEMilDEttUmapQl6B7VluJwk,1320 +torch/include/ATen/ops/_remove_batch_dim.h,sha256=eOpL9u5q-Qz_kB6lgOYu1BOK3eWqYSgyX5a2TdQyVZ0,1960 +torch/include/ATen/ops/_remove_batch_dim_compositeimplicitautograd_dispatch.h,sha256=Xwe8xXM4f8DLcRc9q6sthSqyWmMQGDDgDtwYBVUKczY,1209 +torch/include/ATen/ops/_remove_batch_dim_native.h,sha256=ZNniP5PB9mIjrWMf4h3ZEeP--tmkM8_8tnsPI4Vi9NE,793 +torch/include/ATen/ops/_remove_batch_dim_ops.h,sha256=6znZrY45-YMP4FoV5AdOvTD0qEyk1ByZXAUCMzxNj_U,1430 +torch/include/ATen/ops/_reshape_alias.h,sha256=ReViPo3V-LiTtuD5qSw0i-6xitFPNs64mawUXIXKj88,1949 +torch/include/ATen/ops/_reshape_alias_copy.h,sha256=7hrQF2mFmBilYx_spJuzzLi6quOqmDoArsCSgeSY2do,4814 +torch/include/ATen/ops/_reshape_alias_copy_compositeexplicitautograd_dispatch.h,sha256=0-YZVkeLhJYOD5Ba-ZNI9ppRMfp-rz2VDJDB4WIOpAw,1544 +torch/include/ATen/ops/_reshape_alias_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=N8GKbgxyKQt2sYVRnmQQ3TYOjUNDVyNMLvNZzlLmJYY,1231 +torch/include/ATen/ops/_reshape_alias_copy_native.h,sha256=tph-eWL2VYNjTkbDx0lVyK5ZQ1llXI81LbR5vxEzanI,956 +torch/include/ATen/ops/_reshape_alias_copy_ops.h,sha256=JWjYFRQPyuI0TRDTVVUDJrYGKcbxzvtLEXwtNFeGPuI,2243 +torch/include/ATen/ops/_reshape_alias_cpu_dispatch.h,sha256=V9z_QhGXRKUN7O8IL5w4hJWLiXmcZRh8d-MAqZlN0MA,1151 +torch/include/ATen/ops/_reshape_alias_cuda_dispatch.h,sha256=-t-_vz8cqBndjmsF7hFa1bC3V-pLEeUmyL5DcUI9IHg,1153 +torch/include/ATen/ops/_reshape_alias_meta_dispatch.h,sha256=XaGj8uswEiurDazL7HzNwj3QSnBpF43xCU9y9ipWzaY,1153 +torch/include/ATen/ops/_reshape_alias_native.h,sha256=qygLSg4SzkPqYFKbkn4di87iYqxFzvps1WSRd909Yw8,907 +torch/include/ATen/ops/_reshape_alias_ops.h,sha256=jZGqQc2izhQrLdWoE__8IBkEmFXgHr5x0P7M5o3SbTg,1423 +torch/include/ATen/ops/_reshape_copy.h,sha256=CetYqNpV4vOlT0tGu-beT1uO0mvK-IqpV9vNA-pxZIw,1704 +torch/include/ATen/ops/_reshape_copy_compositeexplicitautograd_dispatch.h,sha256=YovmUvVX4I97WjWOe9dWtHJRH3GAWkxYjEz6blhZ53w,1141 +torch/include/ATen/ops/_reshape_copy_native.h,sha256=vGML376As41Qx1hxEY6YyqqjVxB94S7SErJmh8gd89E,770 +torch/include/ATen/ops/_reshape_copy_ops.h,sha256=NAV-P_6a_8neA5jIY8btg4xNywiDtMigJMDd3kdJWoM,1320 +torch/include/ATen/ops/_reshape_from_tensor.h,sha256=MAiAplBHMN_UkymV0Qjp-MN-HagklaV9h1xyf_HdKqA,994 +torch/include/ATen/ops/_reshape_from_tensor_compositeimplicitautograd_dispatch.h,sha256=JaOPbYWXJFOPlQc1zUwbZcFkz63X2QFd3kqiva_CfGE,1058 +torch/include/ATen/ops/_reshape_from_tensor_native.h,sha256=v4_cg7r-qz16qgmhShPYtQNEP2QZfVWR0W1CSpZPmzo,770 +torch/include/ATen/ops/_reshape_from_tensor_ops.h,sha256=qISJkKrMyBVq9dKuKV2oloyN1k7ozg2GcARSZwdE9Vs,1339 +torch/include/ATen/ops/_resize_output.h,sha256=0Y0DX1HE1azWUJQaPFJRV4tO4iCxPd00KTCd3w47BYs,5650 +torch/include/ATen/ops/_resize_output_compositeexplicitautograd_dispatch.h,sha256=hznXLriUm5o0ojq_EvKhDkxqQeJIYFabGrlhTHOXGOE,1761 +torch/include/ATen/ops/_resize_output_meta_dispatch.h,sha256=BgJf9sp67uXVRJ0ZQ7Rum0JPveFLiOUEPyT434D7gW0,1157 +torch/include/ATen/ops/_resize_output_native.h,sha256=Dkl0hwr8J_vUe6jDsly4GPIj8HNoIUwgWjjAjGOXdzs,1052 +torch/include/ATen/ops/_resize_output_ops.h,sha256=lFyaKqF0X2wzcxtrcvnX-skHuE2MZA-LzNXQxapE4p4,2903 +torch/include/ATen/ops/_rowwise_prune.h,sha256=gOJxK_UJhxkXINCe9w3xTXvV7A32g3tNgxe1RlF10SY,1112 +torch/include/ATen/ops/_rowwise_prune_compositeimplicitautograd_dispatch.h,sha256=Kbn76FF543PcePQ23cmOZhI2BwonNQjRxD3gH2eJv6I,1119 +torch/include/ATen/ops/_rowwise_prune_native.h,sha256=bgvfHcLPZv9OZ9MFYb9YjBHuASKfMxExJp-n4eT5zRk,831 +torch/include/ATen/ops/_rowwise_prune_ops.h,sha256=SLCR51rc_G-VTbvmP9OH6gP6a7f8oliwhUVIwG1KmKY,1544 +torch/include/ATen/ops/_safe_softmax.h,sha256=fXBpzi7mkNyn0oeq9-Q65ltkcWZ_njA-WZRYklnWfhQ,1031 +torch/include/ATen/ops/_safe_softmax_compositeexplicitautograd_dispatch.h,sha256=Ig2Qvf97RxcSTFzsDJwmYMDpqCPWatXHIbgDN_6L52g,1092 +torch/include/ATen/ops/_safe_softmax_native.h,sha256=IUiXfibyQdI4ukkw2yWcyKLDZrctDq-1RBQfEHJF-ck,804 +torch/include/ATen/ops/_safe_softmax_ops.h,sha256=jKYKZgg7IBEQ4J0BO6JaUeyHwicu5aUlKI79sB9d9_Y,1411 +torch/include/ATen/ops/_sample_dirichlet.h,sha256=uCfuSXMIHuxUw6cyz9bqnf4KnWxE9WfOGks7fJ7Y8Uw,1661 +torch/include/ATen/ops/_sample_dirichlet_compositeexplicitautograd_dispatch.h,sha256=3jq_U_Qz7HZtPmhQDbWf6Zf0ykxJv2zWXWM8RtsPFEQ,1242 +torch/include/ATen/ops/_sample_dirichlet_cpu_dispatch.h,sha256=ASQ3z19-oFmygGnHZ5vzHGHD7rLtIjOfyOWVGxUKMFY,1042 +torch/include/ATen/ops/_sample_dirichlet_cuda_dispatch.h,sha256=olV0fpUQUcXm2xT_R7LVj87KbP-oeqESo9V7HaM6QyY,1044 +torch/include/ATen/ops/_sample_dirichlet_native.h,sha256=cFMCLxvkjS_PSAEKWiRGad_6rd8xEfVd143wXI5Id8w,1050 +torch/include/ATen/ops/_sample_dirichlet_ops.h,sha256=X6HJ3f1MPN9r22ZQ3zp3nlHmaZ7ELG4lDNhR4Uk4_8k,2153 +torch/include/ATen/ops/_saturate_weight_to_fp16.h,sha256=RNha5FkTQxxR0UXIlNCuSS4z2XANaMJG11LFvBFrecM,969 +torch/include/ATen/ops/_saturate_weight_to_fp16_compositeimplicitautograd_dispatch.h,sha256=yS0SNFXQz2jxuwe7Zt87JFq9UqXKA16TPX34rhwXJxE,1038 +torch/include/ATen/ops/_saturate_weight_to_fp16_native.h,sha256=AdxN_fk1juTYK7zMrCiNNvL8lLnXycQSf7zN60ZWap0,750 +torch/include/ATen/ops/_saturate_weight_to_fp16_ops.h,sha256=5T9Rc8BlPbtjuUSzLc6ysXENetHb8C1wB7xrc-WZ1L4,1271 +torch/include/ATen/ops/_scaled_dot_product_attention_math.h,sha256=_TYa8ktH1PHzHcwtRwN6qBpxbZmjQ-ajgPMjKqBuijY,1550 +torch/include/ATen/ops/_scaled_dot_product_attention_math_compositeimplicitautograd_dispatch.h,sha256=_eEt8qvdNJ35HTyWqYqYbFPHr9plP-zWGlaq5zooseQ,1338 +torch/include/ATen/ops/_scaled_dot_product_attention_math_for_mps.h,sha256=g7hR0QgcE_sOreA6O-kj-3j0_5jNvp8IAXfDviJB5Aw,1582 +torch/include/ATen/ops/_scaled_dot_product_attention_math_for_mps_native.h,sha256=0SAoE4aPf5nZIVqujS9jFASmof4GFAJst2Lcyq_eobA,676 +torch/include/ATen/ops/_scaled_dot_product_attention_math_for_mps_ops.h,sha256=JeGfvW6cgTJhIweu16yLwFYmA-HH5lirnEggUYpkI9o,2189 +torch/include/ATen/ops/_scaled_dot_product_attention_math_native.h,sha256=lrUtfvmGJ2lI1ZTPQ7PzjPtuhqdQk0Ep24jcgXN4OCg,1050 +torch/include/ATen/ops/_scaled_dot_product_attention_math_ops.h,sha256=Hxchl300QXavAAQyZLgpZNZWyF63rOTqILjce5u3Ypc,2165 +torch/include/ATen/ops/_scaled_dot_product_cudnn_attention.h,sha256=Y_5_NeGXfvohk235UKUVZgRFs7HZnK_3b0T9tHfLEKg,1769 +torch/include/ATen/ops/_scaled_dot_product_cudnn_attention_backward.h,sha256=guWO3YXvUDY_PY3ZgF4zA6SaBelbZjioKtmCwjUdAes,4717 +torch/include/ATen/ops/_scaled_dot_product_cudnn_attention_backward_cuda_dispatch.h,sha256=oZA8H0WIJDscfG5VIjMP9dcWSeaYYeSIFWrOZ4tewbk,1993 +torch/include/ATen/ops/_scaled_dot_product_cudnn_attention_backward_native.h,sha256=Tk4j3AvE4DqNIIsGZQV16lk9adYcXpkWVQSBSZzMOdA,1755 +torch/include/ATen/ops/_scaled_dot_product_cudnn_attention_backward_ops.h,sha256=DzEJ_0MEY6U3ltKq8oKS4od907SuAFpJrlmkh0WI5_M,2755 +torch/include/ATen/ops/_scaled_dot_product_cudnn_attention_cuda_dispatch.h,sha256=ja7ieHhj_P7B5Tyf4RlWQyiV3aMKL9WZHYcWIZcD-OY,1352 +torch/include/ATen/ops/_scaled_dot_product_cudnn_attention_native.h,sha256=JTe1uzm1cKP2SMKTEJvSD1VXRR7Vxbpkb1DjALSo9j0,1559 +torch/include/ATen/ops/_scaled_dot_product_cudnn_attention_ops.h,sha256=ztRblSKZWgG-JzkKd59jzGOzt_wF_6uaNPKJT9Az4H8,2485 +torch/include/ATen/ops/_scaled_dot_product_efficient_attention.h,sha256=oIzzTb7AxKgxUT6h8fhUsrKV8tTHYWIQ9VXy9bY53xA,1562 +torch/include/ATen/ops/_scaled_dot_product_efficient_attention_backward.h,sha256=8iG2kcH3RzKLKUvgyMJhTU0khR8p-kq4Kd-F-MrABys,1833 +torch/include/ATen/ops/_scaled_dot_product_efficient_attention_backward_cuda_dispatch.h,sha256=xt_dgIQETh8Xd00wCk7flwo0HiZ8-ycdmXKNdSorp3Q,1420 +torch/include/ATen/ops/_scaled_dot_product_efficient_attention_backward_native.h,sha256=UiE9SlKp51xMit_8HeDuMIzo5AiUVLGVJyS0DOGKoXU,1179 +torch/include/ATen/ops/_scaled_dot_product_efficient_attention_backward_ops.h,sha256=jdMQ0XZWQ490YpHrer26ZyP6XEFvtAiE0ED_cuFQ5WQ,2614 +torch/include/ATen/ops/_scaled_dot_product_efficient_attention_cuda_dispatch.h,sha256=XR3vVssxe6h1rAzus4mu8tg6pmU-dtQmtD0Vc8m1tK8,1269 +torch/include/ATen/ops/_scaled_dot_product_efficient_attention_native.h,sha256=zjbVX1j4eayG1cpQ7U96v4TVa45laC1126gvCyEiDAA,1393 +torch/include/ATen/ops/_scaled_dot_product_efficient_attention_ops.h,sha256=Qp5BxaHjlxCeU0pIMoqyupIiyMUfTC37zp1CogwKEnY,2155 +torch/include/ATen/ops/_scaled_dot_product_flash_attention.h,sha256=cngjBw61Uvy4WM0h8MZV-9e7Pwz7Z4U2juloMZh9wk8,2692 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_backward.h,sha256=bfTRMLwYVILUmWXMqgGry3eoSmHqU0C5HOwsysS8IPA,4579 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_backward_cuda_dispatch.h,sha256=xpG07K1M8QZugD2zuSibkHp5Rvtg2Cg4VeP1e3xiDaM,1933 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_backward_native.h,sha256=VMOnC4uilfT2ycz5d26S5qAm1e8nbpY6bi1AXNdepCw,1684 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_backward_ops.h,sha256=XUVZ39QSXd3DGzoEPKCu9YYk8-gW7YwNSfV_fT7CHgc,2688 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_cuda_dispatch.h,sha256=xS9MO3W0qgRmGBZnRZwFaIUbLwYHiC-zBgdbnzTusus,1779 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_for_cpu.h,sha256=XvYvOuB4Lc9LBRUKStYjSZNnjS9BhBYbfRx9Zps05iY,1451 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_for_cpu_backward.h,sha256=T44fSiswgcEhzGmnnblItTTHKUx1knaOGm1HB09xIG0,1656 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_for_cpu_backward_cpu_dispatch.h,sha256=xRJSuu7OdMOh3p61Iy5K8yMHZdYfXZKPX4KDRedGSxs,1320 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_for_cpu_backward_native.h,sha256=Ok5e_LibHBAyw4MWT0Fw4jbfVz2LUQN8_4RP63Mvxz0,1072 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_for_cpu_backward_ops.h,sha256=BsXy05iGQr3gywL-66xw4zu6ECoziyfFLxadvy1UDVA,2327 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_for_cpu_cpu_dispatch.h,sha256=ubvOoqbhAHoxXMRC-8zy3W2DkBLlPdOgBpDbHPR4tK8,1227 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_for_cpu_native.h,sha256=t4iu9-OSrOW62l-RGutiOUGASk6zAV_ir75QSK5UnJs,979 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_for_cpu_ops.h,sha256=mtmXBmdPYb0uqfXjdvh1Zd9_UZSKEsMC36W9CYonL8g,1982 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_native.h,sha256=MEFq7loFsToVtuVMtof3GauDBEJ-0NOSByUL_7aSqJM,1929 +torch/include/ATen/ops/_scaled_dot_product_flash_attention_ops.h,sha256=FLqMF0IZ07A8kT6dKfaz3E8vhFtqh_IibFi5IKBZ5QA,4258 +torch/include/ATen/ops/_scaled_dot_product_fused_attention_overrideable.h,sha256=OX16nWo0XgylrrHdN43oHx9A5_i8GU_6zkxyfbrcRkw,1759 +torch/include/ATen/ops/_scaled_dot_product_fused_attention_overrideable_backward.h,sha256=dTHaB2E3ejSBjRUmMOmrrz2gMbTMrR2zSGeC2QNpF08,5282 +torch/include/ATen/ops/_scaled_dot_product_fused_attention_overrideable_backward_compositeexplicitautograd_dispatch.h,sha256=x4_rX0eySBtka0fHxPb5wpxCnvLRS8nBQ1zSdvU3rm8,2159 +torch/include/ATen/ops/_scaled_dot_product_fused_attention_overrideable_backward_native.h,sha256=R8HD1CtZxVrA876Ss3FGgFNyNfx7Euo8bPg-09tY-u0,1266 +torch/include/ATen/ops/_scaled_dot_product_fused_attention_overrideable_backward_ops.h,sha256=n7dvP0-SJPSva12sveflpCDsZEEZDjYfS8B3kEK8wsA,3004 +torch/include/ATen/ops/_scaled_dot_product_fused_attention_overrideable_compositeexplicitautograd_dispatch.h,sha256=gNB-hIMsciN7KHcvN8mLle7y_jBWKbj4s2l5gFRqLRU,1385 +torch/include/ATen/ops/_scaled_dot_product_fused_attention_overrideable_native.h,sha256=7rUEqX__mv3Gigo808FQLL926uKdLbnFc3l4MsOhl98,1097 +torch/include/ATen/ops/_scaled_dot_product_fused_attention_overrideable_ops.h,sha256=aL877R44j4ObBaTMB1coDQ-wmTybIuE1EQbSSlojI2A,2448 +torch/include/ATen/ops/_scaled_grouped_mm.h,sha256=5fH8ry71RiDFW-8OfBXBPvo6iTisN0VgfdFtKWx2t2Q,1490 +torch/include/ATen/ops/_scaled_grouped_mm_cuda_dispatch.h,sha256=pOmC0lABNzTDimislWqwtXfApjj7iHlZb2HysadRKgE,1297 +torch/include/ATen/ops/_scaled_grouped_mm_native.h,sha256=JyBtRzlUDxKfBRSalre6Qo4g53irZ8FaTdg-He2-iRA,1056 +torch/include/ATen/ops/_scaled_grouped_mm_ops.h,sha256=jQZgnj4Pp8iSdGG1Qlh-egj7vLZL_cdr1qMvJRLc7Fo,2180 +torch/include/ATen/ops/_scaled_grouped_mm_v2.h,sha256=I4WIb3QieNWbsSLKolPG8n2GjS8wgSgPI3FwvD0R-44,3711 +torch/include/ATen/ops/_scaled_grouped_mm_v2_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Mh96R6NPXmU9YmyGMF879Uj_mCVt56GnNdjxDmvZzzY,1473 +torch/include/ATen/ops/_scaled_grouped_mm_v2_cuda_dispatch.h,sha256=iz5PpsEtM0rhw6ccv1YrfY5IvPl7Z1y2gfMYg3lkCBU,2390 +torch/include/ATen/ops/_scaled_grouped_mm_v2_meta.h,sha256=aWP3Awy1ibMsIK8dKyXr2GLTRiO5E6UA1IyiZFXpOVo,1192 +torch/include/ATen/ops/_scaled_grouped_mm_v2_meta_dispatch.h,sha256=GNtxkKzSv56Y1Lv5cZMgXJxENPEhuXpE0qMJ9HYreTA,2390 +torch/include/ATen/ops/_scaled_grouped_mm_v2_native.h,sha256=aXZVlqz95mIGhZ42tf4BwPWZvp3RxccjyEsTw6g1QrQ,1256 +torch/include/ATen/ops/_scaled_grouped_mm_v2_ops.h,sha256=TuzCmTYPZahfIGNZs-57cx55C4mTqgPGtYLk4bUUy9M,4443 +torch/include/ATen/ops/_scaled_mm.h,sha256=SxYr8M0K-PvNWV0rq1SXxqk6r4B4RfwlaiTL0R1LELU,2737 +torch/include/ATen/ops/_scaled_mm_cpu_dispatch.h,sha256=uXKAuos4jLgSi2NYYH4Ql1aVrDHC0o3qOcgSw56ahtY,1908 +torch/include/ATen/ops/_scaled_mm_cuda_dispatch.h,sha256=TmK3LinNsD1INvIPaVWtVvRweI6PmDHptC2f5n0aeqg,1910 +torch/include/ATen/ops/_scaled_mm_native.h,sha256=G2dQN2ulY42Ts9dRuI89IfcuErWjSt1NsdtLjqp3Teg,1976 +torch/include/ATen/ops/_scaled_mm_ops.h,sha256=QGCS_zvD2Dk2P0lCYPBuRDhAc8W5dTnckSnwMkgiVCQ,3411 +torch/include/ATen/ops/_scaled_mm_v2.h,sha256=SS_-D6aaahVrKKayOrRL0OWD8vcdfBYfBzAVYgJLicc,3358 +torch/include/ATen/ops/_scaled_mm_v2_compositeexplicitautogradnonfunctional_dispatch.h,sha256=cLJf59TGkxp9svYWuep4KR-D9tRUy6Z9oyTgOGqwqjI,1402 +torch/include/ATen/ops/_scaled_mm_v2_cpu_dispatch.h,sha256=CNaX93uvMU9ta3qU7xk9rtaGPs-OYz8bJ75wV92c0CY,2196 +torch/include/ATen/ops/_scaled_mm_v2_cuda_dispatch.h,sha256=S_gjN2G8Y1PALC7m2-5hQtgwB1O7aUqH-OcIhFK54cw,2198 +torch/include/ATen/ops/_scaled_mm_v2_meta.h,sha256=p81c90nxIaLT1DByrdlVqamR73TyUZePo-rBPJ5TtFY,1156 +torch/include/ATen/ops/_scaled_mm_v2_meta_dispatch.h,sha256=gdKNlN8KLPlvzJEEgyOMit-f4zYoq4h2mzKiH2P8w9s,2198 +torch/include/ATen/ops/_scaled_mm_v2_native.h,sha256=QNUJrC7ltrO8WNFItsTPy6cx68pqewLLnLG94rwKVq8,1691 +torch/include/ATen/ops/_scaled_mm_v2_ops.h,sha256=PQlTvw97wwTapPpKKpnuN4nBDE2A2nZB7WCa1xP5rLo,4095 +torch/include/ATen/ops/_segment_reduce_backward.h,sha256=vWDpFfJnjyTOSmc2nHlmlO5A8UfRQ2kadsMQKuQdpes,2707 +torch/include/ATen/ops/_segment_reduce_backward_compositeexplicitautograd_dispatch.h,sha256=QmJhzSRJYKQhDspir9ZHg88cb5TbVhkhm44orgLHXmE,1632 +torch/include/ATen/ops/_segment_reduce_backward_cpu_dispatch.h,sha256=fBCvjzY1-eqrongBoCAnyaTux29OtpQWttWOV4tHzx0,1241 +torch/include/ATen/ops/_segment_reduce_backward_cuda_dispatch.h,sha256=Eg8VaPpl5O1S5zDpAQCTsKuGvi6gIu_K7pogSCJo1jY,1243 +torch/include/ATen/ops/_segment_reduce_backward_native.h,sha256=eY7cybZJSDck8JxrPYdsgQYD2UxiJ_ang_06pW95i4s,1326 +torch/include/ATen/ops/_segment_reduce_backward_ops.h,sha256=XCDcxrC0_5e4K7IkF6a-O-0DNkABncuRD-X0B1kRPQE,3408 +torch/include/ATen/ops/_shape_as_tensor.h,sha256=5cBcV9Y3mIgrz9FYwsv6P9AFPV0NYa_32s3PXwJAqUk,931 +torch/include/ATen/ops/_shape_as_tensor_compositeimplicitautograd_dispatch.h,sha256=LkHLx596h8aTto0QYiS5Bp1ZRgkUzAd2ivtQx_ba1Yw,1028 +torch/include/ATen/ops/_shape_as_tensor_native.h,sha256=6_jJzgkp8kEN5q18QSiV9y98CXgCm0DDsrhNRwRjOiI,740 +torch/include/ATen/ops/_shape_as_tensor_ops.h,sha256=Q_WY76hISVwIcpo9qukzHnyNpmSCViT2j5LXCuJgo9I,1241 +torch/include/ATen/ops/_slow_conv2d_backward.h,sha256=q5cCUlgUROJMkEVsWUt4B61fstGH8vA5h_LdG7IIrlc,14784 +torch/include/ATen/ops/_slow_conv2d_backward_compositeexplicitautograd_dispatch.h,sha256=1eq9KUm7R8OMCQAgJj0AaBCVyrG27_WrgUD1Ii_VEbQ,2376 +torch/include/ATen/ops/_slow_conv2d_backward_cpu_dispatch.h,sha256=9ZG5qi3HQfBISIRCoba20QYy_7MeZJlt1LdlWY39Ogg,2839 +torch/include/ATen/ops/_slow_conv2d_backward_cuda_dispatch.h,sha256=qE01tDtOcLqdmU3Md2B1t90Edp1Oa5Qh8WCAUkhTeEA,2841 +torch/include/ATen/ops/_slow_conv2d_backward_native.h,sha256=v3MfyZWyD2h8AYRIT7gQfHrx3K7B3RD4UFxLEj9uM50,2270 +torch/include/ATen/ops/_slow_conv2d_backward_ops.h,sha256=xJk_txYe9lmIZIrP-NKKij__-fsPnPNvzdn_cDnqyAU,5115 +torch/include/ATen/ops/_slow_conv2d_forward.h,sha256=qxkRvjqxn357DQSz78KkkT6w69lrrg23pAxZpazZxRk,7035 +torch/include/ATen/ops/_slow_conv2d_forward_cpu_dispatch.h,sha256=KRL0Jud3OYaSu610QTiFpgyGZ42a4FS_hiaEyVJV39s,2377 +torch/include/ATen/ops/_slow_conv2d_forward_cuda_dispatch.h,sha256=fgfhOSXJp5OZSrJDT6LSIIWHKq0esaOSX3YB6dFd1Wc,2379 +torch/include/ATen/ops/_slow_conv2d_forward_native.h,sha256=5HTfK0oOpvJJ6I_WUDtyIbUCc9RNmsI20pzu7wzhhvQ,1604 +torch/include/ATen/ops/_slow_conv2d_forward_ops.h,sha256=IyiW8shg7orMvtokL5slUchXv9rbR62TD9Hadn39jVM,2957 +torch/include/ATen/ops/_sobol_engine_draw.h,sha256=lvsUWXNIgr9r56OOVJFq9CRz7vpxsdHJFPBPQ2zMzyI,1227 +torch/include/ATen/ops/_sobol_engine_draw_compositeimplicitautograd_dispatch.h,sha256=65Ym5KrYaQNz4TdyxF0GgBpxPb2Xy3BMJDGiaFwMnH8,1179 +torch/include/ATen/ops/_sobol_engine_draw_native.h,sha256=vNo9jtij6VeNmN9dXuzmknkeph_0BRsgmvxT5p5_oiU,891 +torch/include/ATen/ops/_sobol_engine_draw_ops.h,sha256=1aXyvdNp-nUZgxAz8qNLs4N-YvacCKfNeQiPyKwhfbU,1740 +torch/include/ATen/ops/_sobol_engine_ff.h,sha256=ZH5vRLbXj81-ahRDCQq6c16lg489WdzUyage0k1zV8U,1123 +torch/include/ATen/ops/_sobol_engine_ff_compositeimplicitautograd_dispatch.h,sha256=iF1A81S53AIupGsoa7Kru6LC-lpWRYnHU6WEVccLUyM,1109 +torch/include/ATen/ops/_sobol_engine_ff_native.h,sha256=cNK56cUosSNE6BK1JZEbWK8YpzdBPwnVD_dY7u9wV70,821 +torch/include/ATen/ops/_sobol_engine_ff_ops.h,sha256=3GLaQlauLSyTMAXDjAK0jx8RuALpvL7MntnEMbee_b4,1515 +torch/include/ATen/ops/_sobol_engine_initialize_state.h,sha256=_PdWJ2ZbqLToQuWJUF8zC23aFA4daA5SKUW7EQz0k0o,1039 +torch/include/ATen/ops/_sobol_engine_initialize_state_compositeimplicitautograd_dispatch.h,sha256=u148FflLZtFN_nfTPzAhpxQkSNPV32vU6bCKtRQHMMU,1058 +torch/include/ATen/ops/_sobol_engine_initialize_state_native.h,sha256=vJA4CfAXV9boGHvHdbcKcSf1QjrUWMOB94rQiQ8H-fU,770 +torch/include/ATen/ops/_sobol_engine_initialize_state_ops.h,sha256=vexYzpW2yMRfwXqHVqriXgb4IXlb1x7CrO31Nh-LNws,1344 +torch/include/ATen/ops/_sobol_engine_scramble.h,sha256=DQOI4cEmgNk-4engAmYN-O6crpFPGhltET9GDqpWdtQ,1048 +torch/include/ATen/ops/_sobol_engine_scramble_compositeimplicitautograd_dispatch.h,sha256=e7NWRZCxyhN7YsebZOzdId9XIYNT9BL1Ft5bhKT1EfM,1074 +torch/include/ATen/ops/_sobol_engine_scramble_native.h,sha256=wD6RyT-6CfRE626PmzOxucBmDbkK0OGJ2v7nmpTa8OM,786 +torch/include/ATen/ops/_sobol_engine_scramble_ops.h,sha256=lq8Abkv4aJJL2qA8y8lmXlMtwb9YBMg4tA6pnbkKIRE,1400 +torch/include/ATen/ops/_softmax.h,sha256=8lOsfawl-QWdBIWspiWtWMOWalcHFMQIasvUolQ7y8g,1547 +torch/include/ATen/ops/_softmax_backward_data.h,sha256=dFj_eQOb2zHjd9U9iQMFqHgDSXLF76Gmf2PBLVjuhV8,1972 +torch/include/ATen/ops/_softmax_backward_data_compositeexplicitautogradnonfunctional_dispatch.h,sha256=dpoxWsAEphwDD8laI2JQkrOOCFBTFwL8n49Nk2M4Z18,1135 +torch/include/ATen/ops/_softmax_backward_data_cpu_dispatch.h,sha256=Z47zOaFUgXtAtlvonugAgVKfrSV5mPH6B-nNhb9EzSM,1418 +torch/include/ATen/ops/_softmax_backward_data_cuda_dispatch.h,sha256=wGhaqWx7Z8wi1lmnBac_dwzXI0SvYcQwlu6RWs8aKYo,1420 +torch/include/ATen/ops/_softmax_backward_data_meta.h,sha256=cxDyRkbKF_4azg6yjdUoYvK0AxQ7fYlq1DqkB8tdPsg,912 +torch/include/ATen/ops/_softmax_backward_data_meta_dispatch.h,sha256=HdM-irR7kbKN9l4yENrmJzCDeWAc1tC5WqscbeNzIrA,1420 +torch/include/ATen/ops/_softmax_backward_data_native.h,sha256=o3mB1NEY5NboLqp1H7rGSH9MWQT4UPgsYPgSNgk_a5s,1378 +torch/include/ATen/ops/_softmax_backward_data_ops.h,sha256=0cxJZhGOtOUpTUkxJoq6-up6hwmeB-6l9XBUqP9MPU8,2418 +torch/include/ATen/ops/_softmax_compositeexplicitautogradnonfunctional_dispatch.h,sha256=pyg2QGOmd5bf_CcTCmF3bLiNiXwtdVp0ZiWtFhXiOYU,1079 +torch/include/ATen/ops/_softmax_cpu_dispatch.h,sha256=nWnn5RAdOuSOdxRWKovDc78M4dQv-G4ekxnf3-QS_3I,1236 +torch/include/ATen/ops/_softmax_cuda_dispatch.h,sha256=eyU0svBZ3lzVw-usu6SlQJtiFJcM6IjTHstX-YIzHCQ,1238 +torch/include/ATen/ops/_softmax_meta.h,sha256=aRU51tHchS-GOToBhfgBbLDa-1RKq2GdDdhmf0543Q4,856 +torch/include/ATen/ops/_softmax_meta_dispatch.h,sha256=obxSUmWx_vMfnR_vZOy7cVKmQk4gZKmcPcnawXJg5WM,1238 +torch/include/ATen/ops/_softmax_native.h,sha256=9hrvUOrNewBAEBVymKc2hfp1qT7_7YdvBF1VUMgQm5Q,1264 +torch/include/ATen/ops/_softmax_ops.h,sha256=e0_lj7QnXdXxtVHvqMbHaF3JDuC6cV4uB3tXuZS4c4Q,2033 +torch/include/ATen/ops/_sparse_addmm.h,sha256=JEdDAUeHzFcYB1FpwpQQW7o49AtinJCvrRhW0p31F1U,1911 +torch/include/ATen/ops/_sparse_addmm_compositeexplicitautograd_dispatch.h,sha256=51DXy9yeutts-LVrlp4J2IDDQHPCFi9iaNKFgzgZ65A,1507 +torch/include/ATen/ops/_sparse_addmm_native.h,sha256=drjrZr7Caqn2xmXATLFVBFFPbTVgfuPmsLe4MdZTckM,1028 +torch/include/ATen/ops/_sparse_addmm_ops.h,sha256=mhHRDikq1oFt8Ru8xFa1sf94bcPCSdS5ZL2rwcwLFqw,2524 +torch/include/ATen/ops/_sparse_broadcast_to.h,sha256=yUS1PDFUk1Jb0PDUX3g0ot-M5bMp4nIVbP7qrASbWLM,993 +torch/include/ATen/ops/_sparse_broadcast_to_copy.h,sha256=nrKzCAJzPSeZKvTnDO5eavcSGyIL8BJczKJ9T6_Z5Ro,1591 +torch/include/ATen/ops/_sparse_broadcast_to_copy_compositeexplicitautograd_dispatch.h,sha256=zrtDHs6SaISFfJSasbJJV4ziG-sX5WA2SC_m9JtgurQ,1203 +torch/include/ATen/ops/_sparse_broadcast_to_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=TK2VUzQzMHc8E4KsaTaHvSxp1RNvHI4t0SmfdLpoIMY,1085 +torch/include/ATen/ops/_sparse_broadcast_to_copy_native.h,sha256=2iik3L_kA3bawcG0SVqdXovWDGR03FV6OhJjwaVhF-M,890 +torch/include/ATen/ops/_sparse_broadcast_to_copy_ops.h,sha256=em22CsWUQz8V9_ZJAQC0JLka6szWPGsFAQQKLfRdogs,2061 +torch/include/ATen/ops/_sparse_broadcast_to_native.h,sha256=eZPbTAYymLlhoPzk_1pkDGu062cygSzL95GLXRwy2Hg,765 +torch/include/ATen/ops/_sparse_broadcast_to_ops.h,sha256=Kz8GL2O53DLp9cBtOiqUacRnuzchb_jVxa0zlC2N_8Q,1332 +torch/include/ATen/ops/_sparse_bsc_tensor_unsafe.h,sha256=A2gN1HzWjMa_tMcO-72B6tadPtBAbuKeQYuSxbFYKKs,2034 +torch/include/ATen/ops/_sparse_bsc_tensor_unsafe_compositeimplicitautograd_dispatch.h,sha256=uYmltbo0r8Y1eE94IBKOTcwmUXZF47oCl8MZLB7JvFE,1463 +torch/include/ATen/ops/_sparse_bsc_tensor_unsafe_native.h,sha256=sKWgsCui-VOs1KC5YqP8hgH_FLcQtJv_BYAbkPJgtdI,995 +torch/include/ATen/ops/_sparse_bsc_tensor_unsafe_ops.h,sha256=mfpeNSPJRWupTJUgnasOtDtzGrAi-qUIOYlmp37vAQQ,2054 +torch/include/ATen/ops/_sparse_bsr_tensor_unsafe.h,sha256=Q9xkWvd4fFu_2-FIejybvXsjrJXAD55JebRKdeEhp9M,2034 +torch/include/ATen/ops/_sparse_bsr_tensor_unsafe_compositeimplicitautograd_dispatch.h,sha256=1a0LwgVW-jOhsbCIDot7Yguay54rGphf8YMvuYbESIM,1463 +torch/include/ATen/ops/_sparse_bsr_tensor_unsafe_native.h,sha256=7SGI_yU64V1K-U7CLYx51A1zl8cO5VqpEi2f1uwxdsI,995 +torch/include/ATen/ops/_sparse_bsr_tensor_unsafe_ops.h,sha256=GPvZEdldYhgn0Z5DOYhk6gdJY_lsyRH2AXv4QKcRfik,2054 +torch/include/ATen/ops/_sparse_compressed_tensor_unsafe.h,sha256=zeEkVnGhQg2wxwNl3vZrpR5DEgZ0yAO44k0m48QSGVM,5848 +torch/include/ATen/ops/_sparse_compressed_tensor_unsafe_compositeimplicitautograd_dispatch.h,sha256=yapsu8aA6yNbvHAAa2AtfwEfHEd2u8mvvjpDA8C9vs0,2044 +torch/include/ATen/ops/_sparse_compressed_tensor_unsafe_native.h,sha256=4QGn8qwVFR8jgs2yGbRbaW6HFocgS-fR2-1oBwFcRew,1021 +torch/include/ATen/ops/_sparse_compressed_tensor_unsafe_ops.h,sha256=ya8ZkcT2VTETU0zGDLZu5qbABidrTNbthlALCRGt3tw,2114 +torch/include/ATen/ops/_sparse_compressed_tensor_with_dims.h,sha256=Txw7x1xRKi8Hg-gomGnwVHwQWqvIGyYxKEI0WdiMi_E,2121 +torch/include/ATen/ops/_sparse_compressed_tensor_with_dims_compositeexplicitautograd_dispatch.h,sha256=gU9X8no1v8UPgW0K9rsQUPmt3edA9z72-OPAtS2hvXM,1470 +torch/include/ATen/ops/_sparse_compressed_tensor_with_dims_native.h,sha256=wSjtN6NMkx-wabA6DmMJAVWjAbfzmjtS_gxXddpNIVw,999 +torch/include/ATen/ops/_sparse_compressed_tensor_with_dims_ops.h,sha256=Qxbr_UV6rG8_rtVPEts_kgMANSmr4tmGQDL3mn-Nrr0,2075 +torch/include/ATen/ops/_sparse_coo_tensor_unsafe.h,sha256=MRqgWKE7p1XjAbXSi385DNQQ5fgc9Rsg0YChCfu9HYI,5561 +torch/include/ATen/ops/_sparse_coo_tensor_unsafe_compositeimplicitautograd_dispatch.h,sha256=I4COQMvvNAqKCnBG4sviRtpuGGJrdqa9b0vQCoYTqOY,2010 +torch/include/ATen/ops/_sparse_coo_tensor_unsafe_native.h,sha256=PNN84LpBpZgp6l-QwsweQ554iugLVaASvufw5Cw-lwg,1020 +torch/include/ATen/ops/_sparse_coo_tensor_unsafe_ops.h,sha256=ZCYYGDivCKCjXlFhxeORHFG6B7RkR_oB4xJBSL_usYU,2070 +torch/include/ATen/ops/_sparse_coo_tensor_with_dims.h,sha256=hP2mu_mF1NZKJ-UuGoGfyn2Lr258zx-tz8tS816-1uQ,2574 +torch/include/ATen/ops/_sparse_coo_tensor_with_dims_and_tensors.h,sha256=_ud5eZHzzm3A3miiomMbVNKn8K5a4Qnp7DDV25tuhJ4,10866 +torch/include/ATen/ops/_sparse_coo_tensor_with_dims_and_tensors_compositeexplicitautograd_dispatch.h,sha256=7fhZ8UmuXz4UqCy5TzyLaH2zZf0k7ygbrg_8p3NAZwI,1974 +torch/include/ATen/ops/_sparse_coo_tensor_with_dims_and_tensors_meta_dispatch.h,sha256=BfX_2JnsWN4_zjB_7kWtdr_79ODjb0GZc1AZWbGrP9Q,2178 +torch/include/ATen/ops/_sparse_coo_tensor_with_dims_and_tensors_native.h,sha256=kuOmLICVh3tXoIgtMFgnItiLHO4bnRZNj8wP1UithMU,1315 +torch/include/ATen/ops/_sparse_coo_tensor_with_dims_and_tensors_ops.h,sha256=jeL9qWLxP-JsVCLIM_-cnXAeS6QGTju45_9x7i_QAmE,3368 +torch/include/ATen/ops/_sparse_coo_tensor_with_dims_compositeexplicitautograd_dispatch.h,sha256=unUeTIogxeXNsACfFRqOLY8FqwezsiXsltiVw5ZF7Qs,1237 +torch/include/ATen/ops/_sparse_coo_tensor_with_dims_meta_dispatch.h,sha256=8vuvVso7W4x_SsjvxQTS9cfdjPojVurwcPfJq0Z_v7A,1318 +torch/include/ATen/ops/_sparse_coo_tensor_with_dims_native.h,sha256=8UBpjmPNTLwa0Lq3DUpKNUVAlYcWb1LE419r4EeXxFE,1073 +torch/include/ATen/ops/_sparse_coo_tensor_with_dims_ops.h,sha256=6dA9JReQiQRoNhZKx2VA_Vdr6cIxnyM14U599u4mi-c,2664 +torch/include/ATen/ops/_sparse_csc_tensor_unsafe.h,sha256=Kd6aJgw73c6W2TiVTKZdlPmcjgk9WW2JKmWuQ_8dQ8g,2034 +torch/include/ATen/ops/_sparse_csc_tensor_unsafe_compositeimplicitautograd_dispatch.h,sha256=0ACSp5RERfN0O-p7GjUKcx88IXgqkSruQZWamVqoeGM,1463 +torch/include/ATen/ops/_sparse_csc_tensor_unsafe_native.h,sha256=rkp4pNmus9mptxFaMQaGivfx2zQpUgtWqL0w_zeLuhQ,995 +torch/include/ATen/ops/_sparse_csc_tensor_unsafe_ops.h,sha256=tPrEXo5lJ7nL9RBUeXphUvkFsVGM5U89HrauLz-44Kc,2054 +torch/include/ATen/ops/_sparse_csr_prod.h,sha256=pU8xfUzU3ciWeMOAUupWigKMM1GYmbokfEKV9CM5lPI,1939 +torch/include/ATen/ops/_sparse_csr_prod_compositeexplicitautograd_dispatch.h,sha256=eCYI3JZAipAMwj2RsFQC8EqUQNLQPwya8t2zqMYQyp0,1310 +torch/include/ATen/ops/_sparse_csr_prod_native.h,sha256=KbO2KlLvXp0HxNJAHYg7ovb1zYTW3THJapmYtDbOaCw,1175 +torch/include/ATen/ops/_sparse_csr_prod_ops.h,sha256=tTq7zKGz20lG_I0EI-Oj6arlHoxdlz-YKMWcweOzHTw,2443 +torch/include/ATen/ops/_sparse_csr_sum.h,sha256=W70LlX-1oMqF84EaH5ApjGZIz6gOlYRjI5AXq5KRXIk,1929 +torch/include/ATen/ops/_sparse_csr_sum_compositeexplicitautograd_dispatch.h,sha256=RusXksQYxdWOExp_15c-T3C6WlwaARbR07ofnInjrXc,1308 +torch/include/ATen/ops/_sparse_csr_sum_native.h,sha256=_2Dl4mymkm4810qo8Om1rrZu6XUk290OZR6t4PWtvR0,1172 +torch/include/ATen/ops/_sparse_csr_sum_ops.h,sha256=zjfamLMz6ydl-Qf7DY7bPel2HsBsFkSSXzURZ11vLZM,2437 +torch/include/ATen/ops/_sparse_csr_tensor_unsafe.h,sha256=IPaUHDUl_KojGaczSaxcQd73zbvta1yoYfGAR9q5Sto,2034 +torch/include/ATen/ops/_sparse_csr_tensor_unsafe_compositeimplicitautograd_dispatch.h,sha256=IEcOH_XXfEZ6lolx2HD9_1j-3zs-eOQ3X24x4y6Hnvo,1463 +torch/include/ATen/ops/_sparse_csr_tensor_unsafe_native.h,sha256=d9V63axTfdAKYN3bCqeIqp2eynwOuF2xreUxD8tQrQI,995 +torch/include/ATen/ops/_sparse_csr_tensor_unsafe_ops.h,sha256=77KzwoW5hNfLc7yh0e-YLVSDCwWqdSCBaMuUSuh62Hs,2054 +torch/include/ATen/ops/_sparse_log_softmax.h,sha256=-lCRcE5Qneq0syt7SvGTVhmZtFjULwgW1zGQCR1YqaI,1951 +torch/include/ATen/ops/_sparse_log_softmax_backward_data.h,sha256=7Y6uM2Ddf2V6uRfrioAA7BkzOfVWDooc_64GAUlIk9U,1977 +torch/include/ATen/ops/_sparse_log_softmax_backward_data_compositeexplicitautograd_dispatch.h,sha256=eWodcdmSG8PSk2uLYpjqbLaPreyMekhzk2dmqgLlsJ8,1319 +torch/include/ATen/ops/_sparse_log_softmax_backward_data_native.h,sha256=Hub86o313x5WOi7dafisMLg0-IgP_Ultz5valJx8NG0,1156 +torch/include/ATen/ops/_sparse_log_softmax_backward_data_ops.h,sha256=HSRDJqXo8zG7wTkli4MAtqgIT8Ny3hHty7Hnw4QcuyM,2437 +torch/include/ATen/ops/_sparse_log_softmax_compositeexplicitautograd_dispatch.h,sha256=QgIjZskOPK4xGBj8mff7SMwovE27mRT_-gE5RKOojwc,1213 +torch/include/ATen/ops/_sparse_log_softmax_compositeimplicitautograd_dispatch.h,sha256=gRO3LsFa1yZM9o7SXPA1aDLvRN3fsbsc_EJ3U1weRq0,1098 +torch/include/ATen/ops/_sparse_log_softmax_native.h,sha256=X7whF77B8EbamyqKpSvSbu5WxD79O78QGEe8Ex2EUUA,1141 +torch/include/ATen/ops/_sparse_log_softmax_ops.h,sha256=4TGXKb4hJJYCqMIrNnVIJyHrEkwAtkVk5A1Ue9iLaCY,2828 +torch/include/ATen/ops/_sparse_mask_projection.h,sha256=FoaHGbwWWMLd02YR_RsQ3yqEJohr6f9PNP3b3EaO_Pw,1511 +torch/include/ATen/ops/_sparse_mask_projection_compositeexplicitautograd_dispatch.h,sha256=U3o3tSyDMITR31LY46IPXQgAdVkS98_lZiIAY7Pklws,1261 +torch/include/ATen/ops/_sparse_mask_projection_native.h,sha256=cVjQfwmWBehkIZc6Q-Rgozct7cailHO8MpP51hXocyQ,947 +torch/include/ATen/ops/_sparse_mask_projection_ops.h,sha256=KI3xUidyM47D9He9FWuDdg2JbLgm39yj1iausnnuIaE,2243 +torch/include/ATen/ops/_sparse_mm.h,sha256=HfkW16IjYIL4egSq8DCoIJj4R8dHfae3TdzD0FmS6_U,1219 +torch/include/ATen/ops/_sparse_mm_compositeimplicitautograd_dispatch.h,sha256=pU1WH4vYdcJZDi3bIQkyqWOpyrCHHM-wTGRRmYdkJ2M,1161 +torch/include/ATen/ops/_sparse_mm_native.h,sha256=A2A3t-d4mUSGtoJ6lIQexV9irH3ZOia7zrGpCRYwT68,873 +torch/include/ATen/ops/_sparse_mm_ops.h,sha256=v7rKiTxWlJ5RKTwD4BbF9ZZkhziRHn7hQ6IPJcamWO8,2019 +torch/include/ATen/ops/_sparse_mm_reduce_impl.h,sha256=uEifMo5AFiy9XuMYA6BuptEKcAYEa5jC4JQ9gn0q7qU,1082 +torch/include/ATen/ops/_sparse_mm_reduce_impl_backward.h,sha256=BB279Lss-5J8I29XESfPgsIWmQ_MI9yKnDCrArRbvIY,1298 +torch/include/ATen/ops/_sparse_mm_reduce_impl_backward_native.h,sha256=e7awKjdhzjSh9-0J61H9Ecm5W90We5N0J1C_aB3e3Us,938 +torch/include/ATen/ops/_sparse_mm_reduce_impl_backward_ops.h,sha256=YWitpUyea5R-OzrypovoEThEmzVOgB4PKBWrLzyEq5Q,1838 +torch/include/ATen/ops/_sparse_mm_reduce_impl_native.h,sha256=7yWu1afm8uZ8lv31dISjHoNka8KQHAWnrxkH5-mCXmo,837 +torch/include/ATen/ops/_sparse_mm_reduce_impl_ops.h,sha256=VAJrRP31GkwuurZs5i-L9mjyZmROsfnaoaooJgBA7bQ,1510 +torch/include/ATen/ops/_sparse_semi_structured_addmm.h,sha256=mCAqiZsnMFaULuBWihG1UxK1vCrkLIT-hOxvkVIIYqg,1332 +torch/include/ATen/ops/_sparse_semi_structured_addmm_cuda_dispatch.h,sha256=IOywnxpQBMJoCa2urDcUPWimsB3hPYZGbiyrxIcnsnc,1193 +torch/include/ATen/ops/_sparse_semi_structured_addmm_native.h,sha256=TslEn0gAcV2rOaKPVcTLsQ6DDg7vt-kNyKOgyhG1QR0,947 +torch/include/ATen/ops/_sparse_semi_structured_addmm_ops.h,sha256=O1v-3RFtr9XdIQHik-2OtIcXqPofytf6_Di_5d4g9es,1870 +torch/include/ATen/ops/_sparse_semi_structured_apply.h,sha256=SuyU6NZUWh8rv9AYoxOQlPejy83FzqZBn5F8eujIejs,1089 +torch/include/ATen/ops/_sparse_semi_structured_apply_cuda_dispatch.h,sha256=b8k4KvRC697kVzTOOUV7XvezeYk14uQh4uhBo8kCOgE,1058 +torch/include/ATen/ops/_sparse_semi_structured_apply_dense.h,sha256=4urKlxLsz-b8WtuTI5utUMO_AwHY1AcSTuIxjhPgkm4,1078 +torch/include/ATen/ops/_sparse_semi_structured_apply_dense_cuda_dispatch.h,sha256=U0PZwukT3WhYuwyiM8MOunIMER_MziaNW-yWuVZ7lUg,1039 +torch/include/ATen/ops/_sparse_semi_structured_apply_dense_native.h,sha256=M80uZ_e0ykiJGUQyQBDMieoE8R5YJuJJ7tGScCuQaAQ,793 +torch/include/ATen/ops/_sparse_semi_structured_apply_dense_ops.h,sha256=ryjbK6f1ah6Uk5yjRzQY8bmbq9UEJfxPTjx5of3hlp4,1408 +torch/include/ATen/ops/_sparse_semi_structured_apply_native.h,sha256=Ra5TuyofUEyBj1a1s4jeOKVFzx-CI5hwq9p2EzY7KfI,812 +torch/include/ATen/ops/_sparse_semi_structured_apply_ops.h,sha256=J_4tvx4orqWUwopZC5GuV6F6UWcJAWjMf5l4eEPEhKQ,1475 +torch/include/ATen/ops/_sparse_semi_structured_linear.h,sha256=RitS-VqQD6z9Kr8nO42HG3l_v0c4Uz5WqwKyI2W8ehw,1349 +torch/include/ATen/ops/_sparse_semi_structured_linear_cuda_dispatch.h,sha256=bizinDywN1rMa_SP9kAMRC_SljifVzdrrTCthcdmY5c,1217 +torch/include/ATen/ops/_sparse_semi_structured_linear_native.h,sha256=AwJ9JnoSQz__M2c9Q6YL5XFrzBVCG4r8r7-7e7FhKb4,971 +torch/include/ATen/ops/_sparse_semi_structured_linear_ops.h,sha256=14GM-GjwN7Zqtww5JKnbL8H3TEqi59ZbWOggHiP1JVM,1897 +torch/include/ATen/ops/_sparse_semi_structured_mm.h,sha256=zl3wgkIqzZ4dQDqPtn9v1iUfFhRyE2QmgCTSXIGrsvE,1174 +torch/include/ATen/ops/_sparse_semi_structured_mm_cuda_dispatch.h,sha256=3VmapmQJgJWeQGHCwvLI-xCJOW6nMrjvahmQHIIb3vg,1109 +torch/include/ATen/ops/_sparse_semi_structured_mm_native.h,sha256=nneNw3v6IAgBaxt8raRGoo82MTgB2mWItRFKXCmJIog,863 +torch/include/ATen/ops/_sparse_semi_structured_mm_ops.h,sha256=-8B9GHe_4N3pP42VzJjZufl4HusSwT78YXnEZ9zCp1A,1602 +torch/include/ATen/ops/_sparse_semi_structured_tile.h,sha256=WAfC5WFpJGW59fNNubWF5iUg7cTpyGgYS9z7n7u1_gY,1193 +torch/include/ATen/ops/_sparse_semi_structured_tile_cuda_dispatch.h,sha256=4OJKQ5l2KGlX-o7Kdn_Tc6nSbXy4DRCDJRErH4GYcSI,1111 +torch/include/ATen/ops/_sparse_semi_structured_tile_native.h,sha256=olsupM3GOEAIkrO3_Zni3BtkuvcjPL0OJjsVdyKQZw8,865 +torch/include/ATen/ops/_sparse_semi_structured_tile_ops.h,sha256=u-IukdlhaQ894uXGIL0ZV2IISghVkYIsP_zUjuYbVYg,1647 +torch/include/ATen/ops/_sparse_softmax.h,sha256=l3HLFlWoIis6ibJPeQfrwzw6AdtG0tFqNGcs_RX4K74,1899 +torch/include/ATen/ops/_sparse_softmax_backward_data.h,sha256=iVMeIXD1SJsTHRE9zOKH35Q9WrellOb9KnwdXivDuQ8,1937 +torch/include/ATen/ops/_sparse_softmax_backward_data_compositeexplicitautograd_dispatch.h,sha256=Un5JWG1L6j8YqUGaaCe-YfaWjoxqXAYnq0GJeN00Bao,1311 +torch/include/ATen/ops/_sparse_softmax_backward_data_native.h,sha256=p6hXfyhQKvSFxLoQYX48jVol2csu6VNXBJqersAwlkQ,1144 +torch/include/ATen/ops/_sparse_softmax_backward_data_ops.h,sha256=w43m6xczEcQjkDpYzsaVNaB5vjplF86eKiqGfpbxR7M,2413 +torch/include/ATen/ops/_sparse_softmax_compositeexplicitautograd_dispatch.h,sha256=ciQS89KIPR6-GRA0Y5ugtxaDFy4o6LEUND6oE5FCEHE,1205 +torch/include/ATen/ops/_sparse_softmax_compositeimplicitautograd_dispatch.h,sha256=2ezII9lwvXaNOJ2kQmAULsoHyH0_VmbMeRerZDp_ah4,1094 +torch/include/ATen/ops/_sparse_softmax_native.h,sha256=-Scoi-WurpteBxt6L63PGsII50DgXPTZKwk8jBylffE,1125 +torch/include/ATen/ops/_sparse_softmax_ops.h,sha256=agg0rU5Sfg5WC6bYeimxv3hvb15Uja8jnlVT2KqL3wo,2792 +torch/include/ATen/ops/_sparse_sparse_matmul.h,sha256=e2UucJi5VgQvBpl6Z9H7PmWSY3GTZbwaMPsfCNj_G4M,1572 +torch/include/ATen/ops/_sparse_sparse_matmul_compositeexplicitautograd_dispatch.h,sha256=72-49i__SIo0HQpV63v1MvsppLp73vgcuyNm8Yxqf8M,1203 +torch/include/ATen/ops/_sparse_sparse_matmul_native.h,sha256=Yq-3LjgMSuExeMng8lLDVnI7yn4kx675rylGc1iQsm0,992 +torch/include/ATen/ops/_sparse_sparse_matmul_ops.h,sha256=zwknDCvBhb8lDmRBGEC3PuS6OP3qq5vleDMLJDY3gPc,2063 +torch/include/ATen/ops/_sparse_sum.h,sha256=QZjgSW1nbi3r0TLn_YRsqL833ogLtQU7AblcckvTOG0,2089 +torch/include/ATen/ops/_sparse_sum_backward.h,sha256=SdhxYiZir_ccdH-hpWfXkozbdBUeRAJ2rpwB4fCOd-w,1664 +torch/include/ATen/ops/_sparse_sum_backward_compositeexplicitautograd_dispatch.h,sha256=qkaIlTWUwrK7Rd44f-6MJDB0TkjK-olpfE7QklU3eUg,1241 +torch/include/ATen/ops/_sparse_sum_backward_native.h,sha256=Jv_VV7b-3QGFFShAxJmumHWplEl8FVFcVtymA4dlJz4,1051 +torch/include/ATen/ops/_sparse_sum_backward_ops.h,sha256=G9D7nr5P3o52X5PcGFIcgKbAlHK-cQu2vMr5ewi_NUg,2191 +torch/include/ATen/ops/_sparse_sum_compositeexplicitautograd_dispatch.h,sha256=0VSZOM5OGo3iijux1aAU5DxbWaW38Svf690IYp3Uwhg,1253 +torch/include/ATen/ops/_sparse_sum_compositeimplicitautograd_dispatch.h,sha256=S5_wOPtSALWkZEeJoGEi38eg50coYP5xFEHTGlvR3zQ,1206 +torch/include/ATen/ops/_sparse_sum_native.h,sha256=wK1grkBCuzNTQ_nm5RbcYeqwsF0zscc7hMNG0LCCykg,1106 +torch/include/ATen/ops/_sparse_sum_ops.h,sha256=T146SrkDcTzZVRAivQ2dl92JG9rr0jCvaKXEyXy4tpk,3820 +torch/include/ATen/ops/_spdiags.h,sha256=hmokoL_XkEDpK5gqTYIR7F-njd0WGNR3F4j7PZh730A,1859 +torch/include/ATen/ops/_spdiags_compositeexplicitautograd_dispatch.h,sha256=UbRPm531USYxmiw8A6rBnVSBhOwqB-UUo7o-XYTIgOA,1324 +torch/include/ATen/ops/_spdiags_cpu_dispatch.h,sha256=JdlH1ntLN6NxWtH1HwEoovXXnVi9kC3yBN4zXfnEie4,1083 +torch/include/ATen/ops/_spdiags_native.h,sha256=Zm3V1MJSf5vev3dLBMg-Lb8baiBBmCz9HA5-Ozr4kTc,1010 +torch/include/ATen/ops/_spdiags_ops.h,sha256=_0X9qyNcNn6HPfX3HWViH7rNP7N0XtNGTzar-OHd7Y0,2423 +torch/include/ATen/ops/_spsolve.h,sha256=P_jbKsoRCLSqlchfnfoMPhZI8tzBRKO1AjK-WnCiHW0,966 +torch/include/ATen/ops/_spsolve_native.h,sha256=KWTsfcG47pJvToZ2kSRpmAV_qSrQ8QXTAhWzTl-J9RM,783 +torch/include/ATen/ops/_spsolve_ops.h,sha256=jk6LRaRv16UHadUJAm4RDl8yowK5BpXW5V4eyN_MWvM,1329 +torch/include/ATen/ops/_stack.h,sha256=6ZidL51Sq5pJIuRpTyp0zMl0OZ30SC7McXC4e9gHUlI,1393 +torch/include/ATen/ops/_stack_compositeexplicitautograd_dispatch.h,sha256=d6FPj-EEKnwaE00xkZ36li_dF8yLkRtErLtUbsPnZLI,1215 +torch/include/ATen/ops/_stack_cpu_dispatch.h,sha256=tyj0nLjDPr6P3UOw47BKKuiGA1CgDqXe5u2m3Fz9Vvw,1171 +torch/include/ATen/ops/_stack_native.h,sha256=Cy_GV1hYym7KG5_6MCD1UgTnGhd3wu6jhk-sFpAcRlc,1000 +torch/include/ATen/ops/_stack_ops.h,sha256=h3pO7_QHRrZRQatSHEpisnT1iAl6PP6gN5FMyIgXWJ0,1891 +torch/include/ATen/ops/_standard_gamma.h,sha256=-KzniOFGogDHzok-kuEPStCYKJo6cfI0WwQmI8KfD2Q,1641 +torch/include/ATen/ops/_standard_gamma_compositeexplicitautograd_dispatch.h,sha256=-n5jp-Qoj30yUEdqFu-ieCVNgEr7Mn8TU_Ai6cfmIhU,1238 +torch/include/ATen/ops/_standard_gamma_cpu_dispatch.h,sha256=oDGhf689aXLHSqhFx3s6tlQ7RSu3WmoneVjupHT4vac,1040 +torch/include/ATen/ops/_standard_gamma_cuda_dispatch.h,sha256=mWGYhroqAyXC8pwiBnlfyNjnfHDewfQAa651IHEFH7w,1042 +torch/include/ATen/ops/_standard_gamma_grad.h,sha256=C2PxB5rU9p3ckbRX5euZ-fzhiA0pdW0cBG34R8LJ7e4,1571 +torch/include/ATen/ops/_standard_gamma_grad_compositeexplicitautograd_dispatch.h,sha256=8uydEf72uD9UdImqI0-JBxraOE8gFdCnCKITFMvf_zE,1203 +torch/include/ATen/ops/_standard_gamma_grad_cpu_dispatch.h,sha256=vqE9ir-H-pAeVk8lHrP2rU73W8_jQEgqRBVBpDa9gnc,1015 +torch/include/ATen/ops/_standard_gamma_grad_cuda_dispatch.h,sha256=qz_2wfki-yfGQ8jWCb4WdF3OyF1OvwI3fRMpsAOzipg,1017 +torch/include/ATen/ops/_standard_gamma_grad_native.h,sha256=M19WbHdhSB5G4Z2-gzhszcjAhkYDfWhkn7H9QizKeQI,994 +torch/include/ATen/ops/_standard_gamma_grad_ops.h,sha256=Du9ZuWG4BpLoSmlxroDtEJXQFu2VjEuiZUPI3ezqVLY,2063 +torch/include/ATen/ops/_standard_gamma_native.h,sha256=Y6hwkP3RjNYUh3YDqloQwRBmBMIACBoTos9US49wBDI,1040 +torch/include/ATen/ops/_standard_gamma_ops.h,sha256=HtyoxMF8Pu6N6XmQpuCEGERWu827L_ifOpUdAzYbmJY,2141 +torch/include/ATen/ops/_test_ambiguous_defaults.h,sha256=iiPtWn9ulkBfqYYjQoFRq5nYGChMY1kPRWlTX7UFO3w,1273 +torch/include/ATen/ops/_test_ambiguous_defaults_compositeimplicitautograd_dispatch.h,sha256=L75HozizZ7Iya6kQXRP4oe2tOXhBBEzVGtxWpG_2S-A,1167 +torch/include/ATen/ops/_test_ambiguous_defaults_native.h,sha256=jr9B7bYvx6C3fy6hCVfrusEHGaiJY8ypy-8YmlJbeiE,885 +torch/include/ATen/ops/_test_ambiguous_defaults_ops.h,sha256=cMVW6fX2gumn6g7HKde7zAQ8ItLL2pyf5IadLjPVe80,2026 +torch/include/ATen/ops/_test_autograd_multiple_dispatch.h,sha256=3yh8AVcE3X3A4NJkZWo_vdwBWcfchWejgoywny1Bn4k,1865 +torch/include/ATen/ops/_test_autograd_multiple_dispatch_compositeexplicitautograd_dispatch.h,sha256=gq5orbrQFiF69pNB4VkDTrlQSPLJ6CDzIN1GiqwnVh8,1253 +torch/include/ATen/ops/_test_autograd_multiple_dispatch_compositeimplicitautograd_dispatch.h,sha256=MX2T8vzFVdHkrW-a-WMNrJsQsx_r1qA5Hw3qusRZVKo,1052 +torch/include/ATen/ops/_test_autograd_multiple_dispatch_native.h,sha256=eOQfDPVueJiTNQfR8Qcn9sdD1n4hqCuhE7Ki2ZDathw,981 +torch/include/ATen/ops/_test_autograd_multiple_dispatch_ops.h,sha256=jne9YO_AT_O75rbKU2y3XcHntXssxtD4a_iX5wXAcR8,2662 +torch/include/ATen/ops/_test_autograd_multiple_dispatch_view.h,sha256=Lqdwo5wPaxS7u9bTKJfuj8FynwHH4xTKCc8LAlC1ZWM,1021 +torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_compositeexplicitautograd_dispatch.h,sha256=cVsywZBhxk1JNeSKXmGNulTde20iGUnybrUH0s9wuvY,1049 +torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_copy.h,sha256=qOD7aMjHdtabPyI-x0zWhILvpN57IJhRklFjpHKLRMA,1641 +torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_copy_compositeexplicitautograd_dispatch.h,sha256=7xqOvc8zJt2JCc9eQIHglbttOHjtWTX3ywMnZzjICnE,1193 +torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=44Lo7Aj3C5QTkXrrhQFYiy0WsnHdHeHAa-saQqbFU9o,1080 +torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_copy_native.h,sha256=2UH3GOMfrNRo-ITvG_1_NA3nrebhI6clR1AHL2shGBM,880 +torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_copy_ops.h,sha256=wfc2QKwk1HSg-gpLUfOSUAJcsMkpkbhugH8OCJcGFfM,2017 +torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_native.h,sha256=zv9UT9OBO1RQyrthAffhkskiGIeXEtKGyoL4eQMfbS4,761 +torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_ops.h,sha256=T2mbQs-DO5fEn904Ds_5y4Gqu-nhreSAJ9rG6tXyh_g,1310 +torch/include/ATen/ops/_test_check_tensor.h,sha256=RkhX2TkiDgaLZ23G8D5UtXnsmA7I-M6xn6H4_c0WEpU,939 +torch/include/ATen/ops/_test_check_tensor_compositeimplicitautograd_dispatch.h,sha256=yetb_9AbjPBYcafcVg7_KLX_-Oe4OK6RsQktBD_vYKI,1030 +torch/include/ATen/ops/_test_check_tensor_native.h,sha256=Yr56mwGyLjxYV-FYiLhe92eT--XPV4bRw-ymI-SIIdk,742 +torch/include/ATen/ops/_test_check_tensor_ops.h,sha256=zzSMYPS5AMfj57zE9RYHwAb31uGsb6M7VsXWNNk3nhw,1247 +torch/include/ATen/ops/_test_functorch_fallback.h,sha256=hZlXO84x0tHo1VDpvbnrwGzOJdjlxdkSk1yB2adNKo8,1602 +torch/include/ATen/ops/_test_functorch_fallback_compositeexplicitautograd_dispatch.h,sha256=35xKz2Q8FEMcI2OsqYXl6hdotm65t7y8jrjxfM4DXMQ,1209 +torch/include/ATen/ops/_test_functorch_fallback_cpu_dispatch.h,sha256=k5A4RAW4tCQsaDua4yjdqqkMFy3XdLz7G5DXaFF1bMk,1018 +torch/include/ATen/ops/_test_functorch_fallback_native.h,sha256=6JYXhXAJCjITbx1w1IcukfQ6vBVaMDusHr5otHGJ1HA,896 +torch/include/ATen/ops/_test_functorch_fallback_ops.h,sha256=Y_gPiQRrV787GGrwuWrNV8y5Z6-nu-HdNBvFwYx66O0,2081 +torch/include/ATen/ops/_test_optional_filled_intlist.h,sha256=lYrO4oOhnypBvMYCqJnWPdsZ_MfvjFdr7w_r1f5dAtw,1706 +torch/include/ATen/ops/_test_optional_filled_intlist_compositeexplicitautograd_dispatch.h,sha256=MUUnG2zgq8yUXrpEoTNQkso2xEZ-9B7b_5Q8CrTXt0Y,1237 +torch/include/ATen/ops/_test_optional_filled_intlist_cpu_dispatch.h,sha256=lcLe8-9tfyzFmtV_ZacLxjhQ2UXojJwXHN5zWYJbhH4,1032 +torch/include/ATen/ops/_test_optional_filled_intlist_native.h,sha256=VUQVnTJz7lR_WBl4RnYL7Fv9XcVd4KY8bhYDFRImlCY,917 +torch/include/ATen/ops/_test_optional_filled_intlist_ops.h,sha256=wXPxlWCQJcbVWrCYD6qXK12l5oYsl48ZnjscjclBSoE,2167 +torch/include/ATen/ops/_test_optional_floatlist.h,sha256=NXjBKt0Ih4z9s0wNF2V3kGgKHc1BixIeO1Byx7r_sEs,1701 +torch/include/ATen/ops/_test_optional_floatlist_compositeexplicitautograd_dispatch.h,sha256=Mk7xzLP7Zau1TS-9MadiV1KLCK2RO2XunxtXmsJtjxw,1255 +torch/include/ATen/ops/_test_optional_floatlist_cpu_dispatch.h,sha256=2p4O-2D29o6ZuHMiAuXmb2A93uSmJXR3MQHCbPoAwyY,1041 +torch/include/ATen/ops/_test_optional_floatlist_native.h,sha256=lU9leB1FcvJ1v-j10qhOj-2_OpHXO23DOrV3fxmvEY0,942 +torch/include/ATen/ops/_test_optional_floatlist_ops.h,sha256=CTwGUUkBgbbIJ3ovoE3-B-zBBzDkcWG0NJ4bVCR4AUw,2223 +torch/include/ATen/ops/_test_optional_intlist.h,sha256=gsoYLS-wG97IkuYqVsUt5fWPLFrzQtTXt6y1S_BLJig,1633 +torch/include/ATen/ops/_test_optional_intlist_compositeexplicitautograd_dispatch.h,sha256=c_I6ss6CQH0sL-I7ASwqDCvVSFjACOqD0fHh4eQ2kYA,1223 +torch/include/ATen/ops/_test_optional_intlist_cpu_dispatch.h,sha256=O1mM_o7BAe9mwbORP304rlJ2UJB_ssm4VBlJcz4NiuA,1025 +torch/include/ATen/ops/_test_optional_intlist_native.h,sha256=Csx-clXQ8K1etHdDBh2jDn9zTrAlWtQKqDa44cS5Xks,910 +torch/include/ATen/ops/_test_optional_intlist_ops.h,sha256=Zp7jqQikbc1qUyBHBib5TreRymYF8YYkDid_LiPJ9es,2123 +torch/include/ATen/ops/_test_parallel_materialize.h,sha256=8iVOsGVdf7hlUmfgJzVieIiCvonMVl2B6asSror2RLY,1083 +torch/include/ATen/ops/_test_parallel_materialize_compositeexplicitautograd_dispatch.h,sha256=gG0Lzh7Gtz32PWB771DD2VEe-8YgKc8tlm-GiWCiQZ8,1083 +torch/include/ATen/ops/_test_parallel_materialize_native.h,sha256=RlO4B6CrscoSEQhpCho5wtrpQpwMHzcVw8T7B7zeH_U,795 +torch/include/ATen/ops/_test_parallel_materialize_ops.h,sha256=Wwc16ZTWV4Ltk7Ps3PD7f0gjuwCorXFhexScEqkB2Yg,1405 +torch/include/ATen/ops/_test_serialization_subcmul.h,sha256=c94gI8FK_cSpWBUlJNAcPS3_SCm06L1ac3rD43Ja4MY,1073 +torch/include/ATen/ops/_test_serialization_subcmul_compositeimplicitautograd_dispatch.h,sha256=9F9Zx2vOVVizB6CWR37s1FBsriyxLc0xkham2u5N-_M,1093 +torch/include/ATen/ops/_test_serialization_subcmul_native.h,sha256=Fph5WdDjpuPj6Gr8ag6unMEXoNln49Xb9P02LYbA_y8,805 +torch/include/ATen/ops/_test_serialization_subcmul_ops.h,sha256=JcV9JJwbX32tMC-NdQcDEZno-0Wwww_qqxCAtF-uowo,1448 +torch/include/ATen/ops/_test_string_default.h,sha256=MkDq9X7C6LNIqbaAdigNAoYCpGNUrJC3VEozLxfjZEU,1042 +torch/include/ATen/ops/_test_string_default_compositeimplicitautograd_dispatch.h,sha256=95twlmJzcdPqZNp3dBO9zwCJNrX1A3Vany6gkB9LAI4,1089 +torch/include/ATen/ops/_test_string_default_native.h,sha256=YuUCUnOdzdV9Xg0BpzcI_TwuHE0PemIROwDwqltWonA,801 +torch/include/ATen/ops/_test_string_default_ops.h,sha256=xzUdQK1Q5WpI8N2RabosI5krcQOnu_c6Zsut3x13eTc,1412 +torch/include/ATen/ops/_test_warn_in_autograd.h,sha256=Gi-ntGUk4XePMOqdAfNVYU5czjLksh7dIt-4G0pyBwI,1441 +torch/include/ATen/ops/_test_warn_in_autograd_compositeexplicitautograd_dispatch.h,sha256=_Q3jsnVyp3c4sa7YFe8rPaJCis0AUfFuvMKey9In47o,1223 +torch/include/ATen/ops/_test_warn_in_autograd_native.h,sha256=fRS5fd_8Bze8ZmdQoU8IEJW5KaixpzBNDoU2qzfcJ34,840 +torch/include/ATen/ops/_test_warn_in_autograd_ops.h,sha256=BVaQph_lXY3xiDNy94G4Nkme-xVp5SG8NDyEE6v_fVA,1897 +torch/include/ATen/ops/_thnn_differentiable_gru_cell_backward.h,sha256=3rYNygXOxdIInxRTzgx8lxcbvglR5ps9fz43xyew62Y,1454 +torch/include/ATen/ops/_thnn_differentiable_gru_cell_backward_compositeimplicitautograd_dispatch.h,sha256=ayMB6RaUjgaYGXhbNROL_k75g78xr2IgH7JSBFFiMOU,1296 +torch/include/ATen/ops/_thnn_differentiable_gru_cell_backward_native.h,sha256=9bQRwlW-KZPiezKunCyHLaHWGOIYqZWf_VNm--Rlxc8,1008 +torch/include/ATen/ops/_thnn_differentiable_gru_cell_backward_ops.h,sha256=LkUlqgdeziGo26TdMXNhpVg9cbiMtn8LRGV5upwJ3jo,2121 +torch/include/ATen/ops/_thnn_differentiable_lstm_cell_backward.h,sha256=7ORzQuyn76mxppmfJ4z3yJJnb6wcRYq46XlHcTGcVBA,1585 +torch/include/ATen/ops/_thnn_differentiable_lstm_cell_backward_compositeimplicitautograd_dispatch.h,sha256=ZAhJe97_XioS_mr3Hr_GwSe_-QWA7ZJZOq5MuD2fyo4,1382 +torch/include/ATen/ops/_thnn_differentiable_lstm_cell_backward_native.h,sha256=eTaSLHJcoGl-GTkoog70UD51p_Svj9jfWFre0jnEvBs,1094 +torch/include/ATen/ops/_thnn_differentiable_lstm_cell_backward_ops.h,sha256=ulRHgb1PdTcg54seN0gP8t4DGMIjn0ysJKFxLBmDkgQ,2397 +torch/include/ATen/ops/_thnn_fused_gru_cell.h,sha256=TZD6mm3HwOcvsxUdScXu_Y0tLmodM1OMx4jKtRnIjIQ,2540 +torch/include/ATen/ops/_thnn_fused_gru_cell_backward.h,sha256=blgtOG-qOt3OOghh7pwb2RSlz_sMOI_eXh5RwoYYb7s,2501 +torch/include/ATen/ops/_thnn_fused_gru_cell_backward_compositeexplicitautograd_dispatch.h,sha256=CVLGfjVwdhBsSElbfsDe1IGXwJxJRTgT8K5Y8ImQpgI,1549 +torch/include/ATen/ops/_thnn_fused_gru_cell_backward_cuda_dispatch.h,sha256=m3ry3x_6zrZZcbN2QSjXo0skv_ZW-LRkHsC60ObZm14,1105 +torch/include/ATen/ops/_thnn_fused_gru_cell_backward_native.h,sha256=tUbVl5QyCKVvr9srb8mClH9AspZuFZW2NAOoxVvEq_E,1156 +torch/include/ATen/ops/_thnn_fused_gru_cell_backward_ops.h,sha256=VvluDNLP-aMG7nGBsV-Auf9tgwlnm_32aSvftzOjX7c,2990 +torch/include/ATen/ops/_thnn_fused_gru_cell_compositeexplicitautograd_dispatch.h,sha256=QaTe26tIyQkScWIvOQWpRW0gfPEwuZksM9m0A-ht2BE,1569 +torch/include/ATen/ops/_thnn_fused_gru_cell_cuda_dispatch.h,sha256=9PFDuacMncKGt5iniW7ji3MsJM68lcwatlRC7C-Tbj8,1181 +torch/include/ATen/ops/_thnn_fused_gru_cell_native.h,sha256=k_zNAKP-upd44yiioQz5Epf8z9_fLbqImJszy0dp0-w,1239 +torch/include/ATen/ops/_thnn_fused_gru_cell_ops.h,sha256=ZwXU1Hq2yTYjS1dm2txZ7YS8y1_LRw4m4e_ReuciEUo,3185 +torch/include/ATen/ops/_thnn_fused_lstm_cell.h,sha256=LxpRssFRX03DOkSdHv0SZOGI4nopHg5EYlKM97DhgRE,2703 +torch/include/ATen/ops/_thnn_fused_lstm_cell_backward.h,sha256=eRZxbhFrEx0Ct27bS0u-KIzIzeu2kwqvqwiwQQSxlw4,1352 +torch/include/ATen/ops/_thnn_fused_lstm_cell_backward_compositeimplicitautograd_dispatch.h,sha256=2Qm_7BsP8P17VYxji3AmEIamfK5m5N958eOyrQUm9mU,1256 +torch/include/ATen/ops/_thnn_fused_lstm_cell_backward_impl.h,sha256=YZJrnHzKvchwNtxFV9fi9m5V4pZkyKYXEyIRXnQoa2s,2750 +torch/include/ATen/ops/_thnn_fused_lstm_cell_backward_impl_compositeexplicitautograd_dispatch.h,sha256=xS_8bA-RVA0KGTO9Lpu1vjW1U_6lzvoo4GzIlHBl7kc,1649 +torch/include/ATen/ops/_thnn_fused_lstm_cell_backward_impl_cuda_dispatch.h,sha256=eWBlJPHyzh_5_onvqDhMiNj1Bz-c1dABLgIk-2QTxvg,1197 +torch/include/ATen/ops/_thnn_fused_lstm_cell_backward_impl_native.h,sha256=tBAOyw72oi8MjdYIRj3gqx87Iy6XvIgY4FGbzs9VrSw,1298 +torch/include/ATen/ops/_thnn_fused_lstm_cell_backward_impl_ops.h,sha256=lhESqcBvYOsV79aRx-L4OKfcpU48E733VEZ-jz5wQ1A,3404 +torch/include/ATen/ops/_thnn_fused_lstm_cell_backward_native.h,sha256=2S0LBDdGQbJtyEnmkfdMei9yoYZjZtP1eVUJePMTOPY,968 +torch/include/ATen/ops/_thnn_fused_lstm_cell_backward_ops.h,sha256=Oa1K65JHI53azCXF8H5-ftwtoeHDrVtMALEKshT25-U,1999 +torch/include/ATen/ops/_thnn_fused_lstm_cell_compositeexplicitautograd_dispatch.h,sha256=HLDN--t8Pycpt6BoojAvbwYsZvtaoJ3J-ulT_vLh6q0,1635 +torch/include/ATen/ops/_thnn_fused_lstm_cell_cuda_dispatch.h,sha256=Qm_T4EXAMKlq1wwn9B5DFutmMs-i4L0NzqlntnXPGCk,1193 +torch/include/ATen/ops/_thnn_fused_lstm_cell_native.h,sha256=quhv1CVF6ROjcYItTKfh13Iu6YPWthVR4Pylo4S4udw,1284 +torch/include/ATen/ops/_thnn_fused_lstm_cell_ops.h,sha256=W4mz7BrNZlFyxnFI4LdNr7OaB-jKjz1qtR8ahMD7t_I,3352 +torch/include/ATen/ops/_to_copy.h,sha256=tpoNP066ht4v1ErhbFf_qGK0lK5Ad1ipxZr0Q3QGVbw,2693 +torch/include/ATen/ops/_to_copy_compositeexplicitautograd_dispatch.h,sha256=0VzVL9Z4dtt2GLIhhkXobAL60ZpyKD-1-GN_qRV2oGA,1726 +torch/include/ATen/ops/_to_copy_native.h,sha256=x4RJ5pROivBwy4eRFl0c5RQ3PGBuV1RVteadk3oUmas,1435 +torch/include/ATen/ops/_to_copy_ops.h,sha256=G907Zm67PpZzv82bOD9-MLdE-tw-yGjHx2Fa0OB6SKY,2781 +torch/include/ATen/ops/_to_cpu.h,sha256=0Swg1FZ0RY7Kf6ayBwx_cQqjsQJAAGvFR6YY4thXuGE,919 +torch/include/ATen/ops/_to_cpu_compositeimplicitautograd_dispatch.h,sha256=_bCRoXU70kTb2yrOdMj_5WQrq1K_WHf8LztBbzsCtfA,1033 +torch/include/ATen/ops/_to_cpu_native.h,sha256=h1lwJcSbsMEP0MtTWF5AGf2WJUTdjW8JO2V8wu5FUDg,745 +torch/include/ATen/ops/_to_cpu_ops.h,sha256=ozgmX-jT6ggk0lujxiAEe-AzVUg1f4VMgS8y7_Sku7g,1260 +torch/include/ATen/ops/_to_dense.h,sha256=uaEPGLX0IyPdRx7aYFq83qKGWaj64MvdZsr_jpRdnsc,1481 +torch/include/ATen/ops/_to_dense_compositeexplicitautograd_dispatch.h,sha256=_JJBbaQa-a5ercbt_y9DMLvQM-K8FkH6W_4jFluHeHg,1305 +torch/include/ATen/ops/_to_dense_native.h,sha256=srizXVjFy42LtfMK8m2vqOyXZYtOu-rlNAhghTHG5QA,1343 +torch/include/ATen/ops/_to_dense_ops.h,sha256=khbFC-w5ssmlPkXCvsmD6tSZNJenPHTsSgu1UPes5TQ,2323 +torch/include/ATen/ops/_to_sparse.h,sha256=1IAf1F-luOLE5uSH7YaUy1jPIOyd9OSfBEcYj6TNOyU,2179 +torch/include/ATen/ops/_to_sparse_bsc.h,sha256=J6FTBASFvRx4mdOtYH0FF3vuJ80NsAtd-ZkLrCEIARk,1465 +torch/include/ATen/ops/_to_sparse_bsc_compositeexplicitautograd_dispatch.h,sha256=AQNyoGIMeKiRZGkQzmQ7LVPXUFk6X0-3GAb47jcLhao,1278 +torch/include/ATen/ops/_to_sparse_bsc_cpu_dispatch.h,sha256=nROADU_Frn7O_8u1Iu48fmotZeYZVNLm-WXVbY8jYyc,1060 +torch/include/ATen/ops/_to_sparse_bsc_cuda_dispatch.h,sha256=Qn2ZNHW8anH9YgGgWNawz-B7hQrERv5hh6gs8HZVj-8,1062 +torch/include/ATen/ops/_to_sparse_bsc_native.h,sha256=TY4fGH2XwXC0UjBffwntD27_mApnvaYsVihn6XTKKBw,1270 +torch/include/ATen/ops/_to_sparse_bsc_ops.h,sha256=cG5kZny2-Kh9PZWM8zaFIDRODha722Dgy3dR0yM3Ydo,2265 +torch/include/ATen/ops/_to_sparse_bsr.h,sha256=8iYLbWbqd12yNYgr9u-jVO-WXm_6X0yLAwDHNdm8qBo,1465 +torch/include/ATen/ops/_to_sparse_bsr_compositeexplicitautograd_dispatch.h,sha256=90sqsU_SxEzydbt5QaC_V-8hQSSR0KPa-IdyLvVhKjg,1278 +torch/include/ATen/ops/_to_sparse_bsr_cpu_dispatch.h,sha256=6dzkt81WGdIFGyyqj64S7fj4-IcpDk0uoxgkztMdOVw,1060 +torch/include/ATen/ops/_to_sparse_bsr_cuda_dispatch.h,sha256=aKKHNV294ySAQY9Bna5d6udKdAkjnmq9B9I9dy6es2A,1062 +torch/include/ATen/ops/_to_sparse_bsr_native.h,sha256=hQy8QH0uZJqVFr6VJCaKAIeAvLPR2n9P7_yUBQ3FoBs,1270 +torch/include/ATen/ops/_to_sparse_bsr_ops.h,sha256=WuONWRG747jmI6BMOY6-ufe9l04m5L17RaELH1n1tzY,2265 +torch/include/ATen/ops/_to_sparse_compositeexplicitautograd_dispatch.h,sha256=sfJ_wKTZAgsF_lVjYiooHFJUdvHG3q0nlBJGjB_n-wQ,1593 +torch/include/ATen/ops/_to_sparse_cpu_dispatch.h,sha256=cLcYe7nMrOqL_mTXloboizJ9RNs6levVCwhgd5IUWpg,1208 +torch/include/ATen/ops/_to_sparse_csc.h,sha256=Cuopo1zMED5QszPJ-9OZ9uxmVU4EvvNLVpkDKOdk3xU,1353 +torch/include/ATen/ops/_to_sparse_csc_compositeexplicitautograd_dispatch.h,sha256=5dU_F4SqaULfV7jl_AdgMdv1rOTEl6gPkwdsF9BwZdc,1224 +torch/include/ATen/ops/_to_sparse_csc_cpu_dispatch.h,sha256=2PzIQy0Q9EH7dYJe6keoapENxX2D1mEMQi3KWv4fDXM,1033 +torch/include/ATen/ops/_to_sparse_csc_cuda_dispatch.h,sha256=e2uVuonpP3_8CRxlDRijgd1xX3KofGSBBJbUaZpcOXA,1035 +torch/include/ATen/ops/_to_sparse_csc_native.h,sha256=T_2e5QnDuSD2ZOtWQkLo7AjMsjGsplZlfb2j89H7SuI,1162 +torch/include/ATen/ops/_to_sparse_csc_ops.h,sha256=1X4xl2FBIwbOrhk15871vJlqa09_llcfnyOyDdG1eYQ,2087 +torch/include/ATen/ops/_to_sparse_csr.h,sha256=BihHWEBdsjLwa6jCfArqraQF6d0Slu9IqAufcpU9O84,1353 +torch/include/ATen/ops/_to_sparse_csr_compositeexplicitautograd_dispatch.h,sha256=f3QFjUvMYGxxEpc2Z37rA-NsCwJbws2TlhfZ_UMRCdk,1224 +torch/include/ATen/ops/_to_sparse_csr_cpu_dispatch.h,sha256=8QZRGZwGCHjgcvukd2Zi2GlVWDSeMhEde1URTj_lo1I,1033 +torch/include/ATen/ops/_to_sparse_csr_cuda_dispatch.h,sha256=1i8E88LM7yiwPBAi4bxRE-hRm1fyv7XqAeyk-kOwKI0,1035 +torch/include/ATen/ops/_to_sparse_csr_native.h,sha256=od03sYzRJRdZF22Vh9R9s6HTSLdtA_hSeQ-LLR55dbA,1162 +torch/include/ATen/ops/_to_sparse_csr_ops.h,sha256=qHO0iyPyco3ICqifeOe6hakLF_Ek3MqjYN7zTgCiFhg,2087 +torch/include/ATen/ops/_to_sparse_cuda_dispatch.h,sha256=cxiAoklxa_3LEnihP4IG2-1LG2EB35Pq9sKau072sXo,1210 +torch/include/ATen/ops/_to_sparse_native.h,sha256=9nTzl9JW3h_nhq56dwM3ETMIcDsQLRyWeVWHw-2_Ais,1906 +torch/include/ATen/ops/_to_sparse_ops.h,sha256=zRMEiSFRTxDJgF1Fhn9hqBhUv1rCE4tCapCrTQdJfVw,3857 +torch/include/ATen/ops/_to_sparse_semi_structured.h,sha256=wgJmbxJ4oQKHSmT7pvY1j4QUebK8SAKXOHW1nPnqFmo,1009 +torch/include/ATen/ops/_to_sparse_semi_structured_cuda_dispatch.h,sha256=EZrmc-Tq5Oec1TnAyXkxhY2FNqrzLbU9tBsc7e9GImE,1022 +torch/include/ATen/ops/_to_sparse_semi_structured_native.h,sha256=oZItHPByU6fk34Z9nwdiAVSjrb5gYG_KRGK7beK7kMI,776 +torch/include/ATen/ops/_to_sparse_semi_structured_ops.h,sha256=Uxoqo5uvFQqCPts6cMS69VOv-WTIS5wGIb0aAr_uwR4,1359 +torch/include/ATen/ops/_transform_bias_rescale_qkv.h,sha256=6gku0rcEDkC1811k_xCUS3DzOwastelNpTNw5HezcZk,2145 +torch/include/ATen/ops/_transform_bias_rescale_qkv_compositeexplicitautograd_dispatch.h,sha256=hLKILXQ4udHttEAMQgGC3RUqpkuDVbLz14RjqOBa6o0,1415 +torch/include/ATen/ops/_transform_bias_rescale_qkv_cpu_dispatch.h,sha256=ud1g1jadambd9o168X2eksnRRLz8TKYSKjukRrg93cw,1078 +torch/include/ATen/ops/_transform_bias_rescale_qkv_cuda_dispatch.h,sha256=4dCJGHvqgqZi023TzGXtCe8rqmu8pQWyb3ydPbMMj_k,1080 +torch/include/ATen/ops/_transform_bias_rescale_qkv_native.h,sha256=IpsnK4ozG2dIG3cDnOUFKbx7c8biTRAUP29srJ7LiRw,1224 +torch/include/ATen/ops/_transform_bias_rescale_qkv_ops.h,sha256=OYTQsL9dq4ZJVzjDlB7LWHam5oFOR5gqDEIhCklvZtU,2648 +torch/include/ATen/ops/_transformer_encoder_layer_fwd.h,sha256=4kflBQOqZjWzW7qkn7tBHdzEDOubiCmu7DKS37oWXhg,4887 +torch/include/ATen/ops/_transformer_encoder_layer_fwd_compositeexplicitautograd_dispatch.h,sha256=Jp3KMyhoPvItq_BKT7XJ7uzSGIFXXn0YKc89L1kXFyA,2269 +torch/include/ATen/ops/_transformer_encoder_layer_fwd_cpu_dispatch.h,sha256=SK2XOuopetC6pxsn44jftP8esI1uKOPvyfvo7L6ZJfY,1557 +torch/include/ATen/ops/_transformer_encoder_layer_fwd_cuda_dispatch.h,sha256=hKTWBHC2a1SQRPs6abcc1Nj08VQC5yr5GQf2lpK8xRc,1559 +torch/include/ATen/ops/_transformer_encoder_layer_fwd_native.h,sha256=s-q8chcwY-4Dbvr5HDvW-YbXOz5efV01awE3YCi1sdU,1959 +torch/include/ATen/ops/_transformer_encoder_layer_fwd_ops.h,sha256=id1Zw8x670qVh-l-xhdm__VaHiSt6fmpfQBudSLEo64,5491 +torch/include/ATen/ops/_trilinear.h,sha256=srDh0Ggs6TYyhcqmWUirhlIALcokJia28GXtV0CDbdM,2264 +torch/include/ATen/ops/_trilinear_compositeexplicitautograd_dispatch.h,sha256=-fWp8km2cB31JautRCWfBk4ziUZzk33Jyyn9x4wq5a8,1457 +torch/include/ATen/ops/_trilinear_compositeexplicitautogradnonfunctional_dispatch.h,sha256=-eVbZWsDJBrLonyTNiuTLPJyd-cYG2BQ2kh81VbK1RE,1213 +torch/include/ATen/ops/_trilinear_native.h,sha256=hExdKVtIQFbxyhh8WgrWe6knk10FaTPavRW3uJ68Dcs,1144 +torch/include/ATen/ops/_trilinear_ops.h,sha256=wkuix8odQE0_HHk53OGXfa_Orpzc1tFXv3OLLRH1jgQ,2905 +torch/include/ATen/ops/_triton_multi_head_attention.h,sha256=kXIu7XGcUz9MpoW82eZ3IX1Y_RP2o4gXqGu0XehFeJM,2968 +torch/include/ATen/ops/_triton_multi_head_attention_compositeexplicitautograd_dispatch.h,sha256=5WCY6MZVIEno9HAF_UPvHpXCvUb9x3q9oA53LuEYak4,1672 +torch/include/ATen/ops/_triton_multi_head_attention_cuda_dispatch.h,sha256=abR5-NvbQ0DYHmyFShW-O9ur1-g4m7fo3TrF09TNJs8,1253 +torch/include/ATen/ops/_triton_multi_head_attention_native.h,sha256=6bJpLjY1CJ92P22NMwFvWOoRBoT6iDtj-QToKX2steY,1358 +torch/include/ATen/ops/_triton_multi_head_attention_ops.h,sha256=LH_nwn_cYh-nwvRM4l6xS8l_zgS01vwwpGtbaq_x3cU,3589 +torch/include/ATen/ops/_triton_scaled_dot_attention.h,sha256=fWD5zErvCpc4k1wijK8hSwEALPOYZk94jlUJlbFkHoc,1842 +torch/include/ATen/ops/_triton_scaled_dot_attention_compositeexplicitautograd_dispatch.h,sha256=cA-65pJuUIAV5i9ugLzDyYp4dryi2ByMlY4cRQ7VGXg,1287 +torch/include/ATen/ops/_triton_scaled_dot_attention_cuda_dispatch.h,sha256=VIVFOLyBgTKQ_1S1edrFncvLSExGTa9-9QK4jkKelUY,1061 +torch/include/ATen/ops/_triton_scaled_dot_attention_native.h,sha256=CtseK7CfJ3vGzP8rodW6CKcW_1YKrFMGwwNtJKnVoAk,973 +torch/include/ATen/ops/_triton_scaled_dot_attention_ops.h,sha256=LENUJ9C2kXqyQPysqeaAP7LqT_O7fDbCBr4v_R9Sftk,2341 +torch/include/ATen/ops/_unique.h,sha256=rsqLx0mhRbgCX2eYi5x2u4ogvYKmnK0_h0nnFHX0PhA,1829 +torch/include/ATen/ops/_unique2.h,sha256=QwDxpD1oOcskM_fTg3tbuGlkkrZIPvLgo-6UP6XowI0,2187 +torch/include/ATen/ops/_unique2_compositeexplicitautograd_dispatch.h,sha256=ySHQRbtkGisvdRleUXa3F_MI9hX7MhCJgbHuXXJgI_0,1408 +torch/include/ATen/ops/_unique2_cpu_dispatch.h,sha256=hZ-roODay6Lq9rAsKZTs11H4ai7X7OGctTcx06k_r_Q,1083 +torch/include/ATen/ops/_unique2_cuda_dispatch.h,sha256=YivjIGnQa8Nj2Ld1nNYfAVr00yrJCjfPV4yVhxLzmIY,1085 +torch/include/ATen/ops/_unique2_native.h,sha256=WYltVX55P4VrjpPBBXRv9bqnW-AYANdlVM5KxybtjN8,1224 +torch/include/ATen/ops/_unique2_ops.h,sha256=Sb4UohpniqR5WQoyUYSCj3FtMJtmzD7h-FjIipYTDtA,2620 +torch/include/ATen/ops/_unique_compositeexplicitautograd_dispatch.h,sha256=vxE9L9FkrbDtegjsLEdF7CDfNyTNa_8ZBWxggW90US0,1296 +torch/include/ATen/ops/_unique_cpu_dispatch.h,sha256=8YaUqvCqyUP5xGnlUe6Wmao1DIbiXq5SV4LmQBd7y00,1045 +torch/include/ATen/ops/_unique_cuda_dispatch.h,sha256=FP1taNR0AfrBLjgkl-j8NoKGmO4QPlDKpyi21QT9wm8,1047 +torch/include/ATen/ops/_unique_native.h,sha256=79Q54mE5ALgnBI_P6cyfW9hYrLWRKgRk8TDNWeS-1NE,1095 +torch/include/ATen/ops/_unique_ops.h,sha256=GX19M2iokyDKfBigxLPy3mHIwrF4X7sUtH_AOhqQ4uE,2309 +torch/include/ATen/ops/_unpack_dual.h,sha256=brWF2l6JfeVlIMeiYBdEMpu4Dj2f9oMm1zLrklsGVDw,1004 +torch/include/ATen/ops/_unpack_dual_compositeimplicitautograd_dispatch.h,sha256=4kc9r9ThBnwM-H1-_mVIB326iYiQxV6g_4YzjhVQsF4,1064 +torch/include/ATen/ops/_unpack_dual_native.h,sha256=ed7Z3N_dwDUgyufmf69qtur7Ow-_mBUUqBMUqFO9aFc,776 +torch/include/ATen/ops/_unpack_dual_ops.h,sha256=5LTmk3aKWbUGeRPImUbQ6_ZxIfePGU3kZ14kmesYPSY,1385 +torch/include/ATen/ops/_unsafe_index.h,sha256=hmqradtOd00tUFx_L8MQzr4eZLLGTCeblnAECPeiX6U,1017 +torch/include/ATen/ops/_unsafe_index_compositeexplicitautograd_dispatch.h,sha256=8pacFQIDwJ02Td3ocszbl3Zy4D01GjTpEM_gMkZ6SLM,1081 +torch/include/ATen/ops/_unsafe_index_native.h,sha256=Z5b21NnM8Yg6C-QULzb2tE-dEKuBMHZ11BMwF0tCmt4,793 +torch/include/ATen/ops/_unsafe_index_ops.h,sha256=_TBdjzHJw73BVk474H2JhvohhhkpZLxWl65Qtc77Vuc,1431 +torch/include/ATen/ops/_unsafe_index_put.h,sha256=TRH3v7-MlIboiSh-WvlrttMdbFR6TVyZtgwl4kfFGio,1127 +torch/include/ATen/ops/_unsafe_index_put_compositeexplicitautograd_dispatch.h,sha256=PTSv-olEDp985V0lzpffHLUSkCVmBWro9uS8D7IJg8U,1135 +torch/include/ATen/ops/_unsafe_index_put_native.h,sha256=2fECDmIRQAO--I-8QzIqjNy-yvea7vgE_HEDVFpqZOk,847 +torch/include/ATen/ops/_unsafe_index_put_ops.h,sha256=6S5CIlpNtu4DcRIgnw0hNJVZbJ2E3-Tfvke42bMokXY,1575 +torch/include/ATen/ops/_unsafe_masked_index.h,sha256=N8gUW1UuTzmxWboI8wZYHlkbeIACGO-7i-W5aZhH76w,1119 +torch/include/ATen/ops/_unsafe_masked_index_compositeexplicitautograd_dispatch.h,sha256=jMuot6odiiXSaeB20ZHxQeS34Odw3XQZ0VV9lsZ7nlU,1138 +torch/include/ATen/ops/_unsafe_masked_index_native.h,sha256=iWj1FFAc62GwnTFgUdUc-dUndV6UhB3vocdAoSpEEBA,850 +torch/include/ATen/ops/_unsafe_masked_index_ops.h,sha256=zZhROJWH0z5m9fi8DdPrjOj1qB1ZhMFGifP2BDVo7J8,1598 +torch/include/ATen/ops/_unsafe_masked_index_put_accumulate.h,sha256=6-c5FqqWIJarYlkKSdjhoBgxGWDjRVQYOLyh1LidYBU,1185 +torch/include/ATen/ops/_unsafe_masked_index_put_accumulate_compositeexplicitautograd_dispatch.h,sha256=tixFFt6nN3TLQQ-ACd8ac7hseUSCbuBK27X5kZ1WjZ0,1155 +torch/include/ATen/ops/_unsafe_masked_index_put_accumulate_native.h,sha256=4zwlnCAYJ8H97YQoi1FfPr9mbGzdMdkYqp49DIBLKJ4,867 +torch/include/ATen/ops/_unsafe_masked_index_put_accumulate_ops.h,sha256=MjWX6KKvWZGUCIF6k9iznV36TvqOp3n-bfGR6I6--24,1649 +torch/include/ATen/ops/_unsafe_view.h,sha256=iWocRbucWFBOCvCcDyVRFzdpt780gnL0ZE8OMLVToUM,3931 +torch/include/ATen/ops/_unsafe_view_compositeexplicitautograd_dispatch.h,sha256=lvA9HWSfa-DVbSxecuti6sloK6r-_tY8ZUk6LxLr67Y,1587 +torch/include/ATen/ops/_unsafe_view_native.h,sha256=krtBJoLo-CkfQxBi_z_0XcEPtcgPXZ4zUD6xOwGRNnk,875 +torch/include/ATen/ops/_unsafe_view_ops.h,sha256=YIoUMtZGrQVXEgtjbmwUjgl032oEsPCogr3-zyBaSt4,2013 +torch/include/ATen/ops/_upsample_bicubic2d_aa.h,sha256=a505MLcsXUXioGqzgMy7l3APw7YNO_3sHPSo5YKuoxc,8356 +torch/include/ATen/ops/_upsample_bicubic2d_aa_backward.h,sha256=i4pmLCRcgFdIs9ye1EvL_M4yBuOSk4Wyjy9NtzLBV2s,8062 +torch/include/ATen/ops/_upsample_bicubic2d_aa_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=W_9xAAMDhMnpUwjqGAX9kTGebwert8vbZEE9sVCAMfE,1527 +torch/include/ATen/ops/_upsample_bicubic2d_aa_backward_cpu_dispatch.h,sha256=TtDQHCGRM__yxkFoNJh1jBq3JaCQYPi_xNWWbLV5fxk,2597 +torch/include/ATen/ops/_upsample_bicubic2d_aa_backward_cuda_dispatch.h,sha256=UCFFR7P6iSvpMhugfqZJi_NRIqcRPFjPnekrKvP2WDo,2599 +torch/include/ATen/ops/_upsample_bicubic2d_aa_backward_meta.h,sha256=LwU2FU6gP1lN86wNuhWadqMpmT7z3uWVEZHU_3HWeKs,1010 +torch/include/ATen/ops/_upsample_bicubic2d_aa_backward_meta_dispatch.h,sha256=pqUCYptw_A2NGFTe9Vgl0G2XtNqnb5WmkllW1reN7TU,2599 +torch/include/ATen/ops/_upsample_bicubic2d_aa_backward_native.h,sha256=nJg7zl7NRrZfZrMt1hzK1kAX75DRGc3QI-Ojm6FCmyc,1467 +torch/include/ATen/ops/_upsample_bicubic2d_aa_backward_ops.h,sha256=LY0YbBxzz_WUzrRGVEzaruV1RZBmxApBz2uVp83z6pY,3061 +torch/include/ATen/ops/_upsample_bicubic2d_aa_compositeexplicitautogradnonfunctional_dispatch.h,sha256=3S6UhJjgiPhYABBzXEl62OQ3HHeba_mEEsSX2uOcrZM,1435 +torch/include/ATen/ops/_upsample_bicubic2d_aa_compositeimplicitautograd_dispatch.h,sha256=Xup1yTCrYPBYmJxMAeE91mtVJt4e1SeABmrAdrKJ0Z0,1336 +torch/include/ATen/ops/_upsample_bicubic2d_aa_cpu_dispatch.h,sha256=jylbU4Hm4HjVVRwMlZH_qELnUgbrjns52k6l6tmvrgY,2293 +torch/include/ATen/ops/_upsample_bicubic2d_aa_cuda_dispatch.h,sha256=2YO3KWkm4JQ2V0B84HW_7PNAIsP2wWp-XMxZsn4sTOc,2295 +torch/include/ATen/ops/_upsample_bicubic2d_aa_meta.h,sha256=dzJ5dBmumhp4WsR_ofKMaWU3-KGRdB1SoJQvTtfAONY,960 +torch/include/ATen/ops/_upsample_bicubic2d_aa_meta_dispatch.h,sha256=v56I6MFZ0Q_ndz7_kGi-xHEdxKxbdwGY0Mwa6sdd_OQ,2295 +torch/include/ATen/ops/_upsample_bicubic2d_aa_native.h,sha256=cwYKmsxsYHhN_tA5zwi8oyUZLzTajfmWOfke0lABlS4,1507 +torch/include/ATen/ops/_upsample_bicubic2d_aa_ops.h,sha256=yMbSWB2p_4jdtxnSvdnCiP01z5nxhkwJm232VzW8Lag,3637 +torch/include/ATen/ops/_upsample_bilinear2d_aa.h,sha256=YvzGar8UtH6sIUpcloHX_lQb4HsVE2_zFBm_Ko_xbCo,8397 +torch/include/ATen/ops/_upsample_bilinear2d_aa_backward.h,sha256=cZWyZZfbkDSn5PWQ7FbaHWBJ_PJKZIFX7MohHAI844s,8093 +torch/include/ATen/ops/_upsample_bilinear2d_aa_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=rIXZ4EhlE-XK2JHk6OG2z_sLKk71_iKan_I07THrftQ,1529 +torch/include/ATen/ops/_upsample_bilinear2d_aa_backward_cpu_dispatch.h,sha256=Kl2BoO9w2E8WCYbT3UeIZtQDwSK3pOeMI8IuyN0MOCA,2603 +torch/include/ATen/ops/_upsample_bilinear2d_aa_backward_cuda_dispatch.h,sha256=VKS6OSPTdcwuWJy6VkiPFUj38RKUCGfXZ6YScMaoC7M,2605 +torch/include/ATen/ops/_upsample_bilinear2d_aa_backward_meta.h,sha256=Fnw_6m4lpSvYZvGJgvwCCD4IDcR_SDW8uM63n83pjbA,1011 +torch/include/ATen/ops/_upsample_bilinear2d_aa_backward_meta_dispatch.h,sha256=rhk4ZnZncfcz6FSKlbtXAW9CQX0bepl5Cu15xPVnnzc,2605 +torch/include/ATen/ops/_upsample_bilinear2d_aa_backward_native.h,sha256=MXh0vjrR6uzhoA33v4awCddfT-j7N_U3MCJ1iYjGLBY,1472 +torch/include/ATen/ops/_upsample_bilinear2d_aa_backward_ops.h,sha256=qyb7xOIH1D6H_rR_BIbxKPuFyYSkW049vH4JfAfO--A,3067 +torch/include/ATen/ops/_upsample_bilinear2d_aa_compositeexplicitautogradnonfunctional_dispatch.h,sha256=K0Z7mqEwvw-q9bhOIR_pzbtIRy-QNwHhxIPRZElWlvs,1437 +torch/include/ATen/ops/_upsample_bilinear2d_aa_compositeimplicitautograd_dispatch.h,sha256=bKKUnvrWzy8IkleB5q0HzrRLgLaND0Du0ganG-Ew4Qg,1338 +torch/include/ATen/ops/_upsample_bilinear2d_aa_cpu_dispatch.h,sha256=q5nBGrSbHYNHErUc1LpPvC24LVUXpB_yDDh1WWWgjls,2299 +torch/include/ATen/ops/_upsample_bilinear2d_aa_cuda_dispatch.h,sha256=6AkwSQliMB4kXSdDgyevsVU2wENF-M7n37y5vn1W45c,2301 +torch/include/ATen/ops/_upsample_bilinear2d_aa_meta.h,sha256=qWLGU_eX5jO6ohH75JVgF2vLiZ1YoBz3AGuGnTUHI-E,961 +torch/include/ATen/ops/_upsample_bilinear2d_aa_meta_dispatch.h,sha256=bzfgxinFjQy3f8HFlGaFdWQvpNkJe5Jtis2a3folihQ,2301 +torch/include/ATen/ops/_upsample_bilinear2d_aa_native.h,sha256=n9Z_xgi8LzuWD4ssW1ImaOjWN0XTrjs7kXfdSEtC4ns,1513 +torch/include/ATen/ops/_upsample_bilinear2d_aa_ops.h,sha256=0Olc6R8uKhj1PQPfeGTr1mPaEqY73oddDf9r3q0OK2A,3646 +torch/include/ATen/ops/_upsample_lanczos2d_aa.h,sha256=EtdVT90xRaFZP1jhUyVlFT7vusQpg-1Cs-Y8r-e68EE,8356 +torch/include/ATen/ops/_upsample_lanczos2d_aa_backward.h,sha256=vwzVw6R4aCo4OROzlHroocM6PNso6TtsjK96boDgVKA,8062 +torch/include/ATen/ops/_upsample_lanczos2d_aa_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Blwhobd3QxlLyZzspmNWVUi9IOn6bi6ipw0yWsTED64,1527 +torch/include/ATen/ops/_upsample_lanczos2d_aa_backward_cpu_dispatch.h,sha256=yuyU1PdjzryOh3gbQdZAHGe8na0F8CfytE9vXK3FdkE,2597 +torch/include/ATen/ops/_upsample_lanczos2d_aa_backward_meta.h,sha256=fSDUXMUXoBvE3OWByfeo-wbiPBPmBYVu5kmOu7NIHzc,1010 +torch/include/ATen/ops/_upsample_lanczos2d_aa_backward_meta_dispatch.h,sha256=Ri1W55ihmwmKCQXgGN-m45-UdLnVFeaphcH235zh7Oo,2599 +torch/include/ATen/ops/_upsample_lanczos2d_aa_backward_native.h,sha256=ZKra-SpzkJ8FoDBeuAHirywk5suoESb8ijlDSMYaNc4,1100 +torch/include/ATen/ops/_upsample_lanczos2d_aa_backward_ops.h,sha256=kcltuThUhEodDY6BdPRKSf3gBEprI5wNDMb0b9Jxky0,3061 +torch/include/ATen/ops/_upsample_lanczos2d_aa_compositeexplicitautogradnonfunctional_dispatch.h,sha256=azfrP5YrON77tfmAA5uQkwz1nRDmKqdJyynXRdJeVfg,1435 +torch/include/ATen/ops/_upsample_lanczos2d_aa_compositeimplicitautograd_dispatch.h,sha256=dnv70_Y4TJW0V_f191LxcxN3t13l_EkLGWplmxmfRYQ,1336 +torch/include/ATen/ops/_upsample_lanczos2d_aa_cpu_dispatch.h,sha256=tHbYWrfOukkAdLZzNdsA0U0rtq5-191l9eWdD1AlC_I,2293 +torch/include/ATen/ops/_upsample_lanczos2d_aa_meta.h,sha256=4xssoiPxfJN_r4MHgnq_SEnptKu8kZgPX5e7xbgot5c,960 +torch/include/ATen/ops/_upsample_lanczos2d_aa_meta_dispatch.h,sha256=mjWNq0MYalKLXvJDha_MvQUDtB54U496VpK2zUkk5oU,2295 +torch/include/ATen/ops/_upsample_lanczos2d_aa_native.h,sha256=2xZmc5fNq4WgjdyhoXpgErSsdXfqLI5N2bJSc2UnU1M,1206 +torch/include/ATen/ops/_upsample_lanczos2d_aa_ops.h,sha256=Wj7o5WgPorlNNQcZVTdYiQGrtNFao8laD6MQJqQFsq8,3637 +torch/include/ATen/ops/_upsample_nearest_exact1d.h,sha256=-VzqLi1f5OqNPNXBfRCuAf9XITS7vhPEfdeZ7aLd98E,6919 +torch/include/ATen/ops/_upsample_nearest_exact1d_backward.h,sha256=Zq8vPZFESYz-2YhSXApOYSfaHwdp6DpBGbWLxHMN-BQ,6775 +torch/include/ATen/ops/_upsample_nearest_exact1d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=JtPQnN0MBhW7jVGVRgfe5z-b1t6UBqf19FFPvGCWkMY,1391 +torch/include/ATen/ops/_upsample_nearest_exact1d_backward_cpu_dispatch.h,sha256=Buxozcm713Vzuo_DLXTmGXnG5OjutSNfQvN6k0-USLI,2219 +torch/include/ATen/ops/_upsample_nearest_exact1d_backward_cuda_dispatch.h,sha256=qR0U3H7WZp4fnRXpPimht7hB_f-OfVvCLLwf7QNXDnU,2221 +torch/include/ATen/ops/_upsample_nearest_exact1d_backward_meta.h,sha256=nHyhPyOPQrpHAT3AAMXyxPI3GCmStmCzyt0-9flq1y0,957 +torch/include/ATen/ops/_upsample_nearest_exact1d_backward_meta_dispatch.h,sha256=sARQXSfllsDLVuTw46DzReAbeAmlobxVZVX0X9LmY30,2221 +torch/include/ATen/ops/_upsample_nearest_exact1d_backward_native.h,sha256=KUxRIl74AANLQcB7b1pdLmsJYMF1apieVw5RMcWadfs,1370 +torch/include/ATen/ops/_upsample_nearest_exact1d_backward_ops.h,sha256=2SpIfpezDzwgkFl1R3B98PIrAxOv2NrIxlEj4Ph3Zmc,2705 +torch/include/ATen/ops/_upsample_nearest_exact1d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=KtdVloCczJfolOClZkGjukZ5YuQkEqJ3LD3NPx757zQ,1299 +torch/include/ATen/ops/_upsample_nearest_exact1d_compositeimplicitautograd_dispatch.h,sha256=hPRQy2ofENs0SetSTeaZl42mhucTQj1KkSVN4MT8_Jo,1302 +torch/include/ATen/ops/_upsample_nearest_exact1d_cpu_dispatch.h,sha256=TtTBUGPwY7AV0cEe7uVJs9QHf0NTEDpbjo8nZ13HKvU,1915 +torch/include/ATen/ops/_upsample_nearest_exact1d_cuda_dispatch.h,sha256=qi43BUOSbTNMhxMbq8F_DrfvdtI8ZH4XLyWNI8k8A8U,1917 +torch/include/ATen/ops/_upsample_nearest_exact1d_meta.h,sha256=7HSjwa0I-NQB936fGElGvp-RIWmus3QHSZP3WoktRIE,907 +torch/include/ATen/ops/_upsample_nearest_exact1d_meta_dispatch.h,sha256=layj9A_7u3EDqLaMhJJ-1cP2VhppbzJc0ckjUSGG-18,1917 +torch/include/ATen/ops/_upsample_nearest_exact1d_native.h,sha256=lazql9Sdgxqv21aKEv-2IHrNEubItERKEIDuTfVzjcQ,1393 +torch/include/ATen/ops/_upsample_nearest_exact1d_ops.h,sha256=GKrlFdXOLwJkKJ9U9-wtV5ZCkkwJYy0pLhzy28IXB9Q,3224 +torch/include/ATen/ops/_upsample_nearest_exact2d.h,sha256=er7MXi7yI46xSpkIflPtVPGrKczXdwgn9oM_ImftD6E,7759 +torch/include/ATen/ops/_upsample_nearest_exact2d_backward.h,sha256=jxZdHt20lbOtnX28tVHGaSs1lGK8tEa5snhilG7tNIo,7615 +torch/include/ATen/ops/_upsample_nearest_exact2d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=wfxLzb2DI9s3lNrP29rUltdVjqliI4NRxBDJgj-a7Lc,1493 +torch/include/ATen/ops/_upsample_nearest_exact2d_backward_cpu_dispatch.h,sha256=JvQgfoNa1J9_bK7AWSOFWDYKf5l4Hx1Y0uuAN8pGlIM,2495 +torch/include/ATen/ops/_upsample_nearest_exact2d_backward_cuda_dispatch.h,sha256=VPvkSeiBjHlQk3437ZQnVPUX-kjAm9HDYAHVXyrleR4,2497 +torch/include/ATen/ops/_upsample_nearest_exact2d_backward_meta.h,sha256=zDN18dX0bcQ1-NV0zSCao4VWoDwd4PXWFktT-OO9390,993 +torch/include/ATen/ops/_upsample_nearest_exact2d_backward_meta_dispatch.h,sha256=STtiQQ6Zg8fbszcGtR9AnLtQsEri0qsDSwtBG7Uww_Y,2497 +torch/include/ATen/ops/_upsample_nearest_exact2d_backward_native.h,sha256=NAWvamyBca1bbaz6iQSZ2C_Ho5_hxaLI1d7xL8nwdGA,1442 +torch/include/ATen/ops/_upsample_nearest_exact2d_backward_ops.h,sha256=Fj1buERxJHULu7Ljz3qJ56rRHmTiEuNAS2ttF3YftJo,2947 +torch/include/ATen/ops/_upsample_nearest_exact2d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=55uGnP6Vas5Z94bMqZocP4Wddx2nKALWJz8SeB7_Ffg,1401 +torch/include/ATen/ops/_upsample_nearest_exact2d_compositeimplicitautograd_dispatch.h,sha256=_8ZULi7SYU1W3OIgdwoDaZi_qMUegD3Tbmp2XzoB928,1302 +torch/include/ATen/ops/_upsample_nearest_exact2d_cpu_dispatch.h,sha256=NJMT6BPIlENl8qnpiACaEhRyfPy0M8tELzG0U0rlU7M,2191 +torch/include/ATen/ops/_upsample_nearest_exact2d_cuda_dispatch.h,sha256=RZ38hgBJK0z7wOYxBNarekhjhOtw8jejV-BHsNY-BRw,2193 +torch/include/ATen/ops/_upsample_nearest_exact2d_meta.h,sha256=wOy0A87SiFip_E-IU5svRcy1-jJRAiJSNOm0ClCnPX4,943 +torch/include/ATen/ops/_upsample_nearest_exact2d_meta_dispatch.h,sha256=a82hPBXPZkFGzC2AO_lg8pyX63aw7_NtgNYOha90ElY,2193 +torch/include/ATen/ops/_upsample_nearest_exact2d_native.h,sha256=ztbEqaJR1Un3378p5ZrAC6RdrqD80DnBX4mm489hnZw,1679 +torch/include/ATen/ops/_upsample_nearest_exact2d_ops.h,sha256=9_ETL_S3FxEx2z0f_j6YASRF11_S-8RVXrRovn3fr7g,3466 +torch/include/ATen/ops/_upsample_nearest_exact3d.h,sha256=m66uZfhFrU3Q68rrx9i0IruJxF8MTD6XLsGbTNVqaN0,8539 +torch/include/ATen/ops/_upsample_nearest_exact3d_backward.h,sha256=gGAEvwTsKbDJJbfZN1L0N_hRKjRyInUMOtd917ewm0w,8395 +torch/include/ATen/ops/_upsample_nearest_exact3d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Dj45oW2SKqkOxcJifeL6KGdICQcfrKEVHyHlrmAvMp8,1591 +torch/include/ATen/ops/_upsample_nearest_exact3d_backward_cpu_dispatch.h,sha256=FeOrO-KUXod0-XZTDYL-FgLvIWcETT_fD6eB5oL0ygc,2759 +torch/include/ATen/ops/_upsample_nearest_exact3d_backward_cuda_dispatch.h,sha256=BxgfmFKa-sW4-NGVGyFWk6OzIkRrvo8pulnJlv_nBDk,2761 +torch/include/ATen/ops/_upsample_nearest_exact3d_backward_meta.h,sha256=tOsyGMLkR7kQ-txLR6A8uLGNv79_FXPTsmgD-uRC0iM,1027 +torch/include/ATen/ops/_upsample_nearest_exact3d_backward_meta_dispatch.h,sha256=WfTcn_mx8KFRPJHqlGvZRRse3Q7rL1-v7D_P36ePOgE,2761 +torch/include/ATen/ops/_upsample_nearest_exact3d_backward_native.h,sha256=7WPaxijaJ-pw_aeSoTvTtUeY1NF8p0edcCjAeOW_CFo,1510 +torch/include/ATen/ops/_upsample_nearest_exact3d_backward_ops.h,sha256=V7irNu74WJGlj0iSCwZXaiQJW6ts0UrAkAn-SBjjIM0,3177 +torch/include/ATen/ops/_upsample_nearest_exact3d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=ukjik3qvwnmcUQuR8P7ppo3b_m9BQVENFbcQmsWE6lY,1499 +torch/include/ATen/ops/_upsample_nearest_exact3d_compositeimplicitautograd_dispatch.h,sha256=Wd79kYkAQsrl4jAvkPAq2itfTImnu2KllGfhCqXVwkU,1302 +torch/include/ATen/ops/_upsample_nearest_exact3d_cpu_dispatch.h,sha256=9d89SQwDQqPlRrDT9qN90GoN2T8o0_j6CSDYt_OxfFs,2455 +torch/include/ATen/ops/_upsample_nearest_exact3d_cuda_dispatch.h,sha256=Mnkl-UneGBFuU3AdDmq4AcP6mz12zKO7eTlPGtyLFoI,2457 +torch/include/ATen/ops/_upsample_nearest_exact3d_meta.h,sha256=qfVa4ROO2O5uOalXdUaT7JzJCQ2_DtykNhTH08761SQ,977 +torch/include/ATen/ops/_upsample_nearest_exact3d_meta_dispatch.h,sha256=H4x4ehY2jkrfO4jy__o7ykqrLVqLFaD0Az3dh9KGtHg,2457 +torch/include/ATen/ops/_upsample_nearest_exact3d_native.h,sha256=M34L2Ck0Hd_otuL9gGPwHUbmde57WSn2dYUWYH80R88,1796 +torch/include/ATen/ops/_upsample_nearest_exact3d_ops.h,sha256=ymyECr6drkzmluGFbjcpR0z5ncBwAkkJBr9rYq1UdWQ,3696 +torch/include/ATen/ops/_use_cudnn_ctc_loss.h,sha256=Q6dtRzf423FRHCbPF8Ys8oHqMOAqFA-sam0N-F3sfbA,1599 +torch/include/ATen/ops/_use_cudnn_ctc_loss_cuda_dispatch.h,sha256=DTkZf4JozwSePZGvbikJ4a8Mv3iv-aQMJW4A5h0DAAk,1272 +torch/include/ATen/ops/_use_cudnn_ctc_loss_native.h,sha256=a_UfLMuo9166t4hvHmvqkejgWnEmui2gK_ysLKpC5FQ,1033 +torch/include/ATen/ops/_use_cudnn_ctc_loss_ops.h,sha256=xAg02IGRYu-Y1u7keUOjEcNWi3gfhJMwvBY1LSqAZos,2509 +torch/include/ATen/ops/_use_cudnn_rnn_flatten_weight.h,sha256=KMjHrpDN8_LM_RniE2Gab1A-vBRa0Pp83X_KH_SKzrU,937 +torch/include/ATen/ops/_use_cudnn_rnn_flatten_weight_compositeimplicitautograd_dispatch.h,sha256=hlgWIOKVPFJ-wFRJ1gDJovQu8nIKlresHJ0jgHMxXhQ,1012 +torch/include/ATen/ops/_use_cudnn_rnn_flatten_weight_native.h,sha256=wxTQ21j3wTM5xQBgfydOXm8C0MLwH5uIALNtKH8W2E4,724 +torch/include/ATen/ops/_use_cudnn_rnn_flatten_weight_ops.h,sha256=xw7TKU8qsfBLCqOXIvNRwtZ-6twudxr48W1dTkO8X4s,1183 +torch/include/ATen/ops/_use_miopen_ctc_loss.h,sha256=ch2oyRNMzvsKwkRvsh93F2uc1sqycsribmR6dnK7d5U,1606 +torch/include/ATen/ops/_use_miopen_ctc_loss_cuda_dispatch.h,sha256=vLFjbLKRx_FfSr6xUQ6y1MRAU2ygHiQbnYxdlO1gFmU,1274 +torch/include/ATen/ops/_use_miopen_ctc_loss_native.h,sha256=12GjqucV_vjKINQ-woJcj_Hvu0tCsVb5XjwQhMnMayI,1035 +torch/include/ATen/ops/_use_miopen_ctc_loss_ops.h,sha256=avNAoNEX9JoZRC-1iIddUv3xnyBacpVTGgn4F9eR08A,2515 +torch/include/ATen/ops/_validate_compressed_sparse_indices.h,sha256=TwKTJlw2cRBvVIIroFatmHZDMfHUMUp9mSAbea6XjbM,1207 +torch/include/ATen/ops/_validate_compressed_sparse_indices_cpu_dispatch.h,sha256=p1WvNhq856wg39g-58tQwA8HHYbAblibVLYAbrLSZp0,1091 +torch/include/ATen/ops/_validate_compressed_sparse_indices_cuda_dispatch.h,sha256=BSNli22tTDuxG3itkZcpGXQsc41kBP1GvoDSyDyAdUg,1093 +torch/include/ATen/ops/_validate_compressed_sparse_indices_native.h,sha256=glqBe3VCHW3vTd2bUCH3MkkQ3sWnFG62F2tsWpZtZmk,1027 +torch/include/ATen/ops/_validate_compressed_sparse_indices_ops.h,sha256=Zf_fMspJD9BqD8LMV_AEuOwJ2-eAQoUR_jhSf2AxH_Q,1587 +torch/include/ATen/ops/_validate_sparse_bsc_tensor_args.h,sha256=ixNPc5dm8_i606gp5fbUIo5W29jBmXSaCwYVTPl6crw,1257 +torch/include/ATen/ops/_validate_sparse_bsc_tensor_args_compositeimplicitautograd_dispatch.h,sha256=lcsWlj5pzZdSoVh9dkh8MH_NIA986axGqPhLq-vpvWw,1179 +torch/include/ATen/ops/_validate_sparse_bsc_tensor_args_native.h,sha256=zWxbahDHV3c5zRGuM7FVHn5gSYmi2uxiwkd0hL0vt7Y,891 +torch/include/ATen/ops/_validate_sparse_bsc_tensor_args_ops.h,sha256=kgwjjPBD9jTiudWr0GONJbkV32YC2_SiiCBPsotmm0I,1680 +torch/include/ATen/ops/_validate_sparse_bsr_tensor_args.h,sha256=rXkSNbt5k2zbytjH_lRPx7TNspy-8IjedrY3ep-HVJM,1257 +torch/include/ATen/ops/_validate_sparse_bsr_tensor_args_compositeimplicitautograd_dispatch.h,sha256=xD8GBwPs5j4_Cs-rVtEjIeWdrehYRMSJlNNLe1nOGbc,1179 +torch/include/ATen/ops/_validate_sparse_bsr_tensor_args_native.h,sha256=_88gen0XPNtZEEWEJcNuUWyLVJLPa4Y1tNbz01p5njo,891 +torch/include/ATen/ops/_validate_sparse_bsr_tensor_args_ops.h,sha256=YVuveutg3GJ6mZZLQ6xMQwD95SIOPAAHMPcCc3I8FnY,1680 +torch/include/ATen/ops/_validate_sparse_compressed_tensor_args.h,sha256=7YGke7COaJqCpj8Qk8S8mK7ka1BaLxe5IQgNIb7HCN0,1351 +torch/include/ATen/ops/_validate_sparse_compressed_tensor_args_compositeimplicitautograd_dispatch.h,sha256=EVH8XCKguYPWBXgX_gaOp5ocDYRs57nAZwJL8bVAsS8,1213 +torch/include/ATen/ops/_validate_sparse_compressed_tensor_args_native.h,sha256=B4pvQ7iPzNOZsEH_N2sP0eygQtFbYcLOcGHrnPnnEaQ,925 +torch/include/ATen/ops/_validate_sparse_compressed_tensor_args_ops.h,sha256=fWlNj3YlEEBZXM3LVJ72Bi2_LAlgqeAO8Flp7tiM5mc,1790 +torch/include/ATen/ops/_validate_sparse_coo_tensor_args.h,sha256=WBRIzoKsgrWjaQTDW6NyTQrAnytE9d45A4jRHZ7iXQI,1267 +torch/include/ATen/ops/_validate_sparse_coo_tensor_args_compositeimplicitautograd_dispatch.h,sha256=3NEmCQCZ683DROT3XMRaI_8sRWgUDHFQEll02M6U7y0,1193 +torch/include/ATen/ops/_validate_sparse_coo_tensor_args_native.h,sha256=q_hWs9fNeUoMFyz4OaTWbjiA5iIOfXdaf4L6BJUwT64,905 +torch/include/ATen/ops/_validate_sparse_coo_tensor_args_ops.h,sha256=oA_FWScGvbW334yN9b83bWmXkRk1ZbtzFwBVNyxf9Bc,1681 +torch/include/ATen/ops/_validate_sparse_csc_tensor_args.h,sha256=WgPHJOtv2MP7vY1fvHRBLXkcvnDLNzw-wMIc1FPr5bs,1257 +torch/include/ATen/ops/_validate_sparse_csc_tensor_args_compositeimplicitautograd_dispatch.h,sha256=VBjHhDxZM4B6DYRiCRIoeMVLWGD1-Eh4pUp1v4jOsE4,1179 +torch/include/ATen/ops/_validate_sparse_csc_tensor_args_native.h,sha256=Srfpvfb_RG1a93X9VAwcHIXW3ooV16eIU1kkwrmjgFU,891 +torch/include/ATen/ops/_validate_sparse_csc_tensor_args_ops.h,sha256=3zxD2w3kY9usfrrNeNbEsRiIV8Ady8I9gkULhYZmzTM,1680 +torch/include/ATen/ops/_validate_sparse_csr_tensor_args.h,sha256=VnlhJ_bOBPeUMxkyT-mVmQSmVAkVJ97EJCmdg3vslTI,1257 +torch/include/ATen/ops/_validate_sparse_csr_tensor_args_compositeimplicitautograd_dispatch.h,sha256=6RoNg5U44a6AYbBq7QTfNC927ES9AII-SN5nwYv_TVk,1179 +torch/include/ATen/ops/_validate_sparse_csr_tensor_args_native.h,sha256=6kRnFWMOs3eJ0yJDIk5nlV_deUIKo9F-0lkQwjZWlyU,891 +torch/include/ATen/ops/_validate_sparse_csr_tensor_args_ops.h,sha256=-whUikyf2-mb0uyqAiEEkNSj1cmmVqGhjUpjzdCXDjQ,1680 +torch/include/ATen/ops/_values.h,sha256=Dg_QWAMq-LLw-BhgaT0IJp42KzKqfOD81eeqesFgXus,758 +torch/include/ATen/ops/_values_copy.h,sha256=wbSEhync8x7_GE35tOco5AgT9W9FCgdjIiPZyZNDBuw,1341 +torch/include/ATen/ops/_values_copy_compositeexplicitautograd_dispatch.h,sha256=XN9fghPHAE3SITptDJ7XTbo676rHuPAO7my_yvFjs2A,1133 +torch/include/ATen/ops/_values_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=_xVpqjkTVrMuk1MbbVj1mPbtO2B5If_1Ez6OFje2ZG0,1050 +torch/include/ATen/ops/_values_copy_native.h,sha256=_8AdpssN8ZEmmVoSg3yrVehBMp39YNT539UPryAXlOg,820 +torch/include/ATen/ops/_values_copy_ops.h,sha256=C4A9ULsTUU2kTyMCF42pIvHszsVU0_Wwt2QdV_JBSjA,1837 +torch/include/ATen/ops/_values_native.h,sha256=dKcw-lt74N_w3u5aLwIgacV_LBzklGQY-GZpHJCQmX4,738 +torch/include/ATen/ops/_values_ops.h,sha256=NMvnlMuOvESmPZgDq_csK17NdxQzvlaIns4BJr9NsY4,1220 +torch/include/ATen/ops/_version.h,sha256=LNcq-X-EzC_6_HcNV7LvEz0t8Egc7os0P1J6ZUkwsGA,759 +torch/include/ATen/ops/_version_compositeimplicitautograd_dispatch.h,sha256=3YwoJcapKyeRV4v4Z7QFIig-jjWT6OsPREw2Zi5pQCc,1017 +torch/include/ATen/ops/_version_native.h,sha256=AX6eWzsaxd6erMgw9UbE6SrzjuvUGXMmxYu8A8dbRzU,729 +torch/include/ATen/ops/_version_ops.h,sha256=tQVkbnf_X2Z3_CxZcTOEw1b-tk-avcZDSYt5FyCDfw4,1205 +torch/include/ATen/ops/_weight_int4pack_mm.h,sha256=d_A5j_NLmHnTjOdrms94oL8u0ZmL7jCu_YnsOjC-TA8,1109 +torch/include/ATen/ops/_weight_int4pack_mm_cuda_dispatch.h,sha256=rq1R-KrOuyzeYOgNK785Up7aocrOoD2XN3bJtzgki2c,1069 +torch/include/ATen/ops/_weight_int4pack_mm_for_cpu.h,sha256=mpPE3zMiTIFstbHvw5CSTf3LcEQrycU4CiyoDeDqhrM,1141 +torch/include/ATen/ops/_weight_int4pack_mm_for_cpu_cpu_dispatch.h,sha256=bPXPjUFsE-0wQjKNlVj7bCDbV6rCSqM2QhKo3H5BVvA,1075 +torch/include/ATen/ops/_weight_int4pack_mm_for_cpu_native.h,sha256=DspzQu0zLyAFgMSlI25j86NPkvHlbw6pnQkZ5u8FdiU,827 +torch/include/ATen/ops/_weight_int4pack_mm_for_cpu_ops.h,sha256=zk_5TdC4rAjBtS6w8pAJBcX8Py_6gppYg1dbVtHZjIc,1535 +torch/include/ATen/ops/_weight_int4pack_mm_native.h,sha256=zzeyLnTm-SVLwjo76XijeXR6p0Kos6tLtudEKLt2ZrA,828 +torch/include/ATen/ops/_weight_int4pack_mm_ops.h,sha256=9gMEf6DWByJoj2Ig2k8bYDgeXeX9MabhviaTykwwGHY,1511 +torch/include/ATen/ops/_weight_int4pack_mm_with_scales_and_zeros.h,sha256=J6Zbv4lrP2njY1W7JrVFAkw9Lc8ihp720tjgkUc7wC8,1223 +torch/include/ATen/ops/_weight_int4pack_mm_with_scales_and_zeros_native.h,sha256=0SAoE4aPf5nZIVqujS9jFASmof4GFAJst2Lcyq_eobA,676 +torch/include/ATen/ops/_weight_int4pack_mm_with_scales_and_zeros_ops.h,sha256=ZM2T5f15r7-ZOq090mOZBErf2FvBmym0qEv9w0h-Y_U,1642 +torch/include/ATen/ops/_weight_int8pack_mm.h,sha256=ANwF-STyZXSbLgt0vmXCBGkjb7aIUHtryjP7JK7Adjg,1037 +torch/include/ATen/ops/_weight_int8pack_mm_cpu_dispatch.h,sha256=faxXveYKBUFxP8qpcOPRaIneL_gWFgDa1z9rae5FAyk,1039 +torch/include/ATen/ops/_weight_int8pack_mm_cuda_dispatch.h,sha256=LeE0AoQYkbCt1JNp5Xf3FupaDETMQ7l8Ka_9LArA-BI,1041 +torch/include/ATen/ops/_weight_int8pack_mm_native.h,sha256=Mb0vQ-eedFjP67QVoXtXHhTm3ZFj0bSlqOfgNxNLuG8,923 +torch/include/ATen/ops/_weight_int8pack_mm_ops.h,sha256=txoGYIYKRfBf2DNsW2hdJqx6JqcMlzNjh35kat3hf2o,1422 +torch/include/ATen/ops/_weight_norm.h,sha256=53Igt22qD3j3vJeRsVrCpxiIZlFbperaR7czMYPssMs,972 +torch/include/ATen/ops/_weight_norm_compositeimplicitautograd_dispatch.h,sha256=EVdypz618yzvtYHohBCqJE2OlxVPuGSRyrJ-nsTrS6g,1058 +torch/include/ATen/ops/_weight_norm_differentiable_backward.h,sha256=a9yqCBnDttIWMYdaIBPWnwpywN3s6mUbWvGOT2NEryk,1250 +torch/include/ATen/ops/_weight_norm_differentiable_backward_compositeimplicitautograd_dispatch.h,sha256=BiIwoIpFNwoeHMOJPEzkLR1ri5MCg9eNI7jAq1jfzX4,1176 +torch/include/ATen/ops/_weight_norm_differentiable_backward_native.h,sha256=mueSgaJg2vLKmTHMv9FSZFIwH34pOh5YgyGxEQFmEQo,888 +torch/include/ATen/ops/_weight_norm_differentiable_backward_ops.h,sha256=qqGc2wqeuT1u3ftQBdze5Ko07UmJt9JKqULbYF9Hs5o,1724 +torch/include/ATen/ops/_weight_norm_interface.h,sha256=Q-7cHN7MqPwEtti8gWDpYBpHu9g-HiWqUyBmnhHtFhk,1817 +torch/include/ATen/ops/_weight_norm_interface_backward.h,sha256=3w5avTEfb0RWLOa2qstBuIMvi3X3P1zEb501hKaEJr8,2350 +torch/include/ATen/ops/_weight_norm_interface_backward_compositeexplicitautograd_dispatch.h,sha256=d5D5t0o1-dt4GhMzM-jx0gxnck6nbNJjWRpeSSs3Uzg,1471 +torch/include/ATen/ops/_weight_norm_interface_backward_cpu_dispatch.h,sha256=-l5pfXMZyBR-Yi-ipEv5cXkoeMclTRj-x3WGdy2KQuM,1127 +torch/include/ATen/ops/_weight_norm_interface_backward_cuda_dispatch.h,sha256=C3pxxD-DNIeMfMhLAYpG7J4xnSutPHkvM6ec-vUx924,1129 +torch/include/ATen/ops/_weight_norm_interface_backward_native.h,sha256=jaHptF8p7gC9RuuIfOYVoEro6iX-5iJnQYYP8YpWdWo,1330 +torch/include/ATen/ops/_weight_norm_interface_backward_ops.h,sha256=YXsymQ-zpFhpT9xk1hpM2xjumvYoe--TtT7PkmRKbok,2879 +torch/include/ATen/ops/_weight_norm_interface_compositeexplicitautograd_dispatch.h,sha256=x-gifq-hW3-GI-MZUJswEn19VEKcgzVaaK2rOLSUTzg,1313 +torch/include/ATen/ops/_weight_norm_interface_cpu_dispatch.h,sha256=_4qkNcvXOOjgV8kPfndwpkQZsDa_B9UsJpmy8cDB1o4,1049 +torch/include/ATen/ops/_weight_norm_interface_cuda_dispatch.h,sha256=hGm-oFnLcqherEvgsxkp-pjs_PAy-UTri8M07oVALeo,1051 +torch/include/ATen/ops/_weight_norm_interface_native.h,sha256=jWUabmzr8wmyFCdwYst9umGl6KtmQ0oOK_Z3jEagzTo,1094 +torch/include/ATen/ops/_weight_norm_interface_ops.h,sha256=alXGbBsVF2vnMqwIJrPX8D6xrojG3ALVrpdW4haOjuo,2371 +torch/include/ATen/ops/_weight_norm_native.h,sha256=6BGgUKA-xq2m-mMd6ExG4STPlCTk7TpSwOSEWwAxT18,770 +torch/include/ATen/ops/_weight_norm_ops.h,sha256=db1Y0FTDHTNULHav8b3IWpUhQoyYQTJtB4UaDqwIKhg,1340 +torch/include/ATen/ops/_wrapped_linear_prepack.h,sha256=JjNAgMROK2W7Qkr_IGUZQWmaBP-KLXBzaiONj7_ycxs,1160 +torch/include/ATen/ops/_wrapped_linear_prepack_compositeimplicitautograd_dispatch.h,sha256=rpHde5mnq6ksUC6ZRTEyT5uDPDDBpMSjT7_lv2dC_Us,1133 +torch/include/ATen/ops/_wrapped_linear_prepack_native.h,sha256=Ch7JDo7iqRnV0pX-Bzmq1pyLwXUKJ6lmQ1F5mp7h56o,845 +torch/include/ATen/ops/_wrapped_linear_prepack_ops.h,sha256=eBuyNNMhjQwZbFRtYmHmCkGpRDWh2sYe1LWp-UCPFzo,1580 +torch/include/ATen/ops/_wrapped_quantized_linear_prepacked.h,sha256=53a_dA5maOraTx47ZtLHBs-St7Ur3bZokrUSSTLrh3Q,1428 +torch/include/ATen/ops/_wrapped_quantized_linear_prepacked_compositeimplicitautograd_dispatch.h,sha256=gCB1ZGWw48KsWTdoBhjz6DSQKbsyQejH5p4aHuYsuu8,1243 +torch/include/ATen/ops/_wrapped_quantized_linear_prepacked_native.h,sha256=inuj7a2dL8DF3pmNozXomSTy3UQE97mXAFMWidu-se4,955 +torch/include/ATen/ops/_wrapped_quantized_linear_prepacked_ops.h,sha256=NEwrsYRTuJ_41uiIf4u1eor20BKTEp_c1_OZs9I4q6U,1931 +torch/include/ATen/ops/abs.h,sha256=VXFWROeF1b0aR89jjuqNJyWSNyzJnUb5JZAlsqS8oxU,1384 +torch/include/ATen/ops/abs_compositeexplicitautograd_dispatch.h,sha256=u6L9CwtSRZRzdS0_c790fSGbDXtENGMgGsE_rlYnQb4,1063 +torch/include/ATen/ops/abs_cpu_dispatch.h,sha256=RmBoDt2pf_ZcrjtiDibUtue7LckDTWp98829UkSK3ns,1071 +torch/include/ATen/ops/abs_cuda_dispatch.h,sha256=slcECZpytQQvdRamusQOZzoBvjZ56olHX8gqorrQON4,1073 +torch/include/ATen/ops/abs_native.h,sha256=S94QPOwCbKpx8-4VSnKs8OOfitkXbV6mulYerIYthOk,1377 +torch/include/ATen/ops/abs_ops.h,sha256=dpwWlKCtkJjwVFLldthcEVScXEOeZHLyIQtjqpZtJkY,2273 +torch/include/ATen/ops/absolute.h,sha256=q2xeb2HznUk2cnzOUXLXMhALhiEJ8CrDZR3er0pLvxs,1301 +torch/include/ATen/ops/absolute_compositeimplicitautograd_dispatch.h,sha256=gavmbjy7CJUy6Tv0EoL0734v59nz6zQTP76qTc2LudQ,1234 +torch/include/ATen/ops/absolute_native.h,sha256=4BnamnLyV9FNQnkwMfKYCmScXFpaPb4PKBx7zUGVAkE,865 +torch/include/ATen/ops/absolute_ops.h,sha256=tr6kE0CsXtkedRNoX_aGbeFrRSVSNZQjLZIu3pEiGqY,2318 +torch/include/ATen/ops/acos.h,sha256=SKpJhnPpujmVHi1iJ8KgEI5f9SoHiogDcq06Dn_NQYo,1397 +torch/include/ATen/ops/acos_compositeexplicitautogradnonfunctional_dispatch.h,sha256=M-Fc06_5nf9VQr_jpO3OXp-xwLypFGBrSoCLogCDrTs,1091 +torch/include/ATen/ops/acos_cpu_dispatch.h,sha256=JCidOgttCzsb0OsfTZyxeRpPy4wsUZ4crLs8ya4hQ84,1174 +torch/include/ATen/ops/acos_cuda_dispatch.h,sha256=Z7NDPlrOc_7fN0G2W0k0pmsWoHz5hDhqMiSZWS5DsLc,1176 +torch/include/ATen/ops/acos_meta.h,sha256=Fxbx8TWXXStWsWioRtg8As5GSOuLHtrc7WBAka3NPB8,819 +torch/include/ATen/ops/acos_meta_dispatch.h,sha256=A9w0xY-3Fx7VKf4ZoOkiaaUQuQ72f1W7S9v0jRftezI,1176 +torch/include/ATen/ops/acos_native.h,sha256=7VpMi1YjhJ_Terwk7Ozi6rGD15Bpp1kR2R7OUPik8I8,844 +torch/include/ATen/ops/acos_ops.h,sha256=P64P2WrWDRjw_e3qz1PyU7g3B_PUBAjn0kQdADkLf-o,2282 +torch/include/ATen/ops/acosh.h,sha256=EX0TixTnxegkFnOGVG4Mjr5FJBkVpDHeGBuJai9KIXw,1410 +torch/include/ATen/ops/acosh_compositeexplicitautogradnonfunctional_dispatch.h,sha256=zRKBMgPIxXPdf9oeMtxk05VxLI-QohO6Z67VRqk-UMY,1093 +torch/include/ATen/ops/acosh_cpu_dispatch.h,sha256=BSsz3pCVkbC6NQ3PgGYFoYX_2umRiNqAI4M9n1yYStQ,1178 +torch/include/ATen/ops/acosh_cuda_dispatch.h,sha256=HhiwzW9WovfcXxFCFD9wrTiP-0dXlxCigU4I2RJVPlo,1180 +torch/include/ATen/ops/acosh_meta.h,sha256=MnBmRufU_rF0A3deLJM88POAlsF4z_JhKMuDBiYVnek,820 +torch/include/ATen/ops/acosh_meta_dispatch.h,sha256=y1V6AsJD6J6BedlPJWSlkiL2Oin6szguVi95nfrLZAw,1180 +torch/include/ATen/ops/acosh_native.h,sha256=hEINhUyNBvZhIviefJ6HMI2TcxEsd4sRQmu2vLeRLKY,847 +torch/include/ATen/ops/acosh_ops.h,sha256=KcQtwP5odYPQ4jrNejm01e9EiYXmR5UN7upRvqB0zK4,2291 +torch/include/ATen/ops/adaptive_avg_pool1d.h,sha256=cvsqAqTtZ40owD4ztXLtC6ABdzkHkDTNvb53QTSUJNs,1597 +torch/include/ATen/ops/adaptive_avg_pool1d_compositeexplicitautograd_dispatch.h,sha256=wdimpWVjiyPUmC_x7svgZwIJGpCJurjbBOZn5dTyXIM,1205 +torch/include/ATen/ops/adaptive_avg_pool1d_compositeimplicitautograd_dispatch.h,sha256=TMUh3JrcxOCWurevgh_SOltOCLlDATQznB0i3qee6E8,1060 +torch/include/ATen/ops/adaptive_avg_pool1d_native.h,sha256=bVW8pIThIaO_ztDhjqKlt1KWiwljT5g9rp-JxKlzO0M,892 +torch/include/ATen/ops/adaptive_avg_pool1d_ops.h,sha256=TabCm5eD_1CLwISDZW6ZfS2uCvqrQmw1UcmV04Sxqj4,2069 +torch/include/ATen/ops/adaptive_avg_pool2d.h,sha256=vYkvJHL1O-psigyoX4Ir6lJcPGnmsZN6Pr-vmz2OUKs,4364 +torch/include/ATen/ops/adaptive_avg_pool2d_compositeimplicitautograd_dispatch.h,sha256=_iB9nsHDQLelULrwxKstVF3Ymt4ODy2BbnxGdG8VE9A,1167 +torch/include/ATen/ops/adaptive_avg_pool2d_cpu_dispatch.h,sha256=riHjvmY7FcYlICc2G8qKU-sDQxvDk1eZemC9uu0C-Qw,1424 +torch/include/ATen/ops/adaptive_avg_pool2d_cuda_dispatch.h,sha256=FySDy4KR6dR0LWAYqVxj2irJCXdcp-zQiXYl1nNo_ZU,1426 +torch/include/ATen/ops/adaptive_avg_pool2d_native.h,sha256=dmjqNiS0zu2YJZ8R_td-SNgxsezNOL-7ctKmvuCmO_I,1164 +torch/include/ATen/ops/adaptive_avg_pool2d_ops.h,sha256=hONaDBIPqUT0goP3QsLrcJJGydx-xDGuc22NNUQ6SCE,2099 +torch/include/ATen/ops/adaptive_avg_pool3d.h,sha256=vQGmOt4e0xO65j1tdX2KGcOnNh10fg1QgKCqu3LOcR0,4364 +torch/include/ATen/ops/adaptive_avg_pool3d_backward.h,sha256=kGBO5I4IU6XB-W4vxWIRKwlavAZaPH6Nrag7BmdAvqY,1500 +torch/include/ATen/ops/adaptive_avg_pool3d_backward_cpu_dispatch.h,sha256=crqhUCUQ0tf9lsX27HkFtxNMBsKaqCvq_EpzXmqGv-k,1199 +torch/include/ATen/ops/adaptive_avg_pool3d_backward_cuda_dispatch.h,sha256=2NRZ9pY3aRj0-c7PizQweWOJ1eLvR0RH4o23XpEZBGQ,1201 +torch/include/ATen/ops/adaptive_avg_pool3d_backward_native.h,sha256=lPeOAGo5WFgDzkcfTEcuWqUEGviiJdQFKVeE1NEo9hs,963 +torch/include/ATen/ops/adaptive_avg_pool3d_backward_ops.h,sha256=7o-jdsz-2aZOk6k4G-tYJ_BRALs3B71SkLpdiacSvTs,1513 +torch/include/ATen/ops/adaptive_avg_pool3d_compositeimplicitautograd_dispatch.h,sha256=29Uyj16XTh4IwPFrPq2NSBRg8IG9cszYK9yeV67ocjU,1167 +torch/include/ATen/ops/adaptive_avg_pool3d_cpu_dispatch.h,sha256=tECjefOtr6qP2_4V8HlafzZVB4lS6V34BOjp4V9u9N0,1424 +torch/include/ATen/ops/adaptive_avg_pool3d_cuda_dispatch.h,sha256=uaEyHDUA4sYOflg37tVYk9AcJ9KvWLd3chP_oBJfO1A,1426 +torch/include/ATen/ops/adaptive_avg_pool3d_native.h,sha256=4-iFS6x1dsVC9lUN6z7es7Vo0GbBlYSHRAMpbvMN2R4,1166 +torch/include/ATen/ops/adaptive_avg_pool3d_ops.h,sha256=XdGoF4Ed5SCSzDhol6XP1uwdl8KUZZUx4jA6ggXDcqA,2099 +torch/include/ATen/ops/adaptive_max_pool1d.h,sha256=-0nUlAjaMhmDW-8jJpDB6cf9p6vyrhjx58xawtfU43U,1040 +torch/include/ATen/ops/adaptive_max_pool1d_compositeimplicitautograd_dispatch.h,sha256=PIEUSJlaiP2HPbXk1qSqzv8j577spTaGT8Pz7WbWG0Q,1085 +torch/include/ATen/ops/adaptive_max_pool1d_native.h,sha256=v_03nADvw8uSvoQCSX-gw4ltLXjtJZA1uk0yMGyR9mE,797 +torch/include/ATen/ops/adaptive_max_pool1d_ops.h,sha256=FIsp8cU6UcWzRINYPbIFJvfWejjb-9oaPRFrlvW7M0c,1430 +torch/include/ATen/ops/adaptive_max_pool2d.h,sha256=DiqjLsIJP2Sm1WmHm5OGkLz0IecNxWJSMHCTQiIh0y8,1816 +torch/include/ATen/ops/adaptive_max_pool2d_backward.h,sha256=PiQpByD_7uKpDggvX--9GtypF0eHpNOmEC-BEcnnV5o,1925 +torch/include/ATen/ops/adaptive_max_pool2d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=02oRBkplBUc9eEdS5j-h0juQzUNdS_J01mddjEs818g,1126 +torch/include/ATen/ops/adaptive_max_pool2d_backward_cpu_dispatch.h,sha256=tqLtKqYZlr-6p6WjqW46Dt_arVQl_U6zPGwE1zSvZ0g,1391 +torch/include/ATen/ops/adaptive_max_pool2d_backward_cuda_dispatch.h,sha256=3moJIuUczYODEL_Qcps0EB28xisuG0nwPAI5miNEQc4,1393 +torch/include/ATen/ops/adaptive_max_pool2d_backward_meta.h,sha256=3DADcZ9jFtPW7FQ_gcHg1baAi8wdMy7ZwqAwZ3mzEkw,903 +torch/include/ATen/ops/adaptive_max_pool2d_backward_meta_dispatch.h,sha256=tEVGBbPrA0EAWhvd3ffFfsngrmNkCHMBBRwrHzDRrdM,1393 +torch/include/ATen/ops/adaptive_max_pool2d_backward_native.h,sha256=LUJYEPD6xlYduE-N7s0qBWsy1KR00S5dpTKcwPpYcu0,1244 +torch/include/ATen/ops/adaptive_max_pool2d_backward_ops.h,sha256=mSmZWYiPjdV_GdOkfpzMTezz2pLHzPizO3DlxIHCVdI,2367 +torch/include/ATen/ops/adaptive_max_pool2d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=k-1oMt7cse1IXiRnJ9KLPJBlRPigDdjplHljnU4kYqU,1111 +torch/include/ATen/ops/adaptive_max_pool2d_cpu_dispatch.h,sha256=DXINe5KXCxRT-x7fDSshhcNxdrkgjzr4il3-L9Mwdyg,1380 +torch/include/ATen/ops/adaptive_max_pool2d_cuda_dispatch.h,sha256=yBpiXu_emEYAnhpdn9yNO-3Hdme2iJIOIfwtfT8VZdQ,1382 +torch/include/ATen/ops/adaptive_max_pool2d_meta.h,sha256=9JRYrYuvXxUtNN4tFkBDE8zsKV7Nl6KTqdZDEj7K6SM,863 +torch/include/ATen/ops/adaptive_max_pool2d_meta_dispatch.h,sha256=yhk7E9WvMoedpFCOZ4xM0oUDLDsUIHIQn3wv4yucfdo,1382 +torch/include/ATen/ops/adaptive_max_pool2d_native.h,sha256=k5cP57Q1tt01OqRHiAxFt0EaC_JKImrSDeLHo-mtCdQ,1179 +torch/include/ATen/ops/adaptive_max_pool2d_ops.h,sha256=LbM5aT7NC94rDKKsMuRi7NXGs_7aDT2okScHfZfXY6o,2327 +torch/include/ATen/ops/adaptive_max_pool3d.h,sha256=Hoeb545SJ6Uc8yaV11NvBaNUBX377iyuJwlfhFv_7TY,1816 +torch/include/ATen/ops/adaptive_max_pool3d_backward.h,sha256=3h2u6Az-qQ26JJ-2OINMhyWx0vglIIK-pjtJxGx850E,1925 +torch/include/ATen/ops/adaptive_max_pool3d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=kk3oXJyrZ7JmF3G8Y5BxJ7bffPijQNzyMFfsCjeBelY,1126 +torch/include/ATen/ops/adaptive_max_pool3d_backward_cpu_dispatch.h,sha256=UFXGqbwSgFOxRQVX2vFQLNx6ea_DvBEgbYqQ9T1nSus,1391 +torch/include/ATen/ops/adaptive_max_pool3d_backward_cuda_dispatch.h,sha256=ulInN7kRNb-B-HPP2ksr8_cro7zMj_fa-r0tzC3kaxk,1393 +torch/include/ATen/ops/adaptive_max_pool3d_backward_meta.h,sha256=7gBriWeTokAlpa21zWII6FMSD9dHOQIA9TY2B5XI180,903 +torch/include/ATen/ops/adaptive_max_pool3d_backward_meta_dispatch.h,sha256=cTBBNkqu42TwIcacV2Y0BlDg1cVgxSUX-UCCsgt7mK0,1393 +torch/include/ATen/ops/adaptive_max_pool3d_backward_native.h,sha256=irD9zifg2Fdlte7xCUDj-BmhHsejs4EljVeHdaafxWU,1244 +torch/include/ATen/ops/adaptive_max_pool3d_backward_ops.h,sha256=euHKvHjqqo0rLIznV7Em3VyzpBQyKkuSZJh7VYR1MmA,2367 +torch/include/ATen/ops/adaptive_max_pool3d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=k8Qg5NkGA1UWpJOjTcUznOLF8BocpL6OIC1kJEXQqEw,1111 +torch/include/ATen/ops/adaptive_max_pool3d_cpu_dispatch.h,sha256=u71JjIEhqWKqMuMJcS3FLtqL9vrIaAs75BLRbJ2TGd4,1380 +torch/include/ATen/ops/adaptive_max_pool3d_cuda_dispatch.h,sha256=_5eSr9wwtG341WSKVqGf6l4PkTmXUXe8v9ZAYg-T9FE,1382 +torch/include/ATen/ops/adaptive_max_pool3d_meta.h,sha256=q46EVVKttpu6Qyof7xlg3Py6vn7Tp5QOh11oZozy-0A,863 +torch/include/ATen/ops/adaptive_max_pool3d_meta_dispatch.h,sha256=MGRsJ_ions_nZXwhfjkcd6xeMqwVPMa41eLko-rfwYs,1382 +torch/include/ATen/ops/adaptive_max_pool3d_native.h,sha256=ML41yts1pIlfeq7LjmrDj4YIQtZzD6Uv_srUMiuZ3bI,1179 +torch/include/ATen/ops/adaptive_max_pool3d_ops.h,sha256=tGRlbBitSgWSrWl4J--_O3yb-Hv1BFCY6IaGCCsKf2o,2327 +torch/include/ATen/ops/add.h,sha256=m6lrA7B-rSG51Io7oG5_ewnfC1aBLFkCgFU1_4dFE3w,2392 +torch/include/ATen/ops/add_compositeexplicitautograd_dispatch.h,sha256=D03vfZ9tGlCEE4nkGdALemm9hU9Au0nppYI0OAhbIbs,1428 +torch/include/ATen/ops/add_compositeexplicitautogradnonfunctional_dispatch.h,sha256=-75RV2Oijnk1s42Hlx-A3JXJCvw2MW3F294vw9cqo2g,1197 +torch/include/ATen/ops/add_cpu_dispatch.h,sha256=Q9exi82uR6zlensj46mqIWfbZCslgKKm3u52lwys0p8,1384 +torch/include/ATen/ops/add_cuda_dispatch.h,sha256=CghG0_M5za1UyzcdMz0xzQCxfS-eNs2R5i8GRNZnnok,1386 +torch/include/ATen/ops/add_meta.h,sha256=6ezeJtIKFAdP-GOBpTAzxHUGGMbSZyDziwlfUtlkWd0,877 +torch/include/ATen/ops/add_meta_dispatch.h,sha256=XsCV2u0nuzkf-emhWiMxI-FgQf-oenCWcYG4U9sm8GM,1386 +torch/include/ATen/ops/add_native.h,sha256=-3Gfdb9dKvIeQSJhiuoJqZE-Otuxgj6UODoim2rXU0Y,3192 +torch/include/ATen/ops/add_ops.h,sha256=uhVYiPvpY3UOEiy7L5RcWXDTg6iDIdaQ7VDj5p098Ow,4986 +torch/include/ATen/ops/addbmm.h,sha256=YpB0pzkc5Kf1QsFE3WgTzxs0Dw1jwrhAjpFEQC_q1Vo,1877 +torch/include/ATen/ops/addbmm_cpu_dispatch.h,sha256=ii329H4Wgj75g1Mls-ibCF2RYJoK026mPulo4PQsRZo,1614 +torch/include/ATen/ops/addbmm_cuda_dispatch.h,sha256=B3jfKpPKNkEp0Sqy6v82AFcRmM7ZJ70Ko1WC1ClzGPM,1616 +torch/include/ATen/ops/addbmm_meta_dispatch.h,sha256=pgTGN84OfzusKgeTOEPUWUNn1GNd_cie5aYwTZ1U0RU,1082 +torch/include/ATen/ops/addbmm_native.h,sha256=vf3QakRHDJ-bLAi_aTQi8vLear21WvoOMuir5mdRp30,1182 +torch/include/ATen/ops/addbmm_ops.h,sha256=GoyU1hlrfdLEPZNWZ_zuBek8g_OpzGcFEL9aRg9mPTs,3359 +torch/include/ATen/ops/addcdiv.h,sha256=t1U1iGjBm28GpDL8V9A24UtbXEEjl_BGFDNsb8Py4yA,1763 +torch/include/ATen/ops/addcdiv_compositeexplicitautogradnonfunctional_dispatch.h,sha256=0kYJpDH1sM06As6VjjhAJnMHX9SNfDV7ktYkNuIoEPY,1265 +torch/include/ATen/ops/addcdiv_cpu_dispatch.h,sha256=ckKtNft32z9OhHOwC8CbMgcQXz2JVyS7V3cvEaVqgLM,1520 +torch/include/ATen/ops/addcdiv_cuda_dispatch.h,sha256=U_BZgItyHrVbYYqaVaeepNMfRYGadNQ5bsTnuEttLeo,1522 +torch/include/ATen/ops/addcdiv_meta.h,sha256=M1U0yXPKvh6GmvmVZdR66gr3JlZudAnAUPJy3i7v-aQ,904 +torch/include/ATen/ops/addcdiv_meta_dispatch.h,sha256=xob8iHLMv6Byfcd-1QiECDW_QVXf-H4JWX_c4-VRgsQ,1522 +torch/include/ATen/ops/addcdiv_native.h,sha256=ciBlAlh3nJgu9kk-hJCu8tUjO5pu1ttKXtitnBo62Uk,935 +torch/include/ATen/ops/addcdiv_ops.h,sha256=3lU7IxvAddBY5j4U07glO6C1eisnnrHFkR7m3_p0BFU,3131 +torch/include/ATen/ops/addcmul.h,sha256=d6yA0MFFrCTnUQAE2cNdgLiI-tVKSm2uWfT0jssBzk4,1763 +torch/include/ATen/ops/addcmul_compositeexplicitautogradnonfunctional_dispatch.h,sha256=nPohaadyYLB8gTbpFwHWOsldaKht-G4NDuksGQW0qOc,1265 +torch/include/ATen/ops/addcmul_cpu_dispatch.h,sha256=9lbRsf9NnypuUx2ANm4AOdlhWYutQZczs_JckYPK2x4,1520 +torch/include/ATen/ops/addcmul_cuda_dispatch.h,sha256=yoHtIwKQ2X_W0NR5vIkzDDIyJQBiAUgtRoW1_z11_h0,1522 +torch/include/ATen/ops/addcmul_meta.h,sha256=4dkSP08fKvzhfnbDkfHUiD_ALxoeWCkIhDb6SDMKM18,904 +torch/include/ATen/ops/addcmul_meta_dispatch.h,sha256=DxXVOvhZtAvjnSOckDnltKHW-6li068UyqlvsXDgA4E,1522 +torch/include/ATen/ops/addcmul_native.h,sha256=B0l0RAVuKH25aZCMwMs4U5lgdwKvGsNeUbl8-ictIR0,935 +torch/include/ATen/ops/addcmul_ops.h,sha256=_SHuJnwpd2P8EBoYAVGUw1O1H8_WKQiclKOUp_osUFA,3131 +torch/include/ATen/ops/addmm.h,sha256=-o4XEvaGbcMOUVC3fYmNtzRbpuenK_BozOSu3PxuW1U,3120 +torch/include/ATen/ops/addmm_compositeexplicitautogradnonfunctional_dispatch.h,sha256=pTq70OPuEuU2y-2EKy9itDkiamtnIcJXpldE-cSq7Cg,1303 +torch/include/ATen/ops/addmm_cpu_dispatch.h,sha256=XcQ2YnhQ30RBEWx1aBAh41Lb_3SV9j9uhiyayjpXZsk,1594 +torch/include/ATen/ops/addmm_cuda_dispatch.h,sha256=Hwi-qjy0MF__LENK4XIzryX-LY4vmJAWoNtG3A1dX6U,2193 +torch/include/ATen/ops/addmm_meta.h,sha256=yROoxshtWW22uqJlz3fvkp6jg3BBMl8J0OJs68DyrV8,921 +torch/include/ATen/ops/addmm_meta_dispatch.h,sha256=-ZMxQ-JE76mSB7gDQYhIu5Du3m0H0fqAy0jolBsLTj4,1596 +torch/include/ATen/ops/addmm_native.h,sha256=vs-YcOXmXcStBbkisyf_efeJpB1M2xlcsRjA-re5z-0,3283 +torch/include/ATen/ops/addmm_ops.h,sha256=qdE3qyCMnWHrwvO8NzKjjO8pw5erGAvLL26ekb-oZjU,5294 +torch/include/ATen/ops/addmv.h,sha256=3nzVDqeH7GXa-NnDQkx_vHNOs2b4WuYsdjBqmVJQ7Eg,2136 +torch/include/ATen/ops/addmv_compositeexplicitautogradnonfunctional_dispatch.h,sha256=T3ypXKUu0OQprtEXQcG35Bw-iAzOeR29MX3m6g4Yeis,1299 +torch/include/ATen/ops/addmv_cpu_dispatch.h,sha256=VZ35EDvsSpxLG1k6Y8mFtPYc7ISEVPKriZQ7vUwBIC8,1586 +torch/include/ATen/ops/addmv_cuda_dispatch.h,sha256=pqfco4hy60f_7EfoHTJUfPeRG6iVjCkXFc4Evpklxlc,1588 +torch/include/ATen/ops/addmv_meta.h,sha256=cYVBtR_dkXbUJi3dZHqEO8VVBv2j27bOpujSmhcR8bc,919 +torch/include/ATen/ops/addmv_meta_dispatch.h,sha256=uZMhLPU3Vy8NPsDA0n6hwQxKIkp4npvjjA1h9D_pxgk,1588 +torch/include/ATen/ops/addmv_native.h,sha256=okfZBptq9X2rQEZKhgoXF3mcoWUq0qwQ3ERStbCa3Ag,1586 +torch/include/ATen/ops/addmv_ops.h,sha256=an0RD3s7ZFVaeySL_Ec0l-ihYH2yYYe6XtjH1rz3pSc,3296 +torch/include/ATen/ops/addr.h,sha256=dEn7LHRNJGIVldThT92l4K2TAxKn6vVBkS1_3qN6KL8,1821 +torch/include/ATen/ops/addr_compositeexplicitautograd_dispatch.h,sha256=P0K5QJPwOkuCZAUsKQXCUXEWStMRUu0AoDQYVKjalUg,1634 +torch/include/ATen/ops/addr_cpu_dispatch.h,sha256=7HaSSdqfzjDzt_T3xHvNPTSbnBRjl6GKl-_YBrOV3Io,1436 +torch/include/ATen/ops/addr_cuda_dispatch.h,sha256=PFOzyufX3Vavp9-R49R1d_Z99qP_0lBQOm4z8cd2Yek,1438 +torch/include/ATen/ops/addr_native.h,sha256=YqPn6BzOANF1u-djnS2VITqI_oAtUUhMqbN3idzP31I,1508 +torch/include/ATen/ops/addr_ops.h,sha256=QjiEGQos_q_JBj9ZnX70RfcwqqFen_BaCnKPUDL0gaM,3305 +torch/include/ATen/ops/adjoint.h,sha256=F4s5cN51xoXVAZySno7UItx-OTulfrZJIghCx_mZ97Y,901 +torch/include/ATen/ops/adjoint_compositeimplicitautograd_dispatch.h,sha256=vOv3srLAcfcrhWeXgTJ6fXg-kxIPqf7ZgbWejFdS034,1019 +torch/include/ATen/ops/adjoint_native.h,sha256=iTV4PJEUIZ8tECa8n9uownsHvZv_ncuFC8Kbp4j-smc,731 +torch/include/ATen/ops/adjoint_ops.h,sha256=iECvks7drZWCFkU7gMQUkXgZYeimSaCn_rST02Hkh9o,1220 +torch/include/ATen/ops/affine_grid_generator.h,sha256=8rQXkwWs772jDr86bPgLP5KFHabnJ17K10PEsomFOMA,4780 +torch/include/ATen/ops/affine_grid_generator_backward.h,sha256=MQV2eisa_JgMsrrEiwjB-L30h1ae0hYFUajcScZsnDw,2071 +torch/include/ATen/ops/affine_grid_generator_backward_compositeimplicitautograd_dispatch.h,sha256=4aS922-zBlehaRkf2-6AWrXOUz-0Vp9RHOgoF8bMfCE,1215 +torch/include/ATen/ops/affine_grid_generator_backward_native.h,sha256=C1VkRkqkdbms7sTqtq-7P-e1YhxPJZdHDgNITz6nzZg,796 +torch/include/ATen/ops/affine_grid_generator_backward_ops.h,sha256=3yvW_Zy50JcrWZggc7FuuVZUvTPU5Kekv0DRj5Qbk7c,1437 +torch/include/ATen/ops/affine_grid_generator_compositeexplicitautograd_dispatch.h,sha256=TpVik6hkMQWZKeLI5K8gvFXdBUfI9b4rZNUmKB95iUg,1767 +torch/include/ATen/ops/affine_grid_generator_native.h,sha256=gE5EaMMPudhWonJpB3E56HWW9tGqsWixqfwqs98G0aw,935 +torch/include/ATen/ops/affine_grid_generator_ops.h,sha256=WoGEgeJqPsnjgBfU6maVP-JF0ZfECVVkbPVGtphQ8kY,2205 +torch/include/ATen/ops/alias.h,sha256=C3LMBrHP_HTyd1AOfdjTV-1scg7ofP821Id2Kg3Jeyw,893 +torch/include/ATen/ops/alias_compositeexplicitautograd_dispatch.h,sha256=nGzzFW756BOmAxwNfYDAyVWU8x5o-E10KRFVQeqscGc,1017 +torch/include/ATen/ops/alias_copy.h,sha256=5vy0sl19ExUPPGiUBOEPK00khwpGrWFpVZdAh3O1AS0,1321 +torch/include/ATen/ops/alias_copy_compositeexplicitautograd_dispatch.h,sha256=cri_CZ9jyxStuFPaEOx0uRvIfg941j_QZrwWG_UNrA8,1129 +torch/include/ATen/ops/alias_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=9psWzdjcAxS9J7YS7Ovo3XwRqG9_r1QDIm4ZHwHMcbM,1048 +torch/include/ATen/ops/alias_copy_native.h,sha256=OdmggpAqopsw1afrHW4T1duNA3yrlKS0k8WVGmTJZFc,816 +torch/include/ATen/ops/alias_copy_ops.h,sha256=njs9obBY3RTj2MBiVLuEp_lVGCVaryS0Y-P7LpuY2aI,1825 +torch/include/ATen/ops/alias_native.h,sha256=e1VY3X5nTr-DwVXWC5FBOB0bDBWXPb5EEycaN37n9MA,789 +torch/include/ATen/ops/alias_ops.h,sha256=NYc_8dfK1oLYtC7uzl1HTSoFsJFIdd1EjXDFmhAjjEY,1214 +torch/include/ATen/ops/all.h,sha256=9j4m3Sy4pJxJrXX6zE5J4zQJAyknUKIuThHGe0PK68w,2817 +torch/include/ATen/ops/all_compositeexplicitautograd_dispatch.h,sha256=mmbBiM2Zn5e1VPEby000TDr3kAHlXskmwYoIGij1P6I,1307 +torch/include/ATen/ops/all_compositeexplicitautogradnonfunctional_dispatch.h,sha256=5nlH9Qbc_MKWl2lGEcNmR6tP2b95ePZ31QKWDc7-8e8,1225 +torch/include/ATen/ops/all_cpu_dispatch.h,sha256=K2NbhOus9oXaAOUqXuvuiqp6jcHm3HR0h9iAnfLsMyA,1760 +torch/include/ATen/ops/all_cuda_dispatch.h,sha256=_XYF8bg24XGb1XozeaZ98VitehNLIK4oMQ436Ww5Xbo,1762 +torch/include/ATen/ops/all_meta.h,sha256=tfRrW8h6Too1ySoip6viegLP981E_miX23dHTx0ve28,1111 +torch/include/ATen/ops/all_meta_dispatch.h,sha256=JNgmdwnAbTf4tFuJjJfrZKm3jszdsrw1lCVSFS0yZec,1762 +torch/include/ATen/ops/all_native.h,sha256=RNnb5lsJ30bDy90Py7mvaMzuCxrCKrgU6XtOq-7W9eE,1555 +torch/include/ATen/ops/all_ops.h,sha256=o_J-7ibCFfEGq7YC0wyKD0Ewv-vBT1G1ARQzwzqDFow,4483 +torch/include/ATen/ops/allclose.h,sha256=HnudG9IsIjn4-Rr0MO_hA4JfKw34snPxpvCy8Dlwt2o,1079 +torch/include/ATen/ops/allclose_compositeexplicitautograd_dispatch.h,sha256=9A3NW8DQFDHQRRwxI3Kg0IyQ1zhOY_iZRfC8JXr7Pgg,1100 +torch/include/ATen/ops/allclose_native.h,sha256=0TQiTzJCl0Di97b54c73YhPcwfT-TfQRid9JkNys3XQ,812 +torch/include/ATen/ops/allclose_ops.h,sha256=n68rqZCqEUG8tA7P36BpP1F0lgbzQsCrYwL6puKJjCg,1447 +torch/include/ATen/ops/alpha_dropout.h,sha256=N4BN3lvZSnWZOmMbGF7_PyQmPqCDxvvbh8vSs-Nz1ew,1191 +torch/include/ATen/ops/alpha_dropout_compositeimplicitautograd_dispatch.h,sha256=5xAG7bhcYGrOWWpNDCxflqmKO3sryvhiQ6Jp_n1T7sc,1128 +torch/include/ATen/ops/alpha_dropout_native.h,sha256=PosbfR95kB-Bn1ikwRDnjRlJjpQjLW6tkPGe9ki-l6M,840 +torch/include/ATen/ops/alpha_dropout_ops.h,sha256=9gk_Nx2RTfTLjXqUYxCabKLdILs16hSkWi2Yp_a9WYs,1913 +torch/include/ATen/ops/amax.h,sha256=WqDBBZstAAC-a32OWFFx_6YrOhs40w6VpK6BIq0CxQU,1531 +torch/include/ATen/ops/amax_compositeexplicitautogradnonfunctional_dispatch.h,sha256=epYea8UhHq6-xL290YLgWWk_pyUgz87Aym0c5HFPhz4,1086 +torch/include/ATen/ops/amax_cpu_dispatch.h,sha256=BTQMNI7KiMPfEpISmuPHGy3qG3XxGiuXhQRECRWWPsA,1248 +torch/include/ATen/ops/amax_cuda_dispatch.h,sha256=D7_kizvYrmC1qyyEU6fv0vRXhnmoyy_5bLH1lfDyLvQ,1250 +torch/include/ATen/ops/amax_meta.h,sha256=-kS1mONJ60VjoruggHXlOmvRGT--FOtrVgfVBi0nlqo,854 +torch/include/ATen/ops/amax_meta_dispatch.h,sha256=ahiWzmV4oILNaQJPgZMQ-E7mB1DS46l--naNxGGszHE,1250 +torch/include/ATen/ops/amax_native.h,sha256=pfyy_S3FTHq1pR5jhsf15c6Gk_jJlShnrUI-XwjTNgI,879 +torch/include/ATen/ops/amax_ops.h,sha256=WbUAGnxlfXCl-NZf9DVwy43WTPRBTkvPriOcKUTnSVQ,2045 +torch/include/ATen/ops/amin.h,sha256=ci0xVbQeMyy0giupqRD1R5MyIjTBUl4IZ8g5SCQqhF0,1531 +torch/include/ATen/ops/amin_compositeexplicitautogradnonfunctional_dispatch.h,sha256=WqXwuPaYDZMkJCM9W96AspBK8PpOrbj895feSVO0XvI,1086 +torch/include/ATen/ops/amin_cpu_dispatch.h,sha256=rVHPbkrq9bFHRHkFjZ0zQDQCHTnzAwuzYdTpFk3ukQ8,1248 +torch/include/ATen/ops/amin_cuda_dispatch.h,sha256=baxW91d_C_P56g7YqexLeyJHapim4YvyVz1qFhb-7oQ,1250 +torch/include/ATen/ops/amin_meta.h,sha256=ZHKQgvQLDtk1CkfpQWYp13MfWTyJtTFfuslxboLJej4,854 +torch/include/ATen/ops/amin_meta_dispatch.h,sha256=5Rd9iLZN05jRS1YT8lwAMZ_cj1foGHkfkwe30AAo0vE,1250 +torch/include/ATen/ops/amin_native.h,sha256=pwtGuBWvIgDPKHZUVMZPAMQZrAFmHS0nTKwr0P-xdG4,879 +torch/include/ATen/ops/amin_ops.h,sha256=rMxfVThw5U8NONM7hfX93GsBJBfyqN84QrB9OE_gPeQ,2045 +torch/include/ATen/ops/aminmax.h,sha256=bQGvNkG0savYjSdImC9eitYWHeLzMMD4OjbrqmRIh-g,1834 +torch/include/ATen/ops/aminmax_compositeexplicitautogradnonfunctional_dispatch.h,sha256=KAR7lCRKROBN5L9yD2T7b-o2OYr_zuunTQrf6MLBJ70,1135 +torch/include/ATen/ops/aminmax_cpu_dispatch.h,sha256=SpKfPBzl44ZC0BAC6RoR8NnHZJ7JR8cfjVjKRZRfZhA,1423 +torch/include/ATen/ops/aminmax_cuda_dispatch.h,sha256=oVDKenyb6eoDfj2-8_b7a-qowJqbcmYFIRjDaYZC6SY,1425 +torch/include/ATen/ops/aminmax_meta.h,sha256=G6d7rD8shu4SYoLNhwV4DG_5i2nNTsHyy4Kbt2UwEeU,866 +torch/include/ATen/ops/aminmax_meta_dispatch.h,sha256=BgMJAQt7Yi686_dG5Zs3KkbXr0UdnEZzIKOiKNc9zy0,1425 +torch/include/ATen/ops/aminmax_native.h,sha256=7IJhFuuP_DjdQyoJ2wHeJ2XG-eIBclTK4O3YjnBj1dg,921 +torch/include/ATen/ops/aminmax_ops.h,sha256=QISYeuZishhhlckBsmrtmYOLszmsrzd5KOXEVtO6o_o,2382 +torch/include/ATen/ops/and.h,sha256=AfdCY8DiDqbF-enw8ZCxtrQC4IVPH8R_Gv3JXBLz8_Y,1151 +torch/include/ATen/ops/and_compositeimplicitautograd_dispatch.h,sha256=5g_sYbFMv32u9xp5FWoc3sT7_-m0L1Z-s6UUL7HnroQ,1282 +torch/include/ATen/ops/and_native.h,sha256=-sX5_rHtYxeNREVIGa7Fl1wXYOKsYyW-CA0LOwnXMmE,994 +torch/include/ATen/ops/and_ops.h,sha256=J3Cr8oBu3R_BNrpnGPESqx55LJOJhOzYdXaXJ8ghzsU,3145 +torch/include/ATen/ops/angle.h,sha256=90wdYFa_q_k42MD_g8ctgyOf6BcfgLC5wyJjxDLYxtI,1271 +torch/include/ATen/ops/angle_cpu_dispatch.h,sha256=bnibbXmwA48hSTJfpselkDimsEj5UlRjL5YrvfBIyJw,1128 +torch/include/ATen/ops/angle_cuda_dispatch.h,sha256=KIM5oQrYRaEzbQ8PHwlQ23xDs2ZDbeliL69SchyjStw,1130 +torch/include/ATen/ops/angle_native.h,sha256=Xuzdky7qeAuYU1TS-aB1L8hvShvV0xw5zL-CBIRQgQg,958 +torch/include/ATen/ops/angle_ops.h,sha256=g80gxwCtt2_jc2y3R9PSMto3QHQVzHEX_0RIxm8XcVU,1795 +torch/include/ATen/ops/any.h,sha256=xQxyrhjWGLjslBRJbGuIjIjSVKIAPbl45e4hsZeXNiE,2817 +torch/include/ATen/ops/any_compositeexplicitautograd_dispatch.h,sha256=SJslF-IN092tN2SYcxQep8zmJWChwoexIAXRRkHEyng,1307 +torch/include/ATen/ops/any_compositeexplicitautogradnonfunctional_dispatch.h,sha256=XcZKZhHKk1oE_QmoqC5gvnQGNCXmKGzD7eXYN_pWAmE,1225 +torch/include/ATen/ops/any_cpu_dispatch.h,sha256=sWT1UNvum9ZQW_QyhyNYxvSCT9JwGZDcR_velMkv8PQ,1760 +torch/include/ATen/ops/any_cuda_dispatch.h,sha256=RWeH9RF17J_I79QNlH9Pi50w-Rdz0Zhij_c8H4ZtOQQ,1762 +torch/include/ATen/ops/any_meta.h,sha256=wlYXdI-imjoS6AUmQ--hgq1uA9ZcKdzH5zKgkddHMuM,1111 +torch/include/ATen/ops/any_meta_dispatch.h,sha256=jQSiHAePU_687iSWqz9WotdfwUzwmVBfMhbm6NazRng,1762 +torch/include/ATen/ops/any_native.h,sha256=Y9djxtWVVrms80H9wD-A7th70XRUfPpgqYHAmDsEFxo,1516 +torch/include/ATen/ops/any_ops.h,sha256=mjbAVTH1aWMd7VYaT4G2j-h9FtDnO-fTJnMZaI04fTI,4483 +torch/include/ATen/ops/arange.h,sha256=ZC56YE4iOmBl6n-ac5x6eGYfeDWHAi9jTlEJ8N1QcqM,4425 +torch/include/ATen/ops/arange_compositeexplicitautograd_dispatch.h,sha256=BXxVE0ecp-tENMd-6TJ2liaRx90s-INb8clb_Pkmk7o,2116 +torch/include/ATen/ops/arange_cpu_dispatch.h,sha256=yftx4XApoiS2TGAtjlfhmlrpomD3pLK1hDD9_9bjTD8,1177 +torch/include/ATen/ops/arange_cuda_dispatch.h,sha256=O2d8hakjkuO08SEZrMmkiw_vHXSLjvbOIvP9G7X9J4s,1179 +torch/include/ATen/ops/arange_meta_dispatch.h,sha256=_WYLjKaJDqjXrA4MIWZ1VFIWRm791JGWY-X011MXXis,1179 +torch/include/ATen/ops/arange_native.h,sha256=AQB_g8uGZ36kn1cPsL3qyf-g7LzO_dlUhOLaJvCr5QY,1723 +torch/include/ATen/ops/arange_ops.h,sha256=mOYjd_YPPA904rmA3RyJjgPriDhogeFFezEo5lwjuqw,5359 +torch/include/ATen/ops/arccos.h,sha256=5Uk3Ps5cTYJOoI1uRfF4vGlfQf-7bexPSi4N-wanxos,1423 +torch/include/ATen/ops/arccos_compositeimplicitautograd_dispatch.h,sha256=20FTmdmQdnBpiD61wcZCla33mPnWhRHtsPBPX1XgoyM,1226 +torch/include/ATen/ops/arccos_native.h,sha256=yErsbOBMKzEgOZKqmt1u_XVGeYpUzYV6JI3xS8zDI6k,859 +torch/include/ATen/ops/arccos_ops.h,sha256=MtwZnA2kMzcF0qVWDGWqTw-xgF7JthGbchWCGR8PgGk,2300 +torch/include/ATen/ops/arccosh.h,sha256=p9En4OL2rdTbXa0tsA5KOuYvKbNBNhoWLC4pDv8Okc4,1436 +torch/include/ATen/ops/arccosh_compositeimplicitautograd_dispatch.h,sha256=ogslVweuObutgL4Pq66k-oWOZzC-oSLmoHaRmpScV5s,1230 +torch/include/ATen/ops/arccosh_native.h,sha256=vfT1T5VA205RoNphHt6a90IhfZ_dYC63Es25p9FeIE4,862 +torch/include/ATen/ops/arccosh_ops.h,sha256=qBgF84vdlKjvlWtKOHbtwJJeqL9WJuv39lLFYGkHbzk,2309 +torch/include/ATen/ops/arcsin.h,sha256=x2yuqImoVOx-osPoQKeprHFPaaVFgff5hO4SdAv6Y3U,1423 +torch/include/ATen/ops/arcsin_compositeimplicitautograd_dispatch.h,sha256=qqSFPhFEf5tpr9-8oFGdNyJohZRbvBf70g9OlDwavoU,1226 +torch/include/ATen/ops/arcsin_native.h,sha256=uMPZE0fDu53Nb6BneOe6tZY1Iue_Andh1TqafqK43RA,859 +torch/include/ATen/ops/arcsin_ops.h,sha256=WPA8_X5cnnxl8dJUkoB4bZtc7c6vroLjMj9L9CA0RtU,2300 +torch/include/ATen/ops/arcsinh.h,sha256=MDyYdl7ux4Z0_2sjMCWaSSj3jX8HhYmGdp_lZT3IpoA,1436 +torch/include/ATen/ops/arcsinh_compositeimplicitautograd_dispatch.h,sha256=vZu0a0jk-yLlFlmKWD9LrHvk1EDh5EDJ1HfSSsa_hho,1230 +torch/include/ATen/ops/arcsinh_native.h,sha256=JhmmU6Kl1vaghGW3C7f37BPIdo-GbvPM-2GQG8XR9qU,862 +torch/include/ATen/ops/arcsinh_ops.h,sha256=2e2tGcaiwr8f1LXAbdvNZtGeP4GFkMyA3xIqdFNiTGE,2309 +torch/include/ATen/ops/arctan.h,sha256=zb-WgJZLEAvPJLFeIdSNjSY90nJac5mr1GiHkNC6z7Q,1423 +torch/include/ATen/ops/arctan2.h,sha256=FYrvrRpCoh2pCPi9CsnlpaL8OdhUzdDRyXvgjvNa5W4,1432 +torch/include/ATen/ops/arctan2_compositeimplicitautograd_dispatch.h,sha256=fypc2XKT61xM0GQ8-dzVUjqfEXrPV_Y6KNfoHJctfVM,1334 +torch/include/ATen/ops/arctan2_native.h,sha256=Kwvcy1iWGYA3VuIx92CLaxyvhvdcVJnc4oHOA7OzdGs,940 +torch/include/ATen/ops/arctan2_ops.h,sha256=LwpOsawft6yiyzY5brvOu1tcervVBFkq5LW3Pmvy5c4,2567 +torch/include/ATen/ops/arctan_compositeimplicitautograd_dispatch.h,sha256=1MALW4LAvSK6hc3RgXlDDWWZF6CN_zAGeabYbAh-W2Y,1226 +torch/include/ATen/ops/arctan_native.h,sha256=IU-c4I1YdT6Iyofe4Jq4TJzSCtMCFHud4Wlgy5301T0,859 +torch/include/ATen/ops/arctan_ops.h,sha256=6La376X5EkAzig226WdvdaOD46s13NdsDdXQgh259u8,2300 +torch/include/ATen/ops/arctanh.h,sha256=nnaFGSuGPTVOMcdIJ5wiFaS_wa8sx5_K353TAvn8D48,1436 +torch/include/ATen/ops/arctanh_compositeimplicitautograd_dispatch.h,sha256=UuImT6ryokuenV8F2mvr1vsm52UKviVbEv6es7wX35w,1230 +torch/include/ATen/ops/arctanh_native.h,sha256=iDY4ajSbtFqagCIGfHWZOpGiLQZjNyOsd9aJsVxF1Jc,862 +torch/include/ATen/ops/arctanh_ops.h,sha256=3C5UrKxlNwi-FnM4P_bUJUC_EVxLp8LzcwuJld-tzEo,2309 +torch/include/ATen/ops/argmax.h,sha256=BOaWkUGCQ52vEFFOgGnphdWc7haL2syExSmeW6xwk0I,1602 +torch/include/ATen/ops/argmax_compositeexplicitautogradnonfunctional_dispatch.h,sha256=_Gy_M1Wd_sCmkTpPo06kWPX0JzcE3Oi1kLE8QMGO3vQ,1109 +torch/include/ATen/ops/argmax_cpu_dispatch.h,sha256=5VQgtrUwgkvLY5nJrTJmHsI6PZVor7PbJ-xmrgJI3TQ,1305 +torch/include/ATen/ops/argmax_cuda_dispatch.h,sha256=BiENtvgFCJ19UW_6hBSjJbaQ9iixl9fgAqHZAttY1Ao,1307 +torch/include/ATen/ops/argmax_meta.h,sha256=ylVsv-yozGfX0-4dvaqNLl6NLeesW78A4oVJVbdZaNY,865 +torch/include/ATen/ops/argmax_meta_dispatch.h,sha256=9LS6-qecZPjCzF0ZR-MLKbrOXSwxvc9LRaYUZo6ZAEg,1307 +torch/include/ATen/ops/argmax_native.h,sha256=i98fmx-73yBjZuats3G2x7tF9NEVlLvtq27HthxjRPg,894 +torch/include/ATen/ops/argmax_ops.h,sha256=WwP7S_xzRIzayYstRW49xEbULtm3at6ZJosHkP-rKDA,2111 +torch/include/ATen/ops/argmin.h,sha256=hWI6tUKRkEXSxpn_gUxSFTsMK7dRlPqdu5eh-KJHKH4,1602 +torch/include/ATen/ops/argmin_compositeexplicitautogradnonfunctional_dispatch.h,sha256=OErO2xFMI74nlrcYGv6TypvHuSrqmklo6Aq9ugaQK_A,1109 +torch/include/ATen/ops/argmin_cpu_dispatch.h,sha256=yIM31vEpJ-sPDyBMFN_6XAHTG2nM2EBJrAbwVHz4uIU,1305 +torch/include/ATen/ops/argmin_cuda_dispatch.h,sha256=9mKzbp3MenIDMgiXWxYd0ntzta0h_J6AIENiwT9Y1Wc,1307 +torch/include/ATen/ops/argmin_meta.h,sha256=0hZA7tEq_TxBwj30Hy01j6-tswYRnpJNTJFyaMY1xCw,865 +torch/include/ATen/ops/argmin_meta_dispatch.h,sha256=9TZOAvEJz7ZFyvS_28u89EIaAsaTvL5WCMcJv1cfTCk,1307 +torch/include/ATen/ops/argmin_native.h,sha256=F9KZtYuNzEypuWlaIM2naQtYfeGV4oDKBiyqWwyTI1w,894 +torch/include/ATen/ops/argmin_ops.h,sha256=3osfrvcAKFrAXmGVNf_tG2Pwoz8nEMnf6ld_giRjQIs,2111 +torch/include/ATen/ops/argsort.h,sha256=BHHL6F5DA3Iv7sG_uxnVgTuxa0exEx2YxrIGW6C7dm8,1931 +torch/include/ATen/ops/argsort_compositeimplicitautograd_dispatch.h,sha256=vtVprOsn8SyZiHR5axpCzkYLIFJwN1hRDHSrr9qsgn8,1419 +torch/include/ATen/ops/argsort_native.h,sha256=ef21oIJnFcZ6IJ9ss_rmabNfxdcgzx_cC71E7BTQbog,999 +torch/include/ATen/ops/argsort_ops.h,sha256=sx8M82_idOrKt0HsXQhQ8aaBJkKWgNRJd1UePVTaF9c,2774 +torch/include/ATen/ops/argwhere.h,sha256=Nq_Zqfh23SZ6-Ti-hxFCc0-j-CXcmyPQ6HM2GPPqTs4,899 +torch/include/ATen/ops/argwhere_compositeimplicitautograd_dispatch.h,sha256=AB3PDtUWP1Xn6X5WFaZknKUi7lLm_XvWGl4bGEzfID8,1020 +torch/include/ATen/ops/argwhere_native.h,sha256=gmts4IxllA2N6bVI24zT6IMq-7oFetY-rbGzpNq0POg,732 +torch/include/ATen/ops/argwhere_ops.h,sha256=nA-QJ7XKGbtt8YD3wXA2CnQhS5DxN9UzNmC5SRarPSA,1217 +torch/include/ATen/ops/as_strided.h,sha256=wUrhKUFhKNPg8zaIGq3CGfXUaUUGG8PtGPk54_KZr_Q,4132 +torch/include/ATen/ops/as_strided_compositeexplicitautogradnonfunctional_dispatch.h,sha256=AhnQg49Y4YLSokWXqOfLP8iP1nZ_SiSfPtkOhV3DaO8,1347 +torch/include/ATen/ops/as_strided_copy.h,sha256=CtKlIupFJhHj213e82Fp6ONHTrkV0tnDS6KU3x99HXo,6184 +torch/include/ATen/ops/as_strided_copy_compositeexplicitautograd_dispatch.h,sha256=5kBkiuBTg8sYOXYztjk-V8_R2gUejpgrA6D1CDnxOsQ,1730 +torch/include/ATen/ops/as_strided_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=0cUJbTv-Qw0U5zDFtvSpABbEgkT1-hHIFJW88-fYs7A,1339 +torch/include/ATen/ops/as_strided_copy_native.h,sha256=c2Pp2Wb6cKoamLB9oE9gT2dMAhLzBgo4DXGG76dOS54,1053 +torch/include/ATen/ops/as_strided_copy_ops.h,sha256=LgZ-m1QHzwbzFzMtMKntMrOLNuYfZ5zBLNGRw9W_0cI,2517 +torch/include/ATen/ops/as_strided_cpu_dispatch.h,sha256=U4-kH_sTgIBunN5YXokn_WprFxJXYZylhC1Q2ZWVZmM,1259 +torch/include/ATen/ops/as_strided_cuda_dispatch.h,sha256=eDfgl_rwHq8ugvWhJA3QrSZMflMmgXVmSMtzHZ5k7MI,1261 +torch/include/ATen/ops/as_strided_meta_dispatch.h,sha256=rLGfb9kI-PMVeQNuP4TVl-6XghaAFDxurm6olzH8Ae0,1261 +torch/include/ATen/ops/as_strided_native.h,sha256=fC7uGifTcEzKKbwRdNoHsjYHSkolg24wzsrAHXPtpN8,1402 +torch/include/ATen/ops/as_strided_ops.h,sha256=GoIWysvt1VPdLBm6ogoVxJw3nXMjxSK3nK9a5FFw_hc,2438 +torch/include/ATen/ops/as_strided_scatter.h,sha256=YLigoF9Kw-XMdVICCakVhFmRwLCJ7qE923tCwt2IDPE,6697 +torch/include/ATen/ops/as_strided_scatter_compositeexplicitautograd_dispatch.h,sha256=1upHXfTvZhSrMP8rWZ21dF1Hd6Qepqa7aB6w6YCWD2o,1838 +torch/include/ATen/ops/as_strided_scatter_compositeexplicitautogradnonfunctional_dispatch.h,sha256=J8uzr66aZPTstDIErZHKVCFF7Qzjku6P7Bb4xwIF9gU,1393 +torch/include/ATen/ops/as_strided_scatter_native.h,sha256=aulN12IHKBwp0In-BvNX1E5idPdIsCfzWkjdV3fPBdU,1107 +torch/include/ATen/ops/as_strided_scatter_ops.h,sha256=C0VF4z8kW6pJtdVK35FlPeXB3t0io1XigWBSvkNAudo,2695 +torch/include/ATen/ops/asin.h,sha256=6dZJKY4qGci-jldWDnOKRWrA-a4swl5A04YnEX59IpE,1397 +torch/include/ATen/ops/asin_compositeexplicitautogradnonfunctional_dispatch.h,sha256=pS1KONtDptODIyWb24gDwd6zYWxqq3UU8ce95217Z-I,1091 +torch/include/ATen/ops/asin_cpu_dispatch.h,sha256=TU_cp8cqXXLd0TnQcWdAdyIop5VfjeywdzIvHB6MNLM,1174 +torch/include/ATen/ops/asin_cuda_dispatch.h,sha256=sYh8Y4VSCZDrIeXoD9Ugb1TRiPyImmdL1GvB7KkU83E,1176 +torch/include/ATen/ops/asin_meta.h,sha256=O5kgNxFEMt2e7Y1xEIYhIGO2B3kKa9gbGwGBEVdS05k,819 +torch/include/ATen/ops/asin_meta_dispatch.h,sha256=gGj8XqdzL4KOQ_M1KGbS8hyHLJ52fVo9zliBkBgvKZU,1176 +torch/include/ATen/ops/asin_native.h,sha256=eyknEruGD7pH_F_RW-r7nhqQm-rYZRosKAchUKsA48Q,1252 +torch/include/ATen/ops/asin_ops.h,sha256=RGX5MrYJ1ypFCCveF2MMiISTd_1bGdYfR4Cty0VpU-w,2282 +torch/include/ATen/ops/asinh.h,sha256=B5iPezw69GwhGn9zthCnlgb-PR4wCqx-KM4etx_tpoQ,1410 +torch/include/ATen/ops/asinh_compositeexplicitautogradnonfunctional_dispatch.h,sha256=tA0Ci9Wp9pTHmyQu5KdZht4A8wwVm6GAoR9vFh5kph8,1093 +torch/include/ATen/ops/asinh_cpu_dispatch.h,sha256=gL3KygVUN0VpdOvH3QmVGjCpbnS0LetxoK5MZnpcqSY,1178 +torch/include/ATen/ops/asinh_cuda_dispatch.h,sha256=fcgoxE_B54nYsLDiVp0sWBnwF5E7-KjctvdapzFUynw,1180 +torch/include/ATen/ops/asinh_meta.h,sha256=uu_oPJwLAO80zNWX-YNSHXAuLgGkozoqqfsVMdLkR44,820 +torch/include/ATen/ops/asinh_meta_dispatch.h,sha256=7VJ0tjC6w2_Fa9lMuzpIHSa05LKKMpJlXSUJQq5VcJ0,1180 +torch/include/ATen/ops/asinh_native.h,sha256=3z81vK6b55PFPiN-UB4fxmBLi6dpvh4wVs96P3oAVT4,1261 +torch/include/ATen/ops/asinh_ops.h,sha256=7EfRswjdCqmUf5Tr3ZiGP4IsoiRKuX07HnQOXYRbYNY,2291 +torch/include/ATen/ops/atan.h,sha256=-SJqz5oGrT9HvRgKsmS8SqS7IXD5ol32w8215ZW6WJE,1397 +torch/include/ATen/ops/atan2.h,sha256=1zEyo-XJ40uIovW8ywDpT2DMvDTwYgkwNjn0kNOva7U,1412 +torch/include/ATen/ops/atan2_compositeexplicitautogradnonfunctional_dispatch.h,sha256=692Lrb7ojzHqKgGwo_Stt68QD-C4BEomPM7d-PAHjSM,1145 +torch/include/ATen/ops/atan2_cpu_dispatch.h,sha256=cj6dDror4xzOtToQm5Vw-gCM7K3R9vp4YYaUSjoWknY,1282 +torch/include/ATen/ops/atan2_cuda_dispatch.h,sha256=Ni9e9SPjoVHutlIv8hL0Bc9UKNw4a1j5fxmjbsNEh3o,1284 +torch/include/ATen/ops/atan2_meta.h,sha256=P--U8dOOFN8U_j-FDkO5Ph8h0iS8BomIupQnzvPrr28,846 +torch/include/ATen/ops/atan2_meta_dispatch.h,sha256=Wgbo19_on-VDMBS3UE9ucOdZ9Q0svlvqboVI7awKWDQ,1284 +torch/include/ATen/ops/atan2_native.h,sha256=vMivDfcTyRxV2AuT3HVuqrA70wfPqxN5PAi25nxhQ7A,873 +torch/include/ATen/ops/atan2_ops.h,sha256=Z4Y95GL1FWpzjsDe7khNOhJ7_4_a_2_kNJBOvinm42c,2549 +torch/include/ATen/ops/atan_compositeexplicitautogradnonfunctional_dispatch.h,sha256=F53co3TTVHf_6VdjI5ot-pBoph23Am70UpCTe3r9BxM,1091 +torch/include/ATen/ops/atan_cpu_dispatch.h,sha256=pZl0lgc8um-cj36fSxWUhfXZwf2aiISgexPVxa1TYlo,1174 +torch/include/ATen/ops/atan_cuda_dispatch.h,sha256=BUOsp0_a4krYjeNuuawq-LdYGuPKFhj4sOQJtacMozI,1176 +torch/include/ATen/ops/atan_meta.h,sha256=mLf6Rm97Uuj2PRlSXevn70Bf3Sc4rA6HY0IenQiOTzk,819 +torch/include/ATen/ops/atan_meta_dispatch.h,sha256=23awb09Suck2tJK7_13e8AXn8qOvO05hhW_gw0XX2YI,1176 +torch/include/ATen/ops/atan_native.h,sha256=F48TyFjJBGas9TBbyqFrD_V8Veiz44nDAAL8CJ3Nuu4,1252 +torch/include/ATen/ops/atan_ops.h,sha256=oERuhew2uNIkvGwFI_NxIiJIYdCNMG00D6HJZhTVF0I,2282 +torch/include/ATen/ops/atanh.h,sha256=VZJaifaBgMMw0WKMvYy2zMUlRlBxHGzDtwjTZLD9GWk,1410 +torch/include/ATen/ops/atanh_compositeexplicitautogradnonfunctional_dispatch.h,sha256=aoVfbRzWJ8yo7LkQjQAgodxiZHNSR75YyZnNECFw_08,1093 +torch/include/ATen/ops/atanh_cpu_dispatch.h,sha256=lGWIjCsDc6wnyHc0GHeKb6nKJcdYZQzMG8rvMpyK2tk,1178 +torch/include/ATen/ops/atanh_cuda_dispatch.h,sha256=Ynl5-b8IA0bOpT7DJXhM6PApF2MiaT8TJw6KgckJcGU,1180 +torch/include/ATen/ops/atanh_meta.h,sha256=jOwwN_UxjCWHJ_WuQ7NuGP-RcXrr5i-ezrM9147aIlo,820 +torch/include/ATen/ops/atanh_meta_dispatch.h,sha256=HoqJGAxHmTwxED5N7KpFlWLH4_0T4UVJWzf5o77PB9A,1180 +torch/include/ATen/ops/atanh_native.h,sha256=wKNo6q05YLH7nEO0AV_PpcffS4Yv5oa9BBAZMYjUUy8,1261 +torch/include/ATen/ops/atanh_ops.h,sha256=qXSEXc2cRG8bRy-Ks48xbqQcH1bxxrpeJl0yJa8428E,2291 +torch/include/ATen/ops/atleast_1d.h,sha256=Y2h7FBWO4_ZdnxwkH2n7CFeDPKQFttDw1JT1qK63XVM,1096 +torch/include/ATen/ops/atleast_1d_compositeimplicitautograd_dispatch.h,sha256=cSV_5QNtgEvLGPl67GDLC0vs23zqrIOo2JHxTilNUAM,1094 +torch/include/ATen/ops/atleast_1d_native.h,sha256=qGWk-JixUS2GW_mSwuEnsqIzEdAsIwFAeUu28fNzbWE,806 +torch/include/ATen/ops/atleast_1d_ops.h,sha256=yzKSzeCx6HkC2RHkTc1B6Yp42UC7S8ljja8wdvs8Ziw,1807 +torch/include/ATen/ops/atleast_2d.h,sha256=mzq2LFo5UJjh140DDHNcKEPzV3hX0MSzZWzvNyaMQ2E,1096 +torch/include/ATen/ops/atleast_2d_compositeimplicitautograd_dispatch.h,sha256=9HA8LiiHCm4baPn3MBQhTYLnJXpQUZec_uTB9whnfy8,1094 +torch/include/ATen/ops/atleast_2d_native.h,sha256=ID2YC10s5sZaHUjsDbj2apIB8COPweEREHXMzxsHMuU,806 +torch/include/ATen/ops/atleast_2d_ops.h,sha256=nYVgyh6lO1GPgRVQEeWyfL7TzmhHkD_lat8xpYhrPQc,1807 +torch/include/ATen/ops/atleast_3d.h,sha256=fTcDHZ3EI-auZ_BSG1FUBFheWNq8N4uHnHpRlYf6-sQ,1096 +torch/include/ATen/ops/atleast_3d_compositeimplicitautograd_dispatch.h,sha256=ymjqBMIDFWQaeQy9tBa8J5MjUZnHuKAg3EmO9Bl7D1w,1094 +torch/include/ATen/ops/atleast_3d_native.h,sha256=2DY9kGlI_Zwzo47BV_q4Gjgz-SXcrqTme-wVCEXUdxM,806 +torch/include/ATen/ops/atleast_3d_ops.h,sha256=Rx66_U0cioX8NSPQ4s1xSGGxrCXwENLe0v_ItxEiZY8,1807 +torch/include/ATen/ops/avg_pool1d.h,sha256=GAS9xY3dzNIJ2GPehFWg_oU42MV_XoBeR71nLMDwIfY,2208 +torch/include/ATen/ops/avg_pool1d_compositeexplicitautograd_dispatch.h,sha256=3-Ah5DXwbjPddbzmx0AnsjNLXaN_XsiIfUmtZHT5sw0,1381 +torch/include/ATen/ops/avg_pool1d_compositeimplicitautograd_dispatch.h,sha256=po0kt9Zee6y434D9BmV8e7s_V6QxThEtmDcTdL1jYjo,1156 +torch/include/ATen/ops/avg_pool1d_native.h,sha256=OhtFUdUNC5uIqQUVeJYovj8LTIt12vTSdHQDSJrHHCA,1068 +torch/include/ATen/ops/avg_pool1d_ops.h,sha256=fF3y7aNqFX9a7QNPGYA1CFrNiKRZJRbKqk2Js_56g7E,2637 +torch/include/ATen/ops/avg_pool2d.h,sha256=zzctGWwcWrZFEL6KIf59HWwuyMvCGhv3W883Y6ES3cM,2505 +torch/include/ATen/ops/avg_pool2d_backward.h,sha256=Jsxj5sW6zD3gIhziA-EKNByq9Xm2ibUQ8HaKGic1XuU,2735 +torch/include/ATen/ops/avg_pool2d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=G-nAYYYS6LghwifGh3ZuLISuI02wvCK4qDo7pSNZ9Nk,1250 +torch/include/ATen/ops/avg_pool2d_backward_cpu_dispatch.h,sha256=66mB_AehRWKNj4-vSKo6lHbV2E1fkaTarGmrKhE5QY0,1763 +torch/include/ATen/ops/avg_pool2d_backward_cuda_dispatch.h,sha256=6dPIVB2jOmbjMsIg-IdmC_6dlCLdxLkAHwgDTnxkaNQ,1765 +torch/include/ATen/ops/avg_pool2d_backward_meta.h,sha256=T_nfx1dVnS9aBFrp4msWpjudKDDkKxJ-EI4UNPcxMcg,1027 +torch/include/ATen/ops/avg_pool2d_backward_meta_dispatch.h,sha256=2CfFr-CY9XsEBtx9hDHRTZgm3nz3GM3K7ujJa9VU7qY,1765 +torch/include/ATen/ops/avg_pool2d_backward_native.h,sha256=Pd1ltV_pBxAXjKaixWNRWmcBg9UGcS4JEfBX_Ou3DfE,2030 +torch/include/ATen/ops/avg_pool2d_backward_ops.h,sha256=TP5KSfqcZcJoZk-f7ystcV2VEACZsLzFtGun10ihoZA,3179 +torch/include/ATen/ops/avg_pool2d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=SjBe7jvi6SroirbD0Jgbfoxe_FCw1LAgYuMOu1p9G2E,1240 +torch/include/ATen/ops/avg_pool2d_cpu_dispatch.h,sha256=Fr0c3sjjXUVGXK6k1RylsLoGM1oO6kZurn_tJgK1NdU,1688 +torch/include/ATen/ops/avg_pool2d_cuda_dispatch.h,sha256=htK8eLQ1_aj6bbomIN9NoxRas8Iwbw1AF9yXPqiB_1I,1690 +torch/include/ATen/ops/avg_pool2d_meta.h,sha256=jhOe0UDiJonIpDovNKbSfNX-A-eR9QWStrF0_caOPic,3696 +torch/include/ATen/ops/avg_pool2d_meta_dispatch.h,sha256=RLSQM1VAuzAM1SZ19RVU05Hhi3FQEo88jA-wN9B4Uds,1690 +torch/include/ATen/ops/avg_pool2d_native.h,sha256=CRBYguBG8G4n6y_AnB8YlVjVIEHW1eS5HLFxMdf_3FY,2109 +torch/include/ATen/ops/avg_pool2d_ops.h,sha256=z3mHD10BR9MEjIUDfzofY7MZmkK-WTiuLnDw7dShu9I,2917 +torch/include/ATen/ops/avg_pool3d.h,sha256=pOHOCZfdU02EbBNYScxKtIAaqvVu3Rx8t1HYD29Hk1g,2505 +torch/include/ATen/ops/avg_pool3d_backward.h,sha256=J-JoplellOM4YMYJGH6XxYOtaYjn2TjtPDs_q4TbJiM,2735 +torch/include/ATen/ops/avg_pool3d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=fHCPVhseY42rw4HNB1wfPzrsUVRhnN4c0sQlReSBVp8,1250 +torch/include/ATen/ops/avg_pool3d_backward_cpu_dispatch.h,sha256=QXjzdsDhsrTJsY47iuBJOlS_xxlpic---PuvW_5Cmzk,1763 +torch/include/ATen/ops/avg_pool3d_backward_cuda_dispatch.h,sha256=O3HTIehTjwReRGRDq9eYQCJvnx_danLT_YIj064XMIQ,1765 +torch/include/ATen/ops/avg_pool3d_backward_meta.h,sha256=t-guFOuk1OKRykPPza4QV1ErOITzDteuXCd0JT2lKuo,1027 +torch/include/ATen/ops/avg_pool3d_backward_meta_dispatch.h,sha256=L4y34jkq0CHscSAi-D_lJ3aWEmivEx__lFLPDFxFTa0,1765 +torch/include/ATen/ops/avg_pool3d_backward_native.h,sha256=_FEs7qPPaDLXjIe4cscLmZfE-qXNCahKr-wS_VLbL44,2030 +torch/include/ATen/ops/avg_pool3d_backward_ops.h,sha256=lJ6-lxJ4XpdVKiuvP_n01E3TLrUYdA_gyu5u9dKZ_7A,3179 +torch/include/ATen/ops/avg_pool3d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=vr0DzAinimkzlf6qWuYVlIWFdyuZoVLj71SQd7w1CNM,1240 +torch/include/ATen/ops/avg_pool3d_cpu_dispatch.h,sha256=0omjaNll7JkYCMVZZIvIYThYRp-7n6Uyo3m8lbkugjQ,1688 +torch/include/ATen/ops/avg_pool3d_cuda_dispatch.h,sha256=p4qMEwwGfom8p-C5OGZ55Wk1gDx2vh3RbeM7RNzSSYw,1690 +torch/include/ATen/ops/avg_pool3d_meta.h,sha256=oS2j0t1wsZ-Ggs9qPdGdoiyrevuKP0hN_NhDaL1X5do,986 +torch/include/ATen/ops/avg_pool3d_meta_dispatch.h,sha256=ajLQpnjRtIxPSMz9YjyEOIQCs9yOx7_yx-x8zi6OfIM,1690 +torch/include/ATen/ops/avg_pool3d_native.h,sha256=tciz5tF8OwHbrcSHh3VXlrlbt_4cC9_F1khH0tVuZ54,2113 +torch/include/ATen/ops/avg_pool3d_ops.h,sha256=2UuwBhneqHoU32UPwBQnFfsa-in1XOTjHJxN-7GspCs,2917 +torch/include/ATen/ops/baddbmm.h,sha256=rnbZi1R9Lny3CABJZt_U6fCTTAwcJeo7YAKwvnz8J6U,3230 +torch/include/ATen/ops/baddbmm_compositeexplicitautogradnonfunctional_dispatch.h,sha256=wKXOhmtTSl_bkkls4IUVy6ph3VeMvyRGsvphh4TKilk,1315 +torch/include/ATen/ops/baddbmm_cpu_dispatch.h,sha256=SdfMUkrYPByfx6zkDeIYS-CprSjrKNFbKaTc53Yg1BU,1618 +torch/include/ATen/ops/baddbmm_cuda_dispatch.h,sha256=TXpPDMF5qXu5nw7dVAEenyx_mZ7rvz6aj5CNednlUSw,2235 +torch/include/ATen/ops/baddbmm_meta.h,sha256=jgBmEsntIO-92RLc42kBP987RlQo2ELCjkLCOUiTdnU,927 +torch/include/ATen/ops/baddbmm_meta_dispatch.h,sha256=7t1cJ8xpyTSsnRapiMq1TDjO1Zp8XdPatDTQPw_0Q08,1620 +torch/include/ATen/ops/baddbmm_native.h,sha256=t8PaKQDsNURwvL74Oq6ZhU7kXsiadqFBcK-47GvtAQM,1839 +torch/include/ATen/ops/baddbmm_ops.h,sha256=Q8cSb3m4DefUVeY7wVu2Ea-eOaOcGYgtpwnWMRlo1iI,5384 +torch/include/ATen/ops/bartlett_window.h,sha256=EcWHAx2pNqicPUPWA39vER6JEhKbKMtmfT6uWXD8oQw,3671 +torch/include/ATen/ops/bartlett_window_compositeexplicitautograd_dispatch.h,sha256=iVkQn8joRZw1k6pYXNCfjVvATo-qwQl236TUCHkr3Mw,1960 +torch/include/ATen/ops/bartlett_window_native.h,sha256=ithhbQXMutpR9w3u1R10znm3L-_cL4yPzdGAQUjhl-4,1321 +torch/include/ATen/ops/bartlett_window_ops.h,sha256=KeRzUE3yz-ab79mrzWAW159X6WhUncZeGfwUwHkNweo,4110 +torch/include/ATen/ops/batch_norm.h,sha256=LFi4DCZm_lZ-UEAPcQh1C3Z1vAInCV-3EClwTTFChPs,1375 +torch/include/ATen/ops/batch_norm_backward.h,sha256=Ix3krX6gPn_6ka1GoNXze4hniInBaI4y9jnTnI2hzQM,1609 +torch/include/ATen/ops/batch_norm_backward_cpu_dispatch.h,sha256=Thw7yMxSfgAW4rRmDZmVICF6ttmojf3mGzCE-ZQP-zI,1359 +torch/include/ATen/ops/batch_norm_backward_cuda_dispatch.h,sha256=A92xSMyMeqTSTaUaSe10oxFNvpkhIRzr5FzG_SEjiE8,1361 +torch/include/ATen/ops/batch_norm_backward_elemt.h,sha256=vc2wMSx4kgE0EEVcOkwCkCnNkiHQPMs21SWn6qR9zrI,2611 +torch/include/ATen/ops/batch_norm_backward_elemt_compositeexplicitautograd_dispatch.h,sha256=3otyyE6qzQGikvHxuA-dhTPaVNezovDCqT2U0SCWzfQ,1579 +torch/include/ATen/ops/batch_norm_backward_elemt_cuda_dispatch.h,sha256=155d-60cp5mMW4t9StIIrkrVoIVvFX3OnB_DFHpKnz8,1205 +torch/include/ATen/ops/batch_norm_backward_elemt_native.h,sha256=wsILFVrlVTfv48hHnBQ7tzx8JnYGyYe3fKzwuF64Jtg,1271 +torch/include/ATen/ops/batch_norm_backward_elemt_ops.h,sha256=iREb6jye293XQtvBJYCObr9KeNdHeNEUyaSMDvQZBWc,3289 +torch/include/ATen/ops/batch_norm_backward_native.h,sha256=58zP0Y852N-k4-KpC-7WH5S5CuDJKCGe6oOsbo3iEYc,2024 +torch/include/ATen/ops/batch_norm_backward_ops.h,sha256=15IQ8uCSE4hesE4WJxKnAX6-aNQXPQhq6wioZEjryGA,2466 +torch/include/ATen/ops/batch_norm_backward_reduce.h,sha256=5i2EX80H-ybANCg6RP9_bvZ1Bp8g_Y2E2qp9HUFNnGQ,2990 +torch/include/ATen/ops/batch_norm_backward_reduce_compositeexplicitautograd_dispatch.h,sha256=9aI10F1lQ7fQopytP3-WPmMLRLzqd1R5CWTjlL5ZcQ0,1719 +torch/include/ATen/ops/batch_norm_backward_reduce_cuda_dispatch.h,sha256=QOIQ-1ZFgwUHyZVg3CV07IEd1foVlGquKuRkXFDqy2I,1211 +torch/include/ATen/ops/batch_norm_backward_reduce_native.h,sha256=163855V2OnH39p6_u0coTSPxTTYwLRxbjTxtJLVvdes,1347 +torch/include/ATen/ops/batch_norm_backward_reduce_ops.h,sha256=5GG1OEWLAh-nRB_e6XJynAAGKyZi3eT4dgaurfFqeq4,3605 +torch/include/ATen/ops/batch_norm_compositeimplicitautograd_dispatch.h,sha256=U97fC9tk8J6mw9qaq0nR2WpZKMFR9CX7qQ3Ehyue0_8,1272 +torch/include/ATen/ops/batch_norm_elemt.h,sha256=CqYc72LHO7iq5yi9FCm9mxKanWXtWAjZV1e8LV3pEdg,2146 +torch/include/ATen/ops/batch_norm_elemt_cuda_dispatch.h,sha256=-gOrrAWEUE1LDZBh7opbmsiNbb50BzoxyO32DtF8zvU,1616 +torch/include/ATen/ops/batch_norm_elemt_native.h,sha256=JHtJh340ZK_GgvwJxJk8jb2fEQyBMWlUpmzgRDn3Q1Q,1140 +torch/include/ATen/ops/batch_norm_elemt_ops.h,sha256=KOgVoKZe-NddNNcvxiQBgFknh8cHmB9b6TZhUw0aGK8,2849 +torch/include/ATen/ops/batch_norm_gather_stats.h,sha256=J90Pi9BhzMyv1q21l1ObqIHVGOro2_AQeKN8EYdTL7s,2768 +torch/include/ATen/ops/batch_norm_gather_stats_compositeexplicitautograd_dispatch.h,sha256=CU-WZCQ4eCkXfpnE8dko9fneQRz3ta--7zpkjjhNp_I,1641 +torch/include/ATen/ops/batch_norm_gather_stats_cuda_dispatch.h,sha256=erMlizQQFYtz4lXSWwjrBq7U8luJgR3Wpjv9axE2G8U,1214 +torch/include/ATen/ops/batch_norm_gather_stats_native.h,sha256=-QiU22S_AOUFrCVclH9gFJ6_Q4DoUdi5Cs9s_VT6kUw,1311 +torch/include/ATen/ops/batch_norm_gather_stats_ops.h,sha256=B_F2AJG5mlBP8nNk5Ld9qwlwy-keUwUj4QGpz0ch5Cs,3437 +torch/include/ATen/ops/batch_norm_gather_stats_with_counts.h,sha256=0SZm219jWI0J3QmMrfKxOvBoD12d3tCx17Fc2mu3cvI,2939 +torch/include/ATen/ops/batch_norm_gather_stats_with_counts_compositeexplicitautograd_dispatch.h,sha256=rl9fglm_nFsxlkOCWgUPsqhcWY1mZTWHsGMcn1AnPD4,1689 +torch/include/ATen/ops/batch_norm_gather_stats_with_counts_cuda_dispatch.h,sha256=gHAx_WiKr6R69eNX2uKMeRzD4d3_kjBkC8oqnJU35vE,1238 +torch/include/ATen/ops/batch_norm_gather_stats_with_counts_native.h,sha256=O2znHltp1VMqbAwnZp8MbYThS5KFS6KCXUK1O1hHTmM,1359 +torch/include/ATen/ops/batch_norm_gather_stats_with_counts_ops.h,sha256=kWTLHmVV5JlB1DNZDiicaEyh7mijEVNaHT-kDIN6vtk,3587 +torch/include/ATen/ops/batch_norm_native.h,sha256=DhlN-5nJdZ8t6jRw-9QLGov-SoFCZRfR4yFzfJx1Tbs,984 +torch/include/ATen/ops/batch_norm_ops.h,sha256=S5H5cMyVDvNoG-FAsv3s8cN2QrLsQAwLMn4VaD3WzSc,2035 +torch/include/ATen/ops/batch_norm_stats.h,sha256=a1O45Ft0a3M5C3-7JyG3bRxSLBiXfSDb131rZ326YdY,1681 +torch/include/ATen/ops/batch_norm_stats_compositeexplicitautograd_dispatch.h,sha256=oWcMS63gF6_rWFEzCU32hhgeHZajls6rzDZVALJPUms,1261 +torch/include/ATen/ops/batch_norm_stats_cuda_dispatch.h,sha256=tUArcNzKAK512laBnEdIAoCTR7bWF3BT7e1OXcOv3f4,1024 +torch/include/ATen/ops/batch_norm_stats_native.h,sha256=-rmoHPcCKDPEEZJ4OkOSTl5SACBflyTLo8-gJFALTYY,931 +torch/include/ATen/ops/batch_norm_stats_ops.h,sha256=pD6tFonqozI0Ge_tkD3E6CaPQ8AyhJbB3h_vb0Pg-OY,2205 +torch/include/ATen/ops/batch_norm_update_stats.h,sha256=Z3iMOEL_uxncsA0aqmeDn6MY05UHrwEByzSdMj_ypaY,2303 +torch/include/ATen/ops/batch_norm_update_stats_compositeexplicitautograd_dispatch.h,sha256=gzVw2m52ywuj0Hi16OVNGRo6NPLow6R4nWt4aoydZO0,1483 +torch/include/ATen/ops/batch_norm_update_stats_cpu_dispatch.h,sha256=G110gtSbrjf54bO-HUaUwGkCh3tUJdlvgEp8GYJAyYM,1133 +torch/include/ATen/ops/batch_norm_update_stats_cuda_dispatch.h,sha256=UFmJ6x_bWNh63cVfSgkeTLILdf90Yu4XMyoStq8qWts,1135 +torch/include/ATen/ops/batch_norm_update_stats_native.h,sha256=1rjoRTg3jwuVNsODK9Vl6GN1WgPfCZueOMtLhZTBHic,1370 +torch/include/ATen/ops/batch_norm_update_stats_ops.h,sha256=qN7CflwLSXAjnQAQqKReZxoBvpUdOrqHVcBAzp1DACc,2907 +torch/include/ATen/ops/bernoulli.h,sha256=B0xXToy5r6yPYDIEaCyTZ8pNlOBTiS0Ohr-Vp-BD-I8,3487 +torch/include/ATen/ops/bernoulli_compositeexplicitautograd_dispatch.h,sha256=qxWLxWJOqrGTmc_lFudOAPrinIS7QTRr11Bn9vz4plk,1806 +torch/include/ATen/ops/bernoulli_compositeexplicitautogradnonfunctional_dispatch.h,sha256=PQU6gOYC_HNaDLhlJCLCdKlCidKHTTfqVFTBTXyvNH4,1114 +torch/include/ATen/ops/bernoulli_cpu_dispatch.h,sha256=yibi4VzrAVN1Kp1uzxIpVFMTx4dX1KehEcoQO3JByKc,1440 +torch/include/ATen/ops/bernoulli_cuda_dispatch.h,sha256=ucwS4BbWGFLnAhZ5aBEFyPkDLorVC7k3INu3EkAIXwk,1442 +torch/include/ATen/ops/bernoulli_meta_dispatch.h,sha256=pOz3yuIbZZnP0_w5R1dMoBQQgMrTgw4rqawhVJkS91w,1180 +torch/include/ATen/ops/bernoulli_native.h,sha256=X2BYZoCeV6AG8qbHA1aSxwQou7woAT9ydOJXWAbv9C8,1722 +torch/include/ATen/ops/bernoulli_ops.h,sha256=S8DmmYaRvo1xRC6KeB6npo-kji0tts5qwXY-_Ew19co,6652 +torch/include/ATen/ops/bilinear.h,sha256=FYNT3GohTwwoKL5ODZP0HG7ZJ-TdclUxSf9Yx-o9Uqo,1075 +torch/include/ATen/ops/bilinear_compositeimplicitautograd_dispatch.h,sha256=e3YXu_hWDmorApn1kuLBqWX1KDMCsWDo6_KEkhKgXvs,1121 +torch/include/ATen/ops/bilinear_native.h,sha256=PBrU7BXA-8tvkWY1LKRfRfuFKEie3lifBOafIMQHroc,833 +torch/include/ATen/ops/bilinear_ops.h,sha256=qjaEWwoCBghOTo9Gw0kMcOgLPF8Eak-qtCFjHkIcAaM,1541 +torch/include/ATen/ops/binary_cross_entropy.h,sha256=DCF7LF1HHd19oSDts25qagv9asrXXQElT37AUCqq2ag,1986 +torch/include/ATen/ops/binary_cross_entropy_backward.h,sha256=7RCy4uoQy9PZI2gYJj539lEHPTMv6V1qZ8nm22JejbM,2341 +torch/include/ATen/ops/binary_cross_entropy_backward_cpu_dispatch.h,sha256=JSyYOMegYHYYFqkmCnBzqgT3gLI17XpeHBhWwX6K6Mk,1626 +torch/include/ATen/ops/binary_cross_entropy_backward_cuda_dispatch.h,sha256=wIr-nVSozbeGZwfBpeW34WPF6ZqNcCGR6S91OfV1Xdk,1628 +torch/include/ATen/ops/binary_cross_entropy_backward_native.h,sha256=x4spYwPmveyMQjtEcNWGVrhJYDnKj1B_PCd3ZHtyPsk,1598 +torch/include/ATen/ops/binary_cross_entropy_backward_ops.h,sha256=0xjgIB9_TGuvGTG0jb3qzZffgcpbWuZdcEhqbi53Dsw,2793 +torch/include/ATen/ops/binary_cross_entropy_cpu_dispatch.h,sha256=xxQMdCXt2GZ6D-SgSBiIsu8QIu8tCxH_re28py0ivIc,1489 +torch/include/ATen/ops/binary_cross_entropy_cuda_dispatch.h,sha256=P-ZweLmp1dWSj_VmTv0J4h9KiTwLzA40vVj66cWwXZc,1491 +torch/include/ATen/ops/binary_cross_entropy_native.h,sha256=KgYba0LJtDl7gmw7xJa2MAn1aK2o8u9CVbPVPJp-pFI,1420 +torch/include/ATen/ops/binary_cross_entropy_ops.h,sha256=yVypxWGMmZcwVs81oKaX8Za_tcr68Doq6jC0uVQTXhk,2489 +torch/include/ATen/ops/binary_cross_entropy_with_logits.h,sha256=NpkbQVY1TE5K24xXPY5Lq9TUFS_M8lhue9ufwF-2nx0,2367 +torch/include/ATen/ops/binary_cross_entropy_with_logits_compositeexplicitautograd_dispatch.h,sha256=UQQwtNrIusKed8oifuTq0C8JFJ1lshe8ASKWuPbyFCY,1719 +torch/include/ATen/ops/binary_cross_entropy_with_logits_native.h,sha256=WUGJDzPdDGnCRMD5d8M7nAEIN40etar8foL7UHgFLLE,1162 +torch/include/ATen/ops/binary_cross_entropy_with_logits_ops.h,sha256=2CZZIU74najADjMReDtGY9XurD0FBK74cfQzwNfPN8o,2877 +torch/include/ATen/ops/bincount.h,sha256=zpEwE5AOGA4kzDzu1dc8A7bKgyN45hQjPM6f53wCOSk,4525 +torch/include/ATen/ops/bincount_compositeexplicitautograd_dispatch.h,sha256=qVY8LA1oNcZrro7ZbNTyNLmaMKjibaJ2J85p0R_v8Ms,1574 +torch/include/ATen/ops/bincount_cpu_dispatch.h,sha256=PLY2VvXZPzpup8wyL-JLOQwd9ncivzLQlVqnNs1IabI,1181 +torch/include/ATen/ops/bincount_cuda_dispatch.h,sha256=rQlaxDtxTnMup732yi_5SLFsN0Rz6GB9sRi62UfCyw0,1183 +torch/include/ATen/ops/bincount_native.h,sha256=iqtTp__75jB88uAV04Acup-SkcUFitUXM9K8pS0usuU,1092 +torch/include/ATen/ops/bincount_ops.h,sha256=4X8DRBzXZK6zO65z3PtS75En1VoUfACGNcCK6h33tXQ,2269 +torch/include/ATen/ops/binomial.h,sha256=qGDK6P_X0RzjHwQoO6Cen9B3iqqERlGx7DpXC4Qv2eo,1712 +torch/include/ATen/ops/binomial_compositeexplicitautograd_dispatch.h,sha256=F6-55607MVn2ZoHz8BpOVlDgI1NZkVL1vS4DTfe6A3k,1276 +torch/include/ATen/ops/binomial_cpu_dispatch.h,sha256=ML9WXhZWcO58zDFJOXbuGJk8aLpFMyvv55rdFJRpSDs,1059 +torch/include/ATen/ops/binomial_cuda_dispatch.h,sha256=Rzlyj5xMrm1-2msFyDbdLK0wqonWUhfHGMB4e9_PfMM,1061 +torch/include/ATen/ops/binomial_native.h,sha256=1EMlINS04wgfd1TivQTJsdae4cPhSa0ZASOMrXamUwQ,1117 +torch/include/ATen/ops/binomial_ops.h,sha256=IqYFvyiwEWMPvt1X0_hpc6RMxHoF2RLSyitA3UHKnnY,2271 +torch/include/ATen/ops/bitwise_and.h,sha256=CLnDto9LHTOSQO_mfNQ4rLCw-jdiyCdIb7ujwWaTR0c,3062 +torch/include/ATen/ops/bitwise_and_compositeexplicitautograd_dispatch.h,sha256=5oAHtdrUIRMRgxbKxPsMU_QdpQXnkR8jOrpTn7PfWYM,1654 +torch/include/ATen/ops/bitwise_and_compositeexplicitautogradnonfunctional_dispatch.h,sha256=RRqH3_LwHfq38YDnF4m-8Pwgvv4W_kY3ZC5vkLX-MwY,1157 +torch/include/ATen/ops/bitwise_and_cpu_dispatch.h,sha256=CubvluiIpMCfUj3HlJVgWHipVb5xNjX6PnsLD7Ul0eY,1306 +torch/include/ATen/ops/bitwise_and_cuda_dispatch.h,sha256=30pdrrJIB6LlajhqfCamdSn9AYIHPr2PSPzowCpkX54,1308 +torch/include/ATen/ops/bitwise_and_meta.h,sha256=U8K8WmOvuYdT9S39Gzy9YDYf5fzueWCR789gHqAxvSA,859 +torch/include/ATen/ops/bitwise_and_meta_dispatch.h,sha256=JIzvnJoxHWeY0n6GQ_EWqhkJWcCcvxN5Skz5H2Pjgm4,1308 +torch/include/ATen/ops/bitwise_and_native.h,sha256=U96dGy4rnd3ND4UKMty-61sG3SvfaGF6HLa74-pXVCE,1382 +torch/include/ATen/ops/bitwise_and_ops.h,sha256=4W_wWJAAPAmPg0YyjzMJSi-4SxAAjfl0nBxmq1BKEFg,5992 +torch/include/ATen/ops/bitwise_left_shift.h,sha256=oMcxJpA2P9yuXrRjTCooE_C6LoFlH_0MbNGBj7MStdQ,3300 +torch/include/ATen/ops/bitwise_left_shift_compositeexplicitautograd_dispatch.h,sha256=AKp5xmpr7fAKQZ8__vhqh9s1Wehd684iPPzVcRDjDSg,1703 +torch/include/ATen/ops/bitwise_left_shift_compositeexplicitautogradnonfunctional_dispatch.h,sha256=1t3_VdKZMfYTFuVndXxcJ7EHhxSdlfNsnavpyvzv8Zs,1171 +torch/include/ATen/ops/bitwise_left_shift_cpu_dispatch.h,sha256=UWDDYZT-kPNxL55iUgllZtfTMKc_0LtAGs3bU3fZHSA,1334 +torch/include/ATen/ops/bitwise_left_shift_cuda_dispatch.h,sha256=79OydsP3XTYGf5AFmSpE0hhq-4uUDKdl-fLo71Squ44,1336 +torch/include/ATen/ops/bitwise_left_shift_meta.h,sha256=MULPWugoHVhjYNdFq7jsFmgdaqkIP3HradZ6FTWADUU,866 +torch/include/ATen/ops/bitwise_left_shift_meta_dispatch.h,sha256=B3Qahb2LvZP-FIkMshMfJrH-q_rO-2G2GER8Fnibnoc,1336 +torch/include/ATen/ops/bitwise_left_shift_native.h,sha256=AmYhQHzJb6JBwkh8EBTWxEDQJrKbAIlFGMLIPcnzWfM,1438 +torch/include/ATen/ops/bitwise_left_shift_ops.h,sha256=DIOuexY7sm3VkHrdPorurBKRDCNeUeE9wMWKl0pveDA,6223 +torch/include/ATen/ops/bitwise_not.h,sha256=3cQohMDKPaXDYE0JkJp8RkAlqbc9_khCNaPLrk2hqVQ,1331 +torch/include/ATen/ops/bitwise_not_compositeexplicitautogradnonfunctional_dispatch.h,sha256=U_0i_TRsnmBcy-c8o6sjQrsMG3ayYfCbUOMLx4m0Yt8,1105 +torch/include/ATen/ops/bitwise_not_cpu_dispatch.h,sha256=P86aJOqHlqGt4BcgvxMJfbIEdlfIteDMDOKIZNaUuNU,1202 +torch/include/ATen/ops/bitwise_not_cuda_dispatch.h,sha256=wenskXlaBh2-u9nvfLAbB-InMrvQUitGMJPZcM5LzrY,1204 +torch/include/ATen/ops/bitwise_not_meta.h,sha256=-kKMzUjLBcqaRZe9yZcsxz_ylVHP1hjiPmtQI8_4pws,826 +torch/include/ATen/ops/bitwise_not_meta_dispatch.h,sha256=NlWbzqh8U4bKHuiGjfKy0rLktQnCIbi9PgZka3TX5lo,1204 +torch/include/ATen/ops/bitwise_not_native.h,sha256=rX-_LvhGQ8sW_yUBNOQvAdDdfFkVn-zNFVbu6BGveiQ,865 +torch/include/ATen/ops/bitwise_not_ops.h,sha256=t9kYlpM7xHdcHcudtWbjUn714J0tgUwJQD_PLYUdOoo,2345 +torch/include/ATen/ops/bitwise_or.h,sha256=t5hFHyg1yXrz3hx3HMUka6gk3mxkOaUJDFaocZcqFiM,3034 +torch/include/ATen/ops/bitwise_or_compositeexplicitautograd_dispatch.h,sha256=dvye_yu_Ssr7ka2cU031i9MqerD0RIYxtM7rb6Eos0U,1647 +torch/include/ATen/ops/bitwise_or_compositeexplicitautogradnonfunctional_dispatch.h,sha256=6m83NqXR_FlMI9EYhP2hsQLSDe8AFHC3k6sFf1Ro1EQ,1155 +torch/include/ATen/ops/bitwise_or_cpu_dispatch.h,sha256=xroX9NVDO-bNGw74l-UeHWWQwIjzQ2cb4VZILCtK48I,1302 +torch/include/ATen/ops/bitwise_or_cuda_dispatch.h,sha256=XwYo5OPNzZMi0A-6PTLlqg6aU-f_zuFz4OimrrVChX4,1304 +torch/include/ATen/ops/bitwise_or_meta.h,sha256=t7r4cEqy1i1T8TyxVLOVmsYSGk13RK2xr9SJh-oPdWo,858 +torch/include/ATen/ops/bitwise_or_meta_dispatch.h,sha256=ViNKm8QcwlpYwSF0g2Y2GmF3RAEv0WZ-YjBf6frxAh8,1304 +torch/include/ATen/ops/bitwise_or_native.h,sha256=X1-J9UPXTLgPQYSgGxSxkijM-3jl1-6aQNNyvVotTdo,1374 +torch/include/ATen/ops/bitwise_or_ops.h,sha256=Ec9AlsHaY_UzJDwnu102BDYWTHDaatla1QyYVacz2Ks,5968 +torch/include/ATen/ops/bitwise_right_shift.h,sha256=ZSRJoCZoRYRgpghFYRdc2ynvw8S8FgVu6MNUynu7Oqs,3328 +torch/include/ATen/ops/bitwise_right_shift_compositeexplicitautograd_dispatch.h,sha256=65j4-CNKmDKmTKpvpsaP663aegfkYud7fIMTR21gjXU,1710 +torch/include/ATen/ops/bitwise_right_shift_compositeexplicitautogradnonfunctional_dispatch.h,sha256=6cKQhbj-sKPCs6dsGJKWjHel-hA6jF01IEU2KXt-n2A,1173 +torch/include/ATen/ops/bitwise_right_shift_cpu_dispatch.h,sha256=i5g1QTRgkgxhL2SknTA5MOKDpCCJnkzp6LuJuAl5vao,1338 +torch/include/ATen/ops/bitwise_right_shift_cuda_dispatch.h,sha256=fEmaX4tcc5fb_zfE_G_ApB5FgDmfr7mCh8kznfxGQxs,1340 +torch/include/ATen/ops/bitwise_right_shift_meta.h,sha256=VZv8tNQCJepr_JI6ErlaXPUOtQyqyuHTx8kLAU94as0,867 +torch/include/ATen/ops/bitwise_right_shift_meta_dispatch.h,sha256=RP3QitT4gOr9VZ82o2R0kx285mWCyNR6Ymp42-sSmYs,1340 +torch/include/ATen/ops/bitwise_right_shift_native.h,sha256=j6qgg5CKTZ8M_vFc64mae_DoVm_hcJfri-w9GUvGsMc,1446 +torch/include/ATen/ops/bitwise_right_shift_ops.h,sha256=QYuDcJsQQPGKQ66FB2cQWf2TGAH-hvKnikXaF1Q_nFg,6247 +torch/include/ATen/ops/bitwise_xor.h,sha256=AqyGL6wXyy2ugK8oDDR-OVRlAlrg9FiO54i8RCcayjY,3062 +torch/include/ATen/ops/bitwise_xor_compositeexplicitautograd_dispatch.h,sha256=N6ShDRUxa5WrdUCAoqKYSWkbflXXFGFnAZwl6B2GsrE,1654 +torch/include/ATen/ops/bitwise_xor_compositeexplicitautogradnonfunctional_dispatch.h,sha256=38eTFTo0RP6Sj7Em-5-cxzOykWaYfmWOgnxF8uOkqvY,1157 +torch/include/ATen/ops/bitwise_xor_cpu_dispatch.h,sha256=kPj6XBUAhHpK01y98m4fB7hODoyFGgR4gSPoZsHRVh4,1306 +torch/include/ATen/ops/bitwise_xor_cuda_dispatch.h,sha256=2jJSLVWY0UgT7nYG3hXZcaE49KXBeQ43HyIZiqAOb8s,1308 +torch/include/ATen/ops/bitwise_xor_meta.h,sha256=4JR5wmov_3T8yyuoelc_Y927wRZVq4c7dego6s5P9rI,859 +torch/include/ATen/ops/bitwise_xor_meta_dispatch.h,sha256=o4doeAJae5xyHDJaCJxmM2LGW4TsAgCuAihFAwdYzEw,1308 +torch/include/ATen/ops/bitwise_xor_native.h,sha256=JTZ548ZF52GpEkAiIoJmjB3H4DoeaBT73M5OBfmaU7M,1382 +torch/include/ATen/ops/bitwise_xor_ops.h,sha256=MnweymakQHl3y9b0RU7X1aO8LGl7JTJFqINA43pcu9A,5992 +torch/include/ATen/ops/blackman_window.h,sha256=PJ4BiS7fkTgWl0apKCorR4iwPBkShSCs0QEFt5kexFs,3671 +torch/include/ATen/ops/blackman_window_compositeexplicitautograd_dispatch.h,sha256=aPYzSx0LmDokm3rPloJblKuSdXW-sGOpFDR5HrKd2LA,1960 +torch/include/ATen/ops/blackman_window_native.h,sha256=FNQyxSNQSBVpAh5irIOeAa-izJXkWs3PgKkKBo6YU1g,1321 +torch/include/ATen/ops/blackman_window_ops.h,sha256=-iUzN9oqi0AfgJo6L-vi0glRSaN4IH_n4ZfWcRe0Jb8,4110 +torch/include/ATen/ops/block_diag.h,sha256=Cep1xA7-_a9eLh5NrLfoSlgXpaNHsJDcHIL-6kd12nE,1342 +torch/include/ATen/ops/block_diag_compositeexplicitautograd_dispatch.h,sha256=ZYMRhzAt-9RVShw9E_oW5sfjANvNj0-7HQqrrOBZ-ng,1184 +torch/include/ATen/ops/block_diag_native.h,sha256=rit_2uwtA7HJ_ZAyp1aRuNPVZnN5VIvIXUvLBwaV_Ks,814 +torch/include/ATen/ops/block_diag_ops.h,sha256=JMzfvH6Nbr51898ww9jFzdlxng6FJTcE34ajAI3KZyQ,1823 +torch/include/ATen/ops/bmm.h,sha256=YE5pesQ8-LICeGtu5rwUCKfZwJrQe0KLVYULDNltfrM,2226 +torch/include/ATen/ops/bmm_compositeexplicitautogradnonfunctional_dispatch.h,sha256=ewnx2XAt0IcPK_wkWKKtmepuyJ2aYwIqVbdMneXRpYc,1066 +torch/include/ATen/ops/bmm_cpu_dispatch.h,sha256=H_7IrlmbZpy0GEbX5D2ROi7gSRuqB5AUMDN3O_yZH0o,1197 +torch/include/ATen/ops/bmm_cuda_dispatch.h,sha256=qpStrLwVgPekY8YmvyzPVFm6gGQbH7u4-TdxZ96Uhhg,1554 +torch/include/ATen/ops/bmm_meta.h,sha256=7vvi-eZOa_KSehwvGe2JoCtBORXG2OumHWSTDMDbwoc,843 +torch/include/ATen/ops/bmm_meta_dispatch.h,sha256=bA6Lf-9SSmaQA8NmTSZqHB6bNhYhSV37MpZsE8yJHI0,1199 +torch/include/ATen/ops/bmm_native.h,sha256=3jbVY0aFvauu3JwXCapJCqtc28pf6rm7Y7CUEeHNAXc,1972 +torch/include/ATen/ops/bmm_ops.h,sha256=y0VtT8Uvpj2vsyQ0C2qU0095ePztLntxtK5yZU3x0nA,3402 +torch/include/ATen/ops/broadcast_tensors.h,sha256=JoP7HiuHIYoyXqbDxyjAmJ8Q857aaRJIVR5lEGq2Pyw,959 +torch/include/ATen/ops/broadcast_tensors_compositeimplicitautograd_dispatch.h,sha256=OXMeBBMcXQHsk-Ft353kmJQnuYteb3FxJ0zexnHBp44,1043 +torch/include/ATen/ops/broadcast_tensors_native.h,sha256=q0T5QQa0bFlY6CHaNlkQ22Br6E0vvykNQ-kErS7XY8k,755 +torch/include/ATen/ops/broadcast_tensors_ops.h,sha256=dm2WeOnCxxmONgbID734Lk8PK4qz67MVNAiBsY93qLA,1290 +torch/include/ATen/ops/broadcast_to.h,sha256=xUAhNiHus5FE66lcTbtap3rtky1qIwBtDZ1z4H_iPs8,1705 +torch/include/ATen/ops/broadcast_to_compositeimplicitautograd_dispatch.h,sha256=jMK3yT5Q-9W3CXEKHBSW_oTUraOWY849XK44BqMrD3E,1139 +torch/include/ATen/ops/broadcast_to_native.h,sha256=KDSLk201EBwRnexlAVYjm0XrpsofzAS1-rsg2jmbaGU,769 +torch/include/ATen/ops/broadcast_to_ops.h,sha256=H8AQD-XoKRg2aFd7rAnaXzRWSjSgr5tQjQcV0R4g0Qw,1323 +torch/include/ATen/ops/bucketize.h,sha256=CrAisMsWIsQPwD999GLAFf-r2yR5AX-gGx1kCj1LSXA,2889 +torch/include/ATen/ops/bucketize_compositeexplicitautograd_dispatch.h,sha256=8AlSkC7dBTgN1hyAKqwHvsjYII_msXh0auzx2ba_R4E,1257 +torch/include/ATen/ops/bucketize_cpu_dispatch.h,sha256=bU8i1pR8phE1FOITliaAwa_PmLVq4zqAMxMSqTAOYF4,1469 +torch/include/ATen/ops/bucketize_cuda_dispatch.h,sha256=wZHCh8wert8awZey9TbYhR5KPxwQRD_qGJSzmlxAzJo,1471 +torch/include/ATen/ops/bucketize_native.h,sha256=OCaJ_Xq6Y6kszqdO4-TT9ipjaOq7QxD-7PVVU4dLPmk,1642 +torch/include/ATen/ops/bucketize_ops.h,sha256=5CVTumNf05JifGSCsVRUdHTG5abJVg7pVnXEf7Y4sPo,3851 +torch/include/ATen/ops/can_cast.h,sha256=71vNOsb8uJtHpnn8w4U2gWVHXsOmW3TzP70vMjqiHw8,932 +torch/include/ATen/ops/can_cast_compositeimplicitautograd_dispatch.h,sha256=xwwIEuliU09wyo5A-m2BKy7rWrZ8xiXX-B1__ccpa7E,1030 +torch/include/ATen/ops/can_cast_native.h,sha256=AgwnlPvwSosVqt49JSHq2G0mmxKBinXrV9-IftPYESY,742 +torch/include/ATen/ops/can_cast_ops.h,sha256=xIXV1rmHMZXczKGXp_fXbXhVyB1QBda5u-GTStDu_Y4,1261 +torch/include/ATen/ops/cartesian_prod.h,sha256=M5-Q2uCjPP-0X7ag8A8Ps2qX2uWH2I4hv5y7A_o80hE,930 +torch/include/ATen/ops/cartesian_prod_compositeimplicitautograd_dispatch.h,sha256=vd3MNkCWCabbAC4Cdj1--ThVG8Uz6Zn8Rt0VWXmCYe8,1025 +torch/include/ATen/ops/cartesian_prod_native.h,sha256=mmBRBCffrZfT7yuk1DyKe3FH0UFaozFDG5JAS4Ga7Wc,737 +torch/include/ATen/ops/cartesian_prod_ops.h,sha256=j90wDadDEV--q9-S1sp7zyafjew60LESBHBfmK3Y95Y,1234 +torch/include/ATen/ops/cat.h,sha256=VU2cckbNbBf-kkG7CWx0IZe3mrqqAETm-EbNJEQIzgk,1399 +torch/include/ATen/ops/cat_compositeexplicitautogradnonfunctional_dispatch.h,sha256=alQw12v-X-6Hi696dM_nBlgJT1uj6eJnIwG_vY-rqDM,1067 +torch/include/ATen/ops/cat_cpu_dispatch.h,sha256=t3bHA5XTrHVOZ9zkq-oLJPHcp5I9diRfHQT6Zs_kZ6o,1198 +torch/include/ATen/ops/cat_cuda_dispatch.h,sha256=4SEMu4cZhcLSm3BSz8jTQ1HvEc8ogEPhKzkIvBM2q7E,1200 +torch/include/ATen/ops/cat_meta.h,sha256=VlMv2ne_DNklqcrQGoRQTDQWKtn1AEDQKXuhF-FeggQ,5060 +torch/include/ATen/ops/cat_meta_dispatch.h,sha256=KPwkwoPyp7FKJvBT4cK12Cly9zvleXTJQJ3EKb31svg,1200 +torch/include/ATen/ops/cat_native.h,sha256=V3s4v5Lu15LRQoLes7irbT85_pFP6HATBU_eE0RAX0U,1647 +torch/include/ATen/ops/cat_ops.h,sha256=9DasZ43XH8Yu0N5K824OW1NclcSo_asyzGJTCjLwjpo,1945 +torch/include/ATen/ops/cauchy.h,sha256=BdUIyMufrVKZdcdtycSa5c9yxR7pOq8TjyLP1Q3i0Cc,1787 +torch/include/ATen/ops/cauchy_compositeexplicitautograd_dispatch.h,sha256=MqWVRW9raVK2Px8H7X2QoPtllCZwieulT5zG8OOF8Fw,1426 +torch/include/ATen/ops/cauchy_cpu_dispatch.h,sha256=Lq83Czdk3o1OptTQIevDfVfUF12ILII85d--DAeozQw,1061 +torch/include/ATen/ops/cauchy_cuda_dispatch.h,sha256=p27VKHIPdJ4bO3aaPj55O_-ARbPny9DWmiS46I-xkT0,1063 +torch/include/ATen/ops/cauchy_meta_dispatch.h,sha256=4nxXRVBGeTk_9C4WebFxgl6ukrnojYBjYbXB0f--tbY,1063 +torch/include/ATen/ops/cauchy_native.h,sha256=tWtRqn3-8LBgzbjZfkN9MGdTidUqXy6bGR9FnOyA1Ho,1110 +torch/include/ATen/ops/cauchy_ops.h,sha256=3x6VNCI7BVbuYnPxl4zqzhI_z_VXlR273MVzE7JEpC0,3050 +torch/include/ATen/ops/ccol_indices.h,sha256=MrORAXn8d13FtSy6pNyJrlwrOeybly0_xSA1sGH1OpY,763 +torch/include/ATen/ops/ccol_indices_compositeexplicitautograd_dispatch.h,sha256=cDDpnCkXfXjVfC_ozwJkFNDgpZcOs19C5OWe82xUPno,1024 +torch/include/ATen/ops/ccol_indices_copy.h,sha256=17AXM43zKwwmSuw0oAbMTGDKbDgq73kMXZgnFDrkFF4,1391 +torch/include/ATen/ops/ccol_indices_copy_compositeexplicitautograd_dispatch.h,sha256=iZ8H30ey1RQ9XyY0zbF-Y3CdVZP8oHSQwabAZjAeHZQ,1143 +torch/include/ATen/ops/ccol_indices_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=WX3Aj0RNJpz1tPdGsplgKmiqpO1N6V_okzh2LpW68_M,1055 +torch/include/ATen/ops/ccol_indices_copy_native.h,sha256=jWiE8EgNtDtJkLewzxo53wHTG9oGkudcAuM5FtGUUKU,830 +torch/include/ATen/ops/ccol_indices_copy_ops.h,sha256=ne8hlbcD2XuXFCA5D21a5KW6KjF3xxaBEYewX1sIOek,1867 +torch/include/ATen/ops/ccol_indices_native.h,sha256=JF974sn-ATcW-hgdihkDhoSgCSjK_P5MX3K5W6Ks2Dc,815 +torch/include/ATen/ops/ccol_indices_ops.h,sha256=at44EkIDqFfngxWzvbo7_3EzRD-tg4qRcdNOXEHaVt4,1235 +torch/include/ATen/ops/cdist.h,sha256=iL5d45RRMRSkOQTRE4ZDwBT6BRNfUsWlpN8VQmaa9W4,1037 +torch/include/ATen/ops/cdist_compositeimplicitautograd_dispatch.h,sha256=pBXsj8yog3cQ9cfkrKLFFqg6HiQ8nj1I5JKrsJ2E5Rg,1104 +torch/include/ATen/ops/cdist_native.h,sha256=flat0EyF91YkuiDS38M5UZZPK8qcwN4TInyrxrVkZ5U,816 +torch/include/ATen/ops/cdist_ops.h,sha256=m4G5nSXG6nGcyTMb5JXQ-ykT5LdHG6Ke0Bo3RH4B1_8,1446 +torch/include/ATen/ops/ceil.h,sha256=MZlrN_eZCy8l01wqQWMtGh-6oTCXJF-JH57tFdSgzIs,1397 +torch/include/ATen/ops/ceil_compositeexplicitautogradnonfunctional_dispatch.h,sha256=ESqG0tWQwMmnZ3VPWGke2DPIYIW8TFHIQlP8CrOzoBI,1091 +torch/include/ATen/ops/ceil_cpu_dispatch.h,sha256=XcPCA7xm67Jgp7aKc8RSuSKvLdXPJdnY81ZfYoBDK6U,1174 +torch/include/ATen/ops/ceil_cuda_dispatch.h,sha256=8sLQ4KG3gKTn2SMs6fR2oKSiryfD4mGiEl97Y6Yr1HM,1176 +torch/include/ATen/ops/ceil_meta.h,sha256=iUeIRF6NOMnJU8tC7mBfd1ptLryj0Ge0YF90mLXaV9c,819 +torch/include/ATen/ops/ceil_meta_dispatch.h,sha256=LS39p9XGcg8ZEtX_HwFbqH8MmXgVeurZJNrfkGNENyk,1176 +torch/include/ATen/ops/ceil_native.h,sha256=8V3OfSrNH2aPRls_WtJn4E8G18pzj6l_KdT_SQ3sptg,1252 +torch/include/ATen/ops/ceil_ops.h,sha256=rH-B9IMGmb8ZTyd-T-Ezxem7XUCacUOY4zukuApKVa8,2282 +torch/include/ATen/ops/celu.h,sha256=YI9cBTvXttj5BnX1b3eRKOS4z0J0QMBWKa4yozJNG3o,1613 +torch/include/ATen/ops/celu_compositeexplicitautograd_dispatch.h,sha256=e6fi2FW8mfJSISx9q9IYcnFXR7xyjNShRgczwIl85lU,1334 +torch/include/ATen/ops/celu_native.h,sha256=4DIKLYcIq-5U7kBZH5FdvS1lToV53FCKiE8IFljyg78,939 +torch/include/ATen/ops/celu_ops.h,sha256=E-MukROShG-br6H3QkH8pqDitFUVRmgaIwbPcksPJ2k,2552 +torch/include/ATen/ops/chain_matmul.h,sha256=zyyGGVzI2eN_iHIAPrpU3cFYApy4PP6r4kVXR1YJFSA,1371 +torch/include/ATen/ops/chain_matmul_compositeimplicitautograd_dispatch.h,sha256=LZDPowO23rjc0c1-zkARFLHnq8TZnmK5YzKp_SPESmY,1193 +torch/include/ATen/ops/chain_matmul_native.h,sha256=rMlxporPAKKMdkMI7ohRLq-MZlvqrJNGDNmdfJRnHLc,820 +torch/include/ATen/ops/chain_matmul_ops.h,sha256=HoBLWIluXSfDr7c508vxt0pbzLxdwcAcPe9rITZ-uzM,1841 +torch/include/ATen/ops/chalf.h,sha256=73gO9KgAAnuO-m_4QZfBXC7EpTagK4ezsyObERuXS4o,756 +torch/include/ATen/ops/chalf_compositeimplicitautograd_dispatch.h,sha256=ffBzHy3md47Touge699tOB8jB1odq_fwGQR7TTOm3CU,1081 +torch/include/ATen/ops/chalf_native.h,sha256=YOYoP1QPha3ctTVzyByWHpYvcMca7HYuA7QsWPJisbo,793 +torch/include/ATen/ops/chalf_ops.h,sha256=QnERIcjkeMe80gWW3UAaIJLJFvGTxyNlaiXZm0qPNYk,1378 +torch/include/ATen/ops/channel_shuffle.h,sha256=nxFwNSgOS_oGczkr7i5tPzbWSMTQWhJsQugHvMw7v-E,3820 +torch/include/ATen/ops/channel_shuffle_compositeexplicitautograd_dispatch.h,sha256=_zPnnmChxjcyqxS_D4pQIQ2G7mjn2ZlPAEPc5-DwjTM,1400 +torch/include/ATen/ops/channel_shuffle_cpu_dispatch.h,sha256=7DXG7HBcAQgWgPV7O0ock0eQEsuXdPhtiwSSGg2GSbU,1089 +torch/include/ATen/ops/channel_shuffle_cuda_dispatch.h,sha256=IazzCupurAWVn-TO-RJsPzer3J2FohryAIf3gh4YhOI,1091 +torch/include/ATen/ops/channel_shuffle_native.h,sha256=T6ybPlxvYtuK6GU_lPCskPxhVVHgTF4jU6izLumjuIU,962 +torch/include/ATen/ops/channel_shuffle_ops.h,sha256=2RZPliQ-ZeEOcizh8KEaDDRfQhfNcydx_3tQzb5ks4Q,1991 +torch/include/ATen/ops/cholesky_inverse.h,sha256=vQctG1lXwosH6Zue4rG_axx8Dnus5A6tsyuqPRzES8g,1504 +torch/include/ATen/ops/cholesky_inverse_cpu_dispatch.h,sha256=K6-_o3HxbnZ-xZd7qmKhpr_-PKaK-dxONirdojaj38U,1209 +torch/include/ATen/ops/cholesky_inverse_cuda_dispatch.h,sha256=t1QWaKsQLaECeDi9b9XC4dRhAjQ1V4ut6JA-oVDSAm4,1211 +torch/include/ATen/ops/cholesky_inverse_native.h,sha256=vg-HrtoYqPxfNYZ1YKRWMx9mbcwThGQ5PwTZ7DydjbA,858 +torch/include/ATen/ops/cholesky_inverse_ops.h,sha256=_B8IvLKeTQKb3L5hixxtPFCBRj1eoa7nnGaEz5H4yy8,1957 +torch/include/ATen/ops/cholesky_solve.h,sha256=NxFAUNS0fwuBwiK0l96D5uAFJc6EO-unoGvZL9Rd3jo,1634 +torch/include/ATen/ops/cholesky_solve_compositeexplicitautograd_dispatch.h,sha256=bWQ2HdHF6fm8dU0BeOxtZdTmwuDsWJShRpXkD8zv21g,1328 +torch/include/ATen/ops/cholesky_solve_native.h,sha256=sF3hXLhlwzX1DcCIn4ci52JFuHayrINlQRJKUChGLAM,908 +torch/include/ATen/ops/cholesky_solve_ops.h,sha256=FOc6SIqOTkge-qjztG8h_NowBx3XMhlIBQhI1uoUz04,2123 +torch/include/ATen/ops/choose_qparams_optimized.h,sha256=9gYjgTdh05Ja3Z47oBpaZSsAROZAfoABhRiShk4Zep4,1149 +torch/include/ATen/ops/choose_qparams_optimized_compositeimplicitautograd_dispatch.h,sha256=jzMyOWmFIVMzBYvpHS0UBsVpssmK9IzQdOy5v6OXv88,1126 +torch/include/ATen/ops/choose_qparams_optimized_native.h,sha256=oyMpO6bW5uEQI-YGpGHcqaDFWeZy4-JqyEeFfrmcPh4,838 +torch/include/ATen/ops/choose_qparams_optimized_ops.h,sha256=L_s7Etg6S2ajIJcsnrZHkMf_ZLeKmhipiA_2qk6cZFY,1567 +torch/include/ATen/ops/chunk.h,sha256=di92a3s7psLitFXkeDnjxIeeUUQxbjqpCfho9HHbP44,982 +torch/include/ATen/ops/chunk_compositeimplicitautograd_dispatch.h,sha256=kBhiQa73y2mOFJgygD2kNvVFcO2xQx-TzXRfUW1vRAA,1063 +torch/include/ATen/ops/chunk_native.h,sha256=w1NwgHvt4j-bVWJBQnPz2NDP7a_SPyIQaKJNpNan67E,888 +torch/include/ATen/ops/chunk_ops.h,sha256=I0tHF_LYU3PRK4QQ_XwofsxhrZ7mLUDMQbGuRKG0xpA,1365 +torch/include/ATen/ops/clamp.h,sha256=UjXuzQ0rQ5D9rX0eOACfToNSlFfzc0XIMs23eua1DkM,3208 +torch/include/ATen/ops/clamp_compositeexplicitautogradnonfunctional_dispatch.h,sha256=n6YpO8bwivt-zEz-fIB8mUlqPQe0Y2nO7eJfYO03xLk,1566 +torch/include/ATen/ops/clamp_cpu_dispatch.h,sha256=PfM0xYbc1KvJ_02tJV5di2Z90d468QWCwInaoWNSGAE,2155 +torch/include/ATen/ops/clamp_cuda_dispatch.h,sha256=PQJ_ue1XnHv_apNUTV6haBEirNZbM6HxkgyUejRXnOQ,2157 +torch/include/ATen/ops/clamp_max.h,sha256=o3wVpB2NXwKWEQK2t6eeQ_-3JVdtyzZs8OjF77kNCNA,2549 +torch/include/ATen/ops/clamp_max_compositeexplicitautogradnonfunctional_dispatch.h,sha256=ie0z3Tye2m4vSMwWGngxVCd3y1HYipBORB0Oc75o5b4,1308 +torch/include/ATen/ops/clamp_max_cpu_dispatch.h,sha256=At_nCxGYaphAWyp_w-Tmsk8bJjeXUGcAv3REtTidFyI,1660 +torch/include/ATen/ops/clamp_max_cuda_dispatch.h,sha256=DVRXnKqGD3zERN8HnZPwmMLgy_7MciGlTMpHTM00jQc,1662 +torch/include/ATen/ops/clamp_max_meta.h,sha256=9hHVBEOfmV_ij_ebRX8xIOhMZ7vrBXJFbpJC5fiRJUE,992 +torch/include/ATen/ops/clamp_max_meta_dispatch.h,sha256=EDbmTNOE2EGTzQBXWxnwzhkxnmfUyGfn44FCt6Hay9M,1662 +torch/include/ATen/ops/clamp_max_native.h,sha256=dtVsGAXFhlmUj6Ygzim_D2wFjgcNr7j27e8zSvjN6Ik,1068 +torch/include/ATen/ops/clamp_max_ops.h,sha256=aoyJor9rPU_AAubt8zg1xITFEZ1PQr_2VU5uDlIDlbo,4484 +torch/include/ATen/ops/clamp_meta.h,sha256=Ds3LVlaysfz2ifWHtz9CeVlbtJjKIUTw7V8YxLFCeMk,1044 +torch/include/ATen/ops/clamp_meta_dispatch.h,sha256=0SejF_mlB6RvOOF5fw4FAIE6VVURJ-UqPwyAfdIPOu8,2157 +torch/include/ATen/ops/clamp_min.h,sha256=BnxkOAUPJ22OCQxJXd7JiqIj69_oPRVR100zX_cD7S4,2549 +torch/include/ATen/ops/clamp_min_compositeexplicitautogradnonfunctional_dispatch.h,sha256=YTVWNqV2kSnRehIgJgudxzq0bCXdExG4ygEy5oHphBQ,1308 +torch/include/ATen/ops/clamp_min_cpu_dispatch.h,sha256=TuWQLiy1LK56pDowJMELZGTlKfrrSFncswIM5sEHnd0,1660 +torch/include/ATen/ops/clamp_min_cuda_dispatch.h,sha256=3vXAxTpXxhzYhEBWOlQq60Mhz3DtRBiY5qx22SWHKg0,1662 +torch/include/ATen/ops/clamp_min_meta.h,sha256=U2F4AF2a9goEe0GdBUX98HAJLra1YUcM8qNZd-BdVDg,992 +torch/include/ATen/ops/clamp_min_meta_dispatch.h,sha256=AXd_XLt2rSTQymwAUXpUzQPOdcl9v9qsMovL0TCDIJE,1662 +torch/include/ATen/ops/clamp_min_native.h,sha256=GOGe1C_U2EPdS5vVcbQGXg77kTpYcFP53_tdRXC7vzc,1068 +torch/include/ATen/ops/clamp_min_ops.h,sha256=FL5-taE7AEWGR-yxjBROrNhxE_5pCVFyRXHp1Ftclc0,4484 +torch/include/ATen/ops/clamp_native.h,sha256=mEKETr2TkqT2rEaLlc7uLaVEvELBoI7Dr_P1coUxwU4,1287 +torch/include/ATen/ops/clamp_ops.h,sha256=H3sSF5XmbjkphNtc3my4rYbCGKbySr4YG_5RiFSw0R8,5576 +torch/include/ATen/ops/clip.h,sha256=3V16PBHRjwbL9wzdqltDmelX5wGauKlWQh3O6VUwckw,3183 +torch/include/ATen/ops/clip_compositeimplicitautograd_dispatch.h,sha256=oxTmHj_LAts0BA-AeXK-I5eaVjKHKR7_YVAPifoxRg4,2191 +torch/include/ATen/ops/clip_native.h,sha256=g02MmUoCVfZm9yT_tgU4fFFuhURIkYGc56sl1xanMwE,1594 +torch/include/ATen/ops/clip_ops.h,sha256=BMe1Eug03Rd_tT5LNVHWLUhsYJnGelGggU8BVmpjZtk,5558 +torch/include/ATen/ops/clone.h,sha256=Je3kkQsjxF8s81wb04JH5JdTuHyEyNiEm5WVIF83lwY,1598 +torch/include/ATen/ops/clone_compositeexplicitautograd_dispatch.h,sha256=rsm9snOz_SL9yq2hyPNB5_yAZfy9uubUmtpaQYjo-l0,1349 +torch/include/ATen/ops/clone_native.h,sha256=E4-AIzJAnFDZpb3BjJM_OarNr98sONJCB8zEz9uuG30,1553 +torch/include/ATen/ops/clone_ops.h,sha256=ACo6tfe7mU5hFS10nsTEH-ncIFl72a3yoMfDy7f_BWQ,2132 +torch/include/ATen/ops/coalesce.h,sha256=HUkBjCZQkbHlMqAEYxB10EAA23R78zYeuV1PNzXMmo4,759 +torch/include/ATen/ops/coalesce_compositeimplicitautograd_dispatch.h,sha256=6Fj3vK8f-ZEBSu5coJDVDp_WBAGncjA3MLz8zhwnzI4,1020 +torch/include/ATen/ops/coalesce_native.h,sha256=yNALkZe7lLS0KsWXyhWjZ5QH3cQequU5QqccUw-pkKc,732 +torch/include/ATen/ops/coalesce_ops.h,sha256=Auzn3fDPZT_VNhDZXrCO2RyfKUF9N2PcSAKFdqh3GY0,1223 +torch/include/ATen/ops/col2im.h,sha256=XUy5OcXDjvF4ksnYcAxHnm2j0cyo9-PgE_f92tJAiPY,6097 +torch/include/ATen/ops/col2im_cpu_dispatch.h,sha256=ACKydLEcP4Bs1gr0xyGkYJku9YYXKZh-j8uXG-EUohY,2173 +torch/include/ATen/ops/col2im_cuda_dispatch.h,sha256=8RPo9Y6xqy1jF7b5o179NQfTpjt-eaGUh4DWhz--6Jg,2175 +torch/include/ATen/ops/col2im_native.h,sha256=D2HQeIPCJdCp2sKqGEeXVRfdzre7V_Dq9biCP2JG45w,1490 +torch/include/ATen/ops/col2im_ops.h,sha256=Fg8Tn2LvYSSg3v-p1acri_GpILMVkwPqFWcDCMdcP8Q,2709 +torch/include/ATen/ops/col_indices.h,sha256=UhTewJI5Tpahhah9dPtO7BU67xBGt7LIkK59l4AaPZI,762 +torch/include/ATen/ops/col_indices_compositeexplicitautograd_dispatch.h,sha256=LS3kwnTww5m3Efh1zoVKFlQXwdmEZDfKR7I27Uac150,1023 +torch/include/ATen/ops/col_indices_copy.h,sha256=qbGGfEICE83iwHB8puIyOP42da9aJLGz9LRH_qmd2MI,1381 +torch/include/ATen/ops/col_indices_copy_compositeexplicitautograd_dispatch.h,sha256=KpAD3-aDYpp0EbXjcajvLqRFOFrbiDHLtbp173yN04Q,1141 +torch/include/ATen/ops/col_indices_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=kyvz9dAp3ANmLT_wZ7U8HFop_HMNhWEwTTTOlK0NmJU,1054 +torch/include/ATen/ops/col_indices_copy_native.h,sha256=jG5QInHHTj01b5Czda3_Hmy--j0lcq9EawEm5Mc0GZw,828 +torch/include/ATen/ops/col_indices_copy_ops.h,sha256=uITUMZ_j1lJ0_ae2EU9yhcC6DagGLwH5dMm0PwcWrH4,1861 +torch/include/ATen/ops/col_indices_native.h,sha256=tfghsI3m7QDgmCfVBJW8qLXwmWnaMZduzq_tYDtpKAU,813 +torch/include/ATen/ops/col_indices_ops.h,sha256=j0PeK4q8gFkUj4u-0l1QSlR5Fj1wsXtedcIhUNo04BM,1232 +torch/include/ATen/ops/column_stack.h,sha256=KDwlnOJFAZu7H1oMOPBr0ODH8fSKCmtfwJi6Xqu_EJg,1362 +torch/include/ATen/ops/column_stack_compositeimplicitautograd_dispatch.h,sha256=Vyun0VsVMi824UCKMMajcF6N2T2y8xEl8iYDcWDXQ5E,1190 +torch/include/ATen/ops/column_stack_native.h,sha256=BaW-d9f7JNXtnMfpYwhMdpyTqlrr-tC2dGGevCFHqiY,818 +torch/include/ATen/ops/column_stack_ops.h,sha256=eiVJjA_LdFlQYYxVRpp5SAGb0oZEFOPnjNTCBcAXsaQ,1835 +torch/include/ATen/ops/combinations.h,sha256=ro260zW4yd2SzHmHruOTgoay7DpW9u9K7-fD5GvMVs4,1016 +torch/include/ATen/ops/combinations_compositeimplicitautograd_dispatch.h,sha256=Rw5CyWsTL-m7flEDcRaS8BRQ0JklxENDIwU5V-ZpAbQ,1066 +torch/include/ATen/ops/combinations_native.h,sha256=R9nmXYkuCtUn9glitGGX5MSkU2Ot91vIwov39_aIkLg,778 +torch/include/ATen/ops/combinations_ops.h,sha256=p6GZTECy97kWxlSuyCk6mTecSovhW2AKmWQRJ1ncz5g,1350 +torch/include/ATen/ops/complex.h,sha256=DXkvUGeeVO_Z_Js2XQbFOt_w8LKwWHEF5z789oj_SIQ,1423 +torch/include/ATen/ops/complex_compositeexplicitautograd_dispatch.h,sha256=1dLCA_gDslLar-c3caO9G5ZEsvptzhwAFSpCxdiIq8M,1044 +torch/include/ATen/ops/complex_cpu_dispatch.h,sha256=6B04wdf3hbB0r2ojUWNR9sN5uIibNcYrpJj4Y2LEjkg,1129 +torch/include/ATen/ops/complex_cuda_dispatch.h,sha256=QCWuckNTjNDS0gttroxxLeXtFMLwAXevmTNHJewh_ns,1131 +torch/include/ATen/ops/complex_native.h,sha256=g4fyHkZ3AL7DgNSNl5twLCJevcr7FHYrIg1XG0XJXiQ,860 +torch/include/ATen/ops/complex_ops.h,sha256=XCIxK4uKqqPWgk9A-nhb8lu8zgo1xrjT3ippEfS0_-8,1973 +torch/include/ATen/ops/concat.h,sha256=bsxJE8eXWWHPcIL4wlOwR-HCGP4F1Jv_K7F3xkUo90M,1393 +torch/include/ATen/ops/concat_compositeimplicitautograd_dispatch.h,sha256=lujgQD9o4HC5rvyczeeQ4qR8L4AhQ6C522oVcSoJNW0,1215 +torch/include/ATen/ops/concat_native.h,sha256=0WAG7b4VrjN8TNHInDrxCJz1H1JhQZzVaP9g1zA07sA,834 +torch/include/ATen/ops/concat_ops.h,sha256=Deb2fpVq6OiYaD0pCMVCNWec-_if95JmBAd_aicyXQg,1891 +torch/include/ATen/ops/concatenate.h,sha256=fxoqC0-Uws6Q3adbkSYqQfUHDGZIKw2MrsmeiRnEPeg,1443 +torch/include/ATen/ops/concatenate_compositeimplicitautograd_dispatch.h,sha256=rRKcdij2KmmhOIpnnYNt29mA8PEpFkubF5YCo1cYrfU,1230 +torch/include/ATen/ops/concatenate_native.h,sha256=luzrobyeUnc9XhVUbxH0g8v6VusDz31eA5sd1Wh5Xh4,844 +torch/include/ATen/ops/concatenate_ops.h,sha256=vCaoCDs6S00Mel4gOWoN-_LCg-I2KlGStUFDbLi2e74,1921 +torch/include/ATen/ops/conj.h,sha256=z5HYNIiMQFMMuPuSqQT3hNTA35iCEdiObeJkl8isvQ0,900 +torch/include/ATen/ops/conj_compositeimplicitautograd_dispatch.h,sha256=xaucZb3n9arlmBnnY8PS0G3m-DjQ_jM9QTk-ICKiICQ,1016 +torch/include/ATen/ops/conj_native.h,sha256=lKC1hFYihoj38yKKuTuvZAH1Smr7RK5v_wzRRI7rz2w,728 +torch/include/ATen/ops/conj_ops.h,sha256=dPIJq3gmsnkhqRFOotc2nRHDGMUdRG7MsDv7OznDAps,1211 +torch/include/ATen/ops/conj_physical.h,sha256=UB4Rsu_3y73FI7AFwvtADdzEu1H0pXZ6aX1vVeJAGfU,1514 +torch/include/ATen/ops/conj_physical_compositeexplicitautograd_dispatch.h,sha256=wBzpRJexVfkRRQK6PJ-dAqK3FJsCcXq1BB-WLgy7w98,1022 +torch/include/ATen/ops/conj_physical_compositeimplicitautograd_dispatch.h,sha256=ZFAdnLbq8GILHntlz1E44zUvFS11mk5u8DaeGmp2oyc,1025 +torch/include/ATen/ops/conj_physical_cpu_dispatch.h,sha256=xeWO_OvjgFG6uXC1wAYCCwtfSDooRiI_v96_zX_o3rY,1091 +torch/include/ATen/ops/conj_physical_cuda_dispatch.h,sha256=GOXaMFwmxZoPe-MCpSozemHfBp5ZNVCVhJh0VyOQt3M,1093 +torch/include/ATen/ops/conj_physical_native.h,sha256=GJDM-LZM6olX1S3WgwBcaqbIGxOL9etcgUtedQavEmM,1137 +torch/include/ATen/ops/conj_physical_ops.h,sha256=Kfej-QviSIPW9R16f7dozlD66lCIIphtQxEBTk2HjyA,2363 +torch/include/ATen/ops/constant_pad_nd.h,sha256=tky6JL56A-gbgo0p08GyhUSF_P-aktrLK3wlu88FEmQ,4502 +torch/include/ATen/ops/constant_pad_nd_compositeexplicitautograd_dispatch.h,sha256=9dBNnQvGLW-1W8iIqfjNHf1tv0L8G5Dn1AHkAPQFI-0,1763 +torch/include/ATen/ops/constant_pad_nd_native.h,sha256=IgjF-9RxQY95X5DMQ4d2yXEQYV8av2zFqfrYMpZtQBI,933 +torch/include/ATen/ops/constant_pad_nd_ops.h,sha256=iJqA0wExUBh8R-eRVniRzwZH_F9kYOkg3gM0GM0EHqU,2201 +torch/include/ATen/ops/contiguous.h,sha256=sEXG0CvdIqvTB4SJcgg_LVUyRL_hy4PmR7tyYPDQlao,761 +torch/include/ATen/ops/contiguous_compositeimplicitautograd_dispatch.h,sha256=Um986pl2vq-sZXPZNft5CIPVOk0uZiYKyXQzxExmkPA,1084 +torch/include/ATen/ops/contiguous_native.h,sha256=BC66UB4__Kuarfp-TDKdf49OET07QmJPxj9NlUuUrs4,796 +torch/include/ATen/ops/contiguous_ops.h,sha256=SU_Ieb_PAYowdvOn6gr3jrf36A_c_dJa9jcz-0sXVV8,1360 +torch/include/ATen/ops/conv1d.h,sha256=FpB3TnHXPpjvGvz6mKCcDnzuQXDZHtWwzQmLrPNzzJY,4774 +torch/include/ATen/ops/conv1d_compositeimplicitautograd_dispatch.h,sha256=E1kVxz-w09ZpFgZRC7gDQk8fYOXt1idJpnH8x8wakQ8,1950 +torch/include/ATen/ops/conv1d_native.h,sha256=pVJgyZkymCYvP_cvZhow6Ot5IXrQk8bXMdGTObdI-7c,1250 +torch/include/ATen/ops/conv1d_ops.h,sha256=umiymGU3Y8XrvBdzLpu5E_07LxclbKbhZknidJEjd5E,2931 +torch/include/ATen/ops/conv2d.h,sha256=CKXkJEMnUUPuiqVO4CwHGJbN-1-L1eCoMAefZDz_UP4,4774 +torch/include/ATen/ops/conv2d_compositeimplicitautograd_dispatch.h,sha256=HqsZ03dpQHCBFob6YuHiHWiW5irldJAXo3S4RspeqXE,1950 +torch/include/ATen/ops/conv2d_native.h,sha256=DDiIEflW4T-JigaF-dVM6mNtHu-YQNGmPWMH1-WKAF8,1250 +torch/include/ATen/ops/conv2d_ops.h,sha256=vrRBzu0Iy0kg3zkWxf1APHpZEn5xAk7Nntp-sYfUjQU,2931 +torch/include/ATen/ops/conv3d.h,sha256=e-2yGUt_74wueDE8ypyZ3er--3dxfxyZJ-60478MU-o,4774 +torch/include/ATen/ops/conv3d_compositeimplicitautograd_dispatch.h,sha256=rzC71YCme2QyW4gBsClhLYLSy5fRN7EA3lbSikpRQXs,1950 +torch/include/ATen/ops/conv3d_native.h,sha256=yXo626lnS_W5cPKADvePTtw87q4-Ejg3P6kVJGJ25g4,1250 +torch/include/ATen/ops/conv3d_ops.h,sha256=QBbDlg0mIWC68zezA2tchNdVjkWQIhqS0xpr-9OYd1s,2931 +torch/include/ATen/ops/conv_depthwise3d.h,sha256=xBLhCJAeR4u9tFpFhcPLj6-FnONlqYAt1Tkbl_FOh3w,7547 +torch/include/ATen/ops/conv_depthwise3d_compositeexplicitautograd_dispatch.h,sha256=PFn8ZwTtl5-p1t0srlrT0adDmMAlC87osa393cUTHAA,2056 +torch/include/ATen/ops/conv_depthwise3d_cuda_dispatch.h,sha256=oIvIzaDEozbkqL5gN-2XPYW9I5rL0DUHKXqpbXxsz2M,1419 +torch/include/ATen/ops/conv_depthwise3d_native.h,sha256=nqfOk9kjlW_n2WZNrNM8XsbxKHPHbtqIntfEykq-1k4,1202 +torch/include/ATen/ops/conv_depthwise3d_ops.h,sha256=1uSsEuesUy3mi7aRrvjv7M-DgFKd-1W9SA8VoN1rAQ8,3117 +torch/include/ATen/ops/conv_tbc.h,sha256=6YlWDXf20HAJFZ71ZTgAuWHFX3AOsrd7DhbcL8sRhlU,1674 +torch/include/ATen/ops/conv_tbc_backward.h,sha256=anLSiBIum1LcjCJw2y_w2jX0FoGGkwd_PrHWQ4JWcwI,1157 +torch/include/ATen/ops/conv_tbc_backward_compositeimplicitautograd_dispatch.h,sha256=J-VS2dIXFgdAzkkBI-TYIKE6qz-BI6YtH9w73bJCwpQ,1156 +torch/include/ATen/ops/conv_tbc_backward_native.h,sha256=lC4eZS70oacOuU4ruvttcQat0qFIQosT8bm99PETjpU,868 +torch/include/ATen/ops/conv_tbc_backward_ops.h,sha256=w3uk8PGyiWD7nsGBfhLONWrXR21pcS8VEU6dnCgFZAg,1672 +torch/include/ATen/ops/conv_tbc_compositeexplicitautograd_dispatch.h,sha256=_Ojd5y8COZimt6BdZ3zkOS_nNA-i_8b1H48avSE_r0g,1380 +torch/include/ATen/ops/conv_tbc_native.h,sha256=6SG095g4Gs4K1xEY-SBin3Ep-LLLNhrwfuERYWVE-5c,944 +torch/include/ATen/ops/conv_tbc_ops.h,sha256=XiCJlEdMJaHkU1vccCVQJsn_JBy9uNJOq_fbkffABUE,2249 +torch/include/ATen/ops/conv_transpose1d.h,sha256=JAhJir3ep1UJhFG3LZ5QAOQcUKCtquxGnkALkFBaHPo,3261 +torch/include/ATen/ops/conv_transpose1d_compositeimplicitautograd_dispatch.h,sha256=VBdDHmztns6YRTS7rRUtiSCzokMS2-aXHlzAPPwFG-E,1583 +torch/include/ATen/ops/conv_transpose1d_native.h,sha256=u07kTTj_qQjn36zgYJLoZGoPlxJUVd82HwWkKzjj8aI,1025 +torch/include/ATen/ops/conv_transpose1d_ops.h,sha256=IktNQ2WYCMxL4LNlBZDSBzh0UJcY0y2jGs1sYYHxQaE,1964 +torch/include/ATen/ops/conv_transpose2d.h,sha256=uvcepvf_-rKEnkFNHsp0fMAEn8OaHOLuwEt_q2vd_0s,3297 +torch/include/ATen/ops/conv_transpose2d_compositeimplicitautograd_dispatch.h,sha256=40UtjH50BGmUiNtwXPug-CrrJwIklUNrl9UHig74oos,1583 +torch/include/ATen/ops/conv_transpose2d_native.h,sha256=BdemX3ANVwnMwKqpZRyoKUxFHbv8bNuvWxHCzNxmKas,1025 +torch/include/ATen/ops/conv_transpose2d_ops.h,sha256=OXLGzbUYWL6yMHzrdTQ5bfEpA4dxAq3fL743GdnckWE,1981 +torch/include/ATen/ops/conv_transpose3d.h,sha256=vyMBb7wZLXd1rVyHijWNrcttWiZ178_vscrKmI69q_A,3297 +torch/include/ATen/ops/conv_transpose3d_compositeimplicitautograd_dispatch.h,sha256=JTWuU6fcvfl6wFZ_m6PFWihHTgvs3hIcvxIv6XjH8A4,1583 +torch/include/ATen/ops/conv_transpose3d_native.h,sha256=6Y4J-kElFHC9b-LhJyTOZDEJZNUu8uyVuiINAACXHIw,1025 +torch/include/ATen/ops/conv_transpose3d_ops.h,sha256=XwwUK4P9gUFVU3qKqk3dMHjy07xtScGfoYPQMCZ7fXo,1981 +torch/include/ATen/ops/convolution.h,sha256=T_AT68SB3_vUgd3p9xaF-YLIWzqZ5nqy1OLG-s5xfJE,8340 +torch/include/ATen/ops/convolution_backward.h,sha256=B2ni9MyJiW9OTZtKzR7tdAXDtnUUhMYTkC0G1MUzu7U,11741 +torch/include/ATen/ops/convolution_backward_compositeexplicitautograd_dispatch.h,sha256=nlvEzclraYLJFFH6D6OYFeXqrJdPV2oa68MVOVC15hQ,3568 +torch/include/ATen/ops/convolution_backward_cuda_dispatch.h,sha256=UydXMamLCUDCfix1fivLE82ANm3ofVAa0MlrdJbktIU,1700 +torch/include/ATen/ops/convolution_backward_native.h,sha256=qte5LkqG4oSH7g-idIJwa9QkN55YpnugwJQYCYlRfAg,1521 +torch/include/ATen/ops/convolution_backward_ops.h,sha256=dDOBUtbPTcFSE-BY1C0_IWYPZCMS_OwXk-84qaAS8Mo,4236 +torch/include/ATen/ops/convolution_backward_overrideable.h,sha256=gQJ26cofeCQ5dbAH7_o8oVZZzpsr7VYfsdsPebqwNwA,10938 +torch/include/ATen/ops/convolution_backward_overrideable_compositeexplicitautograd_dispatch.h,sha256=c5J7o6Eu1ftfXXjQ-FcuBIJjsBE6BpJhoydpt_vT3gA,3421 +torch/include/ATen/ops/convolution_backward_overrideable_native.h,sha256=WjMIlhmaN1hdVb6igqyq7s5x5Y5oKkH_74dFInSPP9I,1472 +torch/include/ATen/ops/convolution_backward_overrideable_ops.h,sha256=6KzPByXqTqDZSvawFy6Od8gX0s4Wl3n1NwxyqeEXVUg,4091 +torch/include/ATen/ops/convolution_compositeexplicitautograd_dispatch.h,sha256=4wxazokwjYrBemMdVsseg6JsIoc58kcGpA6cqBegfjc,2757 +torch/include/ATen/ops/convolution_native.h,sha256=4HREAKXNdZe2v_Ht1dB60YKm_snHDWDR6SUyBqzqXZ0,1265 +torch/include/ATen/ops/convolution_ops.h,sha256=GGT5WoKn2TZczrNuUVr9L-n6jHRAx-S0xddAFRfAzvw,3353 +torch/include/ATen/ops/convolution_overrideable.h,sha256=Z_DiL3m_Bp3eBcFPqmDNLymMxtHywMvaUw32RjzpHfQ,8743 +torch/include/ATen/ops/convolution_overrideable_compositeexplicitautograd_dispatch.h,sha256=3woHMh0AGzgT7FiKb6M7cjP-vs9sIJthLFmcMemd_d4,2835 +torch/include/ATen/ops/convolution_overrideable_native.h,sha256=dQosXkrBwVzKIXmgITJNWwNEE6F3S3NSC6rFY_lxNhM,1291 +torch/include/ATen/ops/convolution_overrideable_ops.h,sha256=WrPe-SRsIwV5Dn5IzXFy2ijPQEoYf80A4MTOEaYEDCo,3431 +torch/include/ATen/ops/copy.h,sha256=9IFZrggWuRygYxK_DSlxTHdwkdqiGtPLJNkrw0j5lVA,1570 +torch/include/ATen/ops/copy_compositeexplicitautograd_dispatch.h,sha256=yd4c9qsm49ZfduuiiKCOuag6evx12urQWhjes38lePU,1307 +torch/include/ATen/ops/copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=PiE9IE-N7gy_T3bBlnj2iam2gKwBY68AdtfwReCceV4,1091 +torch/include/ATen/ops/copy_meta_dispatch.h,sha256=9CXIF_9FkwBHGzTEqSC19DSviTx4QpMMTukhNF5O3T8,1023 +torch/include/ATen/ops/copy_native.h,sha256=pAw4pEXEnyPyLWCnkddlH1FWsxn3h-IOy2ozLvR0oZw,1539 +torch/include/ATen/ops/copy_ops.h,sha256=SqoiiThKFhs1-Cuu5IPyBd0BnBpjY2Nknti1PWXith4,2729 +torch/include/ATen/ops/copy_sparse_to_sparse.h,sha256=EsPfiSSI2z0HPiaS0EkuvsYSyiLzLDCjNEmB0Dw3Ns4,2032 +torch/include/ATen/ops/copy_sparse_to_sparse_compositeexplicitautograd_dispatch.h,sha256=oSGqNJnxA3jU4cTLLEzKkieWoi6-2eEF19PPYFKaZC0,1361 +torch/include/ATen/ops/copy_sparse_to_sparse_meta_dispatch.h,sha256=5Y3Vl2EFwH6MlqATX2rKhHVctCoaOkfURmjivNgSfg4,1037 +torch/include/ATen/ops/copy_sparse_to_sparse_native.h,sha256=Yb0mw17GEVjAVTFhkXlzfoPW57ACBqfYjkbkFDDoP78,1035 +torch/include/ATen/ops/copy_sparse_to_sparse_ops.h,sha256=UrJKUc6ySxZLQ4WQPexNwRCR4vJ1smxTBSQbJwgD1wE,2882 +torch/include/ATen/ops/copysign.h,sha256=me1H4Am8APHMzqf5ICqVJKms-ffXw4nNf0kIbfzvpiY,2182 +torch/include/ATen/ops/copysign_compositeexplicitautograd_dispatch.h,sha256=sFzlfsS4RrTYgSn9LBJ2eAUPEFbANmM5lcZp1YSzfrs,1338 +torch/include/ATen/ops/copysign_compositeexplicitautogradnonfunctional_dispatch.h,sha256=8-BnzmjOy6TU_KbXL5zju4t4Sdqzxf88GJX6uJhrEcU,1151 +torch/include/ATen/ops/copysign_cpu_dispatch.h,sha256=wOvjvuKqOj6_6FaRXEpnbr_3rI-1NrxhTLNhwl2yRkc,1294 +torch/include/ATen/ops/copysign_cuda_dispatch.h,sha256=o_FPMuq37qTS1TlZA-I0fF5NDE8vMQhZVULMsopyCJE,1296 +torch/include/ATen/ops/copysign_meta.h,sha256=7EMbc8F9wZ1FCQqbI7xMzb8MlueVGJXkt7afAKQ01Y0,856 +torch/include/ATen/ops/copysign_meta_dispatch.h,sha256=-7RHCxwfC0Rr32etOAx6tjdoSCiPU9unf06IUZbvLI0,1296 +torch/include/ATen/ops/copysign_native.h,sha256=GRfSWimfGAZmxrxMhEezdcR0FartkSZ9v_7CbRN01OE,1156 +torch/include/ATen/ops/copysign_ops.h,sha256=zdWMGeETcznuIDgz8OtzfU-IyHoENPt0z08XFmAi1rw,4542 +torch/include/ATen/ops/corrcoef.h,sha256=0qjbqFk4uQ5FgzxfNnpTr2_YfzaVsIeTI8NeMgXMjc8,899 +torch/include/ATen/ops/corrcoef_compositeimplicitautograd_dispatch.h,sha256=0i-bG2qHZBXnRcmf_R7-BQohGRMost700wsgjzTNuVk,1020 +torch/include/ATen/ops/corrcoef_native.h,sha256=MdueadJ39JBThzKhfUMeCE7gCGM5XTqFI_Fu4p64TdE,732 +torch/include/ATen/ops/corrcoef_ops.h,sha256=zy8DAi7nkPpTtb2f5sEeFn6iFYTkxRCo-AlXBQUf28s,1217 +torch/include/ATen/ops/cos.h,sha256=BHXeo3u6ALuH8dzM7zRDZlGJsGUsHc6OshSHth871Cg,1384 +torch/include/ATen/ops/cos_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Ll50kBkGvgqgl24hIZ5xTHPALioiuXnc8q-lgWyIjWg,1089 +torch/include/ATen/ops/cos_cpu_dispatch.h,sha256=68QbnS7-UCBSOPAMNcVZofvZ1x3qSYnwaHvNxQwVqtY,1170 +torch/include/ATen/ops/cos_cuda_dispatch.h,sha256=wAbf4O9Gl9TUxFndRA-IK1cv3PPocMVZJiIYnj3pzoo,1172 +torch/include/ATen/ops/cos_meta.h,sha256=lazB6zUAyI2CFce3snNR6UUypB6lYrx9P3-m4EaDH2M,818 +torch/include/ATen/ops/cos_meta_dispatch.h,sha256=4jpRTWRwv6SmK0F6exDBc0oLYPX-im5Zq51mo2W-Sgo,1172 +torch/include/ATen/ops/cos_native.h,sha256=aj0-ZwAgwKGtPsN-gP5HetE349YF-PwvW82y2pGXAbM,905 +torch/include/ATen/ops/cos_ops.h,sha256=f5fFhL-FgY5qa0W6PYH7eHqsYawB_s4lV457J9SsLvQ,2273 +torch/include/ATen/ops/cosh.h,sha256=qZu69Tj_PTz4iPbqA2oa-uxM8WB_mXNUk_DbO9gIsEY,1397 +torch/include/ATen/ops/cosh_compositeexplicitautogradnonfunctional_dispatch.h,sha256=SLP7Oa7IR71jJ2JwqaAI3zSMivmUiODLFPUI3nPelEI,1091 +torch/include/ATen/ops/cosh_cpu_dispatch.h,sha256=0Uay4rVvvdOSKXmawx5qGTAHqJ9FLVV1ntCqW_34Aj0,1174 +torch/include/ATen/ops/cosh_cuda_dispatch.h,sha256=F0X6Ly-_2Q24o_KC13Vebq_kHTMeGmIdFd_LMLK3iUA,1176 +torch/include/ATen/ops/cosh_meta.h,sha256=UGgAuh2ebNPHQWZGHGidT_IxgWGB3BIoXP8AUndFkLE,819 +torch/include/ATen/ops/cosh_meta_dispatch.h,sha256=Dk3RySp1Qs4DgArnkBgrJcMFE4uNVwP60JXJhuKlBGo,1176 +torch/include/ATen/ops/cosh_native.h,sha256=dw0IVylLDazt4dU1falh6sUiAw-v9XKxjHk0Iiug1hM,844 +torch/include/ATen/ops/cosh_ops.h,sha256=YKb6TtpeD-WdYmI6CtI1FlSahTzblrKtdudzNm-vW-M,2282 +torch/include/ATen/ops/cosine_embedding_loss.h,sha256=WsHFO6_Xp_raI8dSSpIWFXv73K86qqIjsbtorcWYPPU,1172 +torch/include/ATen/ops/cosine_embedding_loss_compositeimplicitautograd_dispatch.h,sha256=mSH80gavA9CmFwPvsCFwXgxxxW-b6WuWtopR736e0pY,1147 +torch/include/ATen/ops/cosine_embedding_loss_native.h,sha256=bA5uanPyztttUAZuu_kQHr6-O-m7-luR40_uzyeCI98,859 +torch/include/ATen/ops/cosine_embedding_loss_ops.h,sha256=BQCnGAH1BETytucpsr6nchDR6nrRSPm1QsWqpB8gKqc,1563 +torch/include/ATen/ops/cosine_similarity.h,sha256=37E2HMqSTVJCgxsA7_-RnFbYIoA8qheETENxKf5Ry3Y,1038 +torch/include/ATen/ops/cosine_similarity_compositeimplicitautograd_dispatch.h,sha256=5KP-xURniNVMjkIq0tsuZv-VkUgouZRwE4WBGI0OIOo,1083 +torch/include/ATen/ops/cosine_similarity_native.h,sha256=U4EMGswPevu4XGODLx2W1Qfgqbs0GyY6yu1aLxU0b3g,795 +torch/include/ATen/ops/cosine_similarity_ops.h,sha256=Pz5lbF22TgynzdWhrht5IgYct6y65eDsr9GLXQkZiNQ,1410 +torch/include/ATen/ops/count_nonzero.h,sha256=d0w7bunieMNtbp0lzkaDOBEGwPcJcd_v8myRR8VRkGg,2302 +torch/include/ATen/ops/count_nonzero_compositeexplicitautograd_dispatch.h,sha256=7Rlu6hmK_-0ETXzt0wQBe0RXt37eypt4o68JURX6Ia0,1529 +torch/include/ATen/ops/count_nonzero_cpu_dispatch.h,sha256=SsWKGRDePzawMDoAHdKefvCxAsDUC2fvKt2zm-4sKhk,1002 +torch/include/ATen/ops/count_nonzero_cuda_dispatch.h,sha256=Aot9cdQZU_lr-VCsOvbdr3GmqHeXuixRvO4UUKmHiMM,1004 +torch/include/ATen/ops/count_nonzero_native.h,sha256=V0vbET8kcow8J4Z4XsbtvjuuCmbYIBPw6yk6BVwki6c,1188 +torch/include/ATen/ops/count_nonzero_ops.h,sha256=6APJKICqqKebl97mLbq9pz02pw2G3q3Sy1nW9A8IKhc,3388 +torch/include/ATen/ops/cov.h,sha256=vPAA-2SYmIN3QdQXagu4yNKVJzVPLnt343LOkS0DKf0,1098 +torch/include/ATen/ops/cov_compositeimplicitautograd_dispatch.h,sha256=L0TfAbwQ8q46g5PQqOhKRx3MxJm-vS0oRTJAJco4PiI,1135 +torch/include/ATen/ops/cov_native.h,sha256=uvTMkhEtAx5aw3VWZPA8zFGmMylhIpRqcV2dqughjQ8,847 +torch/include/ATen/ops/cov_ops.h,sha256=wKqKIKd01yoh6bIAUXjkyuv3Rn9SXZqWMPex22wIWPg,1576 +torch/include/ATen/ops/cross.h,sha256=BHADy1TIXHnGLOD66PtDynfbo1ObOb_ILEcakBt4OMo,1592 +torch/include/ATen/ops/cross_compositeimplicitautograd_dispatch.h,sha256=-cBQ1nVjOc0ZPfYlhqwL3n2kup-T34TAHEQ6z_dn4Qs,1370 +torch/include/ATen/ops/cross_entropy_loss.h,sha256=ddynqf3sj80UXPUgN7-bXATfpqHBsSRJ15FPltg46Fo,2687 +torch/include/ATen/ops/cross_entropy_loss_compositeimplicitautograd_dispatch.h,sha256=Hnb8T__Ojjjt6Igs4KSo8Kj6Q4ufebe70mmJ52obmss,1443 +torch/include/ATen/ops/cross_entropy_loss_native.h,sha256=eEcoLJeUZmwKNVPu-8gOczEcqWoere8z5L7T8jNMMMI,921 +torch/include/ATen/ops/cross_entropy_loss_ops.h,sha256=CKzht_utb3Zt1CQBk42RQi6l9oz9KOKjo3HidAt7ncI,1723 +torch/include/ATen/ops/cross_native.h,sha256=ope4SGodbjJuFmIZjwzmr3q8XboI-cA9d-0EtIiunys,933 +torch/include/ATen/ops/cross_ops.h,sha256=VayqhwkW5gQMHFLVYymi-6S6b4OjmZM5q7MiMaynyB4,2169 +torch/include/ATen/ops/crow_indices.h,sha256=RZuzgJu8NV_D4320naG0VvM_jJEA73hu2KNvonoEpXg,763 +torch/include/ATen/ops/crow_indices_compositeexplicitautograd_dispatch.h,sha256=PWht7xnhUGSw3mzQ-K2_hRCv89j9TVpthsXkYEWqY2w,1024 +torch/include/ATen/ops/crow_indices_copy.h,sha256=jd5mUmoep5sh5-GWLwSQjDKFuDPkug6i3eYV5XObpww,1391 +torch/include/ATen/ops/crow_indices_copy_compositeexplicitautograd_dispatch.h,sha256=DiOgETwSXBAShC_ID8rvhMwICs88Gdf7ozmjcP0uLIs,1143 +torch/include/ATen/ops/crow_indices_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=xz-nFw_N1MLsjf3PT3SKP7B_AmUCjhI421Ty0uUCjCI,1055 +torch/include/ATen/ops/crow_indices_copy_native.h,sha256=HhbESces5CbHQqYVNKrE9lG-KI3JnBbvyh86E9Iesjk,830 +torch/include/ATen/ops/crow_indices_copy_ops.h,sha256=I8yrMGgpxGOQwEuSf98XJY7wMg033Dm-HwB75wtlGmA,1867 +torch/include/ATen/ops/crow_indices_native.h,sha256=EP6wm-BBTVITZGoensi-Uq0kzCF5aIFsdaO_P9AHx5U,815 +torch/include/ATen/ops/crow_indices_ops.h,sha256=4L8f2oAOgIdZv3GlOsK7YaBwZEyipj8Yhbod6CMjPyE,1235 +torch/include/ATen/ops/ctc_loss.h,sha256=B_h1qP3Cy7TJ-PCwTsT2dMju0mB7do5v9TM1woOCmug,1836 +torch/include/ATen/ops/ctc_loss_compositeimplicitautograd_dispatch.h,sha256=wgQuO0jY9Aj03r8w7CoS2OKrfclyHBWWUadBtc3RMKA,1438 +torch/include/ATen/ops/ctc_loss_native.h,sha256=Ah7xAT4JZDyXuEvFN3Z8i-YrgnhgTkAkSYoy0i9GK1M,1150 +torch/include/ATen/ops/ctc_loss_ops.h,sha256=K09pvc3nrEiAP5xedKaIkpcy1_Eh9jKL3h-jGi-ZT48,2788 +torch/include/ATen/ops/cudnn_affine_grid_generator.h,sha256=qxS-5E1sDi-9xQ6DFCNG4-roAIt0CHsWGZWTDx66CZw,1757 +torch/include/ATen/ops/cudnn_affine_grid_generator_backward.h,sha256=IIwidjfjH-3k0fBHxTUJeX6IRaQZ2QIhByImcL0HnU4,1844 +torch/include/ATen/ops/cudnn_affine_grid_generator_backward_compositeexplicitautograd_dispatch.h,sha256=vkKeJj1-IyQcqUz2E9DSH5gO9jOZWUqPLn1t9ZwGaz8,1269 +torch/include/ATen/ops/cudnn_affine_grid_generator_backward_cuda_dispatch.h,sha256=hk-ssJZpfqR4cyGxPLf1MqRx38sAbmYYdHbIghBb0RQ,1050 +torch/include/ATen/ops/cudnn_affine_grid_generator_backward_native.h,sha256=H8C9TxsJeROesJJ7ZEhKuioDZ_Qcp8E8q4oBcYUswYY,956 +torch/include/ATen/ops/cudnn_affine_grid_generator_backward_ops.h,sha256=7yXOrlMRZjkGrAz2I63ZZUgUTY9e0QNe_0K3hncpEzM,2296 +torch/include/ATen/ops/cudnn_affine_grid_generator_compositeexplicitautograd_dispatch.h,sha256=1HLOOgxvkoaJEGYh8mbi-9GY8pZYgkNsd5e5gpbDKyQ,1253 +torch/include/ATen/ops/cudnn_affine_grid_generator_cuda_dispatch.h,sha256=eFpG6tgTaDq5Esr_KvKZEl0YWqIeOxvebgnlzSt-LOE,1042 +torch/include/ATen/ops/cudnn_affine_grid_generator_native.h,sha256=kWvXFSZE5cRYz9bKVetxtWMZJ0JbZ0XqFAPORde4G1Y,948 +torch/include/ATen/ops/cudnn_affine_grid_generator_ops.h,sha256=UKpG7zlY03h5Esrv1Hu_Q1ETJcwTyZDSlOFemhOEmUs,2242 +torch/include/ATen/ops/cudnn_batch_norm.h,sha256=c4nml8LM5eZnNPaROEAGZfyK39D_mJHjwxgPNDVZKDQ,3277 +torch/include/ATen/ops/cudnn_batch_norm_backward.h,sha256=B7MlxYbauHW5DZVRDfESsNlZ8esRt8SDDcOODubrmJo,3469 +torch/include/ATen/ops/cudnn_batch_norm_backward_compositeexplicitautograd_dispatch.h,sha256=yzySpEs_VsDkbRFX6tPFO6utLsVJ7JEC-yIMszdADYA,1919 +torch/include/ATen/ops/cudnn_batch_norm_backward_cuda_dispatch.h,sha256=viw1pA-IaiW3akgmWzYKC4ckqbY1e6f4i83-PK6Idg4,1332 +torch/include/ATen/ops/cudnn_batch_norm_backward_native.h,sha256=ih9R5zG1pNfA_yjr8tSC4AYmGB_lvAhFNYXGioIvzwQ,1563 +torch/include/ATen/ops/cudnn_batch_norm_backward_ops.h,sha256=RHozn6S92sE4hOw6u0nqC7Z6pEQannh7LBDm8ox7k9Y,4268 +torch/include/ATen/ops/cudnn_batch_norm_cuda_dispatch.h,sha256=1eONKh-tnpRZ45CfOBR84l8qwqElzE95zmh3_nMxKlw,2137 +torch/include/ATen/ops/cudnn_batch_norm_native.h,sha256=NKoxNq9YjXgOQI77f1GglH1yRD_JTtX4YEycpzr3XJY,1456 +torch/include/ATen/ops/cudnn_batch_norm_ops.h,sha256=SEVagF9WREs3GhSeNbHCKJ1eXrOQzl7YUbM40OUgmzw,3955 +torch/include/ATen/ops/cudnn_convolution.h,sha256=OM0kl2IlUCdQp1UTBGrMuCeJHQGRF1k9xdknFDH-JsE,7890 +torch/include/ATen/ops/cudnn_convolution_add_relu.h,sha256=Vzsd9CatvFsFIntpxIRs4ovWOlggrWNc0Y3ZL3AELSE,8469 +torch/include/ATen/ops/cudnn_convolution_add_relu_compositeexplicitautograd_dispatch.h,sha256=lR4_Itws4_cAovSsVXj3Hle9aZ4rkCb9PW7XYkpd-Y8,2304 +torch/include/ATen/ops/cudnn_convolution_add_relu_cuda_dispatch.h,sha256=DKESKHV8F_wgcsQbeWq8p6lmVUGB6r6ZJfQjzL9TtIw,1543 +torch/include/ATen/ops/cudnn_convolution_add_relu_native.h,sha256=9WL0i3Y8HOO-htpEZmjPgiCA34yWaNQ2KONeI2tsVd8,1321 +torch/include/ATen/ops/cudnn_convolution_add_relu_ops.h,sha256=iJyCBEidjokS7w_k1JYljxgdBHVj0pahch3kdh--ous,3511 +torch/include/ATen/ops/cudnn_convolution_cuda_dispatch.h,sha256=ONsQTYmdbG564qqWELM-2qTX3qGnRGiburJx6Js8OMU,2505 +torch/include/ATen/ops/cudnn_convolution_native.h,sha256=GS1yg7BaKzX4p5EFU6eeXsxXridPLQNzgDiRUnRVqDA,1172 +torch/include/ATen/ops/cudnn_convolution_ops.h,sha256=6oWC8M_5hEGtUCMgkTeNDPM0uP8Sn4c_EFjqyxQ0Ew8,3117 +torch/include/ATen/ops/cudnn_convolution_relu.h,sha256=5_pSqRBIx7YBSrREXYJnxvYOyCgQ2hzeXv-o9m3jL_8,7295 +torch/include/ATen/ops/cudnn_convolution_relu_compositeexplicitautograd_dispatch.h,sha256=aKstaYPvziQRw-RoN8CyLULQSvSpfhbsPG1SKTyVu-w,2028 +torch/include/ATen/ops/cudnn_convolution_relu_cuda_dispatch.h,sha256=xcHzaS67d-UWObaIwpywtm2fuz9-8CTLNpBLukJVcBk,1405 +torch/include/ATen/ops/cudnn_convolution_relu_native.h,sha256=2euB-QaPSv_l0hlaBQfelA32UbESfahXJBaXY5j9d5Q,1183 +torch/include/ATen/ops/cudnn_convolution_relu_ops.h,sha256=0P1PLtK6-AWtMCv6IqsxPqiEyXUNP-JU-3bAJpMZ_KA,3063 +torch/include/ATen/ops/cudnn_convolution_transpose.h,sha256=DJY4r-QKnjUxWIpL4CQhpIRj-VyV5N2EWPHmr4x52lg,9106 +torch/include/ATen/ops/cudnn_convolution_transpose_compositeexplicitautograd_dispatch.h,sha256=7ObqRzFhPJ_ALLtE1gJ8I-JHNkrYjS2o8nkcgC6wikk,2228 +torch/include/ATen/ops/cudnn_convolution_transpose_cuda_dispatch.h,sha256=CTYVKHl6FE0Cf_jitF2OKRWhOaHLSQAVf09SdHD1EB4,1505 +torch/include/ATen/ops/cudnn_convolution_transpose_native.h,sha256=V5gpemtkwcfYcfogCadv7J_PGrwX4IhiDfOZc9Jw9TI,1283 +torch/include/ATen/ops/cudnn_convolution_transpose_ops.h,sha256=3XgexstO1s-xy7Dxq7X8LQ_MWuEqPo7lrWjC_LSkchs,3413 +torch/include/ATen/ops/cudnn_grid_sampler.h,sha256=Lc6JCvM5hznRbdLAQIfB8-nUaIYMG85X2zAvsHH9pfM,1540 +torch/include/ATen/ops/cudnn_grid_sampler_backward.h,sha256=B-UN2i5ZSvBUXpy_NyY9ii6LZREOjbMqEvi9DAyMV5o,2045 +torch/include/ATen/ops/cudnn_grid_sampler_backward_compositeexplicitautograd_dispatch.h,sha256=LMu2qZEe3O6-1CpDfnXTp8w6YRQpFibWn4WhPbXj9b0,1371 +torch/include/ATen/ops/cudnn_grid_sampler_backward_cuda_dispatch.h,sha256=zO6G7ZtXGAbLJd6mAFby9ZmweX5DM22NrjrwEdbnyZs,1079 +torch/include/ATen/ops/cudnn_grid_sampler_backward_native.h,sha256=T3DS2ZipefEWGs609-pFifzjqDH3TdHcqGEOZb9ap4c,1036 +torch/include/ATen/ops/cudnn_grid_sampler_backward_ops.h,sha256=qseTid59T9rZRLmSLvO6Tx1rafE3y7bZFO1sAmmOG6k,2573 +torch/include/ATen/ops/cudnn_grid_sampler_compositeexplicitautograd_dispatch.h,sha256=F9LJfrknJEeczFmAo46rExBd0-dhe76QM3HvVlLZouI,1195 +torch/include/ATen/ops/cudnn_grid_sampler_cuda_dispatch.h,sha256=MRAnv5uytQfRxyCMXO2tCjuEO36a-PMLA1RFRKPajkM,1013 +torch/include/ATen/ops/cudnn_grid_sampler_native.h,sha256=ZhL3WUeU1RXO3Fn_sweRJYhaJtEfoMF_DIg2wq0AvAk,890 +torch/include/ATen/ops/cudnn_grid_sampler_ops.h,sha256=E3zLe7WmfhmNmmGc-Y34gJodz8AOkKv1s0w9qdYZh9E,2046 +torch/include/ATen/ops/cudnn_is_acceptable.h,sha256=poqK07lhDhmj2DzjVoE0wm__UjQJePEk6OzOQumq2t0,935 +torch/include/ATen/ops/cudnn_is_acceptable_compositeimplicitautograd_dispatch.h,sha256=h_JyK8XS2h8o2v76O-_Z2feOC2n_FF5bIT7MjpTDrgw,1025 +torch/include/ATen/ops/cudnn_is_acceptable_native.h,sha256=ROICuxcj7oHyAQ-45H_iBdZm9CFv5D5I2UJ5YdM4MdM,737 +torch/include/ATen/ops/cudnn_is_acceptable_ops.h,sha256=_N9AGGY17yLQSKzz4XF05CE1MvHdq8iG7Sap97bm_1U,1230 +torch/include/ATen/ops/cummax.h,sha256=xCYGrYbavbAbfCA6s9oFkpQv7MFg4hpt3wPM1J07LTQ,1644 +torch/include/ATen/ops/cummax_compositeexplicitautograd_dispatch.h,sha256=s80yG1PVRFVODBszuUhVVccF9fBDI3f4z71ZDi1k8YI,1343 +torch/include/ATen/ops/cummax_native.h,sha256=uMz6-vcylZDCzn6_4QV-ngy4IZWpsrJGv61SnyvOSvw,911 +torch/include/ATen/ops/cummax_ops.h,sha256=Q9buel_fCqJw9pqw3dkVWicTrs9Jep0FKnuq1uGfeeU,2186 +torch/include/ATen/ops/cummaxmin_backward.h,sha256=q0AaydzvsTclefcXvylLDRkNLXO6oVAp1sITjNubO5Q,1066 +torch/include/ATen/ops/cummaxmin_backward_compositeimplicitautograd_dispatch.h,sha256=C0GX2WFeO1HG5bGWJtiqzb4-j1o80Ri-p_FedPNvH48,1097 +torch/include/ATen/ops/cummaxmin_backward_native.h,sha256=QORI2zgh1-BLiAFLhTJTnZzT8TxM1-p0k9H-UXd7Xjw,809 +torch/include/ATen/ops/cummaxmin_backward_ops.h,sha256=Jb65S8JKd0otaKmK3-4tyzvezAAiQPsb074Oq7_RqFQ,1469 +torch/include/ATen/ops/cummin.h,sha256=mrgyiY4r2Zi_yOHUTW3Iki4FSOfOJXBvP9sqGJ23xUE,1644 +torch/include/ATen/ops/cummin_compositeexplicitautograd_dispatch.h,sha256=64aTbWHfROi9jAvlBp4_hYiG4tWEh5BTcR-4WqVzBl0,1343 +torch/include/ATen/ops/cummin_native.h,sha256=PihIAHiRkwkAc579LNUJhfbnbxYD87qIdu_xHMAKrbo,911 +torch/include/ATen/ops/cummin_ops.h,sha256=u_8ThA2H5VdQrI2tCd_-WjqGBMJlUE0Q8FcrjxcbPZg,2186 +torch/include/ATen/ops/cumprod.h,sha256=WVLoGaeb2qRikRxke4cBcGhct6ZeQClfdv2K_ueJRrM,1615 +torch/include/ATen/ops/cumprod_backward.h,sha256=KBjrfpKaNuGG5Npm5c4UZhUQScQVe_ocO4e3vL1fT90,1055 +torch/include/ATen/ops/cumprod_backward_compositeimplicitautograd_dispatch.h,sha256=DBkR8KzDXzHkriO3ntXkvZnqHej6PHuOGNpDVb6iPFs,1094 +torch/include/ATen/ops/cumprod_backward_native.h,sha256=IiUsG4O4ABrUWp7sV24j0O1pNlaJe288wAIum8VlNPo,806 +torch/include/ATen/ops/cumprod_backward_ops.h,sha256=BoUg4yUpDoXpHS9hsxkXrWdeb3baxPgdQn7Tgot6wUY,1460 +torch/include/ATen/ops/cumprod_compositeexplicitautogradnonfunctional_dispatch.h,sha256=K7Dr2h-pj8gQ06oCMTyjl61pT3GQ8iK1L18ygaViqMQ,1231 +torch/include/ATen/ops/cumprod_cpu_dispatch.h,sha256=j2ThUdvWFBBuXRjCk3QebhDv7ZcCFfP-_XGjIlzDaMc,1439 +torch/include/ATen/ops/cumprod_cuda_dispatch.h,sha256=igJVnpvNugE4nDkOh7RBY_aDdEYhlc_Px3KmUC2Lqm0,1441 +torch/include/ATen/ops/cumprod_meta.h,sha256=Ph2Fu5rq4FV-B79uyVrXi0HIIWD6MfnWUhoe4znyvaY,874 +torch/include/ATen/ops/cumprod_meta_dispatch.h,sha256=FXG-qAiGvdzXpObdB2S9Qn9UdQNBscLsWBLP1cV8N9M,1441 +torch/include/ATen/ops/cumprod_native.h,sha256=telXfVe7a_3KiiIN-I_INQiFytblKMACLQcixEKtOp4,905 +torch/include/ATen/ops/cumprod_ops.h,sha256=HViyf9cs3g8pWJ1tM7jAOQLB0_HTGP99Xeh_Y2kI3NA,2852 +torch/include/ATen/ops/cumsum.h,sha256=i7c1ELBMceKG-Tn-k2x0Giw3LdzX34L7m7cDv9-o-14,1605 +torch/include/ATen/ops/cumsum_compositeexplicitautogradnonfunctional_dispatch.h,sha256=As4Nwe_0GgX05iwvzLabtdNPBHtHJuEQQzKaR-zrP8U,1229 +torch/include/ATen/ops/cumsum_cpu_dispatch.h,sha256=vu2UZIYr27EWOBByKWsYdj9K1F8n6sKW5V1pmx19Uwk,1435 +torch/include/ATen/ops/cumsum_cuda_dispatch.h,sha256=R0s2fgK3eCJBwO8ebBdreEuD8m0dobmnxpkxntgq-mE,1437 +torch/include/ATen/ops/cumsum_meta.h,sha256=4vSVZtKdalwlGLc3owEnUdk2YNgBRHRys7DHNpIjLC8,873 +torch/include/ATen/ops/cumsum_meta_dispatch.h,sha256=9IfEv-67XlD-v7dmaHBLxQ0Gr6yf6mFG93-GTOC7UU8,1437 +torch/include/ATen/ops/cumsum_native.h,sha256=j0-g9o1ftgQxi8V4AWEf7EdtMqFK5Waj4UPR-HJMcWU,902 +torch/include/ATen/ops/cumsum_ops.h,sha256=pu8gMNEHT4oiwTt1cTKwYbHv2Q_cRx7o6UyfzSYZvAc,2843 +torch/include/ATen/ops/cumulative_trapezoid.h,sha256=ziem09D79D1butfFv8Dd4rrrxUqg1QOftKRbS2IFxuw,1265 +torch/include/ATen/ops/cumulative_trapezoid_compositeimplicitautograd_dispatch.h,sha256=hJLSc1F0xE0LQk8LlNNMCiYDrH0vnGQbACmr4Ak_g00,1173 +torch/include/ATen/ops/cumulative_trapezoid_native.h,sha256=gyy97gUefEHb2J_VQL3tGJpPkSOghFaTUKzxCVoLxic,885 +torch/include/ATen/ops/cumulative_trapezoid_ops.h,sha256=zPV2nS3-C7ytI4KS2CiNVnTU-kikBVsrTr660BKcPOY,2043 +torch/include/ATen/ops/data.h,sha256=TV23nqvF1-IUUNP8Rmp5CcKR_YdrzbPi7AtQaLLjBnY,755 +torch/include/ATen/ops/data_compositeimplicitautograd_dispatch.h,sha256=OHGdDIOt4M8aPru4Tf3UgK9A2bPLMWeDY63rJ4bBxo0,1016 +torch/include/ATen/ops/data_native.h,sha256=LW4mOj4nzjGJNchppy6q01d355x5oGBCLMie-CXKBvw,728 +torch/include/ATen/ops/data_ops.h,sha256=b9RUO92occsbRmvb0XlairjvyCY-wk8ECIQvq5wINJQ,1205 +torch/include/ATen/ops/deg2rad.h,sha256=ZDutqzy9rtUbTTJ_lqfxRw4XTTj5_F4FLgUJPMUZAO8,1436 +torch/include/ATen/ops/deg2rad_compositeexplicitautograd_dispatch.h,sha256=8Uit0Z4HDWkgc-OQowCpChdfJUXjtpDi6NdK5_pPvCg,1230 +torch/include/ATen/ops/deg2rad_native.h,sha256=TYnm5nEVQLaRJ11TOs4SnS7BnctLmGOjAPjQVys4Xuo,1288 +torch/include/ATen/ops/deg2rad_ops.h,sha256=RpoxGAWWtoK8_jw8DrOI91KF9niO7uwLJ7hmupsLv-I,2309 +torch/include/ATen/ops/dense_dim.h,sha256=h5QI8jNXIGVA88k7k5D2oUHuthCG1McLB1P6eAE00Dc,760 +torch/include/ATen/ops/dense_dim_compositeexplicitautograd_dispatch.h,sha256=H-LxjmR3ABztgjTdR_htNeSZe3fjMhyzTlLpUOz3drA,1018 +torch/include/ATen/ops/dense_dim_native.h,sha256=1ZnKfv1v9SnXl__S0ZjtarYR2KpimTnrr0h5rBIJllY,864 +torch/include/ATen/ops/dense_dim_ops.h,sha256=ZL0S4zwUp52mQKjMpojFeNwxP_b7E_bWxzvjNv9h884,1208 +torch/include/ATen/ops/dequantize.h,sha256=urVj_PRq46lUNzGXdu8y9IcZnovkqcw8vhKHMu9N1Fo,1974 +torch/include/ATen/ops/dequantize_compositeexplicitautograd_dispatch.h,sha256=BSNJCJYJNbXCq39AvKkVxtxedSYmZwQw4vbJYy8iqDU,1280 +torch/include/ATen/ops/dequantize_cpu_dispatch.h,sha256=SUHNM2pB13Nk3kI6K81Vfn61-mmBl8PVutFckk0umY8,978 +torch/include/ATen/ops/dequantize_cuda_dispatch.h,sha256=PLGC5IPiaHdh4HI0epknETUmTBTYQP_EQqtVp7Jf3Kk,980 +torch/include/ATen/ops/dequantize_native.h,sha256=6HCXsQcLRuejIf7Vozo1xZt0e8vSMuS9AKJSROkCdME,1078 +torch/include/ATen/ops/dequantize_ops.h,sha256=prcEi9M_4YF_JnBaeG824qsnub4Gw-Vh8tItaCLJikY,3036 +torch/include/ATen/ops/det.h,sha256=jczO8csSP5hHd11SdUiFCJX94uL2GKgZLYTnd3q6pIs,879 +torch/include/ATen/ops/det_compositeimplicitautograd_dispatch.h,sha256=B2uhUQDffTv-bkxIXXZpWk-UKf6vgLlkcAuxpNHadjw,1015 +torch/include/ATen/ops/det_native.h,sha256=-DhbUfDpzsubnx0HjK0_xKS0kK-8Ons9i3lCum9pREU,727 +torch/include/ATen/ops/det_ops.h,sha256=m1XcnujJooJ7cFga14-mv83VieVjDwnOPrSz9dL7mhY,1202 +torch/include/ATen/ops/detach.h,sha256=7WkxgBHIDTHVUYbwXHYNcanAP776PW__GMkds4AM1uA,1039 +torch/include/ATen/ops/detach_compositeexplicitautograd_dispatch.h,sha256=0vTOlltJ85a8L6IqxnwTz4F36xKiLmKOjw7HS8XxZOg,1069 +torch/include/ATen/ops/detach_copy.h,sha256=1Iyoh6pazDN5gNzj1F6oCJvTBY1kshy6sqM0qnj2uA4,1331 +torch/include/ATen/ops/detach_copy_compositeexplicitautograd_dispatch.h,sha256=ICrGZ8XGvGoWEzTfqjyQgXobodtlZ81DIsmJKXI_MX8,1131 +torch/include/ATen/ops/detach_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=SqKzf2xzbYt_R2_4bf-jsxZIIoOfpqHdslVVwqh6L8o,1049 +torch/include/ATen/ops/detach_copy_native.h,sha256=rJjufj_HIzh38Y4eMmK98WEFXjLv7S3Kdy4eniJJI5Y,818 +torch/include/ATen/ops/detach_copy_ops.h,sha256=ZHTi9XtoZfEAto5TX4A_WTQRWFp1AtA12EgCkbb3kNo,1831 +torch/include/ATen/ops/detach_native.h,sha256=leB-3tOPgzMfyqYj4aGZuq7hp2Psz4aUVQhfzFZOJ00,781 +torch/include/ATen/ops/detach_ops.h,sha256=TRFHRQie_ydJaWDVkzXFZrVuSlYK7vwkmIDY4-Gc3PQ,1716 +torch/include/ATen/ops/diag.h,sha256=npmLuxTu6iSN-q1w4T0QLZmIHGF4zry37tB3bDgd9qQ,1397 +torch/include/ATen/ops/diag_compositeimplicitautograd_dispatch.h,sha256=VnMMOs_BI1uTOeu7m7lh5x1mVi7v9Gni7jy3fZyHw_w,1227 +torch/include/ATen/ops/diag_embed.h,sha256=qYt_UU4bidVK-zNgBNq9RiB_ghVi6ONrNLPHuk2jk5I,1649 +torch/include/ATen/ops/diag_embed_compositeexplicitautograd_dispatch.h,sha256=lWUVeAO3kJs06hNiOGTIBftwhy-uWMU41hA_hW9wlw8,1225 +torch/include/ATen/ops/diag_embed_compositeexplicitautogradnonfunctional_dispatch.h,sha256=IBZZGoM1qXtWPAN8OpZDFNX1PgbaW5c2-Mtk2QPnA8o,1100 +torch/include/ATen/ops/diag_embed_native.h,sha256=5epC0Z5oYa7thdrn_OZVoyS-S3Rag79_5CXlS7DcGkY,912 +torch/include/ATen/ops/diag_embed_ops.h,sha256=hxVLWRPTT5lwZi0xKFsM5SJLlZa6mKNeMPLnJus1wSQ,2135 +torch/include/ATen/ops/diag_native.h,sha256=LR16KF71HKv_7sgex2BFoKu3v26FI34V_IK-PiWWRVU,842 +torch/include/ATen/ops/diag_ops.h,sha256=r0Z5JtUofeOuOZKPJVZeBykbZdZI42W7oWCr_dXSna8,1911 +torch/include/ATen/ops/diagflat.h,sha256=Dxb_iNbtMfseol9iZBJRoV1UTYcHMyOrcffWOoGcHwM,939 +torch/include/ATen/ops/diagflat_compositeimplicitautograd_dispatch.h,sha256=P0FVDLPD5l-3Gf3xSB7mQ03-K41Q0zb54tT0k7SG5dY,1038 +torch/include/ATen/ops/diagflat_native.h,sha256=pDg3-n6t4VZAqR2TlWL5fx2kK4RBpR7ANIxJ0I5LvPI,750 +torch/include/ATen/ops/diagflat_ops.h,sha256=aoNV5awRbRyCI2Ok1lwQKjHVUPh94k5y19petTX9k70,1272 +torch/include/ATen/ops/diagonal.h,sha256=HnPHeC6I4TUHPLiWjXZPHAqMMV80Amd0m9YjKVbwHwI,1013 +torch/include/ATen/ops/diagonal_backward.h,sha256=R37XNX6jEepjng_SulC4iMUfY8fCgY8mjHXao9bICYU,5466 +torch/include/ATen/ops/diagonal_backward_compositeexplicitautograd_dispatch.h,sha256=LwsJiHRPnjPxXWcy95F1lNBk6mmmmYq7bfXULHsQuqQ,1965 +torch/include/ATen/ops/diagonal_backward_native.h,sha256=bd22EjrPPLJ51zcpz67YtvLO2JgEAeF1UpGaqiI1aFQ,1012 +torch/include/ATen/ops/diagonal_backward_ops.h,sha256=lsq8k7Zr8m9CWv9oYSMP9AynamgyDHk_JvbOK7DFJO8,2421 +torch/include/ATen/ops/diagonal_compositeexplicitautograd_dispatch.h,sha256=QyJQsA5HARvowGz6Rm2oM71NzjmDnrt7wJVxIqzs7xw,1070 +torch/include/ATen/ops/diagonal_copy.h,sha256=98BOPZ80hP-N8GN5D9XO3p--leVmeJT3Uec8LOYQqnA,1669 +torch/include/ATen/ops/diagonal_copy_compositeexplicitautograd_dispatch.h,sha256=p1DGiIxdSy75uRfRkcqW-zhnMDqO3Bj_m9vNerBn5Wc,1229 +torch/include/ATen/ops/diagonal_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Wz83kIAFeFTpV11LuGwxBJ58gSLAMwTe2szGjlxVeEA,1101 +torch/include/ATen/ops/diagonal_copy_native.h,sha256=5V6V3_SAwOYZ5OQXpKkNQoOV5HGIjVoLzZAfmADFMv0,916 +torch/include/ATen/ops/diagonal_copy_ops.h,sha256=Q6jQ2EjDHV9Q32YuryQUrniST1rf3i3lujyM06nyL1g,2149 +torch/include/ATen/ops/diagonal_native.h,sha256=joztoDV0e0xfMqHElumywXjLv1vPP4Y2dZ0SrqPDvW0,782 +torch/include/ATen/ops/diagonal_ops.h,sha256=xehiilxXM0E1XBGdEyIN__YorBgiGwz0ry785LsAAbU,1376 +torch/include/ATen/ops/diagonal_scatter.h,sha256=m_avua31mmIK4kxco4j3AXu6iXmqpL84iN4EWVZdW_A,1822 +torch/include/ATen/ops/diagonal_scatter_compositeexplicitautograd_dispatch.h,sha256=QDoMJTb076wKchX3cqBwuCRojIHOkRmBpFgifyhqREQ,1283 +torch/include/ATen/ops/diagonal_scatter_compositeexplicitautogradnonfunctional_dispatch.h,sha256=_zmPeLNcYUZ4cZ01acqw5eP44_qqiveJx9YU3nkM8dw,1128 +torch/include/ATen/ops/diagonal_scatter_native.h,sha256=MScxR2seL2a8CklIYTdz-VPgCRs9CTfIAIUnb2JtQFM,970 +torch/include/ATen/ops/diagonal_scatter_ops.h,sha256=J159wcm0Wb_W0EggqN3rvjU5yIrXqPVzK6_pS45NmPE,2327 +torch/include/ATen/ops/diff.h,sha256=G3JPIXwoFJjLgpUi33QMVdJOTmBA_lQk5T2OaHWFsPw,1889 +torch/include/ATen/ops/diff_compositeimplicitautograd_dispatch.h,sha256=EH4Zb8rN_56BwG9DsNeZyYWJfXj2vassCz7XmpTPVLg,1530 +torch/include/ATen/ops/diff_native.h,sha256=zJ0D9Ytoa_08JgZ-1cyZv02MOlBdn1BISAm6gr_oXnk,1041 +torch/include/ATen/ops/diff_ops.h,sha256=P_mHceTuhC5IE5vHS6SWuPQrxCRFQtisNRrGFZNKkTw,2553 +torch/include/ATen/ops/digamma.h,sha256=__YyiHLpeo6QlblwJo4IUD60lcTMbGxko3H2XwLHeKI,1291 +torch/include/ATen/ops/digamma_compositeexplicitautogradnonfunctional_dispatch.h,sha256=G1-lQ6E0FmVzwBgMSqVCIr7m-qV6lRwyVAx0IdGIik8,1097 +torch/include/ATen/ops/digamma_cpu_dispatch.h,sha256=J7Es2jdFZCwQs6_gjnrD5yac_coy376ZaUw6qUEEjsc,1186 +torch/include/ATen/ops/digamma_cuda_dispatch.h,sha256=ugmHMoobUQcb3W6zZEDQ4nAf91FLhiI7YvcS5Te8YL4,1188 +torch/include/ATen/ops/digamma_meta.h,sha256=mqYuU1CysSjg-o9lwrW9xZAf3VrhhcPTgXmOfsmOAo8,822 +torch/include/ATen/ops/digamma_meta_dispatch.h,sha256=M3rPChCNkJ6JjaAMghOc_OHLC9exDerG4809iT1cHsw,1188 +torch/include/ATen/ops/digamma_native.h,sha256=3C0xpjLprAZxmanX1e0cUk15E_29NaA8f1rgmZY8qyM,853 +torch/include/ATen/ops/digamma_ops.h,sha256=z2qiKgEnoXZ81a6BHX5macsYkyUprHoo5DwsPq8QWDo,2309 +torch/include/ATen/ops/dim.h,sha256=aboV7ScjyD2KAcF9OG27768Vp4HoOVBf-so6D-tnfGE,754 +torch/include/ATen/ops/dim_compositeimplicitautograd_dispatch.h,sha256=4Y1uEI-FnXSpa42kLWqRn1uLo7WMpMw-HpyzUXo0G5M,1012 +torch/include/ATen/ops/dim_native.h,sha256=oCGLqnVXDk3rFYnowkZaf8YyNBpK9UuMVReX0Httfzg,724 +torch/include/ATen/ops/dim_ops.h,sha256=-iFYOeX0iOLFg_6ohwwtAXbAMxlDFT-nig_QCgCj-6E,1190 +torch/include/ATen/ops/dist.h,sha256=RGfDnzA9c06_snD5B5DhHlo0dpEZcyobnZH6_S3kFPM,1517 +torch/include/ATen/ops/dist_compositeexplicitautograd_dispatch.h,sha256=i6QhidUOeNQpn5-eJFRCrOjEZ_lA3zMkon68-9OKCu4,1317 +torch/include/ATen/ops/dist_native.h,sha256=IriwHkiPCd5ZJNnA6ZDn64re-u1W84z2CeKHgtOn_m8,902 +torch/include/ATen/ops/dist_ops.h,sha256=oHqPzPGY-M2GWydMjiWRU4U_p47URTilWMZAihWAVIo,2113 +torch/include/ATen/ops/div.h,sha256=DM_ytex7IWnzl8KuItLoyy2Iff4wpryYEB6ekFpH6Ps,3991 +torch/include/ATen/ops/div_compositeexplicitautograd_dispatch.h,sha256=jqRoRmx5r68_3GDXNgnVNWiZ0Igl5V6KktibSbOLO2c,1868 +torch/include/ATen/ops/div_compositeexplicitautogradnonfunctional_dispatch.h,sha256=whSTYQZxAHeOVeapdR0GCY6mG5CuYtsZt6MZTtnaIr0,1390 +torch/include/ATen/ops/div_cpu_dispatch.h,sha256=310bHR6uRfb7GgZ4y69_-h4RyatMsODeRPzRmPFIgHU,1824 +torch/include/ATen/ops/div_cuda_dispatch.h,sha256=e3YOYIl4SCPQIwGi78HTChuTcwl5En5rPWwwUKzaxV4,1826 +torch/include/ATen/ops/div_meta.h,sha256=j_0xV0dF_uWPUFh9WUV7RJwbhLq09UWc5IF9mP7g8aA,1045 +torch/include/ATen/ops/div_meta_dispatch.h,sha256=fJJ4Lt4auGV1_SrUGQyhIHXk-eB4ZZKitKnAUJtYYcg,1826 +torch/include/ATen/ops/div_native.h,sha256=mhfqiXM_l4P4u9d3om-GpDzznxnxQvGBpt8joKe_ufE,2762 +torch/include/ATen/ops/div_ops.h,sha256=2dfhhisJIVcZYwXf8wR4ZhGI_L-ogD8NL0rV2ge5pP4,9213 +torch/include/ATen/ops/divide.h,sha256=Y9V-QfK_BEnEKZlwJglmf2iWHQ7V_vC1h7Sn4qkL5WI,2890 +torch/include/ATen/ops/divide_compositeimplicitautograd_dispatch.h,sha256=Oa-uiYExQf4TBSs2v6CbHKZNQZsD5i6TrqhSsICYX2M,2304 +torch/include/ATen/ops/divide_native.h,sha256=-FSAo6PLmfpQm69GPFMG58oVjuYhfcm-rLrREW0L2P8,1757 +torch/include/ATen/ops/divide_ops.h,sha256=F-8TYrRsXip1BRhhRVor6gyiBOcm8Urf1w1mOyyAYU4,7759 +torch/include/ATen/ops/dot.h,sha256=hDxawQL2lna5PrlIaufZrCbACF_rcoHJDth90DShQ8g,1401 +torch/include/ATen/ops/dot_compositeexplicitautograd_dispatch.h,sha256=wcw5KQn5pJ72LPBKQXNRWmGgaORWWWsDfA4QRHxqZno,1169 +torch/include/ATen/ops/dot_cpu_dispatch.h,sha256=cjLAj9j4idJZ9iuw7vyhaNVvjgOyPjzMFyvyRU_T_tM,998 +torch/include/ATen/ops/dot_cuda_dispatch.h,sha256=fpqckH--kSA6f0xnufNmbmRjmUWLiTfuFu_WD85g7fA,1000 +torch/include/ATen/ops/dot_native.h,sha256=KqLQjyiLykDN-wb8n6Nuq_yZA1RdoaVJ0tu--Hs14RQ,939 +torch/include/ATen/ops/dot_ops.h,sha256=DHXMBOESq_NdyzU-0UY7jd91vP6PuaEx9LKOHP24G14,1961 +torch/include/ATen/ops/dropout.h,sha256=ffgo8SUCRGpVNc1wGajUUor3J5nsZ2m9mchvT6T2ogI,1149 +torch/include/ATen/ops/dropout_compositeimplicitautograd_dispatch.h,sha256=A62lu5eajcqjz-PvdfrsJrLLQI1urzSB0lQnzsLnWm0,1116 +torch/include/ATen/ops/dropout_native.h,sha256=UCpMFQHq58nA8Tfkw-lyshJSg9Li0qf43OXi1LP33RE,828 +torch/include/ATen/ops/dropout_ops.h,sha256=nBlyQIs8qckruwwQap5zz979xW18ur9vrJoC4RjnVQk,1877 +torch/include/ATen/ops/dsplit.h,sha256=K71kl82VElRd99-JOukwK7SRVpnNmpB_aFGfiiKX5Yg,1193 +torch/include/ATen/ops/dsplit_compositeimplicitautograd_dispatch.h,sha256=-RGb4ceDOGIuKJjEXHXdJzsZZYvx5Ytj7wzlxl72kpc,1145 +torch/include/ATen/ops/dsplit_native.h,sha256=gKwPnQFs_neaSi-DShY2MpSBpvswLhhrm8_V05uzYOM,857 +torch/include/ATen/ops/dsplit_ops.h,sha256=thGZzVGK40bWJCEQXi_mB7XAhsyj_B9pz-DxgJM7D2o,1996 +torch/include/ATen/ops/dstack.h,sha256=tvO9rs5SNNrs0T4AujeqXpZ-TPwrkY4nZ9N_6_LANTI,1302 +torch/include/ATen/ops/dstack_compositeimplicitautograd_dispatch.h,sha256=I8O2hHEFfPmP8xAZAU2ICtXjcSw0JvYK71FZ0CG-B1A,1172 +torch/include/ATen/ops/dstack_native.h,sha256=wgq-TUR8kydVd-srbZWHlTdUPwICQs_3vBt4QQMuHGM,806 +torch/include/ATen/ops/dstack_ops.h,sha256=jE3VRqZZ-N6m2g3eQtpxtIdVQk9kMousI1FlWlj7CPE,1799 +torch/include/ATen/ops/einsum.h,sha256=D3a0HC_yNt_12sMPesuQqdCFX_qI6TouIIjSyJmfCig,1021 +torch/include/ATen/ops/einsum_compositeimplicitautograd_dispatch.h,sha256=pb_pi68lRsZQvqT4hkC2QrNiyA4vrC1EpRYccqHGULY,1089 +torch/include/ATen/ops/einsum_native.h,sha256=S14xJR_nmLjzUYMwCtdzrsI0SIBa0mjB5xHKaMlu1N4,801 +torch/include/ATen/ops/einsum_ops.h,sha256=1YmRg95kg8CaFOn1jISe3ZHgF3IA23rq6OD9o2ASzaQ,1402 +torch/include/ATen/ops/elu.h,sha256=geP02olb1-qY7fAmw56HE35zcyXcOLnI9AUlmhmhJHU,2062 +torch/include/ATen/ops/elu_backward.h,sha256=5nUKmINRGnl8vqHR05Xu4yHQMtZZReAJwKQqXm6--6I,2302 +torch/include/ATen/ops/elu_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=BCKv8Rl1OWVDYagC-1Ce1thb3MkztI1mk5O0NXq_waM,1192 +torch/include/ATen/ops/elu_backward_cpu_dispatch.h,sha256=FOA61fDZ73rBKQIqclj8UEH8oV3FLLTjxlnbBCUhx5M,1589 +torch/include/ATen/ops/elu_backward_cuda_dispatch.h,sha256=A15wtBV05y3mNuwdVARSaARNt7Xyb6vIKRAIIL9N594,1591 +torch/include/ATen/ops/elu_backward_meta.h,sha256=cuMqof_dpN44dU6kAG0camgQUCHh-PqgSUum7xknge0,969 +torch/include/ATen/ops/elu_backward_meta_dispatch.h,sha256=HgrJZjt5hf0G0lDNBxESqstcDBYQwAb09Ul9LjY7Cyw,1591 +torch/include/ATen/ops/elu_backward_native.h,sha256=L58MWiCBc1hxBd90tMo11M7syJdSFBgt-hiYOXobBLc,1017 +torch/include/ATen/ops/elu_backward_ops.h,sha256=jOfVQW8jUwDzeVvBumeVBcBg4ltpjW3__dX50X_JeDM,2807 +torch/include/ATen/ops/elu_compositeexplicitautogradnonfunctional_dispatch.h,sha256=baUpx2rkErCKs_oLurmv4GUxlsXX6BL1sxFIJ7fGSho,1269 +torch/include/ATen/ops/elu_cpu_dispatch.h,sha256=y9DShreyq2Vw-O82O5qUCh1BI03Wnbt-6hIlgF9xgIY,1524 +torch/include/ATen/ops/elu_cuda_dispatch.h,sha256=ME9OBP8EdSjqbthwgq06jctUj3_zounYAInQnmhAmq0,1526 +torch/include/ATen/ops/elu_meta.h,sha256=UZgQceU3Qt27H796eHvvYw47hAqprBNGFtJUb_DEsjM,902 +torch/include/ATen/ops/elu_meta_dispatch.h,sha256=6u1fbb1-P9ryRfHAEVTxMnYhra0aBQpcci8lY2Zazog,1526 +torch/include/ATen/ops/elu_native.h,sha256=qm2ltdXeKmStN9l2brxvoc0Q398Oaiq3W3TKY3-kVq8,925 +torch/include/ATen/ops/elu_ops.h,sha256=B2AV3R8ImCvKtQB_N_xiAaIU0pc-kSRtxuVoWu8esCY,3119 +torch/include/ATen/ops/embedding.h,sha256=VXZlgOEHobJWEqmR4MndMdOwj_acjSToAl-8dDkmUKY,5614 +torch/include/ATen/ops/embedding_backward.h,sha256=ZbyfA5bhJwGnCs3I0qY--Y-ygsqMHpMf52BEQ6eUPM4,2445 +torch/include/ATen/ops/embedding_backward_compositeimplicitautograd_dispatch.h,sha256=9oLX0S9dGk-bgqN6DwfBXQwjtfyeozsjT5nvPMyoXww,1327 +torch/include/ATen/ops/embedding_backward_native.h,sha256=cobHiJZ2dlOJ2lPx9OFXXErT5lQJb9eL8tAfmtM_ew8,865 +torch/include/ATen/ops/embedding_backward_ops.h,sha256=XSknOoabtnW_quarg8o8Uc5YUPwU6nfOju3gIJ-JRVQ,1631 +torch/include/ATen/ops/embedding_bag.h,sha256=bvZE-ccv4K2Q5dS6MVyUL6YX0x6wrCfn3x3kF3AKVTs,2208 +torch/include/ATen/ops/embedding_bag_compositeimplicitautograd_dispatch.h,sha256=z2Hlk63FbSyf_et9yE5x2yN3PjW1G2wtEf86UYBmWB4,1625 +torch/include/ATen/ops/embedding_bag_native.h,sha256=_Nxd1dFBAPzB3Fe1pFWITFVD_BtUpLtXMWpMgTmoTts,1337 +torch/include/ATen/ops/embedding_bag_ops.h,sha256=6S9H9Ws95KiDe_Z_ab_lus-_pQ3olNtXAz0bI4vszeM,3515 +torch/include/ATen/ops/embedding_compositeexplicitautograd_dispatch.h,sha256=X9wEeoa3zC3sKdFDFHn7Ktc1qxnPq9VgBD44J7sCqaE,2031 +torch/include/ATen/ops/embedding_dense_backward.h,sha256=V0VD1_9FWwJmZa_BjQqfRdD44WGhZih9K3SEsy7oDu4,6241 +torch/include/ATen/ops/embedding_dense_backward_compositeexplicitautograd_dispatch.h,sha256=ua4FPXRvYb1BJFIZMXjuIq5fSYCQMJrq5yyxTMyJzrE,1788 +torch/include/ATen/ops/embedding_dense_backward_cpu_dispatch.h,sha256=zwa51u0ncbal4FAZsJouJ8cKGSF5si1YcGgrRMkT5nw,1283 +torch/include/ATen/ops/embedding_dense_backward_cuda_dispatch.h,sha256=j-r5ABK_xdDlm1twqGrocOvBiMa2nFr9Ne5puL8qiK8,1285 +torch/include/ATen/ops/embedding_dense_backward_native.h,sha256=xCx4lj1WCt_Z2Ks1nWmD2Pufx9RRKiVmuoUtdQLbpPM,1246 +torch/include/ATen/ops/embedding_dense_backward_ops.h,sha256=9NSiVZo4QX-9F1-DdAZwVsezhi5-uRAwo6bZslqw4X8,2629 +torch/include/ATen/ops/embedding_native.h,sha256=cjL2FfhDAtpYbWUazK9kzTbEVmgkWfIKAgC-lUpGuts,1203 +torch/include/ATen/ops/embedding_ops.h,sha256=iJAQUOuP03GCc3tjvpZ3fwjc_2NNlYYcvBvChA4bzHI,2463 +torch/include/ATen/ops/embedding_renorm.h,sha256=jGEnaPdejB8jSpmVd6QtFHUuv9IRLfq5zqhhDe28yjc,2121 +torch/include/ATen/ops/embedding_renorm_compositeexplicitautograd_dispatch.h,sha256=kt2IrehVKKhjrr9dWCQGVEGJgy-a8wCcjrT8O9SoHhA,1394 +torch/include/ATen/ops/embedding_renorm_cpu_dispatch.h,sha256=OILyb8p8mrUfJiSbU3DHG_doMQSf0SgHfeQJddDb0ok,1044 +torch/include/ATen/ops/embedding_renorm_cuda_dispatch.h,sha256=RGTLkfRRY7F6y_nLAjoP9PzKE1FtWJr_Vt1TcwkwSig,1046 +torch/include/ATen/ops/embedding_renorm_meta_dispatch.h,sha256=eeBiLc_7hoapRnvjc6EogQaO60COpr_1qpHt4swUBXg,1046 +torch/include/ATen/ops/embedding_renorm_native.h,sha256=080IuuA0PMfhi5J-0WNEcl4CihtKNzAO72sZdxMX7Ac,1211 +torch/include/ATen/ops/embedding_renorm_ops.h,sha256=XwwEveXxTvrNz7EGMp4EWYN3D7P5Wd94fCjKI5ZWuVM,3023 +torch/include/ATen/ops/embedding_sparse_backward.h,sha256=jrSdzjOKHcULM1hFOpfIVRrJ2_ueWRJOQz45L2RbvU8,1192 +torch/include/ATen/ops/embedding_sparse_backward_compositeimplicitautograd_dispatch.h,sha256=9pQ4jqFBnXneOWDfRPTKHkzDwNAYYdL7awWbdT_qa_E,1132 +torch/include/ATen/ops/embedding_sparse_backward_native.h,sha256=AE0MzTSqnSWk3zAlE4oxgzXYluvm-ZADy9ks6Ur67EU,844 +torch/include/ATen/ops/embedding_sparse_backward_ops.h,sha256=ibDyI8UpizWRB3HYjf-gQHYxd1WgeuQzrzs-oIaKbZk,1577 +torch/include/ATen/ops/empty.h,sha256=TTg6p83Hbm_Zsz775PDdIXaml-sNVJVG3n0M4Etmmzg,7535 +torch/include/ATen/ops/empty_compositeimplicitautograd_dispatch.h,sha256=ku65s8JHL5Ow3Eq8U2jVvRVstMeKVFyhKu7v0YGJEAQ,1510 +torch/include/ATen/ops/empty_cpu_dispatch.h,sha256=6iQ5rpUED09D-jLOu8bqfM1s8hp0bY-4dYGs1ExTQ2M,1718 +torch/include/ATen/ops/empty_cuda_dispatch.h,sha256=6NipKv-tGlF9wZZABIsPVhrQtJFCqNIRzRPYLRxdKuI,1720 +torch/include/ATen/ops/empty_like.h,sha256=dnLoJqk_Olujv8LnpLM_15zZThPdvXu5wmNVjPOT_p0,2475 +torch/include/ATen/ops/empty_like_compositeexplicitautograd_dispatch.h,sha256=JSHN3P1bs6ta2dTb_TlvXnhNMsuZt9GKbnMyMw5UUX8,1646 +torch/include/ATen/ops/empty_like_native.h,sha256=myr7KZbvEauIshBb8LiAIdZua6uSI3-gMipFg7Yao18,2241 +torch/include/ATen/ops/empty_like_ops.h,sha256=vUKmhPn6RopZy2Bo98BlJxctrdvOxX9GXt2fVocj6gs,2655 +torch/include/ATen/ops/empty_meta_dispatch.h,sha256=-46psyLd8P9957SHSpXmFWhEq1JS3_EG55gpz6RpPy4,1720 +torch/include/ATen/ops/empty_native.h,sha256=uqOEBmp_w9uoEvGNxGqTVJAoD6Fh4-QCcu87NeO045I,3360 +torch/include/ATen/ops/empty_ops.h,sha256=mfcAvQwbZfVs_L8rnfbujrSYxHcnM41-LxgaPZiGVnU,2676 +torch/include/ATen/ops/empty_permuted.h,sha256=tdRLCvKQbDIQ9GTob8i1q8TXDjt_tZB8ulb7MisqO7U,7032 +torch/include/ATen/ops/empty_permuted_compositeexplicitautograd_dispatch.h,sha256=1tmPQnli_yinJV-r-3zJqjq5cwXt1Fs3uGFKVHr7u0U,2192 +torch/include/ATen/ops/empty_permuted_native.h,sha256=1xFuLCm83kiTQSTU3xLRXFnTbhmWcRg7aySoVKN9DyA,1063 +torch/include/ATen/ops/empty_permuted_ops.h,sha256=Yx1pw0EGRJukhgFuex89NyrjNIUMwvPryMoRt2Onq-4,2567 +torch/include/ATen/ops/empty_quantized.h,sha256=W1u-gjSEPeRiwPUE70HYsAkXaIFw59h4xP_GU1NZjIg,2736 +torch/include/ATen/ops/empty_quantized_compositeexplicitautograd_dispatch.h,sha256=YafgEwi-ZJin0TdyrlgkMKpBfu6aQgO6LmrxmkkwF9I,1302 +torch/include/ATen/ops/empty_quantized_native.h,sha256=EsAB1we283m5Eo1DgNrG89KF5ZloS3WoIeBnSEgN7Bo,1146 +torch/include/ATen/ops/empty_quantized_ops.h,sha256=AMPzbmaQufqeQJKC6AbSdkw1Z61UoM3HQCej_0bcYik,2849 +torch/include/ATen/ops/empty_strided.h,sha256=8aqvFYjwEcBdsXVacmcbC8WcCVQqSraI3p02A_6kCo8,6895 +torch/include/ATen/ops/empty_strided_compositeexplicitautograd_dispatch.h,sha256=xhSMpKVmVfiQaNwGIcq7WV3yNAXLQKJd2mRcuEMjV-U,1420 +torch/include/ATen/ops/empty_strided_cpu_dispatch.h,sha256=06o1S6KGVG33CehvBYBu9eT1BoKBYScNv0ArzzybI-k,1628 +torch/include/ATen/ops/empty_strided_cuda_dispatch.h,sha256=ngvPLf8nUvMdTDpE1iF_mS7-kRrULjDlAEvNg5e1X-M,1630 +torch/include/ATen/ops/empty_strided_meta_dispatch.h,sha256=K7IC5qx22Pntiin98KXzfm7tNTbrG5GvCvx9T5DL8HQ,1630 +torch/include/ATen/ops/empty_strided_native.h,sha256=hrdn1rzoZyGehfnzWkk6kQPNbpYMWdSi-P4LaWqpYOY,1800 +torch/include/ATen/ops/empty_strided_ops.h,sha256=bUoaB54xIOOSfO4VKnICAQI3ILwqTOwyUkkLtI9cZEM,2537 +torch/include/ATen/ops/eq.h,sha256=jbiBR_T-cDpsD_icbEZsNdl76sLKZiD83Fj_KQj18Ic,2096 +torch/include/ATen/ops/eq_compositeexplicitautogradnonfunctional_dispatch.h,sha256=_h16vxOSj6JM0iPdBfhjY2g5eaMsVhx3iJ4-3KL5qvk,1288 +torch/include/ATen/ops/eq_cpu_dispatch.h,sha256=p3xdTFcaS2uu3jyvNw6PDDQ_CKrThfqb3rJ0PWNm97M,1620 +torch/include/ATen/ops/eq_cuda_dispatch.h,sha256=YcfuDTYBTe-Hp3ifsK1JtR1QRZbcpZlqGICqTJKWytQ,1622 +torch/include/ATen/ops/eq_meta.h,sha256=ZfxJdGriWEPf5VOGd0VfLWtopp31JMoZBMXg3BnFDbI,989 +torch/include/ATen/ops/eq_meta_dispatch.h,sha256=m-AF4j2HXN6-RJETYIx65S81_kbNroV-4I-QKfx6eek,1622 +torch/include/ATen/ops/eq_native.h,sha256=h9HJF-2Fr053_TtC8GjGw_NdIErC3xqqQeTeQpfqtJI,1639 +torch/include/ATen/ops/eq_ops.h,sha256=YJ0XCXuKoChB6NUDpNW5gDRmOqey8dlRJxsjlattBew,4455 +torch/include/ATen/ops/equal.h,sha256=B1qej1C9ErRx4W4mir8puHicgCT3XMhYSczYO81J1oA,926 +torch/include/ATen/ops/equal_cpu_dispatch.h,sha256=Kg3CwVywunYYUcqiE0sMTyAlIfvnyRSegOb_ejq-kEo,993 +torch/include/ATen/ops/equal_cuda_dispatch.h,sha256=WnEg9gXMy9HzNX_oYdffDqOGlAPLzv7Gn6uQSbZ4Suo,995 +torch/include/ATen/ops/equal_native.h,sha256=4u0z-oBAbVo0uom0BT1tUsNrI3g6hYzDNf2RtkXcPik,918 +torch/include/ATen/ops/equal_ops.h,sha256=OWQeEjGANNFsG2LVJoA0parq-cu2y2zjODl4n9UD4D0,1274 +torch/include/ATen/ops/erf.h,sha256=-Jyqt7S3hLZnbic_e6IpZfj-piJJZXrY1culRJybpJQ,1384 +torch/include/ATen/ops/erf_compositeexplicitautogradnonfunctional_dispatch.h,sha256=aaY4RsKmcDhRjQTQs0w9zjNPv6qFqpxRYNN6IxDptvU,1089 +torch/include/ATen/ops/erf_cpu_dispatch.h,sha256=pcW8HmhwMlLqOCPpxsmZOuNIrzMf_QTazQgHj19zzKs,1170 +torch/include/ATen/ops/erf_cuda_dispatch.h,sha256=wgKacr_pKctv8amK93v334UHHWaXACXOZBYGLLB-F18,1172 +torch/include/ATen/ops/erf_meta.h,sha256=GG8-dyt4ovvx0SOpBNL5I7cVw93ZBveooufTRzt84jc,818 +torch/include/ATen/ops/erf_meta_dispatch.h,sha256=xqqYrV5LfF_eh6FY2OR_6afI6o9teIMZAts5AAuApgQ,1172 +torch/include/ATen/ops/erf_native.h,sha256=-jKnypdbIR7rnGX9Zp4EDhxcz-z36BGsvzbHm22kRiM,1243 +torch/include/ATen/ops/erf_ops.h,sha256=M0CoEgvMBcX80kAjytdJmkkv59q6feHWuVWE_Vr_PoI,2273 +torch/include/ATen/ops/erfc.h,sha256=3fhKgdJE6SHBN74Ge9LVUUa_WjlftLWAvlSLRKZNDNA,1397 +torch/include/ATen/ops/erfc_compositeexplicitautogradnonfunctional_dispatch.h,sha256=p_QN-mNWvtVZQh6pEfIbgX_nW-6mGIj0soUEK9Ig2ro,1091 +torch/include/ATen/ops/erfc_cpu_dispatch.h,sha256=7MqFKcNcp8zalFMN8Qskn-8mzIIiI6IQNAXaMxntCAM,1174 +torch/include/ATen/ops/erfc_cuda_dispatch.h,sha256=TJYzfkTR7Crd0rm7ZjWdEja8GGLp_EUWrjF4nKtxHMY,1176 +torch/include/ATen/ops/erfc_meta.h,sha256=7MRi-D7QH5s4rFHEdjLZYOs0WvTxp94BfXToDSNzgS8,819 +torch/include/ATen/ops/erfc_meta_dispatch.h,sha256=-MIAF7ORvLm00QM75MGflyBr0anj-A-xUkxdPk4OVz0,1176 +torch/include/ATen/ops/erfc_native.h,sha256=vukzl9L6b2yLrCEjp1orpBtu3TjDVO5NEYkUDVOxoTQ,844 +torch/include/ATen/ops/erfc_ops.h,sha256=dGs_VfG_sh0lT0khVc2X8pCrFU9HWkex_6e_aQ7tWqg,2282 +torch/include/ATen/ops/erfinv.h,sha256=XFrToqDxEennZ_A4nBCwjwdgSI19sNJ2FuSF4PDOkfE,1281 +torch/include/ATen/ops/erfinv_compositeexplicitautogradnonfunctional_dispatch.h,sha256=spa_KYP8Us4sENmQpwUdBS9Zx8T8MloytqkyZjWZTYA,1095 +torch/include/ATen/ops/erfinv_cpu_dispatch.h,sha256=eQ-0qRYrh06TYGl33Hj9irVngUjhoIBnDTuwropGGxU,1182 +torch/include/ATen/ops/erfinv_cuda_dispatch.h,sha256=arizfANIM1LTL2IKSNb_bP4-CPqM516v6tF5sJWPrb0,1184 +torch/include/ATen/ops/erfinv_meta.h,sha256=Xq4DfrgcaGXtEbApeKQlLIn_kWfB2x63VxWT7LVgMO4,821 +torch/include/ATen/ops/erfinv_meta_dispatch.h,sha256=2oRmI8jvH_tNQ4-CVa1RgYRfuB9VJdHLetIggkvyxWg,1184 +torch/include/ATen/ops/erfinv_native.h,sha256=i7KumcRxPO-o6fwymkGjYMJxJGln9c_10wSMlGFBq6M,1270 +torch/include/ATen/ops/erfinv_ops.h,sha256=SbPjRYY32oaURpFSk3HoqbQmhHHuR35GuvobiwSYMiA,2300 +torch/include/ATen/ops/exp.h,sha256=DC3Tw7Fm5uilEIeumDm1s2RZOLEHrj_iFuLSbNefE_8,1384 +torch/include/ATen/ops/exp2.h,sha256=W3FGcnwLlqr6NJJFOrOKBlYp82PYKkQnmOYZurehTkc,1397 +torch/include/ATen/ops/exp2_compositeexplicitautogradnonfunctional_dispatch.h,sha256=o50NiBKbX8vfSwSkpUtRIqRsOBh0EK109jpza1-IUcA,1091 +torch/include/ATen/ops/exp2_cpu_dispatch.h,sha256=abYoMbZCXR-1lnszZHf-GGvJiLSw_eOz0k9Wohk1MiM,1174 +torch/include/ATen/ops/exp2_cuda_dispatch.h,sha256=_hGNy4JRC_CzMnFnnUPTLn6zmSfoyk7ulKAVcKxnpFE,1176 +torch/include/ATen/ops/exp2_meta.h,sha256=m8gtBBUgkIkQ1cK4FJ44mx9oNPruOeRXnlaoB26kAWA,819 +torch/include/ATen/ops/exp2_meta_dispatch.h,sha256=pt6cs-uwHTI707A9v09_22pVmmNyQSWnslJC6coMyb4,1176 +torch/include/ATen/ops/exp2_native.h,sha256=7WlENldCopf4GFyv7eCRX-_zDfT3MNaEWcA0JY3h2qI,844 +torch/include/ATen/ops/exp2_ops.h,sha256=5z-tGauNj5uHCel0uYFs6Zex4C2P0mLb0PEDb2wGSZ4,2282 +torch/include/ATen/ops/exp_compositeexplicitautogradnonfunctional_dispatch.h,sha256=KpM3kWXfdW1TTuujUTgis-c98Ze-YUCcVr2WeExCYbg,1089 +torch/include/ATen/ops/exp_cpu_dispatch.h,sha256=Tjpdz2NwhGzA77Mn9DlZdq-TjWVML05JZcPOfnSFHl8,1170 +torch/include/ATen/ops/exp_cuda_dispatch.h,sha256=rjPRw1Zx-Gglf6dT77T66aNJW2yt4l5GeeEto10RD9M,1172 +torch/include/ATen/ops/exp_meta.h,sha256=hmbpqASi6dexagN1P2vkI2OfMppWcolzuhxP7nOfIZQ,818 +torch/include/ATen/ops/exp_meta_dispatch.h,sha256=Vwt198tZdsIJIGKMrMtEMuzHW382JpWqePasNFEu8yw,1172 +torch/include/ATen/ops/exp_native.h,sha256=o4S7V-PU4DYI96hyvJ0KkY0ibEV8i2Hfvv_5ZkgiCA0,841 +torch/include/ATen/ops/exp_ops.h,sha256=cmoOBrkS_1J6bJuRx0vegON4k6cJeo8FfmLoq7Xf2jg,2273 +torch/include/ATen/ops/expand.h,sha256=PezukEin25kZBEXY2tKbl0WvLI3IdYrD3fFrultfHwg,1298 +torch/include/ATen/ops/expand_as.h,sha256=ChCHxBu0I_f237DgEbRZYA_5pWtki-Cx_OPIttdwf-Q,760 +torch/include/ATen/ops/expand_as_compositeimplicitautograd_dispatch.h,sha256=ob0JbBH0eN3_hV1RCXCYDKrrB1zhfa6pQZ5ApsjNjTU,1047 +torch/include/ATen/ops/expand_as_native.h,sha256=MW0wIq_wR6hEtJieGgqozbsEIDz4vadJ_WiY36vSx_Q,759 +torch/include/ATen/ops/expand_as_ops.h,sha256=vM-KWBm9FoEa2Frv-wGv3C2bnGUOLKCXYaxH91orFgc,1312 +torch/include/ATen/ops/expand_compositeexplicitautograd_dispatch.h,sha256=eIYq4nY7QZvYsS3q1QKdxBbALr4PhBfQo8VLB1qxUUc,1169 +torch/include/ATen/ops/expand_copy.h,sha256=jgOt7AwlivhVa8gKcO9qCD3QIuNhuIzoDo8WQSUqDGw,4380 +torch/include/ATen/ops/expand_copy_compositeexplicitautograd_dispatch.h,sha256=YzTyn-w0g6jMkg9QUIJjeGPUiYWoKnVV_30Oe_y9DDQ,1480 +torch/include/ATen/ops/expand_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=0lXoxSKePgFRf_W3yvgDm-85pvldj6wFCoMbOcKWK8A,1205 +torch/include/ATen/ops/expand_copy_native.h,sha256=Lshhf3DWKcEPDbHNVoQxxEcQNJx_ArLPU_QIaP_dSw8,920 +torch/include/ATen/ops/expand_copy_ops.h,sha256=u0cn7LFUFg1H4hEKAH-E-m5TNBa8y65lltLPEi2uSyY,2124 +torch/include/ATen/ops/expand_native.h,sha256=uviKJ_7U7-kOxAkT_1GA0iX2qHwwsIWEdOxSCuZjMEU,773 +torch/include/ATen/ops/expand_ops.h,sha256=dNeK11hk_5eNaU_TplXdMnhMsRi0d5KIaNqUAlvCtr0,1365 +torch/include/ATen/ops/expm1.h,sha256=921qXV22Du8cn9ILwPQkgE-mWpWu-jT1qjmL5aIAzCA,1410 +torch/include/ATen/ops/expm1_compositeexplicitautogradnonfunctional_dispatch.h,sha256=XJKsf7e-R577kGHz084hu1hr9Fsbcm1uYgNaMvKIzAQ,1093 +torch/include/ATen/ops/expm1_cpu_dispatch.h,sha256=oxCmUv1cPWq_taq58ZpKvXCAbKgH7yHtCooYm3yEV-o,1178 +torch/include/ATen/ops/expm1_cuda_dispatch.h,sha256=mE-5U-nqsWPO5BukyZx2W-_dW_aBUJ-P81pTMNemYyo,1180 +torch/include/ATen/ops/expm1_meta.h,sha256=adHkytCmZBxNFqWxUUaVIgyYkr3SaOasjWyTNDYydLE,820 +torch/include/ATen/ops/expm1_meta_dispatch.h,sha256=oEhwLhzasqFzgGi1C9wXLQ_2SFjDJeprT3UspH3PUek,1180 +torch/include/ATen/ops/expm1_native.h,sha256=4XLabeEQ77eh92h4o4s9fgfhxoeq7vTCC8XMh8U9itc,1261 +torch/include/ATen/ops/expm1_ops.h,sha256=hQSO3un2pSI1DvzFBJ949uBvUa234T5_ASfKKaF6NMI,2291 +torch/include/ATen/ops/exponential.h,sha256=OLwz1tMRIyNAQ_Wg3iMZ3cOsVcEgWxosYDCW5n0NKeU,1716 +torch/include/ATen/ops/exponential_compositeexplicitautograd_dispatch.h,sha256=2JGiyMW_TduZm3inMUgXq6yWIvvkon_lRPCBVePMywo,1392 +torch/include/ATen/ops/exponential_cpu_dispatch.h,sha256=Kc2RT6ty52LwMMZwILvYmBUwEy0J8001xFQeC_WOlkc,1049 +torch/include/ATen/ops/exponential_cuda_dispatch.h,sha256=HS-hxBRa1-E6n-z8-Adpn5cEzgmi3-3ihuhRNFPCnOI,1051 +torch/include/ATen/ops/exponential_meta_dispatch.h,sha256=WjauTK8PSgtlf3mwMuAt5SPfVCw9pIcUcODauuR3k1U,1051 +torch/include/ATen/ops/exponential_native.h,sha256=w-2ggg6SMNnqKT0FmKt8huOkKYznDk1rXd5UfjM_bWQ,1076 +torch/include/ATen/ops/exponential_ops.h,sha256=aynzxfKhVSLcVEpOYLhIh5bXY3afU2tGX-zuWrmJ4-c,2933 +torch/include/ATen/ops/eye.h,sha256=yvN9tnXWSxjpZq2umTRF5DIJHXGkbGzONnNiSWDt2Ds,9881 +torch/include/ATen/ops/eye_compositeexplicitautograd_dispatch.h,sha256=YwxF-xhjKV1WLRvRQF7_NYbQTp9i-b0bffZ_QV7nxrQ,2056 +torch/include/ATen/ops/eye_cpu_dispatch.h,sha256=OrZnWPbjBiqa82qIrHrS_YCKSEucuaXYMdQV8bULpzI,1508 +torch/include/ATen/ops/eye_cuda_dispatch.h,sha256=ZUIk0lYNrHpl0xgmx2NCSDDYL9dV2TtuRWQaq33SGAg,1510 +torch/include/ATen/ops/eye_meta_dispatch.h,sha256=mJ-ddSEcIUuRyiJjMeQ71z8WQLjjPzfhOv5eFNKB-fY,1510 +torch/include/ATen/ops/eye_native.h,sha256=3qjHBew7DSKUXihFMsWlIlRtBi9ra-oDY1xMfT-DSYM,1359 +torch/include/ATen/ops/eye_ops.h,sha256=WgmenuNAH2ip3udCtF5chVOHuGXmoTMs-h1xbQO9od0,3844 +torch/include/ATen/ops/fake_quantize_per_channel_affine.h,sha256=PeVPisP3elUtykaZbx00M3xm01AycS81z9Fnr5zjKKI,1224 +torch/include/ATen/ops/fake_quantize_per_channel_affine_cachemask.h,sha256=D2O0dx7Cukpmuul5h7i6OrUwhnwSD2MIL7hcBJCDqKk,2547 +torch/include/ATen/ops/fake_quantize_per_channel_affine_cachemask_backward.h,sha256=LnI91W7oOlfDtsd6K5Mlv4QQk3BIUWZ9g8lBy4DCAVA,1115 +torch/include/ATen/ops/fake_quantize_per_channel_affine_cachemask_backward_compositeimplicitautograd_dispatch.h,sha256=jdjlS_IgLV7IiLS6CzJVg5yVmFXocPgDRKofSiP_FIU,1088 +torch/include/ATen/ops/fake_quantize_per_channel_affine_cachemask_backward_native.h,sha256=1-zBhn4n0FDmCZ3YAVogddgbjgBp0cLuN6W7trh_K9M,800 +torch/include/ATen/ops/fake_quantize_per_channel_affine_cachemask_backward_ops.h,sha256=LZli9OZ8vxXIERdK4E4kPL0Ah-mQgnNTXLc_-YN8z9c,1429 +torch/include/ATen/ops/fake_quantize_per_channel_affine_cachemask_compositeexplicitautograd_dispatch.h,sha256=UwhphtOYbfLX2CelW1IBh4EnjOnEyR-dIXR4Ou8Qp38,1505 +torch/include/ATen/ops/fake_quantize_per_channel_affine_cachemask_cpu_dispatch.h,sha256=3hfbe3Y8Az_t4_sASQwHgUg8Yd43iGEZJhdjA-istRA,1144 +torch/include/ATen/ops/fake_quantize_per_channel_affine_cachemask_cuda_dispatch.h,sha256=wwWUOeNnNg5SBE-KJ9VymmoRuchqro6UnKz0rCiYmSA,1146 +torch/include/ATen/ops/fake_quantize_per_channel_affine_cachemask_native.h,sha256=yZpy2PcC2hHILwWx4_BTZhQ6DHQnpWMBE3RzfmZksCg,1170 +torch/include/ATen/ops/fake_quantize_per_channel_affine_cachemask_ops.h,sha256=QdVnqbPrqO1NUyyLa4QUPwVSAmnYB8tTb94Srd-YF8s,2997 +torch/include/ATen/ops/fake_quantize_per_channel_affine_compositeimplicitautograd_dispatch.h,sha256=CO_4xzd6HXq2C6SAfH5By6OJmoxrxOb7dOTGauq56QA,1153 +torch/include/ATen/ops/fake_quantize_per_channel_affine_native.h,sha256=Yxyu38RSBHgjvPjv2fU2bMi0V3cTW38AHem7ZaLJsLQ,865 +torch/include/ATen/ops/fake_quantize_per_channel_affine_ops.h,sha256=tosCjZgzGyneSPAuvTpW-PetIxEunfPa7UwhzDqY52w,1647 +torch/include/ATen/ops/fake_quantize_per_tensor_affine.h,sha256=yglQ2559s2zf8mxDb6DnxDSj20AXtZwfwCngiF0cPzQ,1602 +torch/include/ATen/ops/fake_quantize_per_tensor_affine_cachemask.h,sha256=_YWL2kvwwND0TPq5KoUqLsUuGANW2HLFhwaET3KwIg0,2366 +torch/include/ATen/ops/fake_quantize_per_tensor_affine_cachemask_backward.h,sha256=R4aEAs5vmG4FmAhqknIIJu9B1ilDxjRtDZ0YjI96c5w,1111 +torch/include/ATen/ops/fake_quantize_per_tensor_affine_cachemask_backward_compositeimplicitautograd_dispatch.h,sha256=WY_f8NPlOyaO270NjTpFTK5d5SEm-aRYcDJG7VPHd8Q,1087 +torch/include/ATen/ops/fake_quantize_per_tensor_affine_cachemask_backward_native.h,sha256=XlFsAxkCXUh29GZybxIlk55oqXPN10wmKNCaVNYEkS0,799 +torch/include/ATen/ops/fake_quantize_per_tensor_affine_cachemask_backward_ops.h,sha256=tAX9NvU4zbLm1jUJgjzPLPw1Onjm3f9i5Rt9cYRAE6M,1426 +torch/include/ATen/ops/fake_quantize_per_tensor_affine_cachemask_compositeexplicitautograd_dispatch.h,sha256=aJxGKx6U62atFKH5aHvKtSydWD5YbB2YWBUdPXlsQu0,1429 +torch/include/ATen/ops/fake_quantize_per_tensor_affine_cachemask_cpu_dispatch.h,sha256=xt97c30q8oLo2XMPT22BENcJ3vPzvnH-GKjHLtrS9eM,1106 +torch/include/ATen/ops/fake_quantize_per_tensor_affine_cachemask_cuda_dispatch.h,sha256=JVIQzZ96Lzpi-f50iuT8vH7D7-ekOjOU5P7IX3wWTJ0,1108 +torch/include/ATen/ops/fake_quantize_per_tensor_affine_cachemask_native.h,sha256=I3rSDY1c4tIFFo6AFzb4ZnBAsazUsmhruf5-N7Fzopg,1094 +torch/include/ATen/ops/fake_quantize_per_tensor_affine_cachemask_ops.h,sha256=jolIWSHPIp96Otyjkxt3XITxRAQpvX0DDPG01Vr2Q60,2751 +torch/include/ATen/ops/fake_quantize_per_tensor_affine_compositeimplicitautograd_dispatch.h,sha256=GQWq-eTUpibA5EZTKtw13KuNkYidU7dXaR2g5Ko28B8,1289 +torch/include/ATen/ops/fake_quantize_per_tensor_affine_native.h,sha256=JBEBVI4-af_-ADdPVDmzEkfTe15hDDZeLG3KwXu3K7Y,1001 +torch/include/ATen/ops/fake_quantize_per_tensor_affine_ops.h,sha256=R35j5L7sJ1AMaVawwjwDp_M1MAS9AFphSC2SYpExYXI,2454 +torch/include/ATen/ops/fbgemm_linear_fp16_weight.h,sha256=rEJWd7iWaoeuNbb31IDvESxaZ_ze2ZPgyGizjvDAqA4,1451 +torch/include/ATen/ops/fbgemm_linear_fp16_weight_compositeimplicitautograd_dispatch.h,sha256=NnxbWuFM_n8flaF5VOtoRU_omvQUbqaWTXd3tq1f6Og,1251 +torch/include/ATen/ops/fbgemm_linear_fp16_weight_fp32_activation.h,sha256=pizXa-j2MbghR0K6Za_-eucQ2xjPRlLGccjnIeWVNVU,1599 +torch/include/ATen/ops/fbgemm_linear_fp16_weight_fp32_activation_compositeimplicitautograd_dispatch.h,sha256=2qHvTxaPDzUmmi3BC2OznzjK7Mf6wc7HpmBWqoOwxX8,1317 +torch/include/ATen/ops/fbgemm_linear_fp16_weight_fp32_activation_native.h,sha256=ALLHF_CWsZ5rABccJNWztgMUckCi0Xda8HfTkXyk2wc,1029 +torch/include/ATen/ops/fbgemm_linear_fp16_weight_fp32_activation_ops.h,sha256=wFHnXSSAfS9d8QMkn63l1zGbxosfgSKt-5UsxBDY9OY,2503 +torch/include/ATen/ops/fbgemm_linear_fp16_weight_native.h,sha256=fKIKK4Ikfjr7OQPxuqSEt9b3EjgPlWUFTiC0JJq1Agg,963 +torch/include/ATen/ops/fbgemm_linear_fp16_weight_ops.h,sha256=jKAw5AFTYNk6j6QfpMOroz1z2wewahT_EtvPev0EAAc,2303 +torch/include/ATen/ops/fbgemm_linear_int8_weight.h,sha256=2SLO1CDjGYvWl3TlPPrNsH5q7PjduZUUNEAWiOHSn_s,1330 +torch/include/ATen/ops/fbgemm_linear_int8_weight_compositeimplicitautograd_dispatch.h,sha256=WTyPo1IuzZbEiGo6txngpU-jMWVRnzIOkHUYrnbBUeA,1220 +torch/include/ATen/ops/fbgemm_linear_int8_weight_fp32_activation.h,sha256=3yrw-E6DlS_AEMsQcEIJdxRr19rZYsT4mn2vwt54BLk,1394 +torch/include/ATen/ops/fbgemm_linear_int8_weight_fp32_activation_compositeimplicitautograd_dispatch.h,sha256=eq6lQUt9oqADBCsCb_FZhepUpuhmFxft1akZiorbArU,1236 +torch/include/ATen/ops/fbgemm_linear_int8_weight_fp32_activation_native.h,sha256=pXBHxCRXh0Dv04wHSSDu2dYQ6pup07KfI2Eb9gb3UoQ,948 +torch/include/ATen/ops/fbgemm_linear_int8_weight_fp32_activation_ops.h,sha256=D4AhBZBISv9YbV95mVFJG0ow467D_0C-nI5KESWwgIw,1913 +torch/include/ATen/ops/fbgemm_linear_int8_weight_native.h,sha256=gP2h6COUhM4enFgI8TPhqcOmH9Zq2mYGxxKMZzfVDd8,932 +torch/include/ATen/ops/fbgemm_linear_int8_weight_ops.h,sha256=NSFL6EZyxesFHNY04vo7bOkgecjjEBYcfk0ZZJChNfE,1865 +torch/include/ATen/ops/fbgemm_linear_quantize_weight.h,sha256=r4NZmsvcL46eoxeVmNbTLSupO2O92kdjta_2RSQ8kUM,1048 +torch/include/ATen/ops/fbgemm_linear_quantize_weight_compositeimplicitautograd_dispatch.h,sha256=jrhuVbpaRgfX7n9Cn4F7ZiUMKMIo35R-okv4S29SPeM,1082 +torch/include/ATen/ops/fbgemm_linear_quantize_weight_native.h,sha256=Y7HhnR60kNBYDX29jtHrKMmwaMA8M8AniZwlGL669-g,794 +torch/include/ATen/ops/fbgemm_linear_quantize_weight_ops.h,sha256=ETt7KOzq-R5BtT2m41ZymB_3JIuPxdZsYOvFYsPxiTo,1425 +torch/include/ATen/ops/fbgemm_pack_gemm_matrix_fp16.h,sha256=ZH7OkWkVCTT0-5fQkHv7jI9ATQqaJ_8TvILfdtgOBYw,982 +torch/include/ATen/ops/fbgemm_pack_gemm_matrix_fp16_compositeimplicitautograd_dispatch.h,sha256=_hB1ElIij5AXi_N4Sy_hZRC5MBD7ndun_fVOPz87gP4,1041 +torch/include/ATen/ops/fbgemm_pack_gemm_matrix_fp16_native.h,sha256=8wpyhAiBln9Taj_sqfvJARfVDU2TTUNt5fb5lPvcauo,753 +torch/include/ATen/ops/fbgemm_pack_gemm_matrix_fp16_ops.h,sha256=vnke88L_XH0eZI4aCt7Gu5J1mpQIy4A7dRwZJJRkOpE,1280 +torch/include/ATen/ops/fbgemm_pack_quantized_matrix.h,sha256=AJ2lH-Vzh9Ye_DXfgV5PbrxOCXIZP2ixXvoYIhppiNA,1234 +torch/include/ATen/ops/fbgemm_pack_quantized_matrix_compositeimplicitautograd_dispatch.h,sha256=kCSvlteZQETsVtytyoGRA63NnS-8Pi9NnHxflgX-9cw,1140 +torch/include/ATen/ops/fbgemm_pack_quantized_matrix_native.h,sha256=1nEER8XyhgNr7VX-hRKWZy15mC9h92XOxqTFY4laQSo,852 +torch/include/ATen/ops/fbgemm_pack_quantized_matrix_ops.h,sha256=P9SAYE65ukiBn2y3JF_X4VqrQvsaUwa7eKghq6kNgVU,1933 +torch/include/ATen/ops/feature_alpha_dropout.h,sha256=IEOzoHvVUT665YiE5OltVEEPAfe0VvXSpr6ePW_hwnM,1247 +torch/include/ATen/ops/feature_alpha_dropout_compositeimplicitautograd_dispatch.h,sha256=7MNUIzUIGo9sxRNW51zRFWz71zKqynUZ1syimBzLjAc,1144 +torch/include/ATen/ops/feature_alpha_dropout_native.h,sha256=wxBM9GcRAQkrxu4mApXJknw__KcTf0-E0bNW2dPmvgE,856 +torch/include/ATen/ops/feature_alpha_dropout_ops.h,sha256=tZG4WA1FEFeRKh9PYfY2CSoBn1Q7_TbE-KMTTt_Q308,1961 +torch/include/ATen/ops/feature_dropout.h,sha256=LtdOsP_y4Wddw1fv60eQWaAt9knJzUrPk1OY143IM_o,1205 +torch/include/ATen/ops/feature_dropout_compositeimplicitautograd_dispatch.h,sha256=F1PqkcJwP3bCsmi7KoSCsQAf63AXEZ0dtLa8uFN2wZg,1132 +torch/include/ATen/ops/feature_dropout_native.h,sha256=lN63OrljGMVRMNqx75hZUHlnag9ksf6en-_gb2SCdn4,844 +torch/include/ATen/ops/feature_dropout_ops.h,sha256=CbEAQ33pnNUJrrNlhI_WtvcxtT83J10ixvUMD50FuBc,1925 +torch/include/ATen/ops/fft_fft.h,sha256=M11Bpu6vaLV4EATPMTVOrKmc2ow6bj7EQP3BHzQ_oWQ,5276 +torch/include/ATen/ops/fft_fft2.h,sha256=0wGgXCjXj1dgDBWaRKal1tURy_KuYNC781_uHMCbCHo,5569 +torch/include/ATen/ops/fft_fft2_compositeimplicitautograd_dispatch.h,sha256=VvqQFq-lPF8DjMk3UWxgvXPy0Wj5r8b9JZ-obTng26M,2108 +torch/include/ATen/ops/fft_fft2_native.h,sha256=DlXa0AHqJ9hFlh8ZgGTyl0aWRNi8U3KYsCa6OgHidlI,1046 +torch/include/ATen/ops/fft_fft2_ops.h,sha256=3H6YGe9ney9ZSc3IEOi0s6_cROL5OmLhs1J8XQgGNrw,2447 +torch/include/ATen/ops/fft_fft_compositeimplicitautograd_dispatch.h,sha256=GKBoWJn3LX6pI8xu03uO3t3LC7WG73XUcggG6H3X6eY,2043 +torch/include/ATen/ops/fft_fft_native.h,sha256=OddNp963aPDRrczthntRUIzSYZ8G_bMbO-KiDrBdwz0,1027 +torch/include/ATen/ops/fft_fft_ops.h,sha256=2dGAHOMeDl7jSYdweA4heUOAyZuUKEinx1dimYmbWsE,2383 +torch/include/ATen/ops/fft_fftfreq.h,sha256=NWlzS0IjAhh8GpcAFQUpilkG7BiKRw_i5b5gjLcvfFg,2018 +torch/include/ATen/ops/fft_fftfreq_compositeexplicitautograd_dispatch.h,sha256=h6v3goHYS8qamyTY5hxLZhkayR8LntViOgxNprp9umA,1416 +torch/include/ATen/ops/fft_fftfreq_native.h,sha256=J0Ii11CbYNVM_unyCRA_w6_QxSKp8aFspiYKsG5XAfs,971 +torch/include/ATen/ops/fft_fftfreq_ops.h,sha256=X7uK1Ndy6eCHNRUjLq8GaCblOYYyVz7Dc92q1o2GUgs,2319 +torch/include/ATen/ops/fft_fftn.h,sha256=UeQOT38Q76hI-5Ew_utnNhk4uTgIItOHt6IDuzK2N7Q,5709 +torch/include/ATen/ops/fft_fftn_compositeimplicitautograd_dispatch.h,sha256=JhEq2CWFST3wpAvyYLp5SZz69By_sMJqa4Q8R7ORX2s,2184 +torch/include/ATen/ops/fft_fftn_native.h,sha256=p0c7bE0iNWEtS4vBIa0BHkCcoKE-7HanIsdgJzBgO9g,1069 +torch/include/ATen/ops/fft_fftn_ops.h,sha256=S9c5O5I3TD_niIx8KO8p4j6Sodrek1oeNDvGnkiEG0Y,2491 +torch/include/ATen/ops/fft_fftshift.h,sha256=yQ_WiuirsiiizCi5okKsFKPcZeqbYe2w7VGrqmjtreg,982 +torch/include/ATen/ops/fft_fftshift_compositeimplicitautograd_dispatch.h,sha256=Y6LA_tyxazzn5yP8ykkFy9oHDXD686CO-XgF3dgTUDw,1068 +torch/include/ATen/ops/fft_fftshift_native.h,sha256=MOa0EAZlLvy7FiwenLfs4c1PMtdf5Cz2tA_NYLmu9jI,780 +torch/include/ATen/ops/fft_fftshift_ops.h,sha256=My5Mjv45q_Auc_lePE-Vw4l6e0uuASnrkpYOxAwgGlM,1330 +torch/include/ATen/ops/fft_hfft.h,sha256=gTfDc8GGlPEeHdDeb2_di2dLfE2M1d1OVLRQ6LNnEzM,5307 +torch/include/ATen/ops/fft_hfft2.h,sha256=uy1oF3Zc4ycrNRgDXqJSaQVFJWa_fG_hl9SYpeJZuXk,5600 +torch/include/ATen/ops/fft_hfft2_compositeimplicitautograd_dispatch.h,sha256=GcOG-F5AlVA03Uu-opJlJDW_Hua8RkXqfVylXBqhDiQ,2114 +torch/include/ATen/ops/fft_hfft2_native.h,sha256=qTENpXwSHQnjhuBL9d4Lv1Ydg4-w7yHJ9le-nAuApJ4,1048 +torch/include/ATen/ops/fft_hfft2_ops.h,sha256=dz_0r8pezT9mTLexp5iWR8VFjDg_So8YP5ZTvluF65k,2453 +torch/include/ATen/ops/fft_hfft_compositeimplicitautograd_dispatch.h,sha256=Yr3snNmW-G92XJftSlhmumUdmXZSk2TXlbUvVEGHz-A,2049 +torch/include/ATen/ops/fft_hfft_native.h,sha256=uQ05CzOpegxwzk7QbaGHVXyNvtwkJ9QBHFwR29zx9-U,1029 +torch/include/ATen/ops/fft_hfft_ops.h,sha256=pBP291CrOQnonQ8o0WZgd98rriqbT-G9jK0zcdKh9lg,2389 +torch/include/ATen/ops/fft_hfftn.h,sha256=yqW73zTcfcuKqAFCxZ-3d0m-cm-K6jVWqdWlmjAZYVk,5740 +torch/include/ATen/ops/fft_hfftn_compositeimplicitautograd_dispatch.h,sha256=oozUau26mclGYm0yL-J5_RKK5KQNyKDnJuK5Sd65KbE,2190 +torch/include/ATen/ops/fft_hfftn_native.h,sha256=zk72mLw0fLEOxKqfPHmLZvnPrIA51UEKMtvrRQp1woY,1071 +torch/include/ATen/ops/fft_hfftn_ops.h,sha256=rD61ulpbfZEAbxE9lRhhsSzp0xiiOTCwWtxcRsrHSas,2497 +torch/include/ATen/ops/fft_ifft.h,sha256=CbpOXQoczX4zacu2GqtHFGFCXFeLZI8RD1h9x33iOiM,5307 +torch/include/ATen/ops/fft_ifft2.h,sha256=B_UaNZEP4ixm0VaCN1yePeAVryTUZXcyuwxzaL2jgdA,5600 +torch/include/ATen/ops/fft_ifft2_compositeimplicitautograd_dispatch.h,sha256=RWkirtkMD5ZhYC0gXpFclnEKw8bC2qaIE0gpmp3X-GY,2114 +torch/include/ATen/ops/fft_ifft2_native.h,sha256=tXygv1YIADTYK9-xbin8XjibW7M62Myet6uE1wde1Ok,1048 +torch/include/ATen/ops/fft_ifft2_ops.h,sha256=Z0OWp9W9p_q5swvflnI5biPsi62cSghPZTien9XBplg,2453 +torch/include/ATen/ops/fft_ifft_compositeimplicitautograd_dispatch.h,sha256=1sqOD_6xaYPhhFPgc8uERKGbPi3WIF0h0L7NkjxXXw0,2049 +torch/include/ATen/ops/fft_ifft_native.h,sha256=Xs-2NrL6Lfy_OTCMETyGSuBsATYfY2CpQE1GWPWOGtE,1029 +torch/include/ATen/ops/fft_ifft_ops.h,sha256=jHOMhQd4W0PvTorj5jEJUSHW2s6PlyAU7BBnYGXGycE,2389 +torch/include/ATen/ops/fft_ifftn.h,sha256=MV2J_BWthgclOzYjGQP0iBQjVJNhUOoXgC1wIhtqwMo,5740 +torch/include/ATen/ops/fft_ifftn_compositeimplicitautograd_dispatch.h,sha256=ylI3iuR3GdhmE7OUP-3vMiLc2xy8qt8Na79CyTGKRlY,2190 +torch/include/ATen/ops/fft_ifftn_native.h,sha256=fh33OfkdYJ61_frIPaQImVbqek7FY8D4a3W0ARC5uRw,1071 +torch/include/ATen/ops/fft_ifftn_ops.h,sha256=_5hcv18jtNgpsKqCaviRENrdMRjs6vNtg61ygHEHAUs,2497 +torch/include/ATen/ops/fft_ifftshift.h,sha256=Ia5BXMcCS0jTGN3PQm35eOxnjwCQYlStRwAdUnSyT50,986 +torch/include/ATen/ops/fft_ifftshift_compositeimplicitautograd_dispatch.h,sha256=psnZTfM0wpG-8FXJ-Ajd8s9pDH7_uM818XGhynoK-hc,1069 +torch/include/ATen/ops/fft_ifftshift_native.h,sha256=n2aP4vhYXVr4OQ4EG70qAx2F0UAOy8G15XimYXg2a_g,781 +torch/include/ATen/ops/fft_ifftshift_ops.h,sha256=gGh28wwcZPah6MfPPCGbKYzMQvm6hfEqpZ5Qg9QwPOM,1333 +torch/include/ATen/ops/fft_ihfft.h,sha256=OSCim3A5EPy74f8ZGWMMB7cWdiSSSvmQ8i3RH8kGkBw,5338 +torch/include/ATen/ops/fft_ihfft2.h,sha256=BpmKJ-bzeumbdNrFSjmJQaAqM8fNNaCjxbWTdumoSTY,5631 +torch/include/ATen/ops/fft_ihfft2_compositeimplicitautograd_dispatch.h,sha256=NN8-Y6NQ47k98G8-1-mIr3DHpUqc8DPyFG5PW740aAE,2120 +torch/include/ATen/ops/fft_ihfft2_native.h,sha256=3JxULIKOLGbPlkT3mOmimmIIlgzeurjRzsg1MBy4Scg,1050 +torch/include/ATen/ops/fft_ihfft2_ops.h,sha256=H_7TwM9v8CddZDHkn2poXz_gQlKRUf_GEi_4n1Js89k,2459 +torch/include/ATen/ops/fft_ihfft_compositeimplicitautograd_dispatch.h,sha256=sI6YpbPpDngZwybOK03ajz72yY_HDOrdmSAipS2je5I,2055 +torch/include/ATen/ops/fft_ihfft_native.h,sha256=kStcTUMX7krIJjKp260Ix7hh67c121L2XVwAB1xBXeY,1031 +torch/include/ATen/ops/fft_ihfft_ops.h,sha256=k_nqM-o8GS7fYTE40xoDwMKuuQWtCLP8Ssr5w6jg9VY,2395 +torch/include/ATen/ops/fft_ihfftn.h,sha256=hhY_ITrEHKw6zWtg5QdueMuoEN-b4u8zbSy4BI2E43w,5771 +torch/include/ATen/ops/fft_ihfftn_compositeimplicitautograd_dispatch.h,sha256=ElvcxXpbHGHOgSaSFF1av_x_RCMxB_1n1Dz2m74Hlp0,2196 +torch/include/ATen/ops/fft_ihfftn_native.h,sha256=tK0B8zcF85H_r5c5Oo-XnBKr-l7-2wtBxdYCPLgWSx8,1073 +torch/include/ATen/ops/fft_ihfftn_ops.h,sha256=t6K6N_ejJj318Ht9oEBBIFw5Q1-4JAZhu2ayFBcWzEo,2503 +torch/include/ATen/ops/fft_irfft.h,sha256=Aug9ws-ifnVir2-p-QDcnv2HX3AZe6ahT8dghIlUAxA,5338 +torch/include/ATen/ops/fft_irfft2.h,sha256=b4DOMevddnkpxUtXtP3YeaEKcxdRB-flFZD3Ac105WE,5631 +torch/include/ATen/ops/fft_irfft2_compositeimplicitautograd_dispatch.h,sha256=0NzWTteqIn9oCPu7ZW0s-9C6dY9zTmWJcImUMwDkxDI,2120 +torch/include/ATen/ops/fft_irfft2_native.h,sha256=TnQiGSfnTlthusoJFtD_TzffgH5t4UGQIYohO7m8d58,1050 +torch/include/ATen/ops/fft_irfft2_ops.h,sha256=y4HRA8aiKneNL30jIm_0ZBExOC_chI_NNffnTZcGfSA,2459 +torch/include/ATen/ops/fft_irfft_compositeimplicitautograd_dispatch.h,sha256=LgUaE8M280ewQ238ImMNsjaXNlYkBy8BUyHKv88FWXc,2055 +torch/include/ATen/ops/fft_irfft_native.h,sha256=ZYZNyw5MFe8VwDmTDZt7y9D5_LoHEgp4gDDibDtCu-4,1031 +torch/include/ATen/ops/fft_irfft_ops.h,sha256=yyS0WTWqrQ3PEyYgm3YVyU1Z0d1hGCcgLeBZjTkzVHU,2395 +torch/include/ATen/ops/fft_irfftn.h,sha256=fWQ8jaKmicIqAjEXC30fXf7P0qz5PwhU_usqEDpiz_Q,5771 +torch/include/ATen/ops/fft_irfftn_compositeimplicitautograd_dispatch.h,sha256=JUbrqKQPxFnIh1S5X5dOL-FOGYdi8qJa8d_83XBBbwY,2196 +torch/include/ATen/ops/fft_irfftn_native.h,sha256=3rEB4LstsS-A4wNbZ6rZm9IlmPoJsLACu4W9nvGWM6E,1073 +torch/include/ATen/ops/fft_irfftn_ops.h,sha256=tqcyE97ohdbQfBv1yxn0DOjaslFmrFpYTEkcJx_zfi0,2503 +torch/include/ATen/ops/fft_rfft.h,sha256=wXupBC0vkiy3byz_UxgGpcfJ49p4wzX0ZutwYwFyTsc,5307 +torch/include/ATen/ops/fft_rfft2.h,sha256=5aL8vROWEYD5FYWKaLT5uyt2DePnMGpCkTPKt5ejnvU,5600 +torch/include/ATen/ops/fft_rfft2_compositeimplicitautograd_dispatch.h,sha256=1fSxwMhyPrzWghUSmCFaREtLYjs0MlSkbmOvplQhD3E,2114 +torch/include/ATen/ops/fft_rfft2_native.h,sha256=KnRTOTNzW8GqHghack_T-f2LA5F6mAfWbRyEVuMaogU,1048 +torch/include/ATen/ops/fft_rfft2_ops.h,sha256=81kX9nrqx0d_agv4AvbuxB6i3ubWUbqk2OWqs9FCSi8,2453 +torch/include/ATen/ops/fft_rfft_compositeimplicitautograd_dispatch.h,sha256=boLg9FJ5a9I2ZISLHmN1eAWIxcZQS9Jeb-5Gr-h3BrY,2049 +torch/include/ATen/ops/fft_rfft_native.h,sha256=yhX8ogoSu1cfodcYXMsNGJEKL6mAG6t4Xy8jOhbpPDc,1029 +torch/include/ATen/ops/fft_rfft_ops.h,sha256=gRsO4HlemDDbRRJXMMsrg0-ei9OLs9v2qpCXOeU8BFs,2389 +torch/include/ATen/ops/fft_rfftfreq.h,sha256=V0wZvl3hHrSJ38A_0OD-R1kHiCZfeN8FlISXNHaky20,2031 +torch/include/ATen/ops/fft_rfftfreq_compositeexplicitautograd_dispatch.h,sha256=86fPq1shdnB9jGLvDkZnTOn3wz-O-XQHCPxMDkrph0M,1420 +torch/include/ATen/ops/fft_rfftfreq_native.h,sha256=9trMZVfdreHMz5oh6EwAQNlF14RAlWu0XmTC7ulbTEA,973 +torch/include/ATen/ops/fft_rfftfreq_ops.h,sha256=mH0kfDrx70NFYBylozAISjXicttZRRqU_CFqsKU8eME,2325 +torch/include/ATen/ops/fft_rfftn.h,sha256=Los8e2Z1JWQXuLJ4YHiXEvETTen6XU8oDx-LMA20py4,5740 +torch/include/ATen/ops/fft_rfftn_compositeimplicitautograd_dispatch.h,sha256=q6d8x-DPk2utIvXzErWwAWHZfEWQdOOIX9yz7fr_dA0,2190 +torch/include/ATen/ops/fft_rfftn_native.h,sha256=g-dG_BIECIrM2j4otNzH64paS7-S3TAcf3fmyaXvfdI,1071 +torch/include/ATen/ops/fft_rfftn_ops.h,sha256=NyIpFN6IuvWLEb8x5cGSWKdI1rIATr8oNzdsVOigJSI,2497 +torch/include/ATen/ops/fill.h,sha256=CmYsDrpGMo3LC8A3qWCDjquXPN3puo1sqmj_exlmWxE,2528 +torch/include/ATen/ops/fill_compositeexplicitautograd_dispatch.h,sha256=SMbE8E7Cur9L5SPnzHDkMXAQ8hmGrFN2cfEJbDW-rUA,1530 +torch/include/ATen/ops/fill_cpu_dispatch.h,sha256=1wxfvPbjfmKG1p-p6TT8P3xDS83j7D0EfCZ2GXU1Bxk,1070 +torch/include/ATen/ops/fill_cuda_dispatch.h,sha256=mdrA6gVYyEgelG8S-td_a3IhKlptb0Co8ofIe6eBpKo,1072 +torch/include/ATen/ops/fill_diagonal.h,sha256=6MOHN0GTTTQmcnt3tLf275O65XOV1MIH94mZIOVn48k,764 +torch/include/ATen/ops/fill_diagonal_compositeimplicitautograd_dispatch.h,sha256=eOL7prkbALjYa1TH2EV00C0JIvg-WIxO-KIOrtmUXq4,1070 +torch/include/ATen/ops/fill_diagonal_native.h,sha256=fo5-lcVXdX2LcokflqCnXhXkrrcgiuOQ9paqL6eRrVM,782 +torch/include/ATen/ops/fill_diagonal_ops.h,sha256=g-mqRusbFaGWt0qGHHkHT2mUqO5Ndu1z5OAShSJ7piI,1377 +torch/include/ATen/ops/fill_meta_dispatch.h,sha256=15gVrQvkc8Cvpm3MSV3oSuKzDh-SYebjWZ-P-ym7F-w,1072 +torch/include/ATen/ops/fill_native.h,sha256=FINbaiTTgMSkz9m_PievKrWX2z-vdOFMr9uOhaMVnmE,1780 +torch/include/ATen/ops/fill_ops.h,sha256=08a4ZKO6VWXusZm89fzd6AhFln0xEhVwLVwGPTIIhcI,4491 +torch/include/ATen/ops/fix.h,sha256=LjhIoTc-Pc11lqgSHnFhdOG8MeMXOC0xhot8PsahYPs,1384 +torch/include/ATen/ops/fix_compositeimplicitautograd_dispatch.h,sha256=Ww9OtVDxfWUgpOcdmHXD3OPLs7RksbZKq9UTE2mn3xk,1214 +torch/include/ATen/ops/fix_native.h,sha256=DUkMUeoWv4Y_zvX6P07csWwKK9NgpwhXGbc1PmuQvaU,850 +torch/include/ATen/ops/fix_ops.h,sha256=L6-wobHT_ndsDPXDNa4S15uycQ5gQKtruC2NHLsi6ms,2273 +torch/include/ATen/ops/flatten.h,sha256=UmXiDXJetL7i7BMKM2TRgWb2SuYnXzd_U89oo4z3-pM,1017 +torch/include/ATen/ops/flatten_compositeimplicitautograd_dispatch.h,sha256=398GWbz5C6jSEqD_b9jFcPIbQqgiTM9Q_IZhoR9nAV8,1060 +torch/include/ATen/ops/flatten_dense_tensors.h,sha256=hQzF31WjAfioGMzTst8m5Yh5oFpeKTO3_gXx3HZYETY,958 +torch/include/ATen/ops/flatten_dense_tensors_compositeimplicitautograd_dispatch.h,sha256=mwmLr9TQmOa2YUcyrSvtCOpDhXoiz3WmtmLcV0EsoBk,1032 +torch/include/ATen/ops/flatten_dense_tensors_native.h,sha256=baRJPS0D3sDDeiAtG-FLl46Y5e9Sp4-jrnFLeyaEu_s,744 +torch/include/ATen/ops/flatten_dense_tensors_ops.h,sha256=-wk6ErOd0adX6xxzSyjdFaGqdxmpEOUHZQacUUrCCS0,1255 +torch/include/ATen/ops/flatten_native.h,sha256=dOGkOxWGv4zDWWKUemkDadHNwL8SnydIPcPqIa_BXig,772 +torch/include/ATen/ops/flatten_ops.h,sha256=fGpXCJkgVtCterySfQN7mhQLZvKyInsMFtaw2l0M2Rs,1375 +torch/include/ATen/ops/flip.h,sha256=2rRZdFRuX7vbvvMxjsg8-EVYifzDso60Rcp7t6nxqNE,1381 +torch/include/ATen/ops/flip_compositeexplicitautograd_dispatch.h,sha256=otnkQYBXa0NOI33GtBMW7JtD41-RDX8JaIMwjxQYrDk,1161 +torch/include/ATen/ops/flip_cpu_dispatch.h,sha256=6BVlvIbh_YM5pGjTHgewv5hG-QDMzxsHaX69N4NIhPo,994 +torch/include/ATen/ops/flip_cuda_dispatch.h,sha256=j3ZoleuxEb3q8S7ZUCWApDgOLmhLkkCnvRj_AgcC7AU,996 +torch/include/ATen/ops/flip_native.h,sha256=5Cfw7aoDe0kaqApnodI4w0eIU6INYofELgwwy_w9fTM,848 +torch/include/ATen/ops/flip_ops.h,sha256=Ytnfwlev3m8eCrDoTt02QeD4ICwb6R7KgOBeM6jjHaE,1935 +torch/include/ATen/ops/fliplr.h,sha256=kVQMLQ7M1sBGTDI-XB-S9z2rnYiVMt9qcuHZ3t01Ryo,891 +torch/include/ATen/ops/fliplr_compositeimplicitautograd_dispatch.h,sha256=1ZXDrZTe_PEYlSKfLQfsS1Ya-418EjrMoSX0VbRaho4,1018 +torch/include/ATen/ops/fliplr_native.h,sha256=rMJyOgWZgN8B-nblfri1vyYCpy7dvidNPe6YwyHdjiE,730 +torch/include/ATen/ops/fliplr_ops.h,sha256=-AE_Av2caiEDa6pMpsglj17cFhGIlrJdxnvR1W4sAN0,1211 +torch/include/ATen/ops/flipud.h,sha256=EU_INCEcxy8U-uv8TNN9nf5KNsJ3Y43eDo0Gsdh0MrQ,891 +torch/include/ATen/ops/flipud_compositeimplicitautograd_dispatch.h,sha256=3j-jfDVZvyoOqh-EyQsZ5V6kXzcNbhsG9_X-at2Gpm4,1018 +torch/include/ATen/ops/flipud_native.h,sha256=4hbi2pH6fdLMEbSSfVqWETvRrGVuErvXrMIAG2aN7yE,730 +torch/include/ATen/ops/flipud_ops.h,sha256=H5M9oEFOLn9b9vwSGYplNthValqHCVq9NCmn42dxcWw,1211 +torch/include/ATen/ops/float_power.h,sha256=p_WfNyBweg7YRlGF20luBXFYm4VJDhJy0Y6CNnoT8aE,3185 +torch/include/ATen/ops/float_power_compositeimplicitautograd_dispatch.h,sha256=3g36PswNAx6RgKDLaVZ5BQTK5E21v5F0eHigQyLxL6A,2073 +torch/include/ATen/ops/float_power_native.h,sha256=CNKKLNUxh57vqzCDX4zBtGrJN86iqZ82XpkcUTlmqpE,1446 +torch/include/ATen/ops/float_power_ops.h,sha256=ylPgKexYH-oXFhNQGj3_5AUSPRtou8oRGjHb_YkJlOc,6106 +torch/include/ATen/ops/floor.h,sha256=jeMqZhwHjHFAxDoRfBWEaPC0TcKTcFT8jeMrtUoq_ug,1410 +torch/include/ATen/ops/floor_compositeexplicitautogradnonfunctional_dispatch.h,sha256=KxcARUIkRIxefK_mieTzzFPE765ud5D_zQicBWxAdzk,1093 +torch/include/ATen/ops/floor_cpu_dispatch.h,sha256=vZD7gChTT-a8EH1fIsbOcuuvqxbyHvbJSi1rVQUwyGI,1178 +torch/include/ATen/ops/floor_cuda_dispatch.h,sha256=RpDy36nL6nYMGswyyKUKTgAEAvsdkzmTVPmGIPTUuRc,1180 +torch/include/ATen/ops/floor_divide.h,sha256=-G13tDwJbvESjQQ3bGAf9P-c1pKS-USjrGwEBaEaZHk,2244 +torch/include/ATen/ops/floor_divide_compositeexplicitautograd_dispatch.h,sha256=JVHa8paW7S8RGEhigBT39u77dfc-AK4DTfXxrejnkoE,1354 +torch/include/ATen/ops/floor_divide_cpu_dispatch.h,sha256=YGvvcwlAyxmCf3UolSOfV_9IyW2srv8aWFztXZO5OnQ,1310 +torch/include/ATen/ops/floor_divide_cuda_dispatch.h,sha256=5W1PuMzmsZOp6mlaHR7bMgiLaqiX4TbN1dJFyR5yK54,1312 +torch/include/ATen/ops/floor_divide_meta_dispatch.h,sha256=K7dTzgvaaCm9ijjhuaYZuj2PF4bXM2KHtWcCcSDGuTk,1005 +torch/include/ATen/ops/floor_divide_native.h,sha256=7tfQOpKTR5IoBSFqwHUsXCB3gc4yjtgIMtjbLb1JzmI,1549 +torch/include/ATen/ops/floor_divide_ops.h,sha256=bhIBBESa_XKcsbbnVj1LHoIVZqJ0QTS-KAVxAmLJuyU,4594 +torch/include/ATen/ops/floor_meta.h,sha256=i86x47d9H7yJsclw1Ti-HE2jVhJMPsfdfH08Gixtzpw,820 +torch/include/ATen/ops/floor_meta_dispatch.h,sha256=puYl619XWp4Ps0IM6Sk_8QKbR6CzA2CnmZrg116SHzc,1180 +torch/include/ATen/ops/floor_native.h,sha256=L19rirdAt1vQNq3RsGaRWw5rMWxBdRh6_K8_uxeVBNk,1261 +torch/include/ATen/ops/floor_ops.h,sha256=-9ZqNwqPXO37mPBu5n35ffp7t6unQJG4hThKjOJ0FMU,2291 +torch/include/ATen/ops/fmax.h,sha256=C8xrycKj0rAkQ87es-fFKDiGCrtik3J1nAJRNysfkzs,1402 +torch/include/ATen/ops/fmax_compositeexplicitautogradnonfunctional_dispatch.h,sha256=CJ4yQK6B8tc8VJHsS0cr4T9K2kCAXnnnXS3yMevzGgs,1068 +torch/include/ATen/ops/fmax_cpu_dispatch.h,sha256=Mj5TBFWU6BdTslprzpiCPrreCmtbT1SFJy2UqIRlNko,1203 +torch/include/ATen/ops/fmax_cuda_dispatch.h,sha256=1_swZzGFZu_YHxzk5MYHG2Nl6Cd5Q_6e5o93bACEklU,1205 +torch/include/ATen/ops/fmax_meta.h,sha256=VQzFhCpOHumFB7J7h6a3yQDQUcvabsjF5jjkoNmgSFo,845 +torch/include/ATen/ops/fmax_meta_dispatch.h,sha256=88I5nqvOuHgZM4s7wBNK30jluZ7tIf-YjiMvPiY8W14,1205 +torch/include/ATen/ops/fmax_native.h,sha256=7Zuy1wo9ieWjUOcqKIBx4poJn3iztBodsSpmIzYYUaQ,870 +torch/include/ATen/ops/fmax_ops.h,sha256=grtHjIIueHpaM77vrwhy-i6VXOFkmzRePcNkgCjfzto,1961 +torch/include/ATen/ops/fmin.h,sha256=LtR-fLULsZd9lKA4ryRFCOToxLuzv2ZjpaxdE1RODbs,1402 +torch/include/ATen/ops/fmin_compositeexplicitautogradnonfunctional_dispatch.h,sha256=-PFMakY72hswvDN7x6rpEuleI_zLy2SvFFuaXLAsDkE,1068 +torch/include/ATen/ops/fmin_cpu_dispatch.h,sha256=RSsjBPS7j0xoAlc3lxKir-zy1tCkBG1IR1I-0P9md3Q,1203 +torch/include/ATen/ops/fmin_cuda_dispatch.h,sha256=PBUqaAsBs6gdczqr4Tv0IXy0NcAuVJVTTmHE8OgOGfQ,1205 +torch/include/ATen/ops/fmin_meta.h,sha256=asGDdC4BJCNclr5liYoPogohKHxW9eqf3yJVZixFzbU,845 +torch/include/ATen/ops/fmin_meta_dispatch.h,sha256=DOztqHYtB_wPICD7KnZbuReubjU3sy5ieecsZ6PpWhs,1205 +torch/include/ATen/ops/fmin_native.h,sha256=WapxsiIYYKqXK1m8pY3-a62LIYsvMYkC7aSGK_kHhcw,870 +torch/include/ATen/ops/fmin_ops.h,sha256=b4LZPNU1-K5_2U5C9ZJr3ObpfFygWBxz_1ONVngawB8,1961 +torch/include/ATen/ops/fmod.h,sha256=OJxMPap8iFBFybff9t5kryaO-lTRXttTAoYfPRttyaE,2134 +torch/include/ATen/ops/fmod_compositeexplicitautograd_dispatch.h,sha256=_bAyJn5u-v39eSmgWTlEsZx50J2ll9IrtYbKdMr7Ve4,1322 +torch/include/ATen/ops/fmod_compositeexplicitautogradnonfunctional_dispatch.h,sha256=RqmMhxykawrRTo-nrCWkUMrj5TVFuxJzQzg6k_TTGMc,1143 +torch/include/ATen/ops/fmod_cpu_dispatch.h,sha256=Lza0K2I5e1p84KQOP53lrcyjUwx1r_feAIipwK05Cv4,1278 +torch/include/ATen/ops/fmod_cuda_dispatch.h,sha256=s3cTmJQC_4n2DR9xlGaVy4-s4vzLKimIx8D-ImjJWPM,1280 +torch/include/ATen/ops/fmod_meta.h,sha256=C1Jpy-wydYgr99CDE0fXxP9iNmRheNY3CXvsAWw10iE,852 +torch/include/ATen/ops/fmod_meta_dispatch.h,sha256=6nX20SaIF9N8vy_VX9ZQbniey4W87tJ0k1-WLw-ffNE,1280 +torch/include/ATen/ops/fmod_native.h,sha256=4fIEEWKrMzfDtfi4df2IIYjbeHQ7R0wmAOjMEhYoKU4,1132 +torch/include/ATen/ops/fmod_ops.h,sha256=iX2alweqSvcLvAqq62fWjrah-wlqfaTBbV-ZfFKkD-8,4491 +torch/include/ATen/ops/frac.h,sha256=qY580vdXLvpcuzvQbieYB-4i9Lbd6jMVSY6o4uqSD5A,1397 +torch/include/ATen/ops/frac_compositeexplicitautogradnonfunctional_dispatch.h,sha256=qsVHJtG7pueSSM9RgwvveigUPOWU1xM-inMzPAMD68c,1091 +torch/include/ATen/ops/frac_cpu_dispatch.h,sha256=sU0VMCJ_gaPO-FlYYxIj4jux4OXk5nX9XIK2O3mEyRI,1174 +torch/include/ATen/ops/frac_cuda_dispatch.h,sha256=t5re6MKQvGtvB08VMd8C28ByXL9gXDV6rKQTOw0tuzA,1176 +torch/include/ATen/ops/frac_meta.h,sha256=RYWiYd5NTHdmBY9uoE5fmgTDiepOSVDP9id6dG69fuU,819 +torch/include/ATen/ops/frac_meta_dispatch.h,sha256=wK11eaXrEGI14x5Yqq8qso6ldJmWE2gTIzJFQCX3kUk,1176 +torch/include/ATen/ops/frac_native.h,sha256=aIR5V8yg_K1pZ6F1y3pJ5uE0qnmgRxEqyoXLbq_Q-F0,1252 +torch/include/ATen/ops/frac_ops.h,sha256=Qt3H4DnwZKE-AxfZJJgapP5JpU5nFLof_u8rF5MR8QU,2282 +torch/include/ATen/ops/fractional_max_pool2d.h,sha256=cxNTlUUqx8QyneQ_C2QI--bHxr5smaJOHak4VAzFHTk,2274 +torch/include/ATen/ops/fractional_max_pool2d_backward.h,sha256=SqwUjv4KyMMlEHjZMfvdubt9HBxaSVsmnEs8eUuv1Ck,2317 +torch/include/ATen/ops/fractional_max_pool2d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=rpaTwPZScDBQR_r9yQr0DPY27AoxlBOovbTpve4FZBU,1186 +torch/include/ATen/ops/fractional_max_pool2d_backward_cpu_dispatch.h,sha256=SYpAqGh2YyEpR-HkhNlkkWSUICwFI3Eu8Ps6TJWEdu4,1571 +torch/include/ATen/ops/fractional_max_pool2d_backward_cuda_dispatch.h,sha256=aB4QDIhPLBRSLrxnzDJUNx_4yY6PuiFHF2OdG2ZWkjM,1573 +torch/include/ATen/ops/fractional_max_pool2d_backward_meta.h,sha256=GThhHLOO1b8mGaEGyOtYnGaLDaNkPvhZnIWbTYEtE64,963 +torch/include/ATen/ops/fractional_max_pool2d_backward_meta_dispatch.h,sha256=tF3BQc3Pxozu662IB6gROAUHMPW0-hffLMKymd1ptTc,1573 +torch/include/ATen/ops/fractional_max_pool2d_backward_native.h,sha256=8Dc6nr3djwjesHHa_V8u-U1oQqxV2BijQZfzUTJ_hrs,1362 +torch/include/ATen/ops/fractional_max_pool2d_backward_ops.h,sha256=HURVUw_JKGc8QFFa8EF7MOoi_GqXzu8KK3bcJkFvkAM,2759 +torch/include/ATen/ops/fractional_max_pool2d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Vfyaj2bpg5DLXulVAp7pfr7yiRt-ulmf8wNy6nUwXNc,1177 +torch/include/ATen/ops/fractional_max_pool2d_cpu_dispatch.h,sha256=0V-fmkeZH-RDpFZGdyaLkVwHHRsJCOKuptZRCrf89WI,1584 +torch/include/ATen/ops/fractional_max_pool2d_cuda_dispatch.h,sha256=CKZmmpH90_hn8hZ_UiB2mj2UtU1FB9oyaMsE-mbwfEg,1586 +torch/include/ATen/ops/fractional_max_pool2d_meta.h,sha256=Bgr5f2-LrgPvrFR5CMZaH2RFrP_TaHB9vrmfEU34ELA,929 +torch/include/ATen/ops/fractional_max_pool2d_meta_dispatch.h,sha256=PagdMeRMM2tkhaJMGriTXL3MVTMhuD_roMJrWMCpkX8,1586 +torch/include/ATen/ops/fractional_max_pool2d_native.h,sha256=Mt9PbQxk2PwIiEGBDk5-suNTccnKuVMx2Yw6QitWkJw,1323 +torch/include/ATen/ops/fractional_max_pool2d_ops.h,sha256=fw9DKaasKi6l2PGaXmrLoiHfpzIfbzDJQcoMf4lsEko,2773 +torch/include/ATen/ops/fractional_max_pool3d.h,sha256=p0ZIF4OZoYV34lnO1_UPci5s7HGp7h7VRJDQOmGxTnk,2274 +torch/include/ATen/ops/fractional_max_pool3d_backward.h,sha256=_CFhrWIpHXBduLpEVb1XWlhrA0mnzo6-gAfJggi21og,2317 +torch/include/ATen/ops/fractional_max_pool3d_backward_cpu_dispatch.h,sha256=fH1a9hlmo0qyXDwQAYWxK-Ozwd_SpTO1kOse4UiNz7s,1571 +torch/include/ATen/ops/fractional_max_pool3d_backward_cuda_dispatch.h,sha256=XFl-vsQnMLVpeDhRO--AzJhcwwHrE3sDrIdulurmEGo,1573 +torch/include/ATen/ops/fractional_max_pool3d_backward_native.h,sha256=URU5O3duKKLPz3liV-EsY5IWgypU4eyewVpa8ArL4oE,1540 +torch/include/ATen/ops/fractional_max_pool3d_backward_ops.h,sha256=HahbbIEB9on2PBL3aS_JhMd3NZPCSmJ-j1FtzeKYoFo,2759 +torch/include/ATen/ops/fractional_max_pool3d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=mvXd0szGn6Np92Y4GeCqYtnyi6araZHJF0gTYfN9AJM,1177 +torch/include/ATen/ops/fractional_max_pool3d_cpu_dispatch.h,sha256=C6Hx4MhTBY58O_L_eMaMepRMH4ZNbOEdTT52LldCo5o,1584 +torch/include/ATen/ops/fractional_max_pool3d_cuda_dispatch.h,sha256=NwWnlhnKMC3x7yQEJQgObe6u-JNZBuXhqCXKn7w6UG8,1586 +torch/include/ATen/ops/fractional_max_pool3d_meta.h,sha256=uHzdLcs_itpvkm-8Axv1V9Ni8d9RKaMY9lHoWmpd1HI,9861 +torch/include/ATen/ops/fractional_max_pool3d_meta_dispatch.h,sha256=clnwBmvmZ6tCt9iFceJ0lv8xFyoBImN60bC2zJGW_yk,1586 +torch/include/ATen/ops/fractional_max_pool3d_native.h,sha256=jJZjNstcckPWOIX-0Su_Jr7Ue385hk5j0pShh-G-_AY,1593 +torch/include/ATen/ops/fractional_max_pool3d_ops.h,sha256=kUKtr4xY5oeknFc50d8NIgE10iWejSuGP2k9azrIyKQ,2773 +torch/include/ATen/ops/frexp.h,sha256=lsto9Fz9Gce5RkHWxWlVFrVgFF6tck8DGv1rljq0SE4,1622 +torch/include/ATen/ops/frexp_compositeexplicitautograd_dispatch.h,sha256=gkewRnZ-TlaXiFdePQuPkUNctjxs68glpFBG9Fiz-4g,1042 +torch/include/ATen/ops/frexp_cpu_dispatch.h,sha256=uZsXm8jR29ztFjYcZf2IZuy_Umx91ik2h937U5X_g8M,1185 +torch/include/ATen/ops/frexp_cuda_dispatch.h,sha256=DAB94PU4tagA3yOQ7uzuhwMGhev5UoPj3YWkHs8tc1Y,1187 +torch/include/ATen/ops/frexp_native.h,sha256=R2xmWQm9i6MsNwOyLyzrw_eZBsuScIgQfNhOS5jRg6M,886 +torch/include/ATen/ops/frexp_ops.h,sha256=4-DwHjVWJpHZdDQMIOXEBSg4Xrk1Bukn5_xwc9n_dB4,2148 +torch/include/ATen/ops/frobenius_norm.h,sha256=Ljau3LSqZpAOClM4xU0XN58hokwbFGxJH47WLhZ3QwM,1624 +torch/include/ATen/ops/frobenius_norm_compositeimplicitautograd_dispatch.h,sha256=Qrou2XNU8ZQyJDsEwnmOpHJfjvj5ic8JJMKl4Nk5LHk,1316 +torch/include/ATen/ops/frobenius_norm_native.h,sha256=SXauc9EZYRCpU4N7KpgWUuvAosUxSBngI9OmPGj7NbE,900 +torch/include/ATen/ops/frobenius_norm_ops.h,sha256=jiB3kfUvIrnswqUF_PR1EGz0klvn6OQ-g4wgljRBdvw,2110 +torch/include/ATen/ops/from_blob.h,sha256=2J8awGnrU51CV7f9rrSulkxc3v7fFmI3ThLRn-gIzJA,4399 +torch/include/ATen/ops/from_file.h,sha256=bKqQNCw9ThLSVYi6NPa17nvK8_o1Y1km4P92XQc6TIE,2462 +torch/include/ATen/ops/from_file_compositeexplicitautograd_dispatch.h,sha256=g-J2jY9VRLBVbHsL06rKqkB4jJ8MnnWxW_f3vyuvPJE,1270 +torch/include/ATen/ops/from_file_cpu_dispatch.h,sha256=W33xVoEQr2c8e6G7-4IZ01eywWEads4iAWQZ552oR80,1352 +torch/include/ATen/ops/from_file_native.h,sha256=ytF2a3bDdutQvN4glY23DBoCzTomT-EYrSmNkTvWCMY,1114 +torch/include/ATen/ops/from_file_ops.h,sha256=cSxTyW4huzL-pBY0un9o3B4egw2Vp1qf64BgGoyFf-A,2727 +torch/include/ATen/ops/full.h,sha256=DnL3gW4wKSFSY25ZtGUctwjjl3J_Pibgx_HV-QOvKGo,6478 +torch/include/ATen/ops/full_compositeexplicitautograd_dispatch.h,sha256=gcSpYE2jthorGWO6VyFRJRM-paOmPn19XCZrqT3frY4,2096 +torch/include/ATen/ops/full_like.h,sha256=_kjVJ5ccsE9Gj0zHyUDVMpV0CY78_Il9MjfIslic6eM,2710 +torch/include/ATen/ops/full_like_compositeexplicitautograd_dispatch.h,sha256=GMOt6ayOgfcK4CtV0FHYawSaUhU1n5JeUmxo1LoUTN0,1766 +torch/include/ATen/ops/full_like_native.h,sha256=l-CUK1VokH7LWXbacXCizZy4FG2wiscYILZvMEt_ccQ,1146 +torch/include/ATen/ops/full_like_ops.h,sha256=PS9-gP2lqGFuicySJKcThE3ZMa3ENX1IlMGDqMRpGps,2851 +torch/include/ATen/ops/full_native.h,sha256=SjLRfvu4pGe_sLHAJmJcZMX8BWpDFG7jFq4cJA4R8YA,1017 +torch/include/ATen/ops/full_ops.h,sha256=P-v_lSOKTuMYRfiEKuQYoXUOR_5uUlRRA-oifd7tTPw,2497 +torch/include/ATen/ops/fused_moving_avg_obs_fake_quant.h,sha256=ZqRhBq4mXANLBZtz2KuAIV2_QtzB-Xlt-YwS3AHBMow,1706 +torch/include/ATen/ops/fused_moving_avg_obs_fake_quant_compositeimplicitautograd_dispatch.h,sha256=qpyMZX0q8jPA7hTwZI-y3XIojUoAbU3UzAr-1_XWbjY,1344 +torch/include/ATen/ops/fused_moving_avg_obs_fake_quant_native.h,sha256=fvXyZM3zFbY58f15vtpVh3-EuJgpRDKd2_CytQzgWjU,1056 +torch/include/ATen/ops/fused_moving_avg_obs_fake_quant_ops.h,sha256=_u3kd5Q0WSt7_BVRH1ovEjmYBITPJYNydRFtydgAoHU,2263 +torch/include/ATen/ops/gather.h,sha256=uPyZosOpXby5bD62IVbKm3XPGVgiy4TEtY5PaJZjMkk,1683 +torch/include/ATen/ops/gather_backward.h,sha256=vhNYOZXNLn0I-JJZ0toD1CYW7TCAZVF9fO32ZGP8gNM,1094 +torch/include/ATen/ops/gather_backward_compositeimplicitautograd_dispatch.h,sha256=RIjP3JnSvef_v51S3I7RbmIw1m6XbkzMJ-l8dG0UANI,1109 +torch/include/ATen/ops/gather_backward_native.h,sha256=o30n_u-LiFTT8u9Vhr3RciyQxXme77elKGBUGvXebjY,821 +torch/include/ATen/ops/gather_backward_ops.h,sha256=aY4hINjO0WQw3XEXoQte0jhnziR0AbXyRpApZGIPomc,1511 +torch/include/ATen/ops/gather_compositeexplicitautogradnonfunctional_dispatch.h,sha256=eWri3P8Ujanm1cdoCnjxia8VZ0rtjT_Qv7Mg6RMIaCY,1107 +torch/include/ATen/ops/gather_cpu_dispatch.h,sha256=pdk3G3NyqS0ljfRv4T7LGu2ekeEkZUJNAWmJBN5AirA,1314 +torch/include/ATen/ops/gather_cuda_dispatch.h,sha256=rbd2ri9hG86gHYxywmMe4pW1F6VDY1R5rKP3Ntzf0_w,1316 +torch/include/ATen/ops/gather_meta.h,sha256=n_-1fl1QfWcfJG7Ha7I1sR83QUesxW4jtNB2PFhf44o,878 +torch/include/ATen/ops/gather_meta_dispatch.h,sha256=T9x3pcLxQVU31e221aLuWswMc17AJ6M-wYk9iMe1rqI,1316 +torch/include/ATen/ops/gather_native.h,sha256=hhUq4oa05xhWQlMQAbs1jAaPtNrPL8PHLacUzQ-_TOs,907 +torch/include/ATen/ops/gather_ops.h,sha256=x7f6JvL2cAEmPr0_lCyol9kHckXiPsHlqp4J44bIZn0,2196 +torch/include/ATen/ops/gcd.h,sha256=dsJg-9nh9KIfD26ioieG0GlQA4fFDZJMH8vxmJvjADs,1572 +torch/include/ATen/ops/gcd_compositeexplicitautogradnonfunctional_dispatch.h,sha256=oum-ltk-OvL0q5wDAQssdewVcvt3Jf46rj4cEHw_B5Y,1141 +torch/include/ATen/ops/gcd_cpu_dispatch.h,sha256=YK7nrMwISnF5m07aNmxgYQ0XDxdbVXAiR73X67EX6pg,1274 +torch/include/ATen/ops/gcd_cuda_dispatch.h,sha256=YHFX1WM-B93lVqieNC8ptr8fjGzPfUOPtFNWWqfFH_g,1276 +torch/include/ATen/ops/gcd_meta.h,sha256=GAs9aVubl_vMTZV_0LVjsYYf2lBRvsc3HCy79uhiBgc,844 +torch/include/ATen/ops/gcd_meta_dispatch.h,sha256=pU93t0zI3ktd2heasFWFwkLiwsZ3HHUNgg-R16AM6no,1276 +torch/include/ATen/ops/gcd_native.h,sha256=YQ6UQjhVSHJHfnnd_BfjB6ogsx9V9R2d6MYbHOlF1MA,867 +torch/include/ATen/ops/gcd_ops.h,sha256=s08wXStZ8sm8pl6oMVzHflZ5I5zT7iYeIce5JRQEuDs,2531 +torch/include/ATen/ops/ge.h,sha256=4htS61aHFxyeVyTApFAgWJOFO11-uEqUSiMwwIFzjIE,2096 +torch/include/ATen/ops/ge_compositeexplicitautogradnonfunctional_dispatch.h,sha256=vNmAOi4mf-a5MVqKnxGC-Tc00ta6QWlhpGjYq6sB_gE,1288 +torch/include/ATen/ops/ge_cpu_dispatch.h,sha256=xbip_u5vJr9F9tFnMT748yBohuPtG3S8ThskqDzoxRQ,1620 +torch/include/ATen/ops/ge_cuda_dispatch.h,sha256=MFLhSA7zXyN8veoR9FPTUI3q0OiwSF8f0LQZFzJVZnI,1622 +torch/include/ATen/ops/ge_meta.h,sha256=fAfB6lqROadWzN2r2lTzK1fZyujjjJXeLaoIamqWGgg,989 +torch/include/ATen/ops/ge_meta_dispatch.h,sha256=Cr8asEW5IqeKgiRRZF-JiqvVd47Er2YYHh2M5jF_Lg8,1622 +torch/include/ATen/ops/ge_native.h,sha256=b7LAzyFNtMrv8sQqnp_KZwzXGUS1IcXmOXm8fSxhSjo,1549 +torch/include/ATen/ops/ge_ops.h,sha256=202W2Q8w1E64PoHu_jg8u-S9QoCnS00ZedbtcPkkGcU,4455 +torch/include/ATen/ops/gelu.h,sha256=vl3Y21MXm1J-df-sllHwcHtPA83d9gtj1muB97J8Q7g,1692 +torch/include/ATen/ops/gelu_backward.h,sha256=YBxYppBY7N9ZXurLcZn_Ji0dyfJeercJTCyGmvGmCuM,1834 +torch/include/ATen/ops/gelu_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=8Idi-LFD4qMlVtuQZiVB-IrGwK2CcRFKCfHB9Othp78,1120 +torch/include/ATen/ops/gelu_backward_cpu_dispatch.h,sha256=H9ARpmU4_n1AVt5akEWJbQnc1eZa-1jOhROHawB87t4,1366 +torch/include/ATen/ops/gelu_backward_cuda_dispatch.h,sha256=nOxRijUP-6M9bTBnN2oSiVeOKHKt6Rz07GpDqFPCRe4,1368 +torch/include/ATen/ops/gelu_backward_meta.h,sha256=4RHWdiRlzsQCA0cQ9Lge1qR4f-DiE4v6FLg_3ZkGctA,890 +torch/include/ATen/ops/gelu_backward_meta_dispatch.h,sha256=Ixqp-Mls_KEbiyZPDhyYsjYVUMgvGzZhoFKAztx_OQE,1368 +torch/include/ATen/ops/gelu_backward_native.h,sha256=MM-rIHQUSwnxaT2iEnBZEx63xfWo_QyVNkGsyUHU2bk,1448 +torch/include/ATen/ops/gelu_backward_ops.h,sha256=Y-8dgBy0WiWrNg9mavdz13DoSHezCrcDO4QGFqy1blc,2300 +torch/include/ATen/ops/gelu_compositeexplicitautogradnonfunctional_dispatch.h,sha256=deL4YyKRMLXJn68NNqcq_HROSaioghWGTpHvqvXOgNg,1165 +torch/include/ATen/ops/gelu_cpu_dispatch.h,sha256=meuSCIb_unDFHsI37OwVqytfn4eIfWo96LYY2-pLmfM,1315 +torch/include/ATen/ops/gelu_cuda_dispatch.h,sha256=KU-wjmLNzE3nIdHL5IIgT7p1oiktGufk6Dufkku99EA,1317 +torch/include/ATen/ops/gelu_meta.h,sha256=AqCyPaeBZNyao5LrSca2hRVWHuHbbo032346AdsPUbI,849 +torch/include/ATen/ops/gelu_meta_dispatch.h,sha256=FSUWNU62DTEJ5hzCvEEmFZGJZFD2Dzk-lRGbUwtpl90,1317 +torch/include/ATen/ops/gelu_native.h,sha256=wMSEfMwO4_1839qER50KUy8ZKUv4A5Nh1iTpfKFWoxQ,1654 +torch/include/ATen/ops/gelu_ops.h,sha256=zqy2KdqC6XSc2RySVb2mXlWEFPDjGGVl8F_qyg7hzO0,2594 +torch/include/ATen/ops/geometric.h,sha256=v-NdFjyWYWsDemX-jxI-GvoZknYeSOccGec2DG4UKvo,1650 +torch/include/ATen/ops/geometric_compositeexplicitautograd_dispatch.h,sha256=jzHhEsFd2wexc4_aIcMUc4natsMyXo3-NzLvh3PQ0Yk,1370 +torch/include/ATen/ops/geometric_cpu_dispatch.h,sha256=p8VfEpw-FOc6FXnzwiH5tLRQvTpwiKbcUYDf0Kz2g5I,1041 +torch/include/ATen/ops/geometric_cuda_dispatch.h,sha256=YvAXhmiYbpz4fh-jdrLk4EYhmqbxKge8qYSgp9QYnaw,1043 +torch/include/ATen/ops/geometric_meta_dispatch.h,sha256=IqeOw2Vyr7JK3YjG2vIE56O6AuELZSjtYx1o8mepSYk,1043 +torch/include/ATen/ops/geometric_native.h,sha256=wKAgHccAmE7iCxQjDMHrTpF6n_b9t6wO_BWa2zyjIzg,1054 +torch/include/ATen/ops/geometric_ops.h,sha256=4z9ZC0JG-Hw-4OS_PXk4edpTinIXgecYP56LyLOLCUc,2873 +torch/include/ATen/ops/geqrf.h,sha256=6ZAaK9W5gnqMT9-I2Fdl9-JLJrsbV0LUzKgrlZ-zoSc,1464 +torch/include/ATen/ops/geqrf_cpu_dispatch.h,sha256=IsUEeLjkD00l83l8vyZaZs8oZA6Ip25LbrOajqnnnVw,1239 +torch/include/ATen/ops/geqrf_cuda_dispatch.h,sha256=0nm5aDSkk3AAAL8FNP0gyDb3XOCUfKTUMDM5rOPMJ9U,1241 +torch/include/ATen/ops/geqrf_native.h,sha256=yB-UfHfTqHoeJw269yOhunxLYbA6_0cy6O8S41uS2nE,874 +torch/include/ATen/ops/geqrf_ops.h,sha256=0yW4k4sox_n0uGhnU45NgXemLoJ4MnX-4VZWJZsTVZ0,2041 +torch/include/ATen/ops/ger.h,sha256=aiCGNNheihEpYD_ixYKdBJXsD4TZGaIdqhpnBdKkGNM,1383 +torch/include/ATen/ops/ger_compositeimplicitautograd_dispatch.h,sha256=k2Ba7OG0dhYHYu3IAgHQB3WJyv2TmefGdxzutyWgsLQ,1241 +torch/include/ATen/ops/ger_native.h,sha256=fNB_f1Oml7qe0qB9yU3xYrkChJWt-gVBCvW9rMgxi8c,852 +torch/include/ATen/ops/ger_ops.h,sha256=1Sbhv-ZOGTHWPG0GkkRoud1josXU5xgE8CIUivXF-Ag,1949 +torch/include/ATen/ops/get_device.h,sha256=MsH4wu4BZaWrA9iOyQmP3KgORASKy8MsrcRmIS17gSM,761 +torch/include/ATen/ops/get_device_compositeimplicitautograd_dispatch.h,sha256=DKpOXXSfikV88MXECZ64lnPjmrQlzsDSzsO2brpox3k,1019 +torch/include/ATen/ops/get_device_native.h,sha256=Ag6pFJKCRD0ESAaESUf3KxohBntW6ZMF3wrHyghbQg8,731 +torch/include/ATen/ops/get_device_ops.h,sha256=ZUJHuQpApmn_7InBW-c3hr9HuzfleGEAaDcYQC9bVIs,1211 +torch/include/ATen/ops/glu.h,sha256=xn0SzjqWKMSRqOXgkEXZkztH6YBsVXshaT3shsjVnyQ,1347 +torch/include/ATen/ops/glu_backward.h,sha256=FDTTv0J9QqlFWqKyBW8kPRwEOBWNSjTp9Ayr47yaWjo,1687 +torch/include/ATen/ops/glu_backward_cpu_dispatch.h,sha256=ZIm8KMmVGqMso3kn4ucINZT-2nzTUdlueJGkx_-9e3o,1298 +torch/include/ATen/ops/glu_backward_cuda_dispatch.h,sha256=mEvAf08XBZ3gmCg0RQLwh5aVQBy1P0Hvifa-SmFsbKA,1300 +torch/include/ATen/ops/glu_backward_jvp.h,sha256=AA_MOKMZATomnaCmwl_-gvhfvFpHdYbXTKZKCFZzNFk,2044 +torch/include/ATen/ops/glu_backward_jvp_compositeexplicitautograd_dispatch.h,sha256=AVJNiZgQ7gp6nbhx1ILkJPrPCsy_1-DdPOc1Z-Tlca0,1379 +torch/include/ATen/ops/glu_backward_jvp_cpu_dispatch.h,sha256=w_tDy61KI-6nWWXtphNOqHUcfkd0hla4kUFgmh5yKsU,1103 +torch/include/ATen/ops/glu_backward_jvp_cuda_dispatch.h,sha256=s2sT-xSUKiK2e6UQIptp0pRsLQGDKwYwDv0SitEOmaw,1105 +torch/include/ATen/ops/glu_backward_jvp_native.h,sha256=iMM04n5Kdh0mmlZTb_rox4cSxUO3gJoAjhSjGwuzqAU,1066 +torch/include/ATen/ops/glu_backward_jvp_ops.h,sha256=EqE0X-U2NgSzR6L2MV9IdChg4FPiaVIHjdQkyRhmIqk,2649 +torch/include/ATen/ops/glu_backward_native.h,sha256=XaSHWK6I6N5Q47po4eEY3jj1J11F0u2snLXmuJmYFYs,1176 +torch/include/ATen/ops/glu_backward_ops.h,sha256=udmCrV_gTqRNDaflJyzextzYl9LgskM9Cvh_pOtB-bE,2175 +torch/include/ATen/ops/glu_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Yz7Mrf3IHsvsiO5NT6_DmVJBS1JU398e4vYXZYn6jUQ,1057 +torch/include/ATen/ops/glu_cpu_dispatch.h,sha256=qi_gH8FERbPmwq8KvZz8ob4OWtT_XuB5ZnOSEYPjFIA,1167 +torch/include/ATen/ops/glu_cuda_dispatch.h,sha256=qfT23KGaitJ2Vh11Fu5ozJHlaja7J_Acz5WrtYeovnw,1169 +torch/include/ATen/ops/glu_jvp.h,sha256=RSiGu2RjyHuSW4hDqYLmpkZDQrRj3EhyWu7H8frmF50,1582 +torch/include/ATen/ops/glu_jvp_compositeexplicitautograd_dispatch.h,sha256=YlOVRhc2-P9vV-EzvVHbl1316AGHx9BcbmhAvLhIpf4,1237 +torch/include/ATen/ops/glu_jvp_cpu_dispatch.h,sha256=8SnhMSnKuLy4Z8tbliRzHhTy4Ievwl-YcXS28CaeL-Y,1032 +torch/include/ATen/ops/glu_jvp_cuda_dispatch.h,sha256=aLTW1uPTxdicNR4svAd0I93v1w0og7qc8OH73NK2Q_s,1034 +torch/include/ATen/ops/glu_jvp_native.h,sha256=MeRS6rff1ToGTBWRe1E4ise6oy4RQsZWTP459cZV9Z0,924 +torch/include/ATen/ops/glu_jvp_ops.h,sha256=C8dsRFQ2rGbvhpDBmdr6oC3eReP8LFYW3Ws1eEToLw0,2191 +torch/include/ATen/ops/glu_meta.h,sha256=Ok6PBNZYx3hOC9dqFgZogvhNADAei90MVASTOKUaufw,831 +torch/include/ATen/ops/glu_meta_dispatch.h,sha256=AFOk0jhFDlkAE6h4NT_lJRnmvJIJmImjNls6grPf35s,1169 +torch/include/ATen/ops/glu_native.h,sha256=ZXDHHkGOYagfi644sIYWcXZuDGiLufip_1Hq5iHTR-M,854 +torch/include/ATen/ops/glu_ops.h,sha256=yh0Fh4Wb1-nt-Q27EP5CraohK0njCIN0DOTPmOpwLvo,1877 +torch/include/ATen/ops/gradient.h,sha256=9hh831UQ5KfvlOURZ6l4NjhzCiHST0yoiYOitDG6V64,3126 +torch/include/ATen/ops/gradient_compositeimplicitautograd_dispatch.h,sha256=nYcD48S_G7LNvQL1jMrFkaloxsWl4vgNs8SORDKUudI,2038 +torch/include/ATen/ops/gradient_native.h,sha256=nUnhXOeZz9y9ATk94XY_Wl6FWhpU8r9LuRu3y_3eEIk,1750 +torch/include/ATen/ops/gradient_ops.h,sha256=lTSLz2M9MBBGm56StlK6gU0UX8wMQA-Klp4fEvJJlo8,6526 +torch/include/ATen/ops/greater.h,sha256=qzqSySHLDwlyQhs3XrLFo06ps-WXx25DC9gP-BTPuY0,2191 +torch/include/ATen/ops/greater_compositeimplicitautograd_dispatch.h,sha256=sDCDMOnWIaAG3MWPb4whbh9CQDeiUS4NCK-t-hQkH2U,1704 +torch/include/ATen/ops/greater_equal.h,sha256=FWtJKJRjXKhC99ZS7fTmT3P08XOe0SZBXdsEMx6XFtQ,2305 +torch/include/ATen/ops/greater_equal_compositeimplicitautograd_dispatch.h,sha256=wf_64kCUUS1oa_dDclA6qk7LyXi6_a27DKmPcC8A7sc,1752 +torch/include/ATen/ops/greater_equal_native.h,sha256=Sszs-lNJkw1SUpjn9jua7bMjV1Nduif3TgrY-1GraBQ,1240 +torch/include/ATen/ops/greater_equal_ops.h,sha256=qmq2Ka_uYDqy-XL2MBoEcHLoPUFqvcEyG7kjg8zrzDE,4653 +torch/include/ATen/ops/greater_native.h,sha256=8GxNQvriWPABq6B1OM12x60CI-cmrLitz2p9aTwZpgM,1204 +torch/include/ATen/ops/greater_ops.h,sha256=C4M5YqFs43Ju2Ay7ePW4LK3YueOgapSNKHZxIPzdH_M,4545 +torch/include/ATen/ops/grid_sampler.h,sha256=LD9Ok2tqYoC5UPndDsTDnRyZO7kV0SBPDrD31jMgsjc,1143 +torch/include/ATen/ops/grid_sampler_2d.h,sha256=KFT1UlwovtC6NUTMgFGd6XW-uK61yiVhfaGbPiNa6ZE,2055 +torch/include/ATen/ops/grid_sampler_2d_backward.h,sha256=9Lv8qDvd8Bs1N60DP9_jKZvlQ8NQIof29CwCVoFCK4E,2751 +torch/include/ATen/ops/grid_sampler_2d_backward_compositeexplicitautograd_dispatch.h,sha256=KRIKJ-bn2negsyXTkrx2OTMTIC2vVayJTMxzsUKP7FM,1575 +torch/include/ATen/ops/grid_sampler_2d_backward_cpu_dispatch.h,sha256=ovSy72TICQtbm61xcM1qIfr9cVf3F5dE00hytTmNzvQ,1179 +torch/include/ATen/ops/grid_sampler_2d_backward_cuda_dispatch.h,sha256=14EWRnAqnJUSnSNCVETcvb_go7vLowutSLnF-OUHvck,1181 +torch/include/ATen/ops/grid_sampler_2d_backward_native.h,sha256=gLn0Lob5L-hqhBCE2d-lVwku7nzqQ5lxQX2dgCawl9A,1508 +torch/include/ATen/ops/grid_sampler_2d_backward_ops.h,sha256=XHs90TkJr7_mbgbHChSBBI_sdavYysNiinLwJoLQwns,3215 +torch/include/ATen/ops/grid_sampler_2d_compositeexplicitautograd_dispatch.h,sha256=ljQBVSmyOCZTAYennI08xroLp26C6On8ocqUOJzZzPk,1331 +torch/include/ATen/ops/grid_sampler_2d_cpu_dispatch.h,sha256=7zxZD2jMAtfveSPa3epi4WnqFjH9tps2CwNuxq7rZXA,1079 +torch/include/ATen/ops/grid_sampler_2d_cuda_dispatch.h,sha256=NCfAlqdXkjOpw9ISeIEtjz-KbpOqBBzb04zO_1xX2lw,1081 +torch/include/ATen/ops/grid_sampler_2d_native.h,sha256=5gFDR7dx3Yvh0PO9C9R5IkHztXGyF0MsxQpojsPhJJA,1186 +torch/include/ATen/ops/grid_sampler_2d_ops.h,sha256=_NmGwc4slgnnObZbBLVeD6w6gJuyxlmDwKW-F9iyxsw,2479 +torch/include/ATen/ops/grid_sampler_3d.h,sha256=sDeCvln2qf4qu3bQEvwZh5wXBx_k00eCNIB51dj3DvQ,2055 +torch/include/ATen/ops/grid_sampler_3d_backward.h,sha256=0XcBmRklJYsctj6awz7xdSxt_4X1hPtu4NkJWDzIu78,2751 +torch/include/ATen/ops/grid_sampler_3d_backward_compositeexplicitautograd_dispatch.h,sha256=7Erkhvn7LJQSSmR7qOXhc6BxdNxzAyOCO46qh5OW3Es,1575 +torch/include/ATen/ops/grid_sampler_3d_backward_cpu_dispatch.h,sha256=dtRsgau5lqKu-7Z69N88k09DmVFtWq4t50ux_gk-Aeo,1179 +torch/include/ATen/ops/grid_sampler_3d_backward_cuda_dispatch.h,sha256=LYe6znNZcaEPH9BpN3_kvjBIQlWRRpVtDq28nlMtrQQ,1181 +torch/include/ATen/ops/grid_sampler_3d_backward_native.h,sha256=D4VyUGxZiSmozgbbWbcALARzDytjejRYHsW4oI7rlgI,1508 +torch/include/ATen/ops/grid_sampler_3d_backward_ops.h,sha256=JdK9XZFKywFz2ze3HKYPLAxw9VsD0HgwkkOr8z0BnnE,3215 +torch/include/ATen/ops/grid_sampler_3d_compositeexplicitautograd_dispatch.h,sha256=HeB1Ca2MKf_Oqvpmdtu8EYmphTTBjQ3ehkCZ25rezbY,1331 +torch/include/ATen/ops/grid_sampler_3d_cpu_dispatch.h,sha256=FeM8WVIFus_5un3A9iGLu4NYclnRBHW8Oan-_MdbRZE,1079 +torch/include/ATen/ops/grid_sampler_3d_cuda_dispatch.h,sha256=XJlepHkCgPp-8UDDDlVKMRmWbazDy5nj3BZ1W-aPwbE,1081 +torch/include/ATen/ops/grid_sampler_3d_native.h,sha256=hFch_qdpZRmdh7cSux82tpjuGnutBQF-ct1EpF-XBQY,1186 +torch/include/ATen/ops/grid_sampler_3d_ops.h,sha256=3NHrNc3GrHZj2SZWggPDYVJn69oPEzvfnO3dcBuVizc,2479 +torch/include/ATen/ops/grid_sampler_compositeimplicitautograd_dispatch.h,sha256=OVVInODeVkoinPvRhmfEGPhdm0MkglexEBmBo7XBHSc,1120 +torch/include/ATen/ops/grid_sampler_native.h,sha256=uc3jYmBAyf4Wnw43hqNSYGX3f0S7YWu1ZjMZNh1Wimw,832 +torch/include/ATen/ops/grid_sampler_ops.h,sha256=WQy9BjniNDggIcitPQYXxRxrzUvjSLnp8rWUK-AOqNc,1541 +torch/include/ATen/ops/group_norm.h,sha256=Md9aGrPMKZJxgZ6O4Cmbi4XnvFEIV7aZeFxzsGREL0Q,1209 +torch/include/ATen/ops/group_norm_compositeimplicitautograd_dispatch.h,sha256=lxV6G2liF6LMf1yOhMbqTspk-dGXlAq5fP0y04HfDI0,1178 +torch/include/ATen/ops/group_norm_native.h,sha256=_Uo0D_CATGofe4S-iq_mqjd3969iBH_YGcPqOtkzq0c,890 +torch/include/ATen/ops/group_norm_ops.h,sha256=gKvbxsHXoQj_O7QZf4IVWH8juswLLQ5bzRvNxWBIkyQ,1697 +torch/include/ATen/ops/gru.h,sha256=K5NeoaUxqLzFQZQzG2Xeh0_evEmjwUxlzLktEdUtKkg,1826 +torch/include/ATen/ops/gru_cell.h,sha256=v2dgfe5obQ4tHFCo27x5XsjlBXQYVCwd6qBp8dVdz68,1168 +torch/include/ATen/ops/gru_cell_compositeimplicitautograd_dispatch.h,sha256=GULA8vDuuN9ZgBPDtOJP3x7gYMRHZJoitcLodWUYP3A,1184 +torch/include/ATen/ops/gru_cell_native.h,sha256=6ijjmxKg2vi4tfAxpBDLpsgMI9v2igfzSuL2_Ho3oBs,896 +torch/include/ATen/ops/gru_cell_ops.h,sha256=onqMGqg1LXKYYDNIv_4ayhhAEV489qhltn78iWE2kaE,1743 +torch/include/ATen/ops/gru_compositeimplicitautograd_dispatch.h,sha256=h_6VkDT1dhwlgOmg_rN4AJlVLstpnhzhVkHXeGko5d8,1429 +torch/include/ATen/ops/gru_native.h,sha256=XD2FpZ6--_yx-aE9wMnHuLNVfK2g0zqvVk5QiKXGh3I,1141 +torch/include/ATen/ops/gru_ops.h,sha256=W-YdrUAbeT9JAF2c8dLkOeleDdOQKvep9J226KpOQ84,2943 +torch/include/ATen/ops/gt.h,sha256=CmCWKASvzFZ9M1VJovX8uH34Q526vStvj7hDpVWMZgo,2096 +torch/include/ATen/ops/gt_compositeexplicitautogradnonfunctional_dispatch.h,sha256=NSZDdJ_G1bGiNn3pe-YYUbwWx5zI86lf7-mWW-fn-SE,1288 +torch/include/ATen/ops/gt_cpu_dispatch.h,sha256=lMFDI_bII8HyfD9cY6VX1JIyXO7hHxaK1jJkRpx329c,1620 +torch/include/ATen/ops/gt_cuda_dispatch.h,sha256=d3D8iRz0SM8oSCihqvy3EPh6s1_0oeYyD9knOA_qYVU,1622 +torch/include/ATen/ops/gt_meta.h,sha256=bjIYECmoBhmaMKTls3_ljcpWmBuvurLZiFbvqLndtek,989 +torch/include/ATen/ops/gt_meta_dispatch.h,sha256=_LF7A-xng55zcgEHKFP2_HAWTE5ZY7Iuyl53rLm-w7c,1622 +torch/include/ATen/ops/gt_native.h,sha256=ACWqY-pW4dQ3dasiX2NnvQvPvwMO9xaJ53--v4E-Eh0,1549 +torch/include/ATen/ops/gt_ops.h,sha256=2pB6HoSEhQ0RMXjEhDShDBlX1mrkl0civmeJEuJXdfw,4455 +torch/include/ATen/ops/hamming_window.h,sha256=FyyJIGMLRb0NL4nCw42h2DdpqAGteTTlP4mzLrSlvmU,7292 +torch/include/ATen/ops/hamming_window_compositeexplicitautograd_dispatch.h,sha256=EBQPtI7JcWXfDpF6NHCTA095VvsQgwtgCRGIkv-qwLw,3164 +torch/include/ATen/ops/hamming_window_native.h,sha256=oaRl9aVs9pZm1iBJj3cKw3b4l47ZEx1rcksszVTZUqU,2096 +torch/include/ATen/ops/hamming_window_ops.h,sha256=6axxbCRGscGsuapARD1v4xHb2Jz5h2uw55f6nALGnp0,8030 +torch/include/ATen/ops/hann_window.h,sha256=3CQtp35kyUTx8q_F9KeKJpuq_xVZqbD5yNr3k8VOl4k,3571 +torch/include/ATen/ops/hann_window_compositeexplicitautograd_dispatch.h,sha256=M1TLXUuEciKp4-0K562sGpOG6nQvUx0vtBI_MEZK-hU,1928 +torch/include/ATen/ops/hann_window_native.h,sha256=Qsluvu6NvnYd0NkMQJ36QlRYYYDFeKmFV8QhY7w2na8,1305 +torch/include/ATen/ops/hann_window_ops.h,sha256=ClgbvDRxSz05StaGb6GECqzYTGJG8ZdRL05Qm9Jtdy8,4062 +torch/include/ATen/ops/hardshrink.h,sha256=v4AkR70pPWqzOCN8pt9DX2dLyD4KoO9-8_H_UFloU4I,1482 +torch/include/ATen/ops/hardshrink_backward.h,sha256=p3DL3FVmb-ua_7YSraqXUGNvaW6HdCRC8H0y6l5ZpUQ,1790 +torch/include/ATen/ops/hardshrink_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=I9qcMLH-e9Kb-s9sxK2uru8CsAVWUx30BV50Mh35vUY,1112 +torch/include/ATen/ops/hardshrink_backward_cpu_dispatch.h,sha256=X9QDbS8L03BSI0oa_y-TFEUrALfym3ch3cTSWHdTm_g,1349 +torch/include/ATen/ops/hardshrink_backward_cuda_dispatch.h,sha256=0Kg3R8hd1Yizq2fa0Yjjm1j4AxZa74sh2JkNOinMWJs,1351 +torch/include/ATen/ops/hardshrink_backward_meta.h,sha256=1PfH8EQsbe3KqDn-vskQuSV9bAyiwW6r8hARZRXoeX4,889 +torch/include/ATen/ops/hardshrink_backward_meta_dispatch.h,sha256=KSzzTmveGAsorNNOB-oDFLMr9OxmM8XoVdG2Fq7pW0E,1351 +torch/include/ATen/ops/hardshrink_backward_native.h,sha256=AhuOadw4gl7-6_LlpdHp4TLbxft1EoGRqeo13mTcT0g,951 +torch/include/ATen/ops/hardshrink_backward_ops.h,sha256=0cbS2qO66bPfhJnzmYRLa-W7QcagR0hArQrE4wCeGIU,2283 +torch/include/ATen/ops/hardshrink_compositeexplicitautogradnonfunctional_dispatch.h,sha256=P3Q_Ju7TDpOPJTqKJDkAgRiWapwgqvUVsZa6tpbqGSM,1078 +torch/include/ATen/ops/hardshrink_cpu_dispatch.h,sha256=ZcNTVnbczXeP2HiOuR_JZdJMJ7zV79JJABaCR-ZnRF4,1229 +torch/include/ATen/ops/hardshrink_cuda_dispatch.h,sha256=n8au5-nwnKrQnv8RoJLRhTb-qTo-4aynVDPn-19LwUA,1231 +torch/include/ATen/ops/hardshrink_meta.h,sha256=zyKrCYPogrTpLd5ZueUm2U46TPtWLb6M3mfMBgCWRF8,851 +torch/include/ATen/ops/hardshrink_meta_dispatch.h,sha256=_DhDjqnuKEwdzWnPZfEdinPOQ3aB_bM-4yFNSZaudz8,1231 +torch/include/ATen/ops/hardshrink_native.h,sha256=0yNAMTnSz0sCob1mdHjwoeai0N07khAcBwECpncwsUM,888 +torch/include/ATen/ops/hardshrink_ops.h,sha256=WUzSkoeSpr27j3SrAHcGXXGAUMGZM8wb3g-FNoFf5dE,2005 +torch/include/ATen/ops/hardsigmoid.h,sha256=brGWlSoNJ9FGBbvh8V-WLZDDaIgu5DKwprCDmVFm1jc,1488 +torch/include/ATen/ops/hardsigmoid_backward.h,sha256=X3Wagbgdt2lSSN7i-CdsDY3AvN4ZtDP-CV_2w0T_iL4,1686 +torch/include/ATen/ops/hardsigmoid_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=qluB9yj4ThqAkpe6MeczqcpZjOrkAMQnVHY9m0bXHG4,1090 +torch/include/ATen/ops/hardsigmoid_backward_cpu_dispatch.h,sha256=hTMduBEVsEW8pBV6Gwa0NkXt1SZQHeU8QQlal0JBH6Y,1283 +torch/include/ATen/ops/hardsigmoid_backward_cuda_dispatch.h,sha256=PAXvzFC3ydQQ-uCNB1qLP8vGSu8jJupN7_XgnMPXbXU,1285 +torch/include/ATen/ops/hardsigmoid_backward_meta.h,sha256=o6buS1fDFRYWLxwJUd-E-3vJKYuAiKR94cIVoFNP6Q8,867 +torch/include/ATen/ops/hardsigmoid_backward_meta_dispatch.h,sha256=ao6zS2EQFNkk8WY8jo-PULEpKT0dvIyn5DAuBoGnB6o,1285 +torch/include/ATen/ops/hardsigmoid_backward_native.h,sha256=5h2m6JbX4oXG930D2ZMUyJKalHVvDZoas8H8vyULBr0,931 +torch/include/ATen/ops/hardsigmoid_backward_ops.h,sha256=_w_zQos8l7nLKs3ZhFXY9OvpWhU2HCbLRC-nK9cBOrw,2135 +torch/include/ATen/ops/hardsigmoid_compositeexplicitautogradnonfunctional_dispatch.h,sha256=uJpvTur1T6EnTaXyetF_ZBViT6eGWGcYCV04wQhtvbU,1105 +torch/include/ATen/ops/hardsigmoid_cpu_dispatch.h,sha256=x69Rk2-jGgjyhZaCaYDhPs5jZOvx0b8Ts3p19y_RBNI,1202 +torch/include/ATen/ops/hardsigmoid_cuda_dispatch.h,sha256=pXw3--3Fg91280E_qeWb6azJ1hyrweYcuukW_DAyg44,1204 +torch/include/ATen/ops/hardsigmoid_meta.h,sha256=0AxhGV39dK8dV8CELTGTA0AHxz655gkCO6iF32ONMqs,826 +torch/include/ATen/ops/hardsigmoid_meta_dispatch.h,sha256=S4LJUEpOBb0Lq1MLYRVjjOnZa4RsHLETO6ErJ6MYgaA,1204 +torch/include/ATen/ops/hardsigmoid_native.h,sha256=Yhj06Bd0NqZzQetCgd3Zn4O2gftz3izt61E_h6VgfNc,1035 +torch/include/ATen/ops/hardsigmoid_ops.h,sha256=nIBmfiMLJrIBJzlIt89ZC0MMJmF2w9eEi2mMye4EGwE,2345 +torch/include/ATen/ops/hardswish.h,sha256=NPdkaxJnLdXrETxx2fBQX5OnU_0S2qGFdHA0LCqEObc,1462 +torch/include/ATen/ops/hardswish_backward.h,sha256=F6J4C7OlRIbDjOnuuE5UJ8YXmbyaxWm2tDVg1HvkiDs,1596 +torch/include/ATen/ops/hardswish_backward_compositeexplicitautograd_dispatch.h,sha256=8tuWr39kiTWe3wdcMjXvILHqpdl1L3Qke0wPVZ1ZYKs,1209 +torch/include/ATen/ops/hardswish_backward_cpu_dispatch.h,sha256=_YVgkurVjT3Y2lPgkQ2NqymLKIEgEJE81tAh_J8VJBM,1018 +torch/include/ATen/ops/hardswish_backward_cuda_dispatch.h,sha256=udWkDTXwXGsZoQ6YfABnD3cHKJb1VI5oPfd9PsF5rzQ,1020 +torch/include/ATen/ops/hardswish_backward_native.h,sha256=n-H0PPZYyd4TWl-7YwhnNmYqUmD_3UHgEIDPGFjklIc,896 +torch/include/ATen/ops/hardswish_backward_ops.h,sha256=96LUi3Y6HM9X_HT1o_Y-Fmh7fVWjgKmgzlISx5BAilI,2081 +torch/include/ATen/ops/hardswish_cpu_dispatch.h,sha256=L48BaSexR4UQMbno6As1lft5DRf8Q4lAMk83ZXmrU1A,1194 +torch/include/ATen/ops/hardswish_cuda_dispatch.h,sha256=ox8utXQY3pXoeCEAMXdVf6jLM_3Rrs2v6K8xv7YJGgk,1196 +torch/include/ATen/ops/hardswish_meta_dispatch.h,sha256=81KVnWt6VqCOHNs9S1rlMMXgsIrNMpFrNbz8z0Lml2o,976 +torch/include/ATen/ops/hardswish_native.h,sha256=MzFXLh3k-boA_Wym8j5qtnNwH6OKsathU5Z7UDtbxhQ,868 +torch/include/ATen/ops/hardswish_ops.h,sha256=HCzdXInIg9ei4WhwwC6hTq2v0myYNiPnPdDrWYQCQHE,2327 +torch/include/ATen/ops/hardtanh.h,sha256=5rmBGsJC8zoAkynQxTfn5nc03bn0oAR5mPcnyW9_PUU,1908 +torch/include/ATen/ops/hardtanh_backward.h,sha256=Kz64IMoPLNp9EEonAP8N0vGjaXiyHlaN-oEO2XHXhMw,1974 +torch/include/ATen/ops/hardtanh_backward_cpu_dispatch.h,sha256=2Xrp4AK41iEA1jKvO5qyn5fVpy1WHUfRWpQ1U9FaI_s,1442 +torch/include/ATen/ops/hardtanh_backward_cuda_dispatch.h,sha256=ZjHrYw7iJOIFKIs2DPuhIBbdaZEMpdFsUlT0tyJOiiU,1444 +torch/include/ATen/ops/hardtanh_backward_native.h,sha256=uy80hqPZkoirL2SjgwQDeVmbQB-Wo2V8s_b9LHu8MLc,1013 +torch/include/ATen/ops/hardtanh_backward_ops.h,sha256=IDNN8AnLNnmR7_CHqEuviAqvgrhi5U-Mz7fxNAM4Yuo,2485 +torch/include/ATen/ops/hardtanh_cpu_dispatch.h,sha256=zO3URwZcWv4XyM4QsxPNqHrAih2EuCHs-GlyhSvP0Vw,1429 +torch/include/ATen/ops/hardtanh_cuda_dispatch.h,sha256=W9k31RCJohNIeEZDI0e6sMEZ2CH8CgWYAM_glAtYboU,1431 +torch/include/ATen/ops/hardtanh_meta_dispatch.h,sha256=tsJCqg01OXhqqRG9kmu5_mmvDDGKyRV45pr9W4BSPuc,1036 +torch/include/ATen/ops/hardtanh_native.h,sha256=pFL0LakwmvhAFO7sGAKiYH9uA5kRzcG9AeS7F3_9ZKM,1452 +torch/include/ATen/ops/hardtanh_ops.h,sha256=FcpiSvBIGhhV54OBSN3x3AAJjx-yfVU0xHRARweHOK8,2885 +torch/include/ATen/ops/hash_tensor.h,sha256=_K4GSgr0ODEiMh4GMFLeW2owM-NRo4fhC0keJRGU_2w,1704 +torch/include/ATen/ops/hash_tensor_compositeexplicitautogradnonfunctional_dispatch.h,sha256=MqDuhbX4RaVYeHO7LgC7OpuOO2v925RejDd0BuLSKYA,1109 +torch/include/ATen/ops/hash_tensor_cpu_dispatch.h,sha256=FCA-al2SwDsuPLI-PrdDEjqhUht2ry5tLebE39L78gE,1315 +torch/include/ATen/ops/hash_tensor_cuda_dispatch.h,sha256=JAjQoyC32yC-RIeMxKdRC8xSKs01JD8VjqguRQK7Ja0,1317 +torch/include/ATen/ops/hash_tensor_meta.h,sha256=2MWgy_rO0XR1LeE4j12FLFCBZJeUUL0aR0xQp6bMzNw,875 +torch/include/ATen/ops/hash_tensor_meta_dispatch.h,sha256=Hnp7ON7_tV9RASK_j_5E5dEWZT8p82Xk2UtHNw6UujA,1317 +torch/include/ATen/ops/hash_tensor_native.h,sha256=V8qQURPUIIUhRH33kNQBCguJ8WvSubLbTluEUhCIWCM,914 +torch/include/ATen/ops/hash_tensor_ops.h,sha256=zLlQSJSaE1GgMnoYESOhHoU8hoGgrIpQcSWKGjEwNUE,2188 +torch/include/ATen/ops/heaviside.h,sha256=TXM03TPE2h_EfIMsfzPnFgl5XPTxy84XUUiM4X9eEx0,1461 +torch/include/ATen/ops/heaviside_compositeexplicitautogradnonfunctional_dispatch.h,sha256=c4algCWF9CNAZONHoUIIP1c5cO6jqpbqKx3j_D1MZOw,1155 +torch/include/ATen/ops/heaviside_cpu_dispatch.h,sha256=QGlf3kg5No0qcI64dVycjcg3pZl1uR1xknBjb1wya6g,1302 +torch/include/ATen/ops/heaviside_cuda_dispatch.h,sha256=6mLKuAZm5I70niFPB2-hDuocuF_BgqlwV35p7uo-tDk,1304 +torch/include/ATen/ops/heaviside_meta.h,sha256=Pr8gCF6nhjYmeyHXc_-9vO6hOG3-o5ukuN2U2wZz-UI,851 +torch/include/ATen/ops/heaviside_meta_dispatch.h,sha256=peVOKxrFNDG48JtzTv6MZrzbO6ygmSLE-inqDbMm9fs,1304 +torch/include/ATen/ops/heaviside_native.h,sha256=uuIlBXYGmy_eQK3Z3xdMhsCu0KEv2EvL7DCDvR2tgPk,886 +torch/include/ATen/ops/heaviside_ops.h,sha256=EixNKEMB3zUxCf_gIXxMV9vvcTTEushbLBuFHS2oxoY,2594 +torch/include/ATen/ops/hinge_embedding_loss.h,sha256=_Kawd8P0i12m5HQx9iRRDA0NvWRJ79xyIISdiCYUyfE,1112 +torch/include/ATen/ops/hinge_embedding_loss_compositeimplicitautograd_dispatch.h,sha256=Xv9X7yRwKQY26ZAvgqzQ2aYM2eF3gPnb_fKe55a4Kzw,1117 +torch/include/ATen/ops/hinge_embedding_loss_native.h,sha256=EoQ7EUDr1Vu5A8HJMimkH54GsjKsbjDicnPjXexLmkQ,829 +torch/include/ATen/ops/hinge_embedding_loss_ops.h,sha256=DdQ6rRnYLHCZar4jV4Xm5m8IvjD-flP-MOVXRKf5wrc,1465 +torch/include/ATen/ops/histc.h,sha256=LdQcPudL0z9WLrekyWU5CrB1DACJvOFqvh5pe7aZbfM,1647 +torch/include/ATen/ops/histc_cpu_dispatch.h,sha256=3NQFjnAH51yWXZzUS8oNXdqwioScqWDYr7kUpSBUZ5Y,1330 +torch/include/ATen/ops/histc_cuda_dispatch.h,sha256=DLzOiDUyznsDIfv8G78IczxTpfLBULMQltq9SFbxWnc,1332 +torch/include/ATen/ops/histc_native.h,sha256=I1dQ-0oPklqqJkoDaBn1G3pqhzwAXDeUdgYFr5dVzgc,1232 +torch/include/ATen/ops/histc_ops.h,sha256=VX1uIOarE6DBY9TprVXtQ5UmToVM7y3XRhWJcgq0uTM,2225 +torch/include/ATen/ops/histogram.h,sha256=vkrSfGhiv1ArjerlM7hFskf-onWjArTVFaARrElBXAQ,3770 +torch/include/ATen/ops/histogram_cpu_dispatch.h,sha256=C4ThtlN9QObPuHOo2M_WGXB49_kSPRGrXCccEjTWOEg,2292 +torch/include/ATen/ops/histogram_native.h,sha256=mc5bJ-TWXkfPuCZNMvEjeVPkWf_E-4Y1MxlmNdATr7c,1543 +torch/include/ATen/ops/histogram_ops.h,sha256=sKFyJ2Dcku75kEZTjZP3ch993dfEOoal1EbskgAmypw,5007 +torch/include/ATen/ops/histogramdd.h,sha256=rOVwTMrfQ5XXTNLr7hotG5DQuVrV0Li76o_txoh26lA,2213 +torch/include/ATen/ops/histogramdd_compositeimplicitautograd_dispatch.h,sha256=wyFoT-gG_BZo2dlYYo3spLX49NXaJZSvgYAJkysfEYI,1699 +torch/include/ATen/ops/histogramdd_native.h,sha256=jLM7bzMKckl6hJvhw0ndJYRVQCygPIqVxyQFZsqHCuU,1411 +torch/include/ATen/ops/histogramdd_ops.h,sha256=R1MLGSvVi4jeaZPAfqDZYd4OdEceW8L9i2Okf8MjOn0,4013 +torch/include/ATen/ops/hsplit.h,sha256=Mlvg3xhYQVUXea_iUc-NOwaapbw77Jrt4f1QNkmVvwM,1193 +torch/include/ATen/ops/hsplit_compositeimplicitautograd_dispatch.h,sha256=uWtCOsxhkkIK76VYFomSbOhMnYW_XP7EwhtVFNO6QW4,1145 +torch/include/ATen/ops/hsplit_native.h,sha256=0yatecVih8I6n2TYNAyaA0xpJT1gIUrYe76LcQRvCT4,857 +torch/include/ATen/ops/hsplit_ops.h,sha256=O5J5ncjApdn1pSvWw504Egex2BNyu65YK_0i5GlN88g,1996 +torch/include/ATen/ops/hspmm.h,sha256=DprT2f7mcA2TB0dUj-l5G3oG_kbkeW5ZILwHUTeXuj8,1403 +torch/include/ATen/ops/hspmm_native.h,sha256=df_HGep2ajOKN2N-UFCGySP8Z8bjk3RX1t_MqWyyxgA,1082 +torch/include/ATen/ops/hspmm_ops.h,sha256=sayAxG2HdU8CSo_JK7u0o67oQUYnO6muOCehBVShemU,1961 +torch/include/ATen/ops/hstack.h,sha256=eJUcmXDPA7vqdQ7W3DOCFkByI5K0sDhEvlUlF7cEeEY,1302 +torch/include/ATen/ops/hstack_compositeimplicitautograd_dispatch.h,sha256=WteoJOs6qqr1IVYK_XnGAd09GKLkMfnmwGQHqzwoKd0,1172 +torch/include/ATen/ops/hstack_native.h,sha256=b-EUGlkrPtoBpRrAlbOTpZlSxjhl27YjqjbYXPKrgiA,806 +torch/include/ATen/ops/hstack_ops.h,sha256=qwxIOi_nuIw-EiAm3UdAvbHmg053DP1w8esyvZJSnlY,1799 +torch/include/ATen/ops/huber_loss.h,sha256=xuS_FrxHsefkpAy0T4JI1zuRbI0aOCtuUovE-8Hz0Fs,1783 +torch/include/ATen/ops/huber_loss_backward.h,sha256=tByeJ-n6vEsGLj7_tVYzICda7yswkuDMyADv3IBtVbA,2035 +torch/include/ATen/ops/huber_loss_backward_compositeexplicitautograd_dispatch.h,sha256=w7-u4rSO8MCq9-6ZUYMAtge0bQMjSAxMxKjCKl00bfY,1123 +torch/include/ATen/ops/huber_loss_backward_cpu_dispatch.h,sha256=V0lZElxOBAVdlRhiOTcm-G2UmdO2VbQTyK14CS3m-GA,1301 +torch/include/ATen/ops/huber_loss_backward_cuda_dispatch.h,sha256=LvATj2EzgSmHki_eSM61dn3HRGVUkIMs-qPfYESWjPY,1303 +torch/include/ATen/ops/huber_loss_backward_native.h,sha256=qTi5r3kUpZpgqB9vJ9t7acUbrOTmYQHb6fspdtzrRcU,1025 +torch/include/ATen/ops/huber_loss_backward_ops.h,sha256=H9TuUDadZPvckCgLUM4Wl-zfNF6Uo_oAat2gJKbH3JQ,2508 +torch/include/ATen/ops/huber_loss_cpu_dispatch.h,sha256=9YMqjOvBln1BtfPcQi-aSZap0h__5zT0Ucn5eNNlA2o,1371 +torch/include/ATen/ops/huber_loss_cuda_dispatch.h,sha256=f2t9RJ2awh7zbuSY6umX_YLZn_Sh01p6O7KncwaJuQI,1373 +torch/include/ATen/ops/huber_loss_native.h,sha256=6-4iN6CvQJnvZnVpRnz7uAnuwVrH-o6UbMFQhlFbYNE,960 +torch/include/ATen/ops/huber_loss_ops.h,sha256=ercboX9fOr2Yx08ce3xhl2tR7QU1IN-_iXoHElXVgHM,2243 +torch/include/ATen/ops/hypot.h,sha256=5iYlUAxQ2Zt73k0WuiSm30VNENUr0AYAVXJXa9da7TQ,1412 +torch/include/ATen/ops/hypot_compositeexplicitautogradnonfunctional_dispatch.h,sha256=K_6T-1CIyiYGrgGYK8_PdBCHhRIpBobe8pAYGafUMrc,1145 +torch/include/ATen/ops/hypot_cpu_dispatch.h,sha256=7HrOioVBGgCt-sPEJwbVSH6JckExCVUETQUKNx6vpGw,1282 +torch/include/ATen/ops/hypot_cuda_dispatch.h,sha256=KJb-6w1R4PvF3uXbHCus486X-qPcKXxtz0OLOtmd_fI,1284 +torch/include/ATen/ops/hypot_meta.h,sha256=KC6TtMhXm2Pqa4gQdaLtggrmhmf3-yH3yonQR-f5Za0,846 +torch/include/ATen/ops/hypot_meta_dispatch.h,sha256=EWNVRRAaWolzV1giKH86II3WhBBJF7YITw9_QB92GSA,1284 +torch/include/ATen/ops/hypot_native.h,sha256=yuJpaBkuaonG--6q5CZl6Uayv7uju6FNKYgiLmKwcTw,873 +torch/include/ATen/ops/hypot_ops.h,sha256=Q_e801uV1XQ13hhWU2hilMn0qlJUI0k7xyV27PydXIc,2549 +torch/include/ATen/ops/i0.h,sha256=T308xBS1wjB9K2ToInJxKKuiLg9XsBx0O11oYwoR9oU,1371 +torch/include/ATen/ops/i0_compositeexplicitautogradnonfunctional_dispatch.h,sha256=_Foe9ReQfNB-9e0lCBD5ETjO52mbMFT5kuRbRBGzSrw,1087 +torch/include/ATen/ops/i0_cpu_dispatch.h,sha256=QdV1ZOv885ouzdDR49LHHE5w7soGzfVzqu6yPH7W9SA,1166 +torch/include/ATen/ops/i0_cuda_dispatch.h,sha256=QTG2-hCydLIWXLpOaTTRuBwYd_9aySwEYIZBE0_yer4,1168 +torch/include/ATen/ops/i0_meta.h,sha256=vtqfBzUpUf78Iq9ld7QuJnsVkfFpTz3ejg8pwM12A68,817 +torch/include/ATen/ops/i0_meta_dispatch.h,sha256=wmvTwEIDLHTN30hVhlb10vQPH01o-J3sEn0Kj57UiOw,1168 +torch/include/ATen/ops/i0_native.h,sha256=85ouRhxa1L79w1WhYpG_FsYpNNrYMrI3QK-RKgZWZxQ,838 +torch/include/ATen/ops/i0_ops.h,sha256=wkVudm7WUExUpKAvrdjAIafKB8rI2sgZlUGVbj9XFGU,2264 +torch/include/ATen/ops/igamma.h,sha256=st-BaNICd7J466iGqtXudFTbOZVup9nht46aNLIyzrM,1422 +torch/include/ATen/ops/igamma_compositeexplicitautogradnonfunctional_dispatch.h,sha256=dIg5allbrVYb8KjUtkIEh2pJ-2_Hwqmlu0SGEzGQIvw,1147 +torch/include/ATen/ops/igamma_cpu_dispatch.h,sha256=XIKq35mDfWRPJaVaAn8951UHuHO97WLGf_4wMmPNI58,1286 +torch/include/ATen/ops/igamma_cuda_dispatch.h,sha256=mEFj2OyIq2pP1XeyAb6eMBClIUDrSy6EP9zsOQGICGY,1288 +torch/include/ATen/ops/igamma_meta.h,sha256=X2EIw4iTtlNlzneM1z-jgy1-pUc9GB8nSVHxAqQ_RIg,847 +torch/include/ATen/ops/igamma_meta_dispatch.h,sha256=xWPYQr1HANT8cVLarzRQmUkrDt24xxmii5_1iIqepYk,1288 +torch/include/ATen/ops/igamma_native.h,sha256=XMblXiG9VQulfksc0YqxIUlc_Z0QzWRioTJBXzhBaUc,876 +torch/include/ATen/ops/igamma_ops.h,sha256=xRlr6FgAOtUxKMauMMfwaxMycecNHkDJsiw9u1166ko,2558 +torch/include/ATen/ops/igammac.h,sha256=tsdDcPjfq57i5aIaPZRSUiNRegjdMI7MtWnvdGrEM3I,1432 +torch/include/ATen/ops/igammac_compositeexplicitautogradnonfunctional_dispatch.h,sha256=8D80aYXXuQz7BoZ5vJyJtAyGUBPoapzpUFyRqYBEWiY,1149 +torch/include/ATen/ops/igammac_cpu_dispatch.h,sha256=dgMYmRnMYDaUVQIXKwGLUd9okMTS_oelXl1qOWj7j3o,1290 +torch/include/ATen/ops/igammac_cuda_dispatch.h,sha256=8gSJnFxGgHAfFAAOmEelH8iX8aKtzB78e9NH-JdHflI,1292 +torch/include/ATen/ops/igammac_meta.h,sha256=dfACs6_XYbhf0jNRo-oZk_Bb9_Lu1efXP8MEIZDF8KU,848 +torch/include/ATen/ops/igammac_meta_dispatch.h,sha256=Y0H23tNOs3fLKDho1qmxvJrqMJaytNRqplKeZ_scQ8A,1292 +torch/include/ATen/ops/igammac_native.h,sha256=QzogQqr8kTcBc8TXvUU7-RUim4sf606CzzehPNwwJds,879 +torch/include/ATen/ops/igammac_ops.h,sha256=ARAh0VHU2m2G4LpBXGJRGNkwLFk7q0b-n_qNV_aLZeA,2567 +torch/include/ATen/ops/im2col.h,sha256=YlDUTDLoz2ZBKGl_lC46ral5zaaW17pqC9UTpKTEPug,1917 +torch/include/ATen/ops/im2col_cpu_dispatch.h,sha256=uOJ22eXzcIHH07RKU0m9CXDhduXH3Q70ULeIBOPenS0,1443 +torch/include/ATen/ops/im2col_cuda_dispatch.h,sha256=fhvxSuBrl5d5pOQlT7tpmnrRAJg6cRj7lUQexSx-NO4,1445 +torch/include/ATen/ops/im2col_native.h,sha256=ePgBbkJNl730DBnNJLCqw8elpcy9CRER-hBLuUX1BGc,1374 +torch/include/ATen/ops/im2col_ops.h,sha256=ua99MTF4_a3rc6UEhyp9ObxNoAuR_pbgATSbMQUVlBw,2489 +torch/include/ATen/ops/imag.h,sha256=yFZjfMxPblNPb9HlmZFIrTa-3XCMUX6dHJ2DbkB_8L0,889 +torch/include/ATen/ops/imag_compositeimplicitautograd_dispatch.h,sha256=SxQ-Wyw8WPQzptOBMIlPwXYIMZaFNPZLh4cK4ITrjp0,1016 +torch/include/ATen/ops/imag_native.h,sha256=WXorn8w1rdDP3XkJB848Apkh9rOrPzJj2Cg2PHjaIXs,728 +torch/include/ATen/ops/imag_ops.h,sha256=HElfQDb9uXvnYsH1XBoRnuPjMXKftZVrmKoSlXLcgLY,1211 +torch/include/ATen/ops/index.h,sha256=ruhPu8n7JyeaFk421zcfKupeioQd9FiOUv5By8f5mac,1565 +torch/include/ATen/ops/index_add.h,sha256=AhZxZ_1LdPqh6cmHJ1PuMw5WzJM-VtoBTNgY38LiKxQ,1837 +torch/include/ATen/ops/index_add_compositeexplicitautogradnonfunctional_dispatch.h,sha256=z9BTErtRCGf-rYCAaTs4VbEJF23IY-0LJPuLNXNCIVY,1289 +torch/include/ATen/ops/index_add_cpu_dispatch.h,sha256=2F4JpX2QZjRsOI1JTmtaWXSJ81UbZ4INd03JaQlR_6g,1568 +torch/include/ATen/ops/index_add_cuda_dispatch.h,sha256=Tui8AsWwqVONrg3sor30TT9HKJ2ijGRzjDlFwb7tdb0,1570 +torch/include/ATen/ops/index_add_meta.h,sha256=DQBoGG5Y0wfzpXygggb_vAdLf0zT-eYjOTwv971Z8yU,1358 +torch/include/ATen/ops/index_add_meta_dispatch.h,sha256=YcuZ2okuVdtOVShtA6pC3f4ZuvMfCT70TnLdUIP1xqg,1570 +torch/include/ATen/ops/index_add_native.h,sha256=UF0nrCv2rtMWQ9UvaEQNYPiMoo7vqJhKC-u2ju933vY,1199 +torch/include/ATen/ops/index_add_ops.h,sha256=NzWyAdcx6LrM7qGaQtXA4hXjHYGqyMlB2v7CoQBFZjI,3254 +torch/include/ATen/ops/index_compositeexplicitautogradnonfunctional_dispatch.h,sha256=ZV_DNR4d_ncrtDwB4RYYw1SimIxzje_0B4ktoZ_S-aY,1099 +torch/include/ATen/ops/index_copy.h,sha256=zNUuIMvB2oSlLqe_CsOoDJA-gUQSViFsItZzE4Cqy2U,1693 +torch/include/ATen/ops/index_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Bae7fhjweIgjzIZLkFynMrGpwni2JadYu4wspwOq4vo,1235 +torch/include/ATen/ops/index_copy_cpu_dispatch.h,sha256=bE1T6LKEhVBpeBxVioeXMy6KnvhhtjuwGWw5Tweqk3w,1462 +torch/include/ATen/ops/index_copy_cuda_dispatch.h,sha256=ZhQFZ0qKg4h2K7zGCsFbiMq6-b4-4fcMSrx4m8CliGE,1464 +torch/include/ATen/ops/index_copy_meta.h,sha256=YWuC5O3xUPp38-j_0LjReV7VdkFWa6f6XZjIwnhRGuo,1333 +torch/include/ATen/ops/index_copy_meta_dispatch.h,sha256=lBnai1XrXcLEBNwD1rB13GFfW1YQRtY26mA6fgWYnfY,1464 +torch/include/ATen/ops/index_copy_native.h,sha256=vYvlzCn6KKrqrXVREL-vbWXpB-hhVt0jBbWrGu_kEa0,928 +torch/include/ATen/ops/index_copy_ops.h,sha256=6TmfKGW34v56Hw3tXAvI5yNfYQN-eYNbbP9bd8zQWUM,2993 +torch/include/ATen/ops/index_cpu_dispatch.h,sha256=RX6W_Jj268ioEBNpscHjqnK5srueJTkiCK8qw9XgZ4k,1296 +torch/include/ATen/ops/index_cuda_dispatch.h,sha256=LlS5NdMJKzo7u3C_dhihdlpLHI7rin7sHK0lD2a41S8,1298 +torch/include/ATen/ops/index_fill.h,sha256=XHz7eVoU_SUtpU_v5rqSBLTgQp3ZswnCiYIMOk1UHG0,2740 +torch/include/ATen/ops/index_fill_compositeexplicitautograd_dispatch.h,sha256=Dcyf5OE5no45rVa-wSKjiQKjpEF47fy9eDLzHShCsG4,1800 +torch/include/ATen/ops/index_fill_cpu_dispatch.h,sha256=0DpqbB7yHf_ophHYJhNxeuiqoQtdRG87rxwtW1lk62E,1160 +torch/include/ATen/ops/index_fill_cuda_dispatch.h,sha256=pgayRlrQ_f3zHnL4tB7yl4EPVAS-ReO1rTnJ2qEUWN0,1162 +torch/include/ATen/ops/index_fill_meta_dispatch.h,sha256=jEj5x-xgAGmEg3CRIBlrcXaorGVctBk_PBRBGHpMSxA,1162 +torch/include/ATen/ops/index_fill_native.h,sha256=7jzmVK92A5o47PXerY0QzyaIIM0BNlhuZ2ll27J18Bk,1478 +torch/include/ATen/ops/index_fill_ops.h,sha256=3_FoAe7TOhkIpD8lbH_VQUMF-1YFSQkOA4wYmHGJHcY,5451 +torch/include/ATen/ops/index_meta.h,sha256=5S_h461qMH4jxskr3Fq_tAhItYCbriTDeA8Z-bFsaEQ,1724 +torch/include/ATen/ops/index_meta_dispatch.h,sha256=XrwxDDDRynUi1n8ta0AaYNqHhr1oduDbL21k4ytb2t4,1298 +torch/include/ATen/ops/index_native.h,sha256=09Lmtqaqa085HGjGWdW8AWGAoMN6DScig4af2Qx7lVs,1017 +torch/include/ATen/ops/index_ops.h,sha256=bwyezNPt29E34-RsJEJaZ8gsYxpPH_0DB36ytz_xz5w,2194 +torch/include/ATen/ops/index_put.h,sha256=Ks-6-jJ2eEoIAMJuwQSMfYCQ2BD-scLrmO2oEJuj3hI,2224 +torch/include/ATen/ops/index_put_compositeexplicitautograd_dispatch.h,sha256=mB5eByzJoPYsqozpQdwRznS7nQDjMRbvVBXCdb55LlU,1656 +torch/include/ATen/ops/index_put_native.h,sha256=oxXCba3BBaIXCVie-cbReO9NUREKQxYdyCs8Sy3IEJw,1180 +torch/include/ATen/ops/index_put_ops.h,sha256=hMUbiJ6pgrcc9G4wvOAbxUR1aFm729E_SzTBqjpvcik,3320 +torch/include/ATen/ops/index_reduce.h,sha256=qamOHdKOCypJx9Q9mG0CFV0MYBFRyhNT3OZ9qG6jdb0,2032 +torch/include/ATen/ops/index_reduce_compositeexplicitautogradnonfunctional_dispatch.h,sha256=TwWtHcnGfcnEVTeeYSj-X58QCKxW4-vKFw_70vQfBc8,1337 +torch/include/ATen/ops/index_reduce_cpu_dispatch.h,sha256=OwK25FXCWKylR0Q7nnM2s3smGdtwmx7pjD8nUq_-LF8,1661 +torch/include/ATen/ops/index_reduce_cuda_dispatch.h,sha256=9B3tVtyEAIKQG6BX12fsfWkvjBat_F8WLuVe1qkadRs,1663 +torch/include/ATen/ops/index_reduce_meta.h,sha256=yNr1Q1yztfsj21p-uf7536-OLQG_xiZaHn-vTfbnmYI,1379 +torch/include/ATen/ops/index_reduce_meta_dispatch.h,sha256=f0PHMzb771qSC1a-Mpe-4vqvJuODpN8LN58EmXrsWYw,1663 +torch/include/ATen/ops/index_reduce_native.h,sha256=93nmh87vvzHNLo0w0jXX8I_b6Yz9YfAuuyqWHwSFlZc,1250 +torch/include/ATen/ops/index_reduce_ops.h,sha256=bbqTJ0RXFEHFX8303ac8e0raRGNP4YKM9mQFhSXsSKg,3461 +torch/include/ATen/ops/index_select.h,sha256=8TbkamSboHxRmW7skozInAbh65kBPIkjnm-Cjcebhi4,1563 +torch/include/ATen/ops/index_select_backward.h,sha256=slOc28DdgfNC_ubjBAmKz8yPjdS-jmQbQyrHWULP2-w,2102 +torch/include/ATen/ops/index_select_backward_compositeimplicitautograd_dispatch.h,sha256=jLGWp0uhJCSVaT2Dr9O-Eb69R6HVB4y1ghSepfMboYk,1247 +torch/include/ATen/ops/index_select_backward_native.h,sha256=gffJaodvfLdw70boye5nj0NQfgp5ddCdix0Hf5kcWI8,823 +torch/include/ATen/ops/index_select_backward_ops.h,sha256=8ME8cNRChaXiYNEv59CQ7-f8iPzfTOLas9IEI8IXsH4,1492 +torch/include/ATen/ops/index_select_cpu_dispatch.h,sha256=S7WsUdWsPKFvV4ZqB8rgCt_s5VoXXqlvTGadHgLZ8EY,1266 +torch/include/ATen/ops/index_select_cuda_dispatch.h,sha256=daEAg9AsS9_4NWm-lDsIppklprjd0l0_WURns5eAw28,1268 +torch/include/ATen/ops/index_select_native.h,sha256=fv_wDMQw_vu18yiW8Vno5_Ba0OxFDOtzIWzE99Hzn_I,1589 +torch/include/ATen/ops/index_select_ops.h,sha256=PFJjim1lCu1NW2GaTp__CEZMDFjGzptZVo0YOfmxGmg,2097 +torch/include/ATen/ops/indices.h,sha256=biiLfebFduEOWdRsTTQD2akmfFG9VaEQkYMJaB0BFGM,758 +torch/include/ATen/ops/indices_compositeexplicitautograd_dispatch.h,sha256=GpSLJ6mt8tofwWsMxD2B3_4eE1qmLzWKQQywRVXrGxc,1019 +torch/include/ATen/ops/indices_copy.h,sha256=_p8Qd4y6N1_LMJnpHoDqe6K1xgdOC17PBkmNHcvjFms,1341 +torch/include/ATen/ops/indices_copy_compositeexplicitautograd_dispatch.h,sha256=oG5_Mhjt7Pc1hO8cMaCv_TF9jF8q_xRxkiYdnLJ4cs0,1133 +torch/include/ATen/ops/indices_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=oUW-_Gg9sZICspCkDSGLWgXrpORttFhhkykL7E9ejTg,1050 +torch/include/ATen/ops/indices_copy_native.h,sha256=Jhrp4gw8IkIbBSYiCA72FjEDgurR-O55c00rCo3dZps,820 +torch/include/ATen/ops/indices_copy_ops.h,sha256=BX1WBcoe3Q09d8AiiTwewazDEUnR0fNW8GKLcipvXxw,1837 +torch/include/ATen/ops/indices_native.h,sha256=bQmbcba8oUdpMoQM1qhnLTj1uwcM0nAxXRLPsfVGma0,801 +torch/include/ATen/ops/indices_ops.h,sha256=2twPl1-5RUgcCS5G-7XOgwBJoNNRb0Q0WGj98BM-On8,1220 +torch/include/ATen/ops/infinitely_differentiable_gelu_backward.h,sha256=6CL9ib1hNQQstISRcupwbnz1Kb53D-hIe8uR4X2Hn9U,1067 +torch/include/ATen/ops/infinitely_differentiable_gelu_backward_compositeimplicitautograd_dispatch.h,sha256=P0swEBGplvXoxxCPjL4J402pAfL6iwPoGpo2FrBsQxw,1076 +torch/include/ATen/ops/infinitely_differentiable_gelu_backward_native.h,sha256=Q6Xy5dnCV9Ey-5P0vnjC8Z6ayRZ_aAVluCrM1yGxMHE,788 +torch/include/ATen/ops/infinitely_differentiable_gelu_backward_ops.h,sha256=1ej29AVmtzPcIK2KqYr02DeEVjnw215g8q7tcMoacdA,1393 +torch/include/ATen/ops/inner.h,sha256=6VRopWehatz55WV_ppIbtt1CdsaK56oJ3pQpdnlojNo,1412 +torch/include/ATen/ops/inner_compositeimplicitautograd_dispatch.h,sha256=xQifvGdPeEXR5dQyZzdc7z6MfMJq_k8Qn4Lm0WpEi6M,1250 +torch/include/ATen/ops/inner_native.h,sha256=3lz0YaoHG9Cq4LwZvlSyNdQZFA5oCuTdm-OpezMcN2o,858 +torch/include/ATen/ops/inner_ops.h,sha256=WVHK0JxecEEYBCiq3tHrbrZ4eUORBh31ZnNXS1g-HVU,1967 +torch/include/ATen/ops/instance_norm.h,sha256=V1tCUnvCqvoSUY18d1pyWHT5svNsELNipScxmjCyy44,1408 +torch/include/ATen/ops/instance_norm_compositeimplicitautograd_dispatch.h,sha256=u3rK6Q5D0koH9sDa14e_qE84teW3luBNOl8jxw9YC-A,1282 +torch/include/ATen/ops/instance_norm_native.h,sha256=70-KXX4cnVxleoMFw3yMG1sktxtfIrO8QrhHVtsOgTo,994 +torch/include/ATen/ops/instance_norm_ops.h,sha256=IYdXEjZohxdjpnMDzxn-nc6lQgGyqJzlZAqUeZDoocE,2065 +torch/include/ATen/ops/int_repr.h,sha256=ycMZZTaTzKFhkPObOnDrFzauNruY1VxCBJ4_KWH-ijg,1301 +torch/include/ATen/ops/int_repr_compositeexplicitautograd_dispatch.h,sha256=fIIwBnoGsN5y1Lhg_8R90GgTBSFKrTocroCzS4z89iY,1125 +torch/include/ATen/ops/int_repr_native.h,sha256=EUKLTh4zazD3MuOy4IzYPz0e141Y4g1ryASQvggv8HM,897 +torch/include/ATen/ops/int_repr_ops.h,sha256=0uupzEn212-x-NvvVhYjQnvK9QP8v1_3aYZJFPujVAQ,1813 +torch/include/ATen/ops/inverse.h,sha256=pRWZUdhSC8wuz0E8rujCAznVF9RRRGcHtjHKJLz0PdU,1291 +torch/include/ATen/ops/inverse_compositeimplicitautograd_dispatch.h,sha256=sa_HVkfj9FO-zSrIGwXs-PReI11tSTFfKUW4aXemRgY,1178 +torch/include/ATen/ops/inverse_native.h,sha256=PH9-A5moRWzDHPcMU3uLx5KR15Zhh5oixC9hLwKu1_o,810 +torch/include/ATen/ops/inverse_ops.h,sha256=F3OKmZrWLuu7IeCtPZvXWvqFjVkpHsEdulCDQONj3AA,1807 +torch/include/ATen/ops/is_coalesced.h,sha256=ZW1-5Et3yx3yR42xodhOWhSHBf9u9xsx8_21e7gR2gA,763 +torch/include/ATen/ops/is_coalesced_compositeexplicitautograd_dispatch.h,sha256=hUlIkuWnqTJQhVbUDdNjY5jTT-MTBvaxFsKyP0OSipk,1018 +torch/include/ATen/ops/is_coalesced_native.h,sha256=l3N5JaXgAqKZQw4xe-Ei1Q7dTaRCWDjJfzyu0HVQaeo,799 +torch/include/ATen/ops/is_coalesced_ops.h,sha256=6mhh4K0KKdQEQdYlTG81pVx5L54FsyGqcv8AoQclrDw,1209 +torch/include/ATen/ops/is_complex.h,sha256=xI4aDfwm0GBVP-RjfC8VJETrSS1aMa1hWgH3i3lGGt4,910 +torch/include/ATen/ops/is_complex_compositeimplicitautograd_dispatch.h,sha256=QjufQ2YdaNIIpSfVy8q1PCdPXTiYKrHJnXl66JIJXSo,1016 +torch/include/ATen/ops/is_complex_native.h,sha256=K0z1XMOTkS1dnoPlj9KLX8WBHf0slUJ0y5SnzCgKrpw,728 +torch/include/ATen/ops/is_complex_ops.h,sha256=Rh8ByZgdXyF0GUP74ZKDa1B82HNFq8D4He6x5FxODp8,1203 +torch/include/ATen/ops/is_conj.h,sha256=YwTCcx5souEsObQYIFNDtdvbzaQbFc4DR_e8z1rw_e4,898 +torch/include/ATen/ops/is_conj_compositeimplicitautograd_dispatch.h,sha256=jj6s52CvUa2vzY8QP-aAzTCtCCenqw_IfCqtOSQKNbs,1013 +torch/include/ATen/ops/is_conj_native.h,sha256=j7u5Rb8BGwYcdsF9s8utwE4gxjg4v8igJj1_bJrzaZA,725 +torch/include/ATen/ops/is_conj_ops.h,sha256=VfXZw3JdCfKItAhvFEFLqoakVcYZ9BxWZLYqqaD-XhU,1194 +torch/include/ATen/ops/is_contiguous.h,sha256=v8QjGuWBzeWKWt70HKmTU5QH9FauY7KsCvlA1kV2JQ4,764 +torch/include/ATen/ops/is_contiguous_compositeimplicitautograd_dispatch.h,sha256=W7ygfJNr1Arx-22dK6QQ86xZa8HouLTRCBxzks0XFXw,1106 +torch/include/ATen/ops/is_contiguous_native.h,sha256=UKYScvs3zkAW_sgelr6gOexaGmljwJFE6JcXgpY1kyM,818 +torch/include/ATen/ops/is_contiguous_ops.h,sha256=sknPt-kpX65jEMoU6a2Pc2oWC1kWgsXOlutM1ClLs3c,1864 +torch/include/ATen/ops/is_distributed.h,sha256=imL-wiVkVCUHTGLBaJY39k1jnnUmdmn_xuVHe_BvXtc,915 +torch/include/ATen/ops/is_distributed_compositeimplicitautograd_dispatch.h,sha256=61V8EBwrJcd2h3csREc6vFPc_Y2CTfIFgkgmobEcrA4,1020 +torch/include/ATen/ops/is_distributed_native.h,sha256=mXFsndnWH3Q2eqkuKEIHGkT3PBXYnznwoVUNFcjIM2s,732 +torch/include/ATen/ops/is_distributed_ops.h,sha256=2tPcfGq5kkcBz3j8D1wv3hnoLYrpDPbKT27vAhsmJK0,1215 +torch/include/ATen/ops/is_floating_point.h,sha256=4IADbedwoa2UqqHiQeEQUL2uFFU-MUEME2QPMhivF1k,938 +torch/include/ATen/ops/is_floating_point_compositeimplicitautograd_dispatch.h,sha256=H59X-DeBoOABV4H6mqpXGnyXVAsxrZ-r1wqebXfhaG4,1023 +torch/include/ATen/ops/is_floating_point_native.h,sha256=yYLKOKzHOrFyPwuOXJi1TuzDcbH-ADjJ3gH0yc93Q_0,735 +torch/include/ATen/ops/is_floating_point_ops.h,sha256=C2s13gNQvqiM6hJiJ07rYwqMRRZKL75YX0o2UutF7Z8,1224 +torch/include/ATen/ops/is_inference.h,sha256=MrBFh043o5hdUsAtcM0NRa5uMb6JDy-mh4iCu4TlKHU,918 +torch/include/ATen/ops/is_inference_compositeimplicitautograd_dispatch.h,sha256=-6wpdSiNuSlOn8e8_GU7NztI15BJrqXvw_U6HVrCraE,1018 +torch/include/ATen/ops/is_inference_native.h,sha256=raRGdsoG9cXjOhou_72jDySWuYgvuOa9LEazG760ekE,730 +torch/include/ATen/ops/is_inference_ops.h,sha256=_1MgjhX7cIwaxuapmIDft_bT1M1AyVfnHwSo8ezJKWk,1209 +torch/include/ATen/ops/is_leaf.h,sha256=6p9jCL1uRs_CR0zyAvD0sNQ-p9VSV0ndQWnK_2ikYfk,758 +torch/include/ATen/ops/is_leaf_compositeimplicitautograd_dispatch.h,sha256=Hkn_EvMg2BcCzh8zvq87y-cC7FzvTyo4sPsiQMsOSvg,1013 +torch/include/ATen/ops/is_leaf_native.h,sha256=gPGiIQPdnneaHuU-dv6PKdOTh0lyjTs9GwFrJC14nrc,725 +torch/include/ATen/ops/is_leaf_ops.h,sha256=A2BFI1ADvX3VxxFRP8C9--vgkm0_BnG0RMSVcBjUdXI,1194 +torch/include/ATen/ops/is_neg.h,sha256=2NqwBkbwXrU_u3JxxYA9TesF2_E52hM6QhwoTl1sPEE,894 +torch/include/ATen/ops/is_neg_compositeimplicitautograd_dispatch.h,sha256=p2wU9Nuzx-3XJ-2Lh_CCTKdDN4RPWcwk-73akS3batg,1012 +torch/include/ATen/ops/is_neg_native.h,sha256=nV9-jkWR_jB9zqUZlW2f0Lm-y4lstQMl1pVmrWJi0vw,724 +torch/include/ATen/ops/is_neg_ops.h,sha256=Lj-KPMw9zkqyspOJH2maU7D4v9MDWNl8CfEYpU59BIc,1191 +torch/include/ATen/ops/is_nonzero.h,sha256=du320jUzSUkWBI59XkWtRENJnqAfjvYXK-s2TWuLO8c,899 +torch/include/ATen/ops/is_nonzero_compositeimplicitautograd_dispatch.h,sha256=YPhPhFiHvnixH4F2ZxHCGLSqhO0eaKK30NSHZq8XDrU,1016 +torch/include/ATen/ops/is_nonzero_native.h,sha256=fA9ymsxDYnv3bmYoUMj45W3yTi2lQ4MoNeBf2gsGzm0,728 +torch/include/ATen/ops/is_nonzero_ops.h,sha256=akpknsqDvhur33b7DYwMh2QsD_aeqix6lfVXt6T5HpQ,1203 +torch/include/ATen/ops/is_pinned.h,sha256=RFCwbemUy4l5PqvKtJZyjB42LtOaEvSo9WMQNaKHhuc,760 +torch/include/ATen/ops/is_pinned_compositeexplicitautograd_dispatch.h,sha256=mEirh2dRfyF7Y7cVxTq-CqiKsAclQQ2cq4ir7G9i2U8,1066 +torch/include/ATen/ops/is_pinned_native.h,sha256=EoZbd05jbb4Ly-BNV00lBF_IiAeccF2SzCQQCpJHGIc,1011 +torch/include/ATen/ops/is_pinned_ops.h,sha256=8r601Z8R2ohjtOXRJrcsmHx0hiufqlD6GjoPWFQiS3o,1322 +torch/include/ATen/ops/is_same_size.h,sha256=YY6JTmKvWO4vRcmqywTOhKd1yEQ82IKWutIKXEkJyhg,954 +torch/include/ATen/ops/is_same_size_compositeexplicitautograd_dispatch.h,sha256=4yVtWXLhSiNxmB-ZMbj6_jf6WHfbhcpf9Rz6nhARD5E,1044 +torch/include/ATen/ops/is_same_size_native.h,sha256=IgDqoTbfvWejDdZhPaPE1bHCtbt6AQzB5p20Jz6-EkE,843 +torch/include/ATen/ops/is_same_size_ops.h,sha256=ublGvFsLWwlhVA09TaL84h_eGcpG413qRfQ4O2GDXyk,1295 +torch/include/ATen/ops/is_set_to.h,sha256=-52DcqLN9voUTp2BcCDm6gYrjzlCbBRq1ZYVzqEF40M,760 +torch/include/ATen/ops/is_set_to_cpu_dispatch.h,sha256=_l_1fXjCdi-Bv1R426pp2bqKhQSCyEle_3fkrKKgAT0,998 +torch/include/ATen/ops/is_set_to_cuda_dispatch.h,sha256=vL6qgiFhkYwg9Sc21o4HKK9fIRiDq3CMpvJNTdXB29E,1000 +torch/include/ATen/ops/is_set_to_native.h,sha256=VcC0hPObWRnbl1HI7DrbjrCGmCjdWDadPp3YWpa4GKk,754 +torch/include/ATen/ops/is_set_to_ops.h,sha256=C2vPudmTX__mrja4NovmyJXjJ9iFxq80fehzM1TBIxE,1289 +torch/include/ATen/ops/is_signed.h,sha256=tcQ35vAA00pLtgAdgqkpbrHyS8gnRmwWU_jiG3Xus5Y,906 +torch/include/ATen/ops/is_signed_compositeimplicitautograd_dispatch.h,sha256=sgJXH_giAQDghHd8wrsmMfI2WF4pwk9lNIu99p_Ayho,1015 +torch/include/ATen/ops/is_signed_native.h,sha256=2pdzOvBDzuV0muVIwbYhYvhq2p6LUJeEAkBQByLJqk4,727 +torch/include/ATen/ops/is_signed_ops.h,sha256=2CSJ_2wRsX-VDHoERaYVy-ZmWCONG3JY05gOqoNBOaI,1200 +torch/include/ATen/ops/is_vulkan_available.h,sha256=mFdqi6hWCHywLPZarfzpqGtewj3LDxIlBcs83i_KrXI,897 +torch/include/ATen/ops/is_vulkan_available_compositeimplicitautograd_dispatch.h,sha256=tVfzrVDeJ0ZF317z4WyUUWuHUq-gu50Y9-DReBL7oss,1002 +torch/include/ATen/ops/is_vulkan_available_native.h,sha256=XgHjC0aiYvMBQmlkGPEThqaRIbj1z0jlPtGvxQoljVw,714 +torch/include/ATen/ops/is_vulkan_available_ops.h,sha256=PIsTRqyHVjFIUhxKdkkTpgQAvij8FvSl0u_EAPwK8Nc,1153 +torch/include/ATen/ops/isclose.h,sha256=-8PBlEtOMJEJOjkAbsxbIg9oEWXeELkjpv6b9iDa2DA,1083 +torch/include/ATen/ops/isclose_compositeimplicitautograd_dispatch.h,sha256=Rld3SOMcLpjog3VPgNI2Oc7WCYjJdGC5WvpG4IyUMH8,1105 +torch/include/ATen/ops/isclose_native.h,sha256=Rshvo3tkn7ojoINHclQOIbYVq9m3t-i2la2YfL9OpA8,817 +torch/include/ATen/ops/isclose_ops.h,sha256=ivRXVQ4o1feQR5ChrobS6zk9S2htBsAYOzNEsYL8YD4,1464 +torch/include/ATen/ops/isfinite.h,sha256=5ToWsv0-Q-_5EChjF9Eeo-cb79RbjbG3oGY24R8R54I,899 +torch/include/ATen/ops/isfinite_compositeimplicitautograd_dispatch.h,sha256=GZiqnUJSOFcdIyuHt0r6YzcV5Bllx1uLdLdMjonh6a0,1020 +torch/include/ATen/ops/isfinite_native.h,sha256=_u-MSvWeA8nF0Jk-_MZmf85GSjFjpC-jGQYQ0ayWIYI,732 +torch/include/ATen/ops/isfinite_ops.h,sha256=vaZ-U87s4wAkB63r8zwQWIqdRiyYwnRFXiOp39cL7kU,1217 +torch/include/ATen/ops/isin.h,sha256=WhazdlD_Opdn7LuG4A09qTWcZlO-XfCEyVTItdSRXDE,4246 +torch/include/ATen/ops/isin_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Qe13jK0y2LvbuO2G-sAH7XbcIltKxbnsJvfMKu_KIQE,1393 +torch/include/ATen/ops/isin_cpu_dispatch.h,sha256=lsT6oOW3z6kmqL5xtPsNRHjFnjzwHHrpV7p7ygmDTQs,2240 +torch/include/ATen/ops/isin_cuda_dispatch.h,sha256=SVubfGLawoH2ppQVDuZVRP05OMYFw3DyreMAm8uPH6I,2242 +torch/include/ATen/ops/isin_meta.h,sha256=fbztCmAgpbgUoxooa5MU6YVS0BbxjIIJlDn0ldMoxMQ,1288 +torch/include/ATen/ops/isin_meta_dispatch.h,sha256=D5ktQImj-v5Hd7-lDFv1deZmvty-sqff66SI_bkIIuo,2242 +torch/include/ATen/ops/isin_native.h,sha256=xB-rEmOmPEjUHnSEP_WCg3RXHORzaOypd_hzwegecb0,1413 +torch/include/ATen/ops/isin_ops.h,sha256=rfm5pWfeuu9hFdUnIutfMl_XmuhyRF_VXsvliZADHWI,5661 +torch/include/ATen/ops/isinf.h,sha256=gypDpC03jA1B4vik9uXFcWd6Uc42CbXRv2LlPHJoWt4,1271 +torch/include/ATen/ops/isinf_compositeexplicitautograd_dispatch.h,sha256=bKqdE6Vai3sIcM0CcfNHkR_6EANwEl38ZOhrJU8yDGc,1172 +torch/include/ATen/ops/isinf_native.h,sha256=TI-grvT35kUJe1hWMmb7XXsvrasd92TZ1_qjzoV_SIc,1061 +torch/include/ATen/ops/isinf_ops.h,sha256=HuWOPetJp37DYsCR60zkssPOeEiE8McCUO2xQvdlqhI,1795 +torch/include/ATen/ops/isnan.h,sha256=77TyLPRerfi28Mfbz7ACkrNvx7Sg87c0lwghJ8iSQpo,1271 +torch/include/ATen/ops/isnan_compositeexplicitautograd_dispatch.h,sha256=AwqiUdjPi7-aruCVfPahUaYe1hIKIRaku5godcXPMRw,1119 +torch/include/ATen/ops/isnan_cpu_dispatch.h,sha256=HVJtU8n3sKIjGr9OQghjM6lU9Z23ek-bNTIEgBKagVU,973 +torch/include/ATen/ops/isnan_cuda_dispatch.h,sha256=vctyu7gU3TY_2JQWYu8FpMCz-CEmh1Cp9HaYrlSAW0k,975 +torch/include/ATen/ops/isnan_native.h,sha256=WsDMzgMMIzxGCDKUE4bLAHq2x9U04vdTUMtrF5qnZL4,996 +torch/include/ATen/ops/isnan_ops.h,sha256=XdC1BkfY6aRhRnQeNxFUGojZafWgsCPLT8Uf-Ibg734,1795 +torch/include/ATen/ops/isneginf.h,sha256=iof4In0F0j-c-1_Xw-Kd3w7pjUIfiO7yNK40Rh4vSoE,1301 +torch/include/ATen/ops/isneginf_compositeexplicitautogradnonfunctional_dispatch.h,sha256=QReQGn0CbxrgaB7o_0v2lSN-PzxSuc1J8ILeeCZkhko,1046 +torch/include/ATen/ops/isneginf_cpu_dispatch.h,sha256=-2QaPawkZP2C31pkXogocXs8tJZ5HIExgoulDvZo5ks,1137 +torch/include/ATen/ops/isneginf_cuda_dispatch.h,sha256=e9Xsl_tsFmQHxCcKtKSPdhbXFSXtVLwSeLL4AlqNpFc,1139 +torch/include/ATen/ops/isneginf_meta.h,sha256=N5qQE5KonmrbHTh9hHxjAPceG7FU8obggG7zEaCh230,823 +torch/include/ATen/ops/isneginf_meta_dispatch.h,sha256=4Dx6mrypjgCIqfRd48sL1cdipVgA5NCfMlgNgqAMEdo,1139 +torch/include/ATen/ops/isneginf_native.h,sha256=1UagMP1SQ01JycJa6oKi8EA4Iocawh2Xlh5YkSJFteI,1233 +torch/include/ATen/ops/isneginf_ops.h,sha256=ei81kyj0f0fIe5KvTjdcJKyFZIkKN_GmzWb0O-igO7M,1813 +torch/include/ATen/ops/isposinf.h,sha256=WLRNW7GNpOR0DyC9ciFiA7YuQfrgQE1634q69c4fJKE,1301 +torch/include/ATen/ops/isposinf_compositeexplicitautogradnonfunctional_dispatch.h,sha256=pPubQ6FYnJ3i_teq9IguUtx8Znb9U95vBGR9-NejlB0,1046 +torch/include/ATen/ops/isposinf_cpu_dispatch.h,sha256=WzV1F_przwXLoEPvWjlz55gads9NLRxvhjXZ_K9wo_I,1137 +torch/include/ATen/ops/isposinf_cuda_dispatch.h,sha256=BptRc-BkZbX2kHsOt5EQqOapZsVl1zmjT7rFynWAKt0,1139 +torch/include/ATen/ops/isposinf_meta.h,sha256=Wbt43lJCcs_ICXWt646GlBkaMj5eJAhFJPAXK9DiyIE,823 +torch/include/ATen/ops/isposinf_meta_dispatch.h,sha256=MRlwyYcBnX6hBgNGQ_7NHkP7iy9lYQFsIaeZB0CEWYM,1139 +torch/include/ATen/ops/isposinf_native.h,sha256=fSWxoxXKNPGGYwfvse_3qQd-dVDAR4qAgFaIMnUqhKo,1233 +torch/include/ATen/ops/isposinf_ops.h,sha256=hp8P_SA6voqbfw6g4LApS7r99ZFyytRoccXrVT-JoTs,1813 +torch/include/ATen/ops/isreal.h,sha256=bGTe-VSHg9TftSCKJtiVjsFrvT2sEgoRrp6LM2FzcvM,891 +torch/include/ATen/ops/isreal_compositeimplicitautograd_dispatch.h,sha256=Jc353OyqBXgmJLYR8IUyw6IWVyIS2UFgnnVX3mJE3zA,1018 +torch/include/ATen/ops/isreal_native.h,sha256=ptkmkB4sShi0e7AagNjvClwYbMHUPHGhPDDz6mErQGA,730 +torch/include/ATen/ops/isreal_ops.h,sha256=5uby9MgEcYx71TAjx7CvWjT3Lai9A8zY4fvMDf9myFc,1211 +torch/include/ATen/ops/istft.h,sha256=Yzjv3QVopjdAt_LowWswshpTDlamT9L5y9bHDfgU24U,1492 +torch/include/ATen/ops/istft_compositeimplicitautograd_dispatch.h,sha256=9Tgl-nGsoUCxkHi8-VZbpdXTB28LZWyFaDI11XuXlqc,1346 +torch/include/ATen/ops/istft_native.h,sha256=MfJ1rPM5bgvL9iMACSA2iz1r8w_PY975VkOmRQuZOBs,1058 +torch/include/ATen/ops/istft_ops.h,sha256=PRxhyMKBPsJoht904kHDJvf3JOE1Vwc1UipHAe24r10,2054 +torch/include/ATen/ops/item.h,sha256=M_CBOXGPchUuvPzFYsD9vuEZWbSuz2Yz3MTjJP12g_o,755 +torch/include/ATen/ops/item_compositeimplicitautograd_dispatch.h,sha256=fU__fqXJsjSZ3HH9vdcEtRedSPJAEStwRwMy2uwjEOs,1016 +torch/include/ATen/ops/item_native.h,sha256=4cjkD8rHfcJVhL8a2GnyYOoA8lXJHGjZthYsHIPr0qc,728 +torch/include/ATen/ops/item_ops.h,sha256=vtZU6i98N49S9LvT761jg5601yg5_axXBufL-LBm_sI,1205 +torch/include/ATen/ops/kaiser_window.h,sha256=isilAV00c5MRgJC2VG1mN5sU4IPYtgqfELXT_ci1CE8,5258 +torch/include/ATen/ops/kaiser_window_compositeexplicitautograd_dispatch.h,sha256=7wg_rjpQCyD8YQFWsSGSPvwmKYqIoG9I8XNWhvcuPac,2516 +torch/include/ATen/ops/kaiser_window_native.h,sha256=sg6GGF0y2guMwldtdB7FcMcMaEo8L-4QfuBCBgc1nBQ,1673 +torch/include/ATen/ops/kaiser_window_ops.h,sha256=TeSIVHxwedxYocx9-wkk9t5g7INbJ3zjrlpeFKN0s_w,5919 +torch/include/ATen/ops/kl_div.h,sha256=83hIlDx7C9fFDZCcfa4OaE8tdEm08nPO6LBLTqlGR_M,1072 +torch/include/ATen/ops/kl_div_compositeimplicitautograd_dispatch.h,sha256=zxBof7Nf3LHnWwrJT_dD9PjnE9rNn5XTUZBsM7QZBXM,1107 +torch/include/ATen/ops/kl_div_native.h,sha256=cjKgIbUNHO_EAl12r4jzmEIR3AfgLAlkK5OxVF0z6Vw,819 +torch/include/ATen/ops/kl_div_ops.h,sha256=a6zf7oZSAU2a47zBWwslq7Dg8dNKph8-uJ8koYxyv1M,1433 +torch/include/ATen/ops/kron.h,sha256=kGIVCkAc6abFhxEUOVWjRq1c_6Pcib3xNF5vgeXymm4,1402 +torch/include/ATen/ops/kron_compositeimplicitautograd_dispatch.h,sha256=XV6Iwbadg4M0_rgZh8ExX4L23OKBfRFiiVq32CT2wI4,1247 +torch/include/ATen/ops/kron_native.h,sha256=9h3bqZZqoKLBKk0N7Yq5r1AxPhB67mGS8DXF6H-3pT0,856 +torch/include/ATen/ops/kron_ops.h,sha256=-YgQbZfQp2vvuCB6BcHFAFBIK11Hfxkp2FHlXYhHYao,1961 +torch/include/ATen/ops/kthvalue.h,sha256=5XnSy5Yy-u8Hqt1Zeou5CeDNtX4EqpR1Y4S4Sbb8v-Y,5115 +torch/include/ATen/ops/kthvalue_compositeexplicitautograd_dispatch.h,sha256=bdHYW7tMi3O0HdKwF6-9G37cnB5qj_V7tjKiPjQa1Z4,1231 +torch/include/ATen/ops/kthvalue_cpu_dispatch.h,sha256=WZVenAAr02TXBwC5sBBkJE3GbJL7-_firfsc6WRN9Aw,1642 +torch/include/ATen/ops/kthvalue_cuda_dispatch.h,sha256=Da2qPRZxqN8OZ3xS_kh1Y-9LQR1wRJ2GPSdFR6nK7wU,1644 +torch/include/ATen/ops/kthvalue_native.h,sha256=cm_gWifxs6KBcfaKazHttKi7VW0BCEle1dxS5Z7n-Jg,1153 +torch/include/ATen/ops/kthvalue_ops.h,sha256=Fp4RUGy_SYkxZ1b_d2Er81Sb2YFH78iO8oScTPRBMGU,2427 +torch/include/ATen/ops/l1_loss.h,sha256=k1a9jf8A0YzQgXdpluFd0O4EqdfU2As-eknk0BkWPHk,1015 +torch/include/ATen/ops/l1_loss_compositeimplicitautograd_dispatch.h,sha256=AJymPUvlIR9MqtkSSNmnBKROoCRuweUa0F0UVKvqUdY,1085 +torch/include/ATen/ops/l1_loss_native.h,sha256=xyUtLW6_QQsdggIV_nhcmF_Pj1tqjXWh_z3Xmn5hB7k,797 +torch/include/ATen/ops/l1_loss_ops.h,sha256=qv0S-bGah_B1cU7oPah8XTK-c__YwAheKsmOKW7LCC8,1370 +torch/include/ATen/ops/layer_norm.h,sha256=qVPK32H5XXf_JjhxsW4DmAzqIFEZ_ZsX133huSLVf4U,2631 +torch/include/ATen/ops/layer_norm_compositeimplicitautograd_dispatch.h,sha256=jI01jMp18uguzxhw3LifyDkgrpBhS7qQ28Na4p6Ljjc,1429 +torch/include/ATen/ops/layer_norm_native.h,sha256=mnvTtwXqu1xB1HSXdj1I2FJPPXjUyHxnsvIrlbg9Z78,914 +torch/include/ATen/ops/layer_norm_ops.h,sha256=Xy7bSxRDT9m1fQrBtD4uwyziOMWfe7y1_K7DwtpT16w,1753 +torch/include/ATen/ops/lcm.h,sha256=4vThhCCCFB0tx2r6-tvPP49HXMdrJmlvd5BvSbI_E2k,1572 +torch/include/ATen/ops/lcm_compositeexplicitautogradnonfunctional_dispatch.h,sha256=3dujOiSGprHvzvMstZdM4wIKAYKKuQ-m8zEUkbzobog,1141 +torch/include/ATen/ops/lcm_cpu_dispatch.h,sha256=eKKeVSnNRjLDImX0rpK8hTYkFzI7Bb5ZfzT7n0jYY3A,1274 +torch/include/ATen/ops/lcm_cuda_dispatch.h,sha256=cENvljCsOCi2BgBcnjgKjzZGiKr5gpRWrXKqbcok88c,1276 +torch/include/ATen/ops/lcm_meta.h,sha256=5-fPw3Pgip9aa6zU-H3ke42xNGdmAz--9OGisNRcha0,844 +torch/include/ATen/ops/lcm_meta_dispatch.h,sha256=srquQgSVi-NxvdsW1LnMzmgtt2Ubjr-LMny8YhleJYM,1276 +torch/include/ATen/ops/lcm_native.h,sha256=ljxcPeT1HmO5qmweFB9lufXTP6NG_0uOwwGIXdfboXI,867 +torch/include/ATen/ops/lcm_ops.h,sha256=FU9_QoC_vG-FXaKBxkUcv2SmwNalCX24vP6XUJPGFFs,2531 +torch/include/ATen/ops/ldexp.h,sha256=SqGIh2-eKtyWRlm-QfPI7yl3noMYe8cTjy3a0ZE6YTE,1612 +torch/include/ATen/ops/ldexp_compositeexplicitautograd_dispatch.h,sha256=I3ji3YpqEojxSz60SXO5Oxj693OPWlbKRUzwElUhKiY,1326 +torch/include/ATen/ops/ldexp_native.h,sha256=8X_ttcVRv3r3JTpp3m_JdYvi6UUkT6-0D8ypAuji6WU,934 +torch/include/ATen/ops/ldexp_ops.h,sha256=Fcae5btGXCVQ-aYkdfUFScWUHpXy_z4luYTRewvy29k,2569 +torch/include/ATen/ops/le.h,sha256=19VZOqVVuWxuKBwioVNIVpWeL7HI_0fNmO_enauTTvs,2096 +torch/include/ATen/ops/le_compositeexplicitautogradnonfunctional_dispatch.h,sha256=WSQI30NcgnnDYsBmmdBYaa0qdGq7hEZ2XH9PIvVm3RU,1288 +torch/include/ATen/ops/le_cpu_dispatch.h,sha256=ESdwdZ3dR2FS4sD9JYnUGjh3zhxUG_ynCPIJ-9sPW6w,1620 +torch/include/ATen/ops/le_cuda_dispatch.h,sha256=zq2_YhS10bXpTb7o3XOvDdTUvxnetTVf-JBKAzNN0is,1622 +torch/include/ATen/ops/le_meta.h,sha256=9sSCUK1F71kS4jHyOwwn7oMk-UhZguRKBHoGO05iwvQ,989 +torch/include/ATen/ops/le_meta_dispatch.h,sha256=IOQmMLQohyiMFEdUcw03fFAlUwgZ3Yk0IH3cyGW5FkM,1622 +torch/include/ATen/ops/le_native.h,sha256=nRxwPXb-WqrQFwoHNFZ_hqiTTqfJ-cVqBPfLYDtctEk,1459 +torch/include/ATen/ops/le_ops.h,sha256=ZMz2UPN6CtD4weuREmGUFjrsmZFowczPflwuw94e_FU,4455 +torch/include/ATen/ops/leaky_relu.h,sha256=-CLGc7m1qfcfpvDdtFRLDm7qUsf7OOHdp6UHu3onKFo,1806 +torch/include/ATen/ops/leaky_relu_backward.h,sha256=gZf4_ZyUhppyzlqBu-tFD45mz46BYBLKA27HISIBPoA,2072 +torch/include/ATen/ops/leaky_relu_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=r6aY2_i1WLNMMUuK6_Y4hXKzSTLasOdKt4zAQ3oyP20,1145 +torch/include/ATen/ops/leaky_relu_backward_cpu_dispatch.h,sha256=hI3h3YAGs3XuW7oXyTubFwBqnFa6JE5RNuPrnCEGFD8,1448 +torch/include/ATen/ops/leaky_relu_backward_cuda_dispatch.h,sha256=vqre75Zx7jRUvG8cg1mHGhbwA50AmoNuJ5QftbMnfZI,1450 +torch/include/ATen/ops/leaky_relu_backward_meta.h,sha256=-NZNhWUdiS1eDHXWd4ZCDFDH04W_7QFBAXr87tAX3u8,922 +torch/include/ATen/ops/leaky_relu_backward_meta_dispatch.h,sha256=XEoRZ1Ah3rleU0AS2uJDkU-ELg3V2-4GQv77ijnpB4w,1450 +torch/include/ATen/ops/leaky_relu_backward_native.h,sha256=P9eNYOd-Jhtw5sZBi4pbTqPQjWM6GQKkuaPBkfWMZ7c,984 +torch/include/ATen/ops/leaky_relu_backward_ops.h,sha256=ZQLlgoUVr2-9c6mzru1hB0sPtWpwsKL5UBvl8QzB0Fo,2493 +torch/include/ATen/ops/leaky_relu_compositeexplicitautogradnonfunctional_dispatch.h,sha256=oTTwf3vV_rlfRVs6vqgveLPJ9UPvtM2_Axu6IKk-XsM,1183 +torch/include/ATen/ops/leaky_relu_cpu_dispatch.h,sha256=PVYVcXH0vmGIebh7pni8H69p1BoDB7ojYC88sAitCVw,1353 +torch/include/ATen/ops/leaky_relu_cuda_dispatch.h,sha256=2gDaaoN0VFGtuXUdq9xehwaMWWe9DuAITOrCKSL1YiM,1355 +torch/include/ATen/ops/leaky_relu_meta.h,sha256=8geIt0FuoZ_2Xs2ZNMdJr4apgtf4VGCbEPFomrSk7bA,860 +torch/include/ATen/ops/leaky_relu_meta_dispatch.h,sha256=_JaiWSEnfjscrGVN23NJc5sJ1j6DUSyViOtETKBxF4U,1355 +torch/include/ATen/ops/leaky_relu_native.h,sha256=H23MHGgMYV3cFkA7W1HVH8cAi6Xr6Yj3geORjK0rYEg,1249 +torch/include/ATen/ops/leaky_relu_ops.h,sha256=Ac0ctgrObbYc3jAADZei4CCIHNdQJaBffyEd0gJOqXc,2690 +torch/include/ATen/ops/lerp.h,sha256=cV1A3CgmYqbIxUBW6j7qf_AHb60f8mK-DQ5HCzeRV2I,2398 +torch/include/ATen/ops/lerp_compositeexplicitautogradnonfunctional_dispatch.h,sha256=tbwm2obIQWAM_mqcKMOw4uVjgk7daIvtlKFmWXZ2MHg,1396 +torch/include/ATen/ops/lerp_cpu_dispatch.h,sha256=j0dcjawLFY1Cn0qZWWZ8o3nB42Fa2THm2VvkvEESsUI,1836 +torch/include/ATen/ops/lerp_cuda_dispatch.h,sha256=VeWnSEjz4ezKT70LvY_9YCgGowLXA6XvR5X9U4fIWHo,1838 +torch/include/ATen/ops/lerp_meta.h,sha256=FWska9KUKFzIcLfW7nShwiKmkQjW5tL196GxQb_QfUg,1043 +torch/include/ATen/ops/lerp_meta_dispatch.h,sha256=ZjL6XVFv0pQTzQTBlTPMMdtUbqE002ZHRBJJEiZj5OM,1838 +torch/include/ATen/ops/lerp_native.h,sha256=2B-Qh3h5JSwM5znXFtez_DOOZjNtFl9xwQpQW7214ZA,1103 +torch/include/ATen/ops/lerp_ops.h,sha256=vlztqvQSgLaVewjEby7Ry0FFPGiS0-K_ehNAbFVWKdE,4989 +torch/include/ATen/ops/less.h,sha256=TaK3EUbj54zdC6t5fEKctgzBl4syqn0A2P_PoKFr1ds,2134 +torch/include/ATen/ops/less_compositeimplicitautograd_dispatch.h,sha256=daH3ip2_gyq5VLdE_UskyunU04o6XEFZbVr04E1ob84,1680 +torch/include/ATen/ops/less_equal.h,sha256=yJBNuQ2UY6t2pCDVSN8Vmw-2FP1F50qEHHLPbzv4vf4,2248 +torch/include/ATen/ops/less_equal_compositeimplicitautograd_dispatch.h,sha256=ShkgZRScfhJgLSs5uHQPVc5azAAdzqITZV9kmzMhDTQ,1728 +torch/include/ATen/ops/less_equal_native.h,sha256=zr9b49YifeXmmdTjF3yIMZg-lvnRClPzZBneiCUDmU8,1222 +torch/include/ATen/ops/less_equal_ops.h,sha256=IJjNdOIJbN49mbSoo00PVio8hp0KlO41JVCi4r1C0t8,4599 +torch/include/ATen/ops/less_native.h,sha256=4r3FR6IRUXdRtsgi37yF8cyvSVnG9eLQjKdaXPmcskA,1186 +torch/include/ATen/ops/less_ops.h,sha256=KgbZ94sD8_7MLN7mxFwj_7Z-zwWTd3UcavGgPYMsPs4,4491 +torch/include/ATen/ops/lgamma.h,sha256=AvNeL1aLSbccWnwoTaOWG1wSZy20Q2yMhXwR0DvLLrQ,1281 +torch/include/ATen/ops/lgamma_compositeexplicitautogradnonfunctional_dispatch.h,sha256=fs_JZBCBJfDMBuDjtLcmBS8Wa0yX6hThZ5Vm21sTmV4,1095 +torch/include/ATen/ops/lgamma_cpu_dispatch.h,sha256=zT_rfENZynhi80uTsSezmONosqKulvCxUcjE5ctUD4A,1182 +torch/include/ATen/ops/lgamma_cuda_dispatch.h,sha256=IkOFjnafoj6Tw9wCfguphdAn6L3dyD3UhNrzqaMWEJM,1184 +torch/include/ATen/ops/lgamma_meta.h,sha256=MQ44SPZgk1x1G1mZxS7KDt4rePmZ46KBxS0JZwMnu7I,821 +torch/include/ATen/ops/lgamma_meta_dispatch.h,sha256=CimaogXH3Yd3d2-J4eBfo3GVntPJA7WVgT-6qCDjFQ0,1184 +torch/include/ATen/ops/lgamma_native.h,sha256=hpsGgP8cYDAXUBR1CkajzAe1Zsf0sKlUHiIZ2ctsFWo,850 +torch/include/ATen/ops/lgamma_ops.h,sha256=vzjaqK6UdW3uSxZ75IVattiTYJ84CIUr-uNHUwtUSHI,2300 +torch/include/ATen/ops/lift.h,sha256=lmY_MR-QmdqfcxtzuQrSvmQ5WgZbuzTV5tBMb0cll8s,1261 +torch/include/ATen/ops/lift_compositeexplicitautograd_dispatch.h,sha256=a_onejlEgkMEhPoN1okFy6-odh39wP-2M-7Zf6BISeE,1169 +torch/include/ATen/ops/lift_fresh.h,sha256=od7cAqJbhdrShvmOPiYF55vFWhcVHKwaVhE5zdvW6ZM,913 +torch/include/ATen/ops/lift_fresh_compositeexplicitautograd_dispatch.h,sha256=4RHH_A_PHR8pUF-FAKeTRhtCgjwGmaD1komeePICyF4,1022 +torch/include/ATen/ops/lift_fresh_copy.h,sha256=I-NX-JmAVvUbTb2nqekp2ePTfmeKXGwuJjaW21i5dks,1371 +torch/include/ATen/ops/lift_fresh_copy_compositeexplicitautograd_dispatch.h,sha256=R9PtKEeb_4YPfSE9_IUpEZvFvcRlI1-oa_HYqtYuBP4,1139 +torch/include/ATen/ops/lift_fresh_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=XUCNNl5fEbVM5JkgHaO3LggULTUeqNMRcjeZnwAndWo,1053 +torch/include/ATen/ops/lift_fresh_copy_native.h,sha256=SeFk8VKnHQy2uYpRoFXHX85skS91wm4EE7973ZFMvEY,826 +torch/include/ATen/ops/lift_fresh_copy_ops.h,sha256=c6owk1ZThAwX817C443bW3K8YrRK4o0VzMoZjWBhO8s,1855 +torch/include/ATen/ops/lift_fresh_native.h,sha256=m2p0jxvIHFSzhQw-kqbqH-efyYMhZyytY-HGmOFnm88,734 +torch/include/ATen/ops/lift_fresh_ops.h,sha256=ATFEMUKzTc267tpBs_MnUtqxoqkXPQu0ryy5FYgE1Do,1229 +torch/include/ATen/ops/lift_native.h,sha256=wn7cGshZrMEBJTDC-KERf9bKp_AUTsmqkQHkZhC7G2I,804 +torch/include/ATen/ops/lift_ops.h,sha256=AikcYovQ71v93GeX4einlF9HYEWw3fI8v6RdeNqSBC4,1789 +torch/include/ATen/ops/linalg__powsum.h,sha256=74f_pFuwe_QXKww_dSHggG7aHm7KlmKJgnqT3dK8Njk,1172 +torch/include/ATen/ops/linalg__powsum_compositeexplicitautograd_dispatch.h,sha256=GKVHdtgZcKhsGGBqKIcWu8hHg3URBlmMoxZXdhnqbpA,1170 +torch/include/ATen/ops/linalg__powsum_cpu_dispatch.h,sha256=QmOSXyNk39nbBmbbVf7rxD9xtNmLXAqTFxXYQf7W0h8,1126 +torch/include/ATen/ops/linalg__powsum_cuda_dispatch.h,sha256=o0QSnlS4y_6J8DYL3v0fYvkRnRApf2Io0Z6PNn_oqyQ,1128 +torch/include/ATen/ops/linalg__powsum_native.h,sha256=7F81_bGfeYKjhxyz69NgWqLrpKm-TsMK4sjm0lvucbI,1093 +torch/include/ATen/ops/linalg__powsum_ops.h,sha256=krWNNuDD1WeiIWh6fvQy3WoC3NV3xH8svmBA6PkBsd0,1610 +torch/include/ATen/ops/linalg_cholesky.h,sha256=x2zwvMMkQ74N2YJrMp1h47S1rFgpD3FB-i8V1jiGd08,1497 +torch/include/ATen/ops/linalg_cholesky_compositeimplicitautograd_dispatch.h,sha256=LMDISHf4MZn8uscele95Z0Xw2sm85S_BYuhSLK_aVyk,1250 +torch/include/ATen/ops/linalg_cholesky_ex.h,sha256=660E56_DFGHmvbzYvBS1r22D2eooSADJnQll-jbqLFY,1915 +torch/include/ATen/ops/linalg_cholesky_ex_compositeexplicitautogradnonfunctional_dispatch.h,sha256=uyD3dRPDXzKPgwLxUVoBNMzbqAaUCluyH_JVxpfqsUk,1124 +torch/include/ATen/ops/linalg_cholesky_ex_cpu_dispatch.h,sha256=WyrhGxEdJ8Vs5vNaTroswiem7anacRyqFsT15qyVWmA,1397 +torch/include/ATen/ops/linalg_cholesky_ex_cuda_dispatch.h,sha256=uv_dPKUBOhXV9ipX5-AoCKLSovHNB9_GMpEPgbT00ME,1399 +torch/include/ATen/ops/linalg_cholesky_ex_meta.h,sha256=aogo9AD55KY1d0nzb-wXYO3ZULg9bqzSfA09H66jyZ4,864 +torch/include/ATen/ops/linalg_cholesky_ex_meta_dispatch.h,sha256=A-SeRYJ8OKryvZi4D_dW0cfm2IEhk8tKT-VXxIAWT-g,1399 +torch/include/ATen/ops/linalg_cholesky_ex_native.h,sha256=kbVierApm4ykLBN-1dq7VBlUtCVouKJ_lU9vNVP6dUQ,940 +torch/include/ATen/ops/linalg_cholesky_ex_ops.h,sha256=UWg7OO9Qq-6ip_aVHBvF5QM73HhSTsELWHriDxmsA7g,2361 +torch/include/ATen/ops/linalg_cholesky_native.h,sha256=Rjz1xOS_dGlqRGaxttRBlvJq_yUjJQDiryhfV3PUoE8,856 +torch/include/ATen/ops/linalg_cholesky_ops.h,sha256=0ibWvh2RPlVi7RyMRJ13mtcU5M-2MSLSPZzZt_WalgI,1954 +torch/include/ATen/ops/linalg_cond.h,sha256=zGdqpDlj8BNXjHwXiK8gF-Mz3EQuweJA8eMuri0tb88,2231 +torch/include/ATen/ops/linalg_cond_compositeimplicitautograd_dispatch.h,sha256=3_GyYscnwGetxAr6-T5NBnbCh9fnJSArX-W9eGZ8bPI,1623 +torch/include/ATen/ops/linalg_cond_native.h,sha256=ewDMhWJUUb5uO21sFw7ZsvtFEig_Sfq6ma6EcO4yEyw,1093 +torch/include/ATen/ops/linalg_cond_ops.h,sha256=k02o--ursXip0jZj-5kOICrFXsImL7l5xntF4xadGwk,3378 +torch/include/ATen/ops/linalg_cross.h,sha256=BbmgQx0LzzSvYANpDkbFadBZY-9Ox7JR5gRs9Oa9XWA,1581 +torch/include/ATen/ops/linalg_cross_compositeexplicitautogradnonfunctional_dispatch.h,sha256=xt98a9At8gD2JkkQJfpcJlYd21mw8eJ3v7g-j7-CMcY,1092 +torch/include/ATen/ops/linalg_cross_cpu_dispatch.h,sha256=-8dgrBXaUh5aDEnNRF_oBYxloIaSNng7R-bjoOGvA4I,1272 +torch/include/ATen/ops/linalg_cross_cuda_dispatch.h,sha256=rkY-sP_r8FWL0gvrY2q-4KeMxLE-oOW2QIgsHQOH4m4,1274 +torch/include/ATen/ops/linalg_cross_meta.h,sha256=R-Ld2d4O9bSk9_RXniR1VvyOKgsTzCt9WCb0JFzBpK8,866 +torch/include/ATen/ops/linalg_cross_meta_dispatch.h,sha256=0Zo0GtBYRYqL3oYCSYgpQI0pd_AbWSMy78sp0frtWPo,1274 +torch/include/ATen/ops/linalg_cross_native.h,sha256=lr9JliLKilkv8uRHTBTAmwt0-CzDderS5ug4eagC6VM,1020 +torch/include/ATen/ops/linalg_cross_ops.h,sha256=Et4fJoTSuBZDXS5H9zsJVtcUMwo4WnOf4LbQ4Vtukko,2106 +torch/include/ATen/ops/linalg_det.h,sha256=qOK9s0G_CQoyJUZ85TnBLysPVUqyzkDD6iUpdCT-fnQ,1294 +torch/include/ATen/ops/linalg_det_compositeimplicitautograd_dispatch.h,sha256=mE314h14Oj4dg4T6k69saIUyfvGCLom4VgpaVQB8vg4,1178 +torch/include/ATen/ops/linalg_det_native.h,sha256=nTJzSpZexmzHdPdMsj-xl9sGon6bBRPGxB2z7LdH9_g,810 +torch/include/ATen/ops/linalg_det_ops.h,sha256=KBEZsoISoHT5ybUkzaT9fDt47yRYOcG-C1OYEDxkzAU,1807 +torch/include/ATen/ops/linalg_diagonal.h,sha256=wKXG2ajQJG6SmQPZUHng63UFEMU61zGiS302fdzQMZo,1039 +torch/include/ATen/ops/linalg_diagonal_compositeimplicitautograd_dispatch.h,sha256=eCSgUovp3SN85fxFJaq7mYRbRouM8YHfgH4OcfHluJY,1076 +torch/include/ATen/ops/linalg_diagonal_native.h,sha256=pWV1suH6pSeTEXv4BfBsIxzBzU5wwkSi4-Wr_O0odeE,788 +torch/include/ATen/ops/linalg_diagonal_ops.h,sha256=Ry15c7gyN9b1EPM-0yZngaixLvHL0o38xGqeGIKtNhc,1393 +torch/include/ATen/ops/linalg_eig.h,sha256=jaBjrOkEfvjMLvDormk8NGAm41nRAEiw9pKj8QzgReI,1693 +torch/include/ATen/ops/linalg_eig_cpu_dispatch.h,sha256=VG0p-dx3oQOitdXiZrd9ZDxroLod4dnnAGiTd2kZiA4,1292 +torch/include/ATen/ops/linalg_eig_cuda_dispatch.h,sha256=h8vsyYjznpcFbLXB6-O3b0WeJY_QdwR-ooc1SzNhnuQ,1294 +torch/include/ATen/ops/linalg_eig_native.h,sha256=nIo1ReBx0tMiMjzlKRnbDAdLxR64OtTYRepdqvEE8lU,903 +torch/include/ATen/ops/linalg_eig_ops.h,sha256=v6tM3JQcGHsxpzJaO-M0GXoX1Xm1pqrP4HA_gYB_6sU,2172 +torch/include/ATen/ops/linalg_eigh.h,sha256=NBxfedX7HJWbeWdBU5DqSE_euNcqxhriE0nQVOLihgA,1802 +torch/include/ATen/ops/linalg_eigh_compositeimplicitautograd_dispatch.h,sha256=QWKJfNgbZHJYtOhbwjjtN6FRExRCq8cp6YGtSO5Fhaw,1398 +torch/include/ATen/ops/linalg_eigh_native.h,sha256=ZxqLYU12YUJYizF1NrxBHT5QOKRtM7KsWlSDEXpnzck,946 +torch/include/ATen/ops/linalg_eigh_ops.h,sha256=CcP4ynUIivnPkxmiig4lZjwErfuPtvSLwZ2oq1A3ljw,2323 +torch/include/ATen/ops/linalg_eigvals.h,sha256=1IkJDMb9dHcHy0-IOoV77TMKS1NfXt6ZFpwbjQOlFrw,1361 +torch/include/ATen/ops/linalg_eigvals_compositeimplicitautograd_dispatch.h,sha256=XoYonDKjvxPUHb2TuW4nsgIuegIRKCEpPA-YwyII4Hs,1026 +torch/include/ATen/ops/linalg_eigvals_cpu_dispatch.h,sha256=mTtZO6JlXXDPwIXaOzWbiyv3qHvprrsojF_ZJyunWbE,1093 +torch/include/ATen/ops/linalg_eigvals_cuda_dispatch.h,sha256=ekzpzUEHwrzThPMKZ0AB2_gwHROim6xvHyl7XcbyzGs,1095 +torch/include/ATen/ops/linalg_eigvals_native.h,sha256=ohHvZ06lKIpLcX1YLmDwys88UJjz9K3DwEEEspKTdcM,824 +torch/include/ATen/ops/linalg_eigvals_ops.h,sha256=yAHMkUQRb85BUYmrv_RaA_dMzC3yVATfXPYTlIB0Rp4,1849 +torch/include/ATen/ops/linalg_eigvalsh.h,sha256=jqVwJXVQAcWVR7cORErnsVI9iiPuFf8NynZSeRDx12s,1508 +torch/include/ATen/ops/linalg_eigvalsh_compositeimplicitautograd_dispatch.h,sha256=7f4qG5c3NfkbJNrtooeqjdjAWrr-EnKIlfx011Wzh_o,1279 +torch/include/ATen/ops/linalg_eigvalsh_native.h,sha256=NJusBBvCGAU_PZwH3Z_wVCkdq6a7TgYsos_WaUP_JVg,876 +torch/include/ATen/ops/linalg_eigvalsh_ops.h,sha256=K7YFYF0Qr1YsFWgCLqgLN8pP_1yAct6YKczovCSOh-g,2015 +torch/include/ATen/ops/linalg_householder_product.h,sha256=_YQRA0JQcCGhB4jQ0UnPtE-m_YZwGLudZUEwlyvADCQ,1613 +torch/include/ATen/ops/linalg_householder_product_cpu_dispatch.h,sha256=Y3TJaqf0h8Q6B7YnOPcn8CzyrOfQd49QV57eLjzRSzg,1266 +torch/include/ATen/ops/linalg_householder_product_cuda_dispatch.h,sha256=tyoiewXg9sp2qOjMQXOa4vqGfd7XGMPe6_LBnapuotM,1268 +torch/include/ATen/ops/linalg_householder_product_native.h,sha256=9bAjC4_sOxUF-eT91KfJtkgaTZ0L6MuL4kVxVdohJYI,898 +torch/include/ATen/ops/linalg_householder_product_ops.h,sha256=wMCzogDmFH9kjJvt5vzo4A6W8Q-Yem7gyBeaC7BtAPA,2087 +torch/include/ATen/ops/linalg_inv.h,sha256=9PUeK0zgGfDG9f-nKo8A2Wxphg7xjtVZTVkGGCkGVTM,1294 +torch/include/ATen/ops/linalg_inv_compositeimplicitautograd_dispatch.h,sha256=LstNcxPDx2Z6cuQLXVWCX7W1BG17VrxazcCsWQx0s8k,1178 +torch/include/ATen/ops/linalg_inv_ex.h,sha256=Xfue3sdq82mJTE5R6lzb18WVT0FOU4cKxu6fvFz1I5w,1793 +torch/include/ATen/ops/linalg_inv_ex_compositeexplicitautogradnonfunctional_dispatch.h,sha256=yjymCW-QdMSxSBOk4AepXkSHoIgyfOQnlll-Q-17H1s,1098 +torch/include/ATen/ops/linalg_inv_ex_cpu_dispatch.h,sha256=dXmY7mwsvfWMAe-mFvA91ufplaCuIbQe9YRfAC3_4EA,1337 +torch/include/ATen/ops/linalg_inv_ex_cuda_dispatch.h,sha256=KeeSs7xa2AGbpDZKcrTU3KCmOhIEee78eBed3SyHeQw,1339 +torch/include/ATen/ops/linalg_inv_ex_meta.h,sha256=w8BfQSfy0hDvQ8QcGdvig64mxn9rpjHxP2BR4uHpsOg,844 +torch/include/ATen/ops/linalg_inv_ex_meta_dispatch.h,sha256=abX504tv_-z3s6cYtZLqSgfFHXY8ok3sYOPEApiREkU,1339 +torch/include/ATen/ops/linalg_inv_ex_native.h,sha256=gFVCRLMrsllOp6vnA6nwhDiwnEh7Yn85fkV7oUBymmM,916 +torch/include/ATen/ops/linalg_inv_ex_ops.h,sha256=vbG2bmvSK7Zfw_RgNo4YbvpDMhQ93gfIBJDqv288vJg,2265 +torch/include/ATen/ops/linalg_inv_native.h,sha256=nrfTfn7Q1zFyHo50pg-kicygmC47FsOFpKPuZpZsKDY,810 +torch/include/ATen/ops/linalg_inv_ops.h,sha256=RVm98LlBc0ItgQ_JHveKBPwX7jm7vvoYyazpx4R6Qfw,1807 +torch/include/ATen/ops/linalg_ldl_factor.h,sha256=EzrfKYeOzJzeBfcG8tStlV3eUSEalOJSVf6iwon6Mx4,1790 +torch/include/ATen/ops/linalg_ldl_factor_compositeimplicitautograd_dispatch.h,sha256=dnUji-9watS2s40fCSf7uyxzF9Qj-CbF_erWzwQVAtE,1387 +torch/include/ATen/ops/linalg_ldl_factor_ex.h,sha256=E0JQO1G42QfQF4MXdKQx3YffYZLZWEDBQLPR8Kj3FZ4,2174 +torch/include/ATen/ops/linalg_ldl_factor_ex_compositeexplicitautogradnonfunctional_dispatch.h,sha256=AwCTPCD-AVZIpxQGkMHVpi04jK9-nCukuW-sW25KPmI,1141 +torch/include/ATen/ops/linalg_ldl_factor_ex_cpu_dispatch.h,sha256=8W8js6HFdHKPPXA5xbHSUzu-XBKwgg7XDzQ9UmtHrAk,1496 +torch/include/ATen/ops/linalg_ldl_factor_ex_cuda_dispatch.h,sha256=c3Zus3yVBoVz_RJRtFJoA_aKVzzDOJUyVBhCkuJtDw0,1498 +torch/include/ATen/ops/linalg_ldl_factor_ex_meta.h,sha256=qWKY_-QeCakfQsSnb0I-YuuNb-3JVhp2v63NyLvCvt4,870 +torch/include/ATen/ops/linalg_ldl_factor_ex_meta_dispatch.h,sha256=mpjY4aZQ8EjBPYavL05r1AzaNR-DXvOMy5DtvU4IL5w,1498 +torch/include/ATen/ops/linalg_ldl_factor_ex_native.h,sha256=gOwCZMo-OJfs7dgYSsYs41O6yv_oJ2hfc-8xd5cSAlg,978 +torch/include/ATen/ops/linalg_ldl_factor_ex_ops.h,sha256=CPzuGRUzKFjz92TO-sqjwC4LMDsWu3IKZnuRRaweD28,2589 +torch/include/ATen/ops/linalg_ldl_factor_native.h,sha256=_CV7CynjnQ7rCiFo0i0roM4-wNeHY_QlXJfaPud9UMU,940 +torch/include/ATen/ops/linalg_ldl_factor_ops.h,sha256=i5piUdrVQTCQbSS_w6qkOXPubV8mqbq4oeGp4CpjBTk,2262 +torch/include/ATen/ops/linalg_ldl_solve.h,sha256=Z7_SISkO0sw0G2SY5XEvmIAydaNKz8f2iaFMjKt1Fu4,1780 +torch/include/ATen/ops/linalg_ldl_solve_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Zo0HfLwVZCAx-86f1jMQuIYLmeA1TaRza0s-gFNpq98,1123 +torch/include/ATen/ops/linalg_ldl_solve_cpu_dispatch.h,sha256=eKVhnapxsYIIjvQbB2CAGhmR5K98PihMWocLg0Wd6wA,1362 +torch/include/ATen/ops/linalg_ldl_solve_cuda_dispatch.h,sha256=TZij5CTle16QLNRcLFNX_MjLrpqsR-OONf6jQ3qKMqU,1364 +torch/include/ATen/ops/linalg_ldl_solve_meta.h,sha256=vHrPcz1qtglcguq-c7pCMLX0ZnyxUnvosqWaOblpig4,894 +torch/include/ATen/ops/linalg_ldl_solve_meta_dispatch.h,sha256=jmJ7AooOk3MTO3cJJsbol5pYU3zvgr6RX4RzTyQGOVo,1364 +torch/include/ATen/ops/linalg_ldl_solve_native.h,sha256=fzR_UhEPiVaarKrxYscyJxWGRA32M8lPXZuO76tjNNc,943 +torch/include/ATen/ops/linalg_ldl_solve_ops.h,sha256=TYInDRUnvnZIC5IXefj0rx6jttCNMZ09B2je9ccTzHw,2298 +torch/include/ATen/ops/linalg_lstsq.h,sha256=eY4mZrc_PyJwdFT-D1T5n-zQiDGx9xmMs3oxBcwpP-o,2637 +torch/include/ATen/ops/linalg_lstsq_compositeexplicitautograd_dispatch.h,sha256=B491D3aN6MFFogIspibuGTQbqzr0OGWLH8is4ORUBSQ,1196 +torch/include/ATen/ops/linalg_lstsq_cpu_dispatch.h,sha256=ZCslv7V9EZ30Db7c9eWqSFCNBE4c_PFnpPtovqmqxdY,1571 +torch/include/ATen/ops/linalg_lstsq_cuda_dispatch.h,sha256=_sCwbXjfWwI_FYckj8xaKPzT1YRGlljEKeWZhQE7_0k,1573 +torch/include/ATen/ops/linalg_lstsq_native.h,sha256=vx2Zvdp1evPIfD1rNpFT8cI7wa254916IUURVknu4ZY,1218 +torch/include/ATen/ops/linalg_lstsq_ops.h,sha256=UWW9eLKVG2mzUWy4QmV6526ADkBYtrv6u7S7tv--vxE,3188 +torch/include/ATen/ops/linalg_lu.h,sha256=Ox2sr3s_BwLU6L1PWsNs5PHn-wscZhT6ONynY9SVtdQ,1729 +torch/include/ATen/ops/linalg_lu_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Tq4lVIBJLeV7q6mjQIc46s30oXlxKZCBj0s7h1M3U-s,1097 +torch/include/ATen/ops/linalg_lu_cpu_dispatch.h,sha256=ayco25_68R37zckSxHNJ-CsRQZBjyL5N-4-KSe2XkPw,1353 +torch/include/ATen/ops/linalg_lu_cuda_dispatch.h,sha256=WZG78J8v6u_Aaq1_Mzjo_dHYLTsRy0S_wmNcm2l2bNI,1355 +torch/include/ATen/ops/linalg_lu_factor.h,sha256=7ZD9WZHPN9ZXS9Sr_kBWGcgAmKv0hLAkbQwkukHaIuk,1712 +torch/include/ATen/ops/linalg_lu_factor_compositeimplicitautograd_dispatch.h,sha256=KFVa1qke9OCtvMJaKyopeUsw6K0q0_6lmDyiw5mrN9M,1361 +torch/include/ATen/ops/linalg_lu_factor_ex.h,sha256=y51x13dmX2afQoWE5qZ9A-YEg2C0bhXxvs30FsKVyO8,2096 +torch/include/ATen/ops/linalg_lu_factor_ex_compositeexplicitautogradnonfunctional_dispatch.h,sha256=QL4qz14k-9TP090aKKj1mufOdhmwKqbtlZnZGax_RG0,1132 +torch/include/ATen/ops/linalg_lu_factor_ex_cpu_dispatch.h,sha256=9j7hoizb5y3qZceZEa_waJs54gHx1C7xyHzJ4wBKr1Y,1470 +torch/include/ATen/ops/linalg_lu_factor_ex_cuda_dispatch.h,sha256=fIPD1N0nRKmOHIEZd-tRn6muw6e2jhv5PcD2kOc1aOQ,1472 +torch/include/ATen/ops/linalg_lu_factor_ex_meta.h,sha256=2SSMymduI4Pbj-1aB6xaOfNDZCpco10dYV-PBi6-ZJc,862 +torch/include/ATen/ops/linalg_lu_factor_ex_meta_dispatch.h,sha256=0_GZk_Y9IZHemr3xihAyX1yTC_vjj3SxeXB-4KgN3Z0,1472 +torch/include/ATen/ops/linalg_lu_factor_ex_native.h,sha256=_ArtkrzB2B8YYm_XwWvGqbHjLrraNu1-i__51HtPfIw,968 +torch/include/ATen/ops/linalg_lu_factor_ex_ops.h,sha256=2JxIPt4ZoAxtjOo4EjcpzVpSrIPqDIpoeqjjHVrPKew,2539 +torch/include/ATen/ops/linalg_lu_factor_native.h,sha256=XiDD3sEhizMJR9uKhni6Kvx1u6dypaypS-L9lRct5oo,923 +torch/include/ATen/ops/linalg_lu_factor_ops.h,sha256=5Lm4G-J8d6IEdm8xtu-bCIJE4Yuqt--8kboJBlZpbqs,2212 +torch/include/ATen/ops/linalg_lu_meta.h,sha256=zQJlysRbWPPFF__tlnFnl9kkmW5WBGv2SbyRBFklzhM,833 +torch/include/ATen/ops/linalg_lu_meta_dispatch.h,sha256=teAv6JQ3QiWoUY6rzWKwAXXs5HwzLFl_J1Z2y_lHrPo,1355 +torch/include/ATen/ops/linalg_lu_native.h,sha256=1l3QXIiwLNyRVduX7_ujPAkp-hnGMk7yXZab8RQBdh0,910 +torch/include/ATen/ops/linalg_lu_ops.h,sha256=46LiBQx1CmdoKV-ll82UMuiuzHWaH-lfgDwzCbxsBO4,2296 +torch/include/ATen/ops/linalg_lu_solve.h,sha256=s1_0al2-sDQ7ZmDj6vPk2MIF-J1iLu7OCbwTpSlfYII,1861 +torch/include/ATen/ops/linalg_lu_solve_compositeexplicitautogradnonfunctional_dispatch.h,sha256=v7y6QWty3XAkrZMN_nepVlDnGKntB2kKehqeGcgwBCU,1136 +torch/include/ATen/ops/linalg_lu_solve_cpu_dispatch.h,sha256=FtLX1ZAmhK_4pz1mnYdSyvhA_Gr43G8INhn4XcxDRqE,1396 +torch/include/ATen/ops/linalg_lu_solve_cuda_dispatch.h,sha256=kvAOyYE9MZqy1E347QKHBVyfJyoipJbdgc_nbF6PcJA,1398 +torch/include/ATen/ops/linalg_lu_solve_meta.h,sha256=JS3ZLUUNAIMFeP_T6AU4hzqwj0WyKlbiEjUpRQlnWcI,902 +torch/include/ATen/ops/linalg_lu_solve_meta_dispatch.h,sha256=MOpZJy2-nh3WaFLsh2QxoIdA2nKAtF8DdX-IIialTt8,1398 +torch/include/ATen/ops/linalg_lu_solve_native.h,sha256=_umB08vNaOgmvAyfCOYp1KSQK78NRWa8QEIlTS70gc0,949 +torch/include/ATen/ops/linalg_lu_solve_ops.h,sha256=89z2Ns2hVyUQzBV6QQUoxMDAG_rOPDh5ARH0sa18EKQ,2368 +torch/include/ATen/ops/linalg_matmul.h,sha256=eOYG8-QlmbI_uaE6SGqhenBLKDmX9Q9f4Ce0vAXlJio,1492 +torch/include/ATen/ops/linalg_matmul_compositeimplicitautograd_dispatch.h,sha256=kzYfzY65To2KgFilD5_gD4nVdvU81WfQhCSki-Yfltg,1274 +torch/include/ATen/ops/linalg_matmul_native.h,sha256=UXufPQrmjThziUKEtvx9lXNG2I0r4gp1ZxrQ4VXTQdU,874 +torch/include/ATen/ops/linalg_matmul_ops.h,sha256=XPY_relY5iZw7nDkuYZFqOv9IxZvLSR7ZiPORaE-5g4,2015 +torch/include/ATen/ops/linalg_matrix_exp.h,sha256=xXa4s2RxaJLxYJGa8TQvp11CeH6ThBjqTRuw0GIs2Io,1391 +torch/include/ATen/ops/linalg_matrix_exp_compositeexplicitautograd_dispatch.h,sha256=QRezsk1kM8wswEnsxWzcgqwMWBlggLtu1QIQJpjWcsQ,1143 +torch/include/ATen/ops/linalg_matrix_exp_cpu_dispatch.h,sha256=jetPXq9tvVH4WTrepAt9jvzeXvcrS-_LlnXb5wpzarU,985 +torch/include/ATen/ops/linalg_matrix_exp_cuda_dispatch.h,sha256=1hf255FmbFLjMl2JSZUmaQKAZwbNw2n5jXUQb6XFNLA,987 +torch/include/ATen/ops/linalg_matrix_exp_native.h,sha256=a-RGdUhRZXmEJ7i-mtZTo03NqRs3v2SbUNb9rWQVmwo,830 +torch/include/ATen/ops/linalg_matrix_exp_ops.h,sha256=CuzE6x655TUQHb6rHK23MWx6A3VNkol9aFYGH5D1NJY,1867 +torch/include/ATen/ops/linalg_matrix_norm.h,sha256=ICvhd6q6AJ4apbyzUoWgO-b3tnATPu29nhDJY3pa6b4,3413 +torch/include/ATen/ops/linalg_matrix_norm_compositeimplicitautograd_dispatch.h,sha256=z5DGd6RezpXzK8uo3SKIQO_tVWWm2FZQH2q_PLN4fpI,2168 +torch/include/ATen/ops/linalg_matrix_norm_native.h,sha256=v_V6AOtwH3Jdb7Ixxb_t2forVGbC1mE4Oa_RgsEGfBc,1440 +torch/include/ATen/ops/linalg_matrix_norm_ops.h,sha256=ehm8hiuWzIMJpllNWmyVvaayp-QVDVSLISiO0jmxrNY,4470 +torch/include/ATen/ops/linalg_matrix_power.h,sha256=UE6UvgBroiH8qT0BoSMJmCDqItymllHQ2KqxyqJzWnE,1474 +torch/include/ATen/ops/linalg_matrix_power_compositeimplicitautograd_dispatch.h,sha256=A5Zs98TOmZh2msBLhlxsm09U9J5-olKVyva7oJ8e5sc,1247 +torch/include/ATen/ops/linalg_matrix_power_native.h,sha256=VwZlIwFeyqH2ROab7KuAJC4hLF7q0sNZi81e7ZPvEZw,856 +torch/include/ATen/ops/linalg_matrix_power_ops.h,sha256=S9FYF2bcdHikNOcmF7anNWasIK-crgp8vqdL3th1HZI,1955 +torch/include/ATen/ops/linalg_matrix_rank.h,sha256=fHKhs-LorBMnPveQCT74RrDW9LIw3BAp_GoFtuBxD5w,5169 +torch/include/ATen/ops/linalg_matrix_rank_compositeimplicitautograd_dispatch.h,sha256=J3S1rCeAGL0kmob6mbyddfhueroVLgDSzm3kIZBWVqA,2750 +torch/include/ATen/ops/linalg_matrix_rank_native.h,sha256=Voe1sNBuYYihdIL8YIrtiSW0abvKhTaUttX0U93MFAA,1852 +torch/include/ATen/ops/linalg_matrix_rank_ops.h,sha256=VXWDoNbJATQx8h3Ip697D-CA59pgZRcbCEbi-RBPKyA,7336 +torch/include/ATen/ops/linalg_matrix_sqrth.h,sha256=S2n-5N_oDCjPU3_Fkbr1aDUGFQZ5Q0LEJeY6ANccnwI,1411 +torch/include/ATen/ops/linalg_matrix_sqrth_compositeexplicitautograd_dispatch.h,sha256=y5dfuY4sCDpbERGzJhmXfR7m5KT4CxFpkiQqEnNTMzk,1147 +torch/include/ATen/ops/linalg_matrix_sqrth_cpu_dispatch.h,sha256=luvqvG_-jI_GG9PD7-ekidXPsA2Ex2NqSSapfTUWxMY,987 +torch/include/ATen/ops/linalg_matrix_sqrth_cuda_dispatch.h,sha256=9VPS7NEODYaqjXhIGma9bI8yCPQ5ggzs0LCCqOuJIGU,989 +torch/include/ATen/ops/linalg_matrix_sqrth_native.h,sha256=GEHQKR_q6VyNF-9VExMb75KcZe44jFZVf3cDkaip2vU,834 +torch/include/ATen/ops/linalg_matrix_sqrth_ops.h,sha256=ubsAriaDauPadJ3TAua4NXpGp6Ype_dXnkFQIoYDPHc,1879 +torch/include/ATen/ops/linalg_multi_dot.h,sha256=p5BCH44cK8ELNiec5_5yxqS1DkUw5vxGLKXQNf-xAHw,1402 +torch/include/ATen/ops/linalg_multi_dot_compositeimplicitautograd_dispatch.h,sha256=qiA2kx_ccqIyVnS2VCYLJWQ8NBa3InKYrYtyKfNm81Q,1202 +torch/include/ATen/ops/linalg_multi_dot_native.h,sha256=xDnloi3IcF_ut5X5tEOrcrNTWlB3Ld156rNMmLHbBug,826 +torch/include/ATen/ops/linalg_multi_dot_ops.h,sha256=YEwkVAY3pGETxszliueBS1DnRxxDVpIpgaeDwiFy1Jo,1859 +torch/include/ATen/ops/linalg_norm.h,sha256=INu8d_T6WFiAqx0Nu8XFZwXY6QWQ7RRMlO63-4xsqBY,3419 +torch/include/ATen/ops/linalg_norm_compositeimplicitautograd_dispatch.h,sha256=djX0meLaJeEgX3Vc9mU-PjnPJV4J2GmyCbkZtdYKPqc,2271 +torch/include/ATen/ops/linalg_norm_native.h,sha256=Qxg47-0c6o-0Enorar2HNnuswbW0BH46SDO_5Aeh8Pc,1501 +torch/include/ATen/ops/linalg_norm_ops.h,sha256=qfBoUdh0FCphEq4LQbyiS7ZJjKt39PG7buyLrWqw4xM,4580 +torch/include/ATen/ops/linalg_pinv.h,sha256=gBjCw4aUu-O9BMHvAsFmu3G2wVueKVGcZGJ0T-lXZpo,4940 +torch/include/ATen/ops/linalg_pinv_compositeexplicitautograd_dispatch.h,sha256=j83aplXZMtVlMrMVMSXHyFWv3IqF_qlHgnQPJloYlc8,1343 +torch/include/ATen/ops/linalg_pinv_compositeexplicitautogradnonfunctional_dispatch.h,sha256=hImXM_P3Dd7r3HXHUm8Wzqh-l4SEId7batxFDv85SJQ,1161 +torch/include/ATen/ops/linalg_pinv_compositeimplicitautograd_dispatch.h,sha256=1Xm7rzihAQJVokNf7pX4XD42YQQYNLuU30su1cFTTVE,2122 +torch/include/ATen/ops/linalg_pinv_native.h,sha256=mOZUTRApqEuHS1QeZf2NoPCf2E3a2foZcbQvjmhoLU0,1800 +torch/include/ATen/ops/linalg_pinv_ops.h,sha256=jEwnEHDNalnZJzQl1VIMKS6wQkzSPXI2vaD3lCi4nr0,7192 +torch/include/ATen/ops/linalg_polar.h,sha256=r8m-szq39xi67Cmdu9q9rb6njc_uY99aVutJwXzzQt0,1497 +torch/include/ATen/ops/linalg_polar_compositeexplicitautogradnonfunctional_dispatch.h,sha256=DwKfGvjBZ4YTLtOEq1QE9dtk-gOeaFRquO8CFZLNKuo,1072 +torch/include/ATen/ops/linalg_polar_cpu_dispatch.h,sha256=pmRCvvHBJub_5ovEoh1COGo-1EijxaOTbBR1tRLAMgQ,1247 +torch/include/ATen/ops/linalg_polar_cuda_dispatch.h,sha256=QY2s2tFcKyO8jJ-tZM6c6o0ooZWQKAdMGGLtI1FKYTc,1249 +torch/include/ATen/ops/linalg_polar_meta.h,sha256=_jq6k_2136VuXGzPsMeHg5F2nSNWXozQH4oEVh6fi0U,824 +torch/include/ATen/ops/linalg_polar_meta_dispatch.h,sha256=Va0C_XQ6vKfkxeiuDqXR3pG42Ks8rStoI3sFTR-4_DM,1249 +torch/include/ATen/ops/linalg_polar_native.h,sha256=mzs43wbvNOy0_bsQqTAEdGzpwyLJ4QxmklXHlkfN3Z0,885 +torch/include/ATen/ops/linalg_polar_ops.h,sha256=vKh2BjCY2BluoOmugTYibc_8JIkrEL4oEGCkSyuZRFY,2061 +torch/include/ATen/ops/linalg_qr.h,sha256=IH9kK8F0E7p09s28JPf03SgiRDTIoEXI9C4OQAdUxgQ,1634 +torch/include/ATen/ops/linalg_qr_compositeexplicitautogradnonfunctional_dispatch.h,sha256=-pHxs2ZtnyA-9Sj8Bii637c2_XRszVIPdiUYFKyEgdU,1102 +torch/include/ATen/ops/linalg_qr_cpu_dispatch.h,sha256=pmMyWWRMpFqDaE9ICBB5ztmS81oG9-FGdLiDZSqPTaI,1327 +torch/include/ATen/ops/linalg_qr_cuda_dispatch.h,sha256=oQs7_EPm2OhmCsaAqTxxmpxoH_LzHazTyT7kia_UD9Q,1329 +torch/include/ATen/ops/linalg_qr_meta.h,sha256=nHSyUEM8110G2goBuN-iZ6r8UiNR-wBEOUiedr14wnA,844 +torch/include/ATen/ops/linalg_qr_meta_dispatch.h,sha256=Gus9Cts7sDp73V7FeL0cZhkEqKkm-jTHMz-d4Do8z9E,1329 +torch/include/ATen/ops/linalg_qr_native.h,sha256=ry61jq-f_KBYg9gltrJLkSNdizqONALvxM7P4VLUZ1k,899 +torch/include/ATen/ops/linalg_qr_ops.h,sha256=wzy9NVttrcs_wNKitpQsAY5_C8Ab4mNJGFwLVSigTBA,2211 +torch/include/ATen/ops/linalg_slogdet.h,sha256=XO4kgsyj0-0HJkJN-0KSkAbQ9cxppi_d5KjBHHsfKw0,1616 +torch/include/ATen/ops/linalg_slogdet_compositeimplicitautograd_dispatch.h,sha256=NN65qjD1tDmbQI3mJvGs0hOBlMFuxLl8OHY5Eeft5d4,1319 +torch/include/ATen/ops/linalg_slogdet_native.h,sha256=M4vdriYbYCcjojReIOkvH5P8k0cvGS2a2OZ30F2yxJY,895 +torch/include/ATen/ops/linalg_slogdet_ops.h,sha256=5fDrKWdRfRMY18TpJel4sEFNR24rSNdQy9YspdwIZrI,2128 +torch/include/ATen/ops/linalg_solve.h,sha256=sUOUj_9oPI-PY58G75x8GWOjASVUwip5oxwrdHqWU_8,1531 +torch/include/ATen/ops/linalg_solve_compositeimplicitautograd_dispatch.h,sha256=3LU0jn8OooVJ3uKXSczqG7PJ1s-hQya-WHAQwXlAkk0,1293 +torch/include/ATen/ops/linalg_solve_ex.h,sha256=gUkvsKLqO1EO1XgmhrCAMju7NT4cbE4AUTp5vCwYUoM,2002 +torch/include/ATen/ops/linalg_solve_ex_compositeimplicitautograd_dispatch.h,sha256=bcGxED3HeyJNQ2J8epnmsk1c8vPSemCoGAdzyVGH1WE,1494 +torch/include/ATen/ops/linalg_solve_ex_native.h,sha256=YPRTBgzu-9ZQEccObZfzrJuoO-9mT3vKJdT9DcPGJsU,1009 +torch/include/ATen/ops/linalg_solve_ex_ops.h,sha256=DXTGw_jrSiGm-lrKaIul9sJuvAMnraIXabxe0vFo1yM,2496 +torch/include/ATen/ops/linalg_solve_native.h,sha256=HUJfU8CstRWvhKu2zQJ5R4C84xnO9rWfSUHM4vswnHs,885 +torch/include/ATen/ops/linalg_solve_ops.h,sha256=5FADMlo6TYZT9dGO_4805y8vgzJ9-1Mm440Af5wmtFo,2058 +torch/include/ATen/ops/linalg_solve_triangular.h,sha256=JzFF64F-6VrHIepTJlZTHY4GrrWnz2kQX66wtEeu09c,1956 +torch/include/ATen/ops/linalg_solve_triangular_cpu_dispatch.h,sha256=JEBt6K0WNu4YW4h0yQIsaLDYIr94ekZ3fKTSzZMk2Hg,1399 +torch/include/ATen/ops/linalg_solve_triangular_cuda_dispatch.h,sha256=aAktMfLDxFse-f2aWYHGtxqASEItPGtPU9TuPyoT7UM,1401 +torch/include/ATen/ops/linalg_solve_triangular_native.h,sha256=c3bWQyFFyAFcRjL0bAHoe7jyPLe32k16T_sv4nndMYQ,983 +torch/include/ATen/ops/linalg_solve_triangular_ops.h,sha256=ZAlFA_ivtqSIeDk2RgcPkJE4-fB8kOxhq7MeirZqWUc,2370 +torch/include/ATen/ops/linalg_svd.h,sha256=CidG3-IJrXcLQPgi2-t_YaZ8qQJJ65FROJz5ud3y9HI,2046 +torch/include/ATen/ops/linalg_svd_compositeimplicitautograd_dispatch.h,sha256=_EDo0ux1ze03tcyrc2K8fEbYYvZKmmAv6m2u25M46ms,1582 +torch/include/ATen/ops/linalg_svd_native.h,sha256=mOMa98wfy9Xq4s44Ao-FG_C9htaEjAPMoDd7D5Rgrxk,1061 +torch/include/ATen/ops/linalg_svd_ops.h,sha256=Uv2nw3Rspc3oqMZfM8_FEvwY7PtF6lpTdIxkojuJ8gc,2623 +torch/include/ATen/ops/linalg_svdvals.h,sha256=S0AFo3h6AhdEXCeHdhZ42FxugMY6KBl7jtGn8pZdhfw,1571 +torch/include/ATen/ops/linalg_svdvals_compositeimplicitautograd_dispatch.h,sha256=Mgux0yIJjerTMtzcJ814vyvxymvyeITJ6KTB4u39wVY,1346 +torch/include/ATen/ops/linalg_svdvals_native.h,sha256=AKYe99jOnVZeCZc333JZrT48FFy96wpA569Y_OugxbE,917 +torch/include/ATen/ops/linalg_svdvals_ops.h,sha256=jQlGE87mPqGk-_jVOCaHIbCm58cA46MAKuKJFSzklgk,2108 +torch/include/ATen/ops/linalg_tensorinv.h,sha256=PThoNEJjzHGnjw5I6C-XccrgpMFEELXXGPbwDOCPH20,1472 +torch/include/ATen/ops/linalg_tensorinv_compositeimplicitautograd_dispatch.h,sha256=QhWibJvDLyBfd4qA28NKk5umE-iR792cKFEFtLbrn6E,1248 +torch/include/ATen/ops/linalg_tensorinv_native.h,sha256=oeZOezZ1d9X5m_KlusAuhilxXR0QyljgT2sN1tsoAJ4,856 +torch/include/ATen/ops/linalg_tensorinv_ops.h,sha256=zmvYevJ_1O4pVgbDvnCM7gU-3dbBUOlnAijxWlLPjqU,1953 +torch/include/ATen/ops/linalg_tensorsolve.h,sha256=oRTz-l08ExGr_K57BEa0vHsNeGG-LcFri8Hj_OHCBB0,1734 +torch/include/ATen/ops/linalg_tensorsolve_compositeimplicitautograd_dispatch.h,sha256=6OKTucGsojuwtMlMAIIyPojiA9ECRiKf1-Yi6eMZG0o,1409 +torch/include/ATen/ops/linalg_tensorsolve_native.h,sha256=fk8xoByzegrJCLbVYRSmA3mfi0vPSrcc9WuQ3FhAxVg,959 +torch/include/ATen/ops/linalg_tensorsolve_ops.h,sha256=QdoyVipbqJhvPRpUNf1RbPGYn6qR80TqfVcw_o8vBGM,2251 +torch/include/ATen/ops/linalg_vander.h,sha256=RW-7ePVWoNSJ5PozO8h8iBUp0Y8LPaiPPLEXBI0tlBI,1840 +torch/include/ATen/ops/linalg_vander_compositeimplicitautograd_dispatch.h,sha256=woFTLPNBQmRVvkkeoeTzT3-5uAnhNGkGgdy-UbnuKTY,1177 +torch/include/ATen/ops/linalg_vander_native.h,sha256=atoJuiM2bAJ8fOBHzUmxIhGL-z7WnWXeNzVjS-ubRrU,788 +torch/include/ATen/ops/linalg_vander_ops.h,sha256=Kixnr_Bq9TL7cSfBdmnuFQfn7phMrHXZX5oGrubTKDg,1336 +torch/include/ATen/ops/linalg_vecdot.h,sha256=zkjF6Tieo07wla-4Z1xRyJ6mZBuTjqLgKRFmkqW6WcY,1528 +torch/include/ATen/ops/linalg_vecdot_compositeimplicitautograd_dispatch.h,sha256=4jAn2-6RtA94O64tB91XkksEFKY0L4Ut-SL0EeOFn9g,1298 +torch/include/ATen/ops/linalg_vecdot_native.h,sha256=3fPm8ubqoX-3gBH0o_8YLH47tkC150uPcv64hiB78RQ,889 +torch/include/ATen/ops/linalg_vecdot_ops.h,sha256=egLqi5iLfcW78erbzWsK405bddpzLMmHAFe996emisU,2070 +torch/include/ATen/ops/linalg_vector_norm.h,sha256=Dix3RyQ-1gRkFV2KhNjZKQpzqUaWBWRF-9F-M9ImGxw,2104 +torch/include/ATen/ops/linalg_vector_norm_compositeexplicitautogradnonfunctional_dispatch.h,sha256=o4BycAW0E8tM-TrBSdNsgYWe7wi0Zp-qwORyke0owdM,1200 +torch/include/ATen/ops/linalg_vector_norm_cpu_dispatch.h,sha256=F06vJc6SBYGF3_LbKlbR-U2NZIIrhWwoBx2KTdHNjfQ,1561 +torch/include/ATen/ops/linalg_vector_norm_cuda_dispatch.h,sha256=DeF-8Qh8mf0XKPZaD7CXo0K4HJzibnzPt_69skj-uik,1563 +torch/include/ATen/ops/linalg_vector_norm_meta.h,sha256=ZjZ6-e2CIuMO6PzDhKefYoQi4oP69NVRORi27QRAl5c,939 +torch/include/ATen/ops/linalg_vector_norm_meta_dispatch.h,sha256=CzOlrzt3tB3XD1H8w0ERW5vegGsI-A5KegDkk2A6D8o,1563 +torch/include/ATen/ops/linalg_vector_norm_native.h,sha256=uDtpwGjxWBt37hL5odcIgcjoVZ7ADkTGuKqVoGF3RpE,1209 +torch/include/ATen/ops/linalg_vector_norm_ops.h,sha256=ehT6-r6FW3vu-Aok7YLNDcGxBSwajiTzW-SoCPhT8BA,2620 +torch/include/ATen/ops/linear.h,sha256=01NokxKu32cxtcMGbjYmlFkzme3PWvCnLNZiCoxkyME,1647 +torch/include/ATen/ops/linear_backward.h,sha256=TicG3L8MI7vLcRyjr7x50_Z2T9GyWZG7aI60caiNWOU,2280 +torch/include/ATen/ops/linear_backward_compositeexplicitautograd_dispatch.h,sha256=H-Eu6Ft5dzxlkOvy25Jg540UHnapKK51EqtUQD3xQKc,1483 +torch/include/ATen/ops/linear_backward_native.h,sha256=kxFDMmtqwnTr7iCUkVGK98G_gJ-7VD_Ys_riaMZJqgg,1134 +torch/include/ATen/ops/linear_backward_ops.h,sha256=eUS9SWQ3SjgiDF5IgyxSoQW3_waxtXMQC34muJPsJ58,2876 +torch/include/ATen/ops/linear_compositeexplicitautograd_dispatch.h,sha256=e58pUTv6ng4qvxUfbFHJ8NaeeXXAtlW5mT5PNdAytl4,1264 +torch/include/ATen/ops/linear_compositeimplicitautograd_dispatch.h,sha256=_TA-g4WbvagtJcXO10D0Z4HaEsK--wnpew1n4FWpJ6E,1091 +torch/include/ATen/ops/linear_native.h,sha256=FJdzdwYLF3XyFiWNJUT91UhnXaczVUcKwbczvgLIJu4,1085 +torch/include/ATen/ops/linear_ops.h,sha256=TNKnjv89VAemh4VL4Lm_sV5Wzabc318StGONbhHLqYo,2265 +torch/include/ATen/ops/linspace.h,sha256=BjrAfCrVYYRPXZg54Ax8-FRkqvvyQym0yrmdffZ4KSs,7130 +torch/include/ATen/ops/linspace_compositeexplicitautograd_dispatch.h,sha256=rAyH894irmhtzNcNcWzcjXpmWjEmfwpE8pbsLW55glo,3155 +torch/include/ATen/ops/linspace_cpu_dispatch.h,sha256=ecsxyxSojt-uO_HAdeqgEDN1D_XxXbIV_RXQx5bIdqI,1161 +torch/include/ATen/ops/linspace_cuda_dispatch.h,sha256=iYJWAcuTUZ2FcOPhfak1qXfktf_maQKFdrgW_t77PiA,1163 +torch/include/ATen/ops/linspace_meta_dispatch.h,sha256=Y4-rZ7EqCL6Z8ILzIP3F-q2K5LJbEV7Fw-0ta9VUWgc,1163 +torch/include/ATen/ops/linspace_native.h,sha256=qp1DUTgf4KUxE1P03pUKgY49E-H3g0pAYRrE7gN6Mxc,2293 +torch/include/ATen/ops/linspace_ops.h,sha256=O4MzxVxSQwJcVnzanBn9gj2B05-ObeInQye4wg_HxWM,8416 +torch/include/ATen/ops/log.h,sha256=xOQaF50tq9lcrCmH4Iezr9Kr3JAb97F5_U0SIpJQHqM,1384 +torch/include/ATen/ops/log10.h,sha256=xryDeKUv0QNiJSy_cJtbl_0FYskLAv975IScBqGoCoI,1410 +torch/include/ATen/ops/log10_compositeexplicitautogradnonfunctional_dispatch.h,sha256=qkkqkBU48LN26KruF22zWeghO3Rogaua_9ULnXB0s9A,1093 +torch/include/ATen/ops/log10_cpu_dispatch.h,sha256=mkNZWZsAT1kCIi0MkXbsZ2Q1XU7mR9VXscNgA6lYDoo,1178 +torch/include/ATen/ops/log10_cuda_dispatch.h,sha256=PAdt6UUCFcqogXnE6i05JLGH5xMpIbF0MnYe59fo1HI,1180 +torch/include/ATen/ops/log10_meta.h,sha256=4LIY7g43NNA1e2WfwVZH7UJ8TabNy_UIAm4BH4ZYCws,820 +torch/include/ATen/ops/log10_meta_dispatch.h,sha256=NlEefBvTdHBwyK-oUARwFZ7QVd0ysRwTuP9Gn4k-oro,1180 +torch/include/ATen/ops/log10_native.h,sha256=MJKOcod__cxaAmd2JpyrzXNwu5kzI9yH2X-tnOSqUOA,847 +torch/include/ATen/ops/log10_ops.h,sha256=BUejzlx8zbqNhCQvWYsxH4wydyj7JUcUqyzpyKpTzt0,2291 +torch/include/ATen/ops/log1p.h,sha256=OG2kPlZlVEhZHiE_fN4S2tONFJyB0KuRATbYN-gCcgA,1410 +torch/include/ATen/ops/log1p_compositeexplicitautogradnonfunctional_dispatch.h,sha256=aa38aHhxPV2nntvQV92r3FkRXc-UJbjGJXWxx-ncSxk,1093 +torch/include/ATen/ops/log1p_cpu_dispatch.h,sha256=MjaXv2WalOgfiP4QungEnD_63_945CZQsCp5sjPDbSI,1178 +torch/include/ATen/ops/log1p_cuda_dispatch.h,sha256=d1qSIy_FVDhYK8kOTuzg2laXOuVTh_JCTi71SiqEX0I,1180 +torch/include/ATen/ops/log1p_meta.h,sha256=vviGLx641ST0YzpoIDcYsRiiEu0JX3jx7vRKgXbssBU,820 +torch/include/ATen/ops/log1p_meta_dispatch.h,sha256=17Sj8Bc8Xv4VvZ2ILmhKidfrm7IpYPqWZFA6yMZHEoQ,1180 +torch/include/ATen/ops/log1p_native.h,sha256=dDrZEZpCtZCwGng_GCKs46VdmfAZE_vH8FcmNhy1f_w,1261 +torch/include/ATen/ops/log1p_ops.h,sha256=kfZm2qspmY-5YLLxLZMXxHovyIVvq8eSAevcChMi6xo,2291 +torch/include/ATen/ops/log2.h,sha256=ZsUCAC7Yg2u6glmX7m-BJ-X5J72XX0tGnAFnFB5zJgc,1397 +torch/include/ATen/ops/log2_compositeexplicitautogradnonfunctional_dispatch.h,sha256=nK5nvLJ0Gry9P6VWStGGRcWQquvrIxlqG7hpj41L748,1091 +torch/include/ATen/ops/log2_cpu_dispatch.h,sha256=uQof6NP-SS_yRQwZBqQc6Z6UR4EV8iILc7G-dBOkFHc,1174 +torch/include/ATen/ops/log2_cuda_dispatch.h,sha256=OUyzi3_I4ZdjFuzXGreORuwih3OXy8efssRn1-Uz5c0,1176 +torch/include/ATen/ops/log2_meta.h,sha256=NwOlwUGSMgyyR_fbcF5lNStLUUycMnTnZy4_r5fwclk,819 +torch/include/ATen/ops/log2_meta_dispatch.h,sha256=-mn18o1vbJF2mWu1AnDBldzC9k7q38QwsdaVEGAus0E,1176 +torch/include/ATen/ops/log2_native.h,sha256=QYS0_A6U9hHTAOB5sZpONdQzQRnEh4QhA5yC5eRZQw8,844 +torch/include/ATen/ops/log2_ops.h,sha256=RN65vluzw9xI2MFtIosJHmPDxAOs-k-p3LvyR4nMUFk,2282 +torch/include/ATen/ops/log_compositeexplicitautogradnonfunctional_dispatch.h,sha256=zawq8hY1L3QuF7G4KL7SXA88VGWA-7fx8z1_fy8MJ-w,1089 +torch/include/ATen/ops/log_cpu_dispatch.h,sha256=fnLB3WJHkN8-27Ca6-NDf3CFqI7mL2-Es0WOY_B0E3M,1170 +torch/include/ATen/ops/log_cuda_dispatch.h,sha256=ZUC-UzXJziTuBICEueFvHfaud3nN5WzPY_PAuDCRiV0,1172 +torch/include/ATen/ops/log_meta.h,sha256=c-pI2Ni5Zc2twOwAo8csq84GSdaJ0QxQ-9aIb86hGls,818 +torch/include/ATen/ops/log_meta_dispatch.h,sha256=qmMW14zAGzjcQb750Rji2dy7C1lEdGE-yC3JxXWib7U,1172 +torch/include/ATen/ops/log_native.h,sha256=CkQiyOgWfrNIdEwMOPWwoYm3FYOLbHklSyd73N3qF_A,841 +torch/include/ATen/ops/log_normal.h,sha256=7MYdqRD2ks9mxwuCzlEGZHbb4TZvmx6ngIw1v3S_vzY,1791 +torch/include/ATen/ops/log_normal_compositeexplicitautograd_dispatch.h,sha256=xcfQNYzJlZkUGfGXqQyhsenc3ACPBwi8SCT98vYLZeQ,1426 +torch/include/ATen/ops/log_normal_cpu_dispatch.h,sha256=HqJnk6grZmcU7YL1cuiQctsgy6ks7N1pj32YjEyrpVM,1061 +torch/include/ATen/ops/log_normal_cuda_dispatch.h,sha256=wylWaji9QReD9PbjajHB-yICpOFKObmNcsEoSCv0Alo,1063 +torch/include/ATen/ops/log_normal_meta_dispatch.h,sha256=EC3fxPiksSCkiUd9o09GWnGOMFRAZTwpcsIL2aHc8Vs,1063 +torch/include/ATen/ops/log_normal_native.h,sha256=ahg-_k9aYRzJ4vd_4zslgmZTMUPmgAjKjtARjxU1Wkc,1110 +torch/include/ATen/ops/log_normal_ops.h,sha256=IpzBUdapLU0rOHJbdYaboTZ6ZptPpQSRNBouuDic_0k,3050 +torch/include/ATen/ops/log_ops.h,sha256=uaEkHCLFuu4ioZqF7PTlP3aZY-OBRq6GZrOAHj1iBls,2273 +torch/include/ATen/ops/log_sigmoid.h,sha256=tVpIKd73NIWqD4WFU2SFd4lp6GmUMdpjcloSniL9bTg,1331 +torch/include/ATen/ops/log_sigmoid_backward.h,sha256=5AxC2EmORABYo5zlXFO8XExJiJ2iMD4W6M5MnFmFZcE,1836 +torch/include/ATen/ops/log_sigmoid_backward_cpu_dispatch.h,sha256=yq_N4Kh9f-Hh-ZyOazRlSBooIh9dAc83fZp4YUb_Mt8,1364 +torch/include/ATen/ops/log_sigmoid_backward_cuda_dispatch.h,sha256=g_us_wU6_cseacHJ3sFkitMbjgNYRyzjqbJUHy770Ko,1366 +torch/include/ATen/ops/log_sigmoid_backward_native.h,sha256=OnL7aSMp4vlMAOxRo-Kfru4ztbjVHYpudt5RKTxoMLc,1264 +torch/include/ATen/ops/log_sigmoid_backward_ops.h,sha256=AO9wm-Ebyj9nyqliZHIDO48FF5qU3aZzZuC7wgKIUOA,2313 +torch/include/ATen/ops/log_sigmoid_compositeimplicitautograd_dispatch.h,sha256=2-zUIbNN1BEWZOB82kS6eFkhkWCKK1zMsOxtLBEgqKA,1190 +torch/include/ATen/ops/log_sigmoid_forward.h,sha256=_gnULzh92JXHEARxbVfmwtTvdi9KWKtG01gbUDEmz6A,1668 +torch/include/ATen/ops/log_sigmoid_forward_cpu_dispatch.h,sha256=yv12S1BJqsaW5Dk9VGbQhWUutgpV6A-LMxInOvBSnfQ,1297 +torch/include/ATen/ops/log_sigmoid_forward_cuda_dispatch.h,sha256=WdjG0Y_VPCkQD58wXcr4uOFXHGzykjdRc6iHMw7nIAI,1299 +torch/include/ATen/ops/log_sigmoid_forward_native.h,sha256=uZs8jJh4isJq70gcNjOoF52L0CHoF4xAb40dXIRZJSM,1162 +torch/include/ATen/ops/log_sigmoid_forward_ops.h,sha256=K_XnvihHFQ-aOsc4nR6PXMeFVvHs93RIRF4UNskHES8,2166 +torch/include/ATen/ops/log_sigmoid_native.h,sha256=HV3C-nCOCAj37EZTFWn72fXz6cSOVUC_rWcjudv3FVM,818 +torch/include/ATen/ops/log_sigmoid_ops.h,sha256=mRyB4WkSGivY20MVGHgPh4aAULcAKFlrvcVPtTCpJ3s,1831 +torch/include/ATen/ops/log_softmax.h,sha256=p8r2lQbjbAvdkwZZ_622wZES2jpoyj1jCEenlYfnWpk,1676 +torch/include/ATen/ops/log_softmax_compositeexplicitautograd_dispatch.h,sha256=rLrrXZUUVt1mWYuls5uw_Z9RDm0u3cD2lIXzby1mU0Y,1250 +torch/include/ATen/ops/log_softmax_compositeimplicitautograd_dispatch.h,sha256=jEGirJgyT0Xz7xvlr3mwHBm2O5kq46dzZcg5IVvz5pQ,1090 +torch/include/ATen/ops/log_softmax_native.h,sha256=PuV1EYm74W8lG69x8OWLqU9okxc00aWdGPFz6i37y2A,937 +torch/include/ATen/ops/log_softmax_ops.h,sha256=xELTfSgWWABG-APxAKhl5F0hjwV9dUPwdPWAbjZbfag,2212 +torch/include/ATen/ops/logaddexp.h,sha256=Y23kfc0RhyR8cai_JsadKidS5bp6hAm3_Ac_9zDPkvo,1452 +torch/include/ATen/ops/logaddexp2.h,sha256=KjwZji3NwDB2tR3W0Kaxe0frkMQ-TPTFmVLPNxXxNzI,1462 +torch/include/ATen/ops/logaddexp2_compositeexplicitautogradnonfunctional_dispatch.h,sha256=EaLUi41_axPiHd000OopXD6iYHkWUDIcYHKxhYj7fGY,1074 +torch/include/ATen/ops/logaddexp2_cpu_dispatch.h,sha256=G04mFynA5zME8xlybq10pYzb2jnrNV2ornDT6rgcBpc,1221 +torch/include/ATen/ops/logaddexp2_cuda_dispatch.h,sha256=3UdZTRjoamcAfQb0-8_b7zNO1GSqoOL8gFe_Np5u1cY,1223 +torch/include/ATen/ops/logaddexp2_meta.h,sha256=i2HyOPegYvVizWcEDCTt_u9n0eg_rvW5R31cfCRK1Ks,851 +torch/include/ATen/ops/logaddexp2_meta_dispatch.h,sha256=Ib0YXv2uCXdBVI1s6PLOg3VgS5C-uuy0pDtawjY-yds,1223 +torch/include/ATen/ops/logaddexp2_native.h,sha256=cxMMc0-hNa2RDQaUvBnLqk-Xs4xFsPK0HMtVcy6uulI,888 +torch/include/ATen/ops/logaddexp2_ops.h,sha256=r4VqUdZSZOVjfnVE1AKMNU0QUuL4s1Uhm9_o6Fbx_SM,1997 +torch/include/ATen/ops/logaddexp_compositeexplicitautogradnonfunctional_dispatch.h,sha256=vUOyXE6CcAB_xCQdVzIED5KKCBNL0Ju9C9dRUQ04Aj8,1073 +torch/include/ATen/ops/logaddexp_cpu_dispatch.h,sha256=Eg5PnJ4Aaa9vXQIAJ0o5SuCUmIDbiEUQJ_3IIqSYdok,1218 +torch/include/ATen/ops/logaddexp_cuda_dispatch.h,sha256=M0YdN8nDynFuhGoSEXkCmJy44IaETALR6PcieefLfDY,1220 +torch/include/ATen/ops/logaddexp_meta.h,sha256=reW3tJD45oPKBCDql38j3TsNBoAo-ffoHk1Oa8dMwD8,850 +torch/include/ATen/ops/logaddexp_meta_dispatch.h,sha256=dryZqZMD_SzE3uMF8aejRvZolCN0W7T9CrdIphHyadM,1220 +torch/include/ATen/ops/logaddexp_native.h,sha256=BbCD3W3B0-bQG-SRCQtmublLZnCwtSkSuMFUrOshESk,885 +torch/include/ATen/ops/logaddexp_ops.h,sha256=Dc2Gy_EAUGzTV0QYwxTE9-x1Qa_B-RXed7O-zT27Hws,1991 +torch/include/ATen/ops/logcumsumexp.h,sha256=b859BZBrzo8GkCVQV4GF-YXVlfYS7MPYcCRMZNZDqfM,1422 +torch/include/ATen/ops/logcumsumexp_compositeexplicitautograd_dispatch.h,sha256=ImURomyp9ubZsRe0xarU7Gw6y4qymFxtmJ6Of3iHImU,1232 +torch/include/ATen/ops/logcumsumexp_native.h,sha256=jxYK8ZXlekgsmT2DD4vrdIfE_ao9blNXORuimeEbpZU,846 +torch/include/ATen/ops/logcumsumexp_ops.h,sha256=SMPtS76yzImwb4ZBst2JCKkSG4QN0sEeFGtS6GGCNl0,1925 +torch/include/ATen/ops/logdet.h,sha256=diUYhDXqTDjqOEgB5X892AXTqPf9sVz2g-nIrpv5XIU,891 +torch/include/ATen/ops/logdet_compositeimplicitautograd_dispatch.h,sha256=-XAH5Ayc1S1rHJwzB2G3D-jZ430HoRTbCkL1n6fHGVE,1018 +torch/include/ATen/ops/logdet_native.h,sha256=OvgfbgSbGdUeBN02pu35DFQAsvrLIaFhm2GdUiSm5jg,730 +torch/include/ATen/ops/logdet_ops.h,sha256=D_7lXSDkbmrfaltIFapPGWqR-hui2jUHl7GsoUylAB8,1211 +torch/include/ATen/ops/logical_and.h,sha256=oE5sRLTXqACgwoWBbxkxsfyeHnJXAxoUsDJT_kqtOQk,1472 +torch/include/ATen/ops/logical_and_compositeexplicitautograd_dispatch.h,sha256=-ap6pSytHxAZOfWT-XzvpJpN2wOUIrdGEjltZ1nqLqM,1131 +torch/include/ATen/ops/logical_and_cpu_dispatch.h,sha256=47tcL1vx1A0FAkwssZSj_R3tAHBAO4PfIuGryWLnjug,1139 +torch/include/ATen/ops/logical_and_cuda_dispatch.h,sha256=d1E6se5-fvbfxyIMhs3xKbBiIjMEIXRB3NhH25ROaec,1141 +torch/include/ATen/ops/logical_and_native.h,sha256=QSE7EjoZ0ExfYN_1clQn6daqYwZcK_Vh5xbmV2jC_mI,952 +torch/include/ATen/ops/logical_and_ops.h,sha256=VwuoqFUW0FunjlWd6Eoww4o8o5Un6tM4Aqzxo-kQ7HE,2603 +torch/include/ATen/ops/logical_not.h,sha256=GBdu7OodZwXyH63pgarjjeYyh8WtMydf48-tECE3Yv0,1331 +torch/include/ATen/ops/logical_not_compositeexplicitautograd_dispatch.h,sha256=i66uZ3cf3D8aCC-ZTD5c6F3k5DvSqxDfULKqBF8r3P0,1079 +torch/include/ATen/ops/logical_not_cpu_dispatch.h,sha256=8Zlgk1tND-AtMAzbYt7VXkp0jRFdG7J3C447PSWql_g,1087 +torch/include/ATen/ops/logical_not_cuda_dispatch.h,sha256=vO8Bse_bBA6rGfIXQQ2BG4iQrWaqO7JoJfDhQf8o19s,1089 +torch/include/ATen/ops/logical_not_native.h,sha256=rd3DYC22BGoowBmbtHiXAgDGQuVNXK7lgIhxhm8gAjE,1015 +torch/include/ATen/ops/logical_not_ops.h,sha256=AkLvfs8EVfmrnUfoDkQ82GIgSjOPBVjuB4rhcx4hNp4,2345 +torch/include/ATen/ops/logical_or.h,sha256=0Ho-YmstSA4Q0GtdqL-BNbiYfuHgZorBkvEk6WIW9UY,1462 +torch/include/ATen/ops/logical_or_compositeexplicitautograd_dispatch.h,sha256=3nWr8pcF_hPjd1-n65-AG_j7_NqIepZl8hWmyvQ01G8,1129 +torch/include/ATen/ops/logical_or_cpu_dispatch.h,sha256=3XstS9SpRsKJuK0LqzoBTAEMQyd5gBT1eo-1wjdm_rU,1137 +torch/include/ATen/ops/logical_or_cuda_dispatch.h,sha256=SZsKMRpZoFJcq2GZlRLaxy1k2Llvwpt608FA57QIgIU,1139 +torch/include/ATen/ops/logical_or_native.h,sha256=8WfC05fxpX2EuVNBBBpWlJ0j-wymLxTpxC1JweYG5S8,949 +torch/include/ATen/ops/logical_or_ops.h,sha256=ioTtybEg5NkT22K0DzLaJYMNV64VTcgjimW-0mgGv-I,2594 +torch/include/ATen/ops/logical_xor.h,sha256=CXdQxCrTEMnxUlE8RA93715We4Id-9NZ24B4wp8JO1U,1472 +torch/include/ATen/ops/logical_xor_compositeexplicitautograd_dispatch.h,sha256=GUv4fv2Xnt1Z6SbK5pgZRSQzwETK-bR34MCkSPZP2rk,1131 +torch/include/ATen/ops/logical_xor_cpu_dispatch.h,sha256=X6BtNUAyK-m6GOhFzjiwiUicHQnzpTmuxN--seWHKrs,1139 +torch/include/ATen/ops/logical_xor_cuda_dispatch.h,sha256=vZbd3ADpAYjcj4HP3ZFdy6Yc3ESWf0H0QxM5jrM6xPA,1141 +torch/include/ATen/ops/logical_xor_native.h,sha256=1uvTjT_q0DOFeeqR-AgOGfBVjV5nBipiV8ypBUxiZiU,952 +torch/include/ATen/ops/logical_xor_ops.h,sha256=Qqypf8jFj67tubYNZAua1wn6oW7lZohGwZ0vMwev3OM,2603 +torch/include/ATen/ops/logit.h,sha256=Ya3qHmsYy_OX5twva9sTNpFcrrGGMZpTsXg_tVgsTTs,1659 +torch/include/ATen/ops/logit_backward.h,sha256=NMoU12-Tw-XziicLqWfJ3F4wwp_1uG9PdJ8fYBOMJQ8,1809 +torch/include/ATen/ops/logit_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=S0FI3VQ1qWU1XvWu5HiL9nMRHwo1hTk-ZgiybXmHMG0,1128 +torch/include/ATen/ops/logit_backward_cpu_dispatch.h,sha256=joDDCtCW-Cok28YwckZx_bfxtFO3fNc0jd3yfc_Hhig,1382 +torch/include/ATen/ops/logit_backward_cuda_dispatch.h,sha256=VHxTok09L8JtelQHq4yY0hY7n6u4Iw20Vz-1koVJxPw,1384 +torch/include/ATen/ops/logit_backward_meta.h,sha256=xmlACX-lpM7_I6fHbqEDVWeqXvFilAzR7t5p4jvl2C8,890 +torch/include/ATen/ops/logit_backward_meta_dispatch.h,sha256=0mhXLbSgSq4Iq3lFzrmVXM4gEs91MnP-OzUDp5z6YTc,1384 +torch/include/ATen/ops/logit_backward_native.h,sha256=9ncuT0W0PIMVnFwCy2QyHEmHP5APvU-zhJaUGM3nJ7A,942 +torch/include/ATen/ops/logit_backward_ops.h,sha256=E4ibf5FOu3JchDuBiWuxUXNcVzimjiE18TX4XY-DjB8,2299 +torch/include/ATen/ops/logit_cpu_dispatch.h,sha256=Px9fLWzg908fJHurvJmlSZaPTnOAPdogryOOMp3qcms,1339 +torch/include/ATen/ops/logit_cuda_dispatch.h,sha256=PiDG8Dj7lASH51KKuOuamr94-POT4J742UTbZbV3JjA,1341 +torch/include/ATen/ops/logit_meta_dispatch.h,sha256=DW5CU2-g0nAS2sRx9asRkViHLKGu15BTV5ZEY64VJkI,1016 +torch/include/ATen/ops/logit_native.h,sha256=lAsyt4rp34A4QvW9JwSrbdMIqQG-CXc_JZBGs8Mw4HE,973 +torch/include/ATen/ops/logit_ops.h,sha256=Rlz34du2wCxNHVXgMNomT6jj2860ik6yoLsdhXqo_Bs,2591 +torch/include/ATen/ops/logspace.h,sha256=i4wqGhOhK8bepCr1uErG8T_2cWMSyc4BBPnxvnWMfPs,7746 +torch/include/ATen/ops/logspace_compositeexplicitautograd_dispatch.h,sha256=r9cf7Zmdsdzy61-mo9qKQExkWo1qXE95U9JHKbwkhQw,3372 +torch/include/ATen/ops/logspace_cpu_dispatch.h,sha256=eg58ehs1Da6YoWoDN37ByZnhKP7n92STIoXJG-BMz08,1192 +torch/include/ATen/ops/logspace_cuda_dispatch.h,sha256=W26u2y7qcGAajB_JCKaoRD-IFKVCagzVcIs1ihQ7xEE,1194 +torch/include/ATen/ops/logspace_meta_dispatch.h,sha256=p3ISKkvaODPme-4JiaEGWNZI1nm9caGnTX3ZqPMSq34,1194 +torch/include/ATen/ops/logspace_native.h,sha256=Ie7eZy96iyE7boinKgMjfKJriZcTvmtMh2-dPlZRunQ,2430 +torch/include/ATen/ops/logspace_ops.h,sha256=K15L8st9R2uRhiIr2z305XoOby4haqNsc0ukrUlFtgM,8824 +torch/include/ATen/ops/logsumexp.h,sha256=aLlP-3CnKNlBPd7CYCIuTxx9W0YdMCV8Tr89MBQijKI,1566 +torch/include/ATen/ops/logsumexp_compositeexplicitautograd_dispatch.h,sha256=fdxdeJb5GBSk5RzDEeZlA8B9BA7Mk1u_PXFFYn2JkcU,1062 +torch/include/ATen/ops/logsumexp_compositeexplicitautogradnonfunctional_dispatch.h,sha256=0dBxOOGT9MZ4xPbeCggbXbKzIuMAqbXfXH5bRQKp7VU,1229 +torch/include/ATen/ops/logsumexp_native.h,sha256=1Vbadz-Bzy_6qsRj9EhqfJ5TFjsVVBoRvnmHzfqkyXQ,890 +torch/include/ATen/ops/logsumexp_ops.h,sha256=YwHSJcXQjbDLe4OUzdaQIRoe6-Kzx8ZagQec_EbnIEY,2069 +torch/include/ATen/ops/lshift.h,sha256=RDWWXhX-4pvyqB6tnF1e91V4bNd1Acqkp3ZM-Z1Kvms,2244 +torch/include/ATen/ops/lshift_compositeexplicitautograd_dispatch.h,sha256=xfEwuM5w3MrqHP-24tJvDwgm_32HoBimYDy8kVfYBuI,1398 +torch/include/ATen/ops/lshift_cpu_dispatch.h,sha256=AJdR9AJbOqOJi7XPdvfUzPDGl4-LMFZ-CmpWWRZUOYo,1250 +torch/include/ATen/ops/lshift_cuda_dispatch.h,sha256=_VtjUtAbtfQOwsKToJB9Z6yBBzJ3zGCkz8eqwbbf1Kc,1252 +torch/include/ATen/ops/lshift_meta_dispatch.h,sha256=fHcInyTf_S7qmmTDYen43KQBkhrGoJvJNOdKZ_nRe3U,1084 +torch/include/ATen/ops/lshift_native.h,sha256=GnfuVfDpmlVLB_GdXO_5X8PvnrT6KmpBqijJjfvV8Gk,1236 +torch/include/ATen/ops/lshift_ops.h,sha256=ExSeUk_d7EoqKRPjrPDsz7A6W3C6czi5vXLtMDfI1Gs,4599 +torch/include/ATen/ops/lstm.h,sha256=npSUDH9EE88Tb45L0k1qjAa5NHFfH2RSuiFF5pRVECQ,1867 +torch/include/ATen/ops/lstm_cell.h,sha256=9ChhGCyLelrwsuysnDQRXfMa7c2-ccAcpkqbH7I1EII,1205 +torch/include/ATen/ops/lstm_cell_compositeimplicitautograd_dispatch.h,sha256=x9Jum4tHatBrTYcpOjvKcPD07wKG78jXG-pbem9QT3U,1206 +torch/include/ATen/ops/lstm_cell_native.h,sha256=qZsF9RM6SH_V3-nNpOjCBtfHiXiz1qm2fb-tY0QGuqU,918 +torch/include/ATen/ops/lstm_cell_ops.h,sha256=Ri-TRhMoB0bVDdDJeBR2uvzJrWUJ4CvKSzCuk0kcF4c,1821 +torch/include/ATen/ops/lstm_compositeimplicitautograd_dispatch.h,sha256=oo1bsfEuBqdy5Xdw8mf-WqpkZaGO5tuO4RcjXfqDoro,1445 +torch/include/ATen/ops/lstm_mps_backward.h,sha256=nq72DjKGxZ-m7Uscrn_C1Eo9uLWp3zFiVYVQSlr6g94,3929 +torch/include/ATen/ops/lstm_mps_backward_compositeexplicitautograd_dispatch.h,sha256=S7mc68XXvZuqszph4aR_aVKPXXqxpPDuJuzvj3ioKfM,1967 +torch/include/ATen/ops/lstm_mps_backward_native.h,sha256=Wlag0V4q0C_u6eEwlKToBo6HVDJrBQo3GEkGIOAiiEk,1177 +torch/include/ATen/ops/lstm_mps_backward_ops.h,sha256=MEalpRoQvChUtS9wdMlx5D4umvciq4Rm6QsfcB_2eBs,4688 +torch/include/ATen/ops/lstm_native.h,sha256=JJ1efTBefLuAICX2t0CqMOF-UyKU8lRaiW2PD65yGKc,1157 +torch/include/ATen/ops/lstm_ops.h,sha256=9cUtntGblA0Lfk6XMkp6adhPD5XqFI7kRX3gNPWg1kY,3011 +torch/include/ATen/ops/lt.h,sha256=pJM_QUThaUSVrMwYAiWvP-hvpCZwBwi0_o15X4OLdFc,2096 +torch/include/ATen/ops/lt_compositeexplicitautogradnonfunctional_dispatch.h,sha256=0ql3-9FWLwNopQf502-k391RocBo62upxdmYTh1lrM0,1288 +torch/include/ATen/ops/lt_cpu_dispatch.h,sha256=Gkayne__OEdU-jOP2_Qj0HzgNPwfkK6Hm_QDk_sFryQ,1620 +torch/include/ATen/ops/lt_cuda_dispatch.h,sha256=JVjXzeuGAJnRxAxnojF2XRg3kXKWSCGo65cHHsec8vU,1622 +torch/include/ATen/ops/lt_meta.h,sha256=tLPOYvSg5YXSet2D-MKkmqkVRIgV3jnVoF6NDcJISfE,989 +torch/include/ATen/ops/lt_meta_dispatch.h,sha256=P0d_sAgOfKDAger7m_1dYvw5-BlljzGpqOkZGPoA-Fg,1622 +torch/include/ATen/ops/lt_native.h,sha256=u8FZvO_Oz7sj3-SxkV1H5_ggoKb1-XjwfNOG2qz78WQ,1459 +torch/include/ATen/ops/lt_ops.h,sha256=QpVL1mJUMd3HclW1dzIE3o_MLOBJzyUdgPjlS4WVw8k,4455 +torch/include/ATen/ops/lu_solve.h,sha256=gUMqtLx25YQdMV_TYceuOI31LZ3X08l5urnieFbckj4,1637 +torch/include/ATen/ops/lu_solve_compositeimplicitautograd_dispatch.h,sha256=NiRiMBRYPIlFRtu2iPtjqUPECt6qMQjynjIktLecwKk,1355 +torch/include/ATen/ops/lu_solve_native.h,sha256=HEthPORZztgozQYyxQQgYmvMgFYM05vnxx2FR6AiRTM,928 +torch/include/ATen/ops/lu_solve_ops.h,sha256=5CiFj94sZeb7yyTtRGTdmuH6bDwROReuAvqbCGQHtso,2193 +torch/include/ATen/ops/lu_unpack.h,sha256=sf9UQ9XXv6OECLmAZCdANrSwCpER9AU3rapkKfyqYB0,2201 +torch/include/ATen/ops/lu_unpack_compositeexplicitautogradnonfunctional_dispatch.h,sha256=c0m1UHGkOIpgqENEwrJ2DAPySp0aEcP1_9sdtV2mvOY,1164 +torch/include/ATen/ops/lu_unpack_cpu_dispatch.h,sha256=UjFauGJ1LEh-1DUzBCBho03FN9XZM4uPL9QziahKmwA,1549 +torch/include/ATen/ops/lu_unpack_cuda_dispatch.h,sha256=-4hA4j37aCfZWWdPkZwNhxyEt-8y05bXsSicyeZ88vw,1551 +torch/include/ATen/ops/lu_unpack_meta.h,sha256=lW8JM5YQAkeZvANUEadeJJ-oVRk2_FoSamer5Xj3Ab8,895 +torch/include/ATen/ops/lu_unpack_meta_dispatch.h,sha256=nlVYF2pvH3HaLoImdzGdH3Wp_BhHs2nUlJ_DeBq2N3s,1551 +torch/include/ATen/ops/lu_unpack_native.h,sha256=Cul8PAQB06yLf4kK4QbpGsOLCsCKfwUcWqH8EKCA4oI,972 +torch/include/ATen/ops/lu_unpack_ops.h,sha256=YKpNT47IfgZneVIfWkuzBB4qH259_8tguWBFJtIyIu8,2703 +torch/include/ATen/ops/mH.h,sha256=pbNrcfKRz-DtptslD6_oOhJh2dQ5_zJP9f1TxcbtwcE,753 +torch/include/ATen/ops/mH_compositeimplicitautograd_dispatch.h,sha256=5c7p1m62IDlFqSdC-EL-1DJYg3QO6d6mRKcOdWGwcYs,1014 +torch/include/ATen/ops/mH_native.h,sha256=grLNKNYYBR6simKgZ_OgIR03IycJfmB05YYQRfOpKaA,726 +torch/include/ATen/ops/mH_ops.h,sha256=DzFMYyTHKnfMWAoprPBlwTkTSap-CNMmwA-a7bXPuoU,1205 +torch/include/ATen/ops/mT.h,sha256=asgp9Kiafnhz0RwllEkh2US0r-y7kxtQfR8WNjcG0-w,753 +torch/include/ATen/ops/mT_compositeimplicitautograd_dispatch.h,sha256=0pOR0xayTRUR4ah9abHsQ9E8-P71Udq0ZjMhueyKPZ8,1014 +torch/include/ATen/ops/mT_native.h,sha256=G62vhGJK_48ZVkW1uArLuBD2IjsdzUIuZS_V342y1K0,726 +torch/include/ATen/ops/mT_ops.h,sha256=G9gruuYoK9zVidxmZIktforSmwMJGdgTkacUUf22M9g,1205 +torch/include/ATen/ops/margin_ranking_loss.h,sha256=PFLMchhpdbTzDMXkLVD8oi8tyGc-WaSOd4YXxn5TwVg,1164 +torch/include/ATen/ops/margin_ranking_loss_compositeimplicitautograd_dispatch.h,sha256=_-8nLE6Hx_cIGR1rCD67voOMYmep-s3Nr9V6g6f3hsk,1145 +torch/include/ATen/ops/margin_ranking_loss_native.h,sha256=d1WrPBpG_A0Lj9uuzEGjIx6FYHOffTfNkms1kHZp32k,857 +torch/include/ATen/ops/margin_ranking_loss_ops.h,sha256=gK-5f3inySwwtdGgjxiFf5KrZfKww-BfCqVt73t2vcA,1557 +torch/include/ATen/ops/masked_fill.h,sha256=orT5D32DYTLYqOPvh037zzMDUwLj0QvPNQLx_KQAjaQ,2531 +torch/include/ATen/ops/masked_fill_compositeexplicitautograd_dispatch.h,sha256=JOPu-_EcrDfa4WROicheidtzasK15rKeEHGMi8RxJZ0,1722 +torch/include/ATen/ops/masked_fill_cpu_dispatch.h,sha256=PiQxtYy71JJWagCkfWRI-DuAjCjI0ezG4wvU_hxfk2k,1134 +torch/include/ATen/ops/masked_fill_cuda_dispatch.h,sha256=ZuhxwuLPH46NygQwFnRa6_EBCoVOJJZ3-mn5atykTeo,1136 +torch/include/ATen/ops/masked_fill_meta_dispatch.h,sha256=o9tTd4hsl8qOKlA5aaWUUGeIpCaR2y6QMZynrKyCdjU,1136 +torch/include/ATen/ops/masked_fill_native.h,sha256=gGVcfz43gSuLsAFr5mNcjtlAGQh-7K7lrE1YOHxg1VQ,2233 +torch/include/ATen/ops/masked_fill_ops.h,sha256=8iEbhJTqeLCTswUGNpFB7HJePwdTYMip9xsXTOYikoo,5115 +torch/include/ATen/ops/masked_scatter.h,sha256=a9U2m2OIIhvA3gZTrUHWzMKyDMKp1OushwVL6-Y_KyE,1643 +torch/include/ATen/ops/masked_scatter_backward.h,sha256=7sN_0PMkcnXlQFlY16zKzCPa-g7ZvQ3_B8W7flMV22c,2044 +torch/include/ATen/ops/masked_scatter_backward_compositeexplicitautograd_dispatch.h,sha256=yLAVLFUAzozW97x7RpoAiD-SUxj20A4D-IaM5mS4uh0,1227 +torch/include/ATen/ops/masked_scatter_backward_native.h,sha256=PM8ZAvzFXjEuS7ZPjP4NuzEd7K5fbUkfRpNKmX_69Ws,813 +torch/include/ATen/ops/masked_scatter_backward_ops.h,sha256=ZFIWw7eIDsz7EHFgkXXW5BbQPVYnb0oPGuJzyKJ8l4o,1457 +torch/include/ATen/ops/masked_scatter_compositeexplicitautograd_dispatch.h,sha256=Fs9RcwUfI7nij7Yl6TPtXjsaIfBppxCDpQI0whYygs4,1355 +torch/include/ATen/ops/masked_scatter_cpu_dispatch.h,sha256=74enrbznF6YmkbMJc3uVuEMOgq7hrRMDufsQQs-B89E,1031 +torch/include/ATen/ops/masked_scatter_cuda_dispatch.h,sha256=ywRIoNAQ6WHmUm5XdHikKKGQgk50ooaJq5nORaqO188,1033 +torch/include/ATen/ops/masked_scatter_meta_dispatch.h,sha256=eglldQYSep8hKmPwy3r49fS_bTzgqbot1f-jS1AIqUI,1033 +torch/include/ATen/ops/masked_scatter_native.h,sha256=RD0R9pqIpzfNY_IUPu4ilMtIvxuNLpn9gJgAzkYqC9s,1159 +torch/include/ATen/ops/masked_scatter_ops.h,sha256=zR_uyGmrNBoclDVhOOczAqkmvSyunWaKYsx4MA_jx5M,2888 +torch/include/ATen/ops/masked_select.h,sha256=35nj-D4EHuABztDY3A2jq0meqZxh6BROXY1_Yadc5oE,1483 +torch/include/ATen/ops/masked_select_backward.h,sha256=Rn1ubEOG7XpYhgA9GGVCk31RJA2bAIEX4jIvHD-mPpM,1046 +torch/include/ATen/ops/masked_select_backward_compositeimplicitautograd_dispatch.h,sha256=kAYmFlfvkQC3w7byIJXLuKYayV-q2a0yorrMX6JJers,1085 +torch/include/ATen/ops/masked_select_backward_native.h,sha256=yJnZ8KsWdHwn9TG_cM7Tzcd-1-zniIKKj5SubCraEc4,797 +torch/include/ATen/ops/masked_select_backward_ops.h,sha256=SqZLGB0h1AXNltai_muPXsVmnDJ4rUP2jHgtVn43Ikw,1428 +torch/include/ATen/ops/masked_select_cpu_dispatch.h,sha256=CVOrGgxffjmefDE4ol_cbs0WVjQymCTFlnfzC5BXcIs,1227 +torch/include/ATen/ops/masked_select_cuda_dispatch.h,sha256=tputscIuPHtyViFhoUY0i7LIbkfpSRjOlSZ7GMmIgJQ,1229 +torch/include/ATen/ops/masked_select_native.h,sha256=kl28b0787rMCrLFBg1pdptB-xp3B9hMDtSMZla6nw7E,1086 +torch/include/ATen/ops/masked_select_ops.h,sha256=6JxuLlGclmcjBkpU37azlpm-3Onh2sldEB4xpaKrbuA,2009 +torch/include/ATen/ops/matmul.h,sha256=jaovUb9XTwqKE27kbctsdJD0gqmAzIJZBasYMp0gPAw,1422 +torch/include/ATen/ops/matmul_backward.h,sha256=ullOJa7sUxUo2jxR1MVlt8Cm9x19Zgof9nyhQjKuzuQ,1992 +torch/include/ATen/ops/matmul_backward_compositeexplicitautograd_dispatch.h,sha256=zjWedAfyxYniZthVD21CtctrVy7nPSriYAN_OobwrlU,1389 +torch/include/ATen/ops/matmul_backward_native.h,sha256=nNmp-C5gxNU7xMfkpuASxuOIH_uAwbKJUq6QNaIv5CQ,1061 +torch/include/ATen/ops/matmul_backward_ops.h,sha256=2nKXYY2acX_eQ7xX-r3wLkG-Vni9Obpuk4fGJwmEKAQ,2625 +torch/include/ATen/ops/matmul_compositeimplicitautograd_dispatch.h,sha256=Q5RMaHujLUx5jnNrv0t9E-Cs23SBFWZozSiFjvFrAyg,1253 +torch/include/ATen/ops/matmul_native.h,sha256=Zz9dnwdj3Uwio5KhA3KhRnQdqHGYtHiSbFHr_7qxBQo,1058 +torch/include/ATen/ops/matmul_ops.h,sha256=UwYR5wSUYHT6IAcgrpAreyoIjBOBb72Bd4P8LDRf5r8,1973 +torch/include/ATen/ops/matrix_H.h,sha256=sZ73InVoI6GVyw7j-twzKeJTL97Gv5qSghZAps97PLA,759 +torch/include/ATen/ops/matrix_H_compositeimplicitautograd_dispatch.h,sha256=JPmH-207ngk4S-UHHR25ePZyzDh6XHpGuVWHhYWKZVg,1020 +torch/include/ATen/ops/matrix_H_native.h,sha256=ARYclGs5nIcEvL8YJ4lo1Buw28Ls4H2RdOv92yD8Zyw,732 +torch/include/ATen/ops/matrix_H_ops.h,sha256=fmyA9eNELzU30vgLZNdgVD3jWAUkVyGOCszpxh1SI7A,1223 +torch/include/ATen/ops/matrix_exp.h,sha256=IrzitVtO0-BND4KUrFOvCq8_Knex_3EAdCeiCqKMyfY,907 +torch/include/ATen/ops/matrix_exp_backward.h,sha256=YrGWftbIT2b5dIiKfrpRfZAiSXxM8MtBGGy4UVOwGd8,987 +torch/include/ATen/ops/matrix_exp_backward_compositeimplicitautograd_dispatch.h,sha256=cUZHMzZN2wCjwrfPc-OadcSORBXJ3-QstLtIKdkvS7E,1056 +torch/include/ATen/ops/matrix_exp_backward_native.h,sha256=iR-evb-MdJb2m8qjJ-Tgvu-SAuBtFqANn8LnRd_sKRQ,768 +torch/include/ATen/ops/matrix_exp_backward_ops.h,sha256=n6GP8TRN8cJaiZ-v4Phmc736aUIuNLowspayB_FQR1I,1333 +torch/include/ATen/ops/matrix_exp_compositeimplicitautograd_dispatch.h,sha256=4BtDf0tsCCvsbvo5OV5X3lPaefvaNna3yq_Ss8wSuSw,1022 +torch/include/ATen/ops/matrix_exp_native.h,sha256=tXFiZgSZWGJL_pXmMN4NmCtbq7n-_wffVqWW8bSIgpE,734 +torch/include/ATen/ops/matrix_exp_ops.h,sha256=IowmHVhsp9I5Y_EyxObyGYuQeN_e5UjHmAi_7urG4ew,1223 +torch/include/ATen/ops/matrix_power.h,sha256=jh5c8AoNqfTsA4pT_bh-FXd2RJU4iQTthmUi0Mm4mzc,1404 +torch/include/ATen/ops/matrix_power_compositeimplicitautograd_dispatch.h,sha256=KylM42hSOfvhT8ubTXCqFzOL8HcMaQJ_72S0ODedcd4,1226 +torch/include/ATen/ops/matrix_power_native.h,sha256=f9blx8Wi0WJVRgZ4mntZZ6Pk7nz0Q_E4ee1hrXG2le4,842 +torch/include/ATen/ops/matrix_power_ops.h,sha256=-oxUv7NCbE62rMAXBr6ow-C2QCpje87cccjY-LyPk5I,1913 +torch/include/ATen/ops/max.h,sha256=VueS3Wc_rR_ErTpaV97KyVPXa78fFfR5nFvtW3jgvgY,2952 +torch/include/ATen/ops/max_compositeexplicitautogradnonfunctional_dispatch.h,sha256=HXAIBO5ZdfZ-NErR0BDkLAowo3MIanL3FkNR0Li9J_A,1099 +torch/include/ATen/ops/max_compositeimplicitautograd_dispatch.h,sha256=ELWi_sf2k7s0B6WVHoHPHZcSKpercDH5EU1HLGeltJ8,1244 +torch/include/ATen/ops/max_cpu_dispatch.h,sha256=5eqgzJt7R4bFmmsHH325G0r2VSWpg_YQzXpxJEoZSaQ,1546 +torch/include/ATen/ops/max_cuda_dispatch.h,sha256=47h3noNEiY9uY_gZduq0P0Jv2S_OHNWQcH-aYgKd6KI,1548 +torch/include/ATen/ops/max_meta.h,sha256=BNDgonEkZb_vWkzEq7PnTm9a7qpMbEIXEKA4LZ3Bs9M,1291 +torch/include/ATen/ops/max_meta_dispatch.h,sha256=8PIbjPimZqMXco05kwJkH57gH-GPESaB-vYIFnRVJMw,1346 +torch/include/ATen/ops/max_native.h,sha256=kjlOKetOzp9SZwpHUyWMBjh0GTy_NScik_qGkSQD1tA,1479 +torch/include/ATen/ops/max_ops.h,sha256=6kFEBqmqhS0i0dce06FwHhjRqHUoWsJ3S_PlxWVIb_U,4650 +torch/include/ATen/ops/max_pool1d.h,sha256=3nLsOLETqlqJHxeayvmmEo7M9G6eQW46kMp9AyxsVxE,1188 +torch/include/ATen/ops/max_pool1d_compositeimplicitautograd_dispatch.h,sha256=Owf8WVpvZsd6SZx-K8LtitQzbFPfP3x4AxVA5WUWnP8,1155 +torch/include/ATen/ops/max_pool1d_native.h,sha256=PIlVY8KDWNiTtwDT1RrJ-Z1hygsq6W6DIEDYvvXcdOU,867 +torch/include/ATen/ops/max_pool1d_ops.h,sha256=HDcdY2PyLvDhF14kR-px9cCTgh8yANh4fJq45f5RODU,1634 +torch/include/ATen/ops/max_pool1d_with_indices.h,sha256=Tp0jZ0OcxG3IjVyobYp6KvcZoD76R_k_RUcskzAbuSA,1275 +torch/include/ATen/ops/max_pool1d_with_indices_compositeimplicitautograd_dispatch.h,sha256=J4DwKwdv8lDc_UQN2CIUCe6BeEk0RgkGCowCZs-Tpi8,1193 +torch/include/ATen/ops/max_pool1d_with_indices_native.h,sha256=SpLGau3sXnn92j7aZ7blLbQ7GLhPM3dzNmY3nO30vAA,905 +torch/include/ATen/ops/max_pool1d_with_indices_ops.h,sha256=tkZs4MuIebTLJ-w1HUFLVfFqGkwVxZvB3X63D6Cta3Q,1758 +torch/include/ATen/ops/max_pool2d.h,sha256=73-9YM7nwbkayq09YNV1lTWLIe8abeWFNYWldNZOr6k,1188 +torch/include/ATen/ops/max_pool2d_backward.h,sha256=HOeg3hpbmfYolMD7Z_7eH_rHzbedMVnz_I3EV5-G-Us,2436 +torch/include/ATen/ops/max_pool2d_backward_compositeexplicitautograd_dispatch.h,sha256=7aFxvT8NWsyoOSje32j0Qjp2BvYRB583zInkYNPWIFA,1464 +torch/include/ATen/ops/max_pool2d_backward_native.h,sha256=lDGs7P8EAQje5FoajByzdOQsRurBYis060R2RjQB10g,919 +torch/include/ATen/ops/max_pool2d_backward_ops.h,sha256=v_1jOxKJEyL70E_lGOri-42XLY8WHjxrb1us1iduAPA,2909 +torch/include/ATen/ops/max_pool2d_compositeimplicitautograd_dispatch.h,sha256=4bRNk_juojizScxd8SSSYrMtp_R4S231zdVWE8GvVgU,1155 +torch/include/ATen/ops/max_pool2d_native.h,sha256=F9EUWLoNlKvNEMxiTKQCjFPKEedoy6gBz-I39DXBVt0,867 +torch/include/ATen/ops/max_pool2d_ops.h,sha256=_Qnsd_7AQNZNL5SPzC9S0u2ntaDZDeG3IruAGNTKsQs,1634 +torch/include/ATen/ops/max_pool2d_with_indices.h,sha256=wJ_eYaqc9gkjm8KOFWjc4nlZG0yykKBgBL5YrF5WA8w,2500 +torch/include/ATen/ops/max_pool2d_with_indices_backward.h,sha256=p3siom_wNOWepDPBXYxuD2q1fKF6LSlLuU5YuxV1W9g,2730 +torch/include/ATen/ops/max_pool2d_with_indices_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=3EQunEvLzt83_Mo9wuoTg11wBWMTSj4AysdKDy9TgQc,1250 +torch/include/ATen/ops/max_pool2d_with_indices_backward_cpu_dispatch.h,sha256=n0Qk3hxtHaigNSCh0Gc-cX3fsPUALgCiEWGFSNphA74,1763 +torch/include/ATen/ops/max_pool2d_with_indices_backward_cuda_dispatch.h,sha256=C4VeX5BS7hQprkWg3e8m7tIUZJvpCHr8TGhsFU9e0Xw,1765 +torch/include/ATen/ops/max_pool2d_with_indices_backward_meta.h,sha256=1H63oFP4OxZPMUaXcvBZn1ne2kzKQWvsSYNK54JruvI,1027 +torch/include/ATen/ops/max_pool2d_with_indices_backward_meta_dispatch.h,sha256=KlHDoAP_PPOhUBRFlXWU5IlCxQLQDloYnhDIg9JcwfI,1765 +torch/include/ATen/ops/max_pool2d_with_indices_backward_native.h,sha256=0cLzUSly6lHWsQewAdDZPwHv5VmpgE24z5FXyCrQrZI,1504 +torch/include/ATen/ops/max_pool2d_with_indices_backward_ops.h,sha256=7-QLg3POJ2k9gW9pYrxoxgOm1dApJdV98jFWSqPRRGw,3187 +torch/include/ATen/ops/max_pool2d_with_indices_compositeexplicitautogradnonfunctional_dispatch.h,sha256=fRT-3r6eZWGGrB3wTqldhlfYjQzylGwRgbvmgT5-hpg,1219 +torch/include/ATen/ops/max_pool2d_with_indices_cpu_dispatch.h,sha256=7bNB-17Ht8XSHAwI1bVVIACEUGy35qJpi1_ZWZL9TM4,1691 +torch/include/ATen/ops/max_pool2d_with_indices_cuda_dispatch.h,sha256=bax5HkuBGFlPKpwLSk6PjRHoIzGkT7gTnw3zPXmXOqc,1693 +torch/include/ATen/ops/max_pool2d_with_indices_meta.h,sha256=K-dBuTS5cjtPfm0exSzqbhED72MZ9UDcbHT-Uymp7GY,958 +torch/include/ATen/ops/max_pool2d_with_indices_meta_dispatch.h,sha256=BVXVjT4iuhk-b5UyH22LYBLGmi01iLgAlbj9pg_4gng,1693 +torch/include/ATen/ops/max_pool2d_with_indices_native.h,sha256=71QmJhhxp_LBOXYk3NHvNX6tewGGlxuoCDterf0PAjc,1381 +torch/include/ATen/ops/max_pool2d_with_indices_ops.h,sha256=UJ-qIvjbH03fo3D05uMjkoj_edto82xV0pIp7aG8uxw,2983 +torch/include/ATen/ops/max_pool3d.h,sha256=gWR3wqBoVSV5JTE4zo8qHQ_8tcCSa9YsfKOGGmWoqf0,1188 +torch/include/ATen/ops/max_pool3d_compositeimplicitautograd_dispatch.h,sha256=uWPnZeRFJCRvisbsPGmVA_MM36OHxRUARFTaWooAcxU,1155 +torch/include/ATen/ops/max_pool3d_native.h,sha256=zwc6Kjp7HG2YfbCk6FL8t7ddJ1glXQcOt_aREmansVI,867 +torch/include/ATen/ops/max_pool3d_ops.h,sha256=MyQ9hSsLCk_bOrZmfphMceF1sCO41SCuQH_FBlXePwM,1634 +torch/include/ATen/ops/max_pool3d_with_indices.h,sha256=bbRLAlAWoOemhxBjvJAA6yKVEt4JjvP7gTPB9oN2ULM,2500 +torch/include/ATen/ops/max_pool3d_with_indices_backward.h,sha256=eT533Cy4gRumLT5B4HbZoZ9Y8unad6tU9b-Bu78XAT8,2730 +torch/include/ATen/ops/max_pool3d_with_indices_backward_cpu_dispatch.h,sha256=XDYGz30WNKWS4IHAzQsgh5mWFWCjAtLJs1BNyuMVLf8,1763 +torch/include/ATen/ops/max_pool3d_with_indices_backward_cuda_dispatch.h,sha256=vRwyLOQtrbJXPV2o8NWKXrRVS6NrsFKvB1JOCM5y7gA,1765 +torch/include/ATen/ops/max_pool3d_with_indices_backward_native.h,sha256=h354nw1axCC7D4mjmN7aVQaA3cDND52aIKW0CilX7QU,1796 +torch/include/ATen/ops/max_pool3d_with_indices_backward_ops.h,sha256=sjgnQZt-grP561wvS9woaJ8irMck6ERjDmuQwG-B5SQ,3187 +torch/include/ATen/ops/max_pool3d_with_indices_cpu_dispatch.h,sha256=IXn52oYMyeg2jTnpT7dbfMKR21rnyCImAsrDZOcOAOc,1691 +torch/include/ATen/ops/max_pool3d_with_indices_cuda_dispatch.h,sha256=hkXwUEl7iI9etz5kMSMuUkmhbxdJrm6WtjQ6nQFiw1M,1693 +torch/include/ATen/ops/max_pool3d_with_indices_native.h,sha256=fZDueaRIdMVuNSttagl4eCUBIOPRE3yVCW42GpipEiM,1680 +torch/include/ATen/ops/max_pool3d_with_indices_ops.h,sha256=XAtkzJTtnbXmMGkyh0zexvRJ_f6ExcB8iYl6JGZB290,2983 +torch/include/ATen/ops/max_unpool2d.h,sha256=SXqQHj_pfv8qhMqfdvC4_ugC6dzdQVJ84MUz9HhgT48,4687 +torch/include/ATen/ops/max_unpool2d_cpu_dispatch.h,sha256=kFQZz9kAjLOaAPAZvkrRHCW8QToKLGQKlnErtReyxZU,1753 +torch/include/ATen/ops/max_unpool2d_cuda_dispatch.h,sha256=cnEIQEG4PmJQtJd1rsagUC-QNzZoZyaAob62xOhu0aw,1755 +torch/include/ATen/ops/max_unpool2d_native.h,sha256=RMDXXGJUZ7TJ-xtvMgXWXOKJZZdP8FuAhppC1wYjJ6Q,1254 +torch/include/ATen/ops/max_unpool2d_ops.h,sha256=o4Mr5UYs9sCNU9cXNPWzMNEbhlgZu_ktyhPlSL3T5AM,2241 +torch/include/ATen/ops/max_unpool3d.h,sha256=VfwcR-ZKW3i81SNiV8c5kIFybRG-ZW1LDVfiMWkpKFE,5665 +torch/include/ATen/ops/max_unpool3d_cpu_dispatch.h,sha256=o2SA5rvkgBRyoYOeoQFMwtXjW8sFKBN65R-eAOIk2ek,2047 +torch/include/ATen/ops/max_unpool3d_cuda_dispatch.h,sha256=uQoqVl7msihpXZ4KC4_2o6fv8kOn3fWamV39jboB1_Q,2049 +torch/include/ATen/ops/max_unpool3d_native.h,sha256=IZ7PFVKVBmMqDe2yagvU4LkmVTnBD4IJYGhb0VrJzPE,1450 +torch/include/ATen/ops/max_unpool3d_ops.h,sha256=gLtHwsWUnr2dNVOIxcDDKGJGvAFRKWi6s3R0-3_rBuo,2567 +torch/include/ATen/ops/maximum.h,sha256=zT515n3Qi4kj6tSiLH8DMN5hWsLANZttowF3GxaO1Js,1432 +torch/include/ATen/ops/maximum_compositeexplicitautogradnonfunctional_dispatch.h,sha256=4flFPhuJ9-ev43Hm6d_oU4jC6c1IzKjoSd5Yl_JMfNU,1071 +torch/include/ATen/ops/maximum_cpu_dispatch.h,sha256=8TAv6qXCmqcxHNHQrDLzcCqWF0dMqxZPyN7t-E763eo,1212 +torch/include/ATen/ops/maximum_cuda_dispatch.h,sha256=1kw9IfbFRVgQlmE2XT6FonYyyp4xfeB9zGpUCgo1O7w,1214 +torch/include/ATen/ops/maximum_meta.h,sha256=OQssgHUq5hhgOZP-Fold8yuif3_5Q90zCvxC8WFo_uI,848 +torch/include/ATen/ops/maximum_meta_dispatch.h,sha256=iVnmEUJwht-AQ1nhTnyq65uKHzqfvcIABznPC_mHBpc,1214 +torch/include/ATen/ops/maximum_native.h,sha256=jPnmvvnlaxQdnHcJG1evFw7gliZdtJrIdg_BLr8wCkM,879 +torch/include/ATen/ops/maximum_ops.h,sha256=M7mjEkAzeqiRQ2rYhvx5k0Y4trrGzWHcdYcOJoYIY9U,1979 +torch/include/ATen/ops/mean.h,sha256=koTo_bJuakcpeoSDzTIErho98Ld6GCz8bZ9Q7r6Y24Q,2568 +torch/include/ATen/ops/mean_compositeexplicitautograd_dispatch.h,sha256=kONrR20k3MH6fuRoctEvnhCCDzYvoeF0DmrKhdM0jRI,1316 +torch/include/ATen/ops/mean_compositeexplicitautogradnonfunctional_dispatch.h,sha256=PTi35X_c5u6Ufv808yBTPyQq3cb_FigOAv7Bd1kXuAI,1145 +torch/include/ATen/ops/mean_cpu_dispatch.h,sha256=Wexg4e0TlQsSCgKLDs08EjWV682boy6u5d0Xvx6WJbE,1413 +torch/include/ATen/ops/mean_cuda_dispatch.h,sha256=ZAAwc7aSRD_meR_sT3D8yzOFxF-FhcPMflHuIzp0fyk,1415 +torch/include/ATen/ops/mean_meta.h,sha256=cVslIWJxSriwnjCQ8pi3tNaYC6gPhl8dP68ggE5B5zk,905 +torch/include/ATen/ops/mean_meta_dispatch.h,sha256=C4KAHwNCxwZbMJLaKii2r4tn_jglUcWAW0i08tLGIzU,1415 +torch/include/ATen/ops/mean_native.h,sha256=0uDSSCVXNyESNAbnOXzF8AcmEr70QDqo4vdEcAr7CEs,1498 +torch/include/ATen/ops/mean_ops.h,sha256=Mzj28-vJ9b34_xJNsbNkp7M6HjUcrGeUG_9_Ocwte98,3742 +torch/include/ATen/ops/median.h,sha256=DJvIV3rR8L3vXIsG-d5nUryU5GXn5HGOQ_ADbrVDw1Q,2346 +torch/include/ATen/ops/median_compositeexplicitautograd_dispatch.h,sha256=TI_cc_DVPuPHPcM0OnmGt1yZUIwIt8YkpfYfkCZz-IY,1233 +torch/include/ATen/ops/median_cpu_dispatch.h,sha256=hlYLTs9fsev6FhdQ_4TbjWCZKCR05_Yg6oIpNKYZ3ME,1295 +torch/include/ATen/ops/median_cuda_dispatch.h,sha256=1qEEeIs8xcWESIdEKkYEk3lVH2LhUejoMhFb2T2OTC8,1297 +torch/include/ATen/ops/median_native.h,sha256=mcRptaWHVLLr5Q4DbrDxLpqetsf3QtEU1Cp6WKHRp7I,1306 +torch/include/ATen/ops/median_ops.h,sha256=AoJkP_bCQd4KMkAo2HVwzNjSXXdZ5U7by7hSe7qM-bE,3416 +torch/include/ATen/ops/meshgrid.h,sha256=1ltTaB7X83B4AEsR6imhOHMJSzg_frPMqgNQCEzbQ3g,1160 +torch/include/ATen/ops/meshgrid_compositeimplicitautograd_dispatch.h,sha256=HxALCti4vu7xjxQt-ZOw3rgvMUO1kYOElv3A7DIKO8M,1131 +torch/include/ATen/ops/meshgrid_native.h,sha256=LBo7w0u98i3b7Lez9p6l_5stVlmyjqozMECwFulp6bc,843 +torch/include/ATen/ops/meshgrid_ops.h,sha256=1f1FUppy8pFB_V9LTzPl4omXhz7W1zRwrxB_Ov2ktFc,1930 +torch/include/ATen/ops/min.h,sha256=LhTcmYJZ69mYmwhDHY-OE_-t_XhD-ilXb643a0ru6hI,2958 +torch/include/ATen/ops/min_compositeexplicitautogradnonfunctional_dispatch.h,sha256=qyB7Evfb7kH0qzYBPggbSLSYYzh5mBYWfN2vTlRavuE,1099 +torch/include/ATen/ops/min_compositeimplicitautograd_dispatch.h,sha256=XyKTXh0xNSjUGGESNI_Ylp5H2Q4V79Z7MpFjA_C3aWU,1244 +torch/include/ATen/ops/min_cpu_dispatch.h,sha256=Gws1QIdqhoEhHohdeUJfIIJZ7_W6wNUAqdSYJJWC3aM,1548 +torch/include/ATen/ops/min_cuda_dispatch.h,sha256=uGwQzJQZOD43VrYLsrcdyWBlNRPjqSzPJCQ1Zj_fN-M,1550 +torch/include/ATen/ops/min_meta.h,sha256=L7c2brEm4cYFh4twYgUbGGwpyPSrmtB0qfzMR0tsJbU,1291 +torch/include/ATen/ops/min_meta_dispatch.h,sha256=Gx5ifqW6UYhdbvNaAROn7uTitXGrn6PJYyL9bbcEZmI,1348 +torch/include/ATen/ops/min_native.h,sha256=hMh1HC7OFeHEX-nDes9XWuq7TAZqMHWvYXebVpT-jts,1480 +torch/include/ATen/ops/min_ops.h,sha256=RC41LPuqJtcDn-ld-QSBGxWiMc1QUThkam0mNq6c2Yk,4653 +torch/include/ATen/ops/minimum.h,sha256=FUDt-lh6oFoSDYPj1iAXt9sLE8Tbw15X9djlvu4nTyA,1432 +torch/include/ATen/ops/minimum_compositeexplicitautogradnonfunctional_dispatch.h,sha256=mB-yGMQp0Hcn6Bc7qYvgekts81y9jC-_m1ji_QmvU7Y,1071 +torch/include/ATen/ops/minimum_cpu_dispatch.h,sha256=3PHqMoGnakLvjSxPT2nSyVFk60XeL3I1PZHBttblF7U,1212 +torch/include/ATen/ops/minimum_cuda_dispatch.h,sha256=UycuTLvdhR0yBFccCvyujK-4RyK6pi9yfvJdi47bk9I,1214 +torch/include/ATen/ops/minimum_meta.h,sha256=7G43dicDfmmT7_vpOelCnfB93-EnL75tFUC7fu5vfRU,848 +torch/include/ATen/ops/minimum_meta_dispatch.h,sha256=DL-1qyViExwJqCumuADsyDpIcUlXr4rsalR3MtbadfA,1214 +torch/include/ATen/ops/minimum_native.h,sha256=VtLsZ2TFJlzItjCO0JJFNzopkUbFD2_Wgt-sEwePb7Q,879 +torch/include/ATen/ops/minimum_ops.h,sha256=wxxlHeTRW7dEzAmQOJyf-rZzPrqAL8SnRLjGOOoobjg,1979 +torch/include/ATen/ops/miopen_batch_norm.h,sha256=DzyIq51M_3hkcQ1OM_rRvbUdH8RO8oC-xatNRbCL9AU,3134 +torch/include/ATen/ops/miopen_batch_norm_backward.h,sha256=3yDrXJGrJ7knlKoeJWAJGkjgO7f6QXkIDDmvZt54PTY,3275 +torch/include/ATen/ops/miopen_batch_norm_backward_compositeexplicitautograd_dispatch.h,sha256=96k4AY0M1CvRNRIa02hOjCn69tXjTHxyfiQaZpRKLvo,1855 +torch/include/ATen/ops/miopen_batch_norm_backward_cuda_dispatch.h,sha256=pO6zsV44b4eCxlWbAzx5E4_KoKJ3vfekfOyvFPIfwJs,1300 +torch/include/ATen/ops/miopen_batch_norm_backward_native.h,sha256=BBkH9I9wCSsaXEUExxh8AvH0jetqr5MIdWxsEHskhro,1499 +torch/include/ATen/ops/miopen_batch_norm_backward_ops.h,sha256=WaFU082P-coTiq6fnzyA3iezG4qFY2m9zGG77BHh9W8,4060 +torch/include/ATen/ops/miopen_batch_norm_compositeexplicitautograd_dispatch.h,sha256=rXefiC1_CAOnPW5S2r3LAEzRYG1WADt-jkF9HwifNvo,1771 +torch/include/ATen/ops/miopen_batch_norm_cuda_dispatch.h,sha256=8eOzvAf3888L7tq9Gzrn2wefADtHv8FyVw6XpxfNfjY,1258 +torch/include/ATen/ops/miopen_batch_norm_native.h,sha256=FJc31fcwy8OKBiqQ0knk2HuymsbdztO_rvNdg-5pIWc,1415 +torch/include/ATen/ops/miopen_batch_norm_ops.h,sha256=DobfZ0Tu_CkFVQBLr1mxMhiy4WdMpxuy2NmMPRsJlh0,3800 +torch/include/ATen/ops/miopen_convolution.h,sha256=vjoINAGOchonGjck1FZKRpJFUYRz4xUFBsv5G9d4b80,8131 +torch/include/ATen/ops/miopen_convolution_add_relu.h,sha256=F0y251lqFpkSQqef62fejd0fADpCGO5ZKBx-p4-QKHw,3226 +torch/include/ATen/ops/miopen_convolution_add_relu_cuda_dispatch.h,sha256=bu5l12qrnHxIQVwNveklWAoBAo03dppr-7nyemlB8wM,1545 +torch/include/ATen/ops/miopen_convolution_add_relu_native.h,sha256=gpPtRnqa0sH34uJ_M_uCSg6hm15hViZwGFwJpvJPZkU,976 +torch/include/ATen/ops/miopen_convolution_add_relu_ops.h,sha256=seInneUD30AZD3gHY01ukWrXIsyfmaA8L-FuUfppcDE,2069 +torch/include/ATen/ops/miopen_convolution_compositeexplicitautograd_dispatch.h,sha256=lPwmtmEHqU3aVSYlLsTpwQEwbNt2hZU25ABprebKKCo,2156 +torch/include/ATen/ops/miopen_convolution_cuda_dispatch.h,sha256=1HVsX8rlHcDcqVP_7KHpM2uu8bJICXQKWoGOlg5RZII,1469 +torch/include/ATen/ops/miopen_convolution_native.h,sha256=muxW44VLb-MeR-SXgECLJEU-LdXQpHM7DvJQhSButyE,1247 +torch/include/ATen/ops/miopen_convolution_ops.h,sha256=wNEFCcc4tyCAx_lWcIXiDWxiWMWKgp_fuUrLnzyu1lE,3279 +torch/include/ATen/ops/miopen_convolution_relu.h,sha256=ZmSOqx-_t7rIjCkWBBTJDbpbByfXkDCeP2i74ZVEB-4,2832 +torch/include/ATen/ops/miopen_convolution_relu_cuda_dispatch.h,sha256=dweI5j-729KqjFBMzvU6C0I8hRMEBWBy_MQP-zAS03k,1407 +torch/include/ATen/ops/miopen_convolution_relu_native.h,sha256=g4vie8NZArMRsAPoAYFt4lvGZ-tajxyc8ySJf6ETe7Y,907 +torch/include/ATen/ops/miopen_convolution_relu_ops.h,sha256=6pWF6RDYmS9-uxdWvjw8jRlfLDs-2qfNI699kIhcEPI,1845 +torch/include/ATen/ops/miopen_convolution_transpose.h,sha256=YDtjkwR_s7KHHQbj3isZwUzUwkwoOkm6nL35t_xtlV8,9347 +torch/include/ATen/ops/miopen_convolution_transpose_compositeexplicitautograd_dispatch.h,sha256=eYIHDkImHd-OHjf8zEtMIdwTeVyV4hq0z_Wsu6JiQt4,2332 +torch/include/ATen/ops/miopen_convolution_transpose_cuda_dispatch.h,sha256=iKQTuQMhQEdqdfslvCpsIzfDXKxcO2uMoXALoIeE9Ws,1557 +torch/include/ATen/ops/miopen_convolution_transpose_native.h,sha256=J9phkFMTErsYNOWG81I87uWBYtxXZyTB9ov9zveonjY,1335 +torch/include/ATen/ops/miopen_convolution_transpose_ops.h,sha256=Yvsp-RkddHerw5uNhoy8vyOHsYXPehBaDDjos8jwYW4,3575 +torch/include/ATen/ops/miopen_ctc_loss.h,sha256=odgd1sX6iSsNiFMYvoKDOVc2rJldKfBVV7PQeXB2UTQ,3189 +torch/include/ATen/ops/miopen_ctc_loss_compositeexplicitautograd_dispatch.h,sha256=v2Pe8eN6UGFUB-3KFgJShNB74GhSJ9IiFlSdS_oSLv4,1535 +torch/include/ATen/ops/miopen_ctc_loss_cuda_dispatch.h,sha256=c0_BQjXyFgGTgx0vkuOHaMANpmJW5iIggZ1v8Mjw1Bg,1406 +torch/include/ATen/ops/miopen_ctc_loss_native.h,sha256=oE8H3iITSdnswboq2r0pMt50fEJ8TT9wKmvc7jyekEQ,1452 +torch/include/ATen/ops/miopen_ctc_loss_ops.h,sha256=ew_NNjkxVpI1nw5wTykRzhi8h0dvcAiGohVHd33yL3Q,4235 +torch/include/ATen/ops/miopen_depthwise_convolution.h,sha256=z4zSRFUpNSv2s9cWEzxzhCgX79-aZ670McIPZsFhdgw,8441 +torch/include/ATen/ops/miopen_depthwise_convolution_compositeexplicitautograd_dispatch.h,sha256=1Kgn6-PIhsoXkDB5TXE8Itp3qaZBf9wRiwoF1h1S_E4,2196 +torch/include/ATen/ops/miopen_depthwise_convolution_cuda_dispatch.h,sha256=9DpqV4lwcaMN5eQ_V0RWrJm1DwlYb_KQx5FbceSe1e4,1489 +torch/include/ATen/ops/miopen_depthwise_convolution_native.h,sha256=TdogTUSlfr4N7EZfpzgneSH7UVftQOmpp7Oaoq-jS34,1267 +torch/include/ATen/ops/miopen_depthwise_convolution_ops.h,sha256=qiJwgD-5YiFL3NCsYbqh7FYJxBFflB-TCF_Pbes0hos,3339 +torch/include/ATen/ops/miopen_rnn.h,sha256=BV3xDqKXPpUpsVqkp9Iwv6rF_cxXVufO_LkRdr9Ae-c,3964 +torch/include/ATen/ops/miopen_rnn_backward.h,sha256=zfGDCwt7FjFUgZ3dfUhkYzDUhBte-KBIxHRDjF5sC6c,5086 +torch/include/ATen/ops/miopen_rnn_backward_compositeexplicitautograd_dispatch.h,sha256=uLUpCNO2POWiLhKPezkl3M56qmdG1Bzru6MdAowaX2U,2393 +torch/include/ATen/ops/miopen_rnn_backward_cuda_dispatch.h,sha256=5FF8zP9_dtYcDRPMUtQ5ZlS_b3AFrw55KXIa9mnXYv8,1622 +torch/include/ATen/ops/miopen_rnn_backward_native.h,sha256=blqOkjdqVyyBhhXMQLTfEaMUFZpE7kOkTozpNGVpAMc,2090 +torch/include/ATen/ops/miopen_rnn_backward_ops.h,sha256=lno9-oinrU5jZBY-vqSC6GeJLW6zis3XCSkHwFeX05Q,6001 +torch/include/ATen/ops/miopen_rnn_compositeexplicitautograd_dispatch.h,sha256=CY8RbdBm-kZILZUbTfozNnihIPqdWbNuMtjdp95SQFA,2039 +torch/include/ATen/ops/miopen_rnn_cuda_dispatch.h,sha256=A-dCGCveAi_2BouFnROF1uIXAsaP-oxoprLqYiCChS8,1350 +torch/include/ATen/ops/miopen_rnn_native.h,sha256=dsPfWLw9OurpYZ8YkPeLWUXbIGk7WtGVbOmf1wfrnPc,1641 +torch/include/ATen/ops/miopen_rnn_ops.h,sha256=WO9BMnhKxvr2Qt7-6OsgiyM6T33tTZ9IUQugDRHogio,4608 +torch/include/ATen/ops/mish.h,sha256=AFjehP8XrwGy8WKYdbziRBQ60Ncia0qB64XsfQpN9Gw,1397 +torch/include/ATen/ops/mish_backward.h,sha256=oazQNMN-gWnv-0Q_yHWd78lrwqeV0GhcvZCJ8q9PLp8,984 +torch/include/ATen/ops/mish_backward_compositeimplicitautograd_dispatch.h,sha256=6UTmKYnWd8vGflhzzvoeboxLsAvia9ruf90SF3hlfg8,1057 +torch/include/ATen/ops/mish_backward_cpu_dispatch.h,sha256=zxh0po5wcWMfIbKAuqSjY1mAXLmKzJRqwGC-Mp81-Dc,1013 +torch/include/ATen/ops/mish_backward_cuda_dispatch.h,sha256=57F_iF1FtW6fnutPijCTzlfqWYHphv6fiIpO9o5BAvk,1015 +torch/include/ATen/ops/mish_backward_native.h,sha256=tkq9H10HLcBUS4VUfFt37tymSdUI8y3bqgblB1uQG7U,867 +torch/include/ATen/ops/mish_backward_ops.h,sha256=ONPY7WZadEAeyIKY_RAi_oReVWhFQKDiQPDpIJB7tZE,1336 +torch/include/ATen/ops/mish_compositeexplicitautogradnonfunctional_dispatch.h,sha256=RxMl1vUDxTwFc2ZV5YVCNQYPhX2_PPMle2Mn5s35EF8,1091 +torch/include/ATen/ops/mish_cpu_dispatch.h,sha256=630vF_vnjCAZvghVjOoGupknZRAJigMVse4idBc6fXI,1174 +torch/include/ATen/ops/mish_cuda_dispatch.h,sha256=hGPq3lVyfahqnfmRtosdkVMn3JeTFGffDVs5fWKX-Dg,1176 +torch/include/ATen/ops/mish_meta.h,sha256=lvJ_U-U9AP5A75rq3IY5MlFGDY3HI_P2j5BgAd6qXG8,819 +torch/include/ATen/ops/mish_meta_dispatch.h,sha256=ByUkAEkUbVfDpf3Vzpdt73oOeVjKih7XqM2edYQ9IdE,1176 +torch/include/ATen/ops/mish_native.h,sha256=1fryZdZzRlotHDfMaUEDGcRFcFWhpcfht6jPVv2U874,844 +torch/include/ATen/ops/mish_ops.h,sha256=2ThhdTYtU8Waljdw8Lu5rxoOppjWy0MBWav3Ugsjgeg,2282 +torch/include/ATen/ops/mkldnn_adaptive_avg_pool2d.h,sha256=OiItyJQkLXpYwzV0Z36fhIZKdsp0ah0cVlc3oSeVlVA,1667 +torch/include/ATen/ops/mkldnn_adaptive_avg_pool2d_backward.h,sha256=KGy2UoFkafW_HiVdiC7Zimv6XYGi1TpFcqHq9nU4jvQ,1766 +torch/include/ATen/ops/mkldnn_adaptive_avg_pool2d_backward_compositeexplicitautograd_dispatch.h,sha256=Bev411GqygfeQ9aCzGS562-oTYa7944R_gLt0aGl2WM,1243 +torch/include/ATen/ops/mkldnn_adaptive_avg_pool2d_backward_native.h,sha256=inVq12MBAeuvAlVZ6FSMVfu_RDOmYvc_uPU-oIK0Sko,930 +torch/include/ATen/ops/mkldnn_adaptive_avg_pool2d_backward_ops.h,sha256=RepvNEOE21bnny-bPJOKhFEAs22KX9Qqu6P4BPg2jf8,2183 +torch/include/ATen/ops/mkldnn_adaptive_avg_pool2d_native.h,sha256=-N6Fuga_L1PvnQiCYlSxn3M-JUnIe2FyHJ-Tb3i0xw4,906 +torch/include/ATen/ops/mkldnn_adaptive_avg_pool2d_ops.h,sha256=okUu1qwLD6H-Gp6mK8L1so4CQv_vJN6doIEH_AV6pnk,2111 +torch/include/ATen/ops/mkldnn_convolution.h,sha256=pIzmpo745a8fcMCEbNwiJm3MTCh1hYHsm45ukK8weAM,7171 +torch/include/ATen/ops/mkldnn_convolution_compositeexplicitautograd_dispatch.h,sha256=HhkZadR3zIsJq3gEdBAL-p-tgKgwFNouBH2CWslNLFI,2487 +torch/include/ATen/ops/mkldnn_convolution_native.h,sha256=jMTdW5qKqbDaD_FHR-5hXb6685MxmW4dJPhjVeYmkVI,1175 +torch/include/ATen/ops/mkldnn_convolution_ops.h,sha256=t89eTIbf15QKipz7_loD4bNrdpT74CK-uyu1QQkaMTw,3039 +torch/include/ATen/ops/mkldnn_linear.h,sha256=UiM5a86XJt1Ot63bRKeQCo0cnEUbW7Iuelh7Ugz-CAc,1708 +torch/include/ATen/ops/mkldnn_linear_backward.h,sha256=cJ9Y07b1178QxQaEOWOhshOhVUIPFbUcm5lOIPNuiuk,2350 +torch/include/ATen/ops/mkldnn_linear_backward_compositeexplicitautograd_dispatch.h,sha256=3Yzy_I744W-26cxZ4yNiUXo2lSvQvOC04eTuYXX1pfA,1497 +torch/include/ATen/ops/mkldnn_linear_backward_input.h,sha256=3Xcp-aDoKyQ1kMWOKzlWrLTX2g7gBsV0LD3RclxYBqY,1888 +torch/include/ATen/ops/mkldnn_linear_backward_input_compositeexplicitautograd_dispatch.h,sha256=kvUTeh7owlnWP8i9R1MQIR_bHtO_wtNdz1L7TIhQY-I,1289 +torch/include/ATen/ops/mkldnn_linear_backward_input_native.h,sha256=plcBsrmnt728jmzYItaThBI1coLwIpLuE_9RoHXH1mQ,976 +torch/include/ATen/ops/mkldnn_linear_backward_input_ops.h,sha256=fi5QTmYklcRXSw8xN9xcP9xS1RjFKrZs6HqGITOf7T8,2335 +torch/include/ATen/ops/mkldnn_linear_backward_native.h,sha256=whQoWTcVfM74ULBrKr64eTwRSMLpJDIfNjKb7Vz_SCo,1141 +torch/include/ATen/ops/mkldnn_linear_backward_ops.h,sha256=xo_LFk3xoEQA5B0umrPspLRiz-nos7I7aclanXRcdIg,2918 +torch/include/ATen/ops/mkldnn_linear_backward_weights.h,sha256=izqEOKt_f-NmHVlCXW1XgK67Fy2g5R6ZhTEKlISxG6c,2238 +torch/include/ATen/ops/mkldnn_linear_backward_weights_compositeexplicitautograd_dispatch.h,sha256=MnJpoOPV_4s7qiyKUF7O2wIC-30t0stazGCjtSJiHp8,1421 +torch/include/ATen/ops/mkldnn_linear_backward_weights_native.h,sha256=hG2ejd5PYL_HIur_5dO5NCsnkSfNkGZ8AxTkwcGmcm8,1086 +torch/include/ATen/ops/mkldnn_linear_backward_weights_ops.h,sha256=DaKBbwTViHdci2X6H1YbiqYNxjJ8RbCSpY5q7HZe5LM,2715 +torch/include/ATen/ops/mkldnn_linear_compositeexplicitautograd_dispatch.h,sha256=kTPQD0X28lzN7o66r11O_ION_rhcMx9zEiZNTJJuY1M,1276 +torch/include/ATen/ops/mkldnn_linear_native.h,sha256=RLAmNgG_uENDJ_RmfVXjKoqnrH6nE1L3y5F5cvrLb2A,963 +torch/include/ATen/ops/mkldnn_linear_ops.h,sha256=N3Xpcx4bljhcupDc2qFdMnBwZjGUO1-MeT78gaBamBk,2301 +torch/include/ATen/ops/mkldnn_max_pool2d.h,sha256=fNgCUQg7ULU50vnCnVqNIomoUzjbmXl__3-xW4RjuEA,2221 +torch/include/ATen/ops/mkldnn_max_pool2d_backward.h,sha256=53HX_XRwFfb0GCZINWIR5GPzpvI5GS0w43MQWHfEmT8,2665 +torch/include/ATen/ops/mkldnn_max_pool2d_backward_compositeexplicitautograd_dispatch.h,sha256=HhVf22eibCb626ro9LDAH3qtoh1xviyqmeEiBxSjH2s,1534 +torch/include/ATen/ops/mkldnn_max_pool2d_backward_native.h,sha256=ruNDMgY1Ea2q2j38DQl5wZE03pVW9051J4c_RVQlwzE,1221 +torch/include/ATen/ops/mkldnn_max_pool2d_backward_ops.h,sha256=NMVMqNgBTG-MCfVjqWhUak0fsmv2JoVnLWV4pBBtyB8,3135 +torch/include/ATen/ops/mkldnn_max_pool2d_compositeexplicitautograd_dispatch.h,sha256=qOqArPvdIBU1u9fotY3cNKV1d5m5irMGCf_wZl9Qr2g,1396 +torch/include/ATen/ops/mkldnn_max_pool2d_native.h,sha256=Xmn9-8UskhsdtG5P8AUTGykOtIa0ti9B92zHBxx6svI,1083 +torch/include/ATen/ops/mkldnn_max_pool2d_ops.h,sha256=3kffAJ09pk_bQJf_-hRxRiJfEuO2xS6p8prJ8M-kFYI,2689 +torch/include/ATen/ops/mkldnn_max_pool3d.h,sha256=ao7vjFT9PzCO-Vdg4rQIUyzOwZ9hXuIalLVMyS0XWds,2221 +torch/include/ATen/ops/mkldnn_max_pool3d_backward.h,sha256=EPHk_OTMyPHZbaUYtMaF15mM1ZQc2owByXRJpNbLxzU,2665 +torch/include/ATen/ops/mkldnn_max_pool3d_backward_compositeexplicitautograd_dispatch.h,sha256=mbQDgWhRUs4X6vYRhq7iHMYpU4dC06g6qvOA8k7jZOw,1534 +torch/include/ATen/ops/mkldnn_max_pool3d_backward_native.h,sha256=3RVD3zo8L0-RbDMvHizjHgo_vRJUCqjA1GRg-F2qqsc,1221 +torch/include/ATen/ops/mkldnn_max_pool3d_backward_ops.h,sha256=Up52WC47eV5BL4SISUm9CATSjCXxyc7cAWCVgGW3GYQ,3135 +torch/include/ATen/ops/mkldnn_max_pool3d_compositeexplicitautograd_dispatch.h,sha256=-IfwNPIIoYSRWtMeRA2QfzegD-9m5vnWc0Fvk2wp-w4,1396 +torch/include/ATen/ops/mkldnn_max_pool3d_native.h,sha256=rqHag1R7l0YGdqDI8o9cj5rq5LrwGri9QfbgSTTmp_I,1083 +torch/include/ATen/ops/mkldnn_max_pool3d_ops.h,sha256=YPAkfEPUJKqdqzwIG7ZdJDo3AmAedN1uFUPiuy0hI9Y,2689 +torch/include/ATen/ops/mkldnn_reorder_conv2d_weight.h,sha256=fVwB0JWSJESu6XhZNw6qQfAehXyQw4e9Ds6_-DVTMxA,8019 +torch/include/ATen/ops/mkldnn_reorder_conv2d_weight_compositeexplicitautograd_dispatch.h,sha256=meQ4Sp8H4y9_y-vxEe0r9pvrG8STS4EAsLt7DMSGuFE,2011 +torch/include/ATen/ops/mkldnn_reorder_conv2d_weight_native.h,sha256=5QMuRkxBh49EydtkSEj_-Bio1OYoM3qFexDWHzCg-Rg,1155 +torch/include/ATen/ops/mkldnn_reorder_conv2d_weight_ops.h,sha256=j2lxKZol50uzH0Z7v5X5FNbR6_V2XgOFxAPwj9XalyY,2939 +torch/include/ATen/ops/mkldnn_reorder_conv3d_weight.h,sha256=C1l7JStT2V26C0cCgGmVC_0V8BnZPOJokR1UW6mcwr4,8019 +torch/include/ATen/ops/mkldnn_reorder_conv3d_weight_compositeexplicitautograd_dispatch.h,sha256=sqchHmDYYowUUREpxPtvdJFL-upuEj8NoabFHOcU46I,2011 +torch/include/ATen/ops/mkldnn_reorder_conv3d_weight_native.h,sha256=j5bvlXT9O-6sh-yIcaL394gCS3ZFR9a7IzEt4xTambo,1155 +torch/include/ATen/ops/mkldnn_reorder_conv3d_weight_ops.h,sha256=PsQ6HMj_uBqtUOOu4xLfn3mp9RkhOLQiaLfspdyxRH8,2939 +torch/include/ATen/ops/mkldnn_rnn_layer.h,sha256=wGploXOeZ6vPc_0S5YUiTxTs7buQ8QxThMjiMpnz9KI,4009 +torch/include/ATen/ops/mkldnn_rnn_layer_backward.h,sha256=cJUWpRoPXWPdNFmbOOrl0O4tb472A12DVVhWfpEcsaU,5833 +torch/include/ATen/ops/mkldnn_rnn_layer_backward_compositeexplicitautograd_dispatch.h,sha256=p8HQltvfWMF7-sTlxAJETLq0-DjWXa7Dsdu_lfbuvA0,2719 +torch/include/ATen/ops/mkldnn_rnn_layer_backward_cpu_dispatch.h,sha256=yCHGaeZT94CRjIDg_XriGHKWkYNanwzngUZHMco75ws,1646 +torch/include/ATen/ops/mkldnn_rnn_layer_backward_native.h,sha256=TIDqXj0LwGAg1KqYP_IlBAkRP7EnHsCbfMFJ27d9NDM,2279 +torch/include/ATen/ops/mkldnn_rnn_layer_backward_ops.h,sha256=Ot6BYMP6RGYpB0y31LdKKFSWBkp1bCeeJzgHTZ5K6dU,6728 +torch/include/ATen/ops/mkldnn_rnn_layer_compositeexplicitautograd_dispatch.h,sha256=OxME3sMYUcTJpf5jdvLflrSajkdKDoObkKHqyegiJds,2015 +torch/include/ATen/ops/mkldnn_rnn_layer_cpu_dispatch.h,sha256=GS_3o9m7W9VP3jZG2Be9DK156BPIXRyszLL7bo-5xNw,1357 +torch/include/ATen/ops/mkldnn_rnn_layer_native.h,sha256=LhohnHmsehGFnqdd5NTYqfm4heTgsZPteThbd5VT254,1638 +torch/include/ATen/ops/mkldnn_rnn_layer_ops.h,sha256=7EKfwpETw9JMidSN_3u5Xkw_foMBUFPyp4iYw0VWrbc,4591 +torch/include/ATen/ops/mm.h,sha256=3gNlWwyefOpkbyUgTZKoHB6S5_mAZwutJ5fp334sHdc,2207 +torch/include/ATen/ops/mm_compositeexplicitautogradnonfunctional_dispatch.h,sha256=_MUXd_6IczxzeMOszOY0SItU3wsVwZkUPOtKvkckOrE,1065 +torch/include/ATen/ops/mm_cpu_dispatch.h,sha256=E1VTfGRHoiGA7E2iwW9jmhBxv73CufYRFxqEZO0vXVc,1194 +torch/include/ATen/ops/mm_cuda_dispatch.h,sha256=iIkQ6zOSmo7KgRLdt6sFaL9qvbYluS8ZcRq4u4_eK-0,1548 +torch/include/ATen/ops/mm_meta.h,sha256=3eB7FnXI07W3vtgPCWR8LJbrmjXYFVWMZ2y8YMiCMFQ,842 +torch/include/ATen/ops/mm_meta_dispatch.h,sha256=eKK-VTqzq3n1yuISj8NlRiEblX0-g6yYTMUTMaAjaMo,1196 +torch/include/ATen/ops/mm_native.h,sha256=cr4QHsey_2OvORLJyOtK93q66XFFYHYlvcxOsfHUCa4,1668 +torch/include/ATen/ops/mm_ops.h,sha256=SysbA_e3XcMy8NxS3ja3LHkFQ1NSqwEwd-q46dXLXbo,3390 +torch/include/ATen/ops/mode.h,sha256=TNTAf3CV1gaXv94AMWLsMMxZGRk-_hfpndLOenhoqWo,1792 +torch/include/ATen/ops/mode_compositeexplicitautograd_dispatch.h,sha256=-FdiEkK6Xejmz39XPsA21HbUncnuflaV_c-a1oM_Lkw,1284 +torch/include/ATen/ops/mode_cpu_dispatch.h,sha256=7BzFAZ5jENU5rwlGINI0U7hcDS67GDrF3C16w70D62o,1033 +torch/include/ATen/ops/mode_cuda_dispatch.h,sha256=I6zdftYd9saNZLaUEmA8hOkoJ9aiVapbFYAqz1XiXlM,1035 +torch/include/ATen/ops/mode_native.h,sha256=tFQTGeuGSQ4f09avQ1SR2D_WGTrKxndN52CwfasZhvE,944 +torch/include/ATen/ops/mode_ops.h,sha256=sKlDYyFhCrkXWt0k9B0GvbiiSfvRxBznn5P_2LcbT-0,2297 +torch/include/ATen/ops/moveaxis.h,sha256=fbQy1NErRcQmsqxP6jlnxPPFuW0bT-JDI6Xlba1enNo,1270 +torch/include/ATen/ops/moveaxis_compositeimplicitautograd_dispatch.h,sha256=oALMgumCd1Utd5uQNYiJkNYyN7Xg7D6pqJzJ6FIyJG8,1166 +torch/include/ATen/ops/moveaxis_native.h,sha256=Rh0Rgl31ziUhSP_dm-D1FwFwHWzCv67lV0IdGsBkAaU,878 +torch/include/ATen/ops/moveaxis_ops.h,sha256=UX-3CtHhkBFbCAhm01o--SPaGohLglOitnmNrGeq3L4,2063 +torch/include/ATen/ops/movedim.h,sha256=ElS6Y9ZTZB9Z2I-lf8OD0q1zIyxgYQHOnTU5VYfUk34,1263 +torch/include/ATen/ops/movedim_compositeimplicitautograd_dispatch.h,sha256=YNdI1Qtu_bMb5B_B18IzMybgfuaU1wKQH-2477ETnoM,1164 +torch/include/ATen/ops/movedim_native.h,sha256=8irGWfcmRuCxodVwVfhdbdCfhlYLwwti3YuJuJnojXE,876 +torch/include/ATen/ops/movedim_ops.h,sha256=nsHVJU7dm7b0SVbReuHdq3Sfm_GqwE6f2ko07J8JE2g,2057 +torch/include/ATen/ops/mps_convolution_backward.h,sha256=ILVW6FoagQq9pk34CsUGhC4C0gyu0h9uz6Ae2Au02mU,9207 +torch/include/ATen/ops/mps_convolution_backward_compositeexplicitautograd_dispatch.h,sha256=amGbfVKGH_mLcmKN4R2GPZ1C4NELV4oj-PYx-sOocCk,2448 +torch/include/ATen/ops/mps_convolution_backward_native.h,sha256=lJjtscC8hACvHQ7SJ0672UHoXBeh8Fi4pabq-IZCYYw,1058 +torch/include/ATen/ops/mps_convolution_backward_ops.h,sha256=Gvx5GoBoL0SicHjCQat4yzDd46jd--tbh9O8KZAzfDI,3648 +torch/include/ATen/ops/mps_convolution_transpose_backward.h,sha256=8QkQuKhkLcBK_-DFg1RUjvh0zjQKGQFDebxUYfsbwH4,9943 +torch/include/ATen/ops/mps_convolution_transpose_backward_compositeexplicitautograd_dispatch.h,sha256=-pthlgSODIFkPj79UlPXXMRYN0NQ3BMfKSkFlNCFyK0,2496 +torch/include/ATen/ops/mps_convolution_transpose_backward_native.h,sha256=GuM9pOUMyLIs2Q7OTvgmx4VAVpQ9yHkviYF-emb-low,1072 +torch/include/ATen/ops/mps_convolution_transpose_backward_ops.h,sha256=JjPIwJQNbg9lY14m1BDmHi5z5JjULPTKidnV1HeJr-k,3783 +torch/include/ATen/ops/mse_loss.h,sha256=d3zyA-zWvT5r8_Obc7or1234nxnrrAJDb7Ea4al2_TQ,1641 +torch/include/ATen/ops/mse_loss_backward.h,sha256=NVivTBkXJdidUr_xqCXXP5SCIIz0HJdHXhqGc8PVcCc,1941 +torch/include/ATen/ops/mse_loss_backward_cpu_dispatch.h,sha256=ebajBXon_udoiNayYNZ3p0cN_KWrvUchrXhpghY0BHA,1412 +torch/include/ATen/ops/mse_loss_backward_cuda_dispatch.h,sha256=DdKdbBrWwQaQw93x92Et3zBIIZEf0tkrGgGz7IfXySA,1414 +torch/include/ATen/ops/mse_loss_backward_native.h,sha256=okIkz67pz_mWVoIBCF-LMmnsUObLPHooqPf9BankCUk,993 +torch/include/ATen/ops/mse_loss_backward_ops.h,sha256=WZ0O3LggZbxqFR06P_kXMg2YLvVMkwe0nnNGbBZW7MA,2419 +torch/include/ATen/ops/mse_loss_compositeexplicitautogradnonfunctional_dispatch.h,sha256=hbBPDxztvKYcZdKCEl-pJJjH9Hf5rcBFQFwJRVCrpCA,1112 +torch/include/ATen/ops/mse_loss_cpu_dispatch.h,sha256=6s3t4cg5mmsiZNa28QwHNZRzsWX_ckwydJKzdJmATTY,1315 +torch/include/ATen/ops/mse_loss_cuda_dispatch.h,sha256=PsTQSwQTq_F2IAqw4hAszQ_AN6ctpLzoVTMHoR6202E,1317 +torch/include/ATen/ops/mse_loss_meta.h,sha256=C8ZhXv5IYxm5m9MQHktQbbXPho9ozjcdS37ah49biMs,869 +torch/include/ATen/ops/mse_loss_meta_dispatch.h,sha256=UhdxJ4Je1IoM4_G52jWpE89UwquiT9afR3F8mde8wwc,1317 +torch/include/ATen/ops/mse_loss_native.h,sha256=YznOoXHkG8guJ576fRAUMCXav_mpG-AIFdsvdXQ4Sic,902 +torch/include/ATen/ops/mse_loss_ops.h,sha256=JpykFUJmAhS89WSlaLx4kIcm6UTzd0srKwPs7CZwTng,2125 +torch/include/ATen/ops/msort.h,sha256=R592S5elfhm5sm3LM-Ym4RJbmUmXZpnVHflq1bd0ho8,1271 +torch/include/ATen/ops/msort_compositeimplicitautograd_dispatch.h,sha256=mOzWk66yCjthOLUDBZ-i9fMDW9yXVQXDSY-0CKzfw4E,1172 +torch/include/ATen/ops/msort_native.h,sha256=toLQqY21bbV_-VJXFpMZNAtmN0CuhzuhiBKYuTIxWGQ,806 +torch/include/ATen/ops/msort_ops.h,sha256=EO5GAjX9CsRVCP7hZ9UDKhnUXPC-2Mz19WLmuJRL31A,1795 +torch/include/ATen/ops/mul.h,sha256=TZrRwMayTY6in94-ahIX4mbX3pcVI6liiqLZCME1L2w,2087 +torch/include/ATen/ops/mul_compositeexplicitautograd_dispatch.h,sha256=uLldtxYv7j97v18gB3YN493P5158pyvQ-2b8zQkciYs,1318 +torch/include/ATen/ops/mul_compositeexplicitautogradnonfunctional_dispatch.h,sha256=AiX2Jrqfzzx9O0pK5B4-2rH7v9xT9fhiyBF9165VToQ,1141 +torch/include/ATen/ops/mul_cpu_dispatch.h,sha256=6oyNCIxgTRYBXKEBDcwCRptSXUxxYfKZtm4LQD0Y5ws,1274 +torch/include/ATen/ops/mul_cuda_dispatch.h,sha256=Ha6FThK3eHVax9shiTb23M4uSfyT5z45hRvBhJikbek,1276 +torch/include/ATen/ops/mul_meta.h,sha256=a7uN2fgODrWiJKGAKOQiNjWeecyHeyET7dneTJRa0Qs,851 +torch/include/ATen/ops/mul_meta_dispatch.h,sha256=qzRm7kDSkrVTlxLCnW59qaXEtYtUxLTjITrunuzGGXc,1276 +torch/include/ATen/ops/mul_native.h,sha256=K_RpZO2msxl445HwfQs3DAvox5oTBhwXyCxwqRTZ_p8,2738 +torch/include/ATen/ops/mul_ops.h,sha256=qpqda27m5uZCWIJ0BWeILqyN6aJ6UshoMxi8-BEqnDg,4452 +torch/include/ATen/ops/multi_margin_loss.h,sha256=zAzeoHQ6x1C6B3eR8pGA14gNagPun9Emg5DxSGcRTcc,2231 +torch/include/ATen/ops/multi_margin_loss_backward.h,sha256=FtBhkrO0_EqNyqcs3OTn6L9pHf-5PvwgdEpfCUGodrc,2566 +torch/include/ATen/ops/multi_margin_loss_backward_cpu_dispatch.h,sha256=qJWmxPBhZv_8xep8KUlVu_Q-cb0aX6SZvowp9oxyD1U,1764 +torch/include/ATen/ops/multi_margin_loss_backward_cuda_dispatch.h,sha256=NXJUzr1RV5P_acKjWIj9NxmrQhezXnl1h9rCEx_mPd8,1766 +torch/include/ATen/ops/multi_margin_loss_backward_native.h,sha256=0EDRGdU4awnD9q7-5BB9gJzNnqlDLs9yoh1p4c2k6D8,1782 +torch/include/ATen/ops/multi_margin_loss_backward_ops.h,sha256=O0tSVWVWWu9PASH9k36yzpCM1GmaCnp5UdNkgFIVZXw,3101 +torch/include/ATen/ops/multi_margin_loss_cpu_dispatch.h,sha256=Dgflnkt7O25XqWjpPySBqP-4A0cXco4jm7-zFSFhHms,1635 +torch/include/ATen/ops/multi_margin_loss_cuda_dispatch.h,sha256=_BYLFxzYACB7TdtPX7oLosEYuE5iSykV7-k7Ktbjm08,1637 +torch/include/ATen/ops/multi_margin_loss_native.h,sha256=gGPXZYEu9m0ZUnX3SBaeZci1mynFLxCRhBjjlvRY9-4,1612 +torch/include/ATen/ops/multi_margin_loss_ops.h,sha256=ChKiNLCwCD2uFo1oqXBVdln9rQIHEtCdRlUunBF1oJg,2805 +torch/include/ATen/ops/multilabel_margin_loss.h,sha256=WNfTo7hf2gqNzwKw35RG29_tftWP_HzCQMdVI3OYw38,1781 +torch/include/ATen/ops/multilabel_margin_loss_backward.h,sha256=hFto8jPx8i_q6HxE8MUA2dW04ZEM7kFDgv9XyMiKygw,2258 +torch/include/ATen/ops/multilabel_margin_loss_backward_cpu_dispatch.h,sha256=wwSj0wSG79lTipGiY0hPhXmhK2bru7Z3k2bPGOHV8Aw,1544 +torch/include/ATen/ops/multilabel_margin_loss_backward_cuda_dispatch.h,sha256=2Y3lNW2kPka02S0DMC4wgcUXuBVCUHdqZywtoHXsdQE,1546 +torch/include/ATen/ops/multilabel_margin_loss_backward_native.h,sha256=fYxqS1rBi8YqZfenbF-OF0tE0TfHxN7qcCt3io87MyM,1504 +torch/include/ATen/ops/multilabel_margin_loss_backward_ops.h,sha256=8QqxxS2IowTgWMIkzDiBoJj04XA-H-fzxV-KqTOaJaw,2699 +torch/include/ATen/ops/multilabel_margin_loss_compositeimplicitautograd_dispatch.h,sha256=cL8fTJkEPKN8uHaQofRsH1k3OlQiJsI9LrgrLXf3A_o,1401 +torch/include/ATen/ops/multilabel_margin_loss_forward.h,sha256=r9d3GsLRUPIRki9n6u3xjqzbwJHyJGxEJbkAOBOGERY,2084 +torch/include/ATen/ops/multilabel_margin_loss_forward_cpu_dispatch.h,sha256=e8Zf_U3W6Sn6YZZ7tSh8MMYy_WxE_Um1IZf6ZDN03-0,1474 +torch/include/ATen/ops/multilabel_margin_loss_forward_cuda_dispatch.h,sha256=v8PslDRuNIVBrBNl03IOHmn8QhHGm4FfIM2mFlWveSM,1476 +torch/include/ATen/ops/multilabel_margin_loss_forward_native.h,sha256=XYxRT66GEfQPjjbBEIxslKXDrEm2MGAm5B4XYZVfUFY,1396 +torch/include/ATen/ops/multilabel_margin_loss_forward_ops.h,sha256=ezfZOZzgCnHBedA8vqW1xxUa9Y0-JLW8B7plDUx6Wg4,2546 +torch/include/ATen/ops/multilabel_margin_loss_native.h,sha256=TqzMIPglGvX_BKlbnromzyoIy8NqxqGmvQHlM5ndl_E,952 +torch/include/ATen/ops/multilabel_margin_loss_ops.h,sha256=Odq5_5tZlfKn1FJG-th3mg4goOKNTeImWWMF5pH4Cjk,2209 +torch/include/ATen/ops/multinomial.h,sha256=yvGZ3Wfvx-LNB3W8L9-5u5eyjSQ5BzQpLLFa205MKrE,5334 +torch/include/ATen/ops/multinomial_cpu_dispatch.h,sha256=cBhHKfdfaGhCIt-EjI1DT4ae154qRvGaAUj9lPwy_WI,1975 +torch/include/ATen/ops/multinomial_cuda_dispatch.h,sha256=Y4xIh2j0CsQ7yhArjERsDsFVXu4dcFKlryACsEvVj0U,1977 +torch/include/ATen/ops/multinomial_native.h,sha256=q1EGnmrsM6gOX7h5qM-rNptb477UMAVz5oYbHxzoBw4,1001 +torch/include/ATen/ops/multinomial_ops.h,sha256=RtShwTYLoVTcg_9rkW51h57cJL8sJynVRpSa9pNAwWc,2418 +torch/include/ATen/ops/multiply.h,sha256=u8mzBJ5Y9R3MET5lkEibB_MP2iG73DcjivoHlspktQw,1658 +torch/include/ATen/ops/multiply_compositeimplicitautograd_dispatch.h,sha256=GSLt3bpNDxmaMsnHZH4CZhHTW9MyyUdkzFBfrsuD3aE,1499 +torch/include/ATen/ops/multiply_native.h,sha256=v6rewbsVV-JL7sZjykUMcDvAIQnD_6ET2oAQyFUm-YY,1104 +torch/include/ATen/ops/multiply_ops.h,sha256=p5HiVpqSsFWuJHmvbqVr4MxwpZdllJZxvXeGpF2qpTg,3839 +torch/include/ATen/ops/mv.h,sha256=X5lykqbK0XT2Z85XK8U02Ay4h6qHYqY3uKX3gB96vzs,1364 +torch/include/ATen/ops/mv_compositeexplicitautograd_dispatch.h,sha256=BXYidWGL-TNbaMqTT1u4EBPI32vylMdZ7wZVLcsTvko,1235 +torch/include/ATen/ops/mv_native.h,sha256=OfOjmJbxiJqxu0JGLfVarAuelBgw9C20VodUFB3nhgo,929 +torch/include/ATen/ops/mv_ops.h,sha256=51P5nk0LLnKoVXGffMFaNiz0FVb_JhQojRYDIoXT_J8,1937 +torch/include/ATen/ops/mvlgamma.h,sha256=m6JOUnsBe4QKCDIsGsKlyp5UawEym_DSjfGRfENX-0Y,1364 +torch/include/ATen/ops/mvlgamma_compositeexplicitautograd_dispatch.h,sha256=GeeB4-qTTs3kSrXH5VqpHJJ2HEy7P3VIoNBCVzocBX8,1095 +torch/include/ATen/ops/mvlgamma_cpu_dispatch.h,sha256=o2rq5NmL0mJvZhzHJ6m3xNuZa8Uo8M1Ur_tJtnQ_6TI,1103 +torch/include/ATen/ops/mvlgamma_cuda_dispatch.h,sha256=rLiquDuthXbayEo3J9zhwcE4eBF2LnqqVeUrNnlPpX0,1105 +torch/include/ATen/ops/mvlgamma_native.h,sha256=ywyVxp8jv8SekLF2dsQnnbNP9gfQHcKTmrM1dpLgNs0,898 +torch/include/ATen/ops/mvlgamma_ops.h,sha256=SXURNS8K5isyJSCqiZZJrTw2JcvN0ni-wendKK8Y-fY,2432 +torch/include/ATen/ops/nan_to_num.h,sha256=MPSKQINhS8_B0jQck-66UhFTp3nOQp94rILzEygMxBw,2294 +torch/include/ATen/ops/nan_to_num_compositeexplicitautograd_dispatch.h,sha256=R4PKDMtv1LVDuHnUARlMWuH15UPh3SixT2tzZCSRsuA,1353 +torch/include/ATen/ops/nan_to_num_cpu_dispatch.h,sha256=4qOBMWh7zintG-vOen7HkpVSaV2OKECVDUEQ219TEHc,1316 +torch/include/ATen/ops/nan_to_num_cuda_dispatch.h,sha256=XHJ8w5f12wdTTUBxPqPPP-b78WxDRwc6L2hX0sVJ-18,1318 +torch/include/ATen/ops/nan_to_num_native.h,sha256=u8sucp0X8lQ7hnrAAKVnpugMobhVCpQ7MOSd_W9aaf0,1825 +torch/include/ATen/ops/nan_to_num_ops.h,sha256=WpftTchVJLbDXSUSJVRCri0qPERPbTs1x1-tgpcGBtA,3290 +torch/include/ATen/ops/nanmean.h,sha256=-JVLwwWhWP1yOhrqJCRAzH-15A7FTqndtuHmnQ1UQDE,1861 +torch/include/ATen/ops/nanmean_compositeimplicitautograd_dispatch.h,sha256=9Y1VMhVvEFFr9zfVNGk4w74SBr6sn6ExicUq4fiQbDg,1496 +torch/include/ATen/ops/nanmean_native.h,sha256=g0eHuBY2qam-D3O07mm0OWDzWQhV076PzBcw_J5m9Lg,1010 +torch/include/ATen/ops/nanmean_ops.h,sha256=gIePLM1Z9BTiywnmpk2k0bQ3vgGEtlTFOXC2coD0yWY,2390 +torch/include/ATen/ops/nanmedian.h,sha256=1VezkCAVS52g8Fq3udfAhpaYwzAqi2A75MofCVJNMfw,2403 +torch/include/ATen/ops/nanmedian_compositeexplicitautograd_dispatch.h,sha256=1zGv1Zk2NM-4UI14Yl1jX7C-6MoBE37MlkZVRGqOU_Q,1242 +torch/include/ATen/ops/nanmedian_cpu_dispatch.h,sha256=9gb-4bWyN5MFMflxSj05m8_6_T1HmsAKBukOUsm9Lpw,1304 +torch/include/ATen/ops/nanmedian_cuda_dispatch.h,sha256=wCuL0EdBMWFjx0WcfQ3fpi5sAav43Q-eAcBU4t-KeP0,1306 +torch/include/ATen/ops/nanmedian_native.h,sha256=fI2faZjwXbWM3ZkgT-pWqUM1AMQizsZXI_LdK3DU1Rs,1324 +torch/include/ATen/ops/nanmedian_ops.h,sha256=YLsO8KqxNe-DaKiyrc4qo4r4FIc4oFlTI21VFKt-hTg,3452 +torch/include/ATen/ops/nanquantile.h,sha256=f5NBFtj_EfyLbL7-mK43lrRcWY10cE2O63HiIRMbZ-g,3248 +torch/include/ATen/ops/nanquantile_compositeimplicitautograd_dispatch.h,sha256=Pz830ni4hTtpT-FLXiBqzIUOeinF2g_CKEtE0DqcLoU,2088 +torch/include/ATen/ops/nanquantile_native.h,sha256=MJNMphCjf5I8S_EWrKzVWIyZnkXwL2pbYPgvl26JZHg,1388 +torch/include/ATen/ops/nanquantile_ops.h,sha256=tHuI4Aj676CrB9ovOv0ZiDzLAu0NX4UntD_TtCHpcpI,4280 +torch/include/ATen/ops/nansum.h,sha256=Le-a87c-7MTQzve36XxzZvULVqKSHtCsJ5fxjIims1A,1851 +torch/include/ATen/ops/nansum_cpu_dispatch.h,sha256=qaNgMG6w3CVYSdlICbrB_KvRYNivfduMdjzuHYb1hEc,1449 +torch/include/ATen/ops/nansum_cuda_dispatch.h,sha256=pBHoKGkarU8RtlgFOVVbTvkhVOoVs8xzkzEiFo5r-qc,1451 +torch/include/ATen/ops/nansum_native.h,sha256=jnP2Wa0OIpnQMQfbDEwzdBeA1gmrU9J2byCeHjN-87A,1008 +torch/include/ATen/ops/nansum_ops.h,sha256=l6PwBLAa2MJ83EEuPhuurIAFrY77fFTKb8BCV-ztNXk,2384 +torch/include/ATen/ops/narrow.h,sha256=tuPziGHNvbVggBDD_R2drMWatAj8NieDTfntd2SRedc,2892 +torch/include/ATen/ops/narrow_compositeimplicitautograd_dispatch.h,sha256=D0mlQLjVH8CQk6aYRXFqQ20W66qdIqcVIizSs1ngVJM,1404 +torch/include/ATen/ops/narrow_copy.h,sha256=IwqGzoGV5yFBz28doHMLvk22YWkeB4Gu8iOCQKWLCHk,4338 +torch/include/ATen/ops/narrow_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=TjYOqzvt_fEejTu3SaiZKI52mNryhBT4QzZIe445kB0,1211 +torch/include/ATen/ops/narrow_copy_cpu_dispatch.h,sha256=amjkFzLO1lz7sigD2tmN0WNW6_VPkLLVIbQDMqXwUw0,1681 +torch/include/ATen/ops/narrow_copy_native.h,sha256=XMmRZtyirmLUUOrlSpe9CE6yPMeM469k7t6ltUdbIfk,1160 +torch/include/ATen/ops/narrow_copy_ops.h,sha256=jjUhA5tpoxF7Quqcyo4DkhcQK5UmqQEZuCU967abvQs,2185 +torch/include/ATen/ops/narrow_native.h,sha256=pZnXu6F69N2fBKtevRgAe2vIxzVJG_7KclFwmtqvbyA,1036 +torch/include/ATen/ops/narrow_ops.h,sha256=K5PuDOQxlSQjieSPovjSP1uEsN3Yws6tKwCGr3WotUI,2118 +torch/include/ATen/ops/native_batch_norm.h,sha256=XUgIXrw1RoKY3vx35RZIwGvZpXusT4D399Vnu9KhM8M,3056 +torch/include/ATen/ops/native_batch_norm_backward.h,sha256=pucNYvGdf9x5SJ72wKSW8bfN0kGc0HB2Hs-DUGWRjOE,3590 +torch/include/ATen/ops/native_batch_norm_backward_compositeexplicitautograd_dispatch.h,sha256=LhkCiqvo6E4mImXqvrpH7ZtojM9kccVKEhINFWUNzIM,1973 +torch/include/ATen/ops/native_batch_norm_backward_cpu_dispatch.h,sha256=RcS2pqc3Kr1dazG2uLkx7r5M7xPzUkkMtcnKWbhJktI,1357 +torch/include/ATen/ops/native_batch_norm_backward_cuda_dispatch.h,sha256=g8eBrQ81B97joeVOptxD9XM7CGOPIT8qV30VDOXnKMc,1359 +torch/include/ATen/ops/native_batch_norm_backward_native.h,sha256=5_LkJ_t8x6En2KvGn5aS2zx_pTIOs75_e6729wbrusU,2486 +torch/include/ATen/ops/native_batch_norm_backward_ops.h,sha256=GUY7V6JVOCmd8SSvHRmLKhWTOGRYQDs87P8AO1Cuw4A,4446 +torch/include/ATen/ops/native_batch_norm_cpu_dispatch.h,sha256=_NVyNLSH2Ift5Dr5582qLMvdRy9bhdaCdKXFXsnwo5I,2070 +torch/include/ATen/ops/native_batch_norm_cuda_dispatch.h,sha256=7F4Bk-SMY5kSDvp05k7IEjImDzypOz5tqdWg0OG2ZmA,2072 +torch/include/ATen/ops/native_batch_norm_native.h,sha256=aoOAbODrWN0-rlWrfddua7Wz0vvED4HXEtvhQEDTsMw,2477 +torch/include/ATen/ops/native_batch_norm_ops.h,sha256=X7udntMza0uIr23VXtNcILRPdLMDrFmXXqwiN6tzWMg,3805 +torch/include/ATen/ops/native_channel_shuffle.h,sha256=KzCSZyniWqrSsNMTdGfByce8K9JgLY7WhxNPcD0pMtc,1735 +torch/include/ATen/ops/native_channel_shuffle_compositeimplicitautograd_dispatch.h,sha256=9Xh4jBZmd6E0OBeRSLDZ37ZhKibq22mRBRD7Gt-7buQ,1147 +torch/include/ATen/ops/native_channel_shuffle_cpu_dispatch.h,sha256=dKAC3JYJ9q5FwUTGOyCmTV5duzDIvOoZM_rIn2YqHHc,1103 +torch/include/ATen/ops/native_channel_shuffle_native.h,sha256=LIQO13Xn_htgZOHy1KHEdJJ_6CnIEe3NJdGI3Lh4LOU,843 +torch/include/ATen/ops/native_channel_shuffle_ops.h,sha256=qnDguQrATE0aiHSOR1tiLNM4wVCXJPMctNCy5TKTs68,1327 +torch/include/ATen/ops/native_dropout.h,sha256=vRtZxe8ojAtMMDCV4LcQjPfP8ZypmCfhAtMe3lX4b_k,1790 +torch/include/ATen/ops/native_dropout_backward.h,sha256=GSHGwW3U4mw8Vai0US3oXiDOgO6nkx0UfuTp0xyGvew,1748 +torch/include/ATen/ops/native_dropout_backward_compositeexplicitautograd_dispatch.h,sha256=mPyJ2bGcfRahWboVQ4PuW1RDSU6KCH7IWQTiFiaHmmI,1247 +torch/include/ATen/ops/native_dropout_backward_cpu_dispatch.h,sha256=jt9SR67LMZFNfc2JIVcrOeWcGR8vpbWGovaE965joZM,1037 +torch/include/ATen/ops/native_dropout_backward_cuda_dispatch.h,sha256=jrDqigpz8h1pqAB13KKddu5FsqeKgtIvDIXBWr5ug-A,1039 +torch/include/ATen/ops/native_dropout_backward_native.h,sha256=tuwhBnk7fDrLBq9eIslnKkmNOvUAn3oDB5-GMqYCd2U,1056 +torch/include/ATen/ops/native_dropout_backward_ops.h,sha256=jy1Bfvp9usroxSyM4WVSZUdu0FUSijoERNSFu-P8k0o,2209 +torch/include/ATen/ops/native_dropout_compositeexplicitautograd_dispatch.h,sha256=cW1XJ_vsyVIfY6cMk-PVAQwkl-PWDJx8IMb4QLdV4zM,1311 +torch/include/ATen/ops/native_dropout_cpu_dispatch.h,sha256=vHGXLLMd63nUYGLYI5_og9mrlPqCk4iDh7KqdCCcKX8,1047 +torch/include/ATen/ops/native_dropout_cuda_dispatch.h,sha256=YBDcHuWeBgTwcmd4g1MtjgL2-jkpOIL7JLS5XAGGDfE,1049 +torch/include/ATen/ops/native_dropout_native.h,sha256=Zk0P4LfqwJYmtFDr6oMDFp0POfwgOFNGLM8dib-GprE,1246 +torch/include/ATen/ops/native_dropout_ops.h,sha256=7wUJF9w9LAS0EzuSPbm9Z2HICZXw4klTTXGMoZQUb2Q,2369 +torch/include/ATen/ops/native_group_norm.h,sha256=7Dv2tYVuhWdWP8XbWeTls3NT7_4HW7y7Q_s5Lp2PZ2M,7466 +torch/include/ATen/ops/native_group_norm_backward.h,sha256=0K6VC4WDzHiueA7fq7pBQMa9X9huRQq7ZCx-k3F7zmA,8975 +torch/include/ATen/ops/native_group_norm_backward_compositeexplicitautograd_dispatch.h,sha256=L7cyjYzKqo5z2fJdL9t7CuGZDxgUyp_YtezTj-g6Tb4,2544 +torch/include/ATen/ops/native_group_norm_backward_cpu_dispatch.h,sha256=rC0SorxLN8--x-yGwrKF_TAHiniPKNxIZHoIPd7wSlg,1575 +torch/include/ATen/ops/native_group_norm_backward_cuda_dispatch.h,sha256=Dua1HplB0jVW6brQG0E_e8u7W9DIXwy5pZSR0YJusy4,1577 +torch/include/ATen/ops/native_group_norm_backward_native.h,sha256=XLEUw9MN42ZFOlniHyzHQQf2qtfhJcg1f48aVGlxOCs,1398 +torch/include/ATen/ops/native_group_norm_backward_ops.h,sha256=0LqN48ShBI9Jj7m5-Qww4PIIt4TGNWYhxBIqqc7oUg4,3796 +torch/include/ATen/ops/native_group_norm_compositeexplicitautograd_dispatch.h,sha256=o5PD18tXtO_shBUaAZlDSClpkbj7Hd-E-c7I_nWpJ2Y,2791 +torch/include/ATen/ops/native_group_norm_cpu_dispatch.h,sha256=ni4C5QGUWcIBg_ivqiTUwqd5vkOFPRagzeU2UTu4uL0,1439 +torch/include/ATen/ops/native_group_norm_cuda_dispatch.h,sha256=iwHv89VEkK55zgCDB9yoAWLRpnL5S9zW0VQsx_9IMhk,1441 +torch/include/ATen/ops/native_group_norm_native.h,sha256=yvXkzMk4OoLKV0dqYWqT4PVkS-op3SKIKlgRvcArNis,1510 +torch/include/ATen/ops/native_group_norm_ops.h,sha256=wYzSuV5XSXDasQyasalXJtAnis4cFVZNncaMj1OIpGM,3354 +torch/include/ATen/ops/native_layer_norm.h,sha256=RngddZoFs1Am2SlzoPjbteqLqZuplYCf20-vBgTtk6U,7286 +torch/include/ATen/ops/native_layer_norm_backward.h,sha256=ESHIilI2Bk2QCeyid48ef4f1wncUWzxeKY1w0vC5JXQ,9455 +torch/include/ATen/ops/native_layer_norm_backward_compositeexplicitautograd_dispatch.h,sha256=harJcPHECBPNEGAuVXvdUbfakSyxsw1ZaL6V345xZpI,2632 +torch/include/ATen/ops/native_layer_norm_backward_cpu_dispatch.h,sha256=BSWs45sTtz8k5LUT-6ciWwBf5VpeKXefKaKEgXekrOk,1619 +torch/include/ATen/ops/native_layer_norm_backward_cuda_dispatch.h,sha256=2B3QtvismkQFb2kjxRJybBcdpJGT3NiZl3RP6M2R87U,1621 +torch/include/ATen/ops/native_layer_norm_backward_native.h,sha256=s-0NgBzl23wiY2D_Isj22KojrxGcZ7DPPm8DPQ88h84,2125 +torch/include/ATen/ops/native_layer_norm_backward_ops.h,sha256=u2aoVn7s-csznVdfxumDmZxDrP-sk99bFYseRUigUig,3884 +torch/include/ATen/ops/native_layer_norm_compositeexplicitautograd_dispatch.h,sha256=Gv6S46OolGSlhSw4SMoVD8yt0txehrxWqXuAqNhU4Gg,2671 +torch/include/ATen/ops/native_layer_norm_cpu_dispatch.h,sha256=IF72vS4T2v16qCBsSWG1FsevKusABWQ4jKENZjiPY5o,1399 +torch/include/ATen/ops/native_layer_norm_cuda_dispatch.h,sha256=YzrvBXZ40HJSwLH2q0XiJLjXV6JCyirWFiX_sa6fqUk,1401 +torch/include/ATen/ops/native_layer_norm_native.h,sha256=-aPAmyEZPpDlfW5WcLDq_4pCuh9bnnBni64opcS9DEw,1924 +torch/include/ATen/ops/native_layer_norm_ops.h,sha256=yvV9yx6aP5P0cBvw3M7Fo566ZZramn59D8VZycRRDDw,3172 +torch/include/ATen/ops/native_norm.h,sha256=NmEcCyc71ydiFy1gZRImOUNB88NPiPPtRp5xVc4aXwk,2715 +torch/include/ATen/ops/native_norm_compositeexplicitautograd_dispatch.h,sha256=gVJRjs55h9DUjt1ZsHYvtyEf9OK_RF-JnZSJWSjvrM8,1570 +torch/include/ATen/ops/native_norm_native.h,sha256=Z5mssLD42nSd-4pTM53U7NZCgI683FHeDWoBOKCdvyg,1252 +torch/include/ATen/ops/native_norm_ops.h,sha256=w7HE1Qo-TOPIcFjqqNmowEOItPnrvrY-4w0FAP6BSkQ,3972 +torch/include/ATen/ops/ne.h,sha256=-DdzR1To3wcnzjWk71AD5gXbGGsbiqwSzBeducMFZQk,2096 +torch/include/ATen/ops/ne_compositeexplicitautogradnonfunctional_dispatch.h,sha256=HPaKzP9g-5lPN4YCJDcrA4Nlo5dwWXtl0CmFzxdMyEs,1288 +torch/include/ATen/ops/ne_cpu_dispatch.h,sha256=DoK7b4q2wTo3VIzT5MDA1zIVXLq-pd-nlc-aTLq5p5w,1620 +torch/include/ATen/ops/ne_cuda_dispatch.h,sha256=KeZkxA4X-5uLA5llipDn9dzgY0_CXhHuBF6zEjtwZ2c,1622 +torch/include/ATen/ops/ne_meta.h,sha256=vi02e6F5EIBfBBM1hprGjzkmFYWyydJ84RZvZQcLxo8,989 +torch/include/ATen/ops/ne_meta_dispatch.h,sha256=ElrVXrJagst6mxw4gHAwYXpERTC0eWda908NCEommb0,1622 +torch/include/ATen/ops/ne_native.h,sha256=l8QcQikr_q6Z4XelASLloRheKJH8m1q43m9gbX77-Z0,1459 +torch/include/ATen/ops/ne_ops.h,sha256=QlQ-L6e4pew1Z0OZHW5tV5Vd1121AM8mgnGOKiRDQdM,4455 +torch/include/ATen/ops/neg.h,sha256=3dil3e93bYN1znPwnJcqO_b4Peu4wlLkQ8GupsBgXLg,1384 +torch/include/ATen/ops/neg_compositeexplicitautogradnonfunctional_dispatch.h,sha256=QKZyMJQouMIyjcrLfVbW0vCY79b6Fd1BMN63doqjOj8,1089 +torch/include/ATen/ops/neg_cpu_dispatch.h,sha256=hVkvXUwRKuGzVIxHtdx2NsUn7ZmLNyqaF4KqpqmCruY,1170 +torch/include/ATen/ops/neg_cuda_dispatch.h,sha256=6ykp4X0Fl0oMxoiyxORWZVCt3GjztdWJ5GMRGP2Jc0M,1172 +torch/include/ATen/ops/neg_meta.h,sha256=57nq1B29KTXV2XD3RxU7dei3e10Va_X11WBeK-1LQjU,818 +torch/include/ATen/ops/neg_meta_dispatch.h,sha256=DoHY3wKyUrOYLrxC1xypYFYhNxMk_ztuy82J6HhZxvc,1172 +torch/include/ATen/ops/neg_native.h,sha256=JV7eREAa3hMs2RlTkwIM8rYTzjokJPAXMicr1SDnNmM,1368 +torch/include/ATen/ops/neg_ops.h,sha256=hvRtHi2LAVleZ5nOC1m6Mb9XIXh4yo2FNYih1ypJWkw,2273 +torch/include/ATen/ops/negative.h,sha256=8Oug72iYvfRcQuDGOKu5bhBOAzCE4pjV4GxLJw0KSRE,1449 +torch/include/ATen/ops/negative_compositeimplicitautograd_dispatch.h,sha256=agjot52602rW0eBazmt6PnGfzapX05YhdxAEtDb-F20,1234 +torch/include/ATen/ops/negative_native.h,sha256=ldt_g8Rtmyuxt4F4aAJ7cywNdKFh_7MhixuNZr_8jU8,865 +torch/include/ATen/ops/negative_ops.h,sha256=xxg6662VE6dSvnyLTaW2xAfrLbU-T9Y5rRE7nr31GFI,2318 +torch/include/ATen/ops/nested_to_padded_tensor.h,sha256=9MigTsKd9zLcSJvor8X4vzkgRhHh-HowWPcbvfeJJwU,1089 +torch/include/ATen/ops/nested_to_padded_tensor_compositeimplicitautograd_dispatch.h,sha256=B01U5BmlHOcvRzMpx3ou91HkfUIHbe4s_oxMqtjnwTU,1103 +torch/include/ATen/ops/nested_to_padded_tensor_native.h,sha256=EMWQlBojardN6cqNN_rZRcVM0Tz7GFTejEvh5hZbJKE,815 +torch/include/ATen/ops/nested_to_padded_tensor_ops.h,sha256=StRExLhgnm7MaQFTpOkcqQCv_AL_s3lBzRznzoitvxY,1441 +torch/include/ATen/ops/new_empty.h,sha256=UiSxVfxrKLKmN3PVd4zKMNFgOQ_rqziGUk0RhvPKh0M,4589 +torch/include/ATen/ops/new_empty_compositeexplicitautograd_dispatch.h,sha256=xOTBvta-cgz_rqYN7b_p0ICF_TxpJRnDzdStyaBjD8s,2088 +torch/include/ATen/ops/new_empty_native.h,sha256=5q3d43fyXuBo8GMv-gIP_G1oGA2oeNR2QNIZJ37qnMY,1037 +torch/include/ATen/ops/new_empty_ops.h,sha256=L_hnffy4GHwE0WfB60wUwWUPMcqnFts2KkCn4lKK3kM,2491 +torch/include/ATen/ops/new_empty_strided.h,sha256=Z1527DKyNyM1SARoC4BSyigjFDQxiBQxM735eehdOz4,5453 +torch/include/ATen/ops/new_empty_strided_compositeexplicitautograd_dispatch.h,sha256=D7_L84y0YmVCk-NLb7nxXU1D1UXQKttOOGM4wwXifnM,1536 +torch/include/ATen/ops/new_empty_strided_compositeexplicitautogradnonfunctional_dispatch.h,sha256=_jRCpvWQ0erhDCUzI6W5Qxad9xfLOx6HJ_VtdNKCclU,1814 +torch/include/ATen/ops/new_empty_strided_native.h,sha256=uG55t8f2jXqnPB4CMyf99Hw1O9oONHKYR0MIAy3K864,1109 +torch/include/ATen/ops/new_empty_strided_ops.h,sha256=PTmQ3eRrhhoSXwdubya7bNLJYPkfZp9yD2BsuwtF4Og,2727 +torch/include/ATen/ops/new_full.h,sha256=JPCK3LhVB2xej1K61CqCgca2Jr30l-Fpdqu_MQEd4W8,5152 +torch/include/ATen/ops/new_full_compositeexplicitautograd_dispatch.h,sha256=wokdK2NxHVo5lQWW810YkxpgR7WMVOMR-IUCIOE0phA,2328 +torch/include/ATen/ops/new_full_native.h,sha256=UUNJocjpxhhAkUtFWr43dcPT-Lhghm80hpyY0QfXc_I,1086 +torch/include/ATen/ops/new_full_ops.h,sha256=4rOLCQmEU3NhhU8oaHpht5OJYfsUxXzxgPqOT_8mwSw,2687 +torch/include/ATen/ops/new_ones.h,sha256=J0OLEZJMBU8Z61SxNoBcThNfJ0CbdIW-Bpdhq3gqki8,4560 +torch/include/ATen/ops/new_ones_compositeexplicitautograd_dispatch.h,sha256=snVoFVkayeE3O9VTx9Q9t0LNy4YFemtxmpJPVe8xqmM,2080 +torch/include/ATen/ops/new_ones_native.h,sha256=nggNLllVKJIO54JFgPyYBz7A2GR7Tke7VommY7NxZ1k,1024 +torch/include/ATen/ops/new_ones_ops.h,sha256=H1Ap5v0zRaopmBasWy1aZRsWG1NdSk3GxEaH3xWFmBc,2485 +torch/include/ATen/ops/new_zeros.h,sha256=AO_RrsVoT8m6th_-P_nEO7TLno_D3Bw0cvW2Amy6wJk,4589 +torch/include/ATen/ops/new_zeros_compositeexplicitautograd_dispatch.h,sha256=Vm6wDPLdJpQ5_080UJWMXPfruElK9Zi_CZRU8eQHodo,2088 +torch/include/ATen/ops/new_zeros_native.h,sha256=YA8SmTDS5Aw3GYOu7DSsbtx8Wu_15wx7IMM3K81z3tM,1026 +torch/include/ATen/ops/new_zeros_ops.h,sha256=cr7vaGPIm_01hN9NxyW9T52Tn9TM7B0IZqjYUnUPTWA,2491 +torch/include/ATen/ops/nextafter.h,sha256=-TblIa9sAkmMrIH07FumvBgni-eYY1rS2yLkVWXFCO4,1452 +torch/include/ATen/ops/nextafter_compositeexplicitautogradnonfunctional_dispatch.h,sha256=CqlDNXL3s0xWbeHpWRnQYw6n4jWPL35aiAtpzqQHtnw,1153 +torch/include/ATen/ops/nextafter_cpu_dispatch.h,sha256=_9AQ9leL9FwtC6_RIkZN148aKPLGdfbC-YGt_qRwd7c,1298 +torch/include/ATen/ops/nextafter_cuda_dispatch.h,sha256=mLsfFLwWS102x7BB439S16n34AP7g12iCKpVY8pCod0,1300 +torch/include/ATen/ops/nextafter_meta.h,sha256=xuWLppoQXGI27BFIeInsk-J-1VLl8EKyIffHEbXCca0,850 +torch/include/ATen/ops/nextafter_meta_dispatch.h,sha256=K1oQxUp-7-_2BOnPnDYr-tXSSQzUBe6bfQO1EA-4Xjo,1300 +torch/include/ATen/ops/nextafter_native.h,sha256=Qx4IZw_tAf7cZUM10MRusRG80CbMZU0iZxIQrjG9iqQ,885 +torch/include/ATen/ops/nextafter_ops.h,sha256=p59BwVz8Fyp9iUaK3W4zUgcjdQWBNmTKAzbdMlGPHyI,2585 +torch/include/ATen/ops/nll_loss.h,sha256=Eh2wlGFDgU1czBhePODMcYtHt5Hn66k9UDEoh4EdjsQ,5777 +torch/include/ATen/ops/nll_loss2d.h,sha256=hv1ov3XmTex5-V66gysrONmfDsBL7pFBmk3CgqPCBCI,5839 +torch/include/ATen/ops/nll_loss2d_backward.h,sha256=tfHW2Q6IdqdsU62Z5_4d-9vE4H7yw9cEQixkL6S38TY,7378 +torch/include/ATen/ops/nll_loss2d_backward_cpu_dispatch.h,sha256=LLSPFElfKtTdSj0jmY9h_KavQLG7yuvU3Qf4_mFkNZ4,2543 +torch/include/ATen/ops/nll_loss2d_backward_cuda_dispatch.h,sha256=a3OgFiSNm25AGITfttM0DoAdUm_oEWOMhGxaxH7hjrE,2545 +torch/include/ATen/ops/nll_loss2d_backward_native.h,sha256=2hDdI1qkBxcizGsxvSGGsCFmZCKiJFdvA_LudGhWwRc,1732 +torch/include/ATen/ops/nll_loss2d_backward_ops.h,sha256=4ut3Fk3y8gWxaFMyFeSJy9EIuMSfHc0uSh6Gcxe80AE,3099 +torch/include/ATen/ops/nll_loss2d_compositeimplicitautograd_dispatch.h,sha256=-Ao-XeVoPaI0VX8L26yBYfdruti516SNFeq8OA9L0wM,2227 +torch/include/ATen/ops/nll_loss2d_forward.h,sha256=b7pJLGZmQI_6wwJr2ZeKvyIhqb-Bo-SmFHiQ6aMjjew,6729 +torch/include/ATen/ops/nll_loss2d_forward_cpu_dispatch.h,sha256=OJBAxo5dXQrlb7BmG4NfCFZ40Gti7g7-ReUGIKYOzVU,2397 +torch/include/ATen/ops/nll_loss2d_forward_cuda_dispatch.h,sha256=e6f819-h_Hw9f2pxWg0TyrRBlKncj-uPESZWH1RN_ZI,2399 +torch/include/ATen/ops/nll_loss2d_forward_native.h,sha256=J2JTuC3PVSC5MYGQ2_5jH3DYPaOrDj6HLqgLe0H1FFw,1618 +torch/include/ATen/ops/nll_loss2d_forward_ops.h,sha256=y_pUpQe32hfrO6ho1FdK01ZZAw7syVPNmelmBIrBjnE,2940 +torch/include/ATen/ops/nll_loss2d_native.h,sha256=CmBsNyPXCY5lg02NcEwRaMq-yVa-ZQhZGSpb8yeKDXk,1079 +torch/include/ATen/ops/nll_loss2d_ops.h,sha256=RwtIuO3O8xqbzfDdHLxp20NIbTvTs2cUecvMkw0yRTU,2611 +torch/include/ATen/ops/nll_loss_backward.h,sha256=6ehcxwFbbZZo_AMiLwottcix32UIGg1y3SfD_rzHzkI,7316 +torch/include/ATen/ops/nll_loss_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=U-tbjWgkvoWMJ8TtcNd_aUsTdffbgDuUFFqJ3KaMSG4,1485 +torch/include/ATen/ops/nll_loss_backward_cpu_dispatch.h,sha256=n8F8w36MpzcTheQbfzcCAIrM95XnORr06Nvy3zO6bY4,2531 +torch/include/ATen/ops/nll_loss_backward_cuda_dispatch.h,sha256=XkkLWKJs_Ai-M7gbdy8zvT5Q4nFMboNuauwmUC3exSk,2533 +torch/include/ATen/ops/nll_loss_backward_meta.h,sha256=W6hjRyONtqptasAonOE2uf4dW0VKKqPl442zHWGk_4g,995 +torch/include/ATen/ops/nll_loss_backward_meta_dispatch.h,sha256=BADsEwi0ZRGeEwJjiVKlKYbYO6ZbB8NDgglbkYUViKM,2533 +torch/include/ATen/ops/nll_loss_backward_native.h,sha256=EhRGO42dPRbuhgo-hRol6SB57OX2Bgw_U67URlpD73o,1395 +torch/include/ATen/ops/nll_loss_backward_ops.h,sha256=RFOLfAi0pl7qFh81NEp-erLW24pfUit-0XdNzxnHYHI,3087 +torch/include/ATen/ops/nll_loss_compositeimplicitautograd_dispatch.h,sha256=0m16YPlIckHH5kJaO5Ox44mWeNRJr8Kwi5ob79e8WBY,2215 +torch/include/ATen/ops/nll_loss_forward.h,sha256=65Mv2fysKAeynCm64upMcuTVL2nu864JVcINk2kZlak,6667 +torch/include/ATen/ops/nll_loss_forward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=8s8oNWzpYA9gOthksx4kDck7aIF6fwztb1ZHJ6Xu86E,1403 +torch/include/ATen/ops/nll_loss_forward_cpu_dispatch.h,sha256=qrjsNekoUDZG6WwPBrhPfMGwghGfQ9yoIOjEixixXJg,2385 +torch/include/ATen/ops/nll_loss_forward_cuda_dispatch.h,sha256=uol3mOU5iOBl5J-PK7eRAD9S3L-lHyPyEvuqblKar3A,2387 +torch/include/ATen/ops/nll_loss_forward_meta.h,sha256=2ZnRaukgVnOPU9GObu_o6O5fZ5XOLNBfvyoqfIyd4ow,929 +torch/include/ATen/ops/nll_loss_forward_meta_dispatch.h,sha256=C497g9x9nVIdVMPYGLKA7I4jtm5gowu9C9hlA5AUTgI,2387 +torch/include/ATen/ops/nll_loss_forward_native.h,sha256=z4g2_bimglUW7JcrbPrHvJ1_bFAlr-zS3GluAS_O0tM,1318 +torch/include/ATen/ops/nll_loss_forward_ops.h,sha256=zvdDJhijxbRzLtELepLrcYyWNS7rrEjJDcAsmh-xJzM,2928 +torch/include/ATen/ops/nll_loss_native.h,sha256=Nqkdacz598yRVl6ORucTIljHbTK0AShFLVdXm-NhiW4,1075 +torch/include/ATen/ops/nll_loss_nd.h,sha256=nc2oGZGxx_m3sjuXvteHhQ6hYmrtc8LKGgAOPPCkctI,2376 +torch/include/ATen/ops/nll_loss_nd_compositeimplicitautograd_dispatch.h,sha256=MJ80xvsCHxI0gnbKddLIq4ZnsY-GkGwwgG_ggs0i3Zo,1373 +torch/include/ATen/ops/nll_loss_nd_native.h,sha256=J5MyTLIgAGDek7eToZpPQx7MpH8pn5qymRvM5gkK-zw,886 +torch/include/ATen/ops/nll_loss_nd_ops.h,sha256=_65h8l1sc3aYwkedTUgKPvSmANass22xfLrXUAE0OnA,1619 +torch/include/ATen/ops/nll_loss_ops.h,sha256=uEAvyzxh7IIpKOo3WvcWoU0l7UEL5qVHx-64_CARvBc,2599 +torch/include/ATen/ops/nonzero.h,sha256=ysYJ5d6QrJY0rDdWgy8wVgykPLLK0e5CcakBdyB0pko,1291 +torch/include/ATen/ops/nonzero_cpu_dispatch.h,sha256=wCdSTwF5T2xedb1J24bVixd7LefZ6AyRN9vak-jGzUg,1134 +torch/include/ATen/ops/nonzero_cuda_dispatch.h,sha256=0eFxM-bOyLWHyYK9eWT8S0m9rD6baPFA3IYAY2F4mh8,1136 +torch/include/ATen/ops/nonzero_native.h,sha256=yxQ2ql_VknxsnQcJFKRIqc26wuc0iNiUbV7e3KNUpZg,962 +torch/include/ATen/ops/nonzero_numpy.h,sha256=fUSQKqON8495ueRHDw-A_MhGkdQMJCwnOc_MYxBlDHA,936 +torch/include/ATen/ops/nonzero_numpy_compositeimplicitautograd_dispatch.h,sha256=_Wh8rlMiWAJ-OkAn0r2tW1B6Kn_oUI8sMuoUho5wJ4o,1040 +torch/include/ATen/ops/nonzero_numpy_native.h,sha256=W5GHvlWkvnA10lbm7dy7zrE3Dd4wBfEDf7N4Hu8PadY,752 +torch/include/ATen/ops/nonzero_numpy_ops.h,sha256=Ef-Mf9PYa3iFU_rJTsJQgoD--odaa1E_CBQbBVVmS2w,1279 +torch/include/ATen/ops/nonzero_ops.h,sha256=Krm-E4Xzq1EYX39aGU_V2yW06SQ6RXhVZkO_ebcZ1VM,1807 +torch/include/ATen/ops/nonzero_static.h,sha256=C75Toksa3S0iRwBf9CM9n5L5AtJAJjWW2r1OJGyE928,4257 +torch/include/ATen/ops/nonzero_static_cpu_dispatch.h,sha256=CYqoWnNE1O1CGUtYgKup6PO8vSP4fAGf3lBm-dupCw4,1639 +torch/include/ATen/ops/nonzero_static_cuda_dispatch.h,sha256=3H28CXLAYVNpgNpUch_dLEOBWwXKNhbt_Ll1U2no-JU,1641 +torch/include/ATen/ops/nonzero_static_native.h,sha256=EvFNaBExDso_SQT7tkDr4lcOTXH_DVRjRNBCUbY6t2E,1132 +torch/include/ATen/ops/nonzero_static_ops.h,sha256=WCUf3ImI-rDUpy4rfMLvL-aSLHTnWXZtEzmIwpBDwuE,2112 +torch/include/ATen/ops/norm.h,sha256=BklV9n4gO9zCLInmS5U3v0zrJfmQ_Pr8P38IA0U5a5M,4372 +torch/include/ATen/ops/norm_compositeexplicitautograd_dispatch.h,sha256=xqzeGOMtHBfiKn3wIp7rvG8jp-MpRRXs7TU3jS5IkZo,1627 +torch/include/ATen/ops/norm_compositeexplicitautogradnonfunctional_dispatch.h,sha256=3JKsNt_7X8ux7dSqqTEMPuh-9vH8QlfIKs1aoMn-xnE,1270 +torch/include/ATen/ops/norm_cpu_dispatch.h,sha256=LgN0McgHf_6bzB2u6uHOnGv1ah40xrB8ZdiZLh9LZBY,1852 +torch/include/ATen/ops/norm_cuda_dispatch.h,sha256=rAFtAGElwqki2OiJb2asKKwgAwz1l2jbjoP1qTK2wEs,1854 +torch/include/ATen/ops/norm_except_dim.h,sha256=35bSg2rX8OIMvvuLo6vyRSwKnLKZ099NKSuCAC_rl_4,980 +torch/include/ATen/ops/norm_except_dim_compositeimplicitautograd_dispatch.h,sha256=Z_IAQ-Cj2aNGHGz30vg3ctp4gYcizsjgbT_21dS5E1o,1054 +torch/include/ATen/ops/norm_except_dim_native.h,sha256=qujaPdGjvf8DBRqJTxj79FtxkW8SmnsRPhSa1ImC9YI,766 +torch/include/ATen/ops/norm_except_dim_ops.h,sha256=JX8m-36vd_Xgk92QfC9vxOAdX9OWPkOivEzngKN4yr4,1321 +torch/include/ATen/ops/norm_meta.h,sha256=3OBPCJ6S5yWI0qE9fcm6TXzzeIDnCem1SXkVb7cXw_k,1103 +torch/include/ATen/ops/norm_meta_dispatch.h,sha256=zl1Huec01S-uNhlfj5_vZ71t8rOqRy8fL7jxNsmrFxo,1854 +torch/include/ATen/ops/norm_native.h,sha256=qwKmuloqm3W9RtUVp6Vz9PQYY30PuD6mwHauFdGLu9g,1910 +torch/include/ATen/ops/norm_ops.h,sha256=nNOj99BkMAg9POw6Qvgz0Us9p5gfnMuJBBeFM1dL8ZI,6991 +torch/include/ATen/ops/normal.h,sha256=wkYf5hdo-VrjhO66g3kHnTu644sZk8oPxxsXzq18QQg,11915 +torch/include/ATen/ops/normal_compositeexplicitautograd_dispatch.h,sha256=hMReygAhIkZH7A3f7Dua6IJ-Q8Oq3E1GC7SRlBszYHI,2921 +torch/include/ATen/ops/normal_cpu_dispatch.h,sha256=RTaM3OHZ5v4TUjLhIGIlaRlVZh8jR8SQjDnA7toHaWg,2306 +torch/include/ATen/ops/normal_cuda_dispatch.h,sha256=hH7zjJTN14P9HMEDPYPtl-OO4_J6pA0IgnbJUZJBqZA,2308 +torch/include/ATen/ops/normal_meta_dispatch.h,sha256=pJ1LMXAEJjz3e8Pg9fSrP3_zWmhcO1erT6L1j69yPVE,2308 +torch/include/ATen/ops/normal_native.h,sha256=nbYl4zEHBkI9leCmqzREc0hP5rULthXRIAb6lbNecTI,3587 +torch/include/ATen/ops/normal_ops.h,sha256=YzA_97ITiVltXJVBa25hS6Pt-hJqvMwwoVrorybo7-s,9888 +torch/include/ATen/ops/not_equal.h,sha256=46rGJui3-kGy_OYmbURITdHsiW9621Aikoh4V1_YkmY,2229 +torch/include/ATen/ops/not_equal_compositeimplicitautograd_dispatch.h,sha256=c9a6mmiEZbgdSpgtbxzwNIATQP5ONSITT-akpvDUiSE,1720 +torch/include/ATen/ops/not_equal_native.h,sha256=s3itfrPp3hKOjBWjWII9-VggE7nxLfnDAORJwQ9WeQo,1216 +torch/include/ATen/ops/not_equal_ops.h,sha256=I-_K8wBN4m4rVhYRByEm8R_ehuHpSCep46lriNkeUIk,4581 +torch/include/ATen/ops/nuclear_norm.h,sha256=VNkWZmqmBZiPEuTHAMJlctWYXR5whhzMtnIcoN3TLMM,2340 +torch/include/ATen/ops/nuclear_norm_compositeimplicitautograd_dispatch.h,sha256=e6v8IqQTUU5woGQ-DlD-Qc6nmWlsbecajbCBQWW6myc,1593 +torch/include/ATen/ops/nuclear_norm_native.h,sha256=pe37nwIvfGzR9Omdl_HLeCl3RjsHZhLtG4V56Wx2aSI,1074 +torch/include/ATen/ops/nuclear_norm_ops.h,sha256=83jT_oJjjYFZ4uT0eYegJEoRtZgGIk9CNwWWZs91bA4,3344 +torch/include/ATen/ops/numel.h,sha256=YiV_IOzZj82f--7CL3z9jx9xDlTUBiM2FFuzCrqUzlw,756 +torch/include/ATen/ops/numel_compositeimplicitautograd_dispatch.h,sha256=2osIzi2Uy3MnHRCu9apwFIYhVXl00uedvx_EqjWvBrA,1014 +torch/include/ATen/ops/numel_native.h,sha256=Ql9Lku3Xf7LgaTnlGcOEzAdeua8c5l5SUwVZtaSKMuI,726 +torch/include/ATen/ops/numel_ops.h,sha256=aFau1zEB2cDfP2IrR2FB2xgQxZ_eJdvwelfrndmXiH8,1196 +torch/include/ATen/ops/numpy_T.h,sha256=32PcuB7WnL62gX0HBE1-5nBWHxCMWuYbU3LAHXZgXyk,758 +torch/include/ATen/ops/numpy_T_compositeimplicitautograd_dispatch.h,sha256=Pv83dKFQ96GgSO9O-dC8zeX90xRZwj5VU_BOl3zSgs0,1019 +torch/include/ATen/ops/numpy_T_native.h,sha256=1JjT7rDgNqehTMlbmFtA0WZCKwgWPZnMuXBqnzLUYR4,731 +torch/include/ATen/ops/numpy_T_ops.h,sha256=hUtDgK-fnM2g_vu-grneQHERiSXCiKV-UxxzjAsKFSw,1220 +torch/include/ATen/ops/one_hot.h,sha256=G557pLCY1UF3S4DntHrQ5iTFO-S1RLESiKKObPdmelw,952 +torch/include/ATen/ops/one_hot_compositeimplicitautograd_dispatch.h,sha256=MkTITT2rvxCjx7CJgcLkqXzCdC-aSYCcDXK12hFPVHM,1043 +torch/include/ATen/ops/one_hot_native.h,sha256=dhrhm1td1sqyj-H8v-g37DlzZ1lf6dWOtH0TGXIim0g,755 +torch/include/ATen/ops/one_hot_ops.h,sha256=0g6hYLhvPvq13oA-Nqg6ngqeDN-T70fGSm3ALe8D9YE,1285 +torch/include/ATen/ops/ones.h,sha256=xbplsvJ1_wIcL4AENZcKcks751ErxZzinik9K0FtH-c,5638 +torch/include/ATen/ops/ones_compositeexplicitautograd_dispatch.h,sha256=LjRQQPMG4D_rN_J_bW3_M8mb0jzz4MErf1obaxwg8Rc,1848 +torch/include/ATen/ops/ones_like.h,sha256=65po7sEMvdbiZD9nBi4gnq61JaK9mu_310T7-5oN1gQ,2462 +torch/include/ATen/ops/ones_like_compositeexplicitautograd_dispatch.h,sha256=FRsNhP7kllx7X6xwHFxoXDwvahwfhV77yIESTbgusqI,1642 +torch/include/ATen/ops/ones_like_native.h,sha256=ga7jIKFXUX1eqWOdJ9uPvmaYeDjmCMVBZzo1iQnY544,1084 +torch/include/ATen/ops/ones_like_ops.h,sha256=PfK109IN9n1F6DYtWTPA5pKDJEtp_efyVRzEjQXwRDk,2649 +torch/include/ATen/ops/ones_meta_dispatch.h,sha256=j5g1DjPHSeWY_KHEnT-7SNfKaKrzCMQWUqyft4Ak0Hg,1490 +torch/include/ATen/ops/ones_native.h,sha256=eW6KNQrGFitQHRCiPY_xmCReoCIDOz79rzB0_8m07jg,1177 +torch/include/ATen/ops/ones_ops.h,sha256=ey18TjjfRgzhGBZRZFUi7hZB4qEDPHVNK4E6Dw9yJVs,2295 +torch/include/ATen/ops/or.h,sha256=wEbGL_7iJQ3LyZpFvyXJWb3hsocq34iKEDGlwmJ7l_o,1144 +torch/include/ATen/ops/or_compositeimplicitautograd_dispatch.h,sha256=dWCpHwpRVFMabWAlCBRK1h-A2ouBdvjCh0Ft4GZ2ClM,1278 +torch/include/ATen/ops/or_native.h,sha256=cQ8L_VYxWkgN52P03bKe6-CGdwj_YBsUIKoaTXfb284,990 +torch/include/ATen/ops/or_ops.h,sha256=30lZvc6fitKLpwgplZEc-fsZ0m_pwA0mtvKA_WAkyv4,3133 +torch/include/ATen/ops/orgqr.h,sha256=_kgKEfoZqGKEpRsbqsOyFG_JH6qSvOPhyiW_iOpyiLs,1421 +torch/include/ATen/ops/orgqr_compositeimplicitautograd_dispatch.h,sha256=DnaoWNhTh0ess9dYIMAPAFyq5ckOVkCKwbuSljXGbhI,1253 +torch/include/ATen/ops/orgqr_native.h,sha256=qdmmLM50RmgcxE0C0tTOn0GhDAupY9Q2thoASCrEc6o,860 +torch/include/ATen/ops/orgqr_ops.h,sha256=uBj1UWLK13j1hDC11DP8TZ8ec_M5VFcJXdPafVei-xg,1973 +torch/include/ATen/ops/ormqr.h,sha256=pGd-p5wEcmMR9Kl5Cqqby1WApBo0ngRD_Sf-EqMYRiA,1839 +torch/include/ATen/ops/ormqr_cpu_dispatch.h,sha256=gnSCAjNid_Bp6K2QMSdvBBiRxp4GEPIPrl0M5yZx60g,1393 +torch/include/ATen/ops/ormqr_cuda_dispatch.h,sha256=xP3oHdel9gPmAZ3kMNZziGqzJFo1-6DXAbkQV4jQ1QI,1395 +torch/include/ATen/ops/ormqr_native.h,sha256=alRGzVKLWzNDmwgLxOjphebjq-LvmXZKwxMyezQmbeE,979 +torch/include/ATen/ops/ormqr_ops.h,sha256=FrmoBlDTz8h8BuTuxPh77KechsoAX-v9A2YRx4jj4RA,2359 +torch/include/ATen/ops/outer.h,sha256=lwZApKb_eLqz6Q3oRMtBnQn9CdcDrqheK5mjfw9yPY4,1403 +torch/include/ATen/ops/outer_compositeimplicitautograd_dispatch.h,sha256=vm1KAYvuhjAMGNiGGpuh6nKrp7WIhXR1tzxpQdJeQM4,1247 +torch/include/ATen/ops/outer_native.h,sha256=Y_3kwwRs1la_4cLm6EZ5TfTef7GwYLtgsC5L_-jPEfc,856 +torch/include/ATen/ops/outer_ops.h,sha256=W-585u8uC4AapAs-Gn61_vN5vm31L_rEAr3pbo6hIpo,1961 +torch/include/ATen/ops/output_nr.h,sha256=Qh4E28AaxT7dPXJ85KP-iGp9PIsmw6BfwqCArG3fBGA,760 +torch/include/ATen/ops/output_nr_compositeimplicitautograd_dispatch.h,sha256=UdpJISwTc4233OyFr3eeRwHujCAg5w6kvENi1lkcjMM,1018 +torch/include/ATen/ops/output_nr_native.h,sha256=G7JHbr5l9ho9Bh3NZ3aS8PD6_DIEHMpoxEbnViUzfmY,730 +torch/include/ATen/ops/output_nr_ops.h,sha256=QTcEcdaOf2O6rUkF5n67O2WyFVi1P9lTsBgv1BZrPcs,1208 +torch/include/ATen/ops/pad.h,sha256=x12iCHoGpQF8TydCXZrE3R8jMUVaxnBlU7cJWSsD9Ws,2036 +torch/include/ATen/ops/pad_compositeimplicitautograd_dispatch.h,sha256=SSC5us6Z9D0wXhTxZDjMU5RNAzJXLBb7iLgVna-PlBE,1279 +torch/include/ATen/ops/pad_native.h,sha256=OUY8EBQoFD792LKHSvbwxaKa15D1fNmbIIVjA07Btg4,839 +torch/include/ATen/ops/pad_ops.h,sha256=-oFcHxD7Esw_4xy_ZP_dcqXkjYwbHxtQjI-0UvChf2k,1480 +torch/include/ATen/ops/pad_sequence.h,sha256=KylRCD1P9tCM41-4_i5bL_I2_I6paYzgf6NrRPIc4X4,1134 +torch/include/ATen/ops/pad_sequence_compositeimplicitautograd_dispatch.h,sha256=ldIyjPXz5f4L5Hy1WcnLX-ivA0uRLp4mljl2MRMMTRo,1114 +torch/include/ATen/ops/pad_sequence_native.h,sha256=j5nMc02Rh9sKhL2meN7AZZ0qMjbkS3STCWUteg_3NM8,826 +torch/include/ATen/ops/pad_sequence_ops.h,sha256=kJMRW6YMTB1ZALIVvEmsJwtmVy7-FAwjfLKRymlj2bU,1485 +torch/include/ATen/ops/pairwise_distance.h,sha256=LwNs-fuATmgAxZgHg2lo7nOsRl_xLaPlNGWfAmi1A1M,1082 +torch/include/ATen/ops/pairwise_distance_compositeimplicitautograd_dispatch.h,sha256=9Ca5HKvuSz01zCiFSik3MA8A9M5lBMIEeOwOeAaN9v4,1100 +torch/include/ATen/ops/pairwise_distance_native.h,sha256=HcociC6WWIZbbawY0WYUTNif4G6gc9JQUKiqp_sL-Cc,812 +torch/include/ATen/ops/pairwise_distance_ops.h,sha256=uMbfQQuLz7KI2pzt4tRdZ-ryGTI01r7FZDRSp44V7Z0,1457 +torch/include/ATen/ops/pdist.h,sha256=dD8ZU0Ee2h8FiB9xo5AvnHnr0rI-ckHxaci6eVkvxws,913 +torch/include/ATen/ops/pdist_compositeimplicitautograd_dispatch.h,sha256=eS3GeRxyjlaM4bBc0cmFwQ-L7u61GVTSNEQvhBjcJxs,1029 +torch/include/ATen/ops/pdist_native.h,sha256=tPQIZmKuiPax2Gpy6DknEZchsVHAFe_ivFWZ5yWaRUI,741 +torch/include/ATen/ops/pdist_ops.h,sha256=hl98K9tMth4ixw9nWXSEdwE8huBcC3kiCxWrFpTdjR0,1247 +torch/include/ATen/ops/permute.h,sha256=ZWyQUTnuu1qiPs3H036jYXcgjhJlGNEaaDPkPB8_8PY,941 +torch/include/ATen/ops/permute_compositeexplicitautograd_dispatch.h,sha256=5B-SH_D-nq4rlLYnS8WF8qDkvRbq8pytlQoIlqFMzV0,1041 +torch/include/ATen/ops/permute_copy.h,sha256=Ia321sUCvMi0WSHBq4etdjrQ1MMSbWS_upPLXkeom64,1461 +torch/include/ATen/ops/permute_copy_compositeexplicitautograd_dispatch.h,sha256=YdDg3DKHc5Pfhq8q1zrDSbg-jphY9yY-H6l7BX9uTL4,1177 +torch/include/ATen/ops/permute_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=9Dx9MCSR9a4fews9rdzRBK1oVCap-AL_l0o5_nPszy8,1072 +torch/include/ATen/ops/permute_copy_native.h,sha256=nG1UwTZQYOM0ZxdaCzYYRgp_m3wfB8iaTu7hwUUnP8c,864 +torch/include/ATen/ops/permute_copy_ops.h,sha256=9h2dMXRmfP4mF20v64FdDcbvRTI2YlSr7J1gxH_zq0s,1983 +torch/include/ATen/ops/permute_native.h,sha256=YN2K44AhN2B799YS23MEykktktlZhh1TQEq6m59eWCw,841 +torch/include/ATen/ops/permute_ops.h,sha256=aCjn1K4Y4GKEHWACWIDrFWlbYfHhcElkOK-RCZtPrYc,1293 +torch/include/ATen/ops/pin_memory.h,sha256=m-iQal92NcI7l6icfTfOBPBhaKVwHStutoVUSutEBI4,761 +torch/include/ATen/ops/pin_memory_compositeimplicitautograd_dispatch.h,sha256=I0DqFATtVQ8hR3ugq07fjqSEyf79xyWLgRAuM5U3ciE,1073 +torch/include/ATen/ops/pin_memory_native.h,sha256=35VkVuEljLoSWYqsVAWieLuW0odmC8RrbEFPoMpBPEI,785 +torch/include/ATen/ops/pin_memory_ops.h,sha256=KyU4ieqwAoRrbO3gSX59ah-JJ0zLOL4Ha1FeuxOi9mA,1351 +torch/include/ATen/ops/pinverse.h,sha256=fGcxnWh-hAQJOQwVeRgtcOkatt8AK28R3T1Vt_lsC7s,945 +torch/include/ATen/ops/pinverse_compositeimplicitautograd_dispatch.h,sha256=oqZCmG7bp8UZlEI0YZ_1gz3bRnI52jlrvOaTGKpG1kY,1040 +torch/include/ATen/ops/pinverse_native.h,sha256=ReZC8u40pfr5BHqxX4jVcd-ON3XGkt5fXmAbx9HJq2c,752 +torch/include/ATen/ops/pinverse_ops.h,sha256=lZ3vBriEXftZgXf660MmOA69XSERE_gN98oBb7XaxkQ,1272 +torch/include/ATen/ops/pixel_shuffle.h,sha256=ejKZdtcIDd9tLZlboJsDLKqXQcynS7U5j0eA9RJvNUY,1531 +torch/include/ATen/ops/pixel_shuffle_compositeexplicitautograd_dispatch.h,sha256=S7DC1zmaKpTiBRJOegN88D3UBewRgKBZ4L_x3NVzulw,1183 +torch/include/ATen/ops/pixel_shuffle_compositeexplicitautogradnonfunctional_dispatch.h,sha256=JfZQBrraEp2Vdr0CcuYPRViZ-lYJchGAKbpo2zrOTAg,1075 +torch/include/ATen/ops/pixel_shuffle_cpu_dispatch.h,sha256=SlKVkKIuKa8jGWOoDLnGbjQA2mKe022T5yw_EvACe_w,1005 +torch/include/ATen/ops/pixel_shuffle_native.h,sha256=ZQxeEzBz7z9tnCXsMxuNXv2dtsObmxrbTcNiaSU8pOQ,964 +torch/include/ATen/ops/pixel_shuffle_ops.h,sha256=wuEfBzTwjjf1ZlEWbF8roXLidJ7lsN4T2s8jds8x4ws,1997 +torch/include/ATen/ops/pixel_unshuffle.h,sha256=xmjgeTFjGetuyVGSBV5brLeWRxACilEXbM55spkJvr8,1569 +torch/include/ATen/ops/pixel_unshuffle_compositeexplicitautograd_dispatch.h,sha256=5xBbUDPtX6lLAnG5QaJR9uUjHXcH_1xNaudLfTFb9Wg,1191 +torch/include/ATen/ops/pixel_unshuffle_compositeexplicitautogradnonfunctional_dispatch.h,sha256=2m-mlFy51O12WjhngoxbycfDWuM2cH3BEsZhhO36erM,1079 +torch/include/ATen/ops/pixel_unshuffle_cpu_dispatch.h,sha256=DHgDfhmZ0PUqqe4RqFAx8RpgM8-HXhgcgj4xZNB1n5Y,1009 +torch/include/ATen/ops/pixel_unshuffle_native.h,sha256=oDHVRRKOKKKWCIt0uALzDy0DGJ5pOi5frp-P9reDfWI,976 +torch/include/ATen/ops/pixel_unshuffle_ops.h,sha256=laVhiKWL91sz_nMff4xXljVg3dvYY8IeseXkpLQvNjs,2021 +torch/include/ATen/ops/poisson.h,sha256=AyVek-ij1xNMT9a9gUyQUoyvkGzhmHHNBT9Q0EBqFLw,1561 +torch/include/ATen/ops/poisson_compositeexplicitautograd_dispatch.h,sha256=giBT2SV-N5P33J3vNwThSlNTINe9TGWaIAsC_XDTRC0,1222 +torch/include/ATen/ops/poisson_cpu_dispatch.h,sha256=y0d3Jb4SOCUV5h-HN5pbARqb2vIk6M9slt2MmBdl_tU,1032 +torch/include/ATen/ops/poisson_cuda_dispatch.h,sha256=OdeJuLd5ml7cXSAuTcMhoFqSdTWei07HvY2Us8f5tmo,1034 +torch/include/ATen/ops/poisson_native.h,sha256=ic7tTHq7bgHilkfQzHURCff5Zhw_WbO2zhbQj4oyPME,1036 +torch/include/ATen/ops/poisson_nll_loss.h,sha256=HksHExpx5JmGBYBcOn1zWKyzqnxTx3YEuOXXOz3YY8A,1128 +torch/include/ATen/ops/poisson_nll_loss_compositeimplicitautograd_dispatch.h,sha256=0SlpWtXrli-3drB73FPD_8Wv5TaKlGSXQs2ahkdAHbY,1114 +torch/include/ATen/ops/poisson_nll_loss_native.h,sha256=0hkcCb32MF0gnA2A_O-M2wSAyNv9VUKde2PhblQfvyw,826 +torch/include/ATen/ops/poisson_nll_loss_ops.h,sha256=mr6YHsfVWWT6aPoMooV3DDpRCgiqC1j5PCjgHl1D7q4,1531 +torch/include/ATen/ops/poisson_ops.h,sha256=fs0y73ogeDIqjpInglErUu87M0mex9hPA-c7rPiwju8,2093 +torch/include/ATen/ops/polar.h,sha256=59nwGgeNPIvJ0x3_djeP2Px-1mHrlpyTuUv7CZLcN3o,1403 +torch/include/ATen/ops/polar_compositeexplicitautograd_dispatch.h,sha256=8jC9x-50uJzs4RlQYTTyFI5GqmB1euAJsBFviP46aKw,1042 +torch/include/ATen/ops/polar_cpu_dispatch.h,sha256=HJPL7YAIEvTamcN4zE_CY5mMamLuBAEQtdkvSnP2Pi8,1125 +torch/include/ATen/ops/polar_cuda_dispatch.h,sha256=uQpP6S5i6jmY0_MUenlQsd2o17qbAmlwXuCQRcmTlWI,1127 +torch/include/ATen/ops/polar_native.h,sha256=PEz-OBSeFuiw1jx5AtblKBAZ2f8meYUHoIMEJTa7EVI,856 +torch/include/ATen/ops/polar_ops.h,sha256=g6fpYt16-ercG4hBhs3iWCSQV2QJbJMmJU7ypF90jTo,1961 +torch/include/ATen/ops/polygamma.h,sha256=-3ikoI7C6MD1aOysM7Eg3ciKQVVDJil5BBvrQSAgrME,1374 +torch/include/ATen/ops/polygamma_compositeexplicitautograd_dispatch.h,sha256=ATyYl5quZzXVmMHddMycxu24v6q1ilz6lgcH2YeDZr8,1029 +torch/include/ATen/ops/polygamma_compositeexplicitautogradnonfunctional_dispatch.h,sha256=FRgHWy67jyCpxRL5eQxPoT4sEAo1OLw0t5fyw7j04_c,1058 +torch/include/ATen/ops/polygamma_cpu_dispatch.h,sha256=fPQ7AR0Mhj8hgT3fUnce-yzrjhvT4AQS1deAkvVXdxw,1173 +torch/include/ATen/ops/polygamma_cuda_dispatch.h,sha256=qhFeGZ0lh4FsTDApAZNrLH53-Iw3_1XkxjUtZl0Vy70,1175 +torch/include/ATen/ops/polygamma_meta.h,sha256=dWzsOLaB2VHnnRmqoP6YfnaOY0o7CJuYw1rFjmZ0M5Q,835 +torch/include/ATen/ops/polygamma_meta_dispatch.h,sha256=Jepz4eowtRhljOQqo8qdoJR1QNSVk7Bt33mhEzZ6Fi8,1175 +torch/include/ATen/ops/polygamma_native.h,sha256=DuBh1KOv1nZAtvYFvl3ZtWn-TnNvNvHX3Ndqo4-hFYM,935 +torch/include/ATen/ops/polygamma_ops.h,sha256=PcoteqJd5A6x0Rsj_1Aajnuf7x3bEokXrWkX0rRkRgM,2441 +torch/include/ATen/ops/positive.h,sha256=Mu66OlqZj3X8Fjlj8X0VfTWnZkzWfQBe-6O1EYAHh8g,905 +torch/include/ATen/ops/positive_compositeimplicitautograd_dispatch.h,sha256=QGsRJWN5RhpOrKn1jnHFQnC6wzW4k9CbiSulfubPbj0,1020 +torch/include/ATen/ops/positive_native.h,sha256=hkiqdyQTI31dieW0rysixXq2-LeJnVYn7E5ZKU4boYM,732 +torch/include/ATen/ops/positive_ops.h,sha256=isaCy0KrT9J4uhltWqTJAPQFPxS6PVrfMAhQO81x9F0,1223 +torch/include/ATen/ops/pow.h,sha256=-EK328jhUomchm4GJz8g-lKw2AONa01SQvo9b_O0HXM,2961 +torch/include/ATen/ops/pow_compositeexplicitautogradnonfunctional_dispatch.h,sha256=nljLUc8gm-mxAzjoArePxFZ_1pC97m0XAwXmbyodLgw,1384 +torch/include/ATen/ops/pow_cpu_dispatch.h,sha256=ArgZui8B6sIA5oigxgmsvRU3eZVqfHtaV4p4rn7KmWo,1941 +torch/include/ATen/ops/pow_cuda_dispatch.h,sha256=fqH9JOOy9E5S3UiGAvf5B8tyTh67Fz_dxlg4wzn3ENM,1943 +torch/include/ATen/ops/pow_meta.h,sha256=DGxa8NeFcOfZMxDtSVJVD3jcAQAldAC7mRnkQSiWX3c,1154 +torch/include/ATen/ops/pow_meta_dispatch.h,sha256=OfUX0PQZOMAK1kcpFgCZ9Mtb6aksFaiwG0EXpcUaGHU,1943 +torch/include/ATen/ops/pow_native.h,sha256=I4_ogEWBQmWgIr8gz6xcKS2X5l-IHQdlVJlu0eP5IE0,1480 +torch/include/ATen/ops/pow_ops.h,sha256=yXOFN_7rgdtJcR9a3sv003I5ifbaAz-sAOkrAuUWgAE,5914 +torch/include/ATen/ops/prelu.h,sha256=TJ-kYkNkD_T7VzAySkx7gE5O3rfPUfrPQOn_neOuTXg,937 +torch/include/ATen/ops/prelu_compositeimplicitautograd_dispatch.h,sha256=WKV2r00u93ai8fCd38QsPzg4b5n5wMMPpmxzMXNG01M,1044 +torch/include/ATen/ops/prelu_native.h,sha256=0NBrld2TiiRUTivI5ijBy-cRI2EqSZNmrmFU0paivyg,756 +torch/include/ATen/ops/prelu_ops.h,sha256=3sXLxty2j3z60eIx_i_PoP1RKZlWIiofLunih73JtKM,1297 +torch/include/ATen/ops/prod.h,sha256=ikNq0GLLqbghmzo9gHA_SF-IoXV2znsZj6z2EjlQx20,2508 +torch/include/ATen/ops/prod_compositeexplicitautograd_dispatch.h,sha256=jHIedNnCNCGj4Z4SVFipP9ik6kv7FjpnKLHFKGbQx2Y,1210 +torch/include/ATen/ops/prod_compositeexplicitautogradnonfunctional_dispatch.h,sha256=XGARH5XY2QagoAuQ0-vyae-Ji4p4vAR7kOCCYnY6OUA,1129 +torch/include/ATen/ops/prod_cpu_dispatch.h,sha256=fgnYuoD44QvJhTYIe3eJEbuQhGwmgfzrhwPOKWH9HrU,1471 +torch/include/ATen/ops/prod_cuda_dispatch.h,sha256=DmsR0vXUVOuhwxqSBxA_ooTMfaK2asLzvIgo4WM232E,1473 +torch/include/ATen/ops/prod_meta.h,sha256=7VOwKynXEdDYYQ52QslmexZjK9YMCiJrbUfQiiT8NGI,893 +torch/include/ATen/ops/prod_meta_dispatch.h,sha256=t5SZZU0jGkzxTL8hbtKh5Er9vQJen8JC6vael0AGwTA,1367 +torch/include/ATen/ops/prod_native.h,sha256=ZDD9-bSAy_FYBk8Luo-4L6KoC5GurabvseRLo7JKLy0,1139 +torch/include/ATen/ops/prod_ops.h,sha256=skI-fqONz2W6qL7mxHd0xegw4USxX-9Na5qUZgGSLW8,3644 +torch/include/ATen/ops/promote_types.h,sha256=yY5J_y9-UDUVg8AOwSjiwBDGk5hgDE-JavgC76jnEiI,977 +torch/include/ATen/ops/promote_types_compositeimplicitautograd_dispatch.h,sha256=Arja6ix0IM_1Ky4cOYBq6FVReHhYa9j0qFg7g8h2bpk,1048 +torch/include/ATen/ops/promote_types_native.h,sha256=HKlBJqK7kookmuQO9vRLxiZb0fr9gEaxmw9lIVxcChQ,760 +torch/include/ATen/ops/promote_types_ops.h,sha256=5AtQQLqc9Whd8GGIpyoc9XsZ4X683vzN835rcZwP0yw,1321 +torch/include/ATen/ops/put.h,sha256=zKxCVw0WuiIJjmPoavVgDbOZEXltqlVr4BWb9tu-hio,1710 +torch/include/ATen/ops/put_compositeexplicitautograd_dispatch.h,sha256=2GFpgaKRAgLzybNMzLnYQ_WpukiljfYr225tc_nE-Bk,1388 +torch/include/ATen/ops/put_cpu_dispatch.h,sha256=AaAzeeYizV4QcCcQNkLj2FqllfIUk5VTlbRmIgXQVi0,1044 +torch/include/ATen/ops/put_cuda_dispatch.h,sha256=DrVD92DdMWmTY2GcKw9V1w5f_Sjsl-rOA4vSuxFF-g8,1046 +torch/include/ATen/ops/put_meta_dispatch.h,sha256=M-jUHofnB-CI49NOTKfmQxz2vjDQJGhfWRxuNUyEJVs,1046 +torch/include/ATen/ops/put_native.h,sha256=OjL_Ozw2av95qgHF1aRfyLj-iMrYinDJ969jmqWlzFg,1072 +torch/include/ATen/ops/put_ops.h,sha256=Xk3ZLM2f8WFluntexeEMJz0WgkCx2S6taNEX8tfHJ3U,2987 +torch/include/ATen/ops/q_per_channel_axis.h,sha256=tYmmRertATakSQ9hD0NCmrW1CJFDu3HNG87ejkqfQpg,933 +torch/include/ATen/ops/q_per_channel_axis_native.h,sha256=f8rqlsUs7RTqUg8bdZTRoL9RV0LtmDgh1OJuiQo8NgM,739 +torch/include/ATen/ops/q_per_channel_axis_ops.h,sha256=pLhS6kbovOUGcBtfg3lqUD-Ugz5NthS5d7wCslKtUec,1235 +torch/include/ATen/ops/q_per_channel_scales.h,sha256=-T265OFu7YwezrloNbyJTrTHXPO7mUXiFiyyNuHrBiM,1421 +torch/include/ATen/ops/q_per_channel_scales_compositeexplicitautograd_dispatch.h,sha256=z_bZB6-nBgom99A-USUFqdOatep1B1jgPhpi2nvPALs,1149 +torch/include/ATen/ops/q_per_channel_scales_native.h,sha256=E5Vczsy39kBk1ZNCYtsoL4DeldjeBkgeNUhzu4TPKUE,836 +torch/include/ATen/ops/q_per_channel_scales_ops.h,sha256=o9qMF9Yq5W8CjsILpC_xY7szEKkWOj5j5iQ7Ef3CjDQ,1885 +torch/include/ATen/ops/q_per_channel_zero_points.h,sha256=xHCcn_bGZ2_YVnjRvL-Cogw6uWFnMoDtC_cGvBSUI3k,1471 +torch/include/ATen/ops/q_per_channel_zero_points_compositeexplicitautograd_dispatch.h,sha256=JDxc3roywf2B4blrB1jaCBATSM6uPllYPU_yRb9v1qw,1159 +torch/include/ATen/ops/q_per_channel_zero_points_native.h,sha256=7f7m6gecEdHNK0nQ-TyBN8AyXwKuZXqLRq4jpLNK6Wo,846 +torch/include/ATen/ops/q_per_channel_zero_points_ops.h,sha256=tqAAxJkMirXR2Xs3mKs2Knex_9ghHri7f874XtWgpJE,1915 +torch/include/ATen/ops/q_scale.h,sha256=1WggPLvpVzf5OYqrqh2nBsRDbq4FMn1H90YNGObIHAI,890 +torch/include/ATen/ops/q_scale_native.h,sha256=Q27fWRo48tf2NhBOYCqXXokNRpAI0xhUgys-P4dHvRY,733 +torch/include/ATen/ops/q_scale_ops.h,sha256=0J-KBz3FzFk572hu2XWKm_E298eC_myyss_Zo0U5vm4,1201 +torch/include/ATen/ops/q_zero_point.h,sha256=vBfIWKFuQayfrECh7jDFjqyCRfm2KielCAMksdjorGk,909 +torch/include/ATen/ops/q_zero_point_native.h,sha256=7B--Bv75JI_LuWHoDIUxAH64If8KUlUWBcRxWol2hJ4,739 +torch/include/ATen/ops/q_zero_point_ops.h,sha256=RJG0IdLFtyI78ImD19zkfxI0Y_UbP2BSYaFBZ9KW_1w,1217 +torch/include/ATen/ops/qscheme.h,sha256=qcrePpz_LIFeYvz4JYdodUaorRagEgJgCUSjDu25Gg8,758 +torch/include/ATen/ops/qscheme_native.h,sha256=SP2sqF4szvKIHYX4TXbTcHXBDdsln61BIt_XBe_djMs,738 +torch/include/ATen/ops/qscheme_ops.h,sha256=x-z57214V3Ban8AUYHvV2mNbY9btFN05qDY4gBwAK7c,1218 +torch/include/ATen/ops/quantile.h,sha256=s6m5pSEXB6R8AJg18UMVW2eXawwuwj27_sDrPon3-Q0,3191 +torch/include/ATen/ops/quantile_compositeimplicitautograd_dispatch.h,sha256=jdbRH7Dwb_bd5V9hlOeImfGB14hndR1LHSSk4m0WVSw,2070 +torch/include/ATen/ops/quantile_native.h,sha256=wdI-OpgxXzH-xqC9AVB9dMmdMX5W0gZh9fTst_A59Uc,1376 +torch/include/ATen/ops/quantile_ops.h,sha256=Oy7PlxJUK-eUXLOAnU9MvHqPjNUt_c_oF-UfvRzKoHs,4244 +torch/include/ATen/ops/quantize_per_channel.h,sha256=WkuQCnJuDOOs4BmgJMLsQk_Ex5bY5w60YHKs4hnT3Do,1997 +torch/include/ATen/ops/quantize_per_channel_compositeexplicitautograd_dispatch.h,sha256=qQvHSUOuGiavBC-9iC1mWW5FwwrBoCLtjO0_cUlSSGM,1339 +torch/include/ATen/ops/quantize_per_channel_cpu_dispatch.h,sha256=CbP2HmOAy-BZJMi9eo6gpwDaGGYNJZKWHarAYkVgJcc,1083 +torch/include/ATen/ops/quantize_per_channel_cuda_dispatch.h,sha256=WP3Gw_P3OZsAqDSxmYBEeOnplwmGF-g_PR5Sz5iwNvo,1085 +torch/include/ATen/ops/quantize_per_channel_native.h,sha256=tPlLsPG6noHvkeBoC0B97llxAgJYQB5UbWZu3KubZ3s,1026 +torch/include/ATen/ops/quantize_per_channel_ops.h,sha256=fZoP1IKOPh9OMXq6GuOPf9ejI9uP6PhVl81jGKWWoec,2521 +torch/include/ATen/ops/quantize_per_tensor.h,sha256=34mT0kVQ1JnapUS61DJq-uYQab0tQWydyF4LArMwMYM,4188 +torch/include/ATen/ops/quantize_per_tensor_compositeexplicitautograd_dispatch.h,sha256=T6j9LfbP9VXbuHkfuFuL9vG97uMovGA_hE2urK9K0BA,1931 +torch/include/ATen/ops/quantize_per_tensor_cpu_dispatch.h,sha256=Uu-tbhTQNnuUcgrgcgIIWcN4dfiap_hUTavhPcFWGNQ,1351 +torch/include/ATen/ops/quantize_per_tensor_cuda_dispatch.h,sha256=hiY6FAhmHLPETKxsL7_wR-Z8CGq3zaR89X4EsKTJAT4,1191 +torch/include/ATen/ops/quantize_per_tensor_dynamic.h,sha256=Zt8SdrwOVmrgmVL1sfNB_9VWDBkQTdoDw8ShRhGkJjY,1788 +torch/include/ATen/ops/quantize_per_tensor_dynamic_compositeexplicitautograd_dispatch.h,sha256=HmjSm2p6Ddv9oMM8_4C-7YFvDDZg7-IGy517mm1Pp7k,1245 +torch/include/ATen/ops/quantize_per_tensor_dynamic_cpu_dispatch.h,sha256=qq0AH2mKj5Vn8MaPfs51FRIWCbxbsPgxJo4drDSyc7w,1036 +torch/include/ATen/ops/quantize_per_tensor_dynamic_cuda_dispatch.h,sha256=qWO5oerFtBm33iFtCZ2WQ0B89r9TTGWZO3zW7PiatHM,1038 +torch/include/ATen/ops/quantize_per_tensor_dynamic_native.h,sha256=WJ7lt_Hf8USh63iLtAp7YrZZMoDPBgRMDJUk8g0g5hY,932 +torch/include/ATen/ops/quantize_per_tensor_dynamic_ops.h,sha256=ZHjRfSmQFUEJlwOKGmN_C8SRS3JtetbtG2MjaZyzWKY,2209 +torch/include/ATen/ops/quantize_per_tensor_native.h,sha256=--AnfYaBoBXKJlYlVnVghxzTn058ZQDE_U0zKFBqq8k,1636 +torch/include/ATen/ops/quantize_per_tensor_ops.h,sha256=qWdPhurwMFX7yGfE4_mbh0JpkIIdBa9GGM0KHqrVF-k,5828 +torch/include/ATen/ops/quantized_batch_norm.h,sha256=Re9Hjr6PLCg_ymAZ_oHEI_RA8oKGo1Bp0ESdsprarMc,2531 +torch/include/ATen/ops/quantized_batch_norm_compositeexplicitautograd_dispatch.h,sha256=EY8ZuhILv9_i9PZTu2Jv639KiMibAD8kWp3psKPBkS0,1541 +torch/include/ATen/ops/quantized_batch_norm_native.h,sha256=AYd2nnzy6w8Jx4hoDtermw6O7LCJUy8tgFpp9zsNKVY,1228 +torch/include/ATen/ops/quantized_batch_norm_ops.h,sha256=U6jCfgRrK90aQh0SeXz_xTpTScOEQ2ThczQm4xY0ZMw,3167 +torch/include/ATen/ops/quantized_gru_cell.h,sha256=8ISaZ1OYgDObb2MSq5rsGI-69vbB3a-cWOo--cT67LQ,1676 +torch/include/ATen/ops/quantized_gru_cell_compositeimplicitautograd_dispatch.h,sha256=inhkG_wQnqgQ0ENC82U787h78mjhkbCZSqCxKGdpp6U,1410 +torch/include/ATen/ops/quantized_gru_cell_native.h,sha256=dGkcKSYwVdr3Bsvmp5U5iYJJl4pH8q97QlfXxjA0Gxo,1122 +torch/include/ATen/ops/quantized_gru_cell_ops.h,sha256=bSk8YkuU5wy8JAVDkyCm9ZOR9-bvjsmxCxfQYeHROZU,2491 +torch/include/ATen/ops/quantized_lstm_cell.h,sha256=j2NYTrMBolo_FqzY_lWnepWrX4cSi8QD5jqCyrNIqHM,1713 +torch/include/ATen/ops/quantized_lstm_cell_compositeimplicitautograd_dispatch.h,sha256=QyGEzK8m2VWlcmCDj5DJzyT2mdSOibzk6P3RwTRUVbc,1432 +torch/include/ATen/ops/quantized_lstm_cell_native.h,sha256=T7B7MUP9Hn9pSO0ByVV435idnp3QXbDlNKqRFwmKkAI,1144 +torch/include/ATen/ops/quantized_lstm_cell_ops.h,sha256=B4T9AQvpTv6Tc5g-kVyQ5HgMDeSZ_9TEmt2fjpa_ZqU,2569 +torch/include/ATen/ops/quantized_max_pool1d.h,sha256=GEwGRhrOwBbdodISt4HD8eSH0edViDNGM_yW4wtbBx0,2251 +torch/include/ATen/ops/quantized_max_pool1d_compositeexplicitautograd_dispatch.h,sha256=A07VGjkfwp7xAhVci5x03iVnfVCunf3wqAoFIhxlMpI,1402 +torch/include/ATen/ops/quantized_max_pool1d_native.h,sha256=HK392qLIUpe26ee_RXalccEenbusO2kl8TFxAel8V24,1089 +torch/include/ATen/ops/quantized_max_pool1d_ops.h,sha256=3nuPSb-TZBKFDdjXwl0c9vpJagvhz1vGAdo31wAetls,2707 +torch/include/ATen/ops/quantized_max_pool2d.h,sha256=n7Cw1nFwh0WTxGN5qXJFRvwtLWdIxZqD0716BrcwwVs,2251 +torch/include/ATen/ops/quantized_max_pool2d_compositeexplicitautograd_dispatch.h,sha256=1Ea3qbbHJ-FISD_PYCnTGCJNkw2-ySXciHjVVApPkho,1402 +torch/include/ATen/ops/quantized_max_pool2d_native.h,sha256=tWicl9hnkZ3lXOSHi2wpgAf6iHgB1XE02UEwTQozduI,1296 +torch/include/ATen/ops/quantized_max_pool2d_ops.h,sha256=1tbBoarO2v8UzDbjb9vJ8jbuYFkOWIzjI16dEfuUw6E,2707 +torch/include/ATen/ops/quantized_max_pool3d.h,sha256=SSEbwvl8pS4IaKXZKKmKrnhlf8BXRG0dSeyFN_WgOZo,2251 +torch/include/ATen/ops/quantized_max_pool3d_compositeexplicitautograd_dispatch.h,sha256=ALRVG5vck8nIrNpWrhYtbcXgD20U-mmhAO8T6sdNcVA,1402 +torch/include/ATen/ops/quantized_max_pool3d_native.h,sha256=fEQVDh31mm_JouOd9CqCYWV_9BPc4GZ-quoKuUYhVqg,1089 +torch/include/ATen/ops/quantized_max_pool3d_ops.h,sha256=9LLe7DDVeTUKGsa4mpSkL-ZM9mGNYU3DzoJLdwg9znM,2707 +torch/include/ATen/ops/quantized_rnn_relu_cell.h,sha256=rtqOVAZc1gYada_24zATRm7e_3C7yYU4PGHYguBRcp4,1696 +torch/include/ATen/ops/quantized_rnn_relu_cell_compositeimplicitautograd_dispatch.h,sha256=HjwjPjX80DSmtz6_iYjLB1xA8pwEKeD9pclOGZjLd4M,1415 +torch/include/ATen/ops/quantized_rnn_relu_cell_native.h,sha256=uQVATTp_Twcm76vKglNu7dVU5Spdb9M6yr1Rb4bFC44,1127 +torch/include/ATen/ops/quantized_rnn_relu_cell_ops.h,sha256=VpevJOyReHyE4-um0Nm9LCjng9tsnzovO8KdAf5wy6g,2506 +torch/include/ATen/ops/quantized_rnn_tanh_cell.h,sha256=zxN3OwhGY48MJqpaHdpt4PTb31Dnqp1GkPcOcH6QVZM,1696 +torch/include/ATen/ops/quantized_rnn_tanh_cell_compositeimplicitautograd_dispatch.h,sha256=JhXqJjT8JQnielLh15vQOXTtZ4epL4YeSnI5OckxWFk,1415 +torch/include/ATen/ops/quantized_rnn_tanh_cell_native.h,sha256=7kWFjiDJHPBbc0--3kWTfj88aJB02riZOKjUECdUQWw,1127 +torch/include/ATen/ops/quantized_rnn_tanh_cell_ops.h,sha256=BQBhu6OKofQ-HJATJhVQ-v-mzqWAultISlxCTR3jb_I,2506 +torch/include/ATen/ops/rad2deg.h,sha256=L20HGM_cphhO_glBxFJlHMucSwBjK5mNsfFKIrxsdIg,1436 +torch/include/ATen/ops/rad2deg_compositeexplicitautograd_dispatch.h,sha256=3o0DspkJr7-95oR08TysYEWhkltVTU0Peup0hGdbRA0,1230 +torch/include/ATen/ops/rad2deg_native.h,sha256=FONDrgrUReE-UKb82F9QzNUzzLBDvUQ6EWOsVzD-gUU,1288 +torch/include/ATen/ops/rad2deg_ops.h,sha256=D_UDLDxHI0i9q0-ClarEjV3fffayYJL2OYJr_lGHH3U,2309 +torch/include/ATen/ops/rand.h,sha256=b_i6ifdajlBvV4CXc3Abd-pMDdXeYXD8puxJ1v0_lKs,11786 +torch/include/ATen/ops/rand_compositeexplicitautograd_dispatch.h,sha256=eR3r7M_BgDbId6Q-5meRY9oBY6lYEyKg5NW_ABweuiM,2584 +torch/include/ATen/ops/rand_compositeimplicitautograd_dispatch.h,sha256=XOf4FXZWAbTzlUzB7cskBVUO_kEpRoAbqKa4NJHKv4U,1448 +torch/include/ATen/ops/rand_like.h,sha256=30z_hfw4t-yuh9iOHMGhHdIRVh5o9_-y_k_-a2e2RW8,4545 +torch/include/ATen/ops/rand_like_compositeexplicitautograd_dispatch.h,sha256=CvN0dq9YBvH6nUxFxlmRwmhEM0a1G-jiEQcUxr3H0ZQ,2488 +torch/include/ATen/ops/rand_like_native.h,sha256=HT1gOkkv_I0a7Bw8Bnq_-Y6ItReGxDTJiQ6nHoUbaUY,1586 +torch/include/ATen/ops/rand_like_ops.h,sha256=iSJJNV3bo6L95OOlMbuQS64lyPyaHWfcGUwzGO0xSXs,4922 +torch/include/ATen/ops/rand_native.h,sha256=ZV289ytNu0JAnBZ3HdyBA5F7WZM4C-BE-FP7GWcCDYE,1318 +torch/include/ATen/ops/rand_ops.h,sha256=6m_5DtLe9xWAeTHIFEMsArzZ3J65UluY1NE9Itv207E,4214 +torch/include/ATen/ops/randint.h,sha256=njWb3PkPu81pzt887dvG3XW-DT4AlHNPcjCvXz443BM,26261 +torch/include/ATen/ops/randint_compositeexplicitautograd_dispatch.h,sha256=vwKaTEFxcnvddIxK70wozO8bUsuJjazMa6yk2zFmOFY,6076 +torch/include/ATen/ops/randint_like.h,sha256=Zw_Vxq7aWmWJ9TvohMCmSUEKT2th60gkChh0KfgfNPY,37484 +torch/include/ATen/ops/randint_like_compositeexplicitautograd_dispatch.h,sha256=fONL8wew8dwgBwAzQHEq02udoQSfrzoIYtG2Way030s,9768 +torch/include/ATen/ops/randint_like_native.h,sha256=Hkr1PAIv-kmenkiuqmEGSbf1O5ThaBPfyCqLZm2BaZw,3792 +torch/include/ATen/ops/randint_like_ops.h,sha256=g2x8YQ8Of013u6o5pomIRbqj4mV1idUX0eD8NeP6Y1c,14718 +torch/include/ATen/ops/randint_native.h,sha256=_9fXPK6KxvBkYw692glbOoaJU1RBjjtYAM65UB3tgpk,2148 +torch/include/ATen/ops/randint_ops.h,sha256=NqJbnqsvSDhE21wK77NcrOF4wzYmypsWHptPd_fcR4M,8568 +torch/include/ATen/ops/randn.h,sha256=2ih9d-T5d2unHTdeFKX0zoJZsVHq8YfhuQ-TkvRaMEc,11867 +torch/include/ATen/ops/randn_compositeexplicitautograd_dispatch.h,sha256=7c3EjgfILbLrMdCL4pVhnbDcYHe5J9p6yBo23Wltahw,2276 +torch/include/ATen/ops/randn_compositeimplicitautograd_dispatch.h,sha256=1VYIrrAHNebbAnXhTKgSFOOzXlOoIosEeM_FrLtgNMk,1772 +torch/include/ATen/ops/randn_like.h,sha256=Bye3xG69AGctJD_t7_PzlYw-pqeCc2M10gpJrucG_AQ,4570 +torch/include/ATen/ops/randn_like_compositeexplicitautograd_dispatch.h,sha256=jqF_nztvdBs8m1hOoNbMIiqI7mxhxHFRy8sZX7tIYOw,2496 +torch/include/ATen/ops/randn_like_compositeimplicitautogradnestedtensor_dispatch.h,sha256=hMw9z46joIOu_8W6Y1_UDw-FOjzP4e0Y_5IiX7kM6cI,1880 +torch/include/ATen/ops/randn_like_native.h,sha256=gNfG4KdGjhnrtEf5SAeBiubZybXyfVGnlWL8sQDtpKY,1590 +torch/include/ATen/ops/randn_like_ops.h,sha256=467VLa2wSHK1s5eTsKY1F8vVveWUxK3VSmsJKmSfY6E,4934 +torch/include/ATen/ops/randn_native.h,sha256=ztpxyn7oIFCNp2J2PnB-FLSFH3GXNolnIvNsw9bvJeY,1322 +torch/include/ATen/ops/randn_ops.h,sha256=IUowTOOLjqUGLvWE_ZUbW9w_4E8F1J_79PKm1EU0uAk,4226 +torch/include/ATen/ops/random.h,sha256=4FaCZPsIRPxvaSP6BFBi2rYYQvgCBQXEzHUvDxyQgIE,3486 +torch/include/ATen/ops/random_compositeexplicitautograd_dispatch.h,sha256=RQARzbrmjpSbGq3ib7KJ0_49yrdbesOOKdkE86uHSmY,2230 +torch/include/ATen/ops/random_cpu_dispatch.h,sha256=5y06dYxMprv45Tg-Kl9suUtdQKD9TNo1ypAFXbxVEEw,1299 +torch/include/ATen/ops/random_cuda_dispatch.h,sha256=HQn61lwk7EluM2Z6rjylHyw6anPQSzZ5ronaozuefvA,1301 +torch/include/ATen/ops/random_meta_dispatch.h,sha256=mMiibvwYr8fUAoOjwrgZWGHm93ADVrWCuTjfHbC7hjI,1301 +torch/include/ATen/ops/random_native.h,sha256=it_BC0AlkZolxUUFDUC1odw0jUzQM8GtLHV5G2BjrKg,2260 +torch/include/ATen/ops/random_ops.h,sha256=Xqn52y11O6ku4NeEHbo4Tv8MoyoZ02GXN6Ivx9KKbQ4,7394 +torch/include/ATen/ops/randperm.h,sha256=glg9AJ3ylTt-pF6t0UBwdjYccM0cL_sVOM4xT8bq38E,11222 +torch/include/ATen/ops/randperm_compositeexplicitautograd_dispatch.h,sha256=y8aHVtjduxYUUjxN30RqfNShWOO_gONRU0Ih-8SYRJY,2528 +torch/include/ATen/ops/randperm_cpu_dispatch.h,sha256=CcsZ6VtbBGPvQLacoJpXYrVXkq31BKKegwEZ8yO9iRQ,1376 +torch/include/ATen/ops/randperm_cuda_dispatch.h,sha256=QJFO2xE4S14tv3dWY1-5PZHwwO0BnhC0BQG4UQYHpcU,1378 +torch/include/ATen/ops/randperm_native.h,sha256=n40UpAUEqfRjX_ERSgRyT8PcCtwwxn7KPUSvJ765A3s,1407 +torch/include/ATen/ops/randperm_ops.h,sha256=E5OPegkLeLj8SfKq5FMlgGbnL05-kMLH5B46VZxJ4n8,4122 +torch/include/ATen/ops/range.h,sha256=9jRvfb8oVPjUmarWv2-MwFkkQfUrZiw2B0G6k0F2P7o,3647 +torch/include/ATen/ops/range_compositeexplicitautograd_dispatch.h,sha256=fti55kETwhtEhgdNFUg6-qg8LdMXrBPtSeEIzzBF5bA,1883 +torch/include/ATen/ops/range_cpu_dispatch.h,sha256=NgaZ6eDxMoGvcMbTu8AOqhgXWo2y8n_Az88YySObO0U,1175 +torch/include/ATen/ops/range_cuda_dispatch.h,sha256=D1RSUE1eeOT0Z3gFgdpHzgSaBpPNGkbV_lAqr9Js4QU,1177 +torch/include/ATen/ops/range_meta_dispatch.h,sha256=ONjT2hjR5t6jpv1gQHWhO2Tl5x47ZOVBHabhw30HwDE,1177 +torch/include/ATen/ops/range_native.h,sha256=JowoZgl4hPVAnthjug-c7kzXhyxYDqmLTNfGlBmnJDE,1542 +torch/include/ATen/ops/range_ops.h,sha256=5jWNaXTdww0V-68Tit-7fYNq4MaQK7zJAn_HtEsDoFk,4390 +torch/include/ATen/ops/ravel.h,sha256=Us73mVpadnS2DLxLyr_dM9xEkReX8whvTchohGWoEfI,893 +torch/include/ATen/ops/ravel_compositeimplicitautograd_dispatch.h,sha256=AC0K5pnZnU2vsFpHbeXwalZGpbzvTPrSMNMQRb6BNSM,1017 +torch/include/ATen/ops/ravel_native.h,sha256=eAwJ7usg91zpuHC5DZugKJKEG6Yq3095MBcKclfDM3g,729 +torch/include/ATen/ops/ravel_ops.h,sha256=QJe1iqrrX9mfUm9J0RO8mlyF391AzjqV6Dwox0RhJAU,1214 +torch/include/ATen/ops/real.h,sha256=m0C_rkM1UXEnQIPUDJNALKA-JshQphvqg_ePzmbz0ok,889 +torch/include/ATen/ops/real_compositeimplicitautograd_dispatch.h,sha256=rCcPKi6vWpwyZzllVskusj328A7fJPZ2fDWMzD7IOEw,1016 +torch/include/ATen/ops/real_native.h,sha256=1trlUHuin7b5xra45F4tKGv0yd6lkfri3KmEfHoHKi8,728 +torch/include/ATen/ops/real_ops.h,sha256=uSC3nf7sYq8TzgRdU7tZOWMXDvkX_GXHRHu2M2GN8KU,1211 +torch/include/ATen/ops/reciprocal.h,sha256=-jPdvliiLlx75gZjTXlxE1cgJGzd7uHwaJztSt2uKQY,1475 +torch/include/ATen/ops/reciprocal_compositeexplicitautogradnonfunctional_dispatch.h,sha256=MzlFb7uHD_H2hvkP36WTwOeP4KhlqSReNipxxKkEook,1103 +torch/include/ATen/ops/reciprocal_cpu_dispatch.h,sha256=884lW1jzF7CnpFMGCjjWv3LNhoX_aPBNbCNndYJtoTc,1198 +torch/include/ATen/ops/reciprocal_cuda_dispatch.h,sha256=DVAjuichl9gnssKsfWiKIf9j1boRPAojCxXGc6IvQzI,1200 +torch/include/ATen/ops/reciprocal_meta.h,sha256=Lec4KaLukDNry0qos2trLid9M2ktfWOqmJiv7p-o18w,825 +torch/include/ATen/ops/reciprocal_meta_dispatch.h,sha256=Ckqjj75BMxtx9YUibhR2fqybidHIm-RopIxakiczAYk,1200 +torch/include/ATen/ops/reciprocal_native.h,sha256=0XFprc6k6yhPWw2BlDPJ3_rjQ2PNbwDAGIpULZ0zOhY,862 +torch/include/ATen/ops/reciprocal_ops.h,sha256=qcX9FWoThII9ldlSbMcKmms_LRrfRUYJC64Skl0VPcA,2336 +torch/include/ATen/ops/record_stream.h,sha256=RIphFBPfEIjMJvONie68kSEHYP6Kw9ecpzGsF4MHrXY,764 +torch/include/ATen/ops/record_stream_cuda_dispatch.h,sha256=8bjzIFiPwQP-wQcK4VjOV_nmeWozPVV4W1fStlmmT2M,985 +torch/include/ATen/ops/record_stream_native.h,sha256=1hwm6nRo6gwRXqb_96AdOdWBtyO0Sy_We-pDb_g96vY,744 +torch/include/ATen/ops/record_stream_ops.h,sha256=LGYJDo0kliPFdM-Rqdyd__hPI35vTr49u8ei_qSUlgk,1246 +torch/include/ATen/ops/reflection_pad1d.h,sha256=UY80qaP1xwTwjnTzCbyJlzP80PenYTeEVMgAQJ2-7hM,4151 +torch/include/ATen/ops/reflection_pad1d_backward.h,sha256=l_ePIfxYV_9pSp5LZdOn6e9p-K7T07cM5le4f02jdM0,5314 +torch/include/ATen/ops/reflection_pad1d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=GhYCZL8SysRsZuyOLG0JCeQBjqrGmqMZFZSjnNCPXAA,1261 +torch/include/ATen/ops/reflection_pad1d_backward_cpu_dispatch.h,sha256=KEEVFzJvAZpp5pl_0OxQKWJ-ImpZhRHwUArtOyJV2bQ,1859 +torch/include/ATen/ops/reflection_pad1d_backward_cuda_dispatch.h,sha256=ZMPaRICpZcX5vQ2w3Q5cJxXovmYu75HOoVMilyYOON8,1861 +torch/include/ATen/ops/reflection_pad1d_backward_meta.h,sha256=HfZKDgWXyER7MSi-zWZs5MCiPSlr9iZd67HMpOeJr3k,903 +torch/include/ATen/ops/reflection_pad1d_backward_meta_dispatch.h,sha256=-qrCLdT1ByDqg3ep310A2cmL-y_VtHc58MLctuiiUwc,1861 +torch/include/ATen/ops/reflection_pad1d_backward_native.h,sha256=v4GA8PqAwxNvhhmAAmJmKxAn0qlBLpmFP5o_btw_Czc,1235 +torch/include/ATen/ops/reflection_pad1d_backward_ops.h,sha256=C-Ot0cNPNt731FYDBlGyYFqz_PAA-lJOYLU_bcAtasU,2361 +torch/include/ATen/ops/reflection_pad1d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Y3HT-6Bl8eno5h7t4mmJpx7sYBmI4MJqckzwHh2WwWM,1179 +torch/include/ATen/ops/reflection_pad1d_cpu_dispatch.h,sha256=dmhfwd8xYTgFlPdvXssBPFiSa2PyAqcxwvbSqZzTsPg,1585 +torch/include/ATen/ops/reflection_pad1d_cuda_dispatch.h,sha256=W-98_P50XzYFfIRx9e56e6I7sa8hPnZKi06p-1p4TO0,1587 +torch/include/ATen/ops/reflection_pad1d_meta.h,sha256=NrvYNVehvn2rINRc-ruhBsjWqv-VMHi4GZttwDzNvNg,862 +torch/include/ATen/ops/reflection_pad1d_meta_dispatch.h,sha256=Cv-E_PFMykunJOg9uAm06A5P-j_W6jjFOuMv0AD3pQ8,1587 +torch/include/ATen/ops/reflection_pad1d_native.h,sha256=1Tq0P9chLbvTfXY8NUTCj1GF3s70XvcqRbWM8niAIAk,1239 +torch/include/ATen/ops/reflection_pad1d_ops.h,sha256=mw1r3HxWJ8vRDaq47s7IjFL_5HOxGoDeom-QPeuBw2k,2057 +torch/include/ATen/ops/reflection_pad2d.h,sha256=U2BRBYRegUdF68QuSKXuYMImup7W1rpEUYL3K3rAnHw,4151 +torch/include/ATen/ops/reflection_pad2d_backward.h,sha256=Bt0OJNNkuezIEjx8TRqFmcoVtvQR01X2gGicQrNxnQA,5314 +torch/include/ATen/ops/reflection_pad2d_backward_cpu_dispatch.h,sha256=pNJcHalJIeC8dMO1avdOn8V_l4yRdj88rB0n_KBT-c4,1859 +torch/include/ATen/ops/reflection_pad2d_backward_cuda_dispatch.h,sha256=NLhnKGeptuWQHOz28zr8esQEW_Cr7CU0jEJbFPPCOZA,1861 +torch/include/ATen/ops/reflection_pad2d_backward_native.h,sha256=Kb54ajQxtyrF8DQyXw1jkHYs68l44yT8BuCU1jfG84k,1276 +torch/include/ATen/ops/reflection_pad2d_backward_ops.h,sha256=KlqPoRnuoo0wqoUJyA-Z8nxDrbZyaKVIymyj3V6z20o,2361 +torch/include/ATen/ops/reflection_pad2d_cpu_dispatch.h,sha256=QlzzQ90f5NZevfBtPakBCJ_Xjnins5CeqlqZh9wUuoQ,1585 +torch/include/ATen/ops/reflection_pad2d_cuda_dispatch.h,sha256=429oLBFEnPJ_szzCa4HqO7mq-XIbq3Q90FO98Epd-Fk,1587 +torch/include/ATen/ops/reflection_pad2d_native.h,sha256=6WnpsEvizH8uJTHRJ22doRG2krJbERDIFnDv6S0gWbg,1201 +torch/include/ATen/ops/reflection_pad2d_ops.h,sha256=3wQ4XITmP_quFNIijmfJIXM1sVA59JAVsxOzgUGu4vc,2057 +torch/include/ATen/ops/reflection_pad3d.h,sha256=vcv1E1zsthf-Cl8inuyzbQh7y2QeOmWQ3SNVQ4jdZQw,4151 +torch/include/ATen/ops/reflection_pad3d_backward.h,sha256=2_x1myub93IM9lkKd1-Iee_GMbaJsxXiNqlEGFi-o_4,5314 +torch/include/ATen/ops/reflection_pad3d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=2SIEA00zT0m4Wou2NODQAsjQHp_SR1w6A6eZWFUk-1A,1261 +torch/include/ATen/ops/reflection_pad3d_backward_cpu_dispatch.h,sha256=9ZtGHIQF9UZ8Z2tlVlLaMAxVZD_jlY626savtIYWAsk,1859 +torch/include/ATen/ops/reflection_pad3d_backward_cuda_dispatch.h,sha256=9lxLgRM5r31_jSMzE7OEtjDkB66EyZYTm4gaXdqDfqw,1861 +torch/include/ATen/ops/reflection_pad3d_backward_meta.h,sha256=5WDCmDFE-DcReKo6EQvv7_fFPi1l85ayObZyUWs6Cvs,903 +torch/include/ATen/ops/reflection_pad3d_backward_meta_dispatch.h,sha256=octYefl8wyWJTLYppgLCvifFttsVTnGBEC57kPpUEdU,1861 +torch/include/ATen/ops/reflection_pad3d_backward_native.h,sha256=WvVpG4NWP0LAykxK3LmSODOI3qGLYlPsXl2md2BNdeo,1235 +torch/include/ATen/ops/reflection_pad3d_backward_ops.h,sha256=zozrXunXGe8dcJkZccp8MmmMeVolQHR2JyjWtSRiMoQ,2361 +torch/include/ATen/ops/reflection_pad3d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=aEKFUkbofzrEEOrprIQ86Au9hHwu8B0yTqHz6dhageM,1179 +torch/include/ATen/ops/reflection_pad3d_cpu_dispatch.h,sha256=W23FfB5owb-t2-alhkZ5DsrEB0MfRFLfqN4EqquUZXQ,1585 +torch/include/ATen/ops/reflection_pad3d_cuda_dispatch.h,sha256=IiNHvHicpEu8C_FJNQXrzHb2EMEzjeOhpL7LaWHnD08,1587 +torch/include/ATen/ops/reflection_pad3d_meta.h,sha256=Tbc3adBTs32m_HsQbEmyr5CtN4jNHl88OpAoHWpk-10,862 +torch/include/ATen/ops/reflection_pad3d_meta_dispatch.h,sha256=wOnhEYo9ZRnHwRw06pRKGYNfaK8Tv4J6b7SfAxNe9Do,1587 +torch/include/ATen/ops/reflection_pad3d_native.h,sha256=Ew3mEzMDoMkyh1mQT_p4ClHNFkbrEq-TwgqkoIya4J0,1112 +torch/include/ATen/ops/reflection_pad3d_ops.h,sha256=VPAS7x6khaZsrlqsDYwSiLpJ17mvXh1oBFKn4tru80Q,2057 +torch/include/ATen/ops/relu.h,sha256=M3Ode7artRDDTJwUeP9z0Y7vuic5Bn-5B7XPDxeozG4,1397 +torch/include/ATen/ops/relu6.h,sha256=ICGrAtEkkJq-pTGwPKXwXXhaAoCAcVdgfKP8DBaIQUI,1026 +torch/include/ATen/ops/relu6_compositeimplicitautograd_dispatch.h,sha256=EbYthn2TW62VG-_1Jxn2M9QrFDiPCv97xqk8PbQhcHA,1067 +torch/include/ATen/ops/relu6_native.h,sha256=ugDbunXLVeeYsmMEhE2Ud8AE_82blKXS59JT4JwjG64,779 +torch/include/ATen/ops/relu6_ops.h,sha256=5iT80HKY2kHHZ2oIsA8v8vpXYBdy-hoG_DYZ4rr9E2c,1704 +torch/include/ATen/ops/relu_compositeexplicitautograd_dispatch.h,sha256=cC0-1b2VlMWkpFmygY8D_6reYLz8zBFsWG87sS8Cc7A,1117 +torch/include/ATen/ops/relu_cpu_dispatch.h,sha256=Qb49RqVhCTNvYT3ZLhrubXoTe9H7BzH5QXxXdUoGASQ,1021 +torch/include/ATen/ops/relu_cuda_dispatch.h,sha256=pucxk11bsv6dE1lSMY4LLcNLQzzBlZm2g5QvzS7coO4,1023 +torch/include/ATen/ops/relu_meta_dispatch.h,sha256=xRDQYzYoXHu1QT1uXCKU8QBLRMY9l-LUYQdo_cdQCtk,971 +torch/include/ATen/ops/relu_native.h,sha256=oU2xN_7HRLREco2-tF5P1Ke_1UIP4zkoi83rwepV7sE,1593 +torch/include/ATen/ops/relu_ops.h,sha256=DxhQlofLOB1ibY4VFqHroBkh990x0YUJOzOw1KYqHt8,2282 +torch/include/ATen/ops/remainder.h,sha256=Osj0cmtCbG9_xjdA0Ea05djtjQtCqIqwdGMvBgTpIeA,3006 +torch/include/ATen/ops/remainder_compositeexplicitautograd_dispatch.h,sha256=f7qvcs7gqzV7SJAtoroztt3vY28spb9RvfJhK7boqVA,1557 +torch/include/ATen/ops/remainder_compositeexplicitautogradnonfunctional_dispatch.h,sha256=b8GiBfPhw-i-M4lqSEhj6Rk1kurCUp3ReqVk6rNO_l0,1153 +torch/include/ATen/ops/remainder_cpu_dispatch.h,sha256=8gsBJAMsOZsYbC5W-SIfPSiXXHOI-lp8fA0Lxko-F8U,1381 +torch/include/ATen/ops/remainder_cuda_dispatch.h,sha256=1BaJazlSaoBWqeX7onZpZBpiNE0JXkWh0qVTuYmfrAc,1383 +torch/include/ATen/ops/remainder_meta.h,sha256=6Z_ncBROTEATuHdn3NOZREIk7costpBZo_GJVz8WdQw,857 +torch/include/ATen/ops/remainder_meta_dispatch.h,sha256=Rw0QVtedtDa3RNVwFUqohTNJYutFnGEnD4toZrPMITU,1300 +torch/include/ATen/ops/remainder_native.h,sha256=m9IlMYru23jQPFB4oC5otTHGGvpprGOlxpGFHQF_r7g,1366 +torch/include/ATen/ops/remainder_ops.h,sha256=1zDq8kbwdkTk9tOAhhtTk6QbbiP-XpdQsASuhwlwvMo,5944 +torch/include/ATen/ops/renorm.h,sha256=iVTnx6dEppCbuP10wa4yu-F4ZLQ03aXRerV4SEBXNNw,1626 +torch/include/ATen/ops/renorm_compositeexplicitautogradnonfunctional_dispatch.h,sha256=eBFw2KmDCM8MhgwMklqnqOTRLvvHLR7fygVGDrMR8yo,1221 +torch/include/ATen/ops/renorm_cpu_dispatch.h,sha256=Q34m2YPI2fwe0vvH7sw4ct5HsCJBxgSvPEKHBBN_ZYw,1434 +torch/include/ATen/ops/renorm_cuda_dispatch.h,sha256=JNc-OZogwv61mKLJEwaZ237zpUJ9xe7Vh-sSJ6WnbM8,1436 +torch/include/ATen/ops/renorm_meta.h,sha256=SuPJShyv9iubL3yXxNhrNfdogFrjQL1LhF0HWZbl3eM,884 +torch/include/ATen/ops/renorm_meta_dispatch.h,sha256=M9L9XchacR90S91h9CJ93WwttKC_TpMCHO4krZEcKqo,1436 +torch/include/ATen/ops/renorm_native.h,sha256=gPXoREEzazMNB0Yj63y5QcQop7Qaclekz_fhgq_KU-g,913 +torch/include/ATen/ops/renorm_ops.h,sha256=l0n_35vl_Nh_0Z8w0nWxmoA_YwS4T9qbQWSbAh5c4-Q,2930 +torch/include/ATen/ops/repeat.h,sha256=YYm-DhJ_s26M5-w_FbF0oafvhEegOI8VMH9oqZCbNSk,3426 +torch/include/ATen/ops/repeat_compositeexplicitautograd_dispatch.h,sha256=PugdJDXjwh-4gHRkyn-J1ahorV8kc3YwxbrJ6ZOI-v0,1569 +torch/include/ATen/ops/repeat_interleave.h,sha256=Y-4qkS3MMNsGpSnZ4bLt4R5FDuTeMpK1ppEOz8PmuBA,8532 +torch/include/ATen/ops/repeat_interleave_compositeexplicitautograd_dispatch.h,sha256=EtEDxoHAP6q01p8VAyHx5XRzsh9ueo36219v_9ziwII,1538 +torch/include/ATen/ops/repeat_interleave_compositeimplicitautograd_dispatch.h,sha256=ZsyN3yZkPLg2GnR_qF9u8b3jxhAS752bvG54-d5Y7I0,1732 +torch/include/ATen/ops/repeat_interleave_cpu_dispatch.h,sha256=shAe6RFMhoFaCY9Xv5wHxvAhkT1VX-JbvNDPIm8vA7I,1173 +torch/include/ATen/ops/repeat_interleave_cuda_dispatch.h,sha256=yorsUGfSYSBJej10a4hbmllPv5a1-nCk8otaSYC0Ado,1175 +torch/include/ATen/ops/repeat_interleave_native.h,sha256=-Yl0xyzyqzPMN-acziJ9jmD4PUTjx_akkHsQwJ6imTI,1472 +torch/include/ATen/ops/repeat_interleave_ops.h,sha256=iKDfyew8-Ujy-HcIbsyomZ7ESI6pNQ3TScMywdGjK34,3987 +torch/include/ATen/ops/repeat_native.h,sha256=VNKlb3YGWgZpyHAj6cEJLXofU94obelDdw2K-Bp5JZk,869 +torch/include/ATen/ops/repeat_ops.h,sha256=_InN0wG9mFg54N1wraWlHODJcxR-Ut7kl8cvpN_bEnA,1995 +torch/include/ATen/ops/replication_pad1d.h,sha256=Cwwr5gTh7z_vO1S8VrmsuhHt1IErOJN-esgl55p2ML8,4182 +torch/include/ATen/ops/replication_pad1d_backward.h,sha256=Sog_edg4WD0M3KGBGov--52l9aNyeX_VqGzEvelMLwc,5345 +torch/include/ATen/ops/replication_pad1d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=ptIHUmH-yJIfW2e2hh36zD1davS_sXX-sPclDErSj_0,1263 +torch/include/ATen/ops/replication_pad1d_backward_cpu_dispatch.h,sha256=aKJrgYCMFXNpCDbq8N5y9ritvnfj1o9p9ZQ_ouu7f10,1865 +torch/include/ATen/ops/replication_pad1d_backward_cuda_dispatch.h,sha256=mN-qmRr3cAuPD4waigfdpyjkSTd3tBzJO0xyuRBUyYI,1867 +torch/include/ATen/ops/replication_pad1d_backward_meta.h,sha256=D-aHDcGfrkMnfrRSBI1FGCpxhKp85hpKMg_drn6IYNQ,904 +torch/include/ATen/ops/replication_pad1d_backward_meta_dispatch.h,sha256=mLR6otC481JtqHcJ40W98U0IdDQlyAXKr3B_tetuSn4,1867 +torch/include/ATen/ops/replication_pad1d_backward_native.h,sha256=ojNbOUubaj-hmrVF5xx0XKY43oa2QzYdkuqO15n35Ok,1240 +torch/include/ATen/ops/replication_pad1d_backward_ops.h,sha256=WOUl6RE2fUjCO5UqRxgLWW9QSaWboGc7d234WisbuLo,2367 +torch/include/ATen/ops/replication_pad1d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=_sg7u1j6ORuRstakmnogDMQCKqbpf6PSF4Pl3_xKHSQ,1181 +torch/include/ATen/ops/replication_pad1d_cpu_dispatch.h,sha256=s0uH7ECJUBJVPN7DKz2Z7HAHK62qn8qJh91dXkxyF08,1591 +torch/include/ATen/ops/replication_pad1d_cuda_dispatch.h,sha256=hfJsQXlPy_uYizytPiJAm_u6KRma0N52OMxkXtkIgX8,1593 +torch/include/ATen/ops/replication_pad1d_meta.h,sha256=LbHofGuZTUhPrNbUN0SouXhlEs6oeKUYH2LfdD37qNA,863 +torch/include/ATen/ops/replication_pad1d_meta_dispatch.h,sha256=N2RC2miI99rOtgYEUdPyUvFDGPsiokvVBul5GbiqGLk,1593 +torch/include/ATen/ops/replication_pad1d_native.h,sha256=Hu2sj4UXDLX1gY-uiDB1wfVxpzTXquuhDk_OOAUJ7o0,1117 +torch/include/ATen/ops/replication_pad1d_ops.h,sha256=u-1lNbPLVpEmS9Xl83bmFiPhih_9e1GbFTQ2G8PIhYk,2063 +torch/include/ATen/ops/replication_pad2d.h,sha256=j-SSJ4Co5-s8jfGCJVoPPF74PYrxg8FLfNzVgd8Qpho,4182 +torch/include/ATen/ops/replication_pad2d_backward.h,sha256=eMFa6-htInS6xdgFvthcDlkqQkhTyU0xdVllVjpg3H0,5345 +torch/include/ATen/ops/replication_pad2d_backward_cpu_dispatch.h,sha256=pMkRopxXrFVDzY2k5t13uvUZfZmb61KgdZiypMrLvHk,1865 +torch/include/ATen/ops/replication_pad2d_backward_cuda_dispatch.h,sha256=Ro8fxz3Kjpto5hkY9KTa4KXN5l9rx-ZZ3rupR11ivmY,1867 +torch/include/ATen/ops/replication_pad2d_backward_native.h,sha256=78qaewhRA62UU6_r_UnovcXOCdnkYMmXuRqj5Wrk06s,1280 +torch/include/ATen/ops/replication_pad2d_backward_ops.h,sha256=QvaIkBT1o1G1qu_uGU6Zc84aMIKr18yBsH9C01aNc9A,2367 +torch/include/ATen/ops/replication_pad2d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=6ZGMXo1s7QCVxgCqQlNgPsEMYZeoTl_cWSyQkyIJsyA,1181 +torch/include/ATen/ops/replication_pad2d_cpu_dispatch.h,sha256=IOb1LrLtTR9xpkLblAJwymYRIOCJFF7cUrdupn9gZgQ,1591 +torch/include/ATen/ops/replication_pad2d_cuda_dispatch.h,sha256=nIOrAOck57QzDRYox84FLcJR0p_iPWMpQ2meGQiCOBw,1593 +torch/include/ATen/ops/replication_pad2d_meta.h,sha256=HXnrb9UY0UTBQVM4dIZH4WBD9EHOUdA7XLLMv2gmUz8,863 +torch/include/ATen/ops/replication_pad2d_meta_dispatch.h,sha256=LYKHPDh8ZTHI4a3LdcGn9AS6D-l9_TsHPdmQue-78pA,1593 +torch/include/ATen/ops/replication_pad2d_native.h,sha256=D_tAYx7prU2vov8QqKdzkovxZpanVNUF-OcWCQdX4BU,1117 +torch/include/ATen/ops/replication_pad2d_ops.h,sha256=-HeNAHmbzIaGMe850EvzYTHE4T8gy0KuW94c9Rd8pKI,2063 +torch/include/ATen/ops/replication_pad3d.h,sha256=9Myy1sd0Ss5uhCbMRyYzEboEiWhcmzNgDD4LT-mBM1I,4182 +torch/include/ATen/ops/replication_pad3d_backward.h,sha256=QL0tSpeBNIdIuF6Y0fa_lASmmsjsYnhKRV0PVnCUZKE,5345 +torch/include/ATen/ops/replication_pad3d_backward_cpu_dispatch.h,sha256=kESHBTy6QmdNspXp9gXz-dvtbCyCpDqCQjVjwTOE_Xc,1865 +torch/include/ATen/ops/replication_pad3d_backward_cuda_dispatch.h,sha256=pdMrLi4PG-uwoMf1l_amc-48jemiPTj81SOn8drlkrw,1867 +torch/include/ATen/ops/replication_pad3d_backward_native.h,sha256=g3VedJAwiddBH0gzEruWx6t9U0-Fb7LAxzSM_0Www2k,1280 +torch/include/ATen/ops/replication_pad3d_backward_ops.h,sha256=soIB8cO5lGaJ40ZgK_IznBlyNUordqRoDUgUu3PCjBQ,2367 +torch/include/ATen/ops/replication_pad3d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=KTBVCkRZRdU716CPOZDlrkihHntPQSZZ-VOQs2qx_Bc,1181 +torch/include/ATen/ops/replication_pad3d_cpu_dispatch.h,sha256=VOAZ6H-eFE5cnkYAkoth8OCBB_on_W2f20DK_6IKECs,1591 +torch/include/ATen/ops/replication_pad3d_cuda_dispatch.h,sha256=0Lid9SfKQrp3v-t1yE8fZ_W8eVo_URlCezWPKJOVdoY,1593 +torch/include/ATen/ops/replication_pad3d_meta.h,sha256=DrvZTdrbcwjLdghvk91yc4GKbYVTu5QJaj_WAgy4F-0,863 +torch/include/ATen/ops/replication_pad3d_meta_dispatch.h,sha256=jZ3CXGKCFnjCeDJDjW4kpYcSxJMmUZ-nO-rohuvsbTA,1593 +torch/include/ATen/ops/replication_pad3d_native.h,sha256=iNTK6Kb9ieuCPauTpy2XL3wrX8jqC3nwdM8qZRn6pmk,1117 +torch/include/ATen/ops/replication_pad3d_ops.h,sha256=h2IX1Stq3tUdVJVlDmy2Ohv70EtHIuPPZiXAwwIdFpI,2063 +torch/include/ATen/ops/requires_grad.h,sha256=iFzT1FldNNBKBzludNNejfGosc0lzv9YwmIzn9kp2y0,764 +torch/include/ATen/ops/requires_grad_compositeimplicitautograd_dispatch.h,sha256=qpBzni24u10t6eWB8pr6BiXwnVSH3VkhLCBpMF5xkH8,1047 +torch/include/ATen/ops/requires_grad_native.h,sha256=61peM-jUV1s8fnwW5-dexOp26T3pzTrqdYTOblB8cw0,759 +torch/include/ATen/ops/requires_grad_ops.h,sha256=RpnooLnkLyku83_od4jMsoeqb4f_0cBPkrBfvJkbas4,1302 +torch/include/ATen/ops/reshape.h,sha256=BFPfub9tIH_UvNfI2Xa9M7vSnIKis5aOSYGagW-i07Y,1660 +torch/include/ATen/ops/reshape_as.h,sha256=DyGu6KKfYZvSfk7pTmKSKCb_2Nzf1wsYU4STx56gnRk,761 +torch/include/ATen/ops/reshape_as_compositeimplicitautograd_dispatch.h,sha256=j60g1mY6selAp2GEywCligywln4mX81FSS-rOorA59A,1048 +torch/include/ATen/ops/reshape_as_compositeimplicitautogradnestedtensor_dispatch.h,sha256=HVZk13u_G59WiO8A6VQHYtfNSWGUQRy8bJOb_DYyS9k,1072 +torch/include/ATen/ops/reshape_as_native.h,sha256=-2G3gv7vc5iWNGpXsoSL6ji-hLvMgXsyL6PxxJeHdVA,851 +torch/include/ATen/ops/reshape_as_ops.h,sha256=jN_y295lfb9P4x_FqYcPRMFpYjpESJ4xOESDhluvkpU,1315 +torch/include/ATen/ops/reshape_compositeimplicitautograd_dispatch.h,sha256=o3mwg7Q83CjaBB5j5GstvmonxCr4fOR8Jiz2r5iahF8,1131 +torch/include/ATen/ops/reshape_compositeimplicitautogradnestedtensor_dispatch.h,sha256=DTOxteltG44ExFj1M14Fhg0PkqzSOKlwIvNET474ba8,1155 +torch/include/ATen/ops/reshape_native.h,sha256=uvmBO9ee0wTP5egkqawAgEiiIYpc9Kbdve6I4IWoFP8,861 +torch/include/ATen/ops/reshape_ops.h,sha256=wwnp5E3vhULEg872z7mVOcbvAd3Al4YBztROjdUIREg,1311 +torch/include/ATen/ops/resize.h,sha256=IYWBHzf7PLdQ_wCeEIPuCH5PwLYnJNLkmA8N88TARQ0,5597 +torch/include/ATen/ops/resize_as.h,sha256=xamaWvIy-wwV1DZdmPECPFyezAN6lA81U8XgE_Dn3P8,2213 +torch/include/ATen/ops/resize_as_compositeexplicitautograd_dispatch.h,sha256=3mgsgd8Mtnt9TRAkS_-Ps0GIFYBX8p_k0JxS4TVMIrg,1647 +torch/include/ATen/ops/resize_as_native.h,sha256=sAGg-38LAahm5nCb37WZuMTedvMX0NjCY9LTYHWiOtY,1168 +torch/include/ATen/ops/resize_as_ops.h,sha256=jwl7hsDw3suTcTHvT65bOv-2D3D7SJyekIa1hgSJ_5k,3227 +torch/include/ATen/ops/resize_as_sparse.h,sha256=M18TmIwKH7-oPvmWBcBLdDe4-mP7nbEZZ25IAqmm2BM,1861 +torch/include/ATen/ops/resize_as_sparse_compositeexplicitautograd_dispatch.h,sha256=0wGvXBB0qLc-jaiQMrN0MJKKh38WyYErTsJiNrpgm5w,1328 +torch/include/ATen/ops/resize_as_sparse_meta_dispatch.h,sha256=kmEBxHWIW5pGQSiyH99RxSZWcbnN5vnF1JzqTIzyNFQ,1028 +torch/include/ATen/ops/resize_as_sparse_native.h,sha256=yCAnsL6Ip1bw_54pvNDvALeqxoGsoIndHCFlUxzsLrs,1129 +torch/include/ATen/ops/resize_as_sparse_ops.h,sha256=o2QWVMV_tzrk7reFnpKJJq0Dyh-gsfXeg7wP6Eayw_U,2783 +torch/include/ATen/ops/resize_compositeexplicitautograd_dispatch.h,sha256=wHQiylJRlA3iFcCxep4HlvZnnEc13Lxi3vtrtrbHC1U,1953 +torch/include/ATen/ops/resize_cpu_dispatch.h,sha256=H1lLuHJ9Axfc2vaT1LwLn5_0ouV3D_ff1IqMwBSXF34,1229 +torch/include/ATen/ops/resize_cuda_dispatch.h,sha256=MaC2QglQnPogkHx2fkeSYD2LeMCT7o1Mm_OZICes6cM,1231 +torch/include/ATen/ops/resize_meta_dispatch.h,sha256=nPcAMuZrV8bxIwPtyEN8lnS2kF1msjAEd9suelYjMFI,1231 +torch/include/ATen/ops/resize_native.h,sha256=oppUtU3hm5OC9gCoiCMgpDR4NEJxwq4kR8xCHODdar4,1785 +torch/include/ATen/ops/resize_ops.h,sha256=DFHPGOw2Md-c1xWrfdPMIcIfRq6osG0kfyoEyGHrBIw,3143 +torch/include/ATen/ops/resolve_conj.h,sha256=pZtPlWnWRIbY8W-7LCBdfLbe_sTs-Bo8KsKyjp2_uKc,921 +torch/include/ATen/ops/resolve_conj_compositeimplicitautograd_dispatch.h,sha256=MMWJp6bkyNCnSl8beG7msh9bueBVklGsW3s8fIkXQFw,1024 +torch/include/ATen/ops/resolve_conj_native.h,sha256=scu8vXMMNhYOyHvKRB5HK2oowzOOh2SoS71jCo7AtCw,736 +torch/include/ATen/ops/resolve_conj_ops.h,sha256=WNfXTJeGcOYue_QDzUz5EZaps7ed5O08SzR1wVWm67w,1235 +torch/include/ATen/ops/resolve_neg.h,sha256=9UrAcYJ5Aqk-N3a_pRN0GDU_8fyATM1LyWT7IM_dDyo,917 +torch/include/ATen/ops/resolve_neg_compositeimplicitautograd_dispatch.h,sha256=vMcqr1afLV42uFe_dT1SX1BVLdd3yA7I7Hsq9QPVkHE,1023 +torch/include/ATen/ops/resolve_neg_native.h,sha256=tyQGWZmAnkl8KI7bdKtrol10brhZ_LpAAGg0PN1KKZ0,735 +torch/include/ATen/ops/resolve_neg_ops.h,sha256=p-s6jTrwrCdaHs3CLZX2AqAjAqtrDD_VvDxk30NG18U,1232 +torch/include/ATen/ops/result_type.h,sha256=3in95uv0aS1mYcr59Cwnsr0mhxPshdDR9WqGN57QvMg,1701 +torch/include/ATen/ops/result_type_compositeimplicitautograd_dispatch.h,sha256=vxGsMgAasADhF1SGQlAJDMSZA48UmdFxErNn56u7KWk,1332 +torch/include/ATen/ops/result_type_native.h,sha256=UMIeRIFjJLjuBE4c_f3BJxiZl00lSfadXDxp0ql2BOc,1044 +torch/include/ATen/ops/result_type_ops.h,sha256=WcXMZ86xsqfnLoZp4ndfKEW64AKrop5u3HZh6KqE5CE,3337 +torch/include/ATen/ops/retain_grad.h,sha256=bUNZdCHtNiwc-z-dw5xsHy8G3vPB7JMIo5AOQt4IOBY,762 +torch/include/ATen/ops/retain_grad_compositeimplicitautograd_dispatch.h,sha256=4K4BImGp96Lihs7BA32LkVKIFKfcgQHIdMXmA-5zuNc,1011 +torch/include/ATen/ops/retain_grad_native.h,sha256=96yVKd7RmXZLe7G_b52YchMTiEDCQmknNbAEh7raJ2I,723 +torch/include/ATen/ops/retain_grad_ops.h,sha256=GhFUc4kf8X2UO_5tQxBeeHeh-WoKRBGJrQEWb4ZgLi0,1190 +torch/include/ATen/ops/retains_grad.h,sha256=5BkCy3-WJP2_U_c8cWOEJlUHjCvt9CzJJoMmQSt_fno,763 +torch/include/ATen/ops/retains_grad_compositeimplicitautograd_dispatch.h,sha256=ZRoDPXbg-uJRZMQ6WpvW_DSLLiHe4yk8RJGOFiT8zEE,1018 +torch/include/ATen/ops/retains_grad_native.h,sha256=hb-WUlpilDpbV1YIOEvArLprzHaKglof0WkX9PAo5sw,730 +torch/include/ATen/ops/retains_grad_ops.h,sha256=V_SQL20VIOniAonJ5l-IluUsFw2r23EVy8I90Oh1YG4,1209 +torch/include/ATen/ops/rms_norm.h,sha256=xJQba4oZBg-DWe7WRJ1f4jW_fqgdDGntvmap-BUF8rc,2271 +torch/include/ATen/ops/rms_norm_compositeimplicitautograd_dispatch.h,sha256=b8SYQoMbJd7sAo8mPdTWc7hbJdVCIVv_tMe8NzpxZZY,1339 +torch/include/ATen/ops/rms_norm_native.h,sha256=-JNHx8yW9UgXOio0PInQcoe6kAjdZBuplaySltW1Vn8,869 +torch/include/ATen/ops/rms_norm_ops.h,sha256=7bCTm0b043x4416xi5mI0s5zVYdmtvhStOLskTTS0us,1590 +torch/include/ATen/ops/rnn_relu.h,sha256=QEwxcBWyy6jWgWgwJMM9iRS1af0lcL7QSTKPXjO4IBU,1861 +torch/include/ATen/ops/rnn_relu_cell.h,sha256=m2yH1O2fDnqCVtf0mIUt47I1ymuvvu07MCulmFZewec,1188 +torch/include/ATen/ops/rnn_relu_cell_compositeimplicitautograd_dispatch.h,sha256=HinWxB7fWsAmQ9q2ydL9LDUmIefTXlBWbsOYuSehX-Y,1189 +torch/include/ATen/ops/rnn_relu_cell_native.h,sha256=9tzEeeaTW5EdDefnrthG6D6dq2xlmusSo0dNNZ1yLUM,901 +torch/include/ATen/ops/rnn_relu_cell_ops.h,sha256=1pR-1h8NaRY99OV9wYFTEGMGkUoydlr-oxt0h03Wykc,1758 +torch/include/ATen/ops/rnn_relu_compositeimplicitautograd_dispatch.h,sha256=TQrk-NR5CG-FU-SNlYZ0r0epL0VC4ZB-X7ZX8MPWiM8,1439 +torch/include/ATen/ops/rnn_relu_native.h,sha256=O6OcVbUzxbAEgY0PcmNcG1F5mRab6C-dM6H45eI5R2c,1151 +torch/include/ATen/ops/rnn_relu_ops.h,sha256=Wj3AbagwQNpv344CwEUp95syFEldV00LaPi7gPemGCI,2973 +torch/include/ATen/ops/rnn_tanh.h,sha256=GQnk-5thc9RdtoST57kLlV3o5HYZVJ_xon0mrNN0Fm0,1861 +torch/include/ATen/ops/rnn_tanh_cell.h,sha256=DoD4LDfI5C95r33lHQ36YSDEbqcOel0mNacaYJtQB28,1188 +torch/include/ATen/ops/rnn_tanh_cell_compositeimplicitautograd_dispatch.h,sha256=Mu9nq6TFukphH6uQMph1-cKgTGpc7qJFDLrKMa5Uzgs,1189 +torch/include/ATen/ops/rnn_tanh_cell_native.h,sha256=mKZ2mwWX8-6DVdR_hnIMjPvhsJXmXiKK0BAF3pAY-go,901 +torch/include/ATen/ops/rnn_tanh_cell_ops.h,sha256=L_jDi_0p8Y2CcYg6eUveLWoHUTiJkMsUMqNR2mSJf9o,1758 +torch/include/ATen/ops/rnn_tanh_compositeimplicitautograd_dispatch.h,sha256=S7pqJVofnSkzdoC-pN5B1zElBUMLSQQdnOWN93ZZvww,1439 +torch/include/ATen/ops/rnn_tanh_native.h,sha256=1uWu_uDUskwUF1W9m7M-kQX5qNmTe9eeV2h6Axw8NI0,1151 +torch/include/ATen/ops/rnn_tanh_ops.h,sha256=6eaas8njrf4ooq9cCUqurt8Fpw26fudKnRrwZZawv4E,2973 +torch/include/ATen/ops/roll.h,sha256=Y5QhgZvOxlvx4u9Hi-KPgLmax2qCKt6mO0KlU-U8Vj8,4205 +torch/include/ATen/ops/roll_compositeexplicitautograd_dispatch.h,sha256=lXipB92Mg4riTG1_vXgMb14_tv_js1a3Antu0Aw5G5E,1482 +torch/include/ATen/ops/roll_cpu_dispatch.h,sha256=YVrguTeonBDLSvVixTaSajS-b9eZbsz15908AWn6os4,1133 +torch/include/ATen/ops/roll_cuda_dispatch.h,sha256=EX1-bNw6GhCaeZqibckT2xpbBgwunfowqzeLr_pGb5k,1135 +torch/include/ATen/ops/roll_native.h,sha256=eks9eTtMlvMlpmE_T1gs6wfWm8PyMTUaMrHPoNmSiO8,1016 +torch/include/ATen/ops/roll_ops.h,sha256=vP_G10mPReE77cpEpUE_y6msmHX-xDj9neHSzyh1nOI,2133 +torch/include/ATen/ops/rot90.h,sha256=m_0rYw6u0QxttASHHds_GEjtcGHq7x8Ho0jRFcSlDX8,1494 +torch/include/ATen/ops/rot90_compositeexplicitautograd_dispatch.h,sha256=pz3FgSORR4LO07R0ELZQ3Cv4XYamZttaFkhXA88dF18,1287 +torch/include/ATen/ops/rot90_native.h,sha256=WufEaaZDE7bgw5qnZismipAghFY-zog_2DzCJ3oxO-4,880 +torch/include/ATen/ops/rot90_ops.h,sha256=4gT7zNK_a5qH3WOGo0h6wwKPYfhzB7Ntf6H8l-zSSz8,2033 +torch/include/ATen/ops/round.h,sha256=ghp7jbFWm-Y7wav-ZBZNOq95EgUAiZMpMrp3Hv1y1BI,2311 +torch/include/ATen/ops/round_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Tu4Zl9DIWzGI_ztyt1j2yM6br_KIqqKWX7GSO4i6UJ4,1232 +torch/include/ATen/ops/round_cpu_dispatch.h,sha256=tMkOcMxju_dDaFdbJW1EWXR11auZHTaeCkvuceCtnfs,1508 +torch/include/ATen/ops/round_cuda_dispatch.h,sha256=0pzUNDYaNiL_w6o3MddOMqmo1onwXwdkD765bFSmANA,1510 +torch/include/ATen/ops/round_meta.h,sha256=T5eY_el-mxFZ8Vn2ZtO7IUiZb_NzjrEM6cOSOSGuh9A,956 +torch/include/ATen/ops/round_meta_dispatch.h,sha256=otEmONNKe41ZrBz-Dz8bwzYtjAbljw0unDWxrYODoIY,1510 +torch/include/ATen/ops/round_native.h,sha256=kjQSMNYB90LPkt8ArmPqpV5Q68Zpy9bM6D96HFQgNTM,1436 +torch/include/ATen/ops/round_ops.h,sha256=b6Izjd81rSRPBzJgJDv9QSS0LXegndLwDe_vDCJ8Ce0,4133 +torch/include/ATen/ops/row_indices.h,sha256=o9nZn0NvcMqpha-mVkSSFQdCjYSYEO1C-I0xwqiz02U,762 +torch/include/ATen/ops/row_indices_compositeexplicitautograd_dispatch.h,sha256=mtV3jVdtuO9axQOfyeLiy3Au9QIe_jl1iimzHp7JaF8,1023 +torch/include/ATen/ops/row_indices_copy.h,sha256=tb2QHVhgwWbze6HsImcA58qUsxFIkCrkq_ln3ucOtZw,1381 +torch/include/ATen/ops/row_indices_copy_compositeexplicitautograd_dispatch.h,sha256=-Ew0ig5VhEkc_yYjQ7s8TgYd-54Uh_iZZHSCAqYskQw,1141 +torch/include/ATen/ops/row_indices_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=veNw2jtcIlGpDwoX29vr_pW107ChnThpQPe0gzDrjTY,1054 +torch/include/ATen/ops/row_indices_copy_native.h,sha256=fEdIiytcms4CWzKthLPmKbUi_etE0CrpyRrOwm5I-gg,828 +torch/include/ATen/ops/row_indices_copy_ops.h,sha256=1xb1uDlmJyZ_CV9eeg_THDuh4IZ_96Roe-wJmjMWIEs,1861 +torch/include/ATen/ops/row_indices_native.h,sha256=R8dRIhV-lr2seMEWjXNZynBxTGkDm-ZakAy4eN8LPM4,813 +torch/include/ATen/ops/row_indices_ops.h,sha256=iQHlckPo28PSy1Ly4nI3MrCAQL4WBXsiJLNYylN0IC0,1232 +torch/include/ATen/ops/row_stack.h,sha256=kahBlM4-q49wxRz99mVKn2LbDm-q-aGrP_q1isDOxSw,1332 +torch/include/ATen/ops/row_stack_compositeimplicitautograd_dispatch.h,sha256=D72AykzujZss5C2Ufhj5pWUzXuPAdYO0BlWGmO8gpS4,1181 +torch/include/ATen/ops/row_stack_native.h,sha256=dSsMLMxRIbmvVeX33oFT7Ibu1OVEXW4fK3-evmrZg1Q,812 +torch/include/ATen/ops/row_stack_ops.h,sha256=1VxWuN0TRse0lG3olG1jxstxOesdKqeb6q6ulEKx9N4,1817 +torch/include/ATen/ops/rrelu.h,sha256=bmqBOt7onCiqT-jJMOlDRaGZSLwmUw5eOjvkGVmS3Q8,1608 +torch/include/ATen/ops/rrelu_compositeimplicitautograd_dispatch.h,sha256=OMGTnlclDSiT25pyd63aS7dCaIqDZ7crdnFEQhkaPBk,1377 +torch/include/ATen/ops/rrelu_native.h,sha256=xDrAzGdJGd2BMx5qgZMaBDNYj-6VF1N9qHV7_wrX-_c,1089 +torch/include/ATen/ops/rrelu_ops.h,sha256=Q7PmJDYM-ZAnNZ61T_Ye5tGbBDovGW7D1MiYLBU611k,2498 +torch/include/ATen/ops/rrelu_with_noise.h,sha256=K3n5q1eXTQniw0MA3h6yIpmZNEkejKDznV6Q-oe2llU,3432 +torch/include/ATen/ops/rrelu_with_noise_backward.h,sha256=aSKgzR4QSAj9arm4aevxRGeUZ9BidID3G5Bqtjg2uS4,2383 +torch/include/ATen/ops/rrelu_with_noise_backward_compositeexplicitautograd_dispatch.h,sha256=wl4evcR0LIk12O4OdsoKJrT6LKg10lBZU6rN09vQmG4,1670 +torch/include/ATen/ops/rrelu_with_noise_backward_native.h,sha256=cwl7MgEcztpDjf3BfD5meAwXSfTkL-KyDTIVrhpEyXY,1138 +torch/include/ATen/ops/rrelu_with_noise_backward_ops.h,sha256=pGlPN34EfFSjtDK5pQQjABz7M2FI0xWUw6bAHSqD7eY,2879 +torch/include/ATen/ops/rrelu_with_noise_compositeexplicitautograd_dispatch.h,sha256=ZAoQgJua52TFwVXkkJ3ftELM30NRSFAGNxi-V_4WTaI,1245 +torch/include/ATen/ops/rrelu_with_noise_cpu_dispatch.h,sha256=GRwXfGnQTHJwQ79aj2bAm-mk58eCMZSFMKwxvVqUfBk,1876 +torch/include/ATen/ops/rrelu_with_noise_cuda_dispatch.h,sha256=ptBOwhoYw24F0GvgPVtLoqeHj80CZG2LUKHAEot40yY,1878 +torch/include/ATen/ops/rrelu_with_noise_meta_dispatch.h,sha256=zc8JPzRWVS1JkKjyFHBoJqwvFGtlzweiH7GmtM7m4mo,1158 +torch/include/ATen/ops/rrelu_with_noise_native.h,sha256=YHn8WQ_ZZysGw9Zq9pyjm_KBN-y4HjDx6roxUpg7UGU,2368 +torch/include/ATen/ops/rrelu_with_noise_ops.h,sha256=2jng3KR15CsuF46_jRONyE5BesNXudh6I23W_kum2Uo,4938 +torch/include/ATen/ops/rshift.h,sha256=qgsM7uK6gUvmCleprWnI_BrGeobjfViMBTqdKDFF7mM,2244 +torch/include/ATen/ops/rshift_compositeexplicitautograd_dispatch.h,sha256=0pTXVKXMTK-sFdHkvh1V7jlM3BKh39AgLwispQMN_ZU,1398 +torch/include/ATen/ops/rshift_cpu_dispatch.h,sha256=KNyNENoUSFPfXprgo2mgwU6RS71LMaTsCOvGk2cLwls,1250 +torch/include/ATen/ops/rshift_cuda_dispatch.h,sha256=zYQm2xOyZ1eE9HwhPbVsJ54Y-3lbFw3SiuuGR7tvzJw,1252 +torch/include/ATen/ops/rshift_meta_dispatch.h,sha256=hq5LEIdT8yPOTEGq7bu5xVZO17GO-PF2JAT2B1zqkIM,1084 +torch/include/ATen/ops/rshift_native.h,sha256=0hBLz_e1qVx8YYuZ3c9tO9Ey3laBDZYIvmbgAaQ1UD8,1236 +torch/include/ATen/ops/rshift_ops.h,sha256=p-dePtjLTXw3-ioSq1NbQp42nT9LL_vZ2e8JSxHtpEk,4599 +torch/include/ATen/ops/rsqrt.h,sha256=OQFow5aN1yF6srkgYkDSWWpGEVcI7-uxi268AFIILRU,1410 +torch/include/ATen/ops/rsqrt_compositeexplicitautogradnonfunctional_dispatch.h,sha256=UiHL4fE5ezjXaTuOAWDxAqw-x4srIQ6ppdr_2X00D-8,1093 +torch/include/ATen/ops/rsqrt_cpu_dispatch.h,sha256=F6Zx-gU1GmJ-2as9JNgN1RUPyIs9BE0Yor_3miY0xjw,1178 +torch/include/ATen/ops/rsqrt_cuda_dispatch.h,sha256=2Na13kIC_KOGHPLtBxKL0cxSBRDgsxmf0i2nNcCEWa0,1180 +torch/include/ATen/ops/rsqrt_meta.h,sha256=msSUjsSMNzMEfZH_GKynmUNPEEHMY0nFBBhQ527sZZ0,820 +torch/include/ATen/ops/rsqrt_meta_dispatch.h,sha256=MiXXXnAS36rqNIoO4Lt51_gpDfawZWGjnSt-my6Qh64,1180 +torch/include/ATen/ops/rsqrt_native.h,sha256=4UOMKgClGpukdqxafE-JeBz3wa03BdgkuDlI01n7_aQ,847 +torch/include/ATen/ops/rsqrt_ops.h,sha256=_rdRzTuj4kE9WygHNeDX7LRr5KJb4_dYnURaGssfxJs,2291 +torch/include/ATen/ops/rsub.h,sha256=IbYZi_ubsf6FH1i804LEOOKmt7yvcZOnKwoJZcBKLY8,2439 +torch/include/ATen/ops/rsub_compositeexplicitautograd_dispatch.h,sha256=kVIxMNqzlUNAkV1X-2n6WW_aInOB7KVgbiOLiPPcIUg,1588 +torch/include/ATen/ops/rsub_cpu_dispatch.h,sha256=WQp_YNNrsLUY_2mNrfy2V8eoFvAV18AQ2nJztOUOiAk,1026 +torch/include/ATen/ops/rsub_cuda_dispatch.h,sha256=ag2judvZL_iuuzMcxenZF8pCg6g8KkuB3Mf50ZcYKso,1028 +torch/include/ATen/ops/rsub_native.h,sha256=vaigEO2IFHNl9du9eE1g7CSgkVcwLz_bT9JT5-ddKW0,1158 +torch/include/ATen/ops/rsub_ops.h,sha256=1hjUvdhgmehU8O8mqYV_vwYJyz8PXqcfDPma4RpLzPw,3648 +torch/include/ATen/ops/scalar_tensor.h,sha256=OG5uP7JLZye0yZIpHiPKqXNQNxwhyrc-njGV_SebmsY,1988 +torch/include/ATen/ops/scalar_tensor_compositeexplicitautograd_dispatch.h,sha256=NEEwV6P3W7QDmCDNEcV3Pu1eEa_0GcQS-oS8GD6MQwA,1420 +torch/include/ATen/ops/scalar_tensor_native.h,sha256=8Vb3HPzGeMNycXG3KovDQg2ZNheVixBR0l5Ivq79kDA,973 +torch/include/ATen/ops/scalar_tensor_ops.h,sha256=6-fhFAPbBk_VMVGcIgSx0aGSfdRbMmVDpRnkVCEhK_s,2321 +torch/include/ATen/ops/scaled_dot_product_attention.h,sha256=waNWxgRDuKZlPXiraeJqlUSVWNR4CE6HPiLy3pWp8fM,1397 +torch/include/ATen/ops/scaled_dot_product_attention_compositeimplicitautograd_dispatch.h,sha256=m1QUiPPEAAuJ8fJa4G74wRM96nRJtHGQXqjElJVLJdM,1254 +torch/include/ATen/ops/scaled_dot_product_attention_native.h,sha256=-L6xIvtJGKSTlfbQ-_NCkxKS75urLu77cXNyqwQLco0,966 +torch/include/ATen/ops/scaled_dot_product_attention_ops.h,sha256=ufGybKU04q7S5f4s0RswWHnt-ii3Hw0iCkgx2iiwYLY,1898 +torch/include/ATen/ops/scatter.h,sha256=WLmE7D8_lWsIjuywZCDGV35o1SJdF6_cDxpLIAX7z9k,4765 +torch/include/ATen/ops/scatter_add.h,sha256=XEGfx0PoYxdK5xH0258M71mlSWPpnThMynYNU_6PEg4,1676 +torch/include/ATen/ops/scatter_add_compositeexplicitautogradnonfunctional_dispatch.h,sha256=5QyA_y1ln2sUIYJSdEbZQdI4tg-E5fFYgBfzr0knB28,1231 +torch/include/ATen/ops/scatter_add_cpu_dispatch.h,sha256=X7irNUJK6RBdC206W5o-pB9E1PsNR36xBmjLdFi0z7E,1454 +torch/include/ATen/ops/scatter_add_cuda_dispatch.h,sha256=aQScy9LFhdAPcrOjjv1FEPhhF1qCdCKxgI4mSyhOFRs,1456 +torch/include/ATen/ops/scatter_add_meta.h,sha256=cr-h3LflBxtjom5ugQ-SrVsgEliCdDGN2CsULqLz_jk,889 +torch/include/ATen/ops/scatter_add_meta_dispatch.h,sha256=KIASOmQRROY77Asek8YviiEP_t7zLQLg5Or9Gu8VS-g,1456 +torch/include/ATen/ops/scatter_add_native.h,sha256=FiqduN-3uQsIxLjJ7pgfUJLVq95N8CT4ij5JDOf5It8,924 +torch/include/ATen/ops/scatter_add_ops.h,sha256=qhR5EtI-d2MJpeLsucLif5C9VruFVXgKa4tyuZJ76hA,2975 +torch/include/ATen/ops/scatter_compositeexplicitautogradnonfunctional_dispatch.h,sha256=guN5dRoEwYDMXLAfNzG3S9PfLjlpcDHEqMaw9qrLyP4,2030 +torch/include/ATen/ops/scatter_cpu_dispatch.h,sha256=Y-XCrhhA6_ylmW20J6kXU8_jWV_fifxLx_XQll68s4Y,3208 +torch/include/ATen/ops/scatter_cuda_dispatch.h,sha256=ptJgXfz2dRr7KHv4CV4un3x2CFNo1S89uJXbSOA5edw,3210 +torch/include/ATen/ops/scatter_meta.h,sha256=7-4b5p9SohXf3RNiPewk1bzcDZgnNY0UvHKOppOC-08,1491 +torch/include/ATen/ops/scatter_meta_dispatch.h,sha256=3gB9rZ8AXoUMcuVj6NXBcdB9b7lodZz9lcxzC1WnLD8,3210 +torch/include/ATen/ops/scatter_native.h,sha256=e-9kbggx2EPWdPzw_eT9JuiPm47QqF5zgagHeI8JNng,1648 +torch/include/ATen/ops/scatter_ops.h,sha256=gJmVr1Yx_0QDrEZb5aky1JXkwd9jd7Puiwn0gLGgwUc,10413 +torch/include/ATen/ops/scatter_reduce.h,sha256=P-qfQKnAe65txT9YYrmLvOgbkCDT7dWOj7OE1g0zg4I,2049 +torch/include/ATen/ops/scatter_reduce_compositeexplicitautogradnonfunctional_dispatch.h,sha256=x01ccrTho4U1MrLcMYKny2QfECBNbVrh7YBVZ-N9vjY,1335 +torch/include/ATen/ops/scatter_reduce_cpu_dispatch.h,sha256=0-cysGg9b3TwwYTCeauwbAXJJWFo9UjUXwKvfE1QnEE,1657 +torch/include/ATen/ops/scatter_reduce_cuda_dispatch.h,sha256=WvvmrBH0tbxbpLvuc1RzhhPH9v-WoQJvuqCDGBHN5wo,1659 +torch/include/ATen/ops/scatter_reduce_meta.h,sha256=LpqD2aXtxtd1J2ixFlFIG-1PKMmBkQNVsJ0Yfb-yBmY,940 +torch/include/ATen/ops/scatter_reduce_meta_dispatch.h,sha256=W5sJQVT7t4x-hAc_iKGwLe7RLW_US5s9JbuBEIEl67E,1659 +torch/include/ATen/ops/scatter_reduce_native.h,sha256=uYOl2oVbcR8-xo84rhrkoENo4xfx9L45iU_zSM0ot3Y,985 +torch/include/ATen/ops/scatter_reduce_ops.h,sha256=1wOgqs-MKtFuuA85TpyGL6_1WVleuqAYk3D3TQS5UAk,3486 +torch/include/ATen/ops/searchsorted.h,sha256=qJGnimAqzADjhFBSgxsRJledjno2u9WN82hbuW-q1BA,3918 +torch/include/ATen/ops/searchsorted_cpu_dispatch.h,sha256=T97oFww58m-OXUlIM7uaI7qv_aoPrR_TYVtUoQoxn-4,2386 +torch/include/ATen/ops/searchsorted_cuda_dispatch.h,sha256=10EBjqxA5a_0kR88yGRiKzIlMrlzu5sMLHB2uAVauD0,2388 +torch/include/ATen/ops/searchsorted_native.h,sha256=6SLQb-IVU4qv0_WLfUZnURCVYjquRgvcaqrq_KsFik8,2592 +torch/include/ATen/ops/searchsorted_ops.h,sha256=3kymaFbHoUBaSBCWySg0X7hv0zfuR6tTSFQ7NTvs968,5055 +torch/include/ATen/ops/segment_reduce.h,sha256=Yfyvw55KNGD1tkizeu4VZfMMfnMenjjcLqWXTZEmetk,2691 +torch/include/ATen/ops/segment_reduce_compositeexplicitautograd_dispatch.h,sha256=3ydRv6-fP1P6jGGFJBwgRedGM5pD0CDqeSMPAmlKt-c,1633 +torch/include/ATen/ops/segment_reduce_cpu_dispatch.h,sha256=13ol0tPxvXoHOpjJGOrv19nWbu8L5iXYWALF1xBx1ZU,1246 +torch/include/ATen/ops/segment_reduce_cuda_dispatch.h,sha256=3DdKpRlDliNNJTSlli0bKf-JXkybxhtQMli4OzMncNU,1248 +torch/include/ATen/ops/segment_reduce_native.h,sha256=yRJSHwAb512BW7hwPCWUuqQTKy6a5q7uEd4bi0JesB8,1327 +torch/include/ATen/ops/segment_reduce_ops.h,sha256=RoJVJZiDCl5woNaVpPzoN96Rc4Hwn30jBDtTSYAu6YU,3404 +torch/include/ATen/ops/select.h,sha256=nHiywkxcW9BPQ36vcGv7PuY4-lAH0Z8Jay-whzJAxo0,1675 +torch/include/ATen/ops/select_backward.h,sha256=cci8wzIzE612qTyx51S-i9iBXmfiIabaGRLzli7-2LQ,5086 +torch/include/ATen/ops/select_backward_compositeexplicitautograd_dispatch.h,sha256=qiRlEyCwlxoiWePtVX8wXWfFofL5xSw9l6R7_XdCNaI,1600 +torch/include/ATen/ops/select_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=bo2r3jXA7T0W8xoPFnoExLzQi0Auf5AJA12avIxiQQg,1259 +torch/include/ATen/ops/select_backward_native.h,sha256=r4PKzswJB3QMYVVjnC_4HqNXTKtnZ6_0NVhob5k20Fw,984 +torch/include/ATen/ops/select_backward_ops.h,sha256=cA9rrppl0G2Zt4jzgm4IzR1MDJa0S8Y3sz2qdsl6ggM,2333 +torch/include/ATen/ops/select_compositeexplicitautograd_dispatch.h,sha256=CAriz-Wukhboa005Sfq88-VvfH0tx0t7BAxScrHEVaw,1139 +torch/include/ATen/ops/select_copy.h,sha256=JyqOVVZm0cavwhKgWZsxh9IO1nNg4VSpJSA115O2IgI,4008 +torch/include/ATen/ops/select_copy_compositeexplicitautograd_dispatch.h,sha256=mWQmENydby4TzvZ1N6Ex5eICLfBd1xlycLDUItAO_94,1432 +torch/include/ATen/ops/select_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=ccRmau6MIaPbC51GEzDV88h0AtX2W9kuXJ2fklK_8Dc,1175 +torch/include/ATen/ops/select_copy_native.h,sha256=mxgkE48Do2VvXPUlbBH2VYd1j5mK5-vSiqKZ5bQGCA8,998 +torch/include/ATen/ops/select_copy_ops.h,sha256=JogO8p6_WduqfmP6xYMNabbVSsd-FXHAqG8uZ5dqIZg,2072 +torch/include/ATen/ops/select_native.h,sha256=wTcDAxdspdTMsOmL2VfWRJluafG_wajuM6gpwrmHHkc,951 +torch/include/ATen/ops/select_ops.h,sha256=EAVKMRYK7PR08ErNZuNGcH8mI1vc75cZNf1aAkFXpA8,1337 +torch/include/ATen/ops/select_scatter.h,sha256=MrfI6oY9dVBUpXXU5QQLCje6C1lIcu_5abqT9CEhD-s,4449 +torch/include/ATen/ops/select_scatter_compositeexplicitautograd_dispatch.h,sha256=iTgT4fnr8dLTPKuSoivNDKOmqyLppKjTtoiznQyUu5w,1540 +torch/include/ATen/ops/select_scatter_compositeexplicitautogradnonfunctional_dispatch.h,sha256=LverrgwrzZMwqGJFH8UbKWauyxMaKVjR8BxPZMHjpFQ,1229 +torch/include/ATen/ops/select_scatter_native.h,sha256=T0FhLnC4OBmDaCUv4yk8xpsSJEfDVxfulmDn7VFlAek,950 +torch/include/ATen/ops/select_scatter_ops.h,sha256=s0gb8NqCH54P0wjpuPtmssRNMmaobAoipSbc_RkOknA,2227 +torch/include/ATen/ops/selu.h,sha256=ITghWDoBQ0vNIfM9nNc9_2TOXm0TPiLVjy4mhPPXX-w,1019 +torch/include/ATen/ops/selu_compositeimplicitautograd_dispatch.h,sha256=6gtCF172XP9dT1GnJ1A2D86Qlenm-TKtYwBSHrWWMmI,1065 +torch/include/ATen/ops/selu_native.h,sha256=fpiZZm6VxLKIQKxIlIXjWOJ7IiH3dLN9U47s4SWLmlM,777 +torch/include/ATen/ops/selu_ops.h,sha256=VNhMqvGJzPtkVtZVHjjXUVK_Nwrb4ssYGr5sgOiC0NE,1698 +torch/include/ATen/ops/set.h,sha256=_qV0ht3c1durpm9fSaDU_3S772ue-Kj5Jljt-Rtp1cU,9464 +torch/include/ATen/ops/set_compositeexplicitautograd_dispatch.h,sha256=9yomqD2b979Bo_uFmFxfv8MbRaYIHd70vhPWDgcU5ZQ,2724 +torch/include/ATen/ops/set_compositeimplicitautograd_dispatch.h,sha256=czaR2sRMEhrINebzvDiK50UDESWdtrRuzeCRwzI6pzU,1279 +torch/include/ATen/ops/set_cpu_dispatch.h,sha256=eAwk6b3skUvO9iJNcbeee6W5GwP93tzWg6Sqx3Q31fo,1412 +torch/include/ATen/ops/set_cuda_dispatch.h,sha256=rIXh27UjeR8VY2qym57p1fkdAUr0WHSLF5JE5Wnp29s,1414 +torch/include/ATen/ops/set_data.h,sha256=Zg11Enb8IekJV53Ci3a4iVLEwOkjT88xeRgLVgBdE3c,759 +torch/include/ATen/ops/set_data_compositeimplicitautograd_dispatch.h,sha256=Bwj-q11Y3fou0GuTETplXF4gC-yhcOJGuU6wanVXK8k,1037 +torch/include/ATen/ops/set_data_native.h,sha256=V85wfKgmMB6O5PXded7OW6hFL2Rycko_O71fDfI_X7c,749 +torch/include/ATen/ops/set_data_ops.h,sha256=dGdEs3cjwKAqdqeAf7M_fXJyEd6y-V9O7qHnHg6NV1M,1276 +torch/include/ATen/ops/set_meta_dispatch.h,sha256=RHyyh5XyHYoSOC7cFhrmeLVoI141jHzTZ_kGiNd1UME,1414 +torch/include/ATen/ops/set_native.h,sha256=JLpKJJpwJ59-A4rUtmEfj-1Xz-aC27DJPTiYv25LnZA,2668 +torch/include/ATen/ops/set_ops.h,sha256=Uk30BQHMCfVq2HmYSIY3YF2YZ9P9eHiHzNhOht55F9I,9938 +torch/include/ATen/ops/sgn.h,sha256=kI6oR1iPTFNCY0ytOgSu4dn06C0ikMp_MVhsWSvRBco,1251 +torch/include/ATen/ops/sgn_compositeexplicitautogradnonfunctional_dispatch.h,sha256=1TObnSBX3qT5dUptHoUXXP3VJszaggpyL7kEF06jZtU,1089 +torch/include/ATen/ops/sgn_cpu_dispatch.h,sha256=7tUfCjhN2aSAyvvuK6fimSVAOpjA0Z4hxZumJsEHbgs,1170 +torch/include/ATen/ops/sgn_cuda_dispatch.h,sha256=ZC17B79tEvNFWdp-1dIcBY620WMcYOxde9HPhDn1K3Q,1172 +torch/include/ATen/ops/sgn_meta.h,sha256=3v8kBuKKtLjcuSFRxBoX1GLjbNcDhD_TTKU-wsL4S4E,818 +torch/include/ATen/ops/sgn_meta_dispatch.h,sha256=3fqrjwCr3QJw8-qgTksL3KUsfG-0R_-yyIflCO1FP5M,1172 +torch/include/ATen/ops/sgn_native.h,sha256=eFs7GLEH00cRgnesHp4alyc2I7_4dYNiMyGSsjZCsmg,1368 +torch/include/ATen/ops/sgn_ops.h,sha256=uJ35vi2kPGZHPr7Zijsl3sNMCJzryCCYpc5H9zPfKvk,2273 +torch/include/ATen/ops/sigmoid.h,sha256=SP35S1-8mE6rellGA63DV4rlaaRjvEWcCZY3ZMRQI5w,1436 +torch/include/ATen/ops/sigmoid_backward.h,sha256=YkZuVSkqxLqmvWEqhJeu6XJmb8EnOtx3QRAoETKYofo,1664 +torch/include/ATen/ops/sigmoid_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=5URGXYFbUjtr7vBzO6FJs_vxzWcHkcmG0KNNNAAfCjA,1088 +torch/include/ATen/ops/sigmoid_backward_cpu_dispatch.h,sha256=vfip83mtbtU6AGKa7dyh63CNYgQHSO37Upvi2d7xIy8,1277 +torch/include/ATen/ops/sigmoid_backward_cuda_dispatch.h,sha256=mV8F5s0GKYeh0Ec6WQIbBJwFae9Rq6fzWrFjU8xSX58,1279 +torch/include/ATen/ops/sigmoid_backward_meta.h,sha256=vamPqk9RH5Oak3b-df8qn9U_K5piC2fGV8W8IvokxRY,865 +torch/include/ATen/ops/sigmoid_backward_meta_dispatch.h,sha256=y2vfQ1HFlEYyF15M-LHxMIGEd1oDFAJMH56jmRFAR6I,1279 +torch/include/ATen/ops/sigmoid_backward_native.h,sha256=7N1vDAB-dTGTDxvi7FpHZn8_OAP4YrdrW80iPhdrhG4,921 +torch/include/ATen/ops/sigmoid_backward_ops.h,sha256=J7EHByjZEKEeIsR9YInQi38LJJ6UG7i6OfHMqnIsZ4Y,2123 +torch/include/ATen/ops/sigmoid_compositeexplicitautogradnonfunctional_dispatch.h,sha256=ircFvP3RbayrEdzzGJdj4isQC23LAH8uwBXNIwg7jSY,1097 +torch/include/ATen/ops/sigmoid_cpu_dispatch.h,sha256=uaMyqYr9JlH_IfkxrspT8jnJ-OVbGBKq_vzLCvZQW9I,1186 +torch/include/ATen/ops/sigmoid_cuda_dispatch.h,sha256=jbvBcLX-LB7czGp-dsc2hWTsGaKnWHGZ_uEy1sHWBno,1188 +torch/include/ATen/ops/sigmoid_meta.h,sha256=8SIac2c0v2xgH4po4wwEHNsgnWqTfSHHNAuYZidRxjk,822 +torch/include/ATen/ops/sigmoid_meta_dispatch.h,sha256=Kr5wm70cOY81sZIkCFmZo_RjaDDqUkvi0sMpLOK4Qv8,1188 +torch/include/ATen/ops/sigmoid_native.h,sha256=EPPFWLxMsbulfwgzI6f-OlnWA8jSy_bPo8gCvS-XFjs,1043 +torch/include/ATen/ops/sigmoid_ops.h,sha256=YMmoS_8uX_2NoYZJ4v2R_5vrZsOzrCTOKE29waccmDM,2309 +torch/include/ATen/ops/sign.h,sha256=zLFbcn3EpuP4EOceElsn7uBz4ywjCz4EJWk-WYbrNic,1261 +torch/include/ATen/ops/sign_compositeexplicitautogradnonfunctional_dispatch.h,sha256=u5_Tb2wgdJ-C-sV5BFAgNQfUczgODEyXahPQhxBLIYw,1091 +torch/include/ATen/ops/sign_cpu_dispatch.h,sha256=iDAbHMqmYggcQ1KZj_DR-4WkgDqOcJk-jyhnjVVrEws,1174 +torch/include/ATen/ops/sign_cuda_dispatch.h,sha256=06dl16Gr9zFlRtGGYGeWShdymHEGHUtamk6cx-cuCjc,1176 +torch/include/ATen/ops/sign_meta.h,sha256=a30zithYb093NjF5Pz0OHllx4usPxeWKrm4IPSgqWt4,819 +torch/include/ATen/ops/sign_meta_dispatch.h,sha256=qSV8Gel4hdVFhVal3JBLuWkGjTA8mjuRbvUf9CXIQ6E,1176 +torch/include/ATen/ops/sign_native.h,sha256=8tE4gCWZM7qoTbZ-c2krE4yL9a0SM89No3vebyi3F2w,1252 +torch/include/ATen/ops/sign_ops.h,sha256=8ZYl8YDO8ez6jpH538cwcTk4CFdsv2fEpBufQJy_C3s,2282 +torch/include/ATen/ops/signbit.h,sha256=8raUbE9A3BSRJ1i91JumIYD8wnNqKsalZvAJISz8Ewc,1291 +torch/include/ATen/ops/signbit_compositeexplicitautogradnonfunctional_dispatch.h,sha256=dKG0zQYQNc-gO1mp9pQSPaE5pB1GSQWxbW2vHAEvLLk,1045 +torch/include/ATen/ops/signbit_cpu_dispatch.h,sha256=ghacY1-BhVYCzdqth8Pd9Rp2h7IbWhaPlXC4EdwdkQg,1134 +torch/include/ATen/ops/signbit_cuda_dispatch.h,sha256=n-hXRnEcBB4D8ZsmkCR2obOslV5X9XpUDObYx0d8yIY,1136 +torch/include/ATen/ops/signbit_meta.h,sha256=z1DB1eigJJgdsalJngbGiWQ1j5GEQR7rkVCw_VcSKRY,822 +torch/include/ATen/ops/signbit_meta_dispatch.h,sha256=XreuC_tXOtOxF35Kj9p1M_ZxSwkciN3VixF8FEzzePk,1136 +torch/include/ATen/ops/signbit_native.h,sha256=lbVBTjMgal7sDsWmxHsfA2cxfwRyTYmJMJAXqkKdH3I,1157 +torch/include/ATen/ops/signbit_ops.h,sha256=o6yV8bSrInlsFurvNs-4i2l4blVYNKN1I7dIEL2jCUM,1807 +torch/include/ATen/ops/silu.h,sha256=1ucL0i4qRjjU0EcV1Jebc10looOuoj0NtGdeqbbi9X8,1397 +torch/include/ATen/ops/silu_backward.h,sha256=5MjcViFALzdxwZ19Tz0etmOC5C63uakz-vTjB3oPtTg,1616 +torch/include/ATen/ops/silu_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=MP0iPaXAmhRYKNEClxJ68u1zihsLs4U3qvfuCMYVTZE,1083 +torch/include/ATen/ops/silu_backward_compositeimplicitautograd_dispatch.h,sha256=uXCIoxGDuqVQRkHtamFdqZ5SASD36cPXTNoR68HwC1c,1057 +torch/include/ATen/ops/silu_backward_cpu_dispatch.h,sha256=hSk2vnrP-7FZnWaN5HwwpVilpHL1GKzAfLVMhP-8Sv8,1262 +torch/include/ATen/ops/silu_backward_cuda_dispatch.h,sha256=WW31UOYV-SvGSDTDRBREnjpSQnuQcR3hN-KE5MOEdqs,1264 +torch/include/ATen/ops/silu_backward_meta.h,sha256=Igtb9j_htA0cAiY78vRKc9504ZWL4rVirWXJkvZ-Lpc,860 +torch/include/ATen/ops/silu_backward_meta_dispatch.h,sha256=yv0qMaKhtyzKfb25pSCwwrCAqQxQzK7GFZ-TrPfxyj8,1264 +torch/include/ATen/ops/silu_backward_native.h,sha256=I2QaNP-pcT7itvu3RHRtmM8vcDbdFfNzsCXKCctyjwM,1108 +torch/include/ATen/ops/silu_backward_ops.h,sha256=pvoDjdylieWb14IdwhPZNFEZBLnkSogPu2IEml82Tns,2093 +torch/include/ATen/ops/silu_compositeexplicitautogradnonfunctional_dispatch.h,sha256=oIErYPa3AcRltGRKOeD957NGfUcPKHUjobCRn83yjYI,1091 +torch/include/ATen/ops/silu_cpu_dispatch.h,sha256=CR0lHgiTUIoIaKbFcBbIZjid8MPVghctLameXKtnNRg,1174 +torch/include/ATen/ops/silu_cuda_dispatch.h,sha256=oDfWNaebBAHaZLZr0trZb1fkKUXo2nSLpGw-_mDzrC0,1176 +torch/include/ATen/ops/silu_meta.h,sha256=MLkU3umju5GEIjiRvxfWyNjdiumdDka8aQq_2dCvDzs,819 +torch/include/ATen/ops/silu_meta_dispatch.h,sha256=53NEmZGzUUAcLKWJU_EYs2LW9xb0y1ua3ZeO2-xZSww,1176 +torch/include/ATen/ops/silu_native.h,sha256=qsvgPSg_Bo0jiIKvkZkMVtkkRfiilz54fscc8Ra6W5Y,971 +torch/include/ATen/ops/silu_ops.h,sha256=Hu17I0HyVv8hwpYXH5goasMa_swSnHwsZBv1OVhu_JU,2282 +torch/include/ATen/ops/sin.h,sha256=VYOnRrwlpzHP6xcD7uUFyMSbZp59nyEZ-1ffZJ96nqc,1384 +torch/include/ATen/ops/sin_compositeexplicitautogradnonfunctional_dispatch.h,sha256=my9QX9Z0GJfSw6Xw7SWHcUTYnrGcMvBE3-rKDnBNYno,1089 +torch/include/ATen/ops/sin_cpu_dispatch.h,sha256=CqBqUhuEbzir-8zZn2ittMKzg_C5ZdYdH3pDVDYsrj8,1170 +torch/include/ATen/ops/sin_cuda_dispatch.h,sha256=QdcgB7HLsRXnhfvj9bldaChoJQGMtV5YV5nkRrdqE0Q,1172 +torch/include/ATen/ops/sin_meta.h,sha256=h2k4PBLyLEaFfNnu4pFC4KvdKjq-b7fRHPnEYjSCaRM,818 +torch/include/ATen/ops/sin_meta_dispatch.h,sha256=bt00eNUqL72JRlh1GjxhnaA84NV7qDqX3NCM6m8nUuk,1172 +torch/include/ATen/ops/sin_native.h,sha256=QDG03Vdp1XpJf6nXO8COvnEm-OJWlMGlwk5ETRzYfjs,1307 +torch/include/ATen/ops/sin_ops.h,sha256=YbcZLqGv3LB_ha9iWdbT1vKvnZQTt3xk4FvvtjPjqDw,2273 +torch/include/ATen/ops/sinc.h,sha256=gH9yZTjoDcWJVNiig2cu2b1Oa601fsFb4LB7SiZXcMs,1397 +torch/include/ATen/ops/sinc_compositeexplicitautogradnonfunctional_dispatch.h,sha256=a0V7eutuY0WYLPqvm3SZumQzzJMG5mq991RYJoi5fnI,1091 +torch/include/ATen/ops/sinc_cpu_dispatch.h,sha256=FqWcZU8S_9w4P_aD4wWNZnvIn-r5TNVfJRg9_uAXyRE,1174 +torch/include/ATen/ops/sinc_cuda_dispatch.h,sha256=Q2G6re58qKB5Jjab2aOlxm-HHqRfpBkWqmgjH9ZnbGg,1176 +torch/include/ATen/ops/sinc_meta.h,sha256=j9PY7loM_Nq7YCm8cBROx73OKduh5rkX4r6jrrdfutY,819 +torch/include/ATen/ops/sinc_meta_dispatch.h,sha256=XcvMLSoKHE_bF6K_6QeIMoI84mNHs8-MGPKw-p413Ag,1176 +torch/include/ATen/ops/sinc_native.h,sha256=O6CyE7AEOqrP5qPLy0zHtvIwxoxMwLtMKDJE0_epAmQ,844 +torch/include/ATen/ops/sinc_ops.h,sha256=cREVeGspVDvP2pEingUp_uKwnAtCJVCn1_2spDvEYz4,2282 +torch/include/ATen/ops/sinh.h,sha256=JaBiBLWfTNW9ymS_YhLn2otw8DZziUkmqFnRrD37we8,1397 +torch/include/ATen/ops/sinh_compositeexplicitautogradnonfunctional_dispatch.h,sha256=F2lmt1N9UdgHiJ9g3CCQL1rvCV7w2hawN3ZijklOaIA,1091 +torch/include/ATen/ops/sinh_cpu_dispatch.h,sha256=Vc8OM0gMxhCOnPLJ_BiScfIoR6bZgWWOddo9DkIbTo0,1174 +torch/include/ATen/ops/sinh_cuda_dispatch.h,sha256=gnXdbzuNB30NiU22rTVMjRcJeY4c68RG63NGtAn0KN0,1176 +torch/include/ATen/ops/sinh_meta.h,sha256=EdjpUvQdtsjsPQb-efPAC14oL8BiOGdw8YcQXhkd0hw,819 +torch/include/ATen/ops/sinh_meta_dispatch.h,sha256=V4YQ_gr9S2v-SuwDe6nuvSP92YVhLz6VztHoV9sanqo,1176 +torch/include/ATen/ops/sinh_native.h,sha256=GQnPzrnjsWmHDq7hh89T3jRaHzawpeDWqcCawXUddA0,1252 +torch/include/ATen/ops/sinh_ops.h,sha256=WlRPU9UJXG4pjuxCY9Ja4Dl5Cu9qC3GOWyryIlhp8KE,2282 +torch/include/ATen/ops/size.h,sha256=Tl-8h_8E6EtjY5bqsPe_KKiGN4_EDEuXV14TZvHTLtE,923 +torch/include/ATen/ops/size_compositeimplicitautograd_dispatch.h,sha256=xYLlYVupd-k1eHrQyf9vd7MFAmRWiIT3i3i9Ertghg4,1026 +torch/include/ATen/ops/size_native.h,sha256=8EPGQoRpXuFkwPSwhxsdTvezDfzg6nhdzx73ioWWX5E,738 +torch/include/ATen/ops/size_ops.h,sha256=BCSg1SeEaUh-UHLqjfvI4r5l8j37gK5iMRPlivlFlug,1248 +torch/include/ATen/ops/slice.h,sha256=X3WJmttO7XXf7ua4AaCgRSE8FIl_GMA5ptFR8RLvvPk,2492 +torch/include/ATen/ops/slice_backward.h,sha256=GpdqDAgKSp54FTTBi8HRiuFvGGwSVdv2CnqV7JEoTgE,5709 +torch/include/ATen/ops/slice_backward_compositeexplicitautograd_dispatch.h,sha256=RpGYSUzCKh07LstQtjoGxfxNLyv3C0NkWdGK0sgMScg,2049 +torch/include/ATen/ops/slice_backward_native.h,sha256=KY3r9Z7wjQxxIus--_TT479reZ-aaZS38G1WWZb7dC8,1029 +torch/include/ATen/ops/slice_backward_ops.h,sha256=QbhELvlTKKXG3df5jTKW3XZSezthuX-elMDq4inpOc4,2569 +torch/include/ATen/ops/slice_compositeexplicitautograd_dispatch.h,sha256=8jjPzsvgjt_oHadl1LbNE6vI478sy7PjMCBbK-E8FLg,1335 +torch/include/ATen/ops/slice_copy.h,sha256=nxFp0KSYh9Ka8uzX0UaLnHo1hENaou-4CzJJ1lCDeRc,6325 +torch/include/ATen/ops/slice_copy_compositeexplicitautograd_dispatch.h,sha256=0gYggcdX4SCLlWeTx-GaHWvnz-HaqsnTQVmig8Ix2zg,1756 +torch/include/ATen/ops/slice_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=94wkloCmIt-De3qh4ldU2YG8BhblhwTfM1Xz3aF0wkI,1371 +torch/include/ATen/ops/slice_copy_native.h,sha256=tgvL13FGp9soWzh-Kw9ovvaeb00rjXal309VeJs7tnU,1080 +torch/include/ATen/ops/slice_copy_ops.h,sha256=jXcClfPIo6i1EumEyqFpeD1_CvBE1nbL78bHJ4gZR9c,2562 +torch/include/ATen/ops/slice_inverse.h,sha256=gN3zDtQEohd7f_qVDiS_Q0imhOJYOYmFFRTNKZFuIPE,2678 +torch/include/ATen/ops/slice_inverse_compositeexplicitautograd_dispatch.h,sha256=1psWKg-U8ecGPszm2urUWasfj88GHc5jpwtYjjdQggs,1399 +torch/include/ATen/ops/slice_inverse_native.h,sha256=EpyMQfrnx3hPvj7qnVLdhKOjK5aimsIHZLrAbuBrqGE,903 +torch/include/ATen/ops/slice_inverse_ops.h,sha256=DHAPiBUvL8T5jB16VSVXe8U86CSXqVptykL3X9SjxZ8,1666 +torch/include/ATen/ops/slice_native.h,sha256=qnDEVIbZH9TXgYUH9lnqJwgdnr0F6vgvFQlyTQfBEgY,852 +torch/include/ATen/ops/slice_ops.h,sha256=RAN3IqSjVMNBRRCEqNGfBccOp6CN0bLJXQH24k8UQCI,1582 +torch/include/ATen/ops/slice_scatter.h,sha256=SlpeXRVfbj2xgUVW_9YwvvyTkD-UIBOckl9C5rg0c8o,6712 +torch/include/ATen/ops/slice_scatter_compositeexplicitautograd_dispatch.h,sha256=OvWSqk5oo8H-rj4RgTKLXsN-kflm4FmUOp2c-XKjv74,1864 +torch/include/ATen/ops/slice_scatter_compositeexplicitautogradnonfunctional_dispatch.h,sha256=aUOOtrX4K7KQa4C4b01CEPu_-CIusJMSqO2wHCapDoU,1425 +torch/include/ATen/ops/slice_scatter_native.h,sha256=JSEqPhVSsF1NPe-53VOzh7yXYaXZtitplPd5TZUN42U,1101 +torch/include/ATen/ops/slice_scatter_ops.h,sha256=zW4jt_cZAGF2CQBZvBXnBoPOq-AK9P6kJxxG-yv3S7Q,2699 +torch/include/ATen/ops/slogdet.h,sha256=u9oduL3X6cpCcMxZalrbv2_S0_58oasXE8uxJaCxG0w,1573 +torch/include/ATen/ops/slogdet_compositeimplicitautograd_dispatch.h,sha256=Kb4VUK4gDwVMEoix36rvOEYSyt6dXkuoZ6IfcAYB_Ws,1307 +torch/include/ATen/ops/slogdet_native.h,sha256=7Y9Izwd6biFtIvvxDcXNr2TrkaFRM4fjqtnHxKBgxCU,887 +torch/include/ATen/ops/slogdet_ops.h,sha256=pKpMExaaBcY03iw0BQtx3DOWh8UgQp0HoAFKvJf1an0,2104 +torch/include/ATen/ops/slow_conv3d.h,sha256=OZoNbrkN_gL182n9MyhFFMuv3t9GXx2ZNju9UsdcDG4,6874 +torch/include/ATen/ops/slow_conv3d_compositeimplicitautograd_dispatch.h,sha256=H0Z08mDe2Jkgwn4PnaQ1ie-Z2wciDc6ECK0BvGPfQ40,2435 +torch/include/ATen/ops/slow_conv3d_forward.h,sha256=VrQQ6n4Hq3aCh4ZpgLuQZZNl5MfswzX_tNOFJbTyhxk,7004 +torch/include/ATen/ops/slow_conv3d_forward_cpu_dispatch.h,sha256=gZqnu5dFJXoy4EUBipdZMjMpDGUoVrXTh-8mz5JJ_Lk,2371 +torch/include/ATen/ops/slow_conv3d_forward_native.h,sha256=FNTkZWQwM16huCCTrtDaKmQIn93nEUGG1GKyFMti5rw,1139 +torch/include/ATen/ops/slow_conv3d_forward_ops.h,sha256=U928nbkJMrwniysQqsBIM2gjKbPHv0ipWsk0QJHAr3g,2951 +torch/include/ATen/ops/slow_conv3d_native.h,sha256=fSxIZv3A-zCossM_6m0It9k37avz6ND-1wzLuE2VzcM,1119 +torch/include/ATen/ops/slow_conv3d_ops.h,sha256=Tc10lplvojHfysDv67205tskm9LJVDGiODuEZ0f_ZGs,2903 +torch/include/ATen/ops/slow_conv_dilated2d.h,sha256=2xGzI6_LY_sG5g61-zG03h2dijWv_BmihzFVegVyzos,7934 +torch/include/ATen/ops/slow_conv_dilated2d_compositeexplicitautograd_dispatch.h,sha256=eW0V1iuUNwGhDlO3CJ-vEP81hkWZlWLaGHBDGtVdd8M,2125 +torch/include/ATen/ops/slow_conv_dilated2d_cpu_dispatch.h,sha256=bcu8OP8ZxzG99WtcymLHOMz-BLmG3t3SEZCT85hqJq0,1480 +torch/include/ATen/ops/slow_conv_dilated2d_cuda_dispatch.h,sha256=-fU1Pd3GUbBQTi4Ol1yn5is461DcbYj4ugrSpche0AA,1482 +torch/include/ATen/ops/slow_conv_dilated2d_native.h,sha256=vhFalh5Lb62KV2v5xPOkttPkp9h-MqqOMeTyxL1NdFM,1470 +torch/include/ATen/ops/slow_conv_dilated2d_ops.h,sha256=folH8I1PfOrJbYO_R0tz_q6IsQAWUYOwKcOrA6EyQJo,3157 +torch/include/ATen/ops/slow_conv_dilated3d.h,sha256=vEsBA0Fg_xnOK-illpUiGIZwb2cNUh4fYVhpPEaMvt8,7934 +torch/include/ATen/ops/slow_conv_dilated3d_compositeexplicitautograd_dispatch.h,sha256=kwYOH6GDrl-sc_vqKmdqhTxN5qV7qygO_JvDZCUt2K4,2125 +torch/include/ATen/ops/slow_conv_dilated3d_cpu_dispatch.h,sha256=1bp9ypNUL-Lz0SvZOW6TEaWN7__iEoRVXyu4sK3srZg,1480 +torch/include/ATen/ops/slow_conv_dilated3d_cuda_dispatch.h,sha256=uyv01ofzOANsiQiaQ1rc6vmO56KET_jQ-sLtOlXAMCU,1482 +torch/include/ATen/ops/slow_conv_dilated3d_native.h,sha256=NrkBD1o6Ga4YaYVxz8nOuTN8lbj7ovR3YCfD-cO8S64,1470 +torch/include/ATen/ops/slow_conv_dilated3d_ops.h,sha256=jd4tLqH0kfHRC_6lNtyp2P8dQ_clYhSAD1OjCnwlqPQ,3157 +torch/include/ATen/ops/slow_conv_transpose2d.h,sha256=SVs973WWW6Q-h2bZNlkdUOmEgSn-Fsv8-gHN_fWLaxI,8988 +torch/include/ATen/ops/slow_conv_transpose2d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=J1hOvGYXsLzKzDdnzdoP8YKMeKcn-N6XPDTGVCAsYDw,1639 +torch/include/ATen/ops/slow_conv_transpose2d_cpu_dispatch.h,sha256=K9yn_pb8AyIiSMAsc8BL1HaH9-ykjApc-tYndujko9M,2891 +torch/include/ATen/ops/slow_conv_transpose2d_cuda_dispatch.h,sha256=eVWBLJgSkrSMgEhXPhPxV8pfQO3buuS9gbun4_bt4RY,2893 +torch/include/ATen/ops/slow_conv_transpose2d_meta.h,sha256=iX0YK83sD5p9ellF_a3jB8cJUGmGNsIlmh9puoHznhw,1057 +torch/include/ATen/ops/slow_conv_transpose2d_meta_dispatch.h,sha256=TRonKVL6lXb8gM9sGg4hgkkqJC9lPlhL6MdMq6EMmIw,2893 +torch/include/ATen/ops/slow_conv_transpose2d_native.h,sha256=7rBuN9bebLF8-WCXYJYzx5ftVENwpgA05BrBxCNtlBc,1531 +torch/include/ATen/ops/slow_conv_transpose2d_ops.h,sha256=VIFrXgHwfughWbtaRcsYsLTU2F5j0nOU5CYYjVN1zTs,3411 +torch/include/ATen/ops/slow_conv_transpose3d.h,sha256=RXYwCSccUHOx7McihEqSi2p8uaJbuLWf0LRqpPGhIDI,8988 +torch/include/ATen/ops/slow_conv_transpose3d_cpu_dispatch.h,sha256=Px24CcNxo_HBbsmLK7GQsgfRPmchN2F8oGKjq7-gzhU,2891 +torch/include/ATen/ops/slow_conv_transpose3d_cuda_dispatch.h,sha256=5ynb_SdN9KQjAekTz_nkNiCUuIO0A8W4b_xkw7yXti8,2893 +torch/include/ATen/ops/slow_conv_transpose3d_native.h,sha256=z-T_X56A0kJb-uXuIhqLQcjCzCO0ppUz2Devwgty960,1860 +torch/include/ATen/ops/slow_conv_transpose3d_ops.h,sha256=sZK3QG9km8Cst30-IhMH_yqG4X8M5z02zNlRkQZVD04,3411 +torch/include/ATen/ops/smm.h,sha256=Dui1ezudAT1W44Zs94M6FR8WQSsUywfTHoB-SM12Ngs,923 +torch/include/ATen/ops/smm_compositeimplicitautograd_dispatch.h,sha256=XlRdtT8yCOJSm4CyMIop1P7VgaaO9r1CDwgJRQklqx0,1040 +torch/include/ATen/ops/smm_native.h,sha256=tDrFVit4KTnZYr635CttAd2qWgDT7xmNKTgcJCJRcHU,752 +torch/include/ATen/ops/smm_ops.h,sha256=14swLIWERBM6NAMQwdFomyahG24FM-9Gq8cILWRn6e4,1285 +torch/include/ATen/ops/smooth_l1_loss.h,sha256=JOGdfN3B-1z2e_8zEfZZeKjcUiiPr1b2ZNgSAqpWq-w,1814 +torch/include/ATen/ops/smooth_l1_loss_backward.h,sha256=eufX-PHT1sCRCKTunVX1ue7GPdtg5yx2DLsTulUwQNQ,2094 +torch/include/ATen/ops/smooth_l1_loss_backward_compositeexplicitautograd_dispatch.h,sha256=y9A5ksE8lf08yZymzdncwLCvf7vFh8fyIXH2FRKt2kw,1126 +torch/include/ATen/ops/smooth_l1_loss_backward_cpu_dispatch.h,sha256=a0e_9YvepTOINLcAtsok59lpIBJS-c0Z_XWwbKIPNpc,1307 +torch/include/ATen/ops/smooth_l1_loss_backward_cuda_dispatch.h,sha256=JSOTJUpMwZra6xCRFUJjTONZ4hwXcvTr5HNPliNh2yQ,1309 +torch/include/ATen/ops/smooth_l1_loss_backward_native.h,sha256=r3GY4U4CwQSermAUBn6RaYMmpaGvjpUfwy_31syy_9Y,1031 +torch/include/ATen/ops/smooth_l1_loss_backward_ops.h,sha256=eoLzKkTLqzw9IZdH0xcx5lVzFOPSzF-Dy1JRzl35mnY,2547 +torch/include/ATen/ops/smooth_l1_loss_compositeexplicitautogradnonfunctional_dispatch.h,sha256=-L04JUEMe6wsMHRv241ZJhaXwtaqBIr0Co-r5y8QsnY,1135 +torch/include/ATen/ops/smooth_l1_loss_cpu_dispatch.h,sha256=3c3QzHrOx9JvJJLsYRfqDIHG8i44gob57PvwepgKd1Y,1380 +torch/include/ATen/ops/smooth_l1_loss_cuda_dispatch.h,sha256=yI-Nd_JKwbQlyDZ51YOwKks64pnWxpakipmbuikXr68,1382 +torch/include/ATen/ops/smooth_l1_loss_meta.h,sha256=C6n1qKgEkn6cgUDfPk-_Erz0X3SQ9PcPtCksogfkPnA,888 +torch/include/ATen/ops/smooth_l1_loss_meta_dispatch.h,sha256=K8Q-lz04zW-1-eaKDvPq09NEZ4vnf4rowvJUZRvQWD4,1382 +torch/include/ATen/ops/smooth_l1_loss_native.h,sha256=adYdv1CprSjGEQ1fx48TPw7lqeMefBapxcWkG5rJOqc,933 +torch/include/ATen/ops/smooth_l1_loss_ops.h,sha256=qhrgdXZ9O0BicOx_VB_s3Q7thBMU_6s-0e40tKz5rXk,2261 +torch/include/ATen/ops/soft_margin_loss.h,sha256=CZAe8fC7c_mJnnGzXWvwqbbOmOWpz0p01-t4UUJQ1Kk,1721 +torch/include/ATen/ops/soft_margin_loss_backward.h,sha256=eeA8hZ0h3t54Gxp_VmLAkDDflVSJwl47vYApIF-idEc,2021 +torch/include/ATen/ops/soft_margin_loss_backward_compositeexplicitautograd_dispatch.h,sha256=3OaYNQflmlW96u_ZciQxXY8BXkYwXI3e--1eog6m1bo,1480 +torch/include/ATen/ops/soft_margin_loss_backward_native.h,sha256=SxPOek224M2BJLXoHNSxuPett-ASRlUIXKQ2taczb0k,1009 +torch/include/ATen/ops/soft_margin_loss_backward_ops.h,sha256=hyUZAyh77FP-AFp_8-I0id_zBWcZgZ4YrkvdPUCGhW8,2467 +torch/include/ATen/ops/soft_margin_loss_compositeexplicitautograd_dispatch.h,sha256=Js7yrTmAHxFSFCZxPyuoneQl9P3WJ8fomyCd_vJT86c,1383 +torch/include/ATen/ops/soft_margin_loss_native.h,sha256=iCUdsYRPTNMxsHC75KKEEMqTPIuwssgtzBTVlsWdQo0,940 +torch/include/ATen/ops/soft_margin_loss_ops.h,sha256=mDRg8Vc3Ic01gguVIEqVOX56VjCvY6DxMEz3t87i3-M,2173 +torch/include/ATen/ops/softmax.h,sha256=ZmIGdMurQY92WELAJMw7UfVtTl8kjWmbDBarD8yP2d4,1636 +torch/include/ATen/ops/softmax_compositeexplicitautograd_dispatch.h,sha256=46O1w5mWQI4WfjyXW_LaSSslPtX5rSHGqLpCKv-GaiU,1242 +torch/include/ATen/ops/softmax_compositeimplicitautograd_dispatch.h,sha256=Gev69-1dn4L5sezCGGaDLUTN8abdmSNHobaWODFtKak,1086 +torch/include/ATen/ops/softmax_native.h,sha256=wyg-yjnD43iflVbuKbIiOJDbLqlThIPnQDjYu2B2hbc,929 +torch/include/ATen/ops/softmax_ops.h,sha256=qaFij5rlgNvB1k073-URAMBlgej0IhuSiSxBsC6yeYs,2188 +torch/include/ATen/ops/softplus.h,sha256=WQIQXvBbDhRlo4u65s-jYwyECshKvU81Fml1iQiaJEY,1635 +torch/include/ATen/ops/softplus_backward.h,sha256=9As8u9ZqK__KD8_pIVdcex9fQBS1Zi7JqEoVOex6W7k,1965 +torch/include/ATen/ops/softplus_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=LQ8WcPOKD4cD44gqWEFcje3oXCIECs4KFxcBTiShShE,1142 +torch/include/ATen/ops/softplus_backward_cpu_dispatch.h,sha256=Zt4pnDVgwBxakHTojjHGKjL4grPdqwffo6IqcklUfhU,1439 +torch/include/ATen/ops/softplus_backward_cuda_dispatch.h,sha256=U9oL4QJOGoGgLIOdyTtHfhsufaYSwZiYuoyVYZa5548,1441 +torch/include/ATen/ops/softplus_backward_meta.h,sha256=6PbJJT2bgTZiBQto4lXwCs_MUwGsJGRqLgH7Z5e-Ef4,919 +torch/include/ATen/ops/softplus_backward_meta_dispatch.h,sha256=ux1k-QqXJKovpHEt6a-BPrwubeHmgw9ed5GBNh1cIbU,1441 +torch/include/ATen/ops/softplus_backward_native.h,sha256=k_o_c8uao-4x1zfiQfuryDAhD905XQa9hpiN7YkpRE4,977 +torch/include/ATen/ops/softplus_backward_ops.h,sha256=Zl7idp0GUkxgm3WMX_xiWX1YTgoO7FFn9xjb_SXbgPI,2479 +torch/include/ATen/ops/softplus_compositeexplicitautogradnonfunctional_dispatch.h,sha256=9mDOyaBcDTyZfiemmw16ypp4H00RgZGGJv1juV98F3k,1106 +torch/include/ATen/ops/softplus_cpu_dispatch.h,sha256=FwPzQNvjcJx-PETQgnAW8Zml0UBv0bh46oyRgD2q6w4,1312 +torch/include/ATen/ops/softplus_cuda_dispatch.h,sha256=Q7fMWJhIUxPDapjCZ3CuNh2nnwkYChGboYY-Xcz4p_4,1314 +torch/include/ATen/ops/softplus_meta.h,sha256=jbv4pH2VEBB6pAPungWbj6b55x-_XMIu2caz8fR1jGE,878 +torch/include/ATen/ops/softplus_meta_dispatch.h,sha256=yivAyKcxg0IEvF9y6JhdhvN17dzUEdVacrzLhThaexs,1314 +torch/include/ATen/ops/softplus_native.h,sha256=xfZVTk3RXxANJJhqrrApwtt9rd1OKkVQIvI6kS786ms,911 +torch/include/ATen/ops/softplus_ops.h,sha256=qMnql2vSo5vo9PFFEokiHdk1ldro-eWTeFMZ3119bIQ,2185 +torch/include/ATen/ops/softshrink.h,sha256=C9bDTHTegZaDVevI-vAfwJ_TLYGBHvIt7i_kRymLeXA,1482 +torch/include/ATen/ops/softshrink_backward.h,sha256=5GRklJt08Migh6qcpLSbNUqoO54fvnkK3remBjvZtUY,1817 +torch/include/ATen/ops/softshrink_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=bqsdxPOTcEVD4175ZG5qW9VCt6JC15X-dDcH-Ca8Oog,1115 +torch/include/ATen/ops/softshrink_backward_cpu_dispatch.h,sha256=gi9MA86VSsCuFJFMYi4eiwnAOT_n4xoXKx7Mw8y9Upw,1358 +torch/include/ATen/ops/softshrink_backward_cuda_dispatch.h,sha256=nFUNjr5hu2C5ShxXYseOJrLMCICzVr1SCaoRhUguPLE,1360 +torch/include/ATen/ops/softshrink_backward_meta.h,sha256=8EgIn4GdwK7CVVhBiqDm6NAp8qIfljHPiW-TIdk2MuU,892 +torch/include/ATen/ops/softshrink_backward_meta_dispatch.h,sha256=JrsiIYyR5mHtn8OvF5-qXRMocv6OCrDNi99yj_Jo1GE,1360 +torch/include/ATen/ops/softshrink_backward_native.h,sha256=E4MDvgfsjcwcMibfyxvQNiAvXuvp0FYl31KszEae6v4,954 +torch/include/ATen/ops/softshrink_backward_ops.h,sha256=SFQ7HDNOLe60i3gZneAF6nh74tfqwFPr4jDqOYuNINQ,2301 +torch/include/ATen/ops/softshrink_compositeexplicitautogradnonfunctional_dispatch.h,sha256=iBM_HHMHQiPW4p3oEtXXaPpceftMHk7vjBrkfD46DM0,1078 +torch/include/ATen/ops/softshrink_cpu_dispatch.h,sha256=DoVo-tzk7JlQsifxjhiOkF901xBtikSoibEgoz2KA7w,1229 +torch/include/ATen/ops/softshrink_cuda_dispatch.h,sha256=P9IX9CrgoMv1m0nSYl8ACTyjF8OoRbtE2qYxLBa2k68,1231 +torch/include/ATen/ops/softshrink_meta.h,sha256=AEGQC0SvrnRCD5E_TFvQsWbU3t0tVBDZzkprl-tjReQ,851 +torch/include/ATen/ops/softshrink_meta_dispatch.h,sha256=tnlenm1In7uWQtjMZvbBOd77ur7Xrf10-FR7163Z7VE,1231 +torch/include/ATen/ops/softshrink_native.h,sha256=2pANYqaGxU4zr6TKP6YcbQrcnr7BtC6qUey3_wFiAck,888 +torch/include/ATen/ops/softshrink_ops.h,sha256=91weszDfgIxUG3wn70b48P4FKnVtx54vD8QsCbKPN4U,2005 +torch/include/ATen/ops/sort.h,sha256=fWzfeRA3jGq6H_XQaMhBv3sc3-wZacraSDHdK8Qq6P8,3085 +torch/include/ATen/ops/sort_compositeexplicitautograd_dispatch.h,sha256=8Xx7fUNc--WuE4piimGTB331SOZTOR7vGiAvlkajakA,1406 +torch/include/ATen/ops/sort_compositeexplicitautogradnonfunctional_dispatch.h,sha256=ivpaf11vy5Bf1NoFrBeci8DW0H3lsvF6UFzuiIV3Nn4,1136 +torch/include/ATen/ops/sort_cpu_dispatch.h,sha256=rF9nyrcKpw0PPWumEMFTqc35NwaWJghNK4-9b4uKXDI,1452 +torch/include/ATen/ops/sort_cuda_dispatch.h,sha256=u9l87r60ejdIphyGWwXgVvoNZyRAEnAfthBq475wOlE,1454 +torch/include/ATen/ops/sort_meta.h,sha256=2Il2d2Mj1wVlJaQzGfcvjzYRO6pI5IvLkMeE8noY6KU,886 +torch/include/ATen/ops/sort_meta_dispatch.h,sha256=d6jio7spm_vOSB4nIvBjN71NXoN1moaLEiLU4vRmAjc,1454 +torch/include/ATen/ops/sort_native.h,sha256=n9t6sA-gjy1dm6mVCmN88p5FlNuI53iH2hsHNBKrkh0,1390 +torch/include/ATen/ops/sort_ops.h,sha256=GCXmCz0JgjCjsnkO-DwomnH61EQDaScyoPIUcBM_Ins,4157 +torch/include/ATen/ops/sparse_bsc_tensor.h,sha256=Fq0Q5dPjRDVWVUvh2JjgvfUOzS9r6NUiUBD4Pq6V40A,3247 +torch/include/ATen/ops/sparse_bsc_tensor_compositeimplicitautograd_dispatch.h,sha256=e8f6GdRY7Oh4PQ-v2Fe7rJuGxmMZz8zZTrRQBv0WnTw,1880 +torch/include/ATen/ops/sparse_bsc_tensor_native.h,sha256=IsYVUPPf-2MDqOP7jrFI7Tmtawr0XV1GykGWtXZChcU,1276 +torch/include/ATen/ops/sparse_bsc_tensor_ops.h,sha256=VfWF4b2sIJRnw_UPjGs0d5QGCA_aNu3RGneTgjOG1mg,3381 +torch/include/ATen/ops/sparse_bsr_tensor.h,sha256=1vPZQdI5qudigZklILkvKGty_PgtvuxMQmpv56cxAhk,3247 +torch/include/ATen/ops/sparse_bsr_tensor_compositeimplicitautograd_dispatch.h,sha256=5fTZhnMAAz60Ih0Lna0iVcZ4QzjB6Gb81YQ-ALy_QTc,1880 +torch/include/ATen/ops/sparse_bsr_tensor_native.h,sha256=EhqWdef8wDUPF-XP9C-Q2Cuybyh89tSTJiGUeUezZmc,1276 +torch/include/ATen/ops/sparse_bsr_tensor_ops.h,sha256=hoM9Bic1cevjUsERjCabCvAAxTHf2JZwU5qnSL_rxQg,3381 +torch/include/ATen/ops/sparse_compressed_tensor.h,sha256=5QTL5V4WctniLTXYBiw-gtQJV8qRgLCYPfF2eez7Z0A,7224 +torch/include/ATen/ops/sparse_compressed_tensor_compositeexplicitautograd_dispatch.h,sha256=48KUixU8BXcDw2mAYtabEbDusE63-09-OBf2SnmEOtw,2472 +torch/include/ATen/ops/sparse_compressed_tensor_native.h,sha256=TEtoaO_V6UoMuNuKW3Qb-bdKdI_4EpEGaauFF8sWGu4,1306 +torch/include/ATen/ops/sparse_compressed_tensor_ops.h,sha256=6vpQ90aBC29ZtTdpBVAzE1mMQmqYyy19tPKGtYZRQWU,3498 +torch/include/ATen/ops/sparse_coo_tensor.h,sha256=cjDkL0aEKrNzzBd_KzXMVlBH3XS2GryDR85LLUNdxrQ,4535 +torch/include/ATen/ops/sparse_coo_tensor_compositeexplicitautograd_dispatch.h,sha256=FlSOVJCBBrWtjtlxhjwWQYbTN5VkmYKjoqYzaChmbHs,1433 +torch/include/ATen/ops/sparse_coo_tensor_compositeimplicitautograd_dispatch.h,sha256=cCCF-yLpuwa-V8dwSilqE_TjvthfAtcC1rwkBmIcH9M,1912 +torch/include/ATen/ops/sparse_coo_tensor_native.h,sha256=UXWH223UfzGtuJVVTOFYPCkWt8eYj9kIKV37jvBsvoQ,1614 +torch/include/ATen/ops/sparse_coo_tensor_ops.h,sha256=XpFMmYyR4qvIVh63VFSf7zVvpCfUe2DZTqlRx9VzMCY,5001 +torch/include/ATen/ops/sparse_csc_tensor.h,sha256=f3_js_8uoVbtDaxRtTzPWSLRzpMgpzjeENPpS_uvUcI,3247 +torch/include/ATen/ops/sparse_csc_tensor_compositeimplicitautograd_dispatch.h,sha256=j6KpXBjMBO4Upp7j9Z3JeAHOEGBnoG_6jvUF7a2_FpI,1880 +torch/include/ATen/ops/sparse_csc_tensor_native.h,sha256=H_0c5twzqVfwswcBVgQJ_NKggrhehFm_FOKkEyucChw,1276 +torch/include/ATen/ops/sparse_csc_tensor_ops.h,sha256=yM2g-NHHkMkebFXxTv43mfZ4HiNGkrW8CXaXRLUyHD8,3381 +torch/include/ATen/ops/sparse_csr_tensor.h,sha256=-Yh3gwqcjTcQVTlvwFafYcrE8GfVrWo3auTSQ2eRujk,3247 +torch/include/ATen/ops/sparse_csr_tensor_compositeimplicitautograd_dispatch.h,sha256=3CxhedXXEzGJF8ZTVxqwfFABmmsHea_h2ej1PqIh8xo,1880 +torch/include/ATen/ops/sparse_csr_tensor_native.h,sha256=P8G6aSqmi6fN-HZypmvazbyQn7_6VJXEDhAiFd3pH2s,1276 +torch/include/ATen/ops/sparse_csr_tensor_ops.h,sha256=ikJq-toeMTKrP0Yk9FVsKYCSSUSST4_TKueeP5FwosU,3381 +torch/include/ATen/ops/sparse_dim.h,sha256=GUvojgxOi9n7IQ8Wi7UkGt6-Vy3q7VZGQ1Gt3UmDM9k,761 +torch/include/ATen/ops/sparse_dim_compositeexplicitautograd_dispatch.h,sha256=iH0LCbBzWZb2tkGAz38GnpTgyWHNynjM5ad804GB8OU,1019 +torch/include/ATen/ops/sparse_dim_native.h,sha256=1Ht7WFWJlQouChzvR-tpHdYwpSrT6mm3SgYHRDLil-4,867 +torch/include/ATen/ops/sparse_dim_ops.h,sha256=gw79EMAX-HUG6Uv6NJqoZlRe8L6fdcc1O8CfF9EbWOY,1211 +torch/include/ATen/ops/sparse_mask.h,sha256=jZaxKGZqNzClx9hM1bkoG2s5RrBdJQhoKxbwYE2YUoQ,1269 +torch/include/ATen/ops/sparse_mask_compositeexplicitautograd_dispatch.h,sha256=55Y4UopDswrn4kWu6-2pASWEj-gumemWVMbGRTn7ekI,1181 +torch/include/ATen/ops/sparse_mask_native.h,sha256=eWPWLddFWPP4iE4hVzAH7UdIsjfN9sn2iPTCmR06Gk8,970 +torch/include/ATen/ops/sparse_mask_ops.h,sha256=Z9MV78AADtPk8-KYNxA7j0uotThmpnSg2VYzfjjpLbg,1997 +torch/include/ATen/ops/sparse_resize.h,sha256=bz1iI69PZNC89k5Ul7BwyLh8LRB1kczqG-9momSDgHI,1774 +torch/include/ATen/ops/sparse_resize_and_clear.h,sha256=f0Vy0hPeSo-NqjQjLoZL9bvwwqQn7BmM7CSKeA8oytw,1874 +torch/include/ATen/ops/sparse_resize_and_clear_compositeexplicitautograd_dispatch.h,sha256=WEMQ-GAMCq6Q1sR0xufvpL6rgD8eV7s9sYlhQvS-pJQ,1433 +torch/include/ATen/ops/sparse_resize_and_clear_meta_dispatch.h,sha256=ikbGTRc-SyOBmlYHFtbGeq8YcBkErfoxVwuVyG1sYks,1063 +torch/include/ATen/ops/sparse_resize_and_clear_native.h,sha256=1mGBXIXhnLk2gFwwT079F1Kjy7WUQQK4XOhwfTBbbXU,1117 +torch/include/ATen/ops/sparse_resize_and_clear_ops.h,sha256=up0xhBcF7J0hiyXoqTw_81mp9rKG2UE0Zh4IwCzi8UI,3125 +torch/include/ATen/ops/sparse_resize_compositeexplicitautograd_dispatch.h,sha256=BuIKFbO0XExqms6fNDLhZEKw2pN6gY6yegkV6awfdRU,1403 +torch/include/ATen/ops/sparse_resize_meta_dispatch.h,sha256=l0OXu6u-LnLweEeVji8E6J0rT6spqX0VqB0q7_NuiTA,1053 +torch/include/ATen/ops/sparse_resize_native.h,sha256=T9U2eEtUQg1oyaezslYuG1gwPyCv7-0PJj4MA-tlYbU,1087 +torch/include/ATen/ops/sparse_resize_ops.h,sha256=brrwab60RKJet_ZWIioSgYtmiGS757zEgesQqBKYioo,3035 +torch/include/ATen/ops/sparse_sampled_addmm.h,sha256=QAR_bQg-IN3V7WiLaAh9spJZjWgkzjD8cU1kDpJ2rz0,1981 +torch/include/ATen/ops/sparse_sampled_addmm_native.h,sha256=OpOTKN_7ZhOm8ZVBPk7nE_THrb-Pip66TGwT0c6maAc,1470 +torch/include/ATen/ops/sparse_sampled_addmm_ops.h,sha256=8W-K5jXUeghvwqy-_fUhaK3qPFEH0EuCIYqPFgmyfsQ,2566 +torch/include/ATen/ops/special_airy_ai.h,sha256=MKkP6VJEU4iFHFjposTGGlKu7LCD8Np59-bskHFFwuI,1344 +torch/include/ATen/ops/special_airy_ai_compositeexplicitautogradnonfunctional_dispatch.h,sha256=-7G3ug6FYHXseEgf8P60d3r4hbqULhdh4fe5kh6lYLE,1050 +torch/include/ATen/ops/special_airy_ai_cpu_dispatch.h,sha256=sa-UrcPW1OkJNcpvsazihoJH0V57xypf-jBAi8SGrGI,1149 +torch/include/ATen/ops/special_airy_ai_cuda_dispatch.h,sha256=TD-g4V8Q8qdcZNo2rh1ehEB3QVA7HgAfNUQA5dpvFrc,1151 +torch/include/ATen/ops/special_airy_ai_meta.h,sha256=sUmRfedCbiCVHeuyAG18AVwK5OggeeGRzIXfkEmROCw,827 +torch/include/ATen/ops/special_airy_ai_meta_dispatch.h,sha256=pJnE5QeYLKSEOyHYHYrQ3AlEhzoO9Om_mICEKB3hqCI,1151 +torch/include/ATen/ops/special_airy_ai_native.h,sha256=AF6HaJucbem1_Ke-ltgZNAL0gmA_e9yEzjxsayHFyMs,874 +torch/include/ATen/ops/special_airy_ai_ops.h,sha256=10MxwI2KYSeBIaeSo0DD0UUu0bsBhls1b_cL_gdeOKg,1837 +torch/include/ATen/ops/special_bessel_j0.h,sha256=cY7uADPldNTI3uLCYE8C9orzXvuRiqfpZxm4K56uv9g,1391 +torch/include/ATen/ops/special_bessel_j0_compositeexplicitautogradnonfunctional_dispatch.h,sha256=HIJDQ_TVxHKQ-4GFnDPkMjR03LtzfXbQ3vZTZEqHD90,1055 +torch/include/ATen/ops/special_bessel_j0_cpu_dispatch.h,sha256=6qL6BLh_BRu1cV_OoG1a8P_651ruCAJj7NEwONhuX_k,1164 +torch/include/ATen/ops/special_bessel_j0_cuda_dispatch.h,sha256=IwGeBMGBpWVHg_lHt_Y6zhKw_3BaH6TQXtKCl8B_hnI,1166 +torch/include/ATen/ops/special_bessel_j0_meta.h,sha256=IbpcQ8vd1PvtJbeGDJAs9_CWYgrkJuunXdhiIXG9LVs,832 +torch/include/ATen/ops/special_bessel_j0_meta_dispatch.h,sha256=rMj_YaFJCeRaNFBG8eE095I_QfZYUicteaMwpNvLJqY,1166 +torch/include/ATen/ops/special_bessel_j0_native.h,sha256=_3lUH5OTltPTBmqaHfoRtgJyz6pcD0Cu1l4WzWW9DiY,883 +torch/include/ATen/ops/special_bessel_j0_ops.h,sha256=yCLyfSfnWVrkjXmm7JfPTjF8eQdusLXUIl_5MsiR01M,1867 +torch/include/ATen/ops/special_bessel_j1.h,sha256=nVrhWo9tZ2LeAQ70ffygC3chiz3W-UXGTMMt_DoL37s,1391 +torch/include/ATen/ops/special_bessel_j1_compositeexplicitautogradnonfunctional_dispatch.h,sha256=7MEMk4haPBys3RRxygKoxsZC8cpAamzNDkROlNjn3MY,1055 +torch/include/ATen/ops/special_bessel_j1_cpu_dispatch.h,sha256=8vQMh612vheyQP3rt9LC3hTFtieNPplBsvKhGEK_wTc,1164 +torch/include/ATen/ops/special_bessel_j1_cuda_dispatch.h,sha256=D6aWFlKew1y9-SbVKnfilVYe2G3bjlifKk1OQl-hTj0,1166 +torch/include/ATen/ops/special_bessel_j1_meta.h,sha256=KvBfYUmDK005GRvpqmvxXURg25y3TFjPsL1O3sOW894,832 +torch/include/ATen/ops/special_bessel_j1_meta_dispatch.h,sha256=w_PCyg1v9J6j4TiNLuGFSUZ51Vai8dIYlRM_jCkBvyQ,1166 +torch/include/ATen/ops/special_bessel_j1_native.h,sha256=siQYFLzHqHaKH2uYCuXPVf1v_pGHYJB_pibnqgR8lPU,883 +torch/include/ATen/ops/special_bessel_j1_ops.h,sha256=crKMbapmMiBb1-qmEoMuYYlJWmxPkRlNwsArYw70Bng,1867 +torch/include/ATen/ops/special_bessel_y0.h,sha256=SmTm_yx9QYAxjtq_4iczvFLGMEGUXI-O0FTgO42pUv8,1391 +torch/include/ATen/ops/special_bessel_y0_compositeexplicitautogradnonfunctional_dispatch.h,sha256=w35AhLsOmXvfkCebPmtHiiGOsUo-IhotKwYA-jxstKA,1055 +torch/include/ATen/ops/special_bessel_y0_cpu_dispatch.h,sha256=ickI7Kqy82X31ISx14wv2g9MP6ZGhmKL5a87Sm8QE18,1164 +torch/include/ATen/ops/special_bessel_y0_cuda_dispatch.h,sha256=q4SgZymb03Pd5ecz20hJO1bTDN5pEg3B3H08B3NzgEc,1166 +torch/include/ATen/ops/special_bessel_y0_meta.h,sha256=BSwyOGNAaXLVDiUv5LHFHTlB734hy1WPDzkwDAFIdyc,832 +torch/include/ATen/ops/special_bessel_y0_meta_dispatch.h,sha256=jqRF-zM8B4RiMIC1ODKcuA7QE4q5YBRLqRG5XEl61po,1166 +torch/include/ATen/ops/special_bessel_y0_native.h,sha256=gBxl6iFgYp6uj1RH5I3xaeYOoJAKoQqz5IIQpK3Egi8,883 +torch/include/ATen/ops/special_bessel_y0_ops.h,sha256=s66Fr0lhZ6CfE-Ka-ROmQ4qsfEKeop00ZEbDnMhcpcI,1867 +torch/include/ATen/ops/special_bessel_y1.h,sha256=0PBbb0eMuooE_M7YaOPuPBpeaAfd8vTQ3jRkZ7TCrJU,1391 +torch/include/ATen/ops/special_bessel_y1_compositeexplicitautogradnonfunctional_dispatch.h,sha256=AoWAHK0WCK7Ns3OcwF61dGjTBZU0xQbCfXn3sBshAVc,1055 +torch/include/ATen/ops/special_bessel_y1_cpu_dispatch.h,sha256=fP8NP8yaL3pO_-NRGNNm02yK5kSURwAwmeOooibzLXY,1164 +torch/include/ATen/ops/special_bessel_y1_cuda_dispatch.h,sha256=EmWRwwYmJISV9rO9JREOFdQpJKeTtLr66-2fn8jWsFw,1166 +torch/include/ATen/ops/special_bessel_y1_meta.h,sha256=RuyvQGHmMXkDaZlSXZIlAukCsFuePn5wL7YQWEeeSYE,832 +torch/include/ATen/ops/special_bessel_y1_meta_dispatch.h,sha256=2NTcNGJODqG0lUbSyyNqYZXtAvF7WjbPhTBMrb56yAg,1166 +torch/include/ATen/ops/special_bessel_y1_native.h,sha256=5xEs4HoS_dDjU-yHR63qKcaUAnd5mH9_HBQ0ZhrHCqI,883 +torch/include/ATen/ops/special_bessel_y1_ops.h,sha256=lDIiNDqfNjlVD24Gzytqzq6ks8RAam0oe2NR9L8Z1Lg,1867 +torch/include/ATen/ops/special_chebyshev_polynomial_t.h,sha256=iJGF4l99S8Urp06GTtce3lwSDZX8Jj18R08VXBWhpE0,3345 +torch/include/ATen/ops/special_chebyshev_polynomial_t_compositeexplicitautograd_dispatch.h,sha256=CMWRtks5CwTapR2nAyka1rrj-5s0-vrtfz4CdM0oABU,1644 +torch/include/ATen/ops/special_chebyshev_polynomial_t_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Bmq0VrGdwio8dZGLdtByZcVDl2GNeSPz61p66vIp2tI,1087 +torch/include/ATen/ops/special_chebyshev_polynomial_t_cpu_dispatch.h,sha256=eo2T020-_H2Ek824jblyj4B57JqQJ_SzCWgz0UGPLiI,1260 +torch/include/ATen/ops/special_chebyshev_polynomial_t_cuda_dispatch.h,sha256=2n-MRqFfvjR4O4_Xor5KzvIszpJrgysdxkSOe3YlkD4,1262 +torch/include/ATen/ops/special_chebyshev_polynomial_t_meta.h,sha256=FPPWmsHFYQgDMM4fWpd-rFwPONlgVKW3uIZKV7WP75E,864 +torch/include/ATen/ops/special_chebyshev_polynomial_t_meta_dispatch.h,sha256=G8CpwZ9WH_CbQEgdNFyw_wmW4WtnlwkKCbfRA1tot7A,1262 +torch/include/ATen/ops/special_chebyshev_polynomial_t_native.h,sha256=kpgpZx6RkIf7cHkZ69SMkygKbb9mKEuMmqPnp_-h1MQ,1377 +torch/include/ATen/ops/special_chebyshev_polynomial_t_ops.h,sha256=spsBX-QUpZCMDuWGP20bprmbWsS5t3gHPcBscxUTR-4,4909 +torch/include/ATen/ops/special_chebyshev_polynomial_u.h,sha256=_LJaTeQhRUBaAoK9pNF7wns8rIitcn49PWqde4vIpdk,3345 +torch/include/ATen/ops/special_chebyshev_polynomial_u_compositeexplicitautograd_dispatch.h,sha256=KOHk9UHSNaQOOR4Ryzb2jixdl1mgICS6I89ekfAHxY0,1644 +torch/include/ATen/ops/special_chebyshev_polynomial_u_compositeexplicitautogradnonfunctional_dispatch.h,sha256=0BDs0Mm1RoqSSZldsN9P5Q7lIzfCDmK4KH7LY7ra8EU,1087 +torch/include/ATen/ops/special_chebyshev_polynomial_u_cpu_dispatch.h,sha256=chx-U_NRh_mloUaOW1qN9D4kXD0HTzYw-kdZzPlPyfM,1260 +torch/include/ATen/ops/special_chebyshev_polynomial_u_cuda_dispatch.h,sha256=0VSdEVxNAdk7HB-A714mozml-qtZ_51myydxTXudWVM,1262 +torch/include/ATen/ops/special_chebyshev_polynomial_u_meta.h,sha256=TGOqS3FKLG4Vif_r_D_w7c_8QtgB8o89zvxo6CPenbw,864 +torch/include/ATen/ops/special_chebyshev_polynomial_u_meta_dispatch.h,sha256=hCecgooNwQgrJp2YfibkeRYH7ING33ybLI1SLB0fOH8,1262 +torch/include/ATen/ops/special_chebyshev_polynomial_u_native.h,sha256=_LwdIr0IWI0KfEQB9wonDevxQbxXr6DRB8VFX_e-u0I,1377 +torch/include/ATen/ops/special_chebyshev_polynomial_u_ops.h,sha256=4DdlYHI2-DjgcE5K7KVvg1hYIxj6zi1IUrt_YaoayI4,4909 +torch/include/ATen/ops/special_chebyshev_polynomial_v.h,sha256=91vb59p9yLOKzhsukhKnkFhRk5Df5rtZL-6OvM6f0tE,3345 +torch/include/ATen/ops/special_chebyshev_polynomial_v_compositeexplicitautograd_dispatch.h,sha256=ttyA0gAEONgzWWs0F1AbImF290mwayU-5ieBoKnC0i0,1644 +torch/include/ATen/ops/special_chebyshev_polynomial_v_compositeexplicitautogradnonfunctional_dispatch.h,sha256=6G6Xa0eZKnfZy2FJNHdB6bpJFI9jC9WABYxTefl-liU,1087 +torch/include/ATen/ops/special_chebyshev_polynomial_v_cpu_dispatch.h,sha256=v2b9fl6B-VQIZVSjpwnZYnoYgvTF_-OL2NoQEtkQDv0,1260 +torch/include/ATen/ops/special_chebyshev_polynomial_v_cuda_dispatch.h,sha256=btPy-fatG8R6ybQEAU2uLerQjFtY8b9nh5LXKZ8IJlE,1262 +torch/include/ATen/ops/special_chebyshev_polynomial_v_meta.h,sha256=oi1pEYpPL_VpaTx0a1JlZh1UBcSn77DhOnEELJ0n5nM,864 +torch/include/ATen/ops/special_chebyshev_polynomial_v_meta_dispatch.h,sha256=h13wIrsCL_pt37YfBwq0jNyhDlNTbYLmR9Godh1vvf4,1262 +torch/include/ATen/ops/special_chebyshev_polynomial_v_native.h,sha256=mWSEAWqIHXOSg7nh-l53Xw8qwUlt5QDHzva4xQPhvCc,1377 +torch/include/ATen/ops/special_chebyshev_polynomial_v_ops.h,sha256=u0CYvF7eELw7eb5ANWnRe_JLacS_3OAOG404OOfUG0A,4909 +torch/include/ATen/ops/special_chebyshev_polynomial_w.h,sha256=vQ7ypfNy-yQhzbrpAGxSWA5-maTLR66RLjlvZ_rOyg0,3345 +torch/include/ATen/ops/special_chebyshev_polynomial_w_compositeexplicitautograd_dispatch.h,sha256=0s1D99p5-PVxVdU3DywLSnQt44wXisrYhCOYd4UaRTE,1644 +torch/include/ATen/ops/special_chebyshev_polynomial_w_compositeexplicitautogradnonfunctional_dispatch.h,sha256=NAzztlUcGLfdfVnN3Tbif9Pqz7EpBTrsJLzsLgzuF5s,1087 +torch/include/ATen/ops/special_chebyshev_polynomial_w_cpu_dispatch.h,sha256=sDHtOKJhoeC4ipgLe51V8YfeWL8bsWa3wrVLuST1uds,1260 +torch/include/ATen/ops/special_chebyshev_polynomial_w_cuda_dispatch.h,sha256=YaYUbG6Bn__zFCVC_1DciuyAcHf4qdkF9M68sPDhyTE,1262 +torch/include/ATen/ops/special_chebyshev_polynomial_w_meta.h,sha256=WO2H2QN4UVuYehuFEbAAt0fck2VV4KMu5smBmLhwW0E,864 +torch/include/ATen/ops/special_chebyshev_polynomial_w_meta_dispatch.h,sha256=fHuWQYnPFPp6P4HZgcbfURgYtIODBLoNKCFEzFF9nbQ,1262 +torch/include/ATen/ops/special_chebyshev_polynomial_w_native.h,sha256=ez7ESxhZfbbvubQmb1UQMdMblupq78iYn4O0_9SJu-M,1377 +torch/include/ATen/ops/special_chebyshev_polynomial_w_ops.h,sha256=HSdSOCjrJr5jHqJDeHGthKiiBna3lk5gid8rWLw27qc,4909 +torch/include/ATen/ops/special_digamma.h,sha256=9IJO14dA23fjx-JjlQWLEgAJy6LaYJJ7FQVU09QPg4A,1371 +torch/include/ATen/ops/special_digamma_compositeimplicitautograd_dispatch.h,sha256=4CuO5JDdCwqjq8xRfcNnpno08uyuoArqvShdeAOSklo,1202 +torch/include/ATen/ops/special_digamma_native.h,sha256=kgf2-xl0f0i_nbdlEU0iRKgwH-0l1HuGR330VIJBWso,826 +torch/include/ATen/ops/special_digamma_ops.h,sha256=ekbnyGkNy4pj9HO_wWzRx9Txp_BzZ_nzi_3y6mlq1S4,1855 +torch/include/ATen/ops/special_entr.h,sha256=RXPAAE9uYwxy-UJocNQCWLLc9atFtJVO3W2T9mf_3f4,1341 +torch/include/ATen/ops/special_entr_compositeexplicitautogradnonfunctional_dispatch.h,sha256=knUtBKaUL3jgFe8VKdhtqadvBESqolJ7cSWZYol8d10,1050 +torch/include/ATen/ops/special_entr_cpu_dispatch.h,sha256=bGXo7Ya-ymChtAEcH_Tep-GsGdxqgNS8YXv1AG0M94I,1149 +torch/include/ATen/ops/special_entr_cuda_dispatch.h,sha256=_AVglvrj-gf7TWtAWwVZsXBjxTArP1v158B2TZ4fMsk,1151 +torch/include/ATen/ops/special_entr_meta.h,sha256=wBqjCkTvuIB-TAqXalSb_2wGmTAEiXfrjI8xakvdFqc,827 +torch/include/ATen/ops/special_entr_meta_dispatch.h,sha256=_r-uhmQ4PRZTDPlkgszC90cFvjsPn7mGC_9lVPMClFs,1151 +torch/include/ATen/ops/special_entr_native.h,sha256=0HzQxu5DaiVcwGQcpdeags8RfvbnDsKWnicadCO_QVM,868 +torch/include/ATen/ops/special_entr_ops.h,sha256=PiVB22Vof6Vd70QSzSePmyCLWhysEKQU_tnMpaIkbvk,1837 +torch/include/ATen/ops/special_erf.h,sha256=6ahoHHfgVYsJP4ZGm63Ho0Os8up1znPnk2YpMGMFpuY,1331 +torch/include/ATen/ops/special_erf_compositeimplicitautograd_dispatch.h,sha256=h_bYrWWNMg7_241ad2NZb_y7Ln2TLL_f9zTFdsNUhUw,1190 +torch/include/ATen/ops/special_erf_native.h,sha256=Cjg0Tb1VfnDty0YBy9s7gw0jxq8DpXPqGyvW6EwPDuA,818 +torch/include/ATen/ops/special_erf_ops.h,sha256=hLz2KLgKijNjhSEws118zNS2YT3eqwwcWT4ubnOrxgk,1831 +torch/include/ATen/ops/special_erfc.h,sha256=MVlB88tp5SSSttvm5TQKm3a8rn5k3WGXLUt1pnrlbnI,1341 +torch/include/ATen/ops/special_erfc_compositeimplicitautograd_dispatch.h,sha256=37Lk32_Q6tBZ8ZPxUGk3dO4cV8Ys2gIxOeTgYdKYcYA,1193 +torch/include/ATen/ops/special_erfc_native.h,sha256=NFP0XORc10VRACdJMgXm6bVYPgngrqHjvzO8kUcKiu0,820 +torch/include/ATen/ops/special_erfc_ops.h,sha256=PZKxoYNF1Wv1_vo2LRTJOL7SNYGiNPXQo25tUHsDlBo,1837 +torch/include/ATen/ops/special_erfcx.h,sha256=45fWlZW2faNHPKXRAWwpQ0Ur77sY45NyYC1ul6tEt7w,1351 +torch/include/ATen/ops/special_erfcx_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Yv9ss35FvKIafiJxl8f-7CIoEARS5hQdfovaEztRTho,1051 +torch/include/ATen/ops/special_erfcx_cpu_dispatch.h,sha256=pvT9oVRajlxj7xyXpqFw_XmyfHeNUgoRXEqS_YD3rwM,1152 +torch/include/ATen/ops/special_erfcx_cuda_dispatch.h,sha256=ePdPBCLtPLd9MVaXceOYMAJcY0L6cZnNP48GN5LJs-Q,1154 +torch/include/ATen/ops/special_erfcx_meta.h,sha256=ChdzGzHgGQYG7Sz-k2VjbIx3UtpOQ3SBtKYizWQwYk0,828 +torch/include/ATen/ops/special_erfcx_meta_dispatch.h,sha256=8urEMFpSBgIXw0FaFboczc_vz6IprXBOwP0qD6_Pj5I,1154 +torch/include/ATen/ops/special_erfcx_native.h,sha256=Uh1nffGM6CwIUAEboudSMC2XGzh9WPPhbuo5LWtYybQ,871 +torch/include/ATen/ops/special_erfcx_ops.h,sha256=NF6B2cH7iAeei9wg9DYSacT60kNTdGe4Hf5NAswGnrA,1843 +torch/include/ATen/ops/special_erfinv.h,sha256=L2pSvMBg0m6tXuQ9hEEY-NL8IM1cpBau5NKOm7Yt0a0,1361 +torch/include/ATen/ops/special_erfinv_compositeimplicitautograd_dispatch.h,sha256=1gGaBYei-MK-ev5MsnyafoRSpU3vDeVXj6Sr8otNhPI,1199 +torch/include/ATen/ops/special_erfinv_native.h,sha256=ZZkxIDlrvSqIc7SZS2YKSjsnPGjJPivRYeI_MmSwaks,824 +torch/include/ATen/ops/special_erfinv_ops.h,sha256=LaGbcWJ7CMbeg5ZVqAIMA6MU6Gvc6i3-EEiBHIiqBCs,1849 +torch/include/ATen/ops/special_exp2.h,sha256=D0DhA2YQUqSNQqtlMl2oN44ske7fwCwbhQOKYtkMUFQ,1341 +torch/include/ATen/ops/special_exp2_compositeimplicitautograd_dispatch.h,sha256=8wjnmWcfzFRetLhRnCT2_9o5NRHiKDbi6HvKJDvg4N0,1193 +torch/include/ATen/ops/special_exp2_native.h,sha256=OQCoRcLfVHT07wVAZbZhyEN7oPLmDHiHOT6wpHLHyKQ,820 +torch/include/ATen/ops/special_exp2_ops.h,sha256=31MAdisy6DXWqIl2JN_HDUOTJVAjD13pFjMKXRSE3kg,1837 +torch/include/ATen/ops/special_expit.h,sha256=IfAeCldygOH2FBAFRgfvDhucQBYfcX0qWobtqY7dX2w,1351 +torch/include/ATen/ops/special_expit_compositeimplicitautograd_dispatch.h,sha256=GZ1IKb-EED6Htf5FqrPq-y6TVSBTy3jCAuywLAAYIMc,1196 +torch/include/ATen/ops/special_expit_native.h,sha256=VYjTdnRAoF48b05TV4tYn9ZnUF7nNEab22vuTJFq_sE,822 +torch/include/ATen/ops/special_expit_ops.h,sha256=NPV4sSVF010UxdJFgqU5olskTFuofJwjUkDz1rBxeHE,1843 +torch/include/ATen/ops/special_expm1.h,sha256=dInqsPU1Kyy5aj-32n96F07T14RJaHbMEImcKovOVVo,1351 +torch/include/ATen/ops/special_expm1_compositeimplicitautograd_dispatch.h,sha256=cqRJMp8nKMWCMJfMLW-BugIXP2_gYe_Fhd_sA0il-yU,1196 +torch/include/ATen/ops/special_expm1_native.h,sha256=tak2dFsNCadHVg3bZZ7FbnMW2VfqkdsigPmvICsNioo,822 +torch/include/ATen/ops/special_expm1_ops.h,sha256=xyqoNipDGNlYFymWoe6T6oC8rqGS6ImTlmcVwRxmh1s,1843 +torch/include/ATen/ops/special_gammainc.h,sha256=__o3k6dr-78wbXqejnCBWHQNx8h4gPcP3Wye0PEAUsQ,1522 +torch/include/ATen/ops/special_gammainc_compositeimplicitautograd_dispatch.h,sha256=9hMxf7TTAllEV1TlCouWvgHssP-KmoIOcnjYfArDeoU,1283 +torch/include/ATen/ops/special_gammainc_native.h,sha256=PuV1vZKpTgSxD6QPF6UhO7mpW6ifjWoZs3Q_tHJ3XZE,880 +torch/include/ATen/ops/special_gammainc_ops.h,sha256=pKoAX30_vcVhWjdZ0GbizFHoClBwUTzA5ToRWXVF2Fg,2033 +torch/include/ATen/ops/special_gammaincc.h,sha256=WpUl5Q3REdKvyukcwfg875csnXeOAjRtEySkx5ctl0k,1532 +torch/include/ATen/ops/special_gammaincc_compositeimplicitautograd_dispatch.h,sha256=X3onM9dOzUkb2XIhW8WfeXvnKwx0lAWDPHuhba9xlOI,1286 +torch/include/ATen/ops/special_gammaincc_native.h,sha256=uID8FzXSVHOE4ARBXCGtJv3Bcd1dvBiiXn8mLjXPrtk,882 +torch/include/ATen/ops/special_gammaincc_ops.h,sha256=3gLk5c5mGMVKhjeg0_TSOnMQ5FYza_0Tw3xmB2oXPKo,2039 +torch/include/ATen/ops/special_gammaln.h,sha256=DgU7Gs_u8yTomOfanFbOSjEPPfCPVALTCK4BZyTP1M4,1371 +torch/include/ATen/ops/special_gammaln_compositeimplicitautograd_dispatch.h,sha256=JuBT08-gBvUxQS0jkaxDu9WBgEX9YbEZJN0sObuhU14,1202 +torch/include/ATen/ops/special_gammaln_native.h,sha256=UxjjIJOOdbx88Yrl9nQyd0mdMvx-GGUk1tYZHwOAvH8,826 +torch/include/ATen/ops/special_gammaln_ops.h,sha256=mjU0VPWENCLHfRQxea-E7NAAd-DYdWrpyBO4XLi4ly0,1855 +torch/include/ATen/ops/special_hermite_polynomial_h.h,sha256=1NcmEnYt7W87F02aTb-W6dMbl_f8Ee371ffTBAB7Wa4,3289 +torch/include/ATen/ops/special_hermite_polynomial_h_compositeexplicitautograd_dispatch.h,sha256=cFds92tXmhWqwRhtJSTwRYNLMRmO-QfetMiydZlvazU,1632 +torch/include/ATen/ops/special_hermite_polynomial_h_compositeexplicitautogradnonfunctional_dispatch.h,sha256=HwIIwovuYv2jywNU4I6uJ-LOiXpJPxoaXYRn8abyhpY,1085 +torch/include/ATen/ops/special_hermite_polynomial_h_cpu_dispatch.h,sha256=9YN5hMQ2lkY3KiYP3ToUchuVZDK3UTf85MKxRDNu2sg,1254 +torch/include/ATen/ops/special_hermite_polynomial_h_cuda_dispatch.h,sha256=JIVcIsBYUnkyzwGl6qf7xYl6MK0Qd1VUNidvnSsbf6E,1256 +torch/include/ATen/ops/special_hermite_polynomial_h_meta.h,sha256=laM2E7R2zuw-IYj0HpOvS6N7kOZtX4zAujxbnNyi0EU,862 +torch/include/ATen/ops/special_hermite_polynomial_h_meta_dispatch.h,sha256=RF5oPI6jtmudoPVwYhL2DRo4jDdoEN7M7l6ZOF47Vck,1256 +torch/include/ATen/ops/special_hermite_polynomial_h_native.h,sha256=0gCHnV2iFGDuCelDUEZiIpLIdwiMhU1elq2KYWaLROo,1363 +torch/include/ATen/ops/special_hermite_polynomial_h_ops.h,sha256=jegH2yawZXiXoaQj1seWQDYrmh0WXS1jm6zsvLQ-OrI,4873 +torch/include/ATen/ops/special_hermite_polynomial_he.h,sha256=46rcDhsEvNR0jH0cbhyWYHJI9w5S8jR5taDv830rV_I,3317 +torch/include/ATen/ops/special_hermite_polynomial_he_compositeexplicitautograd_dispatch.h,sha256=JzgfiQf3R48UNUP1HoirMIlbCl_4125mqte-dJnCy1Q,1638 +torch/include/ATen/ops/special_hermite_polynomial_he_compositeexplicitautogradnonfunctional_dispatch.h,sha256=dgWcI8LCfw34FGsDBoiNaJJ-5IcUqv4zD-wlQqWEt0E,1086 +torch/include/ATen/ops/special_hermite_polynomial_he_cpu_dispatch.h,sha256=pS5w3_VAR3_7RPS8_nrV71hAZ6g5GSpwBGbCDQB3DMs,1257 +torch/include/ATen/ops/special_hermite_polynomial_he_cuda_dispatch.h,sha256=kjlAmbgG7LnND8GldBD6u9-UmjIun6RvwwgOXuYrpCc,1259 +torch/include/ATen/ops/special_hermite_polynomial_he_meta.h,sha256=oA8GWkZK93PKJ9QWgO1tC7ER1r1CZoDcsqGr1phVJ9k,863 +torch/include/ATen/ops/special_hermite_polynomial_he_meta_dispatch.h,sha256=jzQcA_qmq-mhz8dO-GUtLOrzKsgqO_UcX3DKPkk8pps,1259 +torch/include/ATen/ops/special_hermite_polynomial_he_native.h,sha256=JohrF2JLG3acHHMzOFGKIo1_a5DL04t2Q2Tp5xaz4lE,1370 +torch/include/ATen/ops/special_hermite_polynomial_he_ops.h,sha256=xgUZrso2yg2rCUqagiDSemof1B99ctX9BpHQV0vWr8k,4891 +torch/include/ATen/ops/special_i0.h,sha256=V8tw2tchIuEULXe0-eUbBSDpZXzxRiV9l2EU9GwU0dE,1321 +torch/include/ATen/ops/special_i0_compositeimplicitautograd_dispatch.h,sha256=3n55QHcEK9bGMLjEHjSVv8V2h_sAVDumKo3rPaEax5o,1187 +torch/include/ATen/ops/special_i0_native.h,sha256=5abiuijh7_P0oyFiXWZBOihUZ3vvWD2bjo8mTFEA4wc,816 +torch/include/ATen/ops/special_i0_ops.h,sha256=7-vH2Zn11RKKv8mC1-xxKIxFvsy1Dy-qQcgKfiXAzh0,1825 +torch/include/ATen/ops/special_i0e.h,sha256=AiDmRthvu28UkJ0uhGemNw039NQR9-HiINojgXUqWH0,1331 +torch/include/ATen/ops/special_i0e_compositeexplicitautogradnonfunctional_dispatch.h,sha256=3VrisaWO3mBL0fxjkqtcOAc7cs-Okwrhn6xgSaCORE0,1049 +torch/include/ATen/ops/special_i0e_cpu_dispatch.h,sha256=GxfnZlWwmNQPQeiXQQS8DD7_huUMoQ2R-bh52uuHXbA,1146 +torch/include/ATen/ops/special_i0e_cuda_dispatch.h,sha256=J5JkIaLlmUprurVjNnfhyg6uMMxmJ_o_jLWm7oyJaSU,1148 +torch/include/ATen/ops/special_i0e_meta.h,sha256=0ExsHhz9Fj-jFueA2lELSakT2bhTuFDjhVEwfUJpqZQ,826 +torch/include/ATen/ops/special_i0e_meta_dispatch.h,sha256=xuX65J-6Chc1qSh-34w2mpj7m2y9cmwDJVItIxCzesc,1148 +torch/include/ATen/ops/special_i0e_native.h,sha256=ptlotzB-Vc3z1xFHPqXAckuZ_mzOuiFk5QXwjCFLzdY,865 +torch/include/ATen/ops/special_i0e_ops.h,sha256=gveA6iHza7QALWZdZMOdl-H1axSyWDVKKWVX2R_Gkx8,1831 +torch/include/ATen/ops/special_i1.h,sha256=dWPvLqcPNANXxEZNr-JY_IKZ0r38aOPXPCNhkuhhDx0,1321 +torch/include/ATen/ops/special_i1_compositeexplicitautogradnonfunctional_dispatch.h,sha256=mrt6tRPObeVF63ubo-KZ69AZKBVWkuH-O24Uk14cD7Y,1048 +torch/include/ATen/ops/special_i1_cpu_dispatch.h,sha256=Y0wgEAJ4hvwEKVCVyv_xWaERHzvuylMER_WtI6vMTE0,1143 +torch/include/ATen/ops/special_i1_cuda_dispatch.h,sha256=m84PlCbbrlpf-3ChcQw9vZtmzufJJoCFNzwkYIpfceM,1145 +torch/include/ATen/ops/special_i1_meta.h,sha256=PU1wCD1BF47vsuIdtXczfrPv2aUpSEBr23i_ef0BrXI,825 +torch/include/ATen/ops/special_i1_meta_dispatch.h,sha256=Bjnpp5U9UiAODTkNfP1-xQ1EvMNbqbnbHWQbvFKYnVo,1145 +torch/include/ATen/ops/special_i1_native.h,sha256=NRjnBeA-UryUnTOZtgYTF0Q4ObEoYyOJAzY9OIRrkq4,862 +torch/include/ATen/ops/special_i1_ops.h,sha256=WXASfh66RmlI8GyeD3hXSgVNATgEfDeubOg64iQlaQI,1825 +torch/include/ATen/ops/special_i1e.h,sha256=zn4Tli6lsMaAm5R0Y53cp447QfP-Z1RRsAZDrvBWCsg,1331 +torch/include/ATen/ops/special_i1e_compositeexplicitautogradnonfunctional_dispatch.h,sha256=BqEOEMu8q64I2yD7LQF2PGUNioRq3lXqjoMHPVMyEBY,1049 +torch/include/ATen/ops/special_i1e_cpu_dispatch.h,sha256=ceBZ37IDl4vchgou6Uj1h2RPl8VKKMXIs0Idw2FQlUw,1146 +torch/include/ATen/ops/special_i1e_cuda_dispatch.h,sha256=k61rhKBWQb8XUujD_LLyDgKcaJHh2bNu1My-D47iZjk,1148 +torch/include/ATen/ops/special_i1e_meta.h,sha256=cV0GwP6QTlVIB_h3VusBJqsE4k-BXxEaHKJKTjNWBCI,826 +torch/include/ATen/ops/special_i1e_meta_dispatch.h,sha256=uVYSQsf-K4Wt4llywZfO1sOixWqszA_I83qqpVwwoqk,1148 +torch/include/ATen/ops/special_i1e_native.h,sha256=vNDtzED4QN7Y43gNq4OU66LQjsIcYWhw3zzL_M9n-Pw,865 +torch/include/ATen/ops/special_i1e_ops.h,sha256=qtyK-ZSeuvVxmILE1RFetSpnCLH_zTVkWOAcZufdPaU,1831 +torch/include/ATen/ops/special_laguerre_polynomial_l.h,sha256=d3qDQmFVD4NiwGpe2VHZu1f4GgeGNU1ebFW5V1-hHG4,3317 +torch/include/ATen/ops/special_laguerre_polynomial_l_compositeexplicitautograd_dispatch.h,sha256=zQa9y6C3lwWXXlrfc-vtIISa0p7HnfILyox9ITSYnvI,1638 +torch/include/ATen/ops/special_laguerre_polynomial_l_compositeexplicitautogradnonfunctional_dispatch.h,sha256=YRwNru4kV_zBgbxdiqJLTwQkdyjJD2drJR_PGivcneA,1086 +torch/include/ATen/ops/special_laguerre_polynomial_l_cpu_dispatch.h,sha256=TtzDW7eUPeLIfpbE2BDExH7h2HgfnQG2rFTlESs5VzY,1257 +torch/include/ATen/ops/special_laguerre_polynomial_l_cuda_dispatch.h,sha256=AsEF7pujBT2EyIg026177YUg5vsiIsfYpMz60tbjLcI,1259 +torch/include/ATen/ops/special_laguerre_polynomial_l_meta.h,sha256=cPV4gb9h11sEhaNqMgHvUJpzUmNtQMERLGfEVllpwo0,863 +torch/include/ATen/ops/special_laguerre_polynomial_l_meta_dispatch.h,sha256=hYAaJxNUztIQAvtQrC_r-3NUoQCpsMvVQKwoBaok-4g,1259 +torch/include/ATen/ops/special_laguerre_polynomial_l_native.h,sha256=9OgmPzBHY3dLkoXAzZsXTYThGs6hGBswHuZhswq-imE,1370 +torch/include/ATen/ops/special_laguerre_polynomial_l_ops.h,sha256=Whwoe1elsEIF11L8FHyCea3a316uWL_xfaDJs2s0eFA,4891 +torch/include/ATen/ops/special_legendre_polynomial_p.h,sha256=wzi2qKGHy3zT1Rvw54QCUc0IIY_ERim55eXySATJizs,3317 +torch/include/ATen/ops/special_legendre_polynomial_p_compositeexplicitautograd_dispatch.h,sha256=Vj0qNn2yK5a85WiguTBC9_DQsh9fNE0kRrYQwXaDQiM,1638 +torch/include/ATen/ops/special_legendre_polynomial_p_compositeexplicitautogradnonfunctional_dispatch.h,sha256=zQn1sTcWMqgwcA2B1EroYjdYXkmFkbuAnzQksEPyXJI,1086 +torch/include/ATen/ops/special_legendre_polynomial_p_cpu_dispatch.h,sha256=oW1fsBQmec4oQINts47Kd9-o6u73zvvl7Ri0nhkgHEw,1257 +torch/include/ATen/ops/special_legendre_polynomial_p_cuda_dispatch.h,sha256=GZxWhCAJDDYWDiKakhSHXda3tvasNIhEQ6DqIPPnACE,1259 +torch/include/ATen/ops/special_legendre_polynomial_p_meta.h,sha256=dcgTa9JH6Lq8W-FZtpAWNv5nuGixKPwhl5R5ekk3K60,863 +torch/include/ATen/ops/special_legendre_polynomial_p_meta_dispatch.h,sha256=Zc6J-UVkbZxBgzvCrlBJ06ZZWtaSSgsIdpSYZYTFmAI,1259 +torch/include/ATen/ops/special_legendre_polynomial_p_native.h,sha256=-L4lBwhaYdTC_XU-n8KdYoQUnCjRM-sbzbSZyZq3sfM,1370 +torch/include/ATen/ops/special_legendre_polynomial_p_ops.h,sha256=Z5LNX6Vc2y9nbAxepUAXxnmZf0EgSzVvUPwkhOjbz9A,4891 +torch/include/ATen/ops/special_log1p.h,sha256=LPDXi2sQG8TPR_yN9SqU03RNqlbMPXG6C-0xxnuj7yc,1351 +torch/include/ATen/ops/special_log1p_compositeimplicitautograd_dispatch.h,sha256=Q-LTYFipCB19V1MOGxmYDHPqS4o1ZYbAeS0NClW4LtU,1196 +torch/include/ATen/ops/special_log1p_native.h,sha256=N6wzYMzGfga4iN7JT9XMQpai5GqToK81wJeOC_MJYPo,822 +torch/include/ATen/ops/special_log1p_ops.h,sha256=UBu24OIQdUJssex3NHCv89cbVW1PibAnlXqhCyJ1szM,1843 +torch/include/ATen/ops/special_log_ndtr.h,sha256=XR1el6-ZDMs3EHkt3mRQT4VOB58hEBmhsTInGQ6pteQ,1381 +torch/include/ATen/ops/special_log_ndtr_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Cb6-4Q8srZvKfKO7dd5eMrprniAdjMNFIrXoxyWbMDY,1054 +torch/include/ATen/ops/special_log_ndtr_cpu_dispatch.h,sha256=0B29Mq593nEQSQO9cRDjSHDYLXnJDcdkKv8cTAjldL8,1161 +torch/include/ATen/ops/special_log_ndtr_cuda_dispatch.h,sha256=LyRmaZ-gHZfFQL5Ic8bGBXRWWX1gG1SqV9GdyrUWCPM,1163 +torch/include/ATen/ops/special_log_ndtr_meta.h,sha256=LCNGFzhV8GoLJfw0SF5q-BVTQDaMiiZ3SEe5n37jf84,831 +torch/include/ATen/ops/special_log_ndtr_meta_dispatch.h,sha256=ATZOolnKmlYQNhenxRpD79_MtkwK3dsK57hzwns27hU,1163 +torch/include/ATen/ops/special_log_ndtr_native.h,sha256=4aI5f1hpDS_CICKlpJPx1GEDQkLR4yxeTG9a7YtHZyY,880 +torch/include/ATen/ops/special_log_ndtr_ops.h,sha256=B7Za6IEfmGfoK1sZHJR1zjarb0uBNWMgxQQUb7qNxwI,1861 +torch/include/ATen/ops/special_log_softmax.h,sha256=vr-KtHqKWHfhnYdaaA4ebVvAGCEcufCRDkKKWGPk26w,1058 +torch/include/ATen/ops/special_log_softmax_compositeimplicitautograd_dispatch.h,sha256=5QPmA_MAk8jPxLQJa9ukDxRf1mN_97u4cRmAwvt-Xzw,1098 +torch/include/ATen/ops/special_log_softmax_native.h,sha256=UtpvAU0SmzIPYd3EQDSIzJRU4n06yfXbsm7jSML04Fo,810 +torch/include/ATen/ops/special_log_softmax_ops.h,sha256=j0O-9aUTYCQL0bQlyGGBdWbukAU-rquC6s85QWkH2mM,1432 +torch/include/ATen/ops/special_logit.h,sha256=gpYJ0ahwOwnb7o1lIc_ouvD5lC7wf5WeqGTv3aSqXWw,1534 +torch/include/ATen/ops/special_logit_compositeimplicitautograd_dispatch.h,sha256=HY7VaQ-yErMjHLHtW9X5w1gExhkXqXuRQenepXLdb0w,1313 +torch/include/ATen/ops/special_logit_native.h,sha256=OpLB3EcTobPPvvF2LfEEOH7vshqr5gRS1Uf6iPmkIG0,895 +torch/include/ATen/ops/special_logit_ops.h,sha256=gwqQnm_wGQteN38TO1ud6f7XE7pr09hhCUhXzv5AvpY,2043 +torch/include/ATen/ops/special_logsumexp.h,sha256=wIufsM4U3zr00vKAt5UzNpKFxnE3-klgLz7LRzCK4vE,1646 +torch/include/ATen/ops/special_logsumexp_compositeimplicitautograd_dispatch.h,sha256=WOjfZnAfdgKygIcPw4Vjo-8cSwxOuT81YWzC1cAy0JY,1325 +torch/include/ATen/ops/special_logsumexp_native.h,sha256=K1TJKA-YX-3EiR0DMKqTxT-kXIuKwkjtFu2k2JjC0Qo,906 +torch/include/ATen/ops/special_logsumexp_ops.h,sha256=ZPuJ59IX93_RRn2x94J2QlBlCmgqbcgULlOKP5U6Xc8,2117 +torch/include/ATen/ops/special_modified_bessel_i0.h,sha256=knoeapUhorXt-clWZTWSxGQAQNa_XeFz_TvJp2l8xdA,1481 +torch/include/ATen/ops/special_modified_bessel_i0_compositeexplicitautogradnonfunctional_dispatch.h,sha256=zN5sbALb8wtJO5uH8_vhfoOazkeCZRH83ExIrlf35sE,1064 +torch/include/ATen/ops/special_modified_bessel_i0_cpu_dispatch.h,sha256=OFoN8Jn2hEmbQtHxIshi2_oWQCqhohJdStcyu6SSDDM,1191 +torch/include/ATen/ops/special_modified_bessel_i0_cuda_dispatch.h,sha256=bfAgVIY-Fi3AF2E6M9iHTO2uaJBoiaIjr_LIcZAOtOA,1193 +torch/include/ATen/ops/special_modified_bessel_i0_meta.h,sha256=CCzP7Zk68Ap_5MMWNrlVOJ66pQBzSDLLZKlHm2EOWsI,841 +torch/include/ATen/ops/special_modified_bessel_i0_meta_dispatch.h,sha256=BSPF5owQRqjZ0z7xV9mBZg3QjiZcBQzwmHmHFYnwTwY,1193 +torch/include/ATen/ops/special_modified_bessel_i0_native.h,sha256=Ln4J-88nEPZHjcZFRIxchk3L7v7DUqyUb8Y_AZKFI6c,910 +torch/include/ATen/ops/special_modified_bessel_i0_ops.h,sha256=Ywdb-YXrqtferIyt5TIanWNKEdyak4g0NdbgH_h43uI,1921 +torch/include/ATen/ops/special_modified_bessel_i1.h,sha256=LYNc8-LLpZMkKiHq9WyTD2RkWZLx6kdbzHe8SRa956M,1481 +torch/include/ATen/ops/special_modified_bessel_i1_compositeexplicitautogradnonfunctional_dispatch.h,sha256=edVq2hBXhza-n_CY65P6XurYwd4i5FqLTQmcnNB2PMw,1064 +torch/include/ATen/ops/special_modified_bessel_i1_cpu_dispatch.h,sha256=700lq2SYTuB9__dI2JBdNpNPMFqdBkddWEbt_kbr7dU,1191 +torch/include/ATen/ops/special_modified_bessel_i1_cuda_dispatch.h,sha256=1X2WFpfQUrHo2DuJ6ZEykJfIKwEXiFTdZnzRM1Pk5d0,1193 +torch/include/ATen/ops/special_modified_bessel_i1_meta.h,sha256=m-kw-FW7K2nJXHpR1f8z8nu1_4TzJM01IyCfNQOOcYA,841 +torch/include/ATen/ops/special_modified_bessel_i1_meta_dispatch.h,sha256=xv7lWaPMJMDHRHEHY-cDsNOvF24b_bhkncsvIg4ShJU,1193 +torch/include/ATen/ops/special_modified_bessel_i1_native.h,sha256=vtha295SK-CFPY2KV9P6rjaJUkQiDklqQLm5MopMCho,910 +torch/include/ATen/ops/special_modified_bessel_i1_ops.h,sha256=cFTDzpIYQD-svJB1P_7zVuq2pwUw6ZKfM8eKUEJrt20,1921 +torch/include/ATen/ops/special_modified_bessel_k0.h,sha256=w3DZNj4M2QXWytNNhdbhiGzvxLXS_HKWrftC-PBwJIU,1481 +torch/include/ATen/ops/special_modified_bessel_k0_compositeexplicitautogradnonfunctional_dispatch.h,sha256=-YR4C87jsSDyzHVfWcVVBkCMQHE-e83qc6Hfa9DpmLY,1064 +torch/include/ATen/ops/special_modified_bessel_k0_cpu_dispatch.h,sha256=jul6H6LZuQh0zRiIykd20XPRkID8f-yXiYJfS0U4Lq8,1191 +torch/include/ATen/ops/special_modified_bessel_k0_cuda_dispatch.h,sha256=4BhmrN79HBpfcaT4nhUuDx62R_l7KJ24bjXuEDAhVVE,1193 +torch/include/ATen/ops/special_modified_bessel_k0_meta.h,sha256=djU-vyM0PaGUQKqm0iauAQ24S666LwxvOxR2T5XHGkU,841 +torch/include/ATen/ops/special_modified_bessel_k0_meta_dispatch.h,sha256=4xmjPpiHA82rC8v1V9rR5SbZoXDLjSZXIUhVUmEIy0s,1193 +torch/include/ATen/ops/special_modified_bessel_k0_native.h,sha256=RweHONzDneJRDmzTYHCA776LRSmDGKe3KzGuLHt4WEg,910 +torch/include/ATen/ops/special_modified_bessel_k0_ops.h,sha256=9gEKY_KhiEh4qROOWzU4hU2QWxNlMQSXJQ7jMW6I4Mo,1921 +torch/include/ATen/ops/special_modified_bessel_k1.h,sha256=WHGLvxJNqlUsdFumKWQWmkSjHKM3V0KcoP90_2akjLc,1481 +torch/include/ATen/ops/special_modified_bessel_k1_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Ke0JlqZASX_3fQtiRYEDC2LIuHn8t4LC-dnZR9sJnOQ,1064 +torch/include/ATen/ops/special_modified_bessel_k1_cpu_dispatch.h,sha256=1xVFdxaV_AaRuCdL53ihEYl0Nx7aHZFbUk9-PrOwJ04,1191 +torch/include/ATen/ops/special_modified_bessel_k1_cuda_dispatch.h,sha256=lL2r5k57gBhN4jDG8m2_LCfZ9l04_4EM2hhOjn6G250,1193 +torch/include/ATen/ops/special_modified_bessel_k1_meta.h,sha256=rFNnu4hAJf5Rhr1bjzHfKMS2OOa-N0Ah1E0sVOuoOMM,841 +torch/include/ATen/ops/special_modified_bessel_k1_meta_dispatch.h,sha256=bb7IKKRR0Fy2IoDalCLWeDngB5fnW1fjCcmjP5K8D8E,1193 +torch/include/ATen/ops/special_modified_bessel_k1_native.h,sha256=lOP2I55dypMpYcOmoFiTULxK6ibd7TRLqCBheYUA8dY,910 +torch/include/ATen/ops/special_modified_bessel_k1_ops.h,sha256=2aPnRmz4tco0_cmOS9bm_79t6fmsUlwh1UoVYG32tPY,1921 +torch/include/ATen/ops/special_multigammaln.h,sha256=5-oT_sOI3A7RLJ8Zs0bcXaOVhwbVkkkVEG5UWao4EjI,1484 +torch/include/ATen/ops/special_multigammaln_compositeimplicitautograd_dispatch.h,sha256=uld9uDo49UCpDyagZG4mlxK7FVpzSufj5yMyNmO07Zc,1250 +torch/include/ATen/ops/special_multigammaln_native.h,sha256=4WzSysSSJoc7iDSYo2V39XBmAqNcz2ExUkgoO4AeZHQ,858 +torch/include/ATen/ops/special_multigammaln_ops.h,sha256=wN8q-OLlqTGc3gtRngZoryH7e7syZB0MluHdDFgqJPc,1961 +torch/include/ATen/ops/special_ndtr.h,sha256=TwOvt_h2VXF6RjM3lOKXFWnd_XK_ixdcou7CZ1WlQ7g,1341 +torch/include/ATen/ops/special_ndtr_compositeimplicitautograd_dispatch.h,sha256=4AzhWFvzzCDurhkl7qT1t-Lv6FEJNzFPTkmPXhtgKuo,1193 +torch/include/ATen/ops/special_ndtr_native.h,sha256=7n6ckBQlZNBQgQevT_2HAXsOmkeeIaLX24M6meFZMiU,820 +torch/include/ATen/ops/special_ndtr_ops.h,sha256=ECbZKHayF9gUav_65OuRSsFcetu4zAX6SNDQAwoKOxs,1837 +torch/include/ATen/ops/special_ndtri.h,sha256=7eEf4wXf32gnqanUZNI0GQLtY4giTgVTTZwJ8E6YK1g,1351 +torch/include/ATen/ops/special_ndtri_compositeexplicitautogradnonfunctional_dispatch.h,sha256=wS2tqh0_aNn5bENe4jR-_Gh_eVfYztArjuNhkciBwj0,1051 +torch/include/ATen/ops/special_ndtri_cpu_dispatch.h,sha256=5fwmcmLEIIHmnZYrcuYBAw8ia8hK466mIcbwdazM5SQ,1152 +torch/include/ATen/ops/special_ndtri_cuda_dispatch.h,sha256=Hs3kGUiEWB2dr6IkKCI5CtNhFg6wxhH21iWK8RTro7o,1154 +torch/include/ATen/ops/special_ndtri_meta.h,sha256=rbewT1A25RjrO7iwl49Q83K7xEtzQllwHJZ8_SLoXq0,828 +torch/include/ATen/ops/special_ndtri_meta_dispatch.h,sha256=rxpurJZ1RQig6W7UIfLwsCmPxlK4wODsI58zatIt34k,1154 +torch/include/ATen/ops/special_ndtri_native.h,sha256=q40c0r_GWdrWUY3HK2Af8o-H7n1lU0NP6p8EAlzvosU,871 +torch/include/ATen/ops/special_ndtri_ops.h,sha256=qqwHxNYaohm8p0TZsRGrOU0rojVd6n6SBCPgXkXWPs4,1843 +torch/include/ATen/ops/special_polygamma.h,sha256=1lPSFppARN3icGVkuNu0m4789zo0DbdX39iXb8OZl88,1454 +torch/include/ATen/ops/special_polygamma_compositeimplicitautograd_dispatch.h,sha256=PeFmbLr--44xjBVcOMqDn6JdeZQf8OJpceSkVXNFcM0,1241 +torch/include/ATen/ops/special_polygamma_native.h,sha256=XPvf-qqb7m2n5MrIrCKQ4BUGjT7EAjlmYHxv_yWPElg,852 +torch/include/ATen/ops/special_polygamma_ops.h,sha256=o2NQYtpB24-ax8lxWt79o4WYHNdqIM7-sOBn43DIqXg,1943 +torch/include/ATen/ops/special_psi.h,sha256=z5maXOO47rGifdAj0CUITXd4lrWtsB8nEtBZqttXR7s,1331 +torch/include/ATen/ops/special_psi_compositeimplicitautograd_dispatch.h,sha256=UL-f5ArY0GTW192qCaf6ODiz-suZpe41wGwBD4RzFsI,1190 +torch/include/ATen/ops/special_psi_native.h,sha256=H972O_EYK50jv1DCS8bg3oAKTpZsJU9HoLsXGBMtYn8,818 +torch/include/ATen/ops/special_psi_ops.h,sha256=hEbXrboP7tMtyv2fqu9L6oscumkw8oCMLyED_pynmZk,1831 +torch/include/ATen/ops/special_round.h,sha256=LSeWpi2zt6i1d5Y_bxyxwkYdKAiimyMuXWjNef2qpTc,1490 +torch/include/ATen/ops/special_round_compositeimplicitautograd_dispatch.h,sha256=P9DIwiDJLamjrbWHwlV49mWbgCLZ0ruXtBl7AGLqweg,1254 +torch/include/ATen/ops/special_round_native.h,sha256=rdEGjONdqI0_jYbctuOdJuSV2JR7QI6leBN9jfTcpCQ,860 +torch/include/ATen/ops/special_round_ops.h,sha256=aGe4qpLO-gPxwFgBSGc363mmApE7DEaFb9zER4fcpHc,1968 +torch/include/ATen/ops/special_scaled_modified_bessel_k0.h,sha256=4ZnaANlB9QM_8w_6tq6OBqTRHWVuiLFInEWKnr0mAQo,1524 +torch/include/ATen/ops/special_scaled_modified_bessel_k0_compositeexplicitautogradnonfunctional_dispatch.h,sha256=D9kguWQ80eEXykSlnGbt7Lw0dZBU3HiTGH8sK9ehme0,1068 +torch/include/ATen/ops/special_scaled_modified_bessel_k0_cpu_dispatch.h,sha256=JgAuDaa9SCTxTJr_SGPNh9seUzRXiMbd4-CVPTMeK_4,1203 +torch/include/ATen/ops/special_scaled_modified_bessel_k0_cuda_dispatch.h,sha256=Jf9eyp8Km9DDpE00ZZGV-iYJJG9pmBgwdxiUa4uGKvU,1205 +torch/include/ATen/ops/special_scaled_modified_bessel_k0_meta.h,sha256=04t1_VYCB4AvbwCdE-HENJ3OKyg0SLKXjFZg3Qz0nsI,845 +torch/include/ATen/ops/special_scaled_modified_bessel_k0_meta_dispatch.h,sha256=1yqdbYu7kAg9p8ZO5WZVBagOIBhWlEHkRMjUwiycdpA,1205 +torch/include/ATen/ops/special_scaled_modified_bessel_k0_native.h,sha256=QVyqiyEvsVKzWCARohDRKZEJq46-0RwmIjy5LV7tfQk,928 +torch/include/ATen/ops/special_scaled_modified_bessel_k0_ops.h,sha256=Yz1gVR8-_r3jS-nvs9ysquOcdOjF51jGYQ9XJiR9CxQ,1945 +torch/include/ATen/ops/special_scaled_modified_bessel_k1.h,sha256=0DppqITfQEDPVBH3iHhRt5J7YYh38AEcJ24VHlS_KpA,1524 +torch/include/ATen/ops/special_scaled_modified_bessel_k1_compositeexplicitautogradnonfunctional_dispatch.h,sha256=0Bwg7ihJNPfAg6xuXW3HRSP1llDm-UWM3o8TlYWcsDI,1068 +torch/include/ATen/ops/special_scaled_modified_bessel_k1_cpu_dispatch.h,sha256=wRWzuki8KAGIsNDkIe6tC0Mq2sirhrau8nU3donxxDo,1203 +torch/include/ATen/ops/special_scaled_modified_bessel_k1_cuda_dispatch.h,sha256=91sqdZEwpJeaZD5_cAJ_VFMUts-SYpvk43ilGsKPleg,1205 +torch/include/ATen/ops/special_scaled_modified_bessel_k1_meta.h,sha256=cGzZ3rl2BD13c6_i_-1GV4i_vahIMk6rvzrQciR04xs,845 +torch/include/ATen/ops/special_scaled_modified_bessel_k1_meta_dispatch.h,sha256=f670AxWiy5hJAnPnB-YvfHK3XTmy7WX1Ch1sl3l3ba8,1205 +torch/include/ATen/ops/special_scaled_modified_bessel_k1_native.h,sha256=O08EcyUqzMRqvk_2mJQQ-TcFXHQs_ACsJHGqrIJbSdY,928 +torch/include/ATen/ops/special_scaled_modified_bessel_k1_ops.h,sha256=X25S02XWxL6zQg56Z7TisEppmyFQMe7P_gqR5lDioB4,1945 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_t.h,sha256=ljKCNRxW188l5nUbaFQcNmNJi7rfQDZWWgEsugQlSsk,3569 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_t_compositeexplicitautograd_dispatch.h,sha256=hT-urNAhc23HedzYvTPvNMe6FV6nGewVVCknfnxCGR4,1692 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_t_compositeexplicitautogradnonfunctional_dispatch.h,sha256=FBcQ2_MAkTQ4GxVK-Jpm2dcGCRJLATmkJyiFBU6Z3aY,1095 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_t_cpu_dispatch.h,sha256=kYNe0g_QyqQ0ZRiASlgcBbiB7Ral9aDKiD0xBYoVgmU,1284 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_t_cuda_dispatch.h,sha256=7qMHGP8PAOV7kGB3JUOBlUFFE6Ayz0AfoHPvdtmfE1M,1286 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_t_meta.h,sha256=8vLjnKRVT97Ex69AeXEGLZUGfFBRCE7hoIvyORj38RY,872 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_t_meta_dispatch.h,sha256=2nNtiOioNw79gFBXNCzqnFDQvq6ZRyrJ7LfOR3b0s90,1286 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_t_native.h,sha256=qQKQbMOjZElascXKM15L1C8fAaejVB3IV30VnG19xIA,1433 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_t_ops.h,sha256=twC2i7DUv5FC1RrGtFkOggMKOxq7JAS6ZJax6JIJZhI,5053 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_u.h,sha256=ju6vHaM7VPDOTJk6W506jeIBuRf0iktOt06XQ5IY7kM,3569 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_u_compositeexplicitautograd_dispatch.h,sha256=erSZLuGNebN7EzySC8-VYxVbHQf93WJvH_d7T5iOu_c,1692 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_u_compositeexplicitautogradnonfunctional_dispatch.h,sha256=RoB8FFeH-J3XZNvTTsglRqsDADPDLIq5GDzGuM_gzGo,1095 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_u_cpu_dispatch.h,sha256=g8_Z6krJVJQNstTNJNijF3GQdKZARo1WTguxB_CDwng,1284 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_u_cuda_dispatch.h,sha256=yWso1KUiwqNI59jAQ8v1duvDoZ03ZWzPNRvhKT-hkfg,1286 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_u_meta.h,sha256=simmZuiwwJoYRmz3h1SIORzzETDoiO-fmm_n8OmPPAw,872 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_u_meta_dispatch.h,sha256=sXj6lMy5fBtEPfCgGcHRYMqTirdhtHTfmvFyzOSLPxs,1286 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_u_native.h,sha256=v8fP-RASCpne0Szoh-3yUDZw6SXjBljSXckN76QiOtQ,1433 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_u_ops.h,sha256=6GiH4BZR6aykUCXz6aA1A4mqwx11remD88j7uwvJTMk,5053 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_v.h,sha256=T1Uc9ohsRc6kHXLMUJa9SmfPo6uZYdrVojcZTwkexjY,3569 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_v_compositeexplicitautograd_dispatch.h,sha256=XcD7eBiPzVfk9r6EBHMlXC5faZ8EohXgzn4TfCIv1l4,1692 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_v_compositeexplicitautogradnonfunctional_dispatch.h,sha256=rJChMcBy3YoQWsh7gh8hvfmHHh1ahHmfhR6eHn-md9M,1095 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_v_cpu_dispatch.h,sha256=fu155XJiSAWEEeAWNRdo5roPIOQwdB-b63FJY_3Xo9Y,1284 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_v_cuda_dispatch.h,sha256=gj5Z3y1VlGxaVDd0PDpptN-DVKrSQKkm7hWtueactmE,1286 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_v_meta.h,sha256=rP2jkzYcfocz1SEoXn8Pt2lkM1-Th0q7k7Nzl6cJdaE,872 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_v_meta_dispatch.h,sha256=aQQX7nojyf0ZmsOJDUxf6dFum41iv4KXWqMS4gpH0zE,1286 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_v_native.h,sha256=O4S0TrTPXCMPsIxkDiE34l53YoHDtT2vwIbCdqhFpZM,1433 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_v_ops.h,sha256=zGGnAYj3zMz-vhTzespj_kHofk5fbE9NxSoWBaO38Do,5053 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_w.h,sha256=ff062I2wZpyX52CxO-pkYpTzw2Peie82O5KqpBVJS8c,3569 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_w_compositeexplicitautograd_dispatch.h,sha256=DApDCH3UpaMJsyQuwryYyy1NDa221YHOdUOgdMRxaJY,1692 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_w_compositeexplicitautogradnonfunctional_dispatch.h,sha256=7n2brL__o-6WS5_SensRHYt_TxGeConmwwjgKg4zIZE,1095 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_w_cpu_dispatch.h,sha256=7cc7E6xiCRB3cVxZ3hyX01fIX81BiVsoHax4Vxx4rmE,1284 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_w_cuda_dispatch.h,sha256=xuIeusRTrGasn34S6vTrGP4dbq9QYrEw-mX6GO9_XQc,1286 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_w_meta.h,sha256=Rxu3uSszXcJKusEPc3vxX4Dd9-AVi0x1LrZud9GGOws,872 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_w_meta_dispatch.h,sha256=y6AmcVGU1cxrOz0iUh7L7oNW8cBfUo4HEgEOW04j03M,1286 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_w_native.h,sha256=uGZMGpKB_brZE0CK2YUriaCRS_uYT8O-92nAmCYqSe0,1433 +torch/include/ATen/ops/special_shifted_chebyshev_polynomial_w_ops.h,sha256=RTMWrVt-MOKVVt-9QeUlLNNgYX_abQx7w0sW7WMjEFw,5053 +torch/include/ATen/ops/special_sinc.h,sha256=dOxn27pAuQVLCHW1SJRhk1HJ6hBWs_5WT_zZQP9gNFM,1341 +torch/include/ATen/ops/special_sinc_compositeimplicitautograd_dispatch.h,sha256=75w5kc3uR8KfGxppEBOqgT7K9PEyU9X6AMsHARzgKC4,1193 +torch/include/ATen/ops/special_sinc_native.h,sha256=3mvrXOhGYB6Ar3lV_sWbxPXt-hQM8WQdN00KiW4Xuss,820 +torch/include/ATen/ops/special_sinc_ops.h,sha256=cSC2g_mGiFif25xqeaM1yRs02TWoJTgoLEqWE1V4NLM,1837 +torch/include/ATen/ops/special_softmax.h,sha256=6Qy2obWyDMKmaSWh9N5syX_PN2kgh_-3Kf2nH9NMFM4,1039 +torch/include/ATen/ops/special_softmax_compositeimplicitautograd_dispatch.h,sha256=0mrweuUJko9utkNIE8OzM6L1sDE5KKeY2H4FBQJ7ejM,1094 +torch/include/ATen/ops/special_softmax_native.h,sha256=BxuGqwf1hSQTFLkJ7YBAMYt_gS7F6g0z_ahXCK4lCvc,806 +torch/include/ATen/ops/special_softmax_ops.h,sha256=V98P9CgFRDrFSnixv9hjSuKa7-ivJKvr3YhM94d909o,1417 +torch/include/ATen/ops/special_spherical_bessel_j0.h,sha256=scTpjGJChq4LQH4ubXAOFMBnT6iKzuRX_btYCikyiEE,1464 +torch/include/ATen/ops/special_spherical_bessel_j0_compositeexplicitautogradnonfunctional_dispatch.h,sha256=n1mUx9qXkEFPLwz-pY-ovV0LgJw5JiIwEnejoVhbfGk,1062 +torch/include/ATen/ops/special_spherical_bessel_j0_cpu_dispatch.h,sha256=NODpgKK53LjDW3cDcvjYwlqxPdVBJbBP12dJUlFe1o0,1185 +torch/include/ATen/ops/special_spherical_bessel_j0_cuda_dispatch.h,sha256=3lOLvfVHp9hEGbFYVebfSqXN2RFMBye-Uj3FJHW9Kbw,1187 +torch/include/ATen/ops/special_spherical_bessel_j0_meta.h,sha256=3EyGu4mbyQVBNQa-PkjrxqKyRcbvgSaKztpCwpZScW4,839 +torch/include/ATen/ops/special_spherical_bessel_j0_meta_dispatch.h,sha256=s1x2F0hDZ9NmSi5Kce4hqw4F3OeOew2Zpsyj21zEZ30,1187 +torch/include/ATen/ops/special_spherical_bessel_j0_native.h,sha256=az0P7BJ_srVRHHjfSK5xvbH_7JfHshU87Zlwxw3J6_w,910 +torch/include/ATen/ops/special_spherical_bessel_j0_ops.h,sha256=u4_SBV8IIPTBY2OuJL5pHsH_AueDbN0sHwkCh12Kvdo,1909 +torch/include/ATen/ops/special_xlog1py.h,sha256=QXHUqpho2S9qj5VClFkgKWaliN2_xHSRW3ouCfNfH84,3156 +torch/include/ATen/ops/special_xlog1py_compositeexplicitautograd_dispatch.h,sha256=9kXNHPGFW6QPtOyeqO2WO-SM-d2navaInKr6y-_90iU,1596 +torch/include/ATen/ops/special_xlog1py_compositeexplicitautogradnonfunctional_dispatch.h,sha256=fcgMuHBAkbu1AEWo4zhPnj1zilnRoRfn7T81OdwRZRg,1079 +torch/include/ATen/ops/special_xlog1py_cpu_dispatch.h,sha256=xKxT92Kg9oTC9mp6gEj2Ia5Rx-OYjA4lWtBOj_E9T4U,1236 +torch/include/ATen/ops/special_xlog1py_cuda_dispatch.h,sha256=J4ivdy1aINjOTHKjoY8GNFcJmV5UpwKe53Ujzktu5QM,1238 +torch/include/ATen/ops/special_xlog1py_meta.h,sha256=KSW_Fz5ntUbbWNZfRtJk24aukTiAX3DkFxFNWVCdbXM,856 +torch/include/ATen/ops/special_xlog1py_meta_dispatch.h,sha256=DLf72TaQKCe069MpA-RMkLLnk2JfXOzRWIoWwACxjTQ,1238 +torch/include/ATen/ops/special_xlog1py_native.h,sha256=7I3bFhzwzIXngHFpLSmgJKTLxLyG1PQWuYom3o_Zevo,1307 +torch/include/ATen/ops/special_xlog1py_ops.h,sha256=b6nFz4fQJXlEhK7VHnQGBlTE0_mP4dMekTbXDHba-rw,4807 +torch/include/ATen/ops/special_xlogy.h,sha256=_NkYG7wNcU94VglkRRZylm38keDjpPH_P1IIU96gEJc,3100 +torch/include/ATen/ops/special_xlogy_compositeimplicitautograd_dispatch.h,sha256=3jH_FojbOq6DtlE5lIpLea3dcUxRT2aoo01NkQoKX6U,1894 +torch/include/ATen/ops/special_xlogy_native.h,sha256=zDnl0dVk9R-hOZxbng4CLymi3nKvJ2lcsMZ5riWsWe8,1270 +torch/include/ATen/ops/special_xlogy_ops.h,sha256=70D6zPiUYT6YdDVVDXMDLHE2Jpdj-4J8LeOiG007q30,4771 +torch/include/ATen/ops/special_zeta.h,sha256=GAN2VCvs76HQN1A5Actk366tjvh8G2GzVzf5Kqr49EA,3072 +torch/include/ATen/ops/special_zeta_compositeexplicitautograd_dispatch.h,sha256=fcjmQTDPjOOUQ-I59FSzCI9GtY4o39LMoGTsnED9wvI,1578 +torch/include/ATen/ops/special_zeta_compositeexplicitautogradnonfunctional_dispatch.h,sha256=raEWaxWLaFFex2wJE1NwZU3oV-YFEtydxr-FV5TrTqU,1076 +torch/include/ATen/ops/special_zeta_cpu_dispatch.h,sha256=AcdCL3lAfGsTXZeoXTBfsbinHFQ2U8cwqGO-BVGwvsk,1227 +torch/include/ATen/ops/special_zeta_cuda_dispatch.h,sha256=GfP7--qjelRQzl3Dny9FcOygD0uhEAm8U32ogSdpWjs,1229 +torch/include/ATen/ops/special_zeta_meta.h,sha256=UTxC2DpPoIdoxxsSugIxJwxRBN3dviPN2tHhDD8V0OY,853 +torch/include/ATen/ops/special_zeta_meta_dispatch.h,sha256=LDzTFXcEXSpfAZrMQ7fDnnWuTU4xRRi8P-AueDculEI,1229 +torch/include/ATen/ops/special_zeta_native.h,sha256=mvlzamNCD1AsMquw0L4-UrnLl0IhEhV8jU9dAVptnO8,1286 +torch/include/ATen/ops/special_zeta_ops.h,sha256=ghtOSy01hilA7BoAeAfLy7NK26oxMm6sFmCXEvvCgSY,4753 +torch/include/ATen/ops/split.h,sha256=h5J5YN-6o8LcLUmncFHcDpfiuzyAngeyOIlIClI1g7w,2963 +torch/include/ATen/ops/split_compositeexplicitautograd_dispatch.h,sha256=MncTnMHOMD8wa3XnKCNSeSuiYF4lItTm5aSIgvjpE-E,1181 +torch/include/ATen/ops/split_compositeimplicitautograd_dispatch.h,sha256=xP5zeap10kz2sSHFLfj70bI_aKbhqtGfrtamMcZDYxo,1197 +torch/include/ATen/ops/split_copy.h,sha256=T1d_ziTAqDnfBvHukgeWH8NIBcIgJlItMr0GHwJ0e_M,4201 +torch/include/ATen/ops/split_copy_compositeexplicitautograd_dispatch.h,sha256=gLkjnJtvIgSJajFHwzRzL64lSxKNnx16hLdgdq6XSIA,1428 +torch/include/ATen/ops/split_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=LEb8v_K8qSzv7oDTPcjWpMxFkiffvea0pTH-_4Xa9oE,1217 +torch/include/ATen/ops/split_copy_native.h,sha256=JgOOj-cNRBT41m5tqLnV_BC-8JOnUH0z_RRTKMAd7KQ,918 +torch/include/ATen/ops/split_copy_ops.h,sha256=y0BIomWBnL_ZLMz5F8lzCFiLdGwvflPF-vM87EY_s1I,2141 +torch/include/ATen/ops/split_native.h,sha256=M-8204CbYMMty0O5Xl9Aq0gUXtiFBNtmEZvX4qdP1UE,901 +torch/include/ATen/ops/split_ops.h,sha256=S7hFWxOs5imD6jB2m2X5Kgw9h71BGsmmJO8arRX6Ezg,2136 +torch/include/ATen/ops/split_with_sizes.h,sha256=1rDs3gjWNK924zsgpO5RpQUcb0cbwjy7Y40Q_wZbw9k,1995 +torch/include/ATen/ops/split_with_sizes_compositeexplicitautograd_dispatch.h,sha256=_Q3dRajwCooY93QH0UAGeqO9ceut9_-QzK2KtZ8AtQU,1221 +torch/include/ATen/ops/split_with_sizes_copy.h,sha256=K_pUUDGP_7rZgK-DeYCW-w7wNxAA8uGgkDrfxFrXz_A,4710 +torch/include/ATen/ops/split_with_sizes_copy_compositeexplicitautograd_dispatch.h,sha256=Ad1oZ19zNZrfioXk1-v6_PeqLy_Mtf-nnpvIQBJQh8o,1508 +torch/include/ATen/ops/split_with_sizes_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=L9uJk97OK3OvRibglcpQ7i5yn3rdLQTsmJsbOfeiqyk,1257 +torch/include/ATen/ops/split_with_sizes_copy_cuda_dispatch.h,sha256=QZROOLbq2U5Ek4ceGkKlHlEfSMPfLhkl6qcy7p6zX-8,1466 +torch/include/ATen/ops/split_with_sizes_copy_native.h,sha256=M8ttUaXpkR2CtuTKAIn1VTmkPqk-odK5QDAnpVA7ao4,1078 +torch/include/ATen/ops/split_with_sizes_copy_ops.h,sha256=NJe6o-MdJX1_iqlSRKmvyhRFK6OE0H5Lsg2PfgQBh9g,2224 +torch/include/ATen/ops/split_with_sizes_native.h,sha256=xqY1T_Z5nhj29HtYCj1bELvjmKP0M-O3QxyT4EfiGeU,929 +torch/include/ATen/ops/split_with_sizes_ops.h,sha256=LRoERWxGmxLOZonierXl-g2P-1wsULymSvfy3Ymi_TI,1454 +torch/include/ATen/ops/sqrt.h,sha256=XHOet260Go_8JBKbHvsAmSvVO8VYY0R-U7f-pQlfb7U,1397 +torch/include/ATen/ops/sqrt_compositeexplicitautogradnonfunctional_dispatch.h,sha256=uQGaFwBmDDOgAO2SYg66pCnD_GXHt4ggTYh5ywNphR0,1091 +torch/include/ATen/ops/sqrt_cpu_dispatch.h,sha256=Fjy3pPCURmAFmAkWN3cm__ae41FJk5S1Yc1ToCqTkio,1174 +torch/include/ATen/ops/sqrt_cuda_dispatch.h,sha256=ypIukgmtYEFqQPBZ3Rr7XYp9wR3UNdtUaMdok92W7vQ,1176 +torch/include/ATen/ops/sqrt_meta.h,sha256=903aTi2X5JhJN9H2DbHxHH3rq7iUoR8W9qWSmTrfcNo,819 +torch/include/ATen/ops/sqrt_meta_dispatch.h,sha256=qGLw8iJGQ7_9a2Rxw37al70Kh0fSFlINCVYQGMTKtiY,1176 +torch/include/ATen/ops/sqrt_native.h,sha256=_fnb5p5W8TeN3EHSMDeL3BvUlbvYaApZSbbPxaxbcbY,1317 +torch/include/ATen/ops/sqrt_ops.h,sha256=kpPjUDtHcGFVCngSvVx1TJ3LkIf4tJkopYpcCyQ-aPI,2282 +torch/include/ATen/ops/square.h,sha256=e4KvE34EgrDnOnTd6m9EfNbsN9EKtBEMV_-Z0AwFwNM,1423 +torch/include/ATen/ops/square_compositeimplicitautograd_dispatch.h,sha256=xo0-A41iPUchBZ6E1Jk3qQuzVypJs2pQmMZHup0_Xzs,1226 +torch/include/ATen/ops/square_native.h,sha256=lKsznyzKFd9EbQjzR8Ge2RkYTPK7YqttZ1Psp9uPq5I,859 +torch/include/ATen/ops/square_ops.h,sha256=dJQh2m70S1BraIARQ4IcsDQHUh1tcJehact_DyEoWEA,2300 +torch/include/ATen/ops/squeeze.h,sha256=qt4qXB4VC3uhBZmDo_1N5-B0TIgveowM4BoTFUJioS8,1271 +torch/include/ATen/ops/squeeze_compositeexplicitautograd_dispatch.h,sha256=ZSb1yOyzqe5O_D35hGbhCsDNYuUUqn0DXRMSAkiI2C4,1353 +torch/include/ATen/ops/squeeze_copy.h,sha256=IKc8Z-e94OyS-YqJ-q4u0MakENZ2Kb58c3Jr2hv4_ZY,2745 +torch/include/ATen/ops/squeeze_copy_compositeexplicitautograd_dispatch.h,sha256=7nDV0C-X_qZkEhNEWYl2sAjoIxqrSGnbmpdRWm6omeY,1539 +torch/include/ATen/ops/squeeze_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=ZsKfXMl5q6az4lo7xuMbL8J8XTZhNehfHjyM3AiTjNA,1204 +torch/include/ATen/ops/squeeze_copy_native.h,sha256=ICFWFY5LWrqAgt4taqvLKW91IxCekEhhFVucCwDlb2o,1194 +torch/include/ATen/ops/squeeze_copy_ops.h,sha256=0hEkbhzOho930mXLaR3ahNFgiSE4bbcyZWpomRDeSd8,4369 +torch/include/ATen/ops/squeeze_native.h,sha256=w73ml7RmcwFFGjadbzSsUN9l1L9tj7t9T-TneSe-PwM,1522 +torch/include/ATen/ops/squeeze_ops.h,sha256=ZTW3LQbHmPW7PeN2RjBeVquYVAEDjCqQHy2zF6lYfI4,4022 +torch/include/ATen/ops/sspaddmm.h,sha256=GCf00WUgI5klLqG9v4biTgi7xQgcRMmMjnh5XNtRom0,1861 +torch/include/ATen/ops/sspaddmm_compositeimplicitautograd_dispatch.h,sha256=Gqt36TJVgrsynX4Bu5jhgrpCoIcXDfD7y5BJw6UCAqA,1125 +torch/include/ATen/ops/sspaddmm_cpu_dispatch.h,sha256=V718TF-MF5Z2R6ABWt6L91UDLoyoQ26geGbvu6cmg8s,1287 +torch/include/ATen/ops/sspaddmm_cuda_dispatch.h,sha256=WSt5AH5f5s0zcN-pvdG-d5-F4NkGB0VOWgz-t3VCazU,1289 +torch/include/ATen/ops/sspaddmm_native.h,sha256=fX2tMqiLDgc0JecPQVJqqvhaPFN2h_mtWYSnpi1pGEc,1603 +torch/include/ATen/ops/sspaddmm_ops.h,sha256=qEu8LzxebW-oNipAhSdLtDtLJejE45P_eEkVejICDyU,2494 +torch/include/ATen/ops/stack.h,sha256=aMZdsxNT_JVDmSOHo8hmkcJGOnpOj091zDnkf_X4Cfs,1383 +torch/include/ATen/ops/stack_compositeexplicitautograd_dispatch.h,sha256=ZvwP0AOFPMgNQaNxuwQZXYpa6xPEq6HNJc8YD81w4_g,1212 +torch/include/ATen/ops/stack_meta_dispatch.h,sha256=BAvmDh1aAatMr-1ZuJy09SvR30rgBIY8o2CU7BMqiM8,989 +torch/include/ATen/ops/stack_native.h,sha256=5XMcdfIYwCtFs3i_UzU4aV8vm4LSFqWTerjxX8wejxE,904 +torch/include/ATen/ops/stack_ops.h,sha256=gn4mp0uSj5_0qhMZoPXDCVhvU_KapoUfdT9OLY25og8,1885 +torch/include/ATen/ops/std.h,sha256=Nmgymf08mkBkoQgnbCByM3KfDHNxVmRhZBAtZt9VPts,3026 +torch/include/ATen/ops/std_compositeimplicitautograd_dispatch.h,sha256=rC_k6gTNPMsVGx1judT0erwyBZ7u60vUAP0rw4ONzyU,1418 +torch/include/ATen/ops/std_cpu_dispatch.h,sha256=rOfugf4oSD9EcGLjyNQJ8RVW-HKh8WyyBQAKbr4EL8M,1467 +torch/include/ATen/ops/std_cuda_dispatch.h,sha256=yrOm16B3Kzeg_zSI60BHl37n-dDsWcpnuo6JuyR_6fE,1469 +torch/include/ATen/ops/std_mean.h,sha256=NcvnQaiNk3InOExecjrh4NjWdDE2FVi43gg2iQbV5yc,2735 +torch/include/ATen/ops/std_mean_compositeexplicitautograd_dispatch.h,sha256=MGcesqjaQ_c87syWBMhvYTE26nxIV-8fOEQKS8iuN44,1437 +torch/include/ATen/ops/std_mean_compositeimplicitautograd_dispatch.h,sha256=C0Q6NCphqrgA4iOgquOQuj5Yzk1vUQhzMZGYY2mrij4,1205 +torch/include/ATen/ops/std_mean_cpu_dispatch.h,sha256=_rbTV-XV9by8EEazPrj_t_0P-1sIIrtOVpJ7PUxQfEU,1128 +torch/include/ATen/ops/std_mean_cuda_dispatch.h,sha256=dGs3PuoL2P6U_B0oQiOs5KUOr7KjYk8c5HSOSSMxA2Y,1130 +torch/include/ATen/ops/std_mean_native.h,sha256=zM_D2XJJiZUMMy9orxyOOQuax1ainzY6W5sZtfKpeEo,1364 +torch/include/ATen/ops/std_mean_ops.h,sha256=UDn84qw0sZXH1JIU19AzB1kmqLi5T6GuUR2oTJXujVk,4214 +torch/include/ATen/ops/std_native.h,sha256=u63XRTK49xXv5P8_VWcFcOrejsfJ7ivv79u8UDemu-Y,1716 +torch/include/ATen/ops/std_ops.h,sha256=y-4-R6YFEXGZsU2be5gyxw_9SPUE66zypHjofVEMKjk,4519 +torch/include/ATen/ops/stft.h,sha256=pUAXR5Z9uP9mfVWWuM2zXVYu4kX66kjOWW0RIZ6fEKo,2326 +torch/include/ATen/ops/stft_compositeimplicitautograd_dispatch.h,sha256=fq-SB2m1ZGwvor63KYlNYaUpOmdt-ka16-0riYisvcs,1770 +torch/include/ATen/ops/stft_native.h,sha256=xPgk-E3809JgwkfSLVYg5CTZLxtae7BTyCnBpGTb4SY,1521 +torch/include/ATen/ops/stft_ops.h,sha256=AO0RvgR5c_Uj9E2qv6Bgb9RX09AM7oa4TkkyK8n-Sf0,3599 +torch/include/ATen/ops/storage_offset.h,sha256=LwVkr21lne9Tvhv4VpkhPBmJ4R3EqqsnHh2RucP0fbo,765 +torch/include/ATen/ops/storage_offset_compositeimplicitautograd_dispatch.h,sha256=6QBhFnrSRgeTyixmlNKMUmy3B7iJE8U4StaV9jQ2DqA,1023 +torch/include/ATen/ops/storage_offset_native.h,sha256=SeXnb_KzBlSpPXPOj_Mc-QKCYTwlNH9nyTOFpWRyOyw,735 +torch/include/ATen/ops/storage_offset_ops.h,sha256=rnrw3CplU-F-BquJnOSfY1Ohs5mhRlkllz7SBE-3q5w,1223 +torch/include/ATen/ops/stride.h,sha256=XAJkxcZwtqfgw6PQGbB403LSsuQnQBLKu-kQ_gewOSs,931 +torch/include/ATen/ops/stride_compositeimplicitautograd_dispatch.h,sha256=77lkVsDOuC2dQBzsGrqaxGBpxJ0WZ6Z9qsdNwtUQwgA,1028 +torch/include/ATen/ops/stride_native.h,sha256=mOPdmsIndhymg-dbqF-Tlnl61RHskQ6AcWTN8HJ7Xa8,740 +torch/include/ATen/ops/stride_ops.h,sha256=lQ57a7KYwPXdvqjP_-or0GRGdDkO7Fsfx8_BsyIMnCg,1254 +torch/include/ATen/ops/sub.h,sha256=MYqpBoJLT6QWdCXNB-soiiYtjcoMpuMjuYDht_fuFQ8,2392 +torch/include/ATen/ops/sub_compositeexplicitautograd_dispatch.h,sha256=f8GQBnN6cbZTLfhmkvqs78JiUfgN5TUnFiMelG9M25A,1428 +torch/include/ATen/ops/sub_compositeexplicitautogradnonfunctional_dispatch.h,sha256=tSjvcBgF5VHlZo6mbEdM-tKUum6YSLhG3wJg-fJ-Uag,1197 +torch/include/ATen/ops/sub_cpu_dispatch.h,sha256=wlywFWikE1X9FAEVaocFH4deo6I857FfFOoKSmk0AKc,1384 +torch/include/ATen/ops/sub_cuda_dispatch.h,sha256=3_CQhhSPJB8Xtxl32zVdmPLWNPcnaSbaO28m4BBxl58,1386 +torch/include/ATen/ops/sub_meta.h,sha256=QWUlFb4sqT61UPmwMyuIfVQbrfDC2OnLLZ_mWuBtv1g,877 +torch/include/ATen/ops/sub_meta_dispatch.h,sha256=gEke6lfMhGgzXCmUirOAVAYw3nuBOEsdASP0_aAVzzs,1386 +torch/include/ATen/ops/sub_native.h,sha256=g-aT-d_XtN9_3eygYLCyvCTF3ZFYk936RqNlbbE_Hrs,1837 +torch/include/ATen/ops/sub_ops.h,sha256=TZPEReaPghV7_6Zk-V3pMCRR_TR5sgXVhSH5KhA0_cs,4986 +torch/include/ATen/ops/subtract.h,sha256=Q45eKrr1fKZAxjez13K74pSMaQVzco5Y4PDww9jCPHw,1863 +torch/include/ATen/ops/subtract_compositeimplicitautograd_dispatch.h,sha256=Fln9p4a7kdCr8BIq2Jv_ejV2U_kemdIMgEv3yHvZmrI,1665 +torch/include/ATen/ops/subtract_native.h,sha256=SXUK8e_f5VMfHFm0DwiTfUN0ViNiuIt2GsdAnIhN7OE,1242 +torch/include/ATen/ops/subtract_ops.h,sha256=MLfovAPIBCPyMlCUxXO7O7i-ehB05M7IBdOpezPRUuc,4285 +torch/include/ATen/ops/sum.h,sha256=U-sNNPx_tA1NLFF6O0UwQC3FEGkWFvhknYiBXiF2nN4,2573 +torch/include/ATen/ops/sum_compositeexplicitautograd_dispatch.h,sha256=Zqeei8aGYMkjMdGYlzIj2a_8LLXe3Y4TNiOpBvNGCbk,1313 +torch/include/ATen/ops/sum_compositeexplicitautogradnonfunctional_dispatch.h,sha256=6OMDNRMBC_1bdtDFzODgwkObyGRUC4m88xaMPRHjZXA,1144 +torch/include/ATen/ops/sum_cpu_dispatch.h,sha256=tnvEV4VVVjQvFS2Y8B7u17g2G8zSLbUhe3dFvYJ1quY,1410 +torch/include/ATen/ops/sum_cuda_dispatch.h,sha256=HTtoGmZhrv1YuW2EFhTViJYX3AFtIpLZoXjlI2yN9Mk,1412 +torch/include/ATen/ops/sum_meta.h,sha256=Wiq_jbANgPZv7XqhNrCZPfcAbW8p6ae3i2bxz-B0mY8,912 +torch/include/ATen/ops/sum_meta_dispatch.h,sha256=kuoLlkGprcuL23_1S7q32G6SwsdNC5YoK0tq8LQkiIw,1412 +torch/include/ATen/ops/sum_native.h,sha256=Z4cCvjvjY52bJu-0PguwxzEbH9uKzvc9-frk8-BNYms,1884 +torch/include/ATen/ops/sum_ops.h,sha256=_AyWrdQLopzMZfgsF79CwjYPuoIxOcO1Gh5VVn6eE38,3760 +torch/include/ATen/ops/sum_to_size.h,sha256=LodmqMNMI_iyxirxS661UHUDbgcwUgNd5ee4stDg9BQ,1261 +torch/include/ATen/ops/sum_to_size_compositeimplicitautograd_dispatch.h,sha256=jr0I3ZTISd2BSrRxpisHDYrSw-TfpyeNt-AqT8JyI7k,1137 +torch/include/ATen/ops/sum_to_size_native.h,sha256=fMQvE6pcoo60o4GG2mK-pVKHUAbpdIbj7FL1cEXy-6E,768 +torch/include/ATen/ops/sum_to_size_ops.h,sha256=MpgsrwhZGkGR0t82hvmLWx2OyShelBCxwmX0d7mKdFA,1314 +torch/include/ATen/ops/svd.h,sha256=ZmGkzEtE2hejqYdbyzFBwfXWGcfSVDiZ4RPDHkC9Z2U,1839 +torch/include/ATen/ops/svd_compositeimplicitautograd_dispatch.h,sha256=86lNN8QpkMUKK4ywF4lTbcilYohIoU3zjJY3PO1MDtw,1446 +torch/include/ATen/ops/svd_native.h,sha256=29sB2pVpERq3myRjUcxcQsQGdr9zjIBFq6CfPIHLJ5c,974 +torch/include/ATen/ops/svd_ops.h,sha256=ShDjnRQF7WjasPTQdUZ2kxmkV2E1tgJ-wXKkMv3qkow,2387 +torch/include/ATen/ops/swapaxes.h,sha256=29t8aYD9AadJpL94IIqTAbeLCtMiD0CpdM9Qz-CYreM,971 +torch/include/ATen/ops/swapaxes_compositeimplicitautograd_dispatch.h,sha256=hB1PurvK8WFYBgDQGSAJYFq58jIPRo-stsWi4VcMQnY,1133 +torch/include/ATen/ops/swapaxes_native.h,sha256=F80B2j2UN0lh7Wz49aqG8XrQRjZ7O-7FTZ7IJq1k9ds,845 +torch/include/ATen/ops/swapaxes_ops.h,sha256=0WvJ4_MIi3tSxw7FqV6XHIiAy5aAZf3TTO82hXy0V20,1928 +torch/include/ATen/ops/swapdims.h,sha256=1kYVp-XKCe_sdPfkoW5mBgh-I3WuzRytJlK6ctolnlw,965 +torch/include/ATen/ops/swapdims_compositeimplicitautograd_dispatch.h,sha256=V997x7yfEy5GAgLmlEWpmCy2GZr8C3qxPgpa3pldPq0,1129 +torch/include/ATen/ops/swapdims_native.h,sha256=5oK3MGVh6NzNMr8OyLolHAhKWV-wAJbXrAzDjvpGfHc,841 +torch/include/ATen/ops/swapdims_ops.h,sha256=nOzW_mchJnSlWG0zziJb0xqgGqHTBj0Tzi6qJVFUw4s,1916 +torch/include/ATen/ops/sym_constrain_range.h,sha256=920VqtO_BcyYZBTg9lFKZDlBe-RvK5PDMhL0Ba6bieo,1066 +torch/include/ATen/ops/sym_constrain_range_compositeexplicitautograd_dispatch.h,sha256=TvCSeIOQyBnbOIBTssN9TaRzOQU-It_r0SfUM3-Wt3o,1115 +torch/include/ATen/ops/sym_constrain_range_for_size.h,sha256=22zDubFHrdSL9v8EH0CXfhpLhYrxmx3GCDZmbhG0STY,1102 +torch/include/ATen/ops/sym_constrain_range_for_size_compositeexplicitautograd_dispatch.h,sha256=hcZ-2ee1dcMBOJYP6p4nAmysKvGxbL_1ympEzo0SEE4,1124 +torch/include/ATen/ops/sym_constrain_range_for_size_native.h,sha256=V9Pu25AdeESmbhN5X_Sk61QlmEsPHveq86Trl6UX-8o,836 +torch/include/ATen/ops/sym_constrain_range_for_size_ops.h,sha256=6Vp1eZJOedqk7QXKg1-UH1QB59M-HHSQyA6NOX6zCJ8,1460 +torch/include/ATen/ops/sym_constrain_range_native.h,sha256=nhPlVm12i5YGm5Tn8y__6TqwvMGDfgl3snli34V7SCw,827 +torch/include/ATen/ops/sym_constrain_range_ops.h,sha256=xx-2cHXUgNvFb1UX_xACI572JLqDO3hWMazv9wpsePU,1433 +torch/include/ATen/ops/sym_is_contiguous.h,sha256=545hxC-VtPox5g4DivnSCriq5LqfQwK1i6NuoVL4Urg,1072 +torch/include/ATen/ops/sym_is_contiguous_compositeimplicitautograd_dispatch.h,sha256=EtqpN5fJ44t_34qhmGV-C0Q1JeA_DBIeazqCKsRW_OQ,1093 +torch/include/ATen/ops/sym_is_contiguous_native.h,sha256=3RShIYGXpoNhpAQl1Zoe28DfJQ8zcHqpIaIwjQUDlsA,805 +torch/include/ATen/ops/sym_is_contiguous_ops.h,sha256=71V5VljVovxsHPIJ8TLXgT9fG_IZm2waAuajYfdQUkU,1379 +torch/include/ATen/ops/sym_numel.h,sha256=U7TIu_SZShOaHN_U0CHLIjLNPjab3dbBLluJhIZ-AMw,915 +torch/include/ATen/ops/sym_numel_compositeimplicitautograd_dispatch.h,sha256=WJtd4KNS4NlRaE_Mf0OKqoEiDwBsSk-_M1wdDvp6MDE,1022 +torch/include/ATen/ops/sym_numel_native.h,sha256=uWIG12AsDJhTVvdtD_dBf3312hpWVAE5WKSH7Fd0wCw,734 +torch/include/ATen/ops/sym_numel_ops.h,sha256=Amr4Dm9Vyd1aj_hA43G3oEJPB_S9v9X4KdpQHhnibq8,1223 +torch/include/ATen/ops/sym_size.h,sha256=YMBukl2X2EejU3pBn0vq8SBP_RZJf9xaHZxFj4BH2sE,946 +torch/include/ATen/ops/sym_size_compositeimplicitautograd_dispatch.h,sha256=vbLHrJfuxmDBvetS4XZ0PAJveyv5dKl_C5Qz-5elcVY,1034 +torch/include/ATen/ops/sym_size_native.h,sha256=edxQty447HlHRaNToij0mdamySiHpHOIRaxKEwPSorU,746 +torch/include/ATen/ops/sym_size_ops.h,sha256=EdhRVhPryJC_WzSDkzQ0Ey2FIuCmKst9EwFKDbnlDXY,1275 +torch/include/ATen/ops/sym_storage_offset.h,sha256=ErnY_L9r4RDI7JVm-vbNfh24IcPr9KRAFV3Q-DSXc9g,951 +torch/include/ATen/ops/sym_storage_offset_compositeimplicitautograd_dispatch.h,sha256=E6cKLs_DkINY2sQ7QOQEZLDsH3_g2zykHyIIR-GWTHk,1031 +torch/include/ATen/ops/sym_storage_offset_native.h,sha256=3cr2k0TMkIsXHRH0bUpGD5F6JTrCQjg0iEysW4j3MqQ,743 +torch/include/ATen/ops/sym_storage_offset_ops.h,sha256=rnQF8QUvu3D6iHbsD7UvCvLFQsU8ZlAtnVi_UHCEdGs,1250 +torch/include/ATen/ops/sym_stride.h,sha256=tuCUaUTJ3sIRmH1EHh5cOkp9mKlO_Y35JuVp4gQ38SU,954 +torch/include/ATen/ops/sym_stride_compositeimplicitautograd_dispatch.h,sha256=jYCNOtxkAX8QMBEWhaNhJ2L84392g_3-DDLuyv6v0Ik,1036 +torch/include/ATen/ops/sym_stride_native.h,sha256=oiBaRgEY-s-uEXhvmQCGeyjYTzAaXLuVwsn9jNHE7Y0,748 +torch/include/ATen/ops/sym_stride_ops.h,sha256=niaNctuWgckNaqbYcNKZepDU-dV_i00ZibxxBjPOjZY,1281 +torch/include/ATen/ops/t.h,sha256=u9g5X1-el2ibTTDSTEEWH8a5U7aoLdD9Cazdok_vtFc,877 +torch/include/ATen/ops/t_compositeexplicitautograd_dispatch.h,sha256=HGXpPcJ8yoJIbS8RXC669bcIkQDeKD80eT4irFyJQHI,1059 +torch/include/ATen/ops/t_copy.h,sha256=7JteRF2KvB6-IYXJv9cce4ThAbdZXuhV5VqDOWVlrA4,1281 +torch/include/ATen/ops/t_copy_compositeexplicitautograd_dispatch.h,sha256=m-nVK9W2tzdV9yjvZ7VIISNtTZpcDbFSL-nLz3uyRUA,1121 +torch/include/ATen/ops/t_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=SkPqxSVglOra5Q-HrMBxMRkx8HTe6le1rc_YRG2NAjk,1044 +torch/include/ATen/ops/t_copy_native.h,sha256=qgQDpbr__9ImbYmJTadCNgdN7_S2TtqRZHRdKkuXlD0,808 +torch/include/ATen/ops/t_copy_ops.h,sha256=iHF3QUMZ9_okqOLGirzFBEHOpXYbaDy473l5lkblOgc,1801 +torch/include/ATen/ops/t_native.h,sha256=Npm4nLUEvm-88NgmL1BaTVZ95i5SQDvukPAhQbtZlRY,771 +torch/include/ATen/ops/t_ops.h,sha256=XXWy-LxZUlJF70KheMCktUoIJrT9TqhHRph-9hEFvOM,1686 +torch/include/ATen/ops/take.h,sha256=h9GX0DT2urGGw2U86S0Mw556saj3tlVAkSsTtP4Won0,1402 +torch/include/ATen/ops/take_along_dim.h,sha256=XOHQnR2X8oeOETCx_bM6flt64BixVLjhzbX72xhiJaI,1700 +torch/include/ATen/ops/take_along_dim_compositeimplicitautograd_dispatch.h,sha256=Gfq5Pm4N_K6TazsL81p6LGq-MT14H_Ywbl4ewL_OV3M,1403 +torch/include/ATen/ops/take_along_dim_native.h,sha256=_uspp1VN-9qn0Ijv4x_Het0ndOdCONiPIA7BeEsEgGI,955 +torch/include/ATen/ops/take_along_dim_ops.h,sha256=0EaGtFKQaK9GVN6nJMkBd67BwfwHUi9RTTMbaWUgZgA,2235 +torch/include/ATen/ops/take_cpu_dispatch.h,sha256=7FWXQJj4mjC5DDzvCcyFWIrKRILuFTnJIzg5HCIDWYU,1203 +torch/include/ATen/ops/take_cuda_dispatch.h,sha256=W7pCDCHcS0Zeqwk0U0ZEtQO3S4TGrclVP-jpOjPiPvs,1205 +torch/include/ATen/ops/take_native.h,sha256=PtbTYdgmS0DmEMgiQDkfCIG9ZvEeZ6Tkmk4SIYBK7TE,856 +torch/include/ATen/ops/take_ops.h,sha256=eUuVYWUGMPVcDXv91rDuCGo1CbSL54xkQ93NR6hmtCw,1961 +torch/include/ATen/ops/tan.h,sha256=Qg8l1Z-sIoWsg7ZVx93-RgtyNRlZ_-V5kV7y3vOAdSo,1384 +torch/include/ATen/ops/tan_compositeexplicitautogradnonfunctional_dispatch.h,sha256=w4l5wEuQHx4oK9UYiCKkhhvljve0ZQJTukuJ8u4it1I,1089 +torch/include/ATen/ops/tan_cpu_dispatch.h,sha256=trzZfZn-aDVkyhVio_K0AKNJR8KEULZzks0eBhQY-gY,1170 +torch/include/ATen/ops/tan_cuda_dispatch.h,sha256=cV7wjgxx4DrJjIAH9MP7R6Z48DVU6zcYSrd3iEjIlrA,1172 +torch/include/ATen/ops/tan_meta.h,sha256=lhLoE-k21uIROQU6KgNiSfx6sEiPYmELsqqKSbP8Cis,818 +torch/include/ATen/ops/tan_meta_dispatch.h,sha256=yZY_4gYPtWeSF2ScksoS-7-R006Oy1e_IWdauAHMEO8,1172 +torch/include/ATen/ops/tan_native.h,sha256=Hs6jUWODlLEQGErWtVVAywRsxHXxT62xbiCoRzHhhCY,1243 +torch/include/ATen/ops/tan_ops.h,sha256=UqayTHgIMHv66ZTJ1Jgm9rqZ4BrAEU4yfc2EKXJnHdw,2273 +torch/include/ATen/ops/tanh.h,sha256=kYp_0mwFqISveSTqRtTKYBfRdqVaG5ocIldAaU6HQkg,1397 +torch/include/ATen/ops/tanh_backward.h,sha256=ezRTu-KK2nhpBGZ7GicCvGZZjUktKxWZ7ny3yKiaJak,1634 +torch/include/ATen/ops/tanh_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=gJVoxe-WXmZeREyVz-QfYCERYWAivd2YdiNb-PqvR5g,1085 +torch/include/ATen/ops/tanh_backward_cpu_dispatch.h,sha256=e-mpAqy1J4hfXuf2vOJKuvAbnRqNZP4qJu8c_hfvLbw,1268 +torch/include/ATen/ops/tanh_backward_cuda_dispatch.h,sha256=nufDEwmP5T_896-UkyO4dVCW679J0Q6BiHUDMae2G9w,1270 +torch/include/ATen/ops/tanh_backward_meta.h,sha256=TAXzJe2rbGsOtSbf5XTKFoSHTnVlglT80tKmvJIgVPE,862 +torch/include/ATen/ops/tanh_backward_meta_dispatch.h,sha256=yJf7-YwZXPFeDJe_Bz3PHMLL0HPAYDy3KhypxUY8WPI,1270 +torch/include/ATen/ops/tanh_backward_native.h,sha256=DUJO-_IQirCBHVwmL1M0SKTyR_vRPvWD7FeZrfkOwVo,912 +torch/include/ATen/ops/tanh_backward_ops.h,sha256=BS3ybMiHGVtkPfYFZ0CjO__3IRbW9MXs0zfb01XUMOM,2105 +torch/include/ATen/ops/tanh_compositeexplicitautogradnonfunctional_dispatch.h,sha256=aqKJ1EwOsNGD36l-9LXJXkUnPuRN3TC8eb38yjJHkbQ,1091 +torch/include/ATen/ops/tanh_cpu_dispatch.h,sha256=2SsHyPlvZlX4-mIwk-6USAQKZWgeSfLQ_xTFHK2N1L4,1174 +torch/include/ATen/ops/tanh_cuda_dispatch.h,sha256=hKlzb5VLTVOu6BQ7iQMr6dC5EV-WHFbrKkCJA--vSZ8,1176 +torch/include/ATen/ops/tanh_meta.h,sha256=hkBWNzudzO0DCxSe9tnMWdKkOaSGaHYNFpgUjmmEaIA,819 +torch/include/ATen/ops/tanh_meta_dispatch.h,sha256=ykbeNysj288-4T20qVbMWKqs7T-ttRkV3pFyGNytRjc,1176 +torch/include/ATen/ops/tanh_native.h,sha256=kueQZXBZYfIHkwT8DXIsVow6iDGYDhYaAyecTk0u8wU,1560 +torch/include/ATen/ops/tanh_ops.h,sha256=7UuSsFu0a67RTSALWkV_L1uK1zWWxzKYf1oYDc_ZEXc,2282 +torch/include/ATen/ops/tensor.h,sha256=bCjxWtrcaqT6yjX9fpCSrf8rjUqUPYy-GyFTcJATMZ8,1885 +torch/include/ATen/ops/tensor_split.h,sha256=efT_6_tZiIzuLhijUBrGBAIzGkeFy3AWC0_ji_iCVb0,3460 +torch/include/ATen/ops/tensor_split_compositeimplicitautograd_dispatch.h,sha256=z7Nj8nXQB2YdKOkxakeSAtLLLVJyjauhXgqj5bYLlUw,1569 +torch/include/ATen/ops/tensor_split_native.h,sha256=k28PvuZEpNl3WEazefvMr_fe4BZP0n0V2Of13lXfNcY,1075 +torch/include/ATen/ops/tensor_split_ops.h,sha256=sYJ_EBA-YWX-oQzGW_1F8XSU0HvG6KhXoeQUSTTmY7A,3026 +torch/include/ATen/ops/tensordot.h,sha256=QPBJ_4TojGG5yd0p4N-MHzRiLmmbVLCRdrneu5-SAzM,1791 +torch/include/ATen/ops/tensordot_compositeimplicitautograd_dispatch.h,sha256=tAuEPyNR5kz_zRUhD2tgienUrhF59yhVOsN-ukwJsEo,1427 +torch/include/ATen/ops/tensordot_native.h,sha256=VwWQpfG0Ed3MlG4d1tnbl4wECAlwZ4a2wY5VJyTJ6Q8,976 +torch/include/ATen/ops/tensordot_ops.h,sha256=kbv4o4q_OKRIKxIunsKAs6c1prBwj4bbuD8_n1o7wW0,2349 +torch/include/ATen/ops/thnn_conv2d.h,sha256=I6YSsJNiruV2dYqPhLaRmcb4RkYboe-rSoGAW1D7Sqg,6874 +torch/include/ATen/ops/thnn_conv2d_compositeimplicitautograd_dispatch.h,sha256=a2rbACf0HJVGCfxfmDeAKMr9IjcTBwDSH8KysBwxAt4,2435 +torch/include/ATen/ops/thnn_conv2d_native.h,sha256=daD5ULTl-Nz2ftBRfic8sMaBTh5n7IIajxjZ7KXK9uk,1119 +torch/include/ATen/ops/thnn_conv2d_ops.h,sha256=OkQbjfqI4nUo-3eyGqa6SV8I4iKv3H9rTtynvlWDgLE,2903 +torch/include/ATen/ops/threshold.h,sha256=sAc16VXqsKz9I28SSH19oEVP2L_YZ1midyk-hq9_7t0,1886 +torch/include/ATen/ops/threshold_backward.h,sha256=DNi6T1wdRP38VeX0DlU4YfVhNtsgATfyshtynOlkXHM,1843 +torch/include/ATen/ops/threshold_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=N8Pm9v2Yqvy4bA8Kq6Dg7lf0abc-HDCnjV7CmZZpy9I,1118 +torch/include/ATen/ops/threshold_backward_cpu_dispatch.h,sha256=u57AxRobSuYCdoRkgMFDtVu35g9w63sshTpTsDauDmI,1367 +torch/include/ATen/ops/threshold_backward_cuda_dispatch.h,sha256=j4KfV8-UwIgMVJqVLpmczXkBdCbiaYp7jCZpd0Jw0P0,1369 +torch/include/ATen/ops/threshold_backward_meta.h,sha256=6J4aA7eeiPrJ4f61hZp7axEzRP8gYCDLHgszmtfq6eA,895 +torch/include/ATen/ops/threshold_backward_meta_dispatch.h,sha256=EvDNFutPr3Q8m2vACRHh08kM3voarQ70AInP6CAxQmA,1369 +torch/include/ATen/ops/threshold_backward_native.h,sha256=xIfOi-zOnZfD2m3bUQ9RQGwLp65OlBM5Qt7CviWDkZI,1845 +torch/include/ATen/ops/threshold_backward_ops.h,sha256=nt6VB43rGB7Sqq5WdVXO1cGVHNay6mSzhITohPmQlao,2319 +torch/include/ATen/ops/threshold_compositeexplicitautogradnonfunctional_dispatch.h,sha256=u_TGVLSgM00QuS3dX7or-r6ioFl_EME2RYoHqzFxAJA,1213 +torch/include/ATen/ops/threshold_cpu_dispatch.h,sha256=MDKpKlo2S5MlKBI06NM9Z-8sClebfx4l-I3k751sCfM,1418 +torch/include/ATen/ops/threshold_cuda_dispatch.h,sha256=jH50Z8yjlC3826l4ey52VkGCHjbJUSgjLZlxEHIq32Q,1420 +torch/include/ATen/ops/threshold_meta.h,sha256=GlsZ8nQLei8OHJVb5wDJOT5OrcA-ZvlOXVAXZZN2TW8,880 +torch/include/ATen/ops/threshold_meta_dispatch.h,sha256=No_lE_Wzu9U-tuplhJJfHaDj2V24xOxmIJSHd6Rl3yU,1420 +torch/include/ATen/ops/threshold_native.h,sha256=0e-KNb9oVqqsI1jsuR0UItVc6hsmtZXO0N9qLUzjubY,1042 +torch/include/ATen/ops/threshold_ops.h,sha256=B9Gw65He73UbJoWuxNsjbsQo_TuMIT9bi-daG5xIWIM,2879 +torch/include/ATen/ops/tile.h,sha256=GL5i3V9uVv8n0DRi5wMZAdmybXdupU5TE3b6mRIioQw,1605 +torch/include/ATen/ops/tile_compositeimplicitautograd_dispatch.h,sha256=EMeOEP8hHt3rmptFkE2CpFe0BM0BfaWeR_FNCTEMHQM,1123 +torch/include/ATen/ops/tile_native.h,sha256=j6v1wvEv0nqUwUJmMgYiXmrtw3MH6pKoi8wR4pEiTk8,761 +torch/include/ATen/ops/tile_ops.h,sha256=tll5NeidjQL9VeIZnMjXkHxtHXJZwHLuptuMlMl0hzQ,1293 +torch/include/ATen/ops/to.h,sha256=uk72uhzpd6xE_3F6SvmPNmULI62M3k_ShTOKOA_rFnE,753 +torch/include/ATen/ops/to_compositeimplicitautograd_dispatch.h,sha256=yQSNN-RKv0JwetkpoiVkI0pPHKNSoArSQuUvFumnn2w,1981 +torch/include/ATen/ops/to_dense.h,sha256=fHv8fHMwxJGM2YVgQbJP6_23jOWA5SFyLuP913EAOuE,759 +torch/include/ATen/ops/to_dense_backward.h,sha256=UMW-FWpJkh0tMXDqgJ8QxmlzcZiuG3pY6sxlEqBt8O0,1069 +torch/include/ATen/ops/to_dense_backward_compositeimplicitautograd_dispatch.h,sha256=LkbNxyMzNtk_lZVf7z2W86kfCh7uNP9_6W7unfF9Z2g,1105 +torch/include/ATen/ops/to_dense_backward_native.h,sha256=sak20s57gMHKoxbh2Ne2ZV51bgu2BeH1rsQZNgFab4w,817 +torch/include/ATen/ops/to_dense_backward_ops.h,sha256=1oUiWlfJGgPdKtLlxjHXXNadQFHOi5GzMp0X6vlXJek,1447 +torch/include/ATen/ops/to_dense_compositeimplicitautograd_dispatch.h,sha256=O7IQ3pznnIwtMXSNfXDoAJ4YQX2SxDWPUSuuWYFbAsU,1124 +torch/include/ATen/ops/to_dense_native.h,sha256=tLsx6TKoPjONACfnWgE2-oYdXwBHOl0rcHpBA8qF1nM,836 +torch/include/ATen/ops/to_dense_ops.h,sha256=wc95r1ro0NS9XGXQpbPIkbHsqe6BcYSjhn5ys1grDXs,1472 +torch/include/ATen/ops/to_mkldnn.h,sha256=JHw_YSLFe7KqbePdPnoUz6ixm2fYvJ9wX3qcHQf8tsY,1322 +torch/include/ATen/ops/to_mkldnn_backward.h,sha256=9jg9UojKNEQ5F4j7T125Q0G8__l5IIFFtjjwFJRiZ0c,986 +torch/include/ATen/ops/to_mkldnn_backward_compositeimplicitautograd_dispatch.h,sha256=AeolIabuJhnL-KIJNzvifupaSFe3Ez7FnU3lWzxLE-0,1056 +torch/include/ATen/ops/to_mkldnn_backward_native.h,sha256=-W4ODuWCpk6TQaJhvjsaj_73frS1xSghmtO32KGseA0,768 +torch/include/ATen/ops/to_mkldnn_backward_ops.h,sha256=fSjcp3eQnzz7U26tuKqdyuFqvdx72duQXkLykDQlMdY,1333 +torch/include/ATen/ops/to_mkldnn_compositeexplicitautograd_dispatch.h,sha256=JXldsfZXgtVaBBfRBIqFCiLkLMeGkGrtEm1adVgiofE,1220 +torch/include/ATen/ops/to_mkldnn_cpu_dispatch.h,sha256=kSek53SiILCJynzCJaO26d7yMmjZUym7sty89vLjBoE,1031 +torch/include/ATen/ops/to_mkldnn_native.h,sha256=gjxvDLEhNhuNCE5oFBI5Y86Aa6iHVc6Qo8hcub_7LbQ,913 +torch/include/ATen/ops/to_mkldnn_ops.h,sha256=I6ekRQWBZuT4vTDnS4A7DVSxPpC8vtWmIUEy7p1nbD4,2089 +torch/include/ATen/ops/to_native.h,sha256=varHgkKEtnW0GNu7oenaL3VJoWqEGhrdh269h0OyccQ,1546 +torch/include/ATen/ops/to_ops.h,sha256=iCZ0RF6M7hDvQ_DgtLHG0_z7hixbb1Gq67ObZGpxVdE,4706 +torch/include/ATen/ops/to_padded_tensor.h,sha256=fkYjvDqjUpX1dUugGLwT-HD2ulP_1KY3IgBPyXu54yc,4601 +torch/include/ATen/ops/to_padded_tensor_compositeexplicitautograd_dispatch.h,sha256=Uus528eR89tjNORMGNb7utCX81nWIqmQ-oedY5zPdYg,1580 +torch/include/ATen/ops/to_padded_tensor_native.h,sha256=hjsUyz5UrWxh0cPj7RLcil6VP81OOkfdSm1hc3Fi0y0,1130 +torch/include/ATen/ops/to_padded_tensor_ops.h,sha256=vxjx21fIaaCt5FnKvpmLKUF82JL2aBe2bU4mek4DPGA,2243 +torch/include/ATen/ops/to_sparse.h,sha256=Go8Ymb444cQPIoI0KpK7M_XqOKUqct5DvkcVvoSPheg,760 +torch/include/ATen/ops/to_sparse_bsc.h,sha256=84KDYvlR5z0LycGO2TLL6apJ7Le15v0AbZ3Q-SXOIoc,764 +torch/include/ATen/ops/to_sparse_bsc_compositeimplicitautograd_dispatch.h,sha256=vUxLgeTpjKdKGkPaQ6RrKrqEpeQpWQolwf11y1pQKWk,1103 +torch/include/ATen/ops/to_sparse_bsc_native.h,sha256=KaGHyVPlJ2O4SSmuQmFJYj0seiak1nFNWImOdoSiurQ,815 +torch/include/ATen/ops/to_sparse_bsc_ops.h,sha256=_LAnxrmEMAkz5Eh_XbzA5ktyCSgGhBvnpC69mG-4PDQ,1440 +torch/include/ATen/ops/to_sparse_bsr.h,sha256=7Ku9qtqm-THc32tRHnmOrUwyLRNeBt1bv0aKtaxf64w,764 +torch/include/ATen/ops/to_sparse_bsr_compositeimplicitautograd_dispatch.h,sha256=bUBegCGsWMbrMyPXhq782MqQz3awVEhSx5Hm0Ajxy3g,1103 +torch/include/ATen/ops/to_sparse_bsr_native.h,sha256=yDGMOHQh9vZFkWxhZAnm4rRAFWrHfTkWND5yFZfOTBM,815 +torch/include/ATen/ops/to_sparse_bsr_ops.h,sha256=JMsERtHsi5h17jZUlS14g0Qi6w45uQ3uCXmoWE3RxZA,1440 +torch/include/ATen/ops/to_sparse_compositeimplicitautograd_dispatch.h,sha256=T00rrQPvK4bqSQgAH-p9baMMbkD6gR-zri8UuBzJyzo,1250 +torch/include/ATen/ops/to_sparse_csc.h,sha256=0JHiT62bxrfu1td4bD9vq41GRkUFJ_sOs7pO46NWoyM,764 +torch/include/ATen/ops/to_sparse_csc_compositeimplicitautograd_dispatch.h,sha256=xIuO2y2kWSL_MtrRa8WCigMx34yd5G6zYZ5EcdhHycw,1076 +torch/include/ATen/ops/to_sparse_csc_native.h,sha256=llKNNxMTC2Vcf2Haurb7_HeEt7Dh42FGUNWNcARBvGY,788 +torch/include/ATen/ops/to_sparse_csc_ops.h,sha256=7WoXLai8dIuBkdMDUDh58Sdv3di80fO3NTYIXT43yVY,1351 +torch/include/ATen/ops/to_sparse_csr.h,sha256=L7QN-fW21xFE2qVQ4f8n5is1Qq_ti8h6a4TXiTCHxcs,764 +torch/include/ATen/ops/to_sparse_csr_compositeimplicitautograd_dispatch.h,sha256=UFV3BsJtY7yuZm-O4QExW5JEBBkxQA02TSZAMOQBBh8,1076 +torch/include/ATen/ops/to_sparse_csr_native.h,sha256=OKZtEXULBHoeJ2OcdzlvF5tKskiI3sbMRJr_Ipyj3QI,788 +torch/include/ATen/ops/to_sparse_csr_ops.h,sha256=n0LzU3IGgbGQi8wMdIiUFCRBt_MJFNmWauHl-3h_2Wo,1351 +torch/include/ATen/ops/to_sparse_native.h,sha256=rB39ccyiEwXsHa_DD_h1OaGs3QEiS30Gr_0KscDs9lc,962 +torch/include/ATen/ops/to_sparse_ops.h,sha256=V5l617qAoin5ADySrMoTGfEdm2USv9JcpDdEk68GyrY,2189 +torch/include/ATen/ops/topk.h,sha256=DJFAcnv7bdIkcMnRbxcY8VtX5d4AvvtBK5UwqibhSuA,5377 +torch/include/ATen/ops/topk_compositeexplicitautogradnonfunctional_dispatch.h,sha256=CYzlMPJGjTKBB9dpmfPiiG6DWUjQRNLBgqEYlqNenjA,1283 +torch/include/ATen/ops/topk_cpu_dispatch.h,sha256=lVrszZjuylFDrJEwodgBK5lVaABxUWmMkssMAACatLQ,1979 +torch/include/ATen/ops/topk_cuda_dispatch.h,sha256=tKCkxpc-E4HHeHfKCfBjNkSe8DYJjsR1nW4rsdVzB4U,1981 +torch/include/ATen/ops/topk_meta.h,sha256=22NNNTMoDh4WMXbJazzj8TlmY0QcN-6oA716xi5cVy4,870 +torch/include/ATen/ops/topk_meta_dispatch.h,sha256=CgUhpAtUtlHoGNsSNKp6CGbadxu-5w0nSGrlbUpnfVY,1981 +torch/include/ATen/ops/topk_native.h,sha256=foxXZmSLN-_8Nasgb2ohgS36lggMu9eJtiVo1p4xY6o,1309 +torch/include/ATen/ops/topk_ops.h,sha256=QWFXbKlTOSx8w_ph6MNtBMirXL87eaSga1hwtTXo5iE,2501 +torch/include/ATen/ops/trace.h,sha256=y7S-OMePDpM17m7LdhEYdeneyMnwi6nhtLQ9hlHMsCo,1271 +torch/include/ATen/ops/trace_backward.h,sha256=MbFkq3U4ipeFbMy2dvn2yzo5Ni10h_cUbSyjfmPdQUc,1725 +torch/include/ATen/ops/trace_backward_compositeimplicitautograd_dispatch.h,sha256=JLhJmSb-EBVNz9nC4jCfykCOqjGqWUWxHvE5zzWI88U,1145 +torch/include/ATen/ops/trace_backward_native.h,sha256=FNJMyBxi91KTBWKBjFOnuM4Px4Lu-Z-BCl1QzrWEgn4,772 +torch/include/ATen/ops/trace_backward_ops.h,sha256=rnEitzif5VYNzCjrsFkSzrv0_taYgeQruQu1jdczF6w,1326 +torch/include/ATen/ops/trace_compositeexplicitautograd_dispatch.h,sha256=v-i6rApLCtmAh022Kug2W4c0awkU27NP-LYg3V8kMWw,1119 +torch/include/ATen/ops/trace_cpu_dispatch.h,sha256=OkPFiwZ7GUBARcii2l94kaA46nw06bqKWGuUOtRy8rI,973 +torch/include/ATen/ops/trace_cuda_dispatch.h,sha256=NrIWj2X4lqIT9Mx7hGZ1QvydlPAS5bwiWtczfbKdJ_s,975 +torch/include/ATen/ops/trace_native.h,sha256=RT6_vEEwGTEwNGaAAVkeY2RWMjp88vrsbCh2cXzlCG4,868 +torch/include/ATen/ops/trace_ops.h,sha256=LDBJR55dDX_FTAECQAllgWuTPatlBv7YQ2iEoiAQTBY,1795 +torch/include/ATen/ops/transpose.h,sha256=v5stPJzEGxkWZunuo7mZUMXXhYD8Jkqw4kvI7epjKwA,977 +torch/include/ATen/ops/transpose_compositeexplicitautograd_dispatch.h,sha256=vDpiK0QPLh2y9JRskDzMwiXyYI1JetrPf39_7SZT2C8,1131 +torch/include/ATen/ops/transpose_copy.h,sha256=_67SbEIGUcegzQb2e52MNwyszBcgUyYEHh0D_d0zTWw,1565 +torch/include/ATen/ops/transpose_copy_compositeexplicitautograd_dispatch.h,sha256=u5QsMpPNQBQB-mUpVbgz2tbli4jEkw9hBvkpXiJ8ea8,1193 +torch/include/ATen/ops/transpose_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=dMqvVp1kjSzPme50lEK_JE6LHgmyCMIYfQUfERR0wss,1080 +torch/include/ATen/ops/transpose_copy_native.h,sha256=dLXUeM8t6rQSMXrYCkPYoLbRucA9If3xvcZdNAKKJ1E,888 +torch/include/ATen/ops/transpose_copy_ops.h,sha256=POhI_Bsu47uoB3iepiP3oivv9bsd9OSxgoakRz11dKg,2060 +torch/include/ATen/ops/transpose_native.h,sha256=asce2V8dVXy6EoBWhfC-KRcBKAAH8jvGRNAYP4HO7-8,935 +torch/include/ATen/ops/transpose_ops.h,sha256=CXWul2E_Q_2AOgTuVEF94fk_xuqMXSrVoV-WwhOD1FI,1933 +torch/include/ATen/ops/trapezoid.h,sha256=Df62Q_BticehSk2JPI_Y7jpdI7GVwFgmEebOA-a021I,1188 +torch/include/ATen/ops/trapezoid_compositeimplicitautograd_dispatch.h,sha256=RI2CHkvX_RtpVqVuz4EYJ-Eu38OnBscCuYp81lie4F4,1151 +torch/include/ATen/ops/trapezoid_native.h,sha256=_Six84Wz_6APyeC7ddBwylfx7IBJyRKuLlCrDntcUgw,863 +torch/include/ATen/ops/trapezoid_ops.h,sha256=MmahfIp4fXXA_FfGDyaTEo_SQJzMNTTVwh4TgDc9C54,1977 +torch/include/ATen/ops/trapz.h,sha256=WNqjA_Xx39vRHK9HhUEADozdHaOr4J_OEHNSKm8mXSg,1147 +torch/include/ATen/ops/trapz_compositeimplicitautograd_dispatch.h,sha256=9ETB9eJ1rYs3-mgf9NjoQPQlk4AfUS6mt13sGloXV4A,1131 +torch/include/ATen/ops/trapz_native.h,sha256=1Bvfk_A3x8mo47m1z_SFITgVgZ9AD1JF0EWtjP0RX7g,843 +torch/include/ATen/ops/trapz_ops.h,sha256=sqyX0dG-AFxA3FVUi8XMe4iYgCRv-6sVtppzyVVx11A,1916 +torch/include/ATen/ops/triangular_solve.h,sha256=zgJ7wCvEXOM8wEheYnJ06apNR1zLBh7lbZT--0UNQQQ,2205 +torch/include/ATen/ops/triangular_solve_compositeexplicitautogradnonfunctional_dispatch.h,sha256=wmtrooultk359PieXB44iyV173Iw7dLqpg39s7LEo8c,1166 +torch/include/ATen/ops/triangular_solve_cpu_dispatch.h,sha256=tyVcfo7LH1sv2FankB_agR-zwgOAsxJsi_dm1WTVm2s,1512 +torch/include/ATen/ops/triangular_solve_cuda_dispatch.h,sha256=sIFedQ68QDvyD8aNWEL41affhMjj-js90iotDcXj27Y,1514 +torch/include/ATen/ops/triangular_solve_meta.h,sha256=3TYkaBDAGCRSRd1IqVJtEItR4YKgAAp1oqOTlEhIptg,901 +torch/include/ATen/ops/triangular_solve_meta_dispatch.h,sha256=sIrwXPY6kzI3AJ92b71JQewFoVgg2wjH1ffsbT94xU0,1514 +torch/include/ATen/ops/triangular_solve_native.h,sha256=Y_3GozTlRh3MyK-DVgEUBJEZVRfZXiRC63xzHzcPWSY,1399 +torch/include/ATen/ops/triangular_solve_ops.h,sha256=APK_qWnjrnif-Z91iPbNBBs2bqMIZJZwrwrkOgdA3ks,2651 +torch/include/ATen/ops/tril.h,sha256=hWmTyK0ebCcfdty_GI816MPKp_Mrqh9LRLA9dM0NPXU,4013 +torch/include/ATen/ops/tril_compositeexplicitautogradnonfunctional_dispatch.h,sha256=7MonXhoFn1QmPWqWLxNSDUZsfVAlscyPLYT87l9QZ28,1294 +torch/include/ATen/ops/tril_cpu_dispatch.h,sha256=FhClPP2DOzfhqPToYaRUkTaFyayyY5yuDhmzy8IFUQ0,1628 +torch/include/ATen/ops/tril_cuda_dispatch.h,sha256=Pw0fYbCZciBsFDCgweji_lkpBa-CV6JQ8FHw9sZOj9Q,1630 +torch/include/ATen/ops/tril_indices.h,sha256=DNkN-Gx0RZYYcyW6Xnc1m2mZGHdCux2_tG9DKC32JW0,2214 +torch/include/ATen/ops/tril_indices_compositeexplicitautograd_dispatch.h,sha256=YS6sTcx5bKhzyeINbU15uSx6CmKYyC96KeZgZhTT-Tk,1169 +torch/include/ATen/ops/tril_indices_cpu_dispatch.h,sha256=N-VfIgdiwoIGmEbdGNmJ_9uCYowLpzw3dCXAXDQ3AD8,1258 +torch/include/ATen/ops/tril_indices_cuda_dispatch.h,sha256=yUk8qARfloPH57aczIlY3uCtAX7w76JJEa5eo3MGreY,1260 +torch/include/ATen/ops/tril_indices_native.h,sha256=4CWekTKKNvTQEAm6RI0kizHvZ5WKOmIrAe6_L0pZsHk,1258 +torch/include/ATen/ops/tril_indices_ops.h,sha256=jolBeqTHLaYt5_HzhRTMLV73zKLDIuDYTvtmRF35yZw,2453 +torch/include/ATen/ops/tril_meta.h,sha256=6SRAPZRNOUvDonbFzhzM84POk9SztKD2OCyKwREqx_A,837 +torch/include/ATen/ops/tril_meta_dispatch.h,sha256=ef-uTzwH0AuCdz80PtIgi_N0aHLypfl4_KmVeK4qNeE,1630 +torch/include/ATen/ops/tril_native.h,sha256=UtWCWB2fyB5PN5osPg3HRqZXCYayhy_uuAEHIEMNACo,1018 +torch/include/ATen/ops/tril_ops.h,sha256=LDJVlJQxta0IcDYuTS9hQHfxIqj0jo_nMvuf0pd5RaU,2510 +torch/include/ATen/ops/triplet_margin_loss.h,sha256=Hmr39QHwiLBtms6GCYvRVgjgFxDwQvY_6VGxjiNu-PI,1282 +torch/include/ATen/ops/triplet_margin_loss_compositeimplicitautograd_dispatch.h,sha256=ygsQoa7Hv103vD93JaTKTNXWFaoffYFJjGRTfPUI7zo,1196 +torch/include/ATen/ops/triplet_margin_loss_native.h,sha256=mdhEb5IFPQzZV_gWKkJ-QDP90LWdU2GW53zAnuVpvI0,908 +torch/include/ATen/ops/triplet_margin_loss_ops.h,sha256=Hvfe_kINZBMt05RhExIbXY0h-fimQnFv9NtYSUY14T8,1702 +torch/include/ATen/ops/triu.h,sha256=cW4-55KxSo6a4Phy2pikk1DQqGjy4b5mmkRO8-pEsB8,4013 +torch/include/ATen/ops/triu_compositeexplicitautogradnonfunctional_dispatch.h,sha256=IQv_0mjONwZaqwbzN3klw-xDAoE6Jx6aTo43aAeLCSc,1294 +torch/include/ATen/ops/triu_cpu_dispatch.h,sha256=TfDoEX__-JW8wSnZk7sMJx-eFb_9qbOaqvI67F5Pit0,1628 +torch/include/ATen/ops/triu_cuda_dispatch.h,sha256=klxQIokRO6heIi5uHKb0pQQoEdS8B72BxXFp0wzRlFg,1630 +torch/include/ATen/ops/triu_indices.h,sha256=-b8__dGDHUuy1yEdrP2FwjVjhsCTfqLdXO79C4TE3kw,2214 +torch/include/ATen/ops/triu_indices_compositeexplicitautograd_dispatch.h,sha256=p99twpuIiW-I4JYsLnOBEm7oTj0HE6mSapRo6Vr9kgw,1169 +torch/include/ATen/ops/triu_indices_cpu_dispatch.h,sha256=ThiFwj8tvlUiwO8Rpv9JnthVQBtzklleI4sLO61njn4,1258 +torch/include/ATen/ops/triu_indices_cuda_dispatch.h,sha256=4RbNsfGAwm-8eptEXusVFfyxGr9BI1CvlHbyetbuRWQ,1260 +torch/include/ATen/ops/triu_indices_native.h,sha256=vZgKik7LpKla_EYEaNIj91QS62d_SiiBZYD97-FvxAw,1258 +torch/include/ATen/ops/triu_indices_ops.h,sha256=UzN2jCOt_7mfG6MS6-sjQ-Q_R2DiCeXxkAqHpfcV4LI,2453 +torch/include/ATen/ops/triu_meta.h,sha256=R3oRI2ROWLR9TN8lKeeriPQSRvT1KIVvDCArvI5x-t0,837 +torch/include/ATen/ops/triu_meta_dispatch.h,sha256=c0DWcTujwcTJ1guoyN7tsYv1QUUVUAINdlrk3Vx0eJw,1630 +torch/include/ATen/ops/triu_native.h,sha256=NJzfQvtGCktCcMroztM33hdPBseg73Jtk5EtNbevXiI,1018 +torch/include/ATen/ops/triu_ops.h,sha256=xzUvf4tfQnyJ6ooE5yKZp4GSq6w-WrdT20t1IZDTdR4,2510 +torch/include/ATen/ops/true_divide.h,sha256=vVM0u8Jt-tnib5lGLU34nX8m7_KGsLqJgQTRQ-iKUQQ,1697 +torch/include/ATen/ops/true_divide_compositeimplicitautograd_dispatch.h,sha256=GTK2kBA9vEY5dlfzn6PiPi8AZy9NgyztGDf976AQXM8,1517 +torch/include/ATen/ops/true_divide_native.h,sha256=HjUGdggLMAiR72SvFqQK62VkWjd-sW30C5nR6av81EA,1119 +torch/include/ATen/ops/true_divide_ops.h,sha256=izXjsaT_Z7c4PutaawTzj61mGAMkyAOhk9TcrelF0e4,3884 +torch/include/ATen/ops/trunc.h,sha256=bThHrJg42Lc4jBItMj1ALdy3fba__G0GWaekARXavO4,1410 +torch/include/ATen/ops/trunc_compositeexplicitautogradnonfunctional_dispatch.h,sha256=ezkCR1YK0N0ehZyEr3AJ0yepOssUvxq6o7mfdK-8DrY,1093 +torch/include/ATen/ops/trunc_cpu_dispatch.h,sha256=XtMNanhlVlfQehDBd-iMP1o2JUas2Ui9Q4AStZe1MnA,1178 +torch/include/ATen/ops/trunc_cuda_dispatch.h,sha256=WnmnDuQoHLYgRRYqhIswwtHq_ypKfDO21q3QVjhAo7M,1180 +torch/include/ATen/ops/trunc_meta.h,sha256=ePhwtjbH5Y9x2TakgYNupYJSqdVtCDpTDOjczOSS3pY,820 +torch/include/ATen/ops/trunc_meta_dispatch.h,sha256=7fixKYBsxpqVDmrtvnBc3OiPP89HBlL6A8VdgCdC7kw,1180 +torch/include/ATen/ops/trunc_native.h,sha256=1mUL_UoI3Ez1Uro5gTZqKsb3boeZlafXdypYbO93HC8,1261 +torch/include/ATen/ops/trunc_ops.h,sha256=N-k-omO5sUAma2FQPIJuEdoz38AkXHgt66fpDtYue8I,2291 +torch/include/ATen/ops/type_as.h,sha256=AwdVDvYR91dnzV2NBKn3jmaFZw3E1GQFUYiHbz2oT3g,758 +torch/include/ATen/ops/type_as_compositeimplicitautograd_dispatch.h,sha256=dv8uyoCMjTCYB5RtdBBuj2oeTDCJBd6lqxvXMCbjW8Y,1045 +torch/include/ATen/ops/type_as_native.h,sha256=v2LPDmsYu4iQrg66e88k11xbntoyJ14YFfyJmwBTg7Y,757 +torch/include/ATen/ops/type_as_ops.h,sha256=OioOs7XMmXtex2G7ERpJo1-uxjvO62JKxlZoRU9Lll8,1300 +torch/include/ATen/ops/unbind.h,sha256=7xZEVM2vVgk9LcN-xCPsPM_1sw49BBU4rOryT5moAog,958 +torch/include/ATen/ops/unbind_compositeexplicitautograd_dispatch.h,sha256=1AUAnZzYjo8pXCoxPwyvOb_rhy_YBKk2Ppv5BvzxwcI,1048 +torch/include/ATen/ops/unbind_copy.h,sha256=odoE7jy3xo_wzzF511YrzFRLq2bTvx1UZVPTD2GhoqM,1439 +torch/include/ATen/ops/unbind_copy_compositeexplicitautograd_dispatch.h,sha256=SCiFQGUcY305ijwIzFe_HMbD5aOVW4x7At7HtuqUicA,1147 +torch/include/ATen/ops/unbind_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=WzJCqQShrinmnjWHlQb4ECZ5RZPu6cxcwKEKw7YVzkY,1079 +torch/include/ATen/ops/unbind_copy_native.h,sha256=o4DwnRwMMa-rrmh_KAYsBbEvKLvv0T6y0711c8OwAJ0,863 +torch/include/ATen/ops/unbind_copy_ops.h,sha256=zCODlW7yla9Ef1r2SyaeWyJZu0wCadw1TbgM2eQILSo,1969 +torch/include/ATen/ops/unbind_native.h,sha256=lCoMWyi8cLxu4T7EOtTt7p8fT70DrMrYxP9rkzclIZw,857 +torch/include/ATen/ops/unbind_ops.h,sha256=q3MU7HTRjuvlqm868_YH6jw0mLSjCZXW2wtVoj7q-Ls,1326 +torch/include/ATen/ops/unflatten.h,sha256=lz2Bkn-s7EfJ6Rbmajh2fz5KKdFjxcJ10yZtx9Kroo4,1796 +torch/include/ATen/ops/unflatten_compositeimplicitautograd_dispatch.h,sha256=WKQaYQ7JI8__Xz-U0Onz7NVCBUDk4Y1Dw8mzpRIyDMI,1161 +torch/include/ATen/ops/unflatten_dense_tensors.h,sha256=hPGFTdnsuy3OOLY9swgY3XBM0l_6I88z5qtUBnA-J_c,1027 +torch/include/ATen/ops/unflatten_dense_tensors_compositeimplicitautograd_dispatch.h,sha256=6n0V_CTfUS0ApPHEaKQH128kwn15EnCOFM6BTktjuzc,1074 +torch/include/ATen/ops/unflatten_dense_tensors_native.h,sha256=g1B_XmzUdt_8FAdIAPpGhj097yd7Gu4_UQpO82UwuRM,786 +torch/include/ATen/ops/unflatten_dense_tensors_ops.h,sha256=V0ocHe-XxJUUnNo-MYjP2hUTZE1uf-6WmdP-BdjFkcI,1391 +torch/include/ATen/ops/unflatten_native.h,sha256=lq2x5l8iwL5_9E68ILHwPH5SYRpC2qluXhVrFlpoSyI,780 +torch/include/ATen/ops/unflatten_ops.h,sha256=kmfTD2f5-MkMREaBCEMfu4aX-Mbet7zFaRlSvI4-1jM,1372 +torch/include/ATen/ops/unfold.h,sha256=s3T99PCBveeZExVaiyiTCPCZl0eEwzNqIKcvNXHGEd4,757 +torch/include/ATen/ops/unfold_backward.h,sha256=6LLF2qOMzqe_M8-sOPDTgT5EYiqzpyGxiDkYPwIu95k,5194 +torch/include/ATen/ops/unfold_backward_compositeexplicitautograd_dispatch.h,sha256=unmx5aSR3mko0ZWHt3ohc3o-kF4Rl9pjgHA_usng708,1628 +torch/include/ATen/ops/unfold_backward_cpu_dispatch.h,sha256=8hNRxDa0O11AYJ21tLQWSF8BexFIYwSHcjTxh6KcrzU,1203 +torch/include/ATen/ops/unfold_backward_cuda_dispatch.h,sha256=0QcM2lEahMqldeLaehuMMi57Xldi6VUoongCt-IT1Rk,1205 +torch/include/ATen/ops/unfold_backward_native.h,sha256=j8JFbKSh-UNSJeSH-ax9Yqsa_0sCadYmwky1lcCVdII,983 +torch/include/ATen/ops/unfold_backward_ops.h,sha256=2ZJwAeZKszpYe0ZFJiqJfqpzJ8nMzQt8e9NRM0OCj6A,2367 +torch/include/ATen/ops/unfold_copy.h,sha256=a2ab_KuD3jBa6cikEArKh_e6lOMsc4HngtRjpSF_Ou0,1646 +torch/include/ATen/ops/unfold_copy_compositeexplicitautograd_dispatch.h,sha256=Tu02oAKCNR3swxznEOAuLhY4Bi-gxH_RlQOEfUpYSrc,1225 +torch/include/ATen/ops/unfold_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=bHCFrbr20k_OQl1EBusSBL6EzSEYkL9RfZldhqyo7Gc,1096 +torch/include/ATen/ops/unfold_copy_native.h,sha256=cTUzPy2baCqqZOYXFFasTflV2E6vcQRjyztT6d_zxgw,912 +torch/include/ATen/ops/unfold_copy_ops.h,sha256=F0Lc3nSJkbVCsq9Cnd0hlUwaZTlIG-Ekr_72Cry20yY,2143 +torch/include/ATen/ops/unfold_cpu_dispatch.h,sha256=LQzs-kZ6aZ6HBSaj6ro4Okh7kwfXQ4_fN_Rk6PwPBbY,1021 +torch/include/ATen/ops/unfold_cuda_dispatch.h,sha256=cEc1Mn6UZnpLXwsnhT-cTiXkBzY5_LwL6YQfx86K5aU,1023 +torch/include/ATen/ops/unfold_meta_dispatch.h,sha256=ZENsp1SbM7bDsRO9Ta2Wn5Nitg5_np-wt8e7MgxNSMw,1023 +torch/include/ATen/ops/unfold_native.h,sha256=r4RtD3L7ZsPvzxbOSQZbFnMUQhJoEQfzbUs7MWBq3CQ,777 +torch/include/ATen/ops/unfold_ops.h,sha256=trzss8tbLxPJIbEhC6MvtwSk58KkFNFRJ_950-bGi7s,1373 +torch/include/ATen/ops/uniform.h,sha256=vudakx8sdSljf7Hee_qgm72Im0ZXRdl3-sx4RDa2bQg,1752 +torch/include/ATen/ops/uniform_compositeexplicitautograd_dispatch.h,sha256=Osq3PHPGpq97Xc0pML9YQ_knpVpFrdVnF0K15t-y2Q4,1414 +torch/include/ATen/ops/uniform_cpu_dispatch.h,sha256=Jv2-6RGQtimjkBYTviWVF0wHhuxsi-ShApxxcon9Ikk,1057 +torch/include/ATen/ops/uniform_cuda_dispatch.h,sha256=S0hqmznLSPxHUUY0cILYLPUAEKFpVSKsSXBXjbb8hWI,1059 +torch/include/ATen/ops/uniform_meta_dispatch.h,sha256=OHslAJlbhpCL0_r1rjvDT6k4FQ4CCKOaVgme73q3udA,1059 +torch/include/ATen/ops/uniform_native.h,sha256=OICD2Mu4nG6XIO1fj-I0qLgqRqKk83XhSXquaWVyzJ0,1240 +torch/include/ATen/ops/uniform_ops.h,sha256=BEzEvPH6roudbfOz0R1sRYWdYdsRPpo8TTjwA2eDWpI,3014 +torch/include/ATen/ops/unique_consecutive.h,sha256=EgYnf30mTLscYKb5YATv8HmR1tHyDnEGlfpjxxTshsE,2340 +torch/include/ATen/ops/unique_consecutive_compositeexplicitautograd_dispatch.h,sha256=ip2_E_cZrTnt8M7M4kvTSGsCzIBuCc_w88Vr6axSLzA,1472 +torch/include/ATen/ops/unique_consecutive_cpu_dispatch.h,sha256=LCX03ZhiWrdgeacTAfMpJoyfKbVzCNHJQ-jaRU1hrvg,1120 +torch/include/ATen/ops/unique_consecutive_cuda_dispatch.h,sha256=cC6Zkl1Fa5Q2Dm8FhQk9hRFeUHrTjM-LPUqQxaQ0CPU,1122 +torch/include/ATen/ops/unique_consecutive_native.h,sha256=xdwhZQKoVU6D38bQhqV5bPvxplPqkEzSRL9WGF1nj30,1325 +torch/include/ATen/ops/unique_consecutive_ops.h,sha256=DUo_TOLEHqv0YCigXDl3eE9gaQfpFffgV5OHgco8UHw,2782 +torch/include/ATen/ops/unique_dim.h,sha256=6s8jKULkqYrRBHKdgiB2vVPaGewbAq2o-LnHDCYS048,2288 +torch/include/ATen/ops/unique_dim_compositeexplicitautograd_dispatch.h,sha256=shtRtoF3VSv1wVzB5OkzvJc5S6I0CyvGsB6l60UuJ5I,1438 +torch/include/ATen/ops/unique_dim_consecutive.h,sha256=LYfEJUSF6-Kx4qPz9udEZt5kbtcxldi07VaqQO4DAUU,2281 +torch/include/ATen/ops/unique_dim_consecutive_compositeexplicitautograd_dispatch.h,sha256=MEAiIko-yvrWz_A3MlNFo_aKhr0APGTBysqQOX-9PIc,1431 +torch/include/ATen/ops/unique_dim_consecutive_cpu_dispatch.h,sha256=VkJHGj9AUjpULH0san-ZJcKw_m0KGs8JV4A9VYHt6bQ,1092 +torch/include/ATen/ops/unique_dim_consecutive_cuda_dispatch.h,sha256=9OdxQ2m3pjc1yyX8bI0kDTZUZrWkFYuqa9vyuzMii6U,1094 +torch/include/ATen/ops/unique_dim_consecutive_native.h,sha256=338Q6ZNjaZKtKvYqvxa2TPXxAy5zKjLAEijXg0wT7MU,1256 +torch/include/ATen/ops/unique_dim_consecutive_ops.h,sha256=0uBeRnSK6KCTZ7pf-gkmVNbAqdSYNu3qRf34o65CM1k,2692 +torch/include/ATen/ops/unique_dim_cpu_dispatch.h,sha256=EvZku3JTmuxuOy5amEBWHZnEv-QieaAtOYM-AuKvScA,1098 +torch/include/ATen/ops/unique_dim_cuda_dispatch.h,sha256=gtyuZJM_xaIwkERvmt2SaM39tUKUr76jIa5cF73mJbk,1100 +torch/include/ATen/ops/unique_dim_native.h,sha256=QRPo2F-tnfoUStfotsY-fQX1nO8cpPVejMtbKDnOdEc,1269 +torch/include/ATen/ops/unique_dim_ops.h,sha256=0AbjIDh-58vw9vJfDGKpEnotyhJO5Jepl1tHXKqeVTI,2720 +torch/include/ATen/ops/unsafe_chunk.h,sha256=ZwioqB5WtrkuEaABDz2_4y6naqIfbOQHnWUOp4bEEXY,999 +torch/include/ATen/ops/unsafe_chunk_compositeimplicitautograd_dispatch.h,sha256=nnNOSfnzJzhvD1NySrLD2APoNW_BqT87WicybE9OGIg,1070 +torch/include/ATen/ops/unsafe_chunk_native.h,sha256=58WRzG0jkJgeDpmTETv-J9_kVe9igwAp3d5WRyYnqCk,782 +torch/include/ATen/ops/unsafe_chunk_ops.h,sha256=NZgRwR_gfq1kcG71bgDIXGPEZaXwvokyWKcJA50bx-4,1375 +torch/include/ATen/ops/unsafe_split.h,sha256=udX3V42Z25IjjIMaZI9wsbvpNBJCg4L5FIvEyuFmeYc,4263 +torch/include/ATen/ops/unsafe_split_compositeexplicitautograd_dispatch.h,sha256=tXaEXZQXb7YC16OGSkQPaa3WhTEv71hEYzFurkzwL7w,1667 +torch/include/ATen/ops/unsafe_split_native.h,sha256=n8TRnYCFC8VcNJfGMgcKCqLlixX5Iq0oQh48KUnYZR8,915 +torch/include/ATen/ops/unsafe_split_ops.h,sha256=9VewGYHzwA-s5VNVryD-dkh7I0XBfH_ImwPU_Up4k4s,2153 +torch/include/ATen/ops/unsafe_split_with_sizes.h,sha256=n2TgDEfYBGpwBc4lfO1LbxPffPwJ_lJE1HsAdSgsuYs,4772 +torch/include/ATen/ops/unsafe_split_with_sizes_compositeexplicitautograd_dispatch.h,sha256=iGy0DN6Fz0l7gitayqAv43f85zBohiqo-3j4ZobyJ0U,1787 +torch/include/ATen/ops/unsafe_split_with_sizes_native.h,sha256=bP9WJI3IexJJkAnDkC2s1gp_eUEErmG-ZWdQiAkHFKc,948 +torch/include/ATen/ops/unsafe_split_with_sizes_ops.h,sha256=i4k-PjlXR3V4FfJO7NRofwsZPeHJY_aPGJ6fIxQc-gc,2236 +torch/include/ATen/ops/unsqueeze.h,sha256=uaqaxIIvhFyw46gXSJqKZsH8oWTrDeezZPKH__mV43k,936 +torch/include/ATen/ops/unsqueeze_compositeexplicitautograd_dispatch.h,sha256=y6D0SxsL3aQH-JA_1ATfZAdlFfwzBP0MwZN9v_9KU-o,1101 +torch/include/ATen/ops/unsqueeze_copy.h,sha256=ulF74zjjITbg2oNi4JH5U7MAA7TWmL7k8o0-GpZGbBw,1442 +torch/include/ATen/ops/unsqueeze_copy_compositeexplicitautograd_dispatch.h,sha256=RXBdoSDxk5-n4IXqOauFoR74IYVoY5ViYX-UWy1sjjQ,1163 +torch/include/ATen/ops/unsqueeze_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=bpxg01nCb_nYLIvqY-jKUeojiSpP6-aAj-SsRs3ZakQ,1065 +torch/include/ATen/ops/unsqueeze_copy_native.h,sha256=kcmh6t_O3JHpSSc7xlnv-luwW_heskS80hCt4LeguVc,850 +torch/include/ATen/ops/unsqueeze_copy_ops.h,sha256=fzNr2J_vu0N5HDHX1t-ciwWzjqGePxu4b44Q1D7PIo0,1937 +torch/include/ATen/ops/unsqueeze_native.h,sha256=jKux_Juj458LEfBG_P61YATAA06JEpEE72FcGPFpqkc,1047 +torch/include/ATen/ops/unsqueeze_ops.h,sha256=Jn3hsOhjPmCk9lqmg8scStR2-mIAFVunQiB18nsqjxc,1822 +torch/include/ATen/ops/upsample_bicubic2d.h,sha256=VFG7Sjs3cg54poGpR31zQKO57-cW4YXMRB2f7GUOi9Y,8192 +torch/include/ATen/ops/upsample_bicubic2d_backward.h,sha256=xohEMXqS3OFZ-BqCGBZS8qjXSkOuDpgTAmvDhoCdDCw,7938 +torch/include/ATen/ops/upsample_bicubic2d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=g0d07D8UAM7dis5G1vaj2eSQFbLukIsthdqS7OlLg9A,1519 +torch/include/ATen/ops/upsample_bicubic2d_backward_cpu_dispatch.h,sha256=9Yqn5LLtryH7gKMl3mXRydYQZKxuZIt2W6BiX6cgG70,2573 +torch/include/ATen/ops/upsample_bicubic2d_backward_cuda_dispatch.h,sha256=DYKpeD_DCL4vXznMLKD6CFhukQpIlTd3FbWTEsVbA68,2575 +torch/include/ATen/ops/upsample_bicubic2d_backward_meta.h,sha256=TwzAviaFoWdnSq8wRpPHi8kGcjJogfR8Ojki6MuxuR8,1006 +torch/include/ATen/ops/upsample_bicubic2d_backward_meta_dispatch.h,sha256=S0RysAHoVnXgESmOAdZmg6k548HPetSwXwzOl_hAuTM,2575 +torch/include/ATen/ops/upsample_bicubic2d_backward_native.h,sha256=ZodaA34-MTFpHkguqLRrbY6UosObu6brVHxx7Plw5tg,1447 +torch/include/ATen/ops/upsample_bicubic2d_backward_ops.h,sha256=YSda_a4UhAkCJNqe4KNEiFdPdc-0TYWAwFlQsnNxXJU,3037 +torch/include/ATen/ops/upsample_bicubic2d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=GJRI66OCMJ0ohJusXTX7lTKXYJK9wN1Ik0BkGVt7lJ4,1427 +torch/include/ATen/ops/upsample_bicubic2d_compositeimplicitautograd_dispatch.h,sha256=g_28nb7pK3wbDQFt-lpLbsksbGGyJMw7s4OmbEGewqw,1328 +torch/include/ATen/ops/upsample_bicubic2d_cpu_dispatch.h,sha256=jB8LfeRwokVGHN6A_e6pg7lBvU8dImc5Hv5EJIL4bP4,2269 +torch/include/ATen/ops/upsample_bicubic2d_cuda_dispatch.h,sha256=tUdJWbV0oKP06DyMQkE3eq7eZ1sI6ZdBhJrKZhw-qvU,2271 +torch/include/ATen/ops/upsample_bicubic2d_meta.h,sha256=Ob_5soB-Ow95Dl99VPXlgwM6avIL59jX_3sq2xKAY6U,956 +torch/include/ATen/ops/upsample_bicubic2d_meta_dispatch.h,sha256=ev5daEgNn9PCJ8etxyp3RaLullGOchlFS-xCy5RXESo,2271 +torch/include/ATen/ops/upsample_bicubic2d_native.h,sha256=a09SH9SdyDfsvgQnTRo60-xVq2QlhFSojRRPFmLX22w,1483 +torch/include/ATen/ops/upsample_bicubic2d_ops.h,sha256=s65OEj73Dz_xkDeg6iKQh9ptYKQ-Ddke1ltVVBzvPUM,3601 +torch/include/ATen/ops/upsample_bilinear2d.h,sha256=2SjYLWupIwtLpSWtct1TGNtx65JWveHxQLSSoTG-oA4,12147 +torch/include/ATen/ops/upsample_bilinear2d_backward.h,sha256=BbykxVTg5wsqn9REo43MSFuDkqG0BDCtpOOY5K2uNLM,7969 +torch/include/ATen/ops/upsample_bilinear2d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=u8y3eHcsdzIvQBxvWPvSSzt0hnCesnTHVPYgxNiQVU0,1521 +torch/include/ATen/ops/upsample_bilinear2d_backward_cpu_dispatch.h,sha256=xpWQkhlw7ixr_NWPqmk5Jg36HV-GWHDPpSJ3Z-pScGs,2579 +torch/include/ATen/ops/upsample_bilinear2d_backward_cuda_dispatch.h,sha256=vwxus4eIHVgo7cBz-bxyHzNOc-cgGTKX3hKUh3B-z0s,2581 +torch/include/ATen/ops/upsample_bilinear2d_backward_meta.h,sha256=y3g_dTcr6vGo26ehNPK3Viptne_AbZGIMGbdt_omaMk,1007 +torch/include/ATen/ops/upsample_bilinear2d_backward_meta_dispatch.h,sha256=P6oJdzjsbmsEOttA3_xDm-np4qqylMsA1dY5PCYD69w,2581 +torch/include/ATen/ops/upsample_bilinear2d_backward_native.h,sha256=pvItM3mfrh4ib5MqVl4Sl1l-dA1XbeKIj71TZoiYxTw,1452 +torch/include/ATen/ops/upsample_bilinear2d_backward_ops.h,sha256=ZSZmqVZdp2Fd41msrdIc_U8DQanU0rHyQcIymzc3Qzk,3043 +torch/include/ATen/ops/upsample_bilinear2d_compositeexplicitautograd_dispatch.h,sha256=AFonp7HYJdKstea9nOO5dp9aued3qjazrSJbOAhhjp0,1794 +torch/include/ATen/ops/upsample_bilinear2d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=Wb9fcvUUqRmxlwgQMtw-z_ON9VWuaQCcPKh_hm74q-Y,1429 +torch/include/ATen/ops/upsample_bilinear2d_compositeimplicitautograd_dispatch.h,sha256=IGmpa4Y6UZTWjvDszfzLQPliXi7zCAzSxkyFcR9Pqf8,1330 +torch/include/ATen/ops/upsample_bilinear2d_cpu_dispatch.h,sha256=kC3Q4xHH3X59GQfKMrVja2E-LnkKmx2PFyZn6Kd4r7Q,2275 +torch/include/ATen/ops/upsample_bilinear2d_cuda_dispatch.h,sha256=MdoExLBsocpwAYjWpXFecH2ZGprjNASpl1ccclWOEt8,2277 +torch/include/ATen/ops/upsample_bilinear2d_meta.h,sha256=jgHIEKvRT6etXOtk7OTvnnB3qUULzJMfgHKJ2bu2bjI,957 +torch/include/ATen/ops/upsample_bilinear2d_meta_dispatch.h,sha256=Py2wNqAxmOarNBPOUk4W818VNqMl8FzTrIQ4rN_M1PU,2277 +torch/include/ATen/ops/upsample_bilinear2d_native.h,sha256=hKGce_EcyoFRXyhw9gz0UDiBpFV2csYx11n6FzQHlMw,1933 +torch/include/ATen/ops/upsample_bilinear2d_ops.h,sha256=cREMKi70-JOeYBAFCjZ1gk5BBXL3f_jAMys_Rxy_4LA,4620 +torch/include/ATen/ops/upsample_linear1d.h,sha256=XMfYzr3D0mfrne1CaQwm2A1II08h7qsfRtbOYaklu88,7311 +torch/include/ATen/ops/upsample_linear1d_backward.h,sha256=kwy5bGep8i7ziVowLguD8P4GigD-Xcl3m6koFjv8E6Y,7067 +torch/include/ATen/ops/upsample_linear1d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=lBSE3kmc4BB7CaxFf3MOqmSUMYlHdnfHg698xqP6OwE,1415 +torch/include/ATen/ops/upsample_linear1d_backward_cpu_dispatch.h,sha256=2fB5y1fQw9ACU-SNsur0W-94i_YqVd5T_r-_Afd4Z8Q,2291 +torch/include/ATen/ops/upsample_linear1d_backward_cuda_dispatch.h,sha256=kere2JAlUoC7O7nq92I9qGSlJbtlOky-L6Y9UjbYaTU,2293 +torch/include/ATen/ops/upsample_linear1d_backward_meta.h,sha256=oRXml8iFunMdUKG369sS5DKGmxhtvGndfqhGwkyL3Hw,969 +torch/include/ATen/ops/upsample_linear1d_backward_meta_dispatch.h,sha256=NG-EBlKmzPyIL8wGGoA74jQ3Uypuu0FL3pPvZTGbmPc,2293 +torch/include/ATen/ops/upsample_linear1d_backward_native.h,sha256=vKSHMAWZ6kus7Co20yq9kunrtMQ8X4nW6elQp-D_MIk,1370 +torch/include/ATen/ops/upsample_linear1d_backward_ops.h,sha256=ATodPxp3U30nOJa2tu9j0uI47vxEh8WhnL7WulKxcak,2789 +torch/include/ATen/ops/upsample_linear1d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=ivwdDgfcGzY1iFx_Pp4G-OIh3g2pAtPLzMMJrsGUfNg,1323 +torch/include/ATen/ops/upsample_linear1d_compositeimplicitautograd_dispatch.h,sha256=yI8L8BBuy_JfEo6UVla9bGV8sfvkIqsaEHGWhB-61dY,1326 +torch/include/ATen/ops/upsample_linear1d_cpu_dispatch.h,sha256=pwsgd1HnHL8zQjq31vcQ5j1VDngHavSVIiOucldbXnY,1987 +torch/include/ATen/ops/upsample_linear1d_cuda_dispatch.h,sha256=dRAjjgUEanXTessojXyjjm4jCA2Cl5vp2OeCRa-Bp2I,1989 +torch/include/ATen/ops/upsample_linear1d_meta.h,sha256=1kWxbA_DjYmeRVPQwmiNoYZdvLVsFNpjMKeEa0KZhos,919 +torch/include/ATen/ops/upsample_linear1d_meta_dispatch.h,sha256=dLS_D0AmqPfBU44_nAd1LYMH9e5fUp6JZgsbiDF9D6U,1989 +torch/include/ATen/ops/upsample_linear1d_native.h,sha256=tT4KwDEmOa5zZpgud45S_pUeU6Ptk-gTcJawtNXR564,1405 +torch/include/ATen/ops/upsample_linear1d_ops.h,sha256=wOXKdObt3qKdzKRIakouFHBD4Z0e7P5l8NCXGyDOF6g,3350 +torch/include/ATen/ops/upsample_nearest1d.h,sha256=jBdVNdzc--py5Z2lGXWt-P-J9YIW7hIhVKDu_crTAhY,6632 +torch/include/ATen/ops/upsample_nearest1d_backward.h,sha256=OEyC1qpBn47Gp95vs7cOILx1IlbBK_tCIccXfBeScr0,6558 +torch/include/ATen/ops/upsample_nearest1d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=mdHB-STpHD5mkRhMpFCMRb6xJMwOPal8eI7d9ZriKK8,1377 +torch/include/ATen/ops/upsample_nearest1d_backward_cpu_dispatch.h,sha256=fcRZb_Fju5v35-UqY7TIc9SMYkw4ljXieLLN-hHrwiA,2177 +torch/include/ATen/ops/upsample_nearest1d_backward_cuda_dispatch.h,sha256=5NDlCuj0EwWJ8UCM-IUypq7-7chnqD5TOwju3_GAKF0,2179 +torch/include/ATen/ops/upsample_nearest1d_backward_meta.h,sha256=U2PLncfKNwHzR0oLm2UDjnCrQu7m6mv1q2AwANDuYXE,950 +torch/include/ATen/ops/upsample_nearest1d_backward_meta_dispatch.h,sha256=dMH9nFTQtTzQLwkesGH-KEsa4SrlmZ_UddUXpBYBP_c,2179 +torch/include/ATen/ops/upsample_nearest1d_backward_native.h,sha256=Aql3slzmg9XS5WdNR0euFGdEVxkNOWhTjKgWePBTW50,1335 +torch/include/ATen/ops/upsample_nearest1d_backward_ops.h,sha256=jsS-FUQ4BmB_fpbyJKLg_ClJ__JBhBEVmnfoBgSJXfM,2663 +torch/include/ATen/ops/upsample_nearest1d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=fGFQAHPhtd06nLi8_fZ5Bq58a47af-q9BEKFtpB1w8w,1285 +torch/include/ATen/ops/upsample_nearest1d_compositeimplicitautograd_dispatch.h,sha256=sumWZGvf75FfJIxi_npiYxXr-SWbK_sXSAUkY4WsVXE,1288 +torch/include/ATen/ops/upsample_nearest1d_cpu_dispatch.h,sha256=w0GpkzU97FINPKcdDjfRXCIpJstKN-pG7c0h_KGPFiM,1873 +torch/include/ATen/ops/upsample_nearest1d_cuda_dispatch.h,sha256=3YSirPZNlB9W4lXB-0iaoZE9ibiTzU-8fsP_lmmrhtI,1875 +torch/include/ATen/ops/upsample_nearest1d_meta.h,sha256=4BPjT8S8sENwPkHN-FYkpDrZEpUwHzJU1Y5eUPs_HNQ,900 +torch/include/ATen/ops/upsample_nearest1d_meta_dispatch.h,sha256=eZAeY7L0vrCO4Pg4TtbZCwrz8L_cWqX6VxqUQt-Tw08,1875 +torch/include/ATen/ops/upsample_nearest1d_native.h,sha256=7Usz2bcZf-ZO9wADjpkIEw5jQQOTk-y_AV2PLh7CwU0,1351 +torch/include/ATen/ops/upsample_nearest1d_ops.h,sha256=1mIGCtCOKUHJavVYyIc2Gx_Vlo-RnrPnc5EZtzX95H0,3161 +torch/include/ATen/ops/upsample_nearest2d.h,sha256=O_5ffpixJga9VIeobNTWWdgiKoF5thaefVCBkvPwxRM,11006 +torch/include/ATen/ops/upsample_nearest2d_backward.h,sha256=udedsCys3u4JReu1l9pqCImHk3HH-obKMEfm6aGzUk4,7398 +torch/include/ATen/ops/upsample_nearest2d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=1MzQcxYgVgdMzf3YAJpyY67spU0xOCyhG-tW3JEqoGE,1479 +torch/include/ATen/ops/upsample_nearest2d_backward_cpu_dispatch.h,sha256=GlbG2EorM5DXATkDUSRQVf0JKKFga_d_rKGojVaDKq8,2453 +torch/include/ATen/ops/upsample_nearest2d_backward_cuda_dispatch.h,sha256=HpAVwdP44f7xWDJOKPxjxVRu-sww8w4L3UnTb0bLUJ0,2455 +torch/include/ATen/ops/upsample_nearest2d_backward_meta.h,sha256=zyGFvrmYXIU2sd5LW9nlg6Pw0Rgo-Lw3seMpjUh9MZo,986 +torch/include/ATen/ops/upsample_nearest2d_backward_meta_dispatch.h,sha256=u_hHiKGlewIkNWzp5GPx9tmnD_O0QQKBzTwApN31ZYo,2455 +torch/include/ATen/ops/upsample_nearest2d_backward_native.h,sha256=pyprzLb6jzVT8DaBvFXab0I__HFVmRfRmzAQCycjNqI,1407 +torch/include/ATen/ops/upsample_nearest2d_backward_ops.h,sha256=yElwaXsJSwUpF-IcYvIljlE10-2_ng4ucZRoGrpVjvM,2905 +torch/include/ATen/ops/upsample_nearest2d_compositeexplicitautograd_dispatch.h,sha256=aFScUxyx5xG6b-zDAf5yIBkQ_ufI2GwOUos4yy616DI,1710 +torch/include/ATen/ops/upsample_nearest2d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=hziL-cvrzOJ6PF8iAzrkr66Eil6xVh2pcSzGuzgzgXk,1387 +torch/include/ATen/ops/upsample_nearest2d_compositeimplicitautograd_dispatch.h,sha256=r_Lh330YzJ2sz137JqJ3_OaELvP31_i59R4_SdGaMMU,1288 +torch/include/ATen/ops/upsample_nearest2d_cpu_dispatch.h,sha256=KLrwfa_aQDjnGJ9xBZueZRDXRrT9Q6Zow-rlvwygA5A,2149 +torch/include/ATen/ops/upsample_nearest2d_cuda_dispatch.h,sha256=uj1k2MBSila5Jc5rIXAvskiD5_K8Nk2e_KNt_QfCPTQ,2151 +torch/include/ATen/ops/upsample_nearest2d_meta.h,sha256=MjEloyM-rcqtkXZ-b1IijXxoEsk7WJnRgEbqWDtwkhM,936 +torch/include/ATen/ops/upsample_nearest2d_meta_dispatch.h,sha256=XKMsaV-fW3k6EykUytRxEDS3Z1X69tZQEuNNOxdM5o0,2151 +torch/include/ATen/ops/upsample_nearest2d_native.h,sha256=iFcnobq73QduuYOSFsj-hRwA_7MzLDN1hASdgH5MigA,1825 +torch/include/ATen/ops/upsample_nearest2d_ops.h,sha256=NX_114ByvM5Iu1Zx3GNfolzNBIiTz5LYd-cOKosTreY,4344 +torch/include/ATen/ops/upsample_nearest3d.h,sha256=QmD2cR5kUTXnmT7a3iTlQwnLOehttMBxX-MlTXwHuts,8252 +torch/include/ATen/ops/upsample_nearest3d_backward.h,sha256=txFD-Av9RCMbP0tgZmPkRLKkcWytQdv_Bqp8SYy_sJY,8178 +torch/include/ATen/ops/upsample_nearest3d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=lzmFuH3ecfnpV7CXnOOsFHoSWhJz0VrH7TuERSz7TCg,1577 +torch/include/ATen/ops/upsample_nearest3d_backward_cpu_dispatch.h,sha256=EqnWiEwPQUa5TuP1DPJwb9IUXxOYGbRYo8xj3K24Z3M,2717 +torch/include/ATen/ops/upsample_nearest3d_backward_cuda_dispatch.h,sha256=AJudIp8RCyXaePWGfY9FJcrmJnsxuZfGLwnh3BKVaC0,2719 +torch/include/ATen/ops/upsample_nearest3d_backward_meta.h,sha256=Rg7bRlZPktxhgg6IXQTXRu4Jp8VDfAtEFC9tQ-D8ikg,1020 +torch/include/ATen/ops/upsample_nearest3d_backward_meta_dispatch.h,sha256=jODEUU2iUNxrZHZj26sZ5FvXTSaBCvX9ESV0GKkbxc4,2719 +torch/include/ATen/ops/upsample_nearest3d_backward_native.h,sha256=ZSnOPvFhS3Y8AFObBHa6YD3_bLMFvK6H2hQKwU60akg,1475 +torch/include/ATen/ops/upsample_nearest3d_backward_ops.h,sha256=ITV4Vn-y5-0EarAIpEFD5N3YeD0InGtWNloqG6NVqeQ,3135 +torch/include/ATen/ops/upsample_nearest3d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=1qJ4luQVnGE6NRtOrz5_OvpdVBmdLwCbBZEulOiRF0k,1485 +torch/include/ATen/ops/upsample_nearest3d_compositeimplicitautograd_dispatch.h,sha256=us4SZKx54BNw8qn5HVT9715KEPu0mK2HSyg4Lzg7m7M,1288 +torch/include/ATen/ops/upsample_nearest3d_cpu_dispatch.h,sha256=6HPW0Dkw3gUPtuUUNGFRTJ94rrc8bZYLGEOplBu77tc,2413 +torch/include/ATen/ops/upsample_nearest3d_cuda_dispatch.h,sha256=Diy1FaKuyB3s9OFDay_lNb8YIgRdItKN7A85oNybFYw,2415 +torch/include/ATen/ops/upsample_nearest3d_meta.h,sha256=mESNA1u323tXos4lHI0Xb-QJe93khPp8rvKnyK1R99c,970 +torch/include/ATen/ops/upsample_nearest3d_meta_dispatch.h,sha256=hIHn0s-OaLYF43OpCBq2t-18wxgNaZjMo70pOJUlkfA,2415 +torch/include/ATen/ops/upsample_nearest3d_native.h,sha256=eiQEhIMx8axNFVzjzmmlhy6becX4VzrDGfwhsnsV1jw,1747 +torch/include/ATen/ops/upsample_nearest3d_ops.h,sha256=2EHfxmEjRNwLffTVHyq6LCkN3OgU_Ww7Xw_DqVQa81I,3633 +torch/include/ATen/ops/upsample_trilinear3d.h,sha256=3W9E6kvtVPHhfnVXQZ9lW3hDgvba3wyjdunYW2XjcZg,9054 +torch/include/ATen/ops/upsample_trilinear3d_backward.h,sha256=SqPf9FNBGRBAk-Zp7-fqkcv8DGnvfD3zfC9DNJQgoms,8780 +torch/include/ATen/ops/upsample_trilinear3d_backward_compositeexplicitautogradnonfunctional_dispatch.h,sha256=AP2kXqEo9wi_XHOFXxzuRfoCQA9pf6gaj88T8-5Z4-c,1621 +torch/include/ATen/ops/upsample_trilinear3d_backward_cpu_dispatch.h,sha256=s0iSQflxCP1hF5pjgR_fDo4LjupLwO2m13LMnPIdHP0,2849 +torch/include/ATen/ops/upsample_trilinear3d_backward_cuda_dispatch.h,sha256=GkTpTsqlRe6z51pXzsRpyztFTRE_71TVDVEN4Jz2WEE,2851 +torch/include/ATen/ops/upsample_trilinear3d_backward_meta.h,sha256=TKGxdkvWo-MGz0oYBtu9NzRbiM0xhJ7oEBApujHZIxI,1042 +torch/include/ATen/ops/upsample_trilinear3d_backward_meta_dispatch.h,sha256=kc9pT8jE0XxHPZELuAaNLLCnopoUV76uD_07KnrzTsA,2851 +torch/include/ATen/ops/upsample_trilinear3d_backward_native.h,sha256=DsDe4hdKCvN2mwABULGcANebhdbb8qK-f1_P3VxFSn0,1525 +torch/include/ATen/ops/upsample_trilinear3d_backward_ops.h,sha256=TRWVmmPmMxw39RsgVgnuiy3SOkrR082bo4Tpa0cMPJ0,3279 +torch/include/ATen/ops/upsample_trilinear3d_compositeexplicitautogradnonfunctional_dispatch.h,sha256=8hW2jm5ozyz78lqhe543EgtIDFRDUx1cOtgRQvKR5ls,1529 +torch/include/ATen/ops/upsample_trilinear3d_compositeimplicitautograd_dispatch.h,sha256=zreAYtRkrA6BjIBcrDqzedxVegRyLV0QMvM6DSeDG1M,1332 +torch/include/ATen/ops/upsample_trilinear3d_cpu_dispatch.h,sha256=zu6J7ocKvCaw8UsQY9T4iu2JwEIsjs3do0_aB1eRpSM,2545 +torch/include/ATen/ops/upsample_trilinear3d_cuda_dispatch.h,sha256=izNpTuxeT3tjQeY6TjjbdVEtxBk0kGyrZMLi8f6YuZM,2547 +torch/include/ATen/ops/upsample_trilinear3d_meta.h,sha256=V2VD_cRq_XmREMLDYHb0XIl9aTGMPLgoUiLqnd_heIE,992 +torch/include/ATen/ops/upsample_trilinear3d_meta_dispatch.h,sha256=30aaUlfLBQZMJ0D7beom4Y1JryH2vLnjikuuf1leQ2I,2547 +torch/include/ATen/ops/upsample_trilinear3d_native.h,sha256=In-rSLbiKtoo5vAbaD-9Wf9abS826W5354l6X6WG0AY,1563 +torch/include/ATen/ops/upsample_trilinear3d_ops.h,sha256=TuDc7fNnX1B6qxAUrKbMxMKqoJo2DTO7rgCYXOi4_9Q,3849 +torch/include/ATen/ops/value_selecting_reduction_backward.h,sha256=50iUpIEwpCTGhy81ykc_3hqc-t6sy6LQXxjyOFbacCI,2335 +torch/include/ATen/ops/value_selecting_reduction_backward_compositeimplicitautograd_dispatch.h,sha256=XZOBQxgOmxOTGbXly8T2DYQTmU5aWD2bc0dFmehGHso,1295 +torch/include/ATen/ops/value_selecting_reduction_backward_native.h,sha256=mVQH2Irl_BLOPJLOCx63QNTNSgI7HYlkPem9DN9sxf0,1025 +torch/include/ATen/ops/value_selecting_reduction_backward_ops.h,sha256=DL7brvLTfri9Paf5ZUfCIaFotzYcaZ2GVwSPFiwH120,1570 +torch/include/ATen/ops/values.h,sha256=aHiEbW13ImT9Kxo2-9wG7ERpwYIQFXHmBIfnIXuHg3g,757 +torch/include/ATen/ops/values_compositeexplicitautograd_dispatch.h,sha256=NfxBe-IKRKHgsn-e6BK3h_gcKPJOrwikkx6sZQkNeso,1018 +torch/include/ATen/ops/values_copy.h,sha256=8ScsN7bZKLseag-JbeMqiQ_ZXR3f1Uau-sQJUX-Z_dg,1331 +torch/include/ATen/ops/values_copy_compositeexplicitautograd_dispatch.h,sha256=-_kQv813ADijVdRCK4oDIlLCs-p4lap3kAxzIGtywLY,1131 +torch/include/ATen/ops/values_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=G7qH4UrcePdCuKcFyg-2Rp0jz2RvZlc9a6EIudFUVOA,1049 +torch/include/ATen/ops/values_copy_native.h,sha256=w9zwAvkNe16eAq1rdQQx1r4uEFC9SVh8OxvYp3CB_yw,818 +torch/include/ATen/ops/values_copy_ops.h,sha256=j_LgxXl5pGa1ZN1KJhogl4nufnr9LzGWL3MrYZf1pHA,1831 +torch/include/ATen/ops/values_native.h,sha256=XL8VFOu16JXk1Cr-GXJSLcVqALOOnizI8baLftH-pZw,925 +torch/include/ATen/ops/values_ops.h,sha256=K0NvQylY7UsEzgdCJWriEkc8UZbT1GPkilN1WLG8JzM,1217 +torch/include/ATen/ops/vander.h,sha256=nHXvQ6uH_FJh9g4JeV4nEBseWwJvT3cvX2e4PGFCYWA,999 +torch/include/ATen/ops/vander_compositeimplicitautograd_dispatch.h,sha256=uXoUUm1vx2D0GgP6KAldUXrrIrtjwrxyJh5SYdNzdLo,1081 +torch/include/ATen/ops/vander_native.h,sha256=btiDecUDd6ABR57r8V5PcmQ9RVdY-BHQnBxDbixdyQg,793 +torch/include/ATen/ops/vander_ops.h,sha256=c4C80epl2oE36jNNfI2WJxpztELmNLlVjvJuoN5MHxQ,1360 +torch/include/ATen/ops/var.h,sha256=Phx4S8KTcJEBp9KghYA0OfytqoLW5w4rBM22ijIu0XU,3026 +torch/include/ATen/ops/var_compositeimplicitautograd_dispatch.h,sha256=bIyJLiSQ9ICLeIeVtbOkjmQRicT6Jo9MwEMc3uP39lQ,1418 +torch/include/ATen/ops/var_cpu_dispatch.h,sha256=xbTiFw-dPZ7yOjUcMeeyw9_moM-xRlVVjJ873Nqd1xs,1467 +torch/include/ATen/ops/var_cuda_dispatch.h,sha256=uzyd8yLSrd0yP0b1MHAUSqV2sMES69nzvHLQ9IPW2Fw,1469 +torch/include/ATen/ops/var_mean.h,sha256=eJ7kEN_bT_U0Gtpz2DIF_jYc3amjE02CPm9Y2Hkq470,2735 +torch/include/ATen/ops/var_mean_compositeexplicitautograd_dispatch.h,sha256=nJCMUsGiTT1vPPZY1S4j2FbynhrMKzGwPb2r4f3Wth8,1437 +torch/include/ATen/ops/var_mean_compositeimplicitautograd_dispatch.h,sha256=8Oh1jN7fbECKdATwqzOdVqiOqNfnFNp5yklpj50Cl58,1205 +torch/include/ATen/ops/var_mean_cpu_dispatch.h,sha256=vYztBG8dlhkkV9Qm0sHdfKesjSBeUwLlAyXWcQ1sR3I,1128 +torch/include/ATen/ops/var_mean_cuda_dispatch.h,sha256=A_4opqHf8q6ilPM5jdkmV8hiQY_UDHbQAZ-t6JFFCmI,1130 +torch/include/ATen/ops/var_mean_native.h,sha256=UQsL4Qhxgn8C-pCYjxObSYH5EoAczs4sNQGCQOeNFqg,1364 +torch/include/ATen/ops/var_mean_ops.h,sha256=Z4JUwUZYbwbqoA38LXxnMY0fxdJW8cO39GeK8CpJRWU,4214 +torch/include/ATen/ops/var_native.h,sha256=rIPwWe4-nz_EgdkaUcWOEIKukDY6FjhqRAkesJbTspg,1344 +torch/include/ATen/ops/var_ops.h,sha256=eqlce01SdpIGvDMOcUGWr8r7KiM9V76JyHTuWr_M904,4519 +torch/include/ATen/ops/vdot.h,sha256=JicLDIkN5IfnoN87enhlobiJviGMJe6C5n1G2wd37UM,1402 +torch/include/ATen/ops/vdot_compositeexplicitautograd_dispatch.h,sha256=l6lc0wGToDZwZPEiSl20UKMYJGxcJi-gUt_xYnHsYjs,1169 +torch/include/ATen/ops/vdot_cpu_dispatch.h,sha256=YHIEGfbDjVlUP_jU-rTJnkolITQ-hkjz_CP1nZDn5JU,998 +torch/include/ATen/ops/vdot_cuda_dispatch.h,sha256=GaZyEFeqgMVWQocjbsYrjrwnfmsi8gdy18XQPDWpcGs,1000 +torch/include/ATen/ops/vdot_native.h,sha256=bxNBtL1qS4gZUG34QntoryniL9Zu2gDzoXQ1LrAhsPA,939 +torch/include/ATen/ops/vdot_ops.h,sha256=9T724eQRJCw7rQYrYOL8ODZ8qU7Ye8qZXgw2HdqdKr8,1961 +torch/include/ATen/ops/view.h,sha256=GGtONjhHkbAAZoG7YkCTLRMSjKO4PJHnyOu4SxGspo8,1226 +torch/include/ATen/ops/view_as.h,sha256=xDxUn24gipOhvcTNyePXEVhT0zQlx7dFF3IySwo45eM,758 +torch/include/ATen/ops/view_as_complex.h,sha256=u7picSMflYrIWKCWQ814OjXBYBFW55tjDY6mHcGzNAk,933 +torch/include/ATen/ops/view_as_complex_copy.h,sha256=1NDBuYRizSL7R0wpMrZehqqnMhwRSID6-I8wdTXQyTs,1421 +torch/include/ATen/ops/view_as_complex_copy_compositeexplicitautograd_dispatch.h,sha256=7YwDxhmZ4enLPGl5UONKstWHBRVHXAv2UxJ5FFcVang,1149 +torch/include/ATen/ops/view_as_complex_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=nIIJh5cxokGirJpguEn88TDnecBG1HxI9RLdSjleJC4,1058 +torch/include/ATen/ops/view_as_complex_copy_native.h,sha256=t_0Bq63ZfO63adSp1mNQ6makFBr2UGGZe4ZKJ8yjG7g,836 +torch/include/ATen/ops/view_as_complex_copy_ops.h,sha256=0rLVSPL32E60Qcjpu-38TfnY_-Jgh7VdxSMxA3Yrt2g,1885 +torch/include/ATen/ops/view_as_complex_cpu_dispatch.h,sha256=3jMO8MKkA30YDaXsRtIsJ7bLvD2hnABjOeCQUUKWpog,983 +torch/include/ATen/ops/view_as_complex_cuda_dispatch.h,sha256=yAopiXBJRt86Ot8cCjrxSTkXRphkp9rQDoe4qQ-i3CU,985 +torch/include/ATen/ops/view_as_complex_meta_dispatch.h,sha256=bnfEFb_v0CGfAxp7lS-4B454LowAle6x6XMdZDk61cI,985 +torch/include/ATen/ops/view_as_complex_native.h,sha256=m_crbI2Lcc2yoM8S4QWDHmZeUyq3clI7S4986T1N61I,809 +torch/include/ATen/ops/view_as_complex_ops.h,sha256=9R6piRXR4G7RDALjgA2UWTU_6wyLo_fwGxmo8V96h9M,1244 +torch/include/ATen/ops/view_as_compositeimplicitautograd_dispatch.h,sha256=C5cdp5DbhwwtcNkmqpICCGuT646zDlRD03zgeIPE8WY,1045 +torch/include/ATen/ops/view_as_native.h,sha256=_wWLqJC__0CWRID3JDYSnqRHczhbQauaX2fDwfMgp-k,757 +torch/include/ATen/ops/view_as_ops.h,sha256=zpiLCubplyWHWYexQuGPI8MyzJZZ2mKkOHm4fw_X02U,1306 +torch/include/ATen/ops/view_as_real.h,sha256=5ayVHt5QlvTfSHaJ1Hz8-4dmx-M_VKWim-WVyA1F9yc,921 +torch/include/ATen/ops/view_as_real_copy.h,sha256=7IQEl-c6a8QJ1wN0jaSyYKcSSGU1-ySygrXWRiyIlNQ,1391 +torch/include/ATen/ops/view_as_real_copy_compositeexplicitautograd_dispatch.h,sha256=7AyOa60Jva43fN_S0GYrJoLyIJt4H0i6bQqpweM67tM,1143 +torch/include/ATen/ops/view_as_real_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=pxYeLcSTKRfJIz1bUIy2ppanoNUMT-Hd2ZVdZ1v0TDo,1055 +torch/include/ATen/ops/view_as_real_copy_native.h,sha256=0WF3X8s2Hqdr_twooGlPfpzwRCMpc6IFsH0YJcXXjVo,830 +torch/include/ATen/ops/view_as_real_copy_ops.h,sha256=1QEGWkzDQPwNNeSuezLkRT278PeaCCkA2bKkVcMx9xg,1867 +torch/include/ATen/ops/view_as_real_cpu_dispatch.h,sha256=IIDz6-o9AGK1JjNbVtGvYxbGGP0cFJ8paH12DRBXxFo,980 +torch/include/ATen/ops/view_as_real_cuda_dispatch.h,sha256=a8jBi4gQ5a-fkvIIVCOLp-vJ4CwbwgZBkX_ZBrgseJs,982 +torch/include/ATen/ops/view_as_real_meta_dispatch.h,sha256=jLFinJQF4v1-HgEsoVUN4-iSY3tTjbHlUG4PMjPtfyw,982 +torch/include/ATen/ops/view_as_real_native.h,sha256=rC2H9uYQki8uZdDLuSdBQXUFoMtsrzyxlx76QQuTWEU,803 +torch/include/ATen/ops/view_as_real_ops.h,sha256=ea3qjXjO9-xonKQR3sG6-kZ-gTzrZxBBLvxmZvFCefg,1235 +torch/include/ATen/ops/view_compositeexplicitautograd_dispatch.h,sha256=YfVf_zRhMJVZwtdi0360E_lsDJZmo0C9jqRX7Ayfq6U,1038 +torch/include/ATen/ops/view_copy.h,sha256=peQjHdsgZV7JG_uG6MABHdu6S-TxxOFhTbD0cxrezYs,4567 +torch/include/ATen/ops/view_copy_compositeexplicitautograd_dispatch.h,sha256=aYEAnUUQxskAc4fziN8xtieCgMmVXicygQUn2l1aWr0,1607 +torch/include/ATen/ops/view_copy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=MvDZROlbaG5ER5LTuq5REUHVGm8kBwwxLP2FVKYX4vU,1238 +torch/include/ATen/ops/view_copy_native.h,sha256=YiUsJYzg0-BgZw7QmPTc7wrqeZJalTBLkngAk_jkVsc,1074 +torch/include/ATen/ops/view_copy_ops.h,sha256=Y2jtVsII1DLIQn31Bcdm57xlnlJOVb4nIoM7-GkwUCQ,3294 +torch/include/ATen/ops/view_cpu_dispatch.h,sha256=n0nHJcsPfSrGba8oDYuE8b93v5BumHDMVt6A-N_enr0,1079 +torch/include/ATen/ops/view_cuda_dispatch.h,sha256=2u7dNdDKeuSEg4aeLaSOOYvfc40dCXn4MINdLMuyLUg,1081 +torch/include/ATen/ops/view_meta_dispatch.h,sha256=vAOyA1AJ5XD0tXbygiTYrRa-uEJX35_SACr1gNTx4lg,1081 +torch/include/ATen/ops/view_native.h,sha256=-3PJs1-uHgjWWTZKvrfYWwdQ3PQzLAPZDJN2FS6dZ6c,1077 +torch/include/ATen/ops/view_ops.h,sha256=SwwCiaWM53F4d3WML2FpoU9FK4ZupDcCcWYJkC-eP9g,1894 +torch/include/ATen/ops/vsplit.h,sha256=KM71VxI6WvjpHrNSaX6Otlz5tKSh3YyP5tvdKBySMMQ,1193 +torch/include/ATen/ops/vsplit_compositeimplicitautograd_dispatch.h,sha256=t52jUPFnDHNxt8JdBEq-3SSE1O9tGfzsOczonUdybOE,1145 +torch/include/ATen/ops/vsplit_native.h,sha256=OIWh43o4DGB9m7Y4bT4EcE6T8vsSo8QV1MdA9RGIUXo,857 +torch/include/ATen/ops/vsplit_ops.h,sha256=u1eSYptxW_q-ruySzD6rhOKni5O-9Kzuv_I5r2tworM,1996 +torch/include/ATen/ops/vstack.h,sha256=9-oSnsmcpHnF7OQmLdMbNGUw1F-DFWDS0MwG49lVZMk,1302 +torch/include/ATen/ops/vstack_compositeimplicitautograd_dispatch.h,sha256=emO4YscThcSAWMKGxGuJosB94u8muTcTjLW98iK6xpY,1172 +torch/include/ATen/ops/vstack_native.h,sha256=me3PDh8hR7Z7IBZcjd2zWU_5Q4leydqeEAY4ewtC16s,806 +torch/include/ATen/ops/vstack_ops.h,sha256=WzGCcbXgd_UTVjQZf5ozkAS13a0bTNWfNict4SXTI-0,1799 +torch/include/ATen/ops/where.h,sha256=e5IQB-LZoBA2mv24F8lCpdGtg5mZLp5IN-75vqLyhS0,2557 +torch/include/ATen/ops/where_compositeimplicitautograd_dispatch.h,sha256=peRwiVwihUlDxQwojEO1mXQO7Ha2XaIaAQ9wqwzcu3w,1364 +torch/include/ATen/ops/where_cpu_dispatch.h,sha256=S0qQQ16Fii0CA3i09OAUYWAY9hrRcudP9OGJV5WWgjQ,1296 +torch/include/ATen/ops/where_cuda_dispatch.h,sha256=4EoxCwDtpsOS4qD5vqgW0mB_wPlZOWrwdG3MMCrx-Sk,1298 +torch/include/ATen/ops/where_native.h,sha256=EdIsoAf_mD76R_OaeXYQ-hzkFPS5RckLT9hvMXmjcLE,1591 +torch/include/ATen/ops/where_ops.h,sha256=4UmqmbPgxA9Ow7EEpldJUbrUgm-JowsOwhAy-K6DdPk,4881 +torch/include/ATen/ops/xlogy.h,sha256=TuCqeYsAVCOenJnWAo8TaphxJlOMowdc7RhMNiOCUug,3318 +torch/include/ATen/ops/xlogy_compositeexplicitautograd_dispatch.h,sha256=iVS_KwkXYj3d4WVWMOLPWnAEWouswJnKsjq736Ito-I,1612 +torch/include/ATen/ops/xlogy_compositeexplicitautogradnonfunctional_dispatch.h,sha256=893tL9CGZya8TpO9sRY0zYtCaipyLDE7CIc_Xpf5C1Q,1145 +torch/include/ATen/ops/xlogy_cpu_dispatch.h,sha256=rLLrWLK8GlMaWaFOjXxFMfLPgxyi3Y8fmDsg-5ApNy8,1282 +torch/include/ATen/ops/xlogy_cuda_dispatch.h,sha256=WbCQeTbvAWTPrGUZ4ahFEM8bjrc9ETJJAqslOU6ADAI,1284 +torch/include/ATen/ops/xlogy_meta.h,sha256=XwY96Fur0W4J-FkBBzSLX7vkPd2hIn0CSfoSxZSA1l8,853 +torch/include/ATen/ops/xlogy_meta_dispatch.h,sha256=XfwHSu5uRYR8XerF7Pj7jia6SWcP7ILRR_82gZC5PoU,1284 +torch/include/ATen/ops/xlogy_native.h,sha256=dxKz3BI0ip-r2VMHmdv4Z5M1dT5a1UvRzEHrNL3GQk8,1320 +torch/include/ATen/ops/xlogy_ops.h,sha256=8qWfUHgkOfm_ltEQLeT0mFjr-fyY9nc2O6raghk8g1I,5881 +torch/include/ATen/ops/xor.h,sha256=UIoqw1zoIaprTXMXWtpL9qk0Zs6lERKjzaPsosIrUKM,1151 +torch/include/ATen/ops/xor_compositeimplicitautograd_dispatch.h,sha256=8R1svVhfc2qFTWM-Fj8wooTqKBD6pYAJXgyS_g73A74,1282 +torch/include/ATen/ops/xor_native.h,sha256=gM5dHlixX5ocP3UuTv8teVyONjrhFj8lkBciivnrQ7s,994 +torch/include/ATen/ops/xor_ops.h,sha256=KNyI_wAKSbxhcl7EmkaPR65P_u2wSNxFq2J2ic-Sx6s,3145 +torch/include/ATen/ops/zero.h,sha256=l1nRjtPSq1AQr6AEwYAKTUeywvg004HZYB-NT3LjQ6c,1397 +torch/include/ATen/ops/zero_compositeexplicitautograd_dispatch.h,sha256=RwOxpmH7vFAarQXVZkuYdBdybZy_YhEfUwdLeSwmlnk,1169 +torch/include/ATen/ops/zero_cpu_dispatch.h,sha256=--hGYlPpPqTv9nVIBWSLlCq1eY4F17dhTx6e-vUKy3c,969 +torch/include/ATen/ops/zero_cuda_dispatch.h,sha256=5yduzMQuacGwEV7MWqKhXMWXF2gjbG3FkvNFS-3Y7Gk,971 +torch/include/ATen/ops/zero_meta_dispatch.h,sha256=zj1PwiKraybZ-vSRnryY-eXt37kxO9M8dtG5HaQW2w4,971 +torch/include/ATen/ops/zero_native.h,sha256=zIxO5KqSUxuJcMoAC6Yrw_prZsmxTz6NJGb30lMjmnw,1135 +torch/include/ATen/ops/zero_ops.h,sha256=SH7IZbIrl1-rELgxW4Rl2LIg23hSNCmLMJwGHwy2gL8,2282 +torch/include/ATen/ops/zeros.h,sha256=uSxRmOPqEj6aNjCttXZq5L_KMTz9tc41zt-TAMSGW9I,5679 +torch/include/ATen/ops/zeros_compositeexplicitautograd_dispatch.h,sha256=hpl2s8wehBJsLHnDGKAcas3TFpsuxW_l0mvoqy5EclU,1856 +torch/include/ATen/ops/zeros_like.h,sha256=jdw3IDyDg_k5_j_t9agBCmStJpL0bfP-PlvJhxqCbpI,2475 +torch/include/ATen/ops/zeros_like_compositeexplicitautograd_dispatch.h,sha256=Zef8fFttnNwB08ztQGWxwQ149IgEewYmpKtgLhLYyu8,1646 +torch/include/ATen/ops/zeros_like_compositeimplicitautogradnestedtensor_dispatch.h,sha256=TmVm2MpPmpHuSrfeqTFuPJ5aVEBnQYMgQauXMJSnbcw,1392 +torch/include/ATen/ops/zeros_like_native.h,sha256=jUbqnlj7UU-v1U3lWjQSFxciVMD7uo-YWOL3JLHcnL8,1086 +torch/include/ATen/ops/zeros_like_ops.h,sha256=FkMXkSDU7uv1jAT_teyuPyr5S1GMgbLVkIkp_i3wSFM,2655 +torch/include/ATen/ops/zeros_native.h,sha256=3AhDu4iupRJUrNvcPHFE1N9cyEcdr3GFjuwGwsLoQcM,1049 +torch/include/ATen/ops/zeros_ops.h,sha256=gilimYZ6sdAABF93NXqBZ-rVShzo2xGgZOICWq8ZHLo,2301 +torch/include/ATen/quantized/QTensorImpl.h,sha256=YCONez30ZR878R0GgzfJazkS44z8xQBYXrIqGM2JG5s,4275 +torch/include/ATen/quantized/Quantizer.h,sha256=11qYFvRL3cOpn03oX2jj-McVtmqvxCTVp70_i2HgokY,9486 +torch/include/ATen/record_function.h,sha256=dcBOVXeL6voE_KcAcjxKUgGkVtI-JZIFzpN-vsrOEX0,24519 +torch/include/ATen/xpu/CachingHostAllocator.h,sha256=gONgsOfhC26F5q2kJ650FDaMpCQT1EvK3OHy-365fDg,1611 +torch/include/ATen/xpu/EmptyTensor.h,sha256=rOqGXEQjRbuhyjk0MVDF3ys9HbnwSjMzbOwtUq7nGCI,1413 +torch/include/ATen/xpu/MemPool.h,sha256=DAJb9mAQvw6eZPhtd7zLPCWqCPbd7BfvZmnKrjEzkAE,1157 +torch/include/ATen/xpu/PeerToPeerAccess.h,sha256=asP_YLMYgbcCoC3deEigGTYHVMKMOCQhO2s1F8sQYeI,954 +torch/include/ATen/xpu/PhiloxXpuState.h,sha256=1XsgWS7eFn9uyFMrhp9KcWESdjg_TMwP0LCYdS8dWWg,1261 +torch/include/ATen/xpu/PinnedMemoryAllocator.h,sha256=pQ7YKcs5YKKEwiGf5yUQROWjKj5WXtt2GOs-dZg1nIA,500 +torch/include/ATen/xpu/XPUContext.h,sha256=2mMuW1pieqh-HETTKnZBhNdwC1fv-A-taQbVquPzvNE,791 +torch/include/ATen/xpu/XPUDevice.h,sha256=rSn5aU7Pn8Pdmig-ckK2xwXXUpH1Q9rtzGJI63Dhsv8,521 +torch/include/ATen/xpu/XPUEvent.h,sha256=jdUIC50oEIdXyYz1r3J2-gQoYg_HIYl9iIzNVooOszI,330 +torch/include/ATen/xpu/XPUGeneratorImpl.h,sha256=n8gJT7tSo_GSdzMzdaLktqU1EpmHLTi2Bk0tj9CssGQ,2912 +torch/include/ATen/xpu/XPUGraph.h,sha256=1aTwdrHbLCGCA00JpuLq4txTfI6bqASHvmYhVnoP8BU,3557 +torch/include/ATen/xpu/XPUGraphsUtils.h,sha256=Z6abmhD97-catJA8HzmeuHUDPIVg3Bt74WSBNLEMiR4,810 +torch/include/ATen/xpu/XPUScaledBlas.h,sha256=TqcyF00HBcwWLUl5Ux2-c9bJzv07NL1OKuzTGndozSU,2897 +torch/include/ATen/xpu/XPUUtils.h,sha256=kpMUbXqmDwFezM13YxjumUw91b-3AKe-DNgWQE78IGo,676 +torch/include/ATen/xpu/detail/LazyLevelZero.h,sha256=2TriZV3vzfkJ3z0GdAp_-0M_pf1p397erweRB_jFh-A,612 +torch/include/ATen/xpu/detail/XPUHooks.h,sha256=7rF5uCSG9Mm5JEfD64H4eMWp55EJ16zqq2p9PeA1gR8,1472 +torch/include/advisor-annotate.h,sha256=MgjrWkMfFXXb2B7pJlf4xO-drRhiQUPw5t36P264E-g,23930 +torch/include/c10/core/Allocator.h,sha256=0Io1avX89Km3sxxlZR8PLK1AnDsk0SPGGUsWispxAxA,14582 +torch/include/c10/core/AllocatorConfig.h,sha256=S6DNI--_Z9_HeDP8gsQkDtErgaKsv6hT0dBz96lSY7g,15504 +torch/include/c10/core/AutogradState.h,sha256=tQyhtQtY0eM4mC6jG1QKi4fn0qfyXMcukCkOk5zHpMc,2427 +torch/include/c10/core/Backend.h,sha256=jUqyE50qhbELtKPwwVryHE_7Aj6M9YXT1PEUbO59uy8,12187 +torch/include/c10/core/CPUAllocator.h,sha256=_tQd7SAIJ5k0s7Inu0P5L-o7SSs7diwk2j71sLX98Lw,1953 +torch/include/c10/core/CachingDeviceAllocator.h,sha256=FQ2E8wL-qhIhHXyEC_BjkFWPmpMfxOOiwjqzF2EPPqM,10462 +torch/include/c10/core/CompileTimeFunctionPointer.h,sha256=ea6PBQnezWHDIAcwtLYbIb-iS_nRuNcF8aE5lS4dgYM,1954 +torch/include/c10/core/ConstantSymNodeImpl.h,sha256=S0UAsSIydJwtWNl5lp759zfM77quImnhBQY7PMGPUhE,3363 +torch/include/c10/core/Contiguity.h,sha256=OcYWLOKaMJuo7dRL5Yw3piqMJ_a5706yUPGr1y47Zr0,10039 +torch/include/c10/core/CopyBytes.h,sha256=MawPcjyx1VMe1f9kp2RIx2BjAs_lI8jlK4BuppekD6I,1597 +torch/include/c10/core/DefaultDtype.h,sha256=KZKv7UUxi8v82O_Rk4gLa8yQ7QvkYq2HYUmxinwch3I,648 +torch/include/c10/core/DefaultTensorOptions.h,sha256=HgF3PO38zQ9lgd4RxZ2D5wWhobFPof5Sao6cxb_XJ_8,1318 +torch/include/c10/core/Device.h,sha256=xOo02kJjwgwFhsBck2TOjH3cg97SsNwbo0NItlqkxr8,7120 +torch/include/c10/core/DeviceArray.h,sha256=22EPv2g9iAoMplJyqgcPJkRJ35OwJAp3LOv_6RFg724,937 +torch/include/c10/core/DeviceCapability.h,sha256=sw7aVyoj2M0skKdyJQoauOguTqBcB9yYKvJwRDRmyoY,2534 +torch/include/c10/core/DeviceGuard.h,sha256=Gms0KqpunmWig_7lmwO7jrGu9f9vSESDEbsIQcBz5FI,8062 +torch/include/c10/core/DeviceType.h,sha256=FSeENqyP_wy2oz9TTWCVIn7UAWq0p2v4v9tMqMTCKlc,1055 +torch/include/c10/core/DispatchKey.h,sha256=lfEJ7hnk_wEonhT4AAFMFwtx8vNGvzCIkbXJjUR7D3c,31914 +torch/include/c10/core/DispatchKeySet.h,sha256=qiL1ym74jG78xromzinvbUA7zNnSjmucxDDzmxbukhs,41930 +torch/include/c10/core/DynamicCast.h,sha256=u8vWNFfLpX9LSGuTQFqW9mlvsz0Xr072TybCyIkBvKI,4887 +torch/include/c10/core/Event.h,sha256=UadXfNbB3Rga50tKW1BbTvfB-0_3vmscx6ta3JbwHxk,4710 +torch/include/c10/core/GeneratorImpl.h,sha256=vwW6696dUTwqRhwQvzFiaRqkKhRfx-89SjkUPvgg1DE,4647 +torch/include/c10/core/GradMode.h,sha256=z9_siQQtwK4RxWAE2eHUyt20IIUgGpdfGLp_LbMzKjE,1915 +torch/include/c10/core/InferenceMode.h,sha256=WiggR4JpCIisvvfKIhts7QMvJBsUvG3uksyGQBAkUZw,4017 +torch/include/c10/core/Layout.h,sha256=WZRk5uQ1-c6RjGjk0TGDwMIWZrgNSxMoXZZxIqQ4TUE,1887 +torch/include/c10/core/MemoryFormat.h,sha256=XI0mFyt3vpwyPJ-urnb0vmdrW2W1EOeoEJuYyKbdGeY,8843 +torch/include/c10/core/OptionalRef.h,sha256=VGHaFtquoi3P9FKVWvCmaEmliVViTAy04X7PLWl-IXc,775 +torch/include/c10/core/PyHandleCache.h,sha256=8yelbdpvMYKaIo1bMawYFGlMx6zj0YO0nrQa6SXVd6I,2783 +torch/include/c10/core/QEngine.h,sha256=0XnrQ3HHh00H39dSdMOnWxDt2mC-2F8gUbRd5mtDopM,1264 +torch/include/c10/core/QScheme.h,sha256=Hxao6hBmnsPo4mDykSRoaHGQV1BKndR9W_qvIoD9P5o,1934 +torch/include/c10/core/RefcountedDeleter.h,sha256=z9vp7IFlO65iZE_GqMSfYYX5tXSLOla7T0jgecY96UU,2505 +torch/include/c10/core/RingBuffer.h,sha256=uDuijfph8XJDK-CQGuGp-yivnlvOh8ONnSdWzOIHBHc,2395 +torch/include/c10/core/SafePyObject.h,sha256=C4eUbVovN5DSCny3CpaMuV0iD65i3urfiM25v9Ce5c4,3975 +torch/include/c10/core/Scalar.h,sha256=kV-m_B9q_ABqJBR7PSR98L9xVfmkIINl8P6VdzlOWKs,14740 +torch/include/c10/core/ScalarType.h,sha256=n9AXdVYUygDlsHXpEiwZMofHtdcgHToIYbv10m-USUY,9705 +torch/include/c10/core/ScalarTypeToTypeMeta.h,sha256=2ZAPKZkxiEGr1pwqGpnxjqF-ISfk5b4jk6zf18IW_bw,1611 +torch/include/c10/core/Storage.h,sha256=nEHPb13MWuBqzgsdGVd9j9yIb0xteDeoRsSIrkkV97I,7997 +torch/include/c10/core/StorageImpl.h,sha256=puoIRgJvLck4PLqlC7VOaufvKtipUqhMpU5EpJWPRmY,13971 +torch/include/c10/core/StorageMaterializer.h,sha256=zx6iS7qbaDgx6jqW_89i6gEpTCG84IjnrKiozrZXzLQ,737 +torch/include/c10/core/Stream.h,sha256=xmk3T7nP5C62JKrPf3fmLAT2C0Z7JOgkGV8BgDDRmnQ,7032 +torch/include/c10/core/StreamGuard.h,sha256=lSXnEpjYzbhTv5LS9PbBpCHFY90SDmbf-pYfDPIqosk,6842 +torch/include/c10/core/SymBool.h,sha256=rdRarYzPMHq3OvsNyg05BbQMt1dDkqiuBZw7dKkVO7M,4892 +torch/include/c10/core/SymFloat.h,sha256=mhRHhTtXNNcyr3B5sDwclWDOLzI5_HOkA64fBNFN_iE,3891 +torch/include/c10/core/SymInt.h,sha256=zREY9U92LNHcuc7xIhBpDa54wGq1lMGQDdrzkhFMIn4,17653 +torch/include/c10/core/SymIntArrayRef.h,sha256=psgPBcmm_8F1Gr_Z9GrUo94nF7LmvkHhs54bP6yYME4,3530 +torch/include/c10/core/SymNodeImpl.h,sha256=e43eQx5LX4kt6RxU2aDGfaFcl89Lpnl-fcfg33lFjZ8,7598 +torch/include/c10/core/SymbolicShapeMeta.h,sha256=mdLCikBatgyXuP4j4XCh_JN0qTVRMzRmpivv10K-oKY,9285 +torch/include/c10/core/TensorImpl.h,sha256=P9cWsrc0N_lsXEurM4c2QzcB_pntBOMuqLCAaiMiYik,117016 +torch/include/c10/core/TensorOptions.h,sha256=JtsL4QO61rvbfimxKLoGh4iME-pnBXuW-t9l2CqQSFw,27414 +torch/include/c10/core/UndefinedTensorImpl.h,sha256=YPHuqeThSMX-hlQXH3_1ax1hejSGvexTJQeULXYJs4s,1487 +torch/include/c10/core/WrapDimMinimal.h,sha256=GzEltFCQfxV_PknyCE2aTtan-Uie-0AtUDNPO76f6ZE,1614 +torch/include/c10/core/alignment.h,sha256=CyLRjpw3Jm1j6I9sVCPc4F1wWXOfo1wcEzSYuezXhNo,1132 +torch/include/c10/core/impl/COW.h,sha256=lZnDDJsQva5AreczS0JFKoZSYNwEKudaCAshq3DyqRA,1291 +torch/include/c10/core/impl/COWDeleter.h,sha256=XnD0YAt5Euep8_WazaoqIs2sxEQpyunbVwLgAoTtGqg,2352 +torch/include/c10/core/impl/DeviceGuardImplInterface.h,sha256=OtencpMABVTKF4V0gRLoNW28l8HQsHwt6FRr5xGB8l8,15748 +torch/include/c10/core/impl/FakeGuardImpl.h,sha256=AO7r_xeS46X0I_63CpAmTlaB7BTNdyo6aYVudvpYBac,3436 +torch/include/c10/core/impl/FakeTensorModeTLS.h,sha256=eybEHnZ1KUAAblAbO5977czRO5sT53SpAlFiKT40oto,695 +torch/include/c10/core/impl/GPUTrace.h,sha256=h3gsM8i7vgjyb8ypN9JpTtxbcKr5xGRB05IML4lffZY,1128 +torch/include/c10/core/impl/InlineDeviceGuard.h,sha256=R8ooBA35wnukVZ5_Cl4eo19Jn4azaxVeUngCTTS66sI,16165 +torch/include/c10/core/impl/InlineEvent.h,sha256=oSHUnxokPTjgAtJsjrcL4iwYaJogtdguP4Ny8bCubns,4562 +torch/include/c10/core/impl/InlineStreamGuard.h,sha256=y0-b1g1el6WQGK1mHXMwcniDstsC9m8Q6HIUL_K4lWc,10168 +torch/include/c10/core/impl/LocalDispatchKeySet.h,sha256=uPWPtzGIfkJqvALMpp-1kFfQh_Ng7owMmmZGXNt9PCU,6819 +torch/include/c10/core/impl/PyInterpreter.h,sha256=Imdw1o8r0S5Pb1NiNyEK_FpB0StVgyyTl9dV67pa52g,11003 +torch/include/c10/core/impl/PyInterpreterHooks.h,sha256=jBr8SU2HACVK6SjQYuJr_0QoMirfThVZIdPDeFt_coU,1403 +torch/include/c10/core/impl/PyObjectSlot.h,sha256=E9C9UF3MIQRlO8sZJyJpaj-MzvFuFe7R3nlqCEEv270,2275 +torch/include/c10/core/impl/PythonDispatcherTLS.h,sha256=iPTFvUJXiDcNL3U0fL9DwbnRBvHKA98Sj1mdxG_esWE,1094 +torch/include/c10/core/impl/SizesAndStrides.h,sha256=7-4nCOGSdKqaM9lnmDkh0CKxDI2qHqTDjlAEfLFZKRY,9038 +torch/include/c10/core/impl/TorchDispatchModeTLS.h,sha256=cc-jimOtCaHndjJJC4CXNc0ZxiJbojjZfbDSnGPbi0w,2535 +torch/include/c10/core/impl/VirtualGuardImpl.h,sha256=5Ds4eZ78mrIaBTos3XwggFbCLqM5wIwjxq-23EsuGhM,3879 +torch/include/c10/core/impl/alloc_cpu.h,sha256=r1kaVQbsvfDznXZhbyfzCd5V1iUhM5cb-i__TG8p7Ik,926 +torch/include/c10/core/thread_pool.h,sha256=I3B_S9Ug2qpxoMRzI6kpxTEJ2QfdE2qQ8_LGEglKpSo,3251 +torch/include/c10/cuda/CUDAAlgorithm.h,sha256=lsQzc-6okqaGCA8Jbeh2Z2nMRzzeMqPrjP8R7_R4XSc,1295 +torch/include/c10/cuda/CUDAAllocatorConfig.h,sha256=9ih4bkOZ5yJUj81O5fJfG09g_bvHS9-9ht3i83autsE,8858 +torch/include/c10/cuda/CUDACachingAllocator.h,sha256=UpGyQJMNlHm-HYCacW2rGXOLpGTa1dch9PK4Lmm_dbo,19116 +torch/include/c10/cuda/CUDADeviceAssertion.h,sha256=8MMMTcwJdHHovtI4mLZQMWwvin9qrDfow5PCTBj9Zq8,4416 +torch/include/c10/cuda/CUDADeviceAssertionHost.h,sha256=c9tcIdVrm43nbQhpLvMMMGQslw-G-RPtF2NB3nYjw7o,6946 +torch/include/c10/cuda/CUDAEvent.h,sha256=iu6jGIlgEt828yqy8Pasp5qMSoritYBEyQumHyWH6_4,12830 +torch/include/c10/cuda/CUDAException.h,sha256=CqxxjNjjyqKa5MEQvK4mqxgantNaCKm5XzY7z_i7_S8,5165 +torch/include/c10/cuda/CUDAFunctions.h,sha256=1gmcIsou0-IIdIiKxqTN7Qh437EQbvUAJk21pCookfc,5611 +torch/include/c10/cuda/CUDAGraphsC10Utils.h,sha256=WqgP3iql25UsyqP2wVs9HRy-tsm73zlQ_KZkdYRA0gA,4970 +torch/include/c10/cuda/CUDAGuard.h,sha256=pogRsenjYuqUa0rxFCuv4PQVtvnC3fbO8eMDF-llypQ,11599 +torch/include/c10/cuda/CUDAMacros.h,sha256=vKcRKJirbLzl6keZ7h9Nq0GHVBG4k8_xD_F6_DRo-rs,1733 +torch/include/c10/cuda/CUDAMathCompat.h,sha256=-ycGywH4SB7-AFYszcthbtzN3tYeRLC59wbhveUS8Gc,3800 +torch/include/c10/cuda/CUDAMiscFunctions.h,sha256=gLA3_R6oS6dnlHwecetvOgL6TZuIvYyqOQHC_McimDw,769 +torch/include/c10/cuda/CUDAStream.h,sha256=zl026YvUY_nt3polh3vK9KGhwe1tMnSI2kLEJMu8GXs,11261 +torch/include/c10/cuda/PeerToPeerAccess.h,sha256=AAm8L22rGCpiQIXDJNNSPg4aOvm-DUQ9hoa5AG5Cq_E,2035 +torch/include/c10/cuda/driver_api.h,sha256=yshTnDzZqJa9k311B4MT4T3l4Cwq-qJxAc-WsaY0pT8,8823 +torch/include/c10/cuda/impl/CUDAGuardImpl.h,sha256=QMdJQjTgnc0KCce1iTfhO4isHSN1riemF7UAnP5albU,11461 +torch/include/c10/cuda/impl/CUDATest.h,sha256=BTPl4FJNqWy_3-YjnTBSSP51zAn9mZNRExbII4A6ldY,368 +torch/include/c10/macros/Export.h,sha256=aKgtX7IoPp-XfETT47kLUzjtrnOMHwXoApOWvfEHm-k,298 +torch/include/c10/macros/Macros.h,sha256=wH4q51OHw80iQFJqqiA9fdomPzKQyNh16vYhQ_FDjkY,298 +torch/include/c10/macros/cmake_macros.h,sha256=1C1RQ6S24kR8rzJDnxSjruaF9pbsx4bfcQjFvsNVKe8,541 +torch/include/c10/metal/atomic.h,sha256=yf8SOG_mCKGqseimMyTokGa9FlKnA5F4nU9Mc2qYDTU,9114 +torch/include/c10/metal/common.h,sha256=KrN_MSGJQFmPvShTrwDET-ZbcI7ICKJbsNapfD2PxJY,3142 +torch/include/c10/metal/error.h,sha256=M2olVqwxGktrssQI-uNXNHI6Hnx4pOhSG1luZhz9R-M,2658 +torch/include/c10/metal/expm1f.h,sha256=W1tWWSsW05yGNpKRElkDGV2p-AMXWMa_NPhRTEkdN-s,3850 +torch/include/c10/metal/igamma.h,sha256=qqyazrvnsloK5hiJX3kibHJXEwbAHDBxSWfzwmMBcdE,29348 +torch/include/c10/metal/indexing.h,sha256=X9VmoHuCIMAJjPO_16LzxoHo8gFgZOxbwBAzCDmder4,80243 +torch/include/c10/metal/random.h,sha256=k4ULTytNu-AYHdfKfndP9ePpWrFJo7Vbisx-NPz2AYI,3487 +torch/include/c10/metal/reduction_utils.h,sha256=LgV9cDmZGISuWllY0U0-051zySctggLyc30K7_STHBs,16399 +torch/include/c10/metal/special_math.h,sha256=qGAZ4bSDxmswRQQr0Jj_c02eRw9WsSj0w1XQRGFUl1s,90903 +torch/include/c10/metal/utils.h,sha256=ghmHeYYnViqkMN0aEwvQpZ2xRhInhsxoYCgH620miDc,17085 +torch/include/c10/mobile/CPUCachingAllocator.h,sha256=siV7RrY8N_OTHsB5pv_i_vLjwP42pTXwrGyXYSJDqnk,4419 +torch/include/c10/mobile/CPUProfilingAllocator.h,sha256=oncuerKj9rl0s1psb-coVn62gPeuacZ9bDRlkRIyS8I,4990 +torch/include/c10/test/util/Macros.h,sha256=zDj8MR87ceOXepi-1GwaSYEnZTKQpcsCivD-tTmzd2k,430 +torch/include/c10/test/util/complex_math_test_common.h,sha256=WybEVfYt5z6FHzF8BQTu3bhpdmizcJYweZWK6T6SUAU,22218 +torch/include/c10/test/util/complex_test_common.h,sha256=iQ67ozmpgtTR3kdLPpWYFjxSV1eQzlXzoQSKOGv5suU,20382 +torch/include/c10/util/AbortHandler.h,sha256=tpnYao6yYLJanEvxZbNYmuWGY0nk9xi-VOaCwPk7k7M,2446 +torch/include/c10/util/ApproximateClock.h,sha256=CG6YMdzmJ0AasrfFhGbSJ3p6WNRoGow4YzL29u9kx5s,4509 +torch/include/c10/util/ArrayRef.h,sha256=vo5LE5-eY2_-j0Dex5m2bJDD3VFE-P1uEtBn5-djwTA,10171 +torch/include/c10/util/BFloat16-inl.h,sha256=tANwC7RCx2Q4TQpZxebutCOlc7XIiQ3rzCiC9GALxWk,298 +torch/include/c10/util/BFloat16-math.h,sha256=vUOkhq7OURRrKc6zddS257-afszkVNzf-94JW66WeEs,8772 +torch/include/c10/util/BFloat16.h,sha256=tANwC7RCx2Q4TQpZxebutCOlc7XIiQ3rzCiC9GALxWk,298 +torch/include/c10/util/Backtrace.h,sha256=99hh6frZffmL9B6uyPlKMEC_DVrSZ90iBnf0buYsBMA,1051 +torch/include/c10/util/Bitset.h,sha256=HPP1hq71R_UPnh6MXxpQMTRCEfjaJzXlD2KG_iMgsIw,3744 +torch/include/c10/util/C++17.h,sha256=knpXYMQApc3HoERm4dG22AydBp82DW9eAFbD_bdCVAA,1178 +torch/include/c10/util/CallOnce.h,sha256=MpdyEek7ttrfoxeAKlfihi81e8j2yfiWUlKxsKQbMM0,2289 +torch/include/c10/util/ConstexprCrc.h,sha256=KxnQ5FBry6GVPm0732nDRE82DIq2g7DWfN-LmHcLfoc,6849 +torch/include/c10/util/DeadlockDetection.h,sha256=quzUTfDHPvS_6mttyRt-dDe_9kyGSmnuL-eI_-yx5BU,2471 +torch/include/c10/util/Deprecated.h,sha256=9xSX2Bd3ZgvKHV3qLA28orYjoEi4OlQW4upS17Ik644,313 +torch/include/c10/util/DimVector.h,sha256=CMuEFgqGmK-gM6sVX6LKXCBrbE3KIjy1PkMBlYIW2SQ,698 +torch/include/c10/util/DynamicCounter.h,sha256=9CUviUDJgTs5bkUecWKED1k03u15M_AEQNVonkxFGh4,1571 +torch/include/c10/util/Enumerate.h,sha256=lF-iYhMrwqAgSJR8OFrJN767aNDdhoQ0cTmy6XvbGeU,4255 +torch/include/c10/util/Exception.h,sha256=_cIBSFGDu4OiHkj4KfeMeNz7ysI8_coIyccJhwf41zM,35606 +torch/include/c10/util/ExclusivelyOwned.h,sha256=zlx2YRTf-jFNLZ3zBihV-VCrnP2-z1XTO1-8Tiuej-0,4832 +torch/include/c10/util/ExclusivelyOwnedTensorTraits.h,sha256=H9-sjDESpRHPJ9PNJ5wHsOznreGa6Q5AZJwIhzZER2s,2474 +torch/include/c10/util/FbcodeMaps.h,sha256=SvWo5BYW6hq-FW5gA-SaXpa2SWxs9wzkKR2erty_Prc,982 +torch/include/c10/util/FileSystem.h,sha256=qa1WnkhdQWOnmAdw6VGPMuRRFC7T7PZZjzTu9r_m6CY,891 +torch/include/c10/util/Flags.h,sha256=LICXlXDamM7sC-CLBxoacYqUvHZpu15JlnWiDb5vGh4,11154 +torch/include/c10/util/Float4_e2m1fn_x2.h,sha256=I5T3I6VvHz10-h6Au7k7hoQPZ0HGgj-QDDA3LmAEJOQ,306 +torch/include/c10/util/Float8_e4m3fn-inl.h,sha256=OUgD3KdzlsxbY4vU88NObVdrSSf2LZktRGUmnUQJsnk,303 +torch/include/c10/util/Float8_e4m3fn.h,sha256=OUgD3KdzlsxbY4vU88NObVdrSSf2LZktRGUmnUQJsnk,303 +torch/include/c10/util/Float8_e4m3fnuz-inl.h,sha256=dU4G7OuItSLI6hzDUQ3akWwsnurqoqmqiguPZqIR8ms,305 +torch/include/c10/util/Float8_e4m3fnuz.h,sha256=dU4G7OuItSLI6hzDUQ3akWwsnurqoqmqiguPZqIR8ms,305 +torch/include/c10/util/Float8_e5m2-inl.h,sha256=iqc-2y8RBLJiqt3vVigCgalkl5Xnv3knpiZ0fLBZLKs,301 +torch/include/c10/util/Float8_e5m2.h,sha256=iqc-2y8RBLJiqt3vVigCgalkl5Xnv3knpiZ0fLBZLKs,301 +torch/include/c10/util/Float8_e5m2fnuz-inl.h,sha256=bSW6u8wgewkReTQ3LAYMfRBsl9iVBlZttCu6ZtbzXtk,305 +torch/include/c10/util/Float8_e5m2fnuz.h,sha256=bSW6u8wgewkReTQ3LAYMfRBsl9iVBlZttCu6ZtbzXtk,305 +torch/include/c10/util/Float8_e8m0fnu-inl.h,sha256=QesGPWulELXJsE1_ymZwYgNS1LACzW1FRM5VIlIyrbU,304 +torch/include/c10/util/Float8_e8m0fnu.h,sha256=QesGPWulELXJsE1_ymZwYgNS1LACzW1FRM5VIlIyrbU,304 +torch/include/c10/util/FunctionRef.h,sha256=fyQ8_KLA5NIOXrYy34ytVaSHMgTm0kuGA9B_T4JnUTs,2584 +torch/include/c10/util/Gauge.h,sha256=kZMzAF3p4sit2L0JEX2gjttCzHPHBRaJyac6FC5YK0U,1446 +torch/include/c10/util/Half-inl.h,sha256=aQVHyZtMaFu4m6195VXdn0DNNsfDuBc4gLu9Jmb82SQ,294 +torch/include/c10/util/Half.h,sha256=WCt2hbTquUvDKVMV-07qwyw0pwhYQeb_V9xDYJeInps,555 +torch/include/c10/util/IdWrapper.h,sha256=XrOlnZhjCy8yK7PGWfS7452TFzEFjQvexjlwkWR1xzE,2590 +torch/include/c10/util/IntrusiveList.h,sha256=bRSOYRII34xAFnoEnYX5flk8t3mARgTdmQ6nEeQJxmo,4987 +torch/include/c10/util/Lazy.h,sha256=cqlGY0dfmPapAy_WV7Lih5j4U1q0Tobe__JaTW2VjXc,3077 +torch/include/c10/util/LeftRight.h,sha256=GKovBValnILIaGvYNlIhkZ7C0Z1gX0sMFW-qTxXK-kM,7463 +torch/include/c10/util/Load.h,sha256=UojwOytDL4SaAR_KCqRyqPTKXzhlN5RJcwbINCnoqtc,1178 +torch/include/c10/util/Logging.h,sha256=OEyhjoez2US21O9_P0KSQpUgJ8OjCWcWa35NNgWxmSc,14354 +torch/include/c10/util/MathConstants.h,sha256=1mpiCU8wwQfIepeIQznB-39Y3vE5sYBCPloMGZCdx4E,3944 +torch/include/c10/util/MaybeOwned.h,sha256=I_4xeTAc6UzR0QrDdutNTm9OxCFKycflG7ARiZXRfrg,7485 +torch/include/c10/util/Metaprogramming.h,sha256=8zzmy2y_5eEUR4lMAPsfBcTadQusC2506eA4Zf7JJ28,305 +torch/include/c10/util/NetworkFlow.h,sha256=EghGK6X4dvknoqYKFIOsPBPiS-Tj-z43CMhDObpOswU,1391 +torch/include/c10/util/Optional.h,sha256=GzsvJjlMuP8KRtSRH7FTMJF6fHZo7k497eXst1y7u2c,2249 +torch/include/c10/util/OptionalArrayRef.h,sha256=RU5rjwtn4ab26Czq0-352vP_eqfCzjmmtGaupIgAmf4,7887 +torch/include/c10/util/ParallelGuard.h,sha256=uV2vMWwnlXgS7s082IZruJiv6OkLAYMMD3Ty39kIVwc,627 +torch/include/c10/util/Registry.h,sha256=HbWzeygfVQq4hX5gJ_NsPVHlf6wRqrUu20Wn3fZH8LQ,13514 +torch/include/c10/util/ScopeExit.h,sha256=t3YVD8cpprBt4WXFuHi1jHT9BJ8DhFSyGtQZ17CEF3U,1513 +torch/include/c10/util/Semaphore.h,sha256=6MAXrwYvAWZAoVFl6NnLntQ4ugHabFOBdwRkqYzF0O0,1992 +torch/include/c10/util/SmallBuffer.h,sha256=aGhJb30t2Mhy7_K97f1hRwtiSLAagGhCvot6PGwR-tg,2142 +torch/include/c10/util/SmallVector.h,sha256=-sP0xp_xApJK7UzQN-lMjaPNNLmjRIT9IQtMW7XqqK4,49704 +torch/include/c10/util/StringUtil.h,sha256=f_FfNStkZp7DvvvDwRMeuFj_cejTlUTjgFwjqs2qmtk,7494 +torch/include/c10/util/Synchronized.h,sha256=2tW_9s7EXK40MUtpwv3-YJjA7FQwWllpaxOZLR0ar6o,2179 +torch/include/c10/util/ThreadLocal.h,sha256=wCti5HZb8cPA89t_y1OpPuw7DHj98QT9YfM9slvgxqI,4274 +torch/include/c10/util/ThreadLocalDebugInfo.h,sha256=e43-qncCGK17G09ZJFdpiA8TsChYXYOL9iJ3hJ-zb7o,5918 +torch/include/c10/util/Type.h,sha256=T1XX9iuFVOaeV2BNjLjgt5Hp1Aku0Q-Ecl_PolibcmU,900 +torch/include/c10/util/TypeCast.h,sha256=fOe94HHn3F1_x9UMlVwgTFxLxMr-3EdUUDJyjQ6ojzg,11507 +torch/include/c10/util/TypeIndex.h,sha256=rbP6WhqkPGA4qh6OszoADJTwSCozAXmLR79XPHPNhn8,4636 +torch/include/c10/util/TypeList.h,sha256=zkNZb9AcFUJktCgDJSi0K2OKn1w8K_UvhVMPT5nhWx8,298 +torch/include/c10/util/TypeSafeSignMath.h,sha256=HvEviNWsHTA3-frX0xDhi-n0TGTNrgwC4GzSRy0dxHU,306 +torch/include/c10/util/TypeTraits.h,sha256=7EvZei8Q0T6N4WzrKKxXrKYtqLiBaU9GEh1l2BE37_Y,300 +torch/include/c10/util/Unicode.h,sha256=Ua4k-_JzTSImffi1DR5qlhijico5wN8hDI5pCl9sRB4,549 +torch/include/c10/util/UniqueVoidPtr.h,sha256=fSov4eN6D-jae-xlEPvZnrfElP8yNbGp7lvT0eEHwUE,5060 +torch/include/c10/util/Unroll.h,sha256=UPOfiyO4HaMYDiu9w0X48H1cC1noEQmvQbfh6tnReRc,1097 +torch/include/c10/util/WaitCounter.h,sha256=3GaSw6xL0LaXhwA9_Rfi5WJSU3lFiXgHM_x3xwIRL1M,3050 +torch/include/c10/util/WaitCounterDynamicBackend.h,sha256=MsfBpIa5pRwQzILRp5Pg6AmlgPvnXXUOfdiz1RE_SYY,916 +torch/include/c10/util/accumulate.h,sha256=vqbcE_ZUjeZ4eC_9x0dAFDinmn-TWl0jp6ZEHNg3Crg,4286 +torch/include/c10/util/bit_cast.h,sha256=sxSghPDly-p8OH6gmTpfHz45ALOYU3Q_qSSForY8N3k,298 +torch/include/c10/util/bits.h,sha256=NvnFKQ-qXIxRN0UJsSzWvlkCWhAaVwJwOQ_saK6-00U,294 +torch/include/c10/util/complex.h,sha256=_qL9DnmLYsZjWUYchBG4C0_MYTjdb-rNgP9tFc2fZFI,2278 +torch/include/c10/util/complex_math.h,sha256=3K3MdjFBpU1bUYNCUmREuInf4dTPSb71QvHZmtYNUig,14390 +torch/include/c10/util/copysign.h,sha256=4fFRt3OSrkCMfGUGbbcqHpCkEs0pw8_uKGOsJGr11Z0,1086 +torch/include/c10/util/env.h,sha256=-M9kaD4sC50yrB2PTSG_v8RykDZyPIo_2e8eLvZEQ3A,1226 +torch/include/c10/util/error.h,sha256=0PShMfIU8VkM8fME8HC_gAkBTfPsP9Op4eeS_k6VpX4,459 +torch/include/c10/util/flat_hash_map.h,sha256=6qOa_TFEe6fmNJlcr18w1jl8Qv4y0sjeyMlGP2tNCAI,62661 +torch/include/c10/util/floating_point_utils.h,sha256=l8yiPUHN9Za9CCKY9MUFvPUMmgP6mwfuetzTN5TobgY,310 +torch/include/c10/util/generic_math.h,sha256=ezfY9osScXISPCzKsoVKsVmk-r1zyaWkQKNbda3Hdt8,3379 +torch/include/c10/util/hash.h,sha256=WmEt4PVMJVu_ISnkP-7yxetqVSS8RbFe_tT7zrtUXIQ,11371 +torch/include/c10/util/int128.h,sha256=lGDT-DCXohEx5riIIeri_91JleTaxyiy8SmZtWuQUz4,12577 +torch/include/c10/util/intrusive_ptr.h,sha256=B9AGYhi2PnyF46YHeYfIp3LYhU6H6K65dv7eGLUb_ow,46255 +torch/include/c10/util/irange.h,sha256=UzaE6wBFzo7QL4IjDnvnZ2zy1j8AITXz2wRpg91G_sc,3690 +torch/include/c10/util/llvmMathExtras.h,sha256=BMYa3VWCxXj7k5PJS9rrpPqDiDjEb7qutsUJOtuI0do,29766 +torch/include/c10/util/logging_common.h,sha256=tvOqN0oPLTJRZ47uh5xapHMgZaYWLiENqzOsadOaR4A,2053 +torch/include/c10/util/logging_is_google_glog.h,sha256=5_XA51tYu4EgZVQDycJLO-Osjy_jcicQOf_ifTUQzyo,3235 +torch/include/c10/util/logging_is_not_google_glog.h,sha256=D2V1ZZyuk4rteBLKehK8hrnb389H6cpgv_q1Hpj3Qno,6459 +torch/include/c10/util/numa.h,sha256=ThNH5iMdklhU1kgFOdr9IlHryVIOKKdcwexg83E0mJE,967 +torch/include/c10/util/order_preserving_flat_hash_map.h,sha256=O0szYNijg27FvK7v2zLo0lQo7ltmD69U6VL69pCtQRo,65783 +torch/include/c10/util/overflows.h,sha256=9MBGXJMVIbS1uqdmsiBF2NW3F6U3yM6rsaAitR5Fox4,4552 +torch/include/c10/util/overloaded.h,sha256=FHGcSpssgR5hnXJJ-MIn9wI2Mqb8FVYgTVNNcDlQ7d0,981 +torch/include/c10/util/python_stub.h,sha256=JqFk4mKCyu0chr2QF5a1IqXXbi9HPecVk_VhA2TxtCA,310 +torch/include/c10/util/qint32.h,sha256=ZxbaslMWGDjHB8VlJu25dTRcWWwklUFkUh6T9b8HHsk,296 +torch/include/c10/util/qint8.h,sha256=8IYNTICfJYSwwplrhGH9VGvjyFW56zDXd59Mh_3l6S4,295 +torch/include/c10/util/quint2x4.h,sha256=zcnQCEqSMrTjovsd5FdRF_KMIumwqhT5zwsHMyRcVHI,298 +torch/include/c10/util/quint4x2.h,sha256=IlMXyvQf4QqSO601TKk69qCMcfiSV8EKGKKQixbqFrI,298 +torch/include/c10/util/quint8.h,sha256=aydMTZmqEB4N7-EM5mRUhTZYJIZpSMJkiH_khO5Qcgg,296 +torch/include/c10/util/safe_conv.h,sha256=ZhVx-Y1pa8DHy3BaZ2WdpxP8eYv74ef2LE4_h5EK8t4,3650 +torch/include/c10/util/safe_numerics.h,sha256=g8o-ABoIf_kpszh3kVm6xLtHiqlzzbfNT2Evx8mcLlg,3347 +torch/include/c10/util/signal_handler.h,sha256=gv0fEnjAovuN0bL101qlZCFKTpj0VvXha_7pG8BG__s,4066 +torch/include/c10/util/sparse_bitset.h,sha256=tLRVQ8J_dDTkoIw6lVU3ZbIdcBW9ZHltKf5l0XaONQc,26931 +torch/include/c10/util/ssize.h,sha256=3LVqLbLSSldl1SP7d45-5ov2KxHnluC7_z7Pf_qkFXA,1623 +torch/include/c10/util/static_tracepoint.h,sha256=rED_IEBTyD9MieY029u4UdzsFnLaXVpAA22wplohBbE,1330 +torch/include/c10/util/static_tracepoint_elfx86.h,sha256=uT3xse24frgvxeuyHh8K34U6YcynWti_y9lacxCOZFo,7927 +torch/include/c10/util/strides.h,sha256=ijl5aJ28SyH_L44u77n1FCOs_kwdm96oYnHFo4IjPC8,884 +torch/include/c10/util/string_utils.h,sha256=FZ-mqgraU_uZqPS1m6iaJ0xD00cuCQ50iycgYya2GBY,700 +torch/include/c10/util/string_view.h,sha256=jGquSkxarFGWYvqo9fSZi2zBX1vEpcS34xmMWSPH5Zo,3345 +torch/include/c10/util/strong_type.h,sha256=riwLN2kJ1cUnuZ8Ow9jDy1Ak_hDFbXHD4jsfLq5eB6A,35793 +torch/include/c10/util/tempfile.h,sha256=QzgZNO5g3E4TW2g16iL6DwmhkdFOUDrSfMKRHCrYMK8,3014 +torch/include/c10/util/thread_name.h,sha256=5EZrohns_m4Tpb9e7lzI11nm6lGBd9wX5C4eA4l9ix4,440 +torch/include/c10/util/typeid.h,sha256=f4AlUA2mZoQUVarFlDgtCkHW3fg5fhcaBRQZdbwxj48,23584 +torch/include/c10/util/win32-headers.h,sha256=k4RXgXQbJ_UwzFiJu6Xv6TQyXQASmvD_Pov5LBpbEvs,303 +torch/include/c10/xpu/PeerToPeerAccess.h,sha256=opZ60OwHD1qnRupWAY5zKmuEmAeQP63NK0xDe-XOTIc,741 +torch/include/c10/xpu/XPUCachingAllocator.h,sha256=wRYDWwhVIR64BTE92_c4wcBYHfGawm4SXGF8ohf9W2w,3521 +torch/include/c10/xpu/XPUDeviceProp.h,sha256=qNcnyCpX8PpLzn-slGSPjMYkCz0XUN3uK-bvRZ_bY8o,15862 +torch/include/c10/xpu/XPUEvent.h,sha256=ai1DG3VZDH9u9jTLZyqUIceTPf__iwskdU-X8g9DN48,6548 +torch/include/c10/xpu/XPUException.h,sha256=LYBaOSJ4EGshvXPMZQ6CvER0NrWBJy-Hr9hWnWuOfeI,728 +torch/include/c10/xpu/XPUFunctions.h,sha256=C34GcpT19aSCWkP5dMKgY2p6rFsXuGtSgM0QDAuKLNQ,1591 +torch/include/c10/xpu/XPUGraphsC10Utils.h,sha256=jky2gKO_NFZWGy9peL_Krn37HAHUhXuc6seXUr2wYi4,1350 +torch/include/c10/xpu/XPUMacros.h,sha256=r6IGtxNCSJg1ccaOrhyZFS-NfTUmGbWhH39Ce9r6o7I,1124 +torch/include/c10/xpu/XPUStream.h,sha256=RsB35OmcbQJbdmeAx8n4rPokuz3P-PtizW3RDY2MJs0,7133 +torch/include/c10/xpu/impl/XPUGuardImpl.h,sha256=CK7PZ80y8q5KfTKq_FnuiACk1MBN5_axB_hgM1y1snU,8593 +torch/include/c10/xpu/test/impl/XPUTest.h,sha256=U4e0J34PGyBX6Tao-X3X85TLgF3sVNpA1xq7oA5Mb6c,720 +torch/include/caffe2/core/common.h,sha256=78VZIbkrJ_3jIbqrn-s-pcJeY6qNw0g5Q5c9GyjNakA,1623 +torch/include/caffe2/core/macros.h,sha256=mkq0xfBkyhKbxhqysnwEjRyhN5kiUF1bmCe2rU_rMWI,3455 +torch/include/caffe2/core/timer.h,sha256=C6gSn8UqhEI1yr7isd_-xGwmYgoIJKhaoIAvah0J12A,1472 +torch/include/caffe2/perfkernels/common.h,sha256=V-FFQ9vAOsaaG4QE08h7Zeuxh6H4m_umwDc8j7FOUuo,6403 +torch/include/caffe2/perfkernels/embedding_lookup_idx.h,sha256=v6rEhVi3EdlyELZwq6W_FZSPS0cdv0emL-0Q-z4kbpU,1928 +torch/include/caffe2/serialize/crc_alt.h,sha256=9-npt1fZ3vAS3LwE9c-sxmOhpgYokW1WvDJ7q-k3iIE,75756 +torch/include/caffe2/serialize/file_adapter.h,sha256=pAP8jaI0BTcjQB2EfPZ76kpsNBQ9G3LPwrvO7nZTchQ,1096 +torch/include/caffe2/serialize/in_memory_adapter.h,sha256=spFkU0FfXtgwVZqkdLOgNPtBzhWtAd3Xfy7NLRbh0Bw,1285 +torch/include/caffe2/serialize/inline_container.h,sha256=ZHsmkcz1SQA5fit_U6iDEkCroGRaQqug0TWOOj-jtMY,10761 +torch/include/caffe2/serialize/istream_adapter.h,sha256=-Y6HdewRC9Uhayv_q9h85R8PPO66a_qIolt1eR0tVlU,899 +torch/include/caffe2/serialize/read_adapter_interface.h,sha256=X-TyU4I-IxYbqQz0lyByvWJFYcAey8tPaX7xx0DESYA,786 +torch/include/caffe2/serialize/versions.h,sha256=nnNzQCd-EYVwQwfLfghke-iDM5X2FKIaVS9wyeJmpKQ,6878 +torch/include/caffe2/utils/fixed_divisor.h,sha256=Zvgc9CidZoQfI7j9QkTqrQaanXf5iZcsvxCJfnJE2bA,3786 +torch/include/caffe2/utils/proto_wrap.h,sha256=1QVXbf-ihQ7qhv9aNvO46oyVXUIYnQrrEi2jc3N9SO8,1514 +torch/include/caffe2/utils/string_utils.h,sha256=OZypdSsHGVDnqhxYJsh_yQXaW0FBlpoEEzpTLlxZieo,1460 +torch/include/caffe2/utils/threadpool/ThreadPool.h,sha256=k8zVVNB-237ElHKofNIJsBPktFzgjp3DX05Dn7j6thg,2630 +torch/include/caffe2/utils/threadpool/ThreadPoolCommon.h,sha256=41zihSOOaucnvGexl1jRBNHowqQDxcwqRPd8mv3PHSg,931 +torch/include/caffe2/utils/threadpool/WorkersPool.h,sha256=Vl9nyM5Fu6CZctEvXOetuqyiAXCoRbl9fSFqiSN8azU,11981 +torch/include/caffe2/utils/threadpool/pthreadpool-cpp.h,sha256=wdhFwxXXDwaAJ-Msy1LkBZD0KA7SEfXZ7EegAf3MpAo,1718 +torch/include/caffe2/utils/threadpool/pthreadpool.h,sha256=J5PnQfqWRF3ETKYJS_vcS95UxeaGIwIA5rmx8T5_spQ,6598 +torch/include/caffe2/utils/threadpool/thread_pool_guard.h,sha256=Bv3NtbE_UJ1KT7Z3Wb0ylMy59G2LOZV09ZWhG4Fr_X4,821 +torch/include/clog.h,sha256=LmhU0B5GdvZxhbdibrfyD6I-wBeQU4ZSuN_mL5O3ZJ8,5154 +torch/include/cpuinfo.h,sha256=DBLTmBf2Z7hPLz6AL8Zt-i2EZZzubg-kYIQocHIuakQ,58122 +torch/include/dnnl.h,sha256=-npiSEIICX2ZJy2baWpMX4uOZQpgXfh1A_IZdGSBp8A,1080 +torch/include/dnnl.hpp,sha256=YPZAJVUfe_dEFAyBWc7Zl1dIWZCKQAvnRezxMjIhkSE,1088 +torch/include/dnnl_config.h,sha256=0LRW_9dJNTWARLqhK-nlCgbnWGxWQBszbSoVyRXZcnY,1108 +torch/include/dnnl_debug.h,sha256=XLjSNgFUn83ayTuqCZHZmn_Yvq4mjwaU5A-czblJTc4,1104 +torch/include/dnnl_ocl.h,sha256=03__vBMCxQj81y5cqXR4lF3yoDlZ2Sd6UQ2GJIKCqHQ,1096 +torch/include/dnnl_ocl.hpp,sha256=Oe6xYIdgeoptQbGC9Z8fBKd-iZRLbVZkVpwPxXgnrC4,1104 +torch/include/dnnl_sycl.h,sha256=QuFHJ9y0PVBk7wE5Ad87DUY8w1ut_0284HA3Azr4OSI,1100 +torch/include/dnnl_sycl.hpp,sha256=qyZJxdsGray5-Qb5GlsreeRFni2Ryj4dwGozwFJBkFk,1108 +torch/include/dnnl_sycl_types.h,sha256=cQOxuhg809O4LuehF2b01m66cjXDd11IYcEub_-txJw,1124 +torch/include/dnnl_threadpool.h,sha256=N_AYimWiSinfGRfaJO7QO-wwUSp656InQMsxoupxsvg,1124 +torch/include/dnnl_threadpool.hpp,sha256=FTZXdpXDy7T-HHTtZ4-R8NFuhl8n_61HKmXHqJLZd8I,1132 +torch/include/dnnl_threadpool_iface.hpp,sha256=5H7Q_E09_nyCmWPAg6KAr2_Vs7VyGDbX4pI6Eq9op0M,1156 +torch/include/dnnl_types.h,sha256=342AMEBUhQUC605L8na27vlAj9dChtGiZ645-f4kbfY,1104 +torch/include/dnnl_version.h,sha256=9R16ZzMZoFGazgp5nucYaHprBXG7Qqm2J67EHYUDZ68,1112 +torch/include/fbgemm/Assert.h,sha256=aEZPQtNt69DRLUxa2LMSKuhAv3ZStf8WfpD1Yw1hlXU,2750 +torch/include/fbgemm/ConvUtils.h,sha256=sQ2ExE7aYAomJSitMwBeJDy8ZWyROUSY_jHZO1NvOkM,5849 +torch/include/fbgemm/Fbgemm.h,sha256=GicHarvh_fPLoZp8Y5cE2TijuUhflOZpRFRRML0Ok38,44258 +torch/include/fbgemm/FbgemmBuild.h,sha256=SYZSvveh9fEvuXtDg7Gm15L7V_ifGFl-yiGhW7NfTss,3489 +torch/include/fbgemm/FbgemmConvert.h,sha256=sKIhN4Lh0lC7Z9dQh7pwHRAd_r2U3XwzF1tYZE3KEnQ,4842 +torch/include/fbgemm/FbgemmEmbedding.h,sha256=EtI9pZJcU_XFkqZKdvTVFhJQN5GaqqHId3coYn6Rw0A,13219 +torch/include/fbgemm/FbgemmFP16.h,sha256=oN251lDlnryIf3rs7eRKZ4EyheMYr6v9r07Y3Q3F_7E,1385 +torch/include/fbgemm/FbgemmFP32.h,sha256=HTQ3TpFERHZgDAnM2OzFuubkHwcPjuu9X8LB4dH0k-w,1272 +torch/include/fbgemm/FbgemmFPCommon.h,sha256=HW20oOoTzmQK1oTLvUXFS6WlgfZHGIaILBRfwtpOVOY,9478 +torch/include/fbgemm/FbgemmI64.h,sha256=oUACFs1tWPDyd3pUO3os_j7tzTH7avHVRRL0OiZFVQ0,835 +torch/include/fbgemm/FbgemmI8DepthwiseAvx2.h,sha256=QumE9n8azzsmzGyx4z754ZYKcRNE-5z8uEIGB40RHm8,3795 +torch/include/fbgemm/FbgemmI8DirectconvAvx2.h,sha256=4oKMoeKXFALz6NSZwZDfNUc3c8Y4S4aXHdcTu22NBU8,2059 +torch/include/fbgemm/FbgemmI8Spmdm.h,sha256=tSDTxQLYGA0p-6NYet_oyL3ybCXjmlKf-XjihebThzI,3691 +torch/include/fbgemm/FbgemmPackMatrixB.h,sha256=4J6y1RyXd3T0ihZNBewAebIOyhPpAkJBaPY3u9nj2Gw,9470 +torch/include/fbgemm/FbgemmSparse.h,sha256=eFxR4UQOaDQUpKlvw7FQIvvmMYIHl7BqPJf0JM92TF8,6642 +torch/include/fbgemm/FloatConversion.h,sha256=1IGDU6pCAxhrr50S7bUW_pZra0lXoA4rRGH_YHh73cI,11734 +torch/include/fbgemm/OutputProcessing-inl.h,sha256=X8hgkXKVIm3id0XaCczDLcEbcSc-QP2mwAVskOXnvZs,10983 +torch/include/fbgemm/PackingTraits-inl.h,sha256=VlgGDAk5zkAmN2CJOdYLCuZSuLnhLacxr9yYtUP9kTM,19699 +torch/include/fbgemm/QuantUtils.h,sha256=s58BOsMwpdUcuOI6slgmVW7qrov0WOpSyKnMB1fMqOc,12683 +torch/include/fbgemm/QuantUtilsAvx2.h,sha256=9qwR79z-NMn9McUH-rdunJjJVEyu4zBt6RQsuR8r5uM,5293 +torch/include/fbgemm/QuantUtilsAvx512.h,sha256=bae15lfRDn8teH7NRXbINDIcHxu84LaG_5Oy-ojy8Q0,1464 +torch/include/fbgemm/QuantUtilsNeon.h,sha256=04RzxD49zSWRzaxEnFcm9ABlW32V-2-Cl0DfCMVAnEs,1666 +torch/include/fbgemm/SimdUtils.h,sha256=tEsPQiR7vh5V1kPYWH4Az1KeDsI99Z-5uhTjfL7gGKk,3209 +torch/include/fbgemm/Types.h,sha256=yKqHzeBTu1e8cVpg1iQOKsjtrShk9cdWvnsoTbIRM5c,806 +torch/include/fbgemm/Utils.h,sha256=0Q28SZcvT7cC_Ch0Gks19FgwnPIlxCxqaa1qO8TDjPM,13499 +torch/include/fbgemm/UtilsAvx2.h,sha256=eDdanmXaLpy8c2mcL4wsuOqOjhZQa2jtpdl_DF_BYM0,2999 +torch/include/fbgemm/spmmUtils.h,sha256=yYztyD1mvv1xwSUEg6yP0GdPwH2Li9ogYcniEzT2P8I,1584 +torch/include/fbgemm/spmmUtilsAvx2.h,sha256=xC5hZAJdIEJJWp9dj51GpL9OXEww7dToPQBQ3f0yCkw,1376 +torch/include/fmt/args.h,sha256=H5xWAU1JcMzgvRSPETJEUAuGhVidld_pOCVm44dnN9M,7446 +torch/include/fmt/base.h,sha256=DxKGjgGRHlMUbH0vM9EgszouaWBkBpKBkcBKe1jTR5Y,102994 +torch/include/fmt/chrono.h,sha256=uhPC8Zt6TNaP14ueA7RH1DJMsqgsFl3BeSmUcsbt7wo,77626 +torch/include/fmt/color.h,sha256=HMDP75LeneOEwBo8Hrs457mcpw1j0SHPDz0NWP4y9w8,25576 +torch/include/fmt/compile.h,sha256=ahrnlUSEx1qIlTMnLz3S2BAxZrbIn1fVNmfdKPH7bsM,21513 +torch/include/fmt/core.h,sha256=fzZxpJFzz0pvviN-3lL0Uew-IjgEPP4ejb815viU2C8,643 +torch/include/fmt/fmt-c.h,sha256=WcOYDcWyBgeXnQEJghw0-giaP6zkAA6ZykaAoizn3Vs,7633 +torch/include/fmt/format-inl.h,sha256=iprQ8d4ebAoGnG5HVlOxeMdTRMIIkiWZHekQs8czdA4,83335 +torch/include/fmt/format.h,sha256=l4OlibepH9aR3dCMuxDnJeaCcC8b1kW6O6aHFQmvBBc,164560 +torch/include/fmt/os.h,sha256=xAoodomfCmwX3UXCO3nfYMsbkkesDWBIlHgItM_KrEI,12866 +torch/include/fmt/ostream.h,sha256=ywUr4B_QnN46Tg1MCurn0LXccRMuqDXrWCd8EWelb5E,5311 +torch/include/fmt/printf.h,sha256=Ywy2lzCPOhrH6ZttQgdBAumZFue42FHGljD7a8wECQ0,21426 +torch/include/fmt/ranges.h,sha256=ZFvrV84opQbjaT4zDcq3XUE0agB9OKPyO_nCr3v-qwQ,29036 +torch/include/fmt/std.h,sha256=-06tGar_c6hewaS-K_778oa895u5qKOXkebv3NywBag,27723 +torch/include/fmt/xchar.h,sha256=bdgfBxe7X_FIgsLZ_k6bsAPwAq9qlgE3GwnChRdLzB8,14478 +torch/include/fp16.h,sha256=qOihPuIFJc7Ka_UrtrCjHjXFWHKZO5sm4MyRgoa6hUw,395 +torch/include/fp16/bitcasts.h,sha256=j98oDlFXdzNmpyi2G416tRL7K3bl2_LORCQnytZ6_cg,2407 +torch/include/fp16/fp16.h,sha256=O-KcphLcDRvpwLmJsl-3FqxqRoTuOvBYIVb0yPBbNmA,22256 +torch/include/fp16/psimd.h,sha256=2L-pHlaH1_t1SUpq0LOvGqKA3zScoC0hHUYhpYwEgbE,7099 +torch/include/fxdiv.h,sha256=tGAjCriH6CaOaYaGoVsuSr56y4GhUyC2NeVsdM1jKY0,13403 +torch/include/google/protobuf/any.h,sha256=_zXg66l-pmqZmyM1FjvCzyuq4bQ_oVNohiSQpYVAhGo,6801 +torch/include/google/protobuf/any.pb.h,sha256=w8mqdJVIe8xT2nUAGIlnUDGc8DvPpAqNj3VmXyNqQQ0,14046 +torch/include/google/protobuf/api.pb.h,sha256=jfDRwNTJNZjaY0r2MWoENq23frtaAIlH_0LE3G7n2rM,52165 +torch/include/google/protobuf/arena.h,sha256=D_8X-B3r6WPPxZ2TNJmRStu4UO2TdxC3tv79dgwFuW4,36035 +torch/include/google/protobuf/arena_impl.h,sha256=sc9j38eiTVvW5cufzCPPDQtwE-duLwgRUaLjHYy9ZWc,25687 +torch/include/google/protobuf/arenastring.h,sha256=2ZRdVQBRym6nYrVN6oSvSRdoRGQ8uML04heQLP4Klb4,19262 +torch/include/google/protobuf/arenaz_sampler.h,sha256=q28drKURkIvg7Y1c5pVsrl0RxT91AKHl2ycG9VoemYw,7896 +torch/include/google/protobuf/compiler/code_generator.h,sha256=Jwb5TLW6z9-K42C8Lwir8yE5arxHeF2PJo1X4SbTUzU,8846 +torch/include/google/protobuf/compiler/command_line_interface.h,sha256=tqNEeGYRqeOrsWTrEHfSDXRjWUACVoM7IhkaTnzkTjs,20561 +torch/include/google/protobuf/compiler/cpp/cpp_generator.h,sha256=qGIoZQz7FImNXY6Lh0341qSgXvjBLrsG0suBN44oBbQ,473 +torch/include/google/protobuf/compiler/cpp/file.h,sha256=x56hvhBlDpv7xqqzJWxCyGvkP97gW6tk2F6XIqE-Y0A,8891 +torch/include/google/protobuf/compiler/cpp/generator.h,sha256=Jc4_njJf6kGAG2RumKGEjt9AISx8op-dQHcvNhjE9HY,4458 +torch/include/google/protobuf/compiler/cpp/helpers.h,sha256=0RZAOBOBgQb3exH89fIyKJ3zG8nf1taP2qQmiD1JcOQ,42921 +torch/include/google/protobuf/compiler/cpp/names.h,sha256=fhNTQAiRO9SsKyPrNVyClJhtZITwcoGL2v3r4HnrWf8,4046 +torch/include/google/protobuf/compiler/csharp/csharp_doc_comment.h,sha256=xwxHkG80bInQa17gGYuCbl94epnsHteQFB1i2-R7-Cw,2779 +torch/include/google/protobuf/compiler/csharp/csharp_generator.h,sha256=XcFa2eqpbj07AFjfRYOxg1f_WQ3-zdi4aCr5SVJNSlY,3066 +torch/include/google/protobuf/compiler/csharp/csharp_names.h,sha256=UrJ-0cNggHHXIQVLv9PyzV8OtKIqF8XGygZYQXtGNlc,4434 +torch/include/google/protobuf/compiler/csharp/csharp_options.h,sha256=sHmqwrUzqRmCrIdD3t-Gk3fvuPxlAjuLSjhzYwKFzIc,3845 +torch/include/google/protobuf/compiler/importer.h,sha256=KSAMaDNONpKHFBxpwgcSw9lTIoG8CO0dkvoEs6cDdyo,14588 +torch/include/google/protobuf/compiler/java/generator.h,sha256=K2o4uSPrDmTzv1vBT3kpFZZYDETGDEK3tVtZGkowesc,3353 +torch/include/google/protobuf/compiler/java/java_generator.h,sha256=LZ2wO6AYgB6agKN-wbyyvU8Lz8jHzAztTioSs0u7d4k,480 +torch/include/google/protobuf/compiler/java/kotlin_generator.h,sha256=FK5mF8BbDAfQtA4RXEn2VTsMTg8yjjd8D5yl33OFaOQ,3249 +torch/include/google/protobuf/compiler/java/names.h,sha256=p8gyZjUgbg79fnhwb6RZA83YJz4dAoz3cv6aDDIp8SE,3531 +torch/include/google/protobuf/compiler/objectivec/objectivec_generator.h,sha256=4CTC3zvW8FbOHsLirwHVO-8UiiBG1fJdYjZ5PGnqo0M,3653 +torch/include/google/protobuf/compiler/objectivec/objectivec_helpers.h,sha256=KozpdI4EvDbS_YV6f7XAFSTw5cvJmLpmlwUcHMRn3JA,14354 +torch/include/google/protobuf/compiler/parser.h,sha256=KE6SlIsUOksNSMRLGfsOAhjTuA_lhsLrep0wlYcYbGE,28086 +torch/include/google/protobuf/compiler/php/php_generator.h,sha256=tkaitDDckQ66GFsjAMi_oFWSo7OwHvJ6XFZpPHClAIA,3802 +torch/include/google/protobuf/compiler/plugin.h,sha256=_NPw9-IG5zzRnSsxTVAgpHps5FUz6E93wdMUmQP8L58,4630 +torch/include/google/protobuf/compiler/plugin.pb.h,sha256=zftZT0hkwK3zUBA48-CFnrBHlssHg1PZxJqA7Jzvuas,78870 +torch/include/google/protobuf/compiler/python/generator.h,sha256=I4w9CsVGmKcJ37nZc2zbRfyXP4EYl8ztBvt305lMVOk,8178 +torch/include/google/protobuf/compiler/python/pyi_generator.h,sha256=fWn_68LQdl7svs941-_Fii5u_BsRhteyN9cHgoG2Oyk,5148 +torch/include/google/protobuf/compiler/python/python_generator.h,sha256=q4iTNOGjSu3gJyeMKO3texejf20sddTy5ZKnJyH80Hk,494 +torch/include/google/protobuf/compiler/ruby/ruby_generator.h,sha256=_iqMiDWu5rA32LhfulNVWEtPj7AJTDeSPYcp-gbEp20,3074 +torch/include/google/protobuf/descriptor.h,sha256=UdRzZPM5gF7F4zwrtsxrl0t1MySe82ZcP9FQVqtmSh4,101078 +torch/include/google/protobuf/descriptor.pb.h,sha256=hKQwEhwPxuuCGtDQFEKYsEB6BpZ7YhntXmMB6qyD2R8,611954 +torch/include/google/protobuf/descriptor_database.h,sha256=tiyurCiL7jR6ndMEAR3gbevFlQ0pa2zVqjTaDdsyy28,19151 +torch/include/google/protobuf/duration.pb.h,sha256=CQIk6osZZq1nPhem2LdQ36Yb0NTSbqK_XkzpAyTxYMs,9423 +torch/include/google/protobuf/dynamic_message.h,sha256=Zxtyj4kWdiotvWcN4FuDzXK-Fey6nYAlKH5IYswjKqM,9397 +torch/include/google/protobuf/empty.pb.h,sha256=-0NXaOV5yqhKGdY_uS95rL-zh1bG_wkRaZ5Ei29uGTg,6986 +torch/include/google/protobuf/endian.h,sha256=yPwHcEpQy3i9VbDrnbb5qY_tfmyqRatzupcygQD5ebM,5383 +torch/include/google/protobuf/explicitly_constructed.h,sha256=CSSI9wND4wgGkr1KzsDkvDP6TlEf6IAYqMrNnSIRVJM,4181 +torch/include/google/protobuf/extension_set.h,sha256=VYgSU2E7ijfuGs-Yl48nV0tVbN-7hmXk-ec5a80uqHs,72136 +torch/include/google/protobuf/extension_set_inl.h,sha256=EaEZJx1FgaCXnJs90UXaQCNudX2dQXVpbhq8VJLi7t8,13007 +torch/include/google/protobuf/field_access_listener.h,sha256=kg8E0eYdSk1N6tH6TD82BzUYdS-C60HjIJv_EGeIaac,7711 +torch/include/google/protobuf/field_mask.pb.h,sha256=9IOg5vkjvAgiM5nCGv3dKrhulUd7SPbnca6Rm3rj_3c,11884 +torch/include/google/protobuf/generated_enum_reflection.h,sha256=JXhqzyzV8F8rNn7bX6T_0fdvZEB5ox_JB9KlNE_WNzE,4274 +torch/include/google/protobuf/generated_enum_util.h,sha256=gL-omZM1ikEFAw8VQirDlaRl4sjPkFeAuNC_WNyLk7c,3547 +torch/include/google/protobuf/generated_message_bases.h,sha256=8ls57f76wR3yuxjrnlWXh18KONHH7LdLxTZ_l4ulcAs,3865 +torch/include/google/protobuf/generated_message_reflection.h,sha256=WPhzxyvmd2EgfjVNhhEp7vUuEnwjwIU6BwVVzGjgu0E,14438 +torch/include/google/protobuf/generated_message_tctable_decl.h,sha256=9SimgYod3BX7QcyWby58z7aRr6HtDmaPRcEYhlQuZL0,12626 +torch/include/google/protobuf/generated_message_tctable_impl.h,sha256=MhGsaZoGnSTXhgWv4txCWUWd7fUJ0gVsmqTm0BxEb5I,23281 +torch/include/google/protobuf/generated_message_util.h,sha256=veu962ZGeScrf_NIc0GFzoyXMfblGreGMQx9OeR_Ik8,8495 +torch/include/google/protobuf/has_bits.h,sha256=g6oExr3JHkup-t20T4cJ-9Q0rY18FBsDjgZ_2O3GgCc,3828 +torch/include/google/protobuf/implicit_weak_message.h,sha256=x3vm1-0dRDjsw6_jfL0K7Wwmwy65okLPXx0HX5IJD3I,8048 +torch/include/google/protobuf/inlined_string_field.h,sha256=aoNyVLmTPOLD_4z3x3DN5ryrRlNAeq9ZWIp1d3Qi7m4,21859 +torch/include/google/protobuf/io/coded_stream.h,sha256=PSDc-gTkCBt6ckoSbP4VyIEtLL_fjqXsJmoYEvqguNk,73758 +torch/include/google/protobuf/io/gzip_stream.h,sha256=nSKtpy0vQS2bzTU4tLUOe9XBwliCYAaIrwqzcnz42hw,7079 +torch/include/google/protobuf/io/io_win32.h,sha256=Fe-6EHZgcQY2Zp-U1iRnK4HxLdwLtQOgIexA3_EWkKw,5665 +torch/include/google/protobuf/io/printer.h,sha256=ymmVO8ezBvU2-p_GiOELu33SPi_nBdtfaA2P8TSq-1I,16207 +torch/include/google/protobuf/io/strtod.h,sha256=TMC_HjbTD3uF3yPXY0a2M7u8NTiGMkqnH9yivdn64zI,2685 +torch/include/google/protobuf/io/tokenizer.h,sha256=lDd-OENCc_qsLOUaKkvRPSFOnCAyIb275LgQj60_3Ks,18334 +torch/include/google/protobuf/io/zero_copy_stream.h,sha256=ypufu6q_nagTdu5Vd8aXaoVxHkluV3rsxHyOsbLKsjw,10943 +torch/include/google/protobuf/io/zero_copy_stream_impl.h,sha256=cuAles6PUjYIv2yoHGLAUerPxfbXc_f9iTZ6tEtoybA,13268 +torch/include/google/protobuf/io/zero_copy_stream_impl_lite.h,sha256=_wW11jNmDmxhfbfv9xkUxQgvs_yrfCixRQKMNLOKP3c,17352 +torch/include/google/protobuf/map.h,sha256=SBmjl8CcbUEqnmK0D0fLz6QtGEUU1YQ37_Tn4DmAPQA,52697 +torch/include/google/protobuf/map_entry.h,sha256=tnLfNVdW6rHrnpTQWsD6mHtGVaTihDOczwkogdpl0oE,5997 +torch/include/google/protobuf/map_entry_lite.h,sha256=jjw8tuXaQtjFndNlpE6YTQayCGxkzo5U075Drka7Bvc,21617 +torch/include/google/protobuf/map_field.h,sha256=ODIpx3wYMo5rzjkQCvA3u9FXfMdADfbnxgZyKlXDCmU,34948 +torch/include/google/protobuf/map_field_inl.h,sha256=jjl0mPZMmMd6oPZ0vaao42fwob2BI3Rf5qKWJTLB884,14791 +torch/include/google/protobuf/map_field_lite.h,sha256=nRXMeOZKuppLHE_NsRjTzqfsK7RnTiikSFhJDirXw2U,8037 +torch/include/google/protobuf/map_type_handler.h,sha256=aoLA5h7A1QARrs8jqhUVSFsg_GLVpClxa6SDJ1OJOBA,34411 +torch/include/google/protobuf/message.h,sha256=S8T-6hy43H0AxETklvAmTiUVXRmqHYYKeLBYKf6CDao,70400 +torch/include/google/protobuf/message_lite.h,sha256=qJ__79rtxkyobWAtm0GLlErKrHXXhdXr4pL_aRx11Ck,26114 +torch/include/google/protobuf/metadata.h,sha256=B1GOMsqbkFBMpUm9cpanG34OxSkvSHz_E3Ck3Nq-nzI,2111 +torch/include/google/protobuf/metadata_lite.h,sha256=HYUR_yA7dN4l0s3ttjSgo85PCrv9WGWbRXSiS-i45sw,11326 +torch/include/google/protobuf/parse_context.h,sha256=Y7TA4306DUpe5pViy9LWSk0Vg-CbueX10CzEt6sbeuQ,39145 +torch/include/google/protobuf/port.h,sha256=N-PrMm8aVg8kdcejkO7cRalen3Kr0OPMY8YZZuv6xZw,3348 +torch/include/google/protobuf/reflection.h,sha256=ZvrcP9mnueR22jEYCk5URBLK9B3_H5cnABcR3kK8c2E,23157 +torch/include/google/protobuf/reflection_ops.h,sha256=X0zqljrU8QMndxAZe8l2uP4-rUsZod0slsGSLtR9j50,4090 +torch/include/google/protobuf/repeated_field.h,sha256=lCNFJ4ANLzTRoXcKoLw8sqAl89ruL438pLPHNtABPcY,43241 +torch/include/google/protobuf/repeated_ptr_field.h,sha256=Di3pVnlENCHQhTr126646HTtKF5R2Jquw1QF6MneffI,71667 +torch/include/google/protobuf/service.h,sha256=Q5PClZ1sbSLcanW7Jp83o7HCnnW3aIRyz74yh0kF71c,13440 +torch/include/google/protobuf/source_context.pb.h,sha256=IJ5xOXeHGK0uFo8Dyd3yTtqn6JCaGl25tXyiFT40W_w,10551 +torch/include/google/protobuf/struct.pb.h,sha256=-GnAOvAtCfDXl0qFIepOmDOa3ZPxqOu6iqAV1bWc1SA,42317 +torch/include/google/protobuf/stubs/bytestream.h,sha256=Vdygn2qvi2fPds8z2S_Sda9VN-ve0anwQatNlqLEjyQ,12023 +torch/include/google/protobuf/stubs/callback.h,sha256=TcGWbFtUt_Fld8B6qW0xvME2PFQ2i11KvyjPCSg_Z3s,17352 +torch/include/google/protobuf/stubs/casts.h,sha256=DD9Ys72_FPGbZGMe00tSNpf6iEmgu0bbp8_TERyUA3k,5957 +torch/include/google/protobuf/stubs/common.h,sha256=PAaD7L3Q9-DRKXk_TxIHP-xC5xme5WevFG3GkWIxDs4,7390 +torch/include/google/protobuf/stubs/hash.h,sha256=iT9L2F36Pas6y_b_4C1KNUjBc_xNoFEvawOjDcZrr5U,4165 +torch/include/google/protobuf/stubs/logging.h,sha256=U5XVnuUehma7eGfllSsGjvOkxDDPqX1U3uFO0TmDC5g,9206 +torch/include/google/protobuf/stubs/macros.h,sha256=xgA6ka_Qnru44evTrRZUhUAsdOGRmbMMXlY9Qp8qeSg,4371 +torch/include/google/protobuf/stubs/map_util.h,sha256=gslw48Z_NWnwpOColoNscPOEvrgLptPUQoeqKy0F3sw,31467 +torch/include/google/protobuf/stubs/mutex.h,sha256=JZICrCbny9zVrJAzfPo1-507d62L_syOdK0LkfaZJVs,7262 +torch/include/google/protobuf/stubs/once.h,sha256=6KqYQ_5GcQ9FkOxmRbnxIP-sYVlGkd-ezXbHwMeGblw,2438 +torch/include/google/protobuf/stubs/platform_macros.h,sha256=6KwMHcbzb1opvLRaeiEGSgvZMx7OcHw7bhcE4b4UrBI,5404 +torch/include/google/protobuf/stubs/port.h,sha256=Ikk-pzEZfKRzOAjOZISc7UKIwXAUAlPDQNrc1tju6Gc,13353 +torch/include/google/protobuf/stubs/status.h,sha256=I-Kj0g5HpFKoj9vRqMSEn-op2t0BVLSMYVk4GkhWbK8,8846 +torch/include/google/protobuf/stubs/stl_util.h,sha256=t2pLwjGSXNewitCDZ8fWONiUSxh1ll2SRzkb9CEqwhw,4187 +torch/include/google/protobuf/stubs/stringpiece.h,sha256=oeBCvb0kz8nzZfrp06-be2MrQiRr_4qSZoUaPjCb3Cg,15346 +torch/include/google/protobuf/stubs/strutil.h,sha256=b83aHLoXRD_-mz6uBDUt8oA8n7XNAp7YsmBXVyCjcGU,39854 +torch/include/google/protobuf/stubs/template_util.h,sha256=I7Y0JDCxRt7QO7qq6VNaUOzLSdLc7mtsHfFwyjEVapo,5088 +torch/include/google/protobuf/text_format.h,sha256=Wtb7XlId-ttxnhkCnkRuW4BKwmdmZQlahK8LoIt7WgU,31194 +torch/include/google/protobuf/timestamp.pb.h,sha256=EDggM0jVs1jjncDRNgQs8_U4IVxL7gZf1vOwbUnEdJ0,9484 +torch/include/google/protobuf/type.pb.h,sha256=tnyxTnLAKTOoLzOLTQ0ALZHayqBT3-Pf6Lq_Y2nX4SA,93951 +torch/include/google/protobuf/unknown_field_set.h,sha256=Aw3zZTHoXT9Ka4fzOZ1af7rVXz37fyHPWg9XCXEWZ-E,14426 +torch/include/google/protobuf/util/delimited_message_util.h,sha256=skVF0Tm1QEaN51UJOwULtBwHplDcCdVvbLcB6HPtfVE,5679 +torch/include/google/protobuf/util/field_comparator.h,sha256=tKjBlrc9zO6QYmYqrigDGpuXG63wI22qW-_M9Iq_9CI,11961 +torch/include/google/protobuf/util/field_mask_util.h,sha256=1zuY77eolIgCW9rPq1Gh2UDqWrUNTKWcB8Ym-BV-HR8,11667 +torch/include/google/protobuf/util/json_util.h,sha256=Iw98srr0I9h6RYknRyerdvElK-DSBlRYwCLIMSq906I,8839 +torch/include/google/protobuf/util/message_differencer.h,sha256=zVCxWyY1MdpeFsMCxgWFdfgjmX0qap4xq8TjsVH-zKI,47698 +torch/include/google/protobuf/util/time_util.h,sha256=GtawHprIF3-xP8QarFb4ND9PKSxaFeQihuL6VWuqSho,12512 +torch/include/google/protobuf/util/type_resolver.h,sha256=KrCUC6MPSRz4C8WR8iywfNpS2DII4QxDkHd-c9-JFrg,3173 +torch/include/google/protobuf/util/type_resolver_util.h,sha256=Uy_xMRuvMTAGVTSzOehvaYbvt4Bp8pxNZ6KUaInbY9I,2687 +torch/include/google/protobuf/wire_format.h,sha256=aOMkxN3WBOTJ0UzAThDcm3AyLmKPydx39LyTJp8mf4E,18374 +torch/include/google/protobuf/wire_format_lite.h,sha256=rfsezEBqb2Mn0YppOnbe9SHXaMuGmqcCiwJoDnB7_vc,86007 +torch/include/google/protobuf/wrappers.pb.h,sha256=ClyN4ypU6zgcfwzCYNXj9_5tr3EU-UooK1hgQpvMP54,59548 +torch/include/ittnotify-zca.h,sha256=B0LFdu1bVWrH3uE6bD37JkUy6GmUpapjNhT6vH1a8eA,4007 +torch/include/ittnotify.h,sha256=ubI9PiSnV95_u6xdsevUFQOOXNuzkp_TyWfMeI3Tl2k,199788 +torch/include/jitprofiling.h,sha256=KUCBurzd7j_1CDBWlBm6LGD5ccDunyQJw8SRfSX8wsQ,29872 +torch/include/kineto/AbstractConfig.h,sha256=HOJ3mr5coLvzktxKGdXvRcmAHwy6CF0xXPxYiwvGRgc,4164 +torch/include/kineto/ActivityProfilerInterface.h,sha256=0EC6By3wAchOEjQkH3KeSEx6zNN55nhwTj0BLloN5Bo,4129 +torch/include/kineto/ActivityTraceInterface.h,sha256=GqIs_ETbsFlvokpmirXS2yXi2eDmzodm9vu_4Wf8GKQ,863 +torch/include/kineto/ActivityType.h,sha256=wjgQs-w8QuI4P8A8K7oZLXOYgUK_OvljL_PQv3Pe1VI,5213 +torch/include/kineto/ClientInterface.h,sha256=YByMXn1wrv6ejl60Xz4aBLTWQkSFHs0zyoy0iCZ3cYU,919 +torch/include/kineto/Config.h,sha256=d96t8skCwpsZ9PdRCdMCs36g3yvci2gtsvQVjOMtkIo,11847 +torch/include/kineto/GenericTraceActivity.h,sha256=nB3QDjdKBCTfwpHXDsAIXoy-5wflvrA5FoXU70Iflfw,5647 +torch/include/kineto/IActivityProfiler.h,sha256=JC78voYLsZnEZ1QfaKe4hHr_Z-HWx5lp1j7d2KwZf1k,5199 +torch/include/kineto/ILoggerObserver.h,sha256=GNkFgrkrcCUvJbu7vnHz7nqAy7b4nLDwkm8qJLmSNRs,3229 +torch/include/kineto/ITraceActivity.h,sha256=vG0WEwIgDkoGovUhtxRzPNhzCumA3avNit1GTpH8xbg,3092 +torch/include/kineto/LoggingAPI.h,sha256=lguI_Ou7FauSHElTPiWO9L1813UTWuqTdV1hikv5IQE,600 +torch/include/kineto/MetadataFieldCatalog.h,sha256=_jcZS-1YX7piTozDBZAvAzG5EBSEhN1DLLHpP7k8dTo,9449 +torch/include/kineto/ThreadUtil.h,sha256=pl7vMR9bCinR4wEs9j9dqjKYmqYNegZqcPIxxPWboHU,1179 +torch/include/kineto/TraceSpan.h,sha256=f3hRCWAJD3sFfrAT7rVEa242XXtLz4cmt5hBKUm09jw,1230 +torch/include/kineto/TypedMetadata.h,sha256=f9p9bzwM_58SZsmaB655keuwSMX-dw69Hn87PhHIZcU,4757 +torch/include/kineto/TypedMetadataJson.h,sha256=96MxtqaTZd0Hldba4ekF__dea2bZBYThAY7n0talV6g,6325 +torch/include/kineto/libkineto.h,sha256=hbC4DnpprP9GLhPihZXOFEq74S5FQOxUCV8-a1Pmmqc,4612 +torch/include/kineto/output_base.h,sha256=efLjCpyf8fGiAl2cgJXEUhlWtJCeiWIY6mnxAhNfiWA,2342 +torch/include/kineto/time_since_epoch.h,sha256=ajdgeVJCND1QHhGj3GMjB8JrHqyyRzcTRmfRmfCjHek,770 +torch/include/legacy/ittnotify.h,sha256=WyHVB1ifIqOIvr7OvKeiXHoLi1FRGE_LuT5aGPf-2fM,37628 +torch/include/libittnotify.h,sha256=zA1MPO6UURWLg9TsFl2vb_Pivo3Sg6PsNZXcr31P91Q,823 +torch/include/libshm.h,sha256=NzZuufgNX2-Y5q_APKnvqt8Cj_f3Fbqts07hk9tME6c,1459 +torch/include/nnpack.h,sha256=Y9NhEeYb9-epCjY-a9X0e6xzyM55mXQAoJKR2LQ1Xts,33337 +torch/include/oneapi/dnnl/dnnl.h,sha256=iELxVaEFLqgLTHQeUhQH-6TuMhLi2E56BiFCAReQIig,198902 +torch/include/oneapi/dnnl/dnnl.hpp,sha256=gfV51FrR8vAkz4acaHj6JWk_WSick50Q9lN4u8aOLgY,665473 +torch/include/oneapi/dnnl/dnnl_common.h,sha256=dbUffm_vzMEsvBBdQm4QWiJcKx7dRZD0IL6BQ34MOaw,5905 +torch/include/oneapi/dnnl/dnnl_common.hpp,sha256=wGf9qyugz_u3Pxgl-Nu4ggeUeYdsyc-5Y5xklfP9gNQ,16045 +torch/include/oneapi/dnnl/dnnl_common_types.h,sha256=cLV7IACzWUeWhvSPArh9PItojqmZC28_9TODH79V8l8,8590 +torch/include/oneapi/dnnl/dnnl_config.h,sha256=Sq2ohBlpP9kBKcAfE9Cq9UskrqGgTxm_ACvc93GGE_8,6760 +torch/include/oneapi/dnnl/dnnl_debug.h,sha256=CyO3SZ5Xl83SZ8gBfr-I564GgMhZ1JaEm3WXjjXuUwk,2597 +torch/include/oneapi/dnnl/dnnl_graph.h,sha256=SsWXMGvP337gv4zIqpC9E0HnT0VzJPlNFgJvPDFEM64,34541 +torch/include/oneapi/dnnl/dnnl_graph.hpp,sha256=NLVa1oKxdzyx0qKmcrNtrvTCpNCXfOL8a-qrDzqgU4A,68894 +torch/include/oneapi/dnnl/dnnl_graph_ocl.h,sha256=JBnC4cE6ewlQcKoy7YckAZKAigytXRZNE9WuSuFrcrA,6028 +torch/include/oneapi/dnnl/dnnl_graph_ocl.hpp,sha256=vZSl091yjQ1Msa_rcWBiOlIzgZMVVkn-9xIca7pUw7g,5682 +torch/include/oneapi/dnnl/dnnl_graph_sycl.h,sha256=KY3JaYUBbJFrpvxZJRoekT4kV2x4vCIT6NPm6hpWxoc,3902 +torch/include/oneapi/dnnl/dnnl_graph_sycl.hpp,sha256=1wJHH9FIBZ0KLZuiaPeahsCQ3gEDfuqUDQq1XZd3u2A,4586 +torch/include/oneapi/dnnl/dnnl_graph_types.h,sha256=6iViDwUyF18TRSb1cAQbD-NLedFgD6wfSL9zWyuc31I,17935 +torch/include/oneapi/dnnl/dnnl_ocl.h,sha256=rYttljfhnv0OhEOI4nfiwtid4zYarfu7FXr_PRZNHVw,11871 +torch/include/oneapi/dnnl/dnnl_ocl.hpp,sha256=hGcbJAPhWM9wx3ylJYoda2HukFI2WUpF7vxSj9tOluU,15571 +torch/include/oneapi/dnnl/dnnl_ocl_types.h,sha256=gzwyeH3ueR6be7RYPtbl4fDNDBnL4ZQiCPXJ0m2HN_Q,1592 +torch/include/oneapi/dnnl/dnnl_sycl.h,sha256=5DhTc-YRz9XF1b-24xBhlh-rrI-bEn1nvOG7DsXGFdA,8562 +torch/include/oneapi/dnnl/dnnl_sycl.hpp,sha256=rmfH8ZRAUHL00kItlGhG3SUsikCxwGsn8hafe3TN4_k,13094 +torch/include/oneapi/dnnl/dnnl_sycl_types.h,sha256=ZUBXIn5gEby1GqtBY8Lm3oqWlIUGeJPu995dC9gvRvc,1599 +torch/include/oneapi/dnnl/dnnl_threadpool.h,sha256=pbXjaWA3NAlbtYyQCzR7KyrgcRvCBDiWfRPL3Agro7I,4773 +torch/include/oneapi/dnnl/dnnl_threadpool.hpp,sha256=wmTX4Asi90ryCGSnDIF5enXRRqcFoWsOZn_l0uTzIiI,4576 +torch/include/oneapi/dnnl/dnnl_threadpool_iface.hpp,sha256=LStQLhzz7sIQMEj5crZ7LO1K2DwiauVUJCj32wzi_c0,2752 +torch/include/oneapi/dnnl/dnnl_types.h,sha256=HhRIGxN28ctazqUvv-J1F3oz82l6IJLitIPepQqJS2I,102379 +torch/include/oneapi/dnnl/dnnl_ukernel.h,sha256=I1iZhzwsd7p32MtbRrHJwlQYKPAwi8Y45gggjwl06Ys,14037 +torch/include/oneapi/dnnl/dnnl_ukernel.hpp,sha256=O8dcx-ypO-jCsGPrDLZIwZRhgCWeAG7cmN8UDKayW6s,17933 +torch/include/oneapi/dnnl/dnnl_ukernel_types.h,sha256=afoOCsxR7bdbi-nmOMcyHhM0Hgn7xCK3EV-m_EZjWBM,2957 +torch/include/oneapi/dnnl/dnnl_version.h,sha256=5XpXloUgzOQ0CFJ2goGMjjKb2Udmg00FYtm2KGIER4M,1262 +torch/include/oneapi/dnnl/dnnl_version_hash.h,sha256=1gITer9v0PRzIG6iGAfo5KPHM41N76p2cRsfe0gfiFY,1500 +torch/include/oneapi/dnnl/dnnl_ze.h,sha256=ftY0F_DrWh6xNWngDG_I_qG6GRteX8KYX9Eeo9ihLOw,6588 +torch/include/oneapi/dnnl/dnnl_ze.hpp,sha256=TFCCyZQgLhtZBfixsOkjoqnehyqugf3ar80VsWanOic,8816 +torch/include/psimd.h,sha256=Zz7YehRUM8gHMbAgELTyZqAx1Vo01wJFgN7-XCnaIWY,45758 +torch/include/pthreadpool.h,sha256=59AR1Vu3NwVOYRVup722uF0vorBToA7H8cH9cGNm6jY,171089 +torch/include/pybind11/attr.h,sha256=4uA4aksL1rleTY1QHdV6stXNK2wuDZqJtPYWgF9TImU,26479 +torch/include/pybind11/buffer_info.h,sha256=kISd7GeBFF7fJ4F_mgvM8tFt11-efXKv3tmFfB6QEao,7838 +torch/include/pybind11/cast.h,sha256=VM_bCVNVKcSzP1ywYxLqAIJg1D5xKJtSIYl8nI3I7-0,96849 +torch/include/pybind11/chrono.h,sha256=4HwFFF2iYc27TVPYDqun3qijmF3tqLkUNDFZmMcPU9Q,8605 +torch/include/pybind11/common.h,sha256=ATg9Bt1pwF8qnNuI086fprM4CUTdrZdk_g2HXE1Sf6A,120 +torch/include/pybind11/complex.h,sha256=2SdTZ7U8NPbehlzubs5vw1iCCRHJ_VdOnAFt-UN6cos,3055 +torch/include/pybind11/conduit/pybind11_conduit_v1.h,sha256=Ga99mDEHaQoCUOU94CV6svOUyZ0rIEbL8M24RkP_3Pw,4153 +torch/include/pybind11/conduit/pybind11_platform_abi_id.h,sha256=VUZW4H7iy9vVUzgLdJ1992wl4NnN6sMCWdtZn1Yxd_Y,3991 +torch/include/pybind11/conduit/wrap_include_python_h.h,sha256=uGyR7aUeOB6EEZGfb19TZ8sycP7ebZ2w5xMaIBMibTM,2069 +torch/include/pybind11/critical_section.h,sha256=Yly5WXAyGP5y9y-X0DjyGAH2dtEqXuWnI-TrnWMHdYk,1610 +torch/include/pybind11/detail/argument_vector.h,sha256=ynrkfGPWxXtAtkxiDFO-oEC-miPR4psqn_ZHvZT5Jpw,13896 +torch/include/pybind11/detail/class.h,sha256=kQh60bPnhfmDl4T21xAW_PCdaCLl5NBRGKHQpP-Ou88,32465 +torch/include/pybind11/detail/common.h,sha256=pFX96XKI0srLULLSEoIGTkNANJNS_As74iCOYeVK1i4,63589 +torch/include/pybind11/detail/cpp_conduit.h,sha256=nGhkbkRrEH9pMEqxr3tXBX74-iSyLDCOsEavKW9Kau4,2545 +torch/include/pybind11/detail/descr.h,sha256=iyJaww3K6gVA_lxeg69vNZyN43XrPVtyUbhmXMBiVFk,8228 +torch/include/pybind11/detail/dynamic_raw_ptr_cast_if_possible.h,sha256=1qWaNlH6-j9n5VoEF70zCOrNz6JpFLFu6gqdYtNFL34,1176 +torch/include/pybind11/detail/exception_translation.h,sha256=MsiLvxqQF6Cs86EWkmA9dU0FSc7SV7VOGPcTmNdHqwc,2593 +torch/include/pybind11/detail/function_record_pyobject.h,sha256=rrPoj2Cx8J6WeQtvGkK76H3zPUXbL0mbaGNPHNxZVzY,7772 +torch/include/pybind11/detail/function_ref.h,sha256=iwcd4UrWGPcBFfIOvkS3C1JCsXa7wHEKyLhCiVpJjrs,3729 +torch/include/pybind11/detail/holder_caster_foreign_helpers.h,sha256=AmAlOCBsxaBPlXhmo8Tpe34UQsiWjFPW4XTrbGRx5EM,3927 +torch/include/pybind11/detail/init.h,sha256=1DhmSJsJVGuV0lHfNMBAFbSoJHTi84pkvCBzMlmo8fQ,23967 +torch/include/pybind11/detail/internals.h,sha256=Xu-mty5DUnej51N4WX4TwpWu-2_40JQ_oiIO2e-1T7w,45731 +torch/include/pybind11/detail/native_enum_data.h,sha256=0wHHqCuCqHwD65sBzq-__FM0e5ADgh7EJqbLDTZZ0ZU,8403 +torch/include/pybind11/detail/pybind11_namespace_macros.h,sha256=YKXjWlsIB9DMFC1K8pjVyYKthPld379l9U42sUDdunc,3574 +torch/include/pybind11/detail/struct_smart_holder.h,sha256=GDBbztrkeS4yBH1tjxsWtuanIBSq1Wgn7gual2yivsw,16425 +torch/include/pybind11/detail/type_caster_base.h,sha256=6p3GUvP10Jsax5lNAPLD6oLGx2PB0hjFwoUZVvWTF48,72331 +torch/include/pybind11/detail/typeid.h,sha256=jw5pr9m72vkDsloT8vxl9wj17VJGcEdXDyziBlt89Js,1625 +torch/include/pybind11/detail/using_smart_holder.h,sha256=sD2hYVl5H4u8UImqmi5ST9oftDQUPkJ6yR3qR3leQkQ,540 +torch/include/pybind11/detail/value_and_holder.h,sha256=Et3CYzOcPru_375pwjZlsMVsB4PBnzX3wfLZ-uDKiv4,3733 +torch/include/pybind11/eigen.h,sha256=-HmSA1kgwCQ-GHUt7PHtTEc-vxqw9xARpF8PHWJip28,316 +torch/include/pybind11/eigen/common.h,sha256=dIeqmK7IzW5K4k2larPnA1A863rDp38U9YbNIwiIyYk,378 +torch/include/pybind11/eigen/matrix.h,sha256=R3Pp9BwEpPKCQcl6AeOXQBgeRqKJVmQ340D7ggG1DcY,32590 +torch/include/pybind11/eigen/tensor.h,sha256=zm0OHh5rjJKWk3R01D3jy-PFCsatkIjf_GA3Ph1EyLQ,18640 +torch/include/pybind11/embed.h,sha256=AG0VqXFCbGTIM33qVQEvsUabZWbS7A65qBAG1ALm8ws,10226 +torch/include/pybind11/eval.h,sha256=bp6HB1dO_kYLR5xrp_MCYQfVFz-98EFMBJSX_5erxwg,4800 +torch/include/pybind11/functional.h,sha256=EfFE1xyyWOL_DJSVvdvxgOzuFfa0vEc7ILEostyceq0,5111 +torch/include/pybind11/gil.h,sha256=Pu3-5yGpOBIYIzINMhXBl-e0pufAHD24kFeHJkjx8tU,6945 +torch/include/pybind11/gil_safe_call_once.h,sha256=r6G0QLdxC6NcBx0M6Y5yt0AfpbglehmXcKL5j_3SRgk,13103 +torch/include/pybind11/gil_simple.h,sha256=AuO9mC1devdjTnXOe0aJGsnJuSC3nerWnG17HVQQX9k,1185 +torch/include/pybind11/iostream.h,sha256=es9LWyzq5_e4bVza73ty2qSgnTVIxPnZY5zGeZXpxYI,10438 +torch/include/pybind11/native_enum.h,sha256=i8tivOvoSwdvXS0tSV80AmyiuNhT3fpvZLbEsTMqGGA,2723 +torch/include/pybind11/numpy.h,sha256=qbuh8JdqzX51l9rvGr05ih4LgSE3RyeM_-9rMll5_uE,94985 +torch/include/pybind11/operators.h,sha256=224RoAXcv1la4NNY9rQ3aD_AeC8S9ZKx3HVK1O8B4MU,9103 +torch/include/pybind11/options.h,sha256=qXvmnj--9fZSp56NYefnB3W5V17ppHlY1Srgo3DNBpw,2734 +torch/include/pybind11/pybind11.h,sha256=ujI7g175HrhTQgV9sjU8usPakEDqyfC4OJGjzmaRGnU,181286 +torch/include/pybind11/pytypes.h,sha256=x03QT7M5onLMclw3TUbt7wX04hOJbacMkAFdzZ_aMS4,104244 +torch/include/pybind11/stl.h,sha256=6oO0ogJ7EGM5P5VG4dMsZjDKnr1wIuCRHcAhDkJZyc4,24742 +torch/include/pybind11/stl/filesystem.h,sha256=wg4yEoed6D4hUDpzEhBwdSHFxws21XgWIQkrIyw_3Zg,4074 +torch/include/pybind11/stl_bind.h,sha256=qdimHwZxBE4PO8SgBjx9YayRAfP6qdHQNb4LMdyJ8t8,30067 +torch/include/pybind11/subinterpreter.h,sha256=OjHrNDbUC0A0W0E3dcebEs7Q_ILnPVOTVZBWGcH8CPA,19423 +torch/include/pybind11/trampoline_self_life_support.h,sha256=-TX9w5TxI1XX3AG255lMLdiCyR-dZkM321wFsedynx8,2673 +torch/include/pybind11/type_caster_pyobject_ptr.h,sha256=H7pKBYTvUlibiJQEcKmeAkygSQwoCkuIyukNSDmVq-U,1929 +torch/include/pybind11/typing.h,sha256=6HLfSNTk29Kzx2q7w7_sPg_WZgXY_NJjPPrEUQ_QF2o,8785 +torch/include/pybind11/warnings.h,sha256=idcBNK5eEXxYBfPeVuycLxcgMrKuvRzQI33BapJ8G4g,2368 +torch/include/qnnpack_func.h,sha256=TtDF5mhpFcTbzvLUYlHV33KG2BkVZELMfdJa8dKN6eo,4400 +torch/include/sleef.h,sha256=tN3wkx-sAV38qn7Sq0Usf7VLFe2QitPFOItkQp0dMew,269286 +torch/include/tensorpipe/channel/basic/factory.h,sha256=ymil_LBc8GItwEFwHfBAuQNp46y_7T3Ll4qnvJ3kSvg,717 +torch/include/tensorpipe/channel/cma/factory.h,sha256=MwKFZJViyVujWnLo4RyfncH50bJSJx7J_gx7hoMxbnA,713 +torch/include/tensorpipe/channel/context.h,sha256=wNHghkQ66kK3UmlgjQVTjzLN1mFIVDQM_pqp6IwHmP0,3955 +torch/include/tensorpipe/channel/error.h,sha256=HpiFTA5aFd7omH5ffWJ_QzRVfmzk4GyE3mEZA_KN3Ho,1032 +torch/include/tensorpipe/channel/mpt/factory.h,sha256=4NYX8S-rdFBR9GDWjgVwF0fuE2k1WhTs7-z8XKYJAiE,900 +torch/include/tensorpipe/channel/xth/factory.h,sha256=oq9LF99KTTer6ZkP2QW2u6a7x4aOBXO3fIR4iTbI0iE,713 +torch/include/tensorpipe/common/buffer.h,sha256=vZhzGJbP7wGrwFQQaY0dnYf_PG70tPEqOaX7D8kvf6Q,3726 +torch/include/tensorpipe/common/cpu_buffer.h,sha256=dWjm6FWlfNu-Gye6ARmHgWxWwOJYEAoHvgo2FwR1AII,695 +torch/include/tensorpipe/common/device.h,sha256=qyWkJ6NhKKGPqDSzXdDxzHyUkNlYX3OMM-wxTHlgACs,1903 +torch/include/tensorpipe/common/error.h,sha256=sUmM9D9IZBstFv8aV27ZLAxDQ2d194w39-auvOR3ZCc,3382 +torch/include/tensorpipe/common/optional.h,sha256=Cg8ztuIvxC8ckWyM1giXZhoIsYCFGIopRQ8wQd3f17k,382 +torch/include/tensorpipe/config.h,sha256=bAyHYIbpM0M0TMPiTcaFvcWnFCfDodz_rqGZNi_kZck,605 +torch/include/tensorpipe/core/context.h,sha256=eUPwjLU3Voc-puVW8YZ03-utlUh1E2pmLrzpmgV8wZQ,2722 +torch/include/tensorpipe/core/error.h,sha256=czqGb_5R6zz5hcj1BrXZN3D04d8ANt49nbEjpsc5sow,1215 +torch/include/tensorpipe/core/listener.h,sha256=NoKRYhODFRTb2oifps5cxRdYoIe6l5pLqhS_m5xHMFQ,3182 +torch/include/tensorpipe/core/message.h,sha256=NylQKLbpf-IKhyNOzOQBUe2j4pVXjJ9Zl0CBruK8hp0,3139 +torch/include/tensorpipe/core/pipe.h,sha256=FzxISVeZVDxVxgLNyz8N4rcqg-En5JYJK3jMDAdDNOM,3226 +torch/include/tensorpipe/tensorpipe.h,sha256=5qmmXu8SyMq_sREiWZ5GljM-glz-pl4bJSeMaRQLh6U,1703 +torch/include/tensorpipe/transport/context.h,sha256=dD4NNcqRe1jvzHAVPYlL_koSf0oC6q3u-ZXIGyqHoQQ,2899 +torch/include/tensorpipe/transport/error.h,sha256=h86Nl4wdVPCBcB11mL630XYqSNzAnavmB2oOU3WwVMw,1173 +torch/include/tensorpipe/transport/ibv/error.h,sha256=iVqKZZU6-Mwxek1SaGohndVYPtL19Ei5fbv8X2b27oU,1174 +torch/include/tensorpipe/transport/ibv/factory.h,sha256=uAAKRzbF6MdDTikr3gCTKXJxGS5sfBjyHcZ4oOCrU9Y,719 +torch/include/tensorpipe/transport/ibv/utility.h,sha256=Yi-VEfXhUG39nK8PMXZT9_jEEO5o3JamDb55besOXw4,823 +torch/include/tensorpipe/transport/shm/factory.h,sha256=HcaaTa5gnGqT0Qz2LlsLttU9DYkLYD2XJ5IE2m_ftfQ,719 +torch/include/tensorpipe/transport/uv/error.h,sha256=QsPw4R0VuiMJPiU4bp2QIYw9A40Uyb-F3J5efL88yaY,970 +torch/include/tensorpipe/transport/uv/factory.h,sha256=D3i_rOQ2F31pDo6iivssNX9q2GlmPcxRQLx3kv-UYTM,717 +torch/include/tensorpipe/transport/uv/utility.h,sha256=5Z_QG64aU9n-yMSMKepKBlUI90htLwHBIcZhJrn92Mg,1303 +torch/include/torch/csrc/CudaIPCTypes.h,sha256=qsqVbMeUqs5FMT02n7hsDxpjxLnBrXnjbn6xgAEmTh4,3651 +torch/include/torch/csrc/DataLoader.h,sha256=0lLHCpmBQ9wnuXLOIH_Ok-t1EQHsX9-IgRPmrYTzfL8,476 +torch/include/torch/csrc/Device.h,sha256=1EXVg-eE46tTIz48aTrijLM4K5tH_b80YIWb4ea2sG8,767 +torch/include/torch/csrc/DeviceAccelerator.h,sha256=kK0O_HBZNVYKHKEB7zCW9c2IB03enTyLR_Q427Kp47Y,430 +torch/include/torch/csrc/Dtype.h,sha256=dAFguxbWWzJ_qG2d3pjS7Ch0pCUVGQZNXou6K9eyrh0,1128 +torch/include/torch/csrc/DynamicTypes.h,sha256=LFNtoH9z3wftoGGyS0lNCgmC4vEAFss3S8-mz3UONWY,1316 +torch/include/torch/csrc/Event.h,sha256=dPK_5QQdnC5kCVrgEBPUfk7aU1Li9KkkjQ6KhZm6VvQ,969 +torch/include/torch/csrc/Exceptions.h,sha256=tUo98K-t1Fv4XuZK2icCWw7TNiWyW3R5_5sIRHME4tI,16256 +torch/include/torch/csrc/Export.h,sha256=cqQQF3wDc-5-WHNjcnuu6fEGxNBDZvqGV7xfx1C5fiM,411 +torch/include/torch/csrc/Generator.h,sha256=PzmUgDGZY0gwyoMcJibf17K3pTJzdlyvrrmVkCb50LU,1335 +torch/include/torch/csrc/Layout.h,sha256=NB5zkGBd7Grp7USYFjF1zYqkXJH6FNEMrwPuCRUdyc8,840 +torch/include/torch/csrc/MemoryFormat.h,sha256=leW7WY12ZeRCjgcbTGhRw1hHEyo5MjP0mzY0B-9Z75s,936 +torch/include/torch/csrc/Module.h,sha256=xPZ6iAnFOpb0kJKIkvSamoVaepAvN9nIp8qDnL1vfpw,355 +torch/include/torch/csrc/PyInterpreter.h,sha256=FwV8NJX2vHVvAgSH9pQKqq66z67jwZjciKcipXFbyjg,647 +torch/include/torch/csrc/PyInterpreterHooks.h,sha256=G-mNkssZIDAX75WkP0z732GCIkqdw29pM0Opp3R_Zmk,596 +torch/include/torch/csrc/PyObjectConversion.h,sha256=NoEF7b6gM4Xo_DUcbCjN681YmEIZLh6pMD9OfsqAxnA,2899 +torch/include/torch/csrc/QScheme.h,sha256=X-6XDVHnS9nPbqA3sbH4iulEe38QurprXBRIXF5puRQ,862 +torch/include/torch/csrc/Size.h,sha256=GG35TADU4Fb5LsxfMYG2S1li_9unhRLFcfMiQ41KiLY,730 +torch/include/torch/csrc/Storage.h,sha256=2_h8Ndwai_c3HhWZTeEoBEUVcj6vg63VOS6m-jy9JXY,1701 +torch/include/torch/csrc/StorageMethods.h,sha256=wdY_jcfOWT5HwMR2634Q7id1n4COsYf-hJiJxPUPr_Y,386 +torch/include/torch/csrc/StorageSharing.h,sha256=FDdRsnDvPPBWeBpuSztbEEC3UwZkprcmSIcK0BeC65I,393 +torch/include/torch/csrc/Stream.h,sha256=Gw3551bYgnkZftehu8yYwhNi7QVAL-VNhxu8iAtmT-0,1038 +torch/include/torch/csrc/THConcat.h,sha256=t4GpgRJv-bY0ccAE0AgICWQNamhXi3g_EDkJOWVpA6I,945 +torch/include/torch/csrc/THP.h,sha256=5gweWqAcY2BZqsPj1bp0at5P-XYyEWN4MM5L2qRBolo,763 +torch/include/torch/csrc/TensorIterator.h,sha256=hpvHkxhM-N3MDLcc6IiS9Bqi8o00UPOkIdj8Elz55uY,400 +torch/include/torch/csrc/TypeInfo.h,sha256=r7tPAL63xDEPFo8x6uvHtgODFHXjhXJDzRFAUulNFsU,819 +torch/include/torch/csrc/Types.h,sha256=sEsjWCg6HiCzV10np0kjdl6YWmjcpU0biDbJzBQGQ5c,417 +torch/include/torch/csrc/acc/Module.h,sha256=dFVIrVAvxN9Uk4QybsLW1QQZsincqYLEbXsi9fg8FD4,428 +torch/include/torch/csrc/api/include/torch/all.h,sha256=vLItftGIL4V3nBOaxoQU5X15IsEXZX9RAMptAQdtiYM,843 +torch/include/torch/csrc/api/include/torch/arg.h,sha256=BL9aGQ0jh03qjO-ktgWHFxTcukzzbsVZlat4G-lSl6s,1681 +torch/include/torch/csrc/api/include/torch/autograd.h,sha256=c2Z8tuuRXj_DwlwBBYHIjDjaHbDjGcA-L6QqrPNy9Yg,426 +torch/include/torch/csrc/api/include/torch/cuda.h,sha256=iEh4xDeeRRMgYfLIkDNu9Q8crqvLJ2CbNTRj6MsNd1s,987 +torch/include/torch/csrc/api/include/torch/data.h,sha256=LQstdyTLY96Iw3-alKqvTgzfeK7McbI5ae83zGoh41E,551 +torch/include/torch/csrc/api/include/torch/data/dataloader.h,sha256=LKWckxETIn2rdHCN_belMApFqkzs-dQfjvZNvUWrek4,2151 +torch/include/torch/csrc/api/include/torch/data/dataloader/base.h,sha256=jBcbswB5JpHaJJ6gn1opeXmZzLF4QUn4ySBcWEQ1XD0,9475 +torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h,sha256=18vlVC47nJ0mCpJtBCZwdKL9bEteU_SYYUn6TrUdVpc,2587 +torch/include/torch/csrc/api/include/torch/data/dataloader/stateless.h,sha256=HByZb45MUrHOb0q-aLcj9aPq5JnpPByCMtlu2An3-Sg,3000 +torch/include/torch/csrc/api/include/torch/data/dataloader_options.h,sha256=PbZabfCzPYj6WCCX1vUkybqdiYPdk4uBGwF-h7tPnns,2451 +torch/include/torch/csrc/api/include/torch/data/datasets.h,sha256=tir-STDUqaajiGy5-x_bwDoOc4PwlvmwadAITiB82a8,543 +torch/include/torch/csrc/api/include/torch/data/datasets/base.h,sha256=Cjw4p8Vo-rca61JdGvm9Gvum6eYjV9G65WJtIH6UrcU,3430 +torch/include/torch/csrc/api/include/torch/data/datasets/chunk.h,sha256=8z9vSRyWbUTzFt0pZ_uRRLN7EyqOoWNTFJx6hGHy89M,19479 +torch/include/torch/csrc/api/include/torch/data/datasets/map.h,sha256=DAwZ6ieQyoHNZrkHBaGEmTbYPt4XtDeS4XISGl6OMEM,4326 +torch/include/torch/csrc/api/include/torch/data/datasets/mnist.h,sha256=YRPvU01q1ywMPAQjrjBaNo6KUzSgW9uvuNPEpfDtQaE,1483 +torch/include/torch/csrc/api/include/torch/data/datasets/shared.h,sha256=dLHvC69hde_HijNDTWAJ9jYMTk_OAX9GelxNjr_goMc,2849 +torch/include/torch/csrc/api/include/torch/data/datasets/stateful.h,sha256=ltL0s1nqziimtGBnUpEJffAeInVa2KwWe0jxuTcvcMc,2488 +torch/include/torch/csrc/api/include/torch/data/datasets/tensor.h,sha256=5GaBd5nOL3lvJw5po94pIRkGZBv1OFC_Am8RX7gUXAA,1185 +torch/include/torch/csrc/api/include/torch/data/detail/data_shuttle.h,sha256=crrKlaIf0Y7nvvN1qiU7vNdthyS7wH5YTQEwE7IUE0w,2839 +torch/include/torch/csrc/api/include/torch/data/detail/queue.h,sha256=3PbwSIlInczgyEu4kzi1TNK9RPA2Ipc6QI8QT5PmDhg,2709 +torch/include/torch/csrc/api/include/torch/data/detail/sequencers.h,sha256=408hk6loMFpzN9QVZdbyGsv0mQ-m63m_86sUawhH77U,4694 +torch/include/torch/csrc/api/include/torch/data/example.h,sha256=s_XXP010mJyyotdSSY0lIUsWJgyqCALdfXgiPj9OJNA,1543 +torch/include/torch/csrc/api/include/torch/data/iterator.h,sha256=ztvL0ZIktgE9uNVqS32HjQ0yRwckT0h_A3KS3k1EZQI,5559 +torch/include/torch/csrc/api/include/torch/data/samplers.h,sha256=EJcqg_L6zv1LbFAlpkytbkGTZA6pGGIAbDc1y_jeDUQ,572 +torch/include/torch/csrc/api/include/torch/data/samplers/base.h,sha256=roqyYGAFtgoLNPaVbQo0FlQ-f7Hyeg1IYUJ1eCMV5Xg,1420 +torch/include/torch/csrc/api/include/torch/data/samplers/custom_batch_request.h,sha256=Go9M3TfetFP9DqO_VLJh3Q7IHWz67v7opPOTFLQMUrQ,760 +torch/include/torch/csrc/api/include/torch/data/samplers/distributed.h,sha256=TsFvLnW8X24dJArLqcXrxDvmAAn658vReUk8m2YG56s,4332 +torch/include/torch/csrc/api/include/torch/data/samplers/random.h,sha256=PBl9BsQzkJ4iVIWCHxyWjz33mpP6PKAXNRpIFuL6Bjs,1716 +torch/include/torch/csrc/api/include/torch/data/samplers/sequential.h,sha256=NDKQhS8I9qqAZJj789_KnUBMkIZjOijEUe3uKJcGGR4,1448 +torch/include/torch/csrc/api/include/torch/data/samplers/serialize.h,sha256=nubpsLpxYasgAUxYhHQI3F0aXeVO71iyVftZAQKUMsk,911 +torch/include/torch/csrc/api/include/torch/data/samplers/stream.h,sha256=1KrRV4D5s25Zyk8TG_2hlGA6gjWFm2pESGO52UHw1jg,2227 +torch/include/torch/csrc/api/include/torch/data/transforms.h,sha256=-7PZ3J4Sl8IGwJkCtsa3gwyRIRwAakqh0XYCjLIRr30,476 +torch/include/torch/csrc/api/include/torch/data/transforms/base.h,sha256=zy50TQRf0TfljUSw97T-uBt3JOsqpTX29QOT_Tyydns,1833 +torch/include/torch/csrc/api/include/torch/data/transforms/collate.h,sha256=6ixnhJX-HgRWGYOxW7TlRt0jfTHEJ_f9k9M6SuoXVoM,1317 +torch/include/torch/csrc/api/include/torch/data/transforms/lambda.h,sha256=oRuX2N9-kb-ri0kl-nXUWFA2Z-ndJ03W7p34b78mpL0,1913 +torch/include/torch/csrc/api/include/torch/data/transforms/stack.h,sha256=e8RMeA2_J1Ee0CBnJVpvGC6oR1YUJzZJlhRb7lgvCUU,1628 +torch/include/torch/csrc/api/include/torch/data/transforms/tensor.h,sha256=uT8NLQGuIK7cAnu3hqZ1MwE9P5DZwKjlt6dayOzrMjU,2677 +torch/include/torch/csrc/api/include/torch/data/worker_exception.h,sha256=cReMfofGMxB08LBOyvVQj_u7E4IqMN9W6ZTPgw7jI2M,1373 +torch/include/torch/csrc/api/include/torch/detail/TensorDataContainer.h,sha256=Gf65fgWWtL0d8WZ-sRFJ8Bw95DTSgS6RR0m_Y_9ym7c,13206 +torch/include/torch/csrc/api/include/torch/detail/static.h,sha256=slXrhsYFnm2u6o3WMwIwn2olNGwC68waixn1TGf8Xlw,2347 +torch/include/torch/csrc/api/include/torch/enum.h,sha256=4dLXAs573lv-RY-KA9SoVS-fZjsMPTtpQjsIysif-ZM,7704 +torch/include/torch/csrc/api/include/torch/expanding_array.h,sha256=mJgJDI08qavPtouHQwo9ZzD_Al8oIFnDZdwkKYwXOBI,6927 +torch/include/torch/csrc/api/include/torch/fft.h,sha256=UhE-r-y8A3qsxDf8xSu1zXKXfOkXBMzM1Jy7mMDrzzE,12358 +torch/include/torch/csrc/api/include/torch/imethod.h,sha256=9jhzS5dOBFwnbq-1_a7C-coPinIrrkssmZfagWPpyHA,1994 +torch/include/torch/csrc/api/include/torch/jit.h,sha256=fVuU6JSqhzY-GsSoOZf4VHgKtnkHbGFo8KPeOd9kTEE,1142 +torch/include/torch/csrc/api/include/torch/mps.h,sha256=HrGBge68iJlcBjFVYOCQ0v6V-_kIpAiJ_pwwPAro_E0,1448 +torch/include/torch/csrc/api/include/torch/nativert/ModelRunnerHandle.h,sha256=pM8dpUHKtzlOjWp8Dhf-6GRCt_AFhfdbqDWSTJyy5DI,1580 +torch/include/torch/csrc/api/include/torch/nested.h,sha256=VjlIslutEY3O4RQUM652WoldCaH-nNMa_x0dUd5Hj0o,3027 +torch/include/torch/csrc/api/include/torch/nn.h,sha256=Y6_mVoiLIHyzr4RRQ5LYIA9MxJOmTPQn2tFbvrYXcZk,505 +torch/include/torch/csrc/api/include/torch/nn/cloneable.h,sha256=hYgWBoO_CdiI7TIkKvKQBc8uzgqpx7_o--jrV_cq-sU,4155 +torch/include/torch/csrc/api/include/torch/nn/functional.h,sha256=Yebih9a14mooUre0-lyB7AbuSM3zQI54o5hy8j5qXyA,896 +torch/include/torch/csrc/api/include/torch/nn/functional/activation.h,sha256=9IvmhFpWJnloBuIih2FlaUOz9ziGp1G20eUwL8YZtX4,30081 +torch/include/torch/csrc/api/include/torch/nn/functional/batchnorm.h,sha256=thPydHdHkAH9GiVKLJ6rBiCnjeyxNh1jKiGG5V5Ntc4,2269 +torch/include/torch/csrc/api/include/torch/nn/functional/conv.h,sha256=Tls9WI9J-iSMRhYGmTkzrPoQZwW7bvk-N7MxU1JfIbM,8373 +torch/include/torch/csrc/api/include/torch/nn/functional/distance.h,sha256=rEP1qHLYXatcmYEMAWWHsjVAumgwF1IGiRBk5c-NbrI,2753 +torch/include/torch/csrc/api/include/torch/nn/functional/dropout.h,sha256=3sJbPO0E8TaifvfoJyTZxTC0KDGi6xydUTVT2r4rSLo,6790 +torch/include/torch/csrc/api/include/torch/nn/functional/embedding.h,sha256=-n4IK-tZPGJmAmdxWyT-gqmzk0clttDfsm-HAhrIciU,6613 +torch/include/torch/csrc/api/include/torch/nn/functional/fold.h,sha256=lLbiMxGeCA1dJP3PIAUVOAfLQAzvM1f-Zw2x5Hp2gjs,2990 +torch/include/torch/csrc/api/include/torch/nn/functional/instancenorm.h,sha256=zIIIVJG2Bzo7FZyED4D0SWWIV6WovO7cbPEOryUohX8,1809 +torch/include/torch/csrc/api/include/torch/nn/functional/linear.h,sha256=ugg28fvjDzk2lgYne1UVM4csQdQLUAGda3ezZuHAkBo,1015 +torch/include/torch/csrc/api/include/torch/nn/functional/loss.h,sha256=Z5tmLVYSQt7Zp7IL_4crceVtUL88rIIBdaXnLhZDT10,32095 +torch/include/torch/csrc/api/include/torch/nn/functional/normalization.h,sha256=s5cxNP6BF1UiO40t8oBV1dIT_h3UiRH_zyjYKFH-cSs,6225 +torch/include/torch/csrc/api/include/torch/nn/functional/padding.h,sha256=5gYWsnKjj7ofCPHkjYPpJ-SynLBJud8EAjaDijQCNTg,1928 +torch/include/torch/csrc/api/include/torch/nn/functional/pixelshuffle.h,sha256=pjM2FRB74Vw2dZWre034KB4LsFPUP-BBoclCa9mYTOU,1547 +torch/include/torch/csrc/api/include/torch/nn/functional/pooling.h,sha256=v_5wJJYLo5db9KDb7SyS0wd7ikfzWwMkb5eVcoCrZqU,35664 +torch/include/torch/csrc/api/include/torch/nn/functional/upsampling.h,sha256=gbZ6HgiDysvMmz9IqOeZQwGT5LB23IYRfxqOVg5dLNU,10982 +torch/include/torch/csrc/api/include/torch/nn/functional/vision.h,sha256=HjnFEeYjeBGo7xEZupgryWYaeprbBRpUS0uDO7HI2cw,3833 +torch/include/torch/csrc/api/include/torch/nn/init.h,sha256=TQ4dS3iK_g_lZSA6H3QRjWHCU8LD3bAMdrV4mT1qv9M,5173 +torch/include/torch/csrc/api/include/torch/nn/module.h,sha256=OtPw-89lpEQPEZ6cO8rW6_rW4NjEVvCFUXoYA5-BV0M,27243 +torch/include/torch/csrc/api/include/torch/nn/modules.h,sha256=UZxQ4tAgNJ5MB824qRZUVwVBRscPY9h3fslYV3b0H8Q,1543 +torch/include/torch/csrc/api/include/torch/nn/modules/_functions.h,sha256=lfmzcEi-3tq_8YKuvNcrCtrPC3UKVtoOEy0G3AqlGoY,910 +torch/include/torch/csrc/api/include/torch/nn/modules/activation.h,sha256=03i8F0M9vuuxzcf3BqAzwpn-GEaEBMBdWCvDmDib0TY,30571 +torch/include/torch/csrc/api/include/torch/nn/modules/adaptive.h,sha256=gzmhHN6jsfv38PJUZMB5RnSkYpFufVcy1hH_dTq14IM,3771 +torch/include/torch/csrc/api/include/torch/nn/modules/batchnorm.h,sha256=v2fGhpWLroZu-HNmj0GqBEv3CBeabjj0KHKzI5BnXOo,8479 +torch/include/torch/csrc/api/include/torch/nn/modules/common.h,sha256=jVT0e01SXVxuvGpfauX-sjoeFZJImpZ-HvtEqhg0XzU,4602 +torch/include/torch/csrc/api/include/torch/nn/modules/container/any.h,sha256=F01wtQcvmgLe3S0o3iYNVpeIA4OcXAV8eytwvqA2KBA,13712 +torch/include/torch/csrc/api/include/torch/nn/modules/container/any_module_holder.h,sha256=S-IMNkIUdSLtUpRD9NSSD_JnjDuXgwO5QUNqAzzQSUo,5250 +torch/include/torch/csrc/api/include/torch/nn/modules/container/any_value.h,sha256=4WmDto4MkFYybDAfv95JVHZ3fURvguwuWV890TzyHTU,4392 +torch/include/torch/csrc/api/include/torch/nn/modules/container/functional.h,sha256=EGxMBeX0zHtKL6wWek3-3FGhVMlG6Z1Ku5ncqfZikwo,3597 +torch/include/torch/csrc/api/include/torch/nn/modules/container/moduledict.h,sha256=iBorAWRt_qNevxSW_1N74gS-5VCrz3lY8_mG1fRJH74,8676 +torch/include/torch/csrc/api/include/torch/nn/modules/container/modulelist.h,sha256=LDi6WBqvIQgDmoiITzkXw2x0iNp54mOOk7YCv8X6F-A,9195 +torch/include/torch/csrc/api/include/torch/nn/modules/container/named_any.h,sha256=b3TYOyXtnx1PtDUfP03XZDnhdmj5F5xTcfq7n_9PhSc,2696 +torch/include/torch/csrc/api/include/torch/nn/modules/container/parameterdict.h,sha256=22O3j4R_oC6MJAmE9iWNffx9Pb6atCVK0-GD6yQDJv0,4711 +torch/include/torch/csrc/api/include/torch/nn/modules/container/parameterlist.h,sha256=lmso41ZtXUOoG80s_lJOWPFaBpbdK7SU-fm4tyxeXcY,5800 +torch/include/torch/csrc/api/include/torch/nn/modules/container/sequential.h,sha256=bb75yxy9DuRtuhb_U3aYDp1G-fYPoyaJRm3PeWMm2XU,13988 +torch/include/torch/csrc/api/include/torch/nn/modules/conv.h,sha256=EpGiG2mprFb7oocnUc7N-r1BERpm2tllnqZNCD1RRjA,16513 +torch/include/torch/csrc/api/include/torch/nn/modules/distance.h,sha256=nql9Y19QBsW032P6_RVhGmfq3NYtvKcLIqSjc-5IM8w,3310 +torch/include/torch/csrc/api/include/torch/nn/modules/dropout.h,sha256=Alr2vWdC2vQ_P3vAFwXqvGYoG9ENxpmCQhzoR8sN2Xo,6654 +torch/include/torch/csrc/api/include/torch/nn/modules/embedding.h,sha256=nuJtlx1iXIalox9jWBJViUIvofZ2JgbiAFve00alXMI,6309 +torch/include/torch/csrc/api/include/torch/nn/modules/fold.h,sha256=czUUxQhErjSun_9F0cQ3cbYjTJsWKzyT8eB_AluM1IE,3076 +torch/include/torch/csrc/api/include/torch/nn/modules/instancenorm.h,sha256=brdUwQ8jDoyuLbS5y8KxnM7NJyKnWs6mJ7IukdHLhtU,5768 +torch/include/torch/csrc/api/include/torch/nn/modules/linear.h,sha256=crO-tpO2wneJ-s9DHFN6h8jkoiahwt3nvjHZtAh4pak,7491 +torch/include/torch/csrc/api/include/torch/nn/modules/loss.h,sha256=QVsU0rm3VxGWPYcH3uS61ed_oJm6s6yKx_8vDOoZ90I,31230 +torch/include/torch/csrc/api/include/torch/nn/modules/normalization.h,sha256=GSvC2nI74qLTUt18BXboGZlfd-SyispJO09d3_6orLA,7185 +torch/include/torch/csrc/api/include/torch/nn/modules/padding.h,sha256=g3RTBTVaJz-8Byd0QaDp7GCXihIh1Sr7ZhjKjKo_90I,14600 +torch/include/torch/csrc/api/include/torch/nn/modules/pixelshuffle.h,sha256=BDmKhAvvlh3XMIBDJCcLwxKZJGcsGj8A0z6nk2ZE8Sw,3363 +torch/include/torch/csrc/api/include/torch/nn/modules/pooling.h,sha256=uikBjDJjHp3v9Ge5WWgF150NIEGEMtAgBgkZjIBxx-s,29894 +torch/include/torch/csrc/api/include/torch/nn/modules/rnn.h,sha256=BF92Lb2iX0HigEyM0mYpms2Yylp4zteTqnvPoLn48K8,13702 +torch/include/torch/csrc/api/include/torch/nn/modules/transformer.h,sha256=VfumjzK-K-ynNtgVZ3kNR81AX17LnQw--a69DTBZoS8,5576 +torch/include/torch/csrc/api/include/torch/nn/modules/transformercoder.h,sha256=uDb4SbKH7TAVu4rQIUtqq9K3BmB24dcL3TSshrK73iY,5455 +torch/include/torch/csrc/api/include/torch/nn/modules/transformerlayer.h,sha256=Tt9KT0wTvMiHiaAUfd0JyAhbAheyKiORKYDxRiyoLmA,6657 +torch/include/torch/csrc/api/include/torch/nn/modules/upsampling.h,sha256=4-8Y2-yx6CYi6FMar3jY3OBgJy3scUubRVieChU0-K8,1873 +torch/include/torch/csrc/api/include/torch/nn/modules/utils.h,sha256=EFeKPqk8CAjyY5KvvaWiDFArSVy_MWuHJ4ryA-QbXMM,1654 +torch/include/torch/csrc/api/include/torch/nn/options.h,sha256=sxG7alldUUJoWyfJrvSTi-0B72_NQXn1Mop-JfTHceo,899 +torch/include/torch/csrc/api/include/torch/nn/options/activation.h,sha256=uhyNnM7WIuoju5zQxwdcz33Ci_kMAfKH98poA5aNa1w,19238 +torch/include/torch/csrc/api/include/torch/nn/options/adaptive.h,sha256=sjOvq3GgknXt1PkX9MFkU7qjOSyGjtQYzuRc6JovEJM,1311 +torch/include/torch/csrc/api/include/torch/nn/options/batchnorm.h,sha256=tSndtNVHDgkdoHeiVnzO8wO6sbb9axlSOgQEEN56AoE,2991 +torch/include/torch/csrc/api/include/torch/nn/options/conv.h,sha256=lQXIbZwhpTt95rCaE0VmHDO7pi0fU8pSlGNUDOFdpdI,13648 +torch/include/torch/csrc/api/include/torch/nn/options/distance.h,sha256=IFWwIffyDJ1Lry00dfccYOt_TOGpK_q4X-Mjbxi6JJA,2243 +torch/include/torch/csrc/api/include/torch/nn/options/dropout.h,sha256=6bJy2Iqz0OXfGSDUX23n2dj2CHTwQ0qfCZQm6nlhx70,3299 +torch/include/torch/csrc/api/include/torch/nn/options/embedding.h,sha256=JUsnVNC9P-Sg9rlUOc-6oKb--hPgKsXrklmfOjBbBGo,11852 +torch/include/torch/csrc/api/include/torch/nn/options/fold.h,sha256=USrVVGHqN90-CLvmnQveb-S2MigbiCwZPfCXSNqW34Q,3167 +torch/include/torch/csrc/api/include/torch/nn/options/instancenorm.h,sha256=tN7AKMLz_tX7u0mvLA2C0JTeATVDiq52g_IwsuXy-pY,2506 +torch/include/torch/csrc/api/include/torch/nn/options/linear.h,sha256=IzxYAeVzX7oF02t9cgWKDXNudmJdXj_W3xCVYacrPIA,2464 +torch/include/torch/csrc/api/include/torch/nn/options/loss.h,sha256=Mtu5B5AaslcrDi6xa7tn50BCtxaxYAjK-epFgIbU8X4,26909 +torch/include/torch/csrc/api/include/torch/nn/options/normalization.h,sha256=LLi4Snl31dy_KfV4m33KbW5Z2Fe5wjyT3pYZRVi34Uc,5731 +torch/include/torch/csrc/api/include/torch/nn/options/padding.h,sha256=tbU2Tvhs-LnyxWJqtOyyb7TGDHycaGcc-l0zIXWWgQo,7089 +torch/include/torch/csrc/api/include/torch/nn/options/pixelshuffle.h,sha256=m5j2SlTRE7BJijFx1RmSloo70YWbPDTlJVm7L3YPSEo,1886 +torch/include/torch/csrc/api/include/torch/nn/options/pooling.h,sha256=rK_4UzIrHnL1BvJ0oX3P5CP3nSJ5HaYg7BasPFd7cEI,17961 +torch/include/torch/csrc/api/include/torch/nn/options/rnn.h,sha256=5qTRgvl4Cq3gTOcQex8Jc_JSPYCmVBewOmxadwkbGyc,8449 +torch/include/torch/csrc/api/include/torch/nn/options/transformer.h,sha256=bvMimjBCIRN0vmA66AZHdKNBNx8Ib0kIen4SODfFhV0,2068 +torch/include/torch/csrc/api/include/torch/nn/options/transformercoder.h,sha256=dEoo8Mx1CZ-yxMtp-CcOn8I0ZeYVMhJ5qk53LgaHD-k,2569 +torch/include/torch/csrc/api/include/torch/nn/options/transformerlayer.h,sha256=vbt-2FO0LdboCf6g0zvQdYi8RHHcefezgSGKeJp0V6w,2313 +torch/include/torch/csrc/api/include/torch/nn/options/upsampling.h,sha256=-rGCWi7NB8ZDo4gC8AyluCZboU0CCCSEs4rhvoG2xoo,4379 +torch/include/torch/csrc/api/include/torch/nn/options/vision.h,sha256=8T2d6HnqLAMZWVrjeHdPrG8hwm8-QG_rJO4araZCx7s,1340 +torch/include/torch/csrc/api/include/torch/nn/parallel/data_parallel.h,sha256=XvscFC2B5pLWeTUJMjsuKN78h8_86WFwJaYKnVibrRc,11569 +torch/include/torch/csrc/api/include/torch/nn/pimpl-inl.h,sha256=_7gjiWDY99dqBzC7khwLF-7g1OKmsunrtTuTMDLhhro,3478 +torch/include/torch/csrc/api/include/torch/nn/pimpl.h,sha256=dUvGjH8Zf0jeTw4HV7YsgQ7-kY0ufWXtyMbXg01iTcQ,6869 +torch/include/torch/csrc/api/include/torch/nn/utils.h,sha256=eZzeszpy667cwp6FJ523gX_puBwH-2OMvLeqGQPuFEI,385 +torch/include/torch/csrc/api/include/torch/nn/utils/clip_grad.h,sha256=fOyCc1u-hCi6OekXaJ6ZMqGgpcX-6lNE5Y-j1ZsuLs8,5092 +torch/include/torch/csrc/api/include/torch/nn/utils/convert_parameters.h,sha256=cYaGluG4Ra0DFAqtbjo1bqD4INGuQA7G8OHo2IFuoUg,2630 +torch/include/torch/csrc/api/include/torch/nn/utils/rnn.h,sha256=1fO253Y8XJjMdccTDcKD8jLSCbqHFr0nMnL-hIRK3Aw,13047 +torch/include/torch/csrc/api/include/torch/optim.h,sha256=dKbqqbG93ik70Mqw60l65oGLZl9N-rWQVhI_TQ07K38,648 +torch/include/torch/csrc/api/include/torch/optim/adagrad.h,sha256=nAVNhd73uYBYL2ZeTCLU3vjEbfJgut34RBhdP-g_yWk,3451 +torch/include/torch/csrc/api/include/torch/optim/adam.h,sha256=PJvoyY_mO-OsMuS2gPjKrZnwakTVLmBTEXR3sfvq2e0,3129 +torch/include/torch/csrc/api/include/torch/optim/adamw.h,sha256=KkrUzV21r36SWjpZhgB5t4v5f_PuUO9LhSFoPvpOfd0,3149 +torch/include/torch/csrc/api/include/torch/optim/lbfgs.h,sha256=sTD9wwF_XrGtm-2aUr4yyfq7k92Nc-J_lLwge0vbJaM,3684 +torch/include/torch/csrc/api/include/torch/optim/optimizer.h,sha256=mbpFHQYn2qtqqeG9KEPO8UKO9nt3TUOPUruEiEnnPoQ,16402 +torch/include/torch/csrc/api/include/torch/optim/rmsprop.h,sha256=srRMwObMUT9gcndgw8Zr0JBtkb-8Wjz-iX5SRTXh_8g,3142 +torch/include/torch/csrc/api/include/torch/optim/schedulers/lr_scheduler.h,sha256=-7Z-GPuYZWCf8TjI5J87q0jR9xi3Opa5Xbayvy3MEE0,1373 +torch/include/torch/csrc/api/include/torch/optim/schedulers/reduce_on_plateau_scheduler.h,sha256=-rWp5O4vbLWCWhv8Ng5-Pi6AowyEYnKRBrmpDaYqtE0,1634 +torch/include/torch/csrc/api/include/torch/optim/schedulers/step_lr.h,sha256=AR6ANTwsCyEVEnfg4_uNiBKM_zgNPEXNlCHpsJcSIWM,653 +torch/include/torch/csrc/api/include/torch/optim/serialize.h,sha256=n4P_G-sQqX3RKGRz0tDGoI0IQLqK6T-j9u-Co--1GjY,12927 +torch/include/torch/csrc/api/include/torch/optim/sgd.h,sha256=mbnkMFtvgOYUWSS25noZtCL1U0-7_UBE7t-mxrnYAjU,2876 +torch/include/torch/csrc/api/include/torch/ordered_dict.h,sha256=-2ctLJHeWZY-XPVh76M-15LIXLtAKZAd2IK_0TltTWw,16517 +torch/include/torch/csrc/api/include/torch/print.h,sha256=FFltpTY6fIutSOOKjOiXUO67AoyUwPzQvcn1RkXF-UU,714 +torch/include/torch/csrc/api/include/torch/python.h,sha256=xNAoE1udfG8OcxH-Ob5ZXcm95WfpEuYaQIywN-mTzbI,10174 +torch/include/torch/csrc/api/include/torch/python/init.h,sha256=DI9siWXORGUKh2T9AousnlS3ss2XOLsXmC2ci2fzdm4,458 +torch/include/torch/csrc/api/include/torch/serialize.h,sha256=cJYBTLdpqP6ZhbZD6XPBwPjNG27lofBkgk_AzjonEZE,5498 +torch/include/torch/csrc/api/include/torch/serialize/archive.h,sha256=bgmYgV3iccrvTK1uih12iixI6ZmuXNlwN2yOiA5JgpE,355 +torch/include/torch/csrc/api/include/torch/serialize/input-archive.h,sha256=94hT0mn8WsZMPf6jDzY0GECw3vOeK_oZTWIiVGDWLys,4209 +torch/include/torch/csrc/api/include/torch/serialize/output-archive.h,sha256=JV4yJh7pHvUejgJT3Ks0ByQv8yy8oBnyM1Krc123AoI,2543 +torch/include/torch/csrc/api/include/torch/serialize/tensor.h,sha256=0zHxiYy2sLUsm0I33QgdUI9wOVukkU_toXnQ4TiAk50,686 +torch/include/torch/csrc/api/include/torch/sparse.h,sha256=Gtx29zexv7Kz-O1GmCSsESZHS9Abtd1INKsc21GmqNM,291 +torch/include/torch/csrc/api/include/torch/special.h,sha256=oH3xzdNxoyHZnP1xjxyG-XISWpdfBrO1-VhzrSHHz_8,38539 +torch/include/torch/csrc/api/include/torch/torch.h,sha256=Pl63ncpcYFuxfHZlmVPbj5_dJ4E6pnRAY8G9QbBd-rw,408 +torch/include/torch/csrc/api/include/torch/types.h,sha256=N00lXLA_-FDh8z1MOBB_ygEfKoxieN3KEOQwy-ACX_4,2642 +torch/include/torch/csrc/api/include/torch/utils.h,sha256=GB1CqG8ZKtQmwCv3I7fOMvdlmngE3RG1FG9XNDRNiIo,3839 +torch/include/torch/csrc/api/include/torch/version.h,sha256=e6jwvr0_ZyDbVQT9pfn4HX7RLbLsPjcFFDnijTct2Fs,292 +torch/include/torch/csrc/api/include/torch/xpu.h,sha256=AMYSk9Y1uA92ZQ16t9uXRxEPjtPo5ScFS3KhaWnVKxM,856 +torch/include/torch/csrc/autograd/FunctionsManual.h,sha256=R41yEQTnseEGyLJe_ld0wOek4VKcnehkAxNIpoL3xEs,36111 +torch/include/torch/csrc/autograd/InferenceMode.h,sha256=IIsNk73vBgJGreu_P72DNwmvvUzynAuFphP3tEAf-eg,410 +torch/include/torch/csrc/autograd/VariableTypeUtils.h,sha256=PmjhUlJv3CvtloYuhxAUDN4mr0SCB3oE6TfuVzd6r-Q,15194 +torch/include/torch/csrc/autograd/anomaly_mode.h,sha256=pYFqhpKgwK_9QXJLfPFSeEpfrf0gbWIeCrm9-DymPlk,2003 +torch/include/torch/csrc/autograd/autograd.h,sha256=y2uSmq-92GvZTI03I2drOlPCvOcvCr9d-wIxKBc3lRM,5564 +torch/include/torch/csrc/autograd/autograd_not_implemented_fallback.h,sha256=tCJe7yOLcR7RL_3UxToohetXaL4IV4-AhirhV0-ICFc,1396 +torch/include/torch/csrc/autograd/cpp_hook.h,sha256=EU4UlP4ia7rBL1MFvTwoQvow-FsZU1q87npXD99hLBc,1213 +torch/include/torch/csrc/autograd/custom_function.h,sha256=w_2QvTQibVJjtfXs-NY_w5jYL_n9UCIIXu4BwJpCXv4,22898 +torch/include/torch/csrc/autograd/edge.h,sha256=WfypQ1-ofJTQICFpvtc2yj7Wh4GJLgattB4Eby_raJs,1893 +torch/include/torch/csrc/autograd/engine.h,sha256=hswpb125lj_mw1-itpy-OOEy0ZAOEH9nPJydHADRphY,11497 +torch/include/torch/csrc/autograd/forward_grad.h,sha256=mbF97GhoH-RLwCNSArB1lxXaJ533vL0QiSwRmkRW9-k,9399 +torch/include/torch/csrc/autograd/function.h,sha256=io_7lLfZQ4aXN_8ovB7TtMvBcZXY_tq_CizdbtbvaZs,3373 +torch/include/torch/csrc/autograd/function_hook.h,sha256=_mhR01mCC8NZPe4VcGVDCWBrluemLCvKjxyLZ_lhwEU,2506 +torch/include/torch/csrc/autograd/functions/accumulate_grad.h,sha256=3a98o7XQl_0MsKDeh8Euw6cHqsexoL1nMW6uhuqdCis,15622 +torch/include/torch/csrc/autograd/functions/basic_ops.h,sha256=wbS5BgGMoGw3C5UKodlHsXVq_a1aM-sX7rjv94Sbro8,3995 +torch/include/torch/csrc/autograd/functions/comm.h,sha256=FNF3iPcVZJLNbnnL6O5iK39EULAsbdjPuPYQ6J9zNGQ,1451 +torch/include/torch/csrc/autograd/functions/pybind.h,sha256=eMdYn3nYpRUpn2gG6xMtyCUKr37Tdcd8yPNF-mdo6eU,634 +torch/include/torch/csrc/autograd/functions/tensor.h,sha256=_J_L6yIZLi1cJOQe0LAIRpEOhQmwn48SPAwrxi46LdM,7529 +torch/include/torch/csrc/autograd/functions/utils.h,sha256=YUkqzTMxI996kWGc2qzVfD3a4GiaDrmFa63hg5yPPlo,3586 +torch/include/torch/csrc/autograd/generated/Functions.h,sha256=Vnu7hJLc-zcjO8bl0pyN6cQ9rmkmeePhIi2J-B7PK5w,528228 +torch/include/torch/csrc/autograd/generated/VariableType.h,sha256=OOGxghmRJgX-KZra275YBxjoa0v30Jh6PM_w8JXiFb4,1717 +torch/include/torch/csrc/autograd/generated/ViewFuncs.h,sha256=yPvzfQIRFWg-9GPcG1JBBIIW6pZ150ihOgyrQdf9ofY,37577 +torch/include/torch/csrc/autograd/generated/python_functions.h,sha256=nHxdfXNZXkyLW-nWFZ1R2nMQtAMkQ98ci7ucZQd43zI,1121 +torch/include/torch/csrc/autograd/generated/python_return_types.h,sha256=f3w1gxRB0mWVcakgeTbksnSPz0Cpktlqw87ALxSP58s,4336 +torch/include/torch/csrc/autograd/generated/variable_factories.h,sha256=npCmY0cF8JiK3m6D5gbkw8X94yXY-tRK5KvUTTGqzKM,55731 +torch/include/torch/csrc/autograd/grad_mode.h,sha256=49QHebGFym_CUOczJEtR9N64aq9mdZjk7o9scjMT6XU,464 +torch/include/torch/csrc/autograd/graph_task.h,sha256=6LGXII9JVwHQ2jg4zvsjGlsaN9CGb5dWlJ1vHBNRDto,9636 +torch/include/torch/csrc/autograd/input_buffer.h,sha256=c5YINfJG8nvRSmvZmjHoLL6jieZX_qtXPNbGgl6ED7o,4164 +torch/include/torch/csrc/autograd/input_metadata.h,sha256=8BE5MVxErQyJ-uqmLYTR7gHVMaGeqMQbIbazSUmqeRw,4022 +torch/include/torch/csrc/autograd/jit_decomp_interface.h,sha256=cQ3nucJtKJIUvLQCHo5vz3mem5As_-Yb0XZIiN9FQkM,2082 +torch/include/torch/csrc/autograd/node.h,sha256=2IUClESt7p9VZBTkiU4hZgIW4i2QeOmP_HE-tN41I_Y,29475 +torch/include/torch/csrc/autograd/node_creation_hook.h,sha256=a30Gv1rF83oQmsbNLDWdQyYaJTQ_WWm7alHpY3GGTFs,815 +torch/include/torch/csrc/autograd/profiler.h,sha256=B4BypHNHlVX9vBCnvfwl4yxogmg-pWrKUhQ3SKceoMU,366 +torch/include/torch/csrc/autograd/profiler_kineto.h,sha256=sU40ynENIA64XrGDJqg_urgC9EsiV_ajM_xgHrpWXXc,9489 +torch/include/torch/csrc/autograd/profiler_legacy.h,sha256=ybnnQqJ55ZyBMj9-X65QC6LBQGHl1a-aGaAYrdziuro,10956 +torch/include/torch/csrc/autograd/profiler_python.h,sha256=w_uymVzw7mSJshQulmwIbbypnob4XkFFcRdr_pLmKeQ,338 +torch/include/torch/csrc/autograd/python_anomaly_mode.h,sha256=UK_w_f8Uc-E02cxvHwxEgIdrtV_NVncdKjrddmiZDHM,1443 +torch/include/torch/csrc/autograd/python_autograd.h,sha256=vU-tC6gZ3BY11lhixIp-rPmPB67doBTiX8eRV7_ogp8,677 +torch/include/torch/csrc/autograd/python_cpp_function.h,sha256=dScYbCCe3sksRCP5TBzgeMjQfSgmi1vWmLE6a_7PgPg,5671 +torch/include/torch/csrc/autograd/python_engine.h,sha256=0eFZmTNzwEE7HPkC4Z9xTBhAzOgX1xIP1IKYXHf2XhY,1607 +torch/include/torch/csrc/autograd/python_enum_tag.h,sha256=DWE7qeWc8UxiHD2TgGvRtkmCNiihI6phVvHIOE76vH8,374 +torch/include/torch/csrc/autograd/python_fft_functions.h,sha256=rCqcUNevR9OzMD2NhlUKC3WWinruFbqKYo13oUS5GLA,389 +torch/include/torch/csrc/autograd/python_function.h,sha256=cAROFwmQGyDj-m7nWDsn3i4MuoYoWEH4qoSfPvwYFdY,6079 +torch/include/torch/csrc/autograd/python_hook.h,sha256=OdHmJXgXfy5jadWaKCHREp80MInG0q2WSR39921_v7g,2321 +torch/include/torch/csrc/autograd/python_legacy_variable.h,sha256=tNV-tr0AfucX_7ooFijF1lEWN3Tw5VT0myraeUQcVB8,511 +torch/include/torch/csrc/autograd/python_linalg_functions.h,sha256=8wRQxErZ873uJ5RptU29fcGT-OJYlaIy3B8hW8g6J4o,392 +torch/include/torch/csrc/autograd/python_nested_functions.h,sha256=4ipseJnANXuARoQRTVboHeqICoDEDKzeVTb0Y7PyDMU,462 +torch/include/torch/csrc/autograd/python_nn_functions.h,sha256=EKy9pNl3ybOxBu0JZTA8W9auzbtCnBqjctIS40LZOgI,383 +torch/include/torch/csrc/autograd/python_node_creation_hook.h,sha256=tvmDX1QS_zHkJRYaNZ_6OP6V5fk5BqCCoalTLC02MOk,874 +torch/include/torch/csrc/autograd/python_saved_variable_hooks.h,sha256=83uwA7LUqaCznTyUST-mlRNzBPt0MA8RUH_jI2RgfEg,1333 +torch/include/torch/csrc/autograd/python_sparse_functions.h,sha256=-BmwGly0XH3XsNvJbbSFkj0taRxazvFz-XRoT79BO4o,392 +torch/include/torch/csrc/autograd/python_special_functions.h,sha256=rxQgJ6E7VDMf73wk-DSnSwj5-j4pQoatW--g9h8HYeM,392 +torch/include/torch/csrc/autograd/python_torch_functions.h,sha256=4F0XERLfpLeD5xS0vyHX4U0ck8jbs0TVnUe3r7b8vsc,897 +torch/include/torch/csrc/autograd/python_variable.h,sha256=VWKfw-DXVrDFKbSZZyNrBLrX2sqbcbYD284Bm-DKJtQ,4112 +torch/include/torch/csrc/autograd/python_variable_indexing.h,sha256=36twHyeeuoUfyqhbj9TQmB4hcYrqEN8K30juO_Xkmqk,3006 +torch/include/torch/csrc/autograd/record_function_ops.h,sha256=FuLjqyuwTmxPp4xP94yxkLp_XfgHcR_H2txjyFqEVzo,1189 +torch/include/torch/csrc/autograd/saved_variable.h,sha256=8wNpHHLubCmE7FRO50QwnPTdqWalSZHl8qEUz-0M5X0,5491 +torch/include/torch/csrc/autograd/saved_variable_hooks.h,sha256=kwnUYEiaui84rDo3h3apvW3G2PXCk-qlB_7bpY213sE,795 +torch/include/torch/csrc/autograd/symbolic.h,sha256=QkadzHJ6l6JTk1lnaBv6t0IQw5L2YQin5b9HKLlZiuQ,554 +torch/include/torch/csrc/autograd/utils/error_messages.h,sha256=gFcxq6VvZbHcu_ADEXdBgdHE6DYWOPIX3mzPq8SZDPU,760 +torch/include/torch/csrc/autograd/utils/grad_layout_contract.h,sha256=-m8k_tjDVBdAlQ6Hq794tYxSILM6R_NWMvKFZN90-QU,3168 +torch/include/torch/csrc/autograd/utils/lambda_post_hook.h,sha256=LmkQcAnvDxXP6ISLWFrmT_qiTeBJsxQvWplpdDqet7o,1658 +torch/include/torch/csrc/autograd/utils/python_arg_parsing.h,sha256=KYRRUVW4HID-8dXLLK8ejR3Q0dRJxK4ORjqsE_RLPBo,1629 +torch/include/torch/csrc/autograd/utils/warnings.h,sha256=vMaKfEyqoSsAqrwKjRVnypKd4wvWDT6h1FYsxwNttUk,837 +torch/include/torch/csrc/autograd/utils/wrap_outputs.h,sha256=EZY-XWTzOCmEwyfDUbxboHGITgBAqFN0HqnbYSMt6H4,4076 +torch/include/torch/csrc/autograd/variable.h,sha256=oq0ummMskjq0-CSB7U7H9PZ5hBxdGplj0y33JXobTno,43217 +torch/include/torch/csrc/autograd/variable_info.h,sha256=x_powXIvA0FoDX1ZfprEiC7UknRztkLKAfKWpvCDpx4,862 +torch/include/torch/csrc/copy_utils.h,sha256=L27LKL-iro2NvWObZ5WKTH-1Csq304z0U1N3gW26N6k,1674 +torch/include/torch/csrc/cpu/Module.h,sha256=zGx7rIRNPxhfuZdJND23s8ueyqhYxEANUwyMs6XBJA8,393 +torch/include/torch/csrc/cuda/CUDAPluggableAllocator.h,sha256=EzQBqqHZz3tIGfnL4fUsh8WrqVYBtlHeG9Pwew3ts40,6913 +torch/include/torch/csrc/cuda/Event.h,sha256=KLa6boqJoG359kbJUQ05SEnt_jfDTgSTZJx9zT9b10I,687 +torch/include/torch/csrc/cuda/GdsFile.h,sha256=_sbk174mXjBzcCce8rvrChCh_0Yyk0e-hIM3VzanxX8,446 +torch/include/torch/csrc/cuda/Module.h,sha256=6zI-FTNZbSykpEcb8uFaHyFAfB78Q8zL-flGiKT2Kq0,804 +torch/include/torch/csrc/cuda/Stream.h,sha256=pOltSeNx7OTGfnVQBh1V3USsJwtMfkvYuBzzBjhfhS8,758 +torch/include/torch/csrc/cuda/THCP.h,sha256=824p3D8G5rEcJ8_mqta6VVtehwmQrX8r2LR630cDITM,477 +torch/include/torch/csrc/cuda/comm.h,sha256=X39M4z7rL1-bsydkOa7ctawby7a9c_rVh_vgZUmtxGE,1768 +torch/include/torch/csrc/cuda/device_set.h,sha256=WphcH70-YDeVx1chXwuIzm6uQZRdDuuGptqpD120_lA,439 +torch/include/torch/csrc/cuda/memory_snapshot.h,sha256=4ZmcuXqpbsDAqtpLS6nooCKozhOdoEb07D4hPJP1tvA,1509 +torch/include/torch/csrc/cuda/nccl.h,sha256=LxuuKy1ABV8CYf2DApknxwVxlF3e7sJJv3UwuOzF-g8,6151 +torch/include/torch/csrc/cuda/python_comm.h,sha256=3UpS2iokMzxsYGpslUbV5JnGWopGe3zjdTHOp5IzgT0,425 +torch/include/torch/csrc/cuda/python_nccl.h,sha256=438GoxIfBg-mTsXGvv2hMY9mKpclUEGX9M7ZV-9p978,936 +torch/include/torch/csrc/cuda/utils.h,sha256=wlakPJDSnG_QUpIK6f8LvWw0r7y5OQc4w1hei9exg3Y,469 +torch/include/torch/csrc/distributed/Placement.h,sha256=Ljbn5O4sm3CF4fBgshX4YRiQqzO6vy9Sk6n_ZCrXlaI,2831 +torch/include/torch/csrc/distributed/autograd/autograd.h,sha256=3rkmIlVBwPEIBrhQOqZZMJlMDEuVAersaMGqVP7IA3I,1890 +torch/include/torch/csrc/distributed/autograd/context/container.h,sha256=iwDa1nSd_MgnEMVd_FOEQB6lF8mB-5Y3odvD1BBSKxE,6639 +torch/include/torch/csrc/distributed/autograd/context/context.h,sha256=qq2woIEnmz8y0VQEDSOxncL145kEiwsXeFIwLAaeEXo,6881 +torch/include/torch/csrc/distributed/autograd/engine/dist_engine.h,sha256=l-UEO_fLFPMqXlOpRwDCmfum6YopkYg2CJh6MopWF-M,7681 +torch/include/torch/csrc/distributed/autograd/functions/recvrpc_backward.h,sha256=yUhTCVz-MeNdBaXoMDHwEzuL-qmFra3_mVjBjkIOopM,1916 +torch/include/torch/csrc/distributed/autograd/functions/sendrpc_backward.h,sha256=ztfoFVFG6KzHKU4Zz3IzpfkshRcOh-awivGQapGF_i8,1577 +torch/include/torch/csrc/distributed/autograd/python_autograd.h,sha256=F9cPdI4F4m7HPMIs_fBea6QMpX0J5kUyD3EDmHHX1Xg,428 +torch/include/torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h,sha256=VdgRx9Eaj6Jy3s55wgTpRQVpYoX1WqNuHutcs8cZbj8,954 +torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_req.h,sha256=QeJbAf00azhBpdrAUaCBXyrT1KHFng6rIeK37d14594,1090 +torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_resp.h,sha256=-CIxYg-7UQ52v3om34tmUM0r1nxWHX35BhQqGAXWnZE,915 +torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_req.h,sha256=cCl7oeWz1PbpB80JTecbjugSF3SMstl2tPW1mIrrrK4,1502 +torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_resp.h,sha256=G_2iVpZVZSecDjhQA-EslD5swLZWHCJ1k1MB5_UvNnM,1008 +torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_autograd.h,sha256=wWIg4p62dn0Kq4BSNnZz0a-CDv0cs09VBtL1Z53W3aw,3760 +torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_req.h,sha256=FZqHLNTHs8uMCbRd_fHTjrf_S5dWJ_MwPHK87W3XiME,2764 +torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_resp.h,sha256=7VpaqDe6N23Qk-vOyJ2J9VQUzrTpHUiiaU9NvR22T2Q,2724 +torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_req.h,sha256=E9P-Y0xyK68cinxepkUq2uKl73qzssChvNtTYZ4eRaA,1444 +torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_resp.h,sha256=yxE9UFlGQauit2LcWyCkFgy8Uw31HXPRheKJFB7Eqvs,762 +torch/include/torch/csrc/distributed/autograd/utils.h,sha256=oRUE0r6ccxMxc3SPd1ViAexoV2c5xsxmyS4YAp2HWW4,2901 +torch/include/torch/csrc/distributed/c10d/Backend.hpp,sha256=cK4aNfyTTal3yKm4iwTMuaElnJ45v2_3-DI-GxfBi-o,27833 +torch/include/torch/csrc/distributed/c10d/Backoff.hpp,sha256=DnLFbWRCa3IhP5E29sSnNpsHBO9oJat1Ek4W1hDjIAw,1305 +torch/include/torch/csrc/distributed/c10d/FakeProcessGroup.hpp,sha256=LZmYHZHDSoho3y137hGDu4qAm-5Xo9GwdZKPCPlCGYY,16269 +torch/include/torch/csrc/distributed/c10d/FakeStore.hpp,sha256=JlO2eE71cBD4XP4540ZbSEuDSOXMXbrLSccOKHL9PI0,1609 +torch/include/torch/csrc/distributed/c10d/FileStore.hpp,sha256=iK7cGCElJxpUzi4-Xv4e1mN_6RSEHvoYYcWvynJw640,1842 +torch/include/torch/csrc/distributed/c10d/FlightRecorder.hpp,sha256=n55IM87YENc0CIgYssG9EqMLRfEQxzoWZoQT7sJd6-Y,12414 +torch/include/torch/csrc/distributed/c10d/FlightRecorderDetail.hpp,sha256=QZ3YXkIcJUOf61l7Kpb42I1lQ2_7rwMa-2rbTA7pIXk,21468 +torch/include/torch/csrc/distributed/c10d/Functional.hpp,sha256=710n8pvHltshQs2MvTdO3atzOT5MmwN4FjNTG4h5OYE,5378 +torch/include/torch/csrc/distributed/c10d/GroupRegistry.hpp,sha256=LFpx87v7dvk11uGm6nS4cxkllN4G6gBHSJL6eouJB44,823 +torch/include/torch/csrc/distributed/c10d/HashStore.hpp,sha256=wLEhb20eHMpuzUCLVCx0q4Ne4bzqa1g_YYupgq9Lgxk,2487 +torch/include/torch/csrc/distributed/c10d/Hooks.hpp,sha256=NczBoTXuOiYJQRLonydhO-FLMILHn-C-3duvJDrqJyo,1697 +torch/include/torch/csrc/distributed/c10d/NCCLCommRegistrationHook.hpp,sha256=KVuVJnZIHe1mrMQS0S7XQUU9yw2wUdSqNGC5yCFdIQM,1757 +torch/include/torch/csrc/distributed/c10d/NCCLUtils.hpp,sha256=NkfIHedJdwpk3aCTPpiZEjkKxDSis2Y1XRs0dAR3bsg,16163 +torch/include/torch/csrc/distributed/c10d/NanCheck.hpp,sha256=7IMJ1X-zeKEMAb4vsPmHB6lRr7NmtkudyjsJyRn5_iw,562 +torch/include/torch/csrc/distributed/c10d/ParamCommsUtils.hpp,sha256=Q84ODQ1pyLO56l2DRoadR0ZOk5pYJ7Vs9_PcSSPxSXE,11813 +torch/include/torch/csrc/distributed/c10d/PrefixStore.hpp,sha256=6ccfMIhqe3OGCWTut0PKGoU43e6uukpMFTu1qpOgioU,2525 +torch/include/torch/csrc/distributed/c10d/ProcessGroup.hpp,sha256=eCIKCpEUyMzsW-keEkWFqkYFugEt4i1fLh2SPp7PDdI,48764 +torch/include/torch/csrc/distributed/c10d/ProcessGroupGloo.hpp,sha256=RF6dSL309ycJgemr4mNgTSNHNM0sRWTXRWItzXjXAIk,17947 +torch/include/torch/csrc/distributed/c10d/ProcessGroupMPI.hpp,sha256=CoWrVlk8Pr9cVAc9v5znOUNEKfn747wym9KkCNdFA-U,9042 +torch/include/torch/csrc/distributed/c10d/ProcessGroupNCCL.hpp,sha256=0QGuO8IcvfzxP-zMyqxfqD2ZoQvsdlVyCcJGNuyw-s4,56944 +torch/include/torch/csrc/distributed/c10d/ProcessGroupUCC.hpp,sha256=azCDzUNbTj-GHRpnwE4bJvP53Wx4baX7-NMtzAd51gM,11340 +torch/include/torch/csrc/distributed/c10d/ProcessGroupWrapper.hpp,sha256=hE6OwfEDtL9rLG4jjFMFXfZ_Lj3NhLnMoG4JXlrjfIw,7924 +torch/include/torch/csrc/distributed/c10d/RankLocal.hpp,sha256=xpv_I2vmc3Y5k6FjIwb3clFuqrWshbe8hXP1rxFXSHI,3180 +torch/include/torch/csrc/distributed/c10d/Store.hpp,sha256=BW7B5upiNj6famiaAMSzsJYiYdaPWmXwVOa8SX7ly9w,5200 +torch/include/torch/csrc/distributed/c10d/TCPStore.hpp,sha256=nhT0-x9ExKKMQdnRoAGHentZG9tyCWuSE9guGRlglY0,5486 +torch/include/torch/csrc/distributed/c10d/TraceUtils.h,sha256=OzbRVbWdDzLqcoSEeyovOhwJ9yK5mgBuN0bOL-HwF18,9542 +torch/include/torch/csrc/distributed/c10d/Types.hpp,sha256=aHTTzK2Hy_vntuKtajpb0g2yw-ba-fuHT0f53jmZ71Y,7206 +torch/include/torch/csrc/distributed/c10d/UnixSockUtils.hpp,sha256=RBTSux9rLp20yj8jF_k5c3rguQBp_o9aWy4aohgsyQU,804 +torch/include/torch/csrc/distributed/c10d/Utils.hpp,sha256=wKrKJUhEPLRu6zcVfKE_2_RRy9VlsnXIOUf0cXHb3Qo,27983 +torch/include/torch/csrc/distributed/c10d/WinSockUtils.hpp,sha256=-DWh4gPRTjDxX8zfhyE9Bu9YXyhUAGciZjCQsctmlkU,795 +torch/include/torch/csrc/distributed/c10d/Window.hpp,sha256=L7P1uUTweNuYclHflSOHm7Tq0b9DFJmeMIuoiWt1748,3083 +torch/include/torch/csrc/distributed/c10d/Work.hpp,sha256=r68It39j-uLXktMqss2TVXpCQF5AW8OitBmANtzaJVU,6362 +torch/include/torch/csrc/distributed/c10d/c10d.h,sha256=98aqdnQ7MT6I3vRDCjmrF2zpwhmlbjjebZHyaDdUz3k,420 +torch/include/torch/csrc/distributed/c10d/comm.hpp,sha256=MB5AenuguWwMeIKABucAzpwS7T4lNA85YgSKkxtbxfo,4677 +torch/include/torch/csrc/distributed/c10d/control_plane/Handlers.hpp,sha256=H8IpREjMOBE8X_LGT8uNOcaTzV0xhP_50cN6c8op_3k,2588 +torch/include/torch/csrc/distributed/c10d/control_plane/WaitCounterHandler.hpp,sha256=XveaRQ5aVYkHecZ2Z4a_3HRejCU0233sxJimG1xtLbk,567 +torch/include/torch/csrc/distributed/c10d/control_plane/WorkerServer.hpp,sha256=xxqg78hobK_Z0E587GIjWeOOsEaiENHKsZsnUeRnlso,902 +torch/include/torch/csrc/distributed/c10d/cuda/CUDAEventCache.hpp,sha256=q4lCWhFi99XcNnFdk9A9YhfUtJlQRfSmr6RykF4HvUs,998 +torch/include/torch/csrc/distributed/c10d/cuda/StreamBlock.hpp,sha256=c3Pu6S_w-tKJz-SIX9P2axR7FUmtxL2HUPxcaEx4xw4,1115 +torch/include/torch/csrc/distributed/c10d/cuda/utils.hpp,sha256=p-DYuAHZo9VjAbXM5FvxqTXSl47rPhPAiWttX5qNprs,484 +torch/include/torch/csrc/distributed/c10d/debug.h,sha256=ebhH_PUCoe7bakjer98f7OMMkrvIkefj3-jdzbwOb9Y,858 +torch/include/torch/csrc/distributed/c10d/default_comm_hooks.hpp,sha256=i9cBVCXiFfq8wAmCUMFnnG4lhvlWyoeaQP7B5GZotmQ,1999 +torch/include/torch/csrc/distributed/c10d/error.h,sha256=VVxbcGxJKtxoYWiji9uEhc3UwMonbEEQ7W5_zMvj_N0,1544 +torch/include/torch/csrc/distributed/c10d/exception.h,sha256=NDYECXJFZdExOQEW-vt3dXvUntTtgP-pvV-UP2uER8s,1600 +torch/include/torch/csrc/distributed/c10d/gloo/GlooDeviceFactory.hpp,sha256=6MsvopYzTV3oGjWqYoDRXQTbeaNCwg7F2CalioXwYeM,1094 +torch/include/torch/csrc/distributed/c10d/gloo/ProcessGroupGlooDetail.hpp,sha256=1ENHPv3UM0Mb8bOLWo8lDvfGFamLVZP7EUf4zg4F4u8,22229 +torch/include/torch/csrc/distributed/c10d/hooks/FlightRecorderHook.hpp,sha256=msagXQfutt6lWRMsMFFRRNFzvo78NyuVWHg-iG1VX2s,2667 +torch/include/torch/csrc/distributed/c10d/hooks/NanCheckHook.hpp,sha256=dG3iiw0ScUT81PYtfWknJz8_eAp447ne_Q8GTKZLR7c,1853 +torch/include/torch/csrc/distributed/c10d/lazy/LazyBackend.hpp,sha256=snveftUxQLJgSW5ovhlY4rZDf8SPSOdN1y7uWFTw5wo,16891 +torch/include/torch/csrc/distributed/c10d/logger.hpp,sha256=G-Fhtj0S7GduFGsSBUBbFZMsjv-Z_FDji3QRww6wOwA,6685 +torch/include/torch/csrc/distributed/c10d/logging.h,sha256=kQSwLqHtBQGg00Ow6Be3fg8HPUrHCHcAC7mLU_xF2-I,2084 +torch/include/torch/csrc/distributed/c10d/nccl/NCCLXStub.hpp,sha256=KDGxYtttU3_Fa-pJid6a7yPSkzKTIxMS8-h9q-komWA,2646 +torch/include/torch/csrc/distributed/c10d/nccl2/Batch.hpp,sha256=i3HPGqst3fJ9_v_4fR_UsnU4XGWLNZ-3L0pwhSJ2hcU,1375 +torch/include/torch/csrc/distributed/c10d/nccl2/Logging.hpp,sha256=0HLoh0HbglrFC5R1QinghE1zZYUR02KKjd0mmzuhmR4,2063 +torch/include/torch/csrc/distributed/c10d/nccl2/NCCLBootstrap.hpp,sha256=AMO_uKZfagM6RUUCChiy2CpDWvK8a5ufUJO1SFAc0vM,2509 +torch/include/torch/csrc/distributed/c10d/nccl2/NCCLCachingAllocatorHook.hpp,sha256=XA_udlmdjD1Nqp_4qw04Z8KxPeAzkkiBaUt6BBs7NmE,1817 +torch/include/torch/csrc/distributed/c10d/nccl2/NcclApi.hpp,sha256=Ar7VnVYiaXIiJE2niLbMu7YxAKV4CPMrLXHmpkI1KSg,14545 +torch/include/torch/csrc/distributed/c10d/nccl2/ProcessGroupNCCL.hpp,sha256=r47F3yqR105OdNI05U2uu0wxXWVE0hXS8aVxHfHFXQM,28090 +torch/include/torch/csrc/distributed/c10d/nccl2/ProcessGroupNCCLLazy.hpp,sha256=6ZKMarDHw9KS6QHeu1s8J6xa69D-a3_uovupgU3rbYg,2176 +torch/include/torch/csrc/distributed/c10d/nccl2/TracingGuard.hpp,sha256=OWFUbEwfAXwa-Stox3eE_6VzJ6Jt3yp_hEVaOtegESM,3229 +torch/include/torch/csrc/distributed/c10d/nccl2/Utils.hpp,sha256=jw2Mrr_f55_GPl8cPLYJL35OqO86ATdxy4pNgCrtHII,810 +torch/include/torch/csrc/distributed/c10d/nccl2/WindowNCCL.hpp,sha256=qdDPrjRBDfwwu_HLPRH_GF5DFUvANRFPGdaNrcF83ps,3368 +torch/include/torch/csrc/distributed/c10d/nccl2/WorkNCCL.hpp,sha256=3Kx4NztZftSf2XHMGfqqzlm632otgMWRZTwIi2IW5no,5834 +torch/include/torch/csrc/distributed/c10d/py/PyBackend.hpp,sha256=LlVDxtLmUpfBV-yBHx21GoODeMXixyZht0Y24pmSGEE,17307 +torch/include/torch/csrc/distributed/c10d/py/PyProcessGroup.hpp,sha256=hSJ78qPZEBiBp8QDyMi0_9ixLaxj7BcS2ajr0M3Bhkg,17047 +torch/include/torch/csrc/distributed/c10d/python_callback_work.hpp,sha256=6Gt8x8CATCK7aJiAFygtXfN9dx7RlINra7pJ77ibpeE,1030 +torch/include/torch/csrc/distributed/c10d/python_comm_hook.h,sha256=KZ2FDYZSeCvTUUdakbwM5TgK7MfS8NVfpundzm1-Zkw,1327 +torch/include/torch/csrc/distributed/c10d/quantization/quantization.h,sha256=Md-HOaJ9-DpVUffMQnBRJ812FMA9jX_JfFVvVhQ_LG4,709 +torch/include/torch/csrc/distributed/c10d/quantization/quantization_gpu.h,sha256=jtpDYbQ9RTOF5AeWmm9zi2e13NCIziUX_rvcHJRUl5E,711 +torch/include/torch/csrc/distributed/c10d/quantization/quantization_utils.h,sha256=S40yJ9Z3sN81eQkoCt1BPol-D41J8RRYI8m9WMmY1LU,1510 +torch/include/torch/csrc/distributed/c10d/reducer.hpp,sha256=z3UCfxmMF83a_k-m_KMcTfGm8G2jnbH4QaRZ6Ifecmo,27244 +torch/include/torch/csrc/distributed/c10d/reducer_timer.hpp,sha256=TD4Lpxk-65H8hy9A1eDI60X8pX4U0zqc_EYLrsJrkC0,2638 +torch/include/torch/csrc/distributed/c10d/sequence_num.hpp,sha256=otUETjq8RGaGOOWeqsCjPAq-MrjJ48rNWSXtlcX563Q,1958 +torch/include/torch/csrc/distributed/c10d/socket.h,sha256=HpAenewC5doWDVOyzdVBkmrO-Q40dpnS_kAPzIMZGxM,2714 +torch/include/torch/csrc/distributed/c10d/socket_fmt.h,sha256=ugcrbys6fYksAsFKph3TptWa_b3MDR-0hqL34nZfgxs,956 +torch/include/torch/csrc/distributed/c10d/store/TCPStoreBackend.hpp,sha256=EOhlch6kDsQ0lPQuua6CZqHxO7h8DltbXU8tAkaj6eg,1843 +torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemory.hpp,sha256=nKDQvoTcW7jMlby6x0ZGl2GfAOVJv_KPBEF9XPj2jgM,5298 +torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemoryTypes.hpp,sha256=wCq_AGNOuVIyx732rMNh5In-6-29Uroe-QmdS19p4Hs,1966 +torch/include/torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemoryUtils.hpp,sha256=6F5u7mXbeUeF6kQERkTruJmWGbrx3pUOejdTjZ5vK3w,5995 +torch/include/torch/csrc/distributed/c10d/symm_mem/DMAConnectivity.hpp,sha256=UA_H2-MUPXBRVjruzND7ieJ_h3MsgrzThydPDEYBu3M,1531 +torch/include/torch/csrc/distributed/c10d/symm_mem/NCCLSymmetricMemory.hpp,sha256=Qy4o4mbe9nxwlUak5P3PlBHZ_C1sFaSXVEpJE6kjrgk,1804 +torch/include/torch/csrc/distributed/c10d/symm_mem/SymmetricMemory.hpp,sha256=FJlIhChapbiE3vgFaIE9tU6CkdT4rdHSP-YKNWBYuQA,9302 +torch/include/torch/csrc/distributed/c10d/symm_mem/env.hpp,sha256=-4nJOjv1iHpWQ8TU3lI2ZgWBcVTLHxHL9dSt1v2jgEk,669 +torch/include/torch/csrc/distributed/c10d/symm_mem/intra_node_comm.hpp,sha256=xc0pB8REL64GJTHgvzGuPNya4u1gLEVPCbd0dctEF3U,2636 +torch/include/torch/csrc/distributed/c10d/symm_mem/macros.hpp,sha256=9_ey3ngus8M1TwEJI1M10rGWKg1_xMrIbL33jrjv7cA,1343 +torch/include/torch/csrc/distributed/c10d/symm_mem/nccl_dev_cap.hpp,sha256=l_4Dtp6DwleapszTWLUxiza8WujrMkF7O282Ts8KlY0,1357 +torch/include/torch/csrc/distributed/c10d/symm_mem/nccl_devcomm_manager.hpp,sha256=aiYgZOGAZ16EpDT5Jdo9cj6ErKdt_8oK5Y6OOxjBXvs,12059 +torch/include/torch/csrc/distributed/c10d/symm_mem/nccl_ep.hpp,sha256=8u5gQ1HRvF6Ee99Qp2O5HX2MspRQQfedEn7vnThgLnI,2374 +torch/include/torch/csrc/distributed/c10d/symm_mem/nccl_extension.hpp,sha256=R7ttxqkUMeytGnXUTEFgRYHDzeYjd6xB16OEf8spUwo,1945 +torch/include/torch/csrc/distributed/c10d/symm_mem/nvshmem_extension.hpp,sha256=OjN9VAq9IWGwcbuItH_K8MEg4cTMG4x6qlPMTmvqT8Y,2937 +torch/include/torch/csrc/distributed/c10d/symm_mem/nvshmem_team_manager.hpp,sha256=8HSMWrOvrI9_qhDRETxEWlpUae9J_8AjaTYAGintoqA,6723 +torch/include/torch/csrc/distributed/c10d/ucc/UCCTracing.hpp,sha256=OWc9JO5gmHfhnN5bnvPW-bDOP3Wja7CYIpceBo-0lq0,2559 +torch/include/torch/csrc/distributed/c10d/ucc/UCCUtils.hpp,sha256=1yEkP1SJnvJQCCtLG7jKUqNAYDlV0mjkJcnxcLRYm0c,6614 +torch/include/torch/csrc/distributed/python_placement.h,sha256=87wvbwBCZkwHvXHZ12w_RIc8nwlR5GgxZVNmuZQACLY,422 +torch/include/torch/csrc/distributed/rpc/agent_utils.h,sha256=-WmN5L_KWnHQPDVm8G8lnvyl8CVP3itL_71MxSoD930,1883 +torch/include/torch/csrc/distributed/rpc/message.h,sha256=4J0JYMLIRqpvzFsG8zwjv49Biok9AtJWttFcW60vj8M,7887 +torch/include/torch/csrc/distributed/rpc/metrics/RpcMetricsHandler.h,sha256=qBhyhGPXtUqD16i-UP-zGC-FcH3heCX4lnFEZJcC3fA,1822 +torch/include/torch/csrc/distributed/rpc/profiler/remote_profiler_manager.h,sha256=57nLwfYlLfg_4Q82xj6teBpsEI-VtpQmrHikpXOJsOo,2480 +torch/include/torch/csrc/distributed/rpc/profiler/server_process_global_profiler.h,sha256=f29goWZ9VC9DoTO6KfPowpNWGihmzkxdDOnWUz1ONpI,4651 +torch/include/torch/csrc/distributed/rpc/py_rref.h,sha256=19R-hMHZZ4wwDCYxoGQZGHBmaDSt4F7imiImR61r8QI,3219 +torch/include/torch/csrc/distributed/rpc/python_call.h,sha256=ib1wexw1L3-FANmVfR5z8k6k8bJWDX_LUDHhhc2SIPc,1065 +torch/include/torch/csrc/distributed/rpc/python_functions.h,sha256=udBVDNxsN7qlVKV6RYNWfga9atMEP64wz0B5h9WfVTk,2511 +torch/include/torch/csrc/distributed/rpc/python_remote_call.h,sha256=L6V5BiyzPhuj0W_-0CfbkUlJzcO2ZBbFW4c9mpMrvuQ,1532 +torch/include/torch/csrc/distributed/rpc/python_resp.h,sha256=Lm4TlIG9M46Qn7uXjSbtGHg5heXeKzFzn_Ccuo6lY_M,875 +torch/include/torch/csrc/distributed/rpc/python_rpc_handler.h,sha256=QzHCjyLvNZIkx5MnBUl_yHTKmiIEhmflIaJPdfvf41s,5211 +torch/include/torch/csrc/distributed/rpc/request_callback.h,sha256=zJnOxrCIzxFWwuia5XvgvIL--WflFgHSPP337JzGcvk,1480 +torch/include/torch/csrc/distributed/rpc/request_callback_impl.h,sha256=ljQoxGJulsdA1jbSXmcKpAOA_fhbSItRx2wCLMAJ9NI,2336 +torch/include/torch/csrc/distributed/rpc/request_callback_no_python.h,sha256=y5wSLgvzWSU9p-8ZATnzUKbRliw29xWVccbSbpf341k,4158 +torch/include/torch/csrc/distributed/rpc/rpc.h,sha256=AZ88ciAR9Kpv7jQjNO9hWvrgFkTMuyssBTr1HaJjBQQ,418 +torch/include/torch/csrc/distributed/rpc/rpc_agent.h,sha256=sIAcZPEtcw0nnYLXSIOG2JoBh2hDJ-ik9nCLS3PlWNE,14157 +torch/include/torch/csrc/distributed/rpc/rpc_command_base.h,sha256=v3MU4z486fYnio_EQ5lZmWz_l8dcEe6tD-vCq4jUJMU,932 +torch/include/torch/csrc/distributed/rpc/rref_context.h,sha256=eXhqk13RvWzx0RweL6L8U6EMQDE2c_nmPsxfRjCYBvI,16036 +torch/include/torch/csrc/distributed/rpc/rref_impl.h,sha256=InGOVxnqLEU0j_ySIKG-M-9P0L2H8031sWQm7IMDBYE,16705 +torch/include/torch/csrc/distributed/rpc/rref_proto.h,sha256=SWbK563pyfM4ErGDXn8csprLuyWMhKQDhBj3YACMZMk,5611 +torch/include/torch/csrc/distributed/rpc/script_call.h,sha256=6YqWqBglQVy9d6ekl0oaficMWr6RpsltysOUMwARXIM,2740 +torch/include/torch/csrc/distributed/rpc/script_remote_call.h,sha256=dmWKw9zMvhAr47cx4wUZfBdcKJ4v-fWOs35CY9KwCCY,1947 +torch/include/torch/csrc/distributed/rpc/script_resp.h,sha256=g-NlV9plQD0iRb4Oe-RdMcUROnVR1KVWxDiW3xi2REU,903 +torch/include/torch/csrc/distributed/rpc/tensorpipe_agent.h,sha256=uku_0SKx9IE_kVuCGltuNcLOVpI8t8u7jbDgwl0Lr_E,17894 +torch/include/torch/csrc/distributed/rpc/tensorpipe_utils.h,sha256=jiKArNodJh9qrWWApKos2cQFYYYwQlpdGXF-P9_0OJg,4995 +torch/include/torch/csrc/distributed/rpc/testing/faulty_tensorpipe_agent.h,sha256=knNysmZUsPfvEdMnV8n5RWVkxXH6yC4QEfBuOWUi79Y,4040 +torch/include/torch/csrc/distributed/rpc/testing/testing.h,sha256=9Z7ubO59UGH4QyrBqzqDuSR4LzuiVJzcV0teEMAa5s0,436 +torch/include/torch/csrc/distributed/rpc/torchscript_functions.h,sha256=h16g5rg-iUPYVNzmfovPMZlq4HJXf-yQZ-QKy4X5Dwo,1910 +torch/include/torch/csrc/distributed/rpc/types.h,sha256=3za2zUBLFSjbS4mMrpcWzfG2xPASKvCJz_mmRIv20jM,2464 +torch/include/torch/csrc/distributed/rpc/unpickled_python_call.h,sha256=lQy-y_rF5i3E1gAh_gH9byjIGMMoWFIi7qFMf2AZjN0,1642 +torch/include/torch/csrc/distributed/rpc/unpickled_python_remote_call.h,sha256=AVUQz2-ZGzECQgZl2Ocpvnw8blFvEIAfnc2KOpMnn_0,1461 +torch/include/torch/csrc/distributed/rpc/utils.h,sha256=2CGx4yhtg62GZHCmuPp2DAN0p-GTGA-6jQ7SpkqMBOM,4044 +torch/include/torch/csrc/dynamo/cache_entry.h,sha256=zxYZEEPp670FjX5M0QXGt_zV1Ki0nY3MRVFwb3Lh69w,3082 +torch/include/torch/csrc/dynamo/compiled_autograd.h,sha256=08ojr1YPAJ3Q7mQNlw6QWP3qvH9GmTVlBNFeemGe_20,51381 +torch/include/torch/csrc/dynamo/cpp_shim.h,sha256=PikXznGvcUJZ5GSh4D6Fs8Pc28kk6BUcB1WzUsDi22E,611 +torch/include/torch/csrc/dynamo/cpython_defs.h,sha256=Axt2oLc0fsLl5VqxCR-5rRyBLHhSpnt-LF8O-4dTYWA,1174 +torch/include/torch/csrc/dynamo/cpython_includes.h,sha256=e308Zb9FDh_TyWp3u_SjK8ddIJqScR40dL6n4BX1kqU,2029 +torch/include/torch/csrc/dynamo/debug_macros.h,sha256=M6MYIcD0iNODFf9uia3dM4XLxiBs0b54HG4JgFh1zHk,3782 +torch/include/torch/csrc/dynamo/eval_frame.h,sha256=ET6EgQVNE-WmdlEH2Bwqy27VP4Qs3oyyXdJKOR-XcCM,1901 +torch/include/torch/csrc/dynamo/eval_frame_cpp.h,sha256=d7NPXFHNt0w0aNoG4qUz9-Q_9swuszwI0gn0Ok7NGNQ,1430 +torch/include/torch/csrc/dynamo/extra_state.h,sha256=V6DlX9bWrm_Bp1QOlAcJPC_zBimxm4vXZzCuZ2mxuo4,8771 +torch/include/torch/csrc/dynamo/framelocals_mapping.h,sha256=1wY8fe28hVm3r1oYVnVtPGWQeJdrim7wP1XuuzpKPPQ,3035 +torch/include/torch/csrc/dynamo/guards.h,sha256=Y06Sgp1dLe2EUstxyUF9bnH-AiQHh_XgABIjH1OeujQ,4253 +torch/include/torch/csrc/dynamo/init.h,sha256=2zowU12pO7ujkPnOise78YFjJq85AilpavNxRc_Fe3g,441 +torch/include/torch/csrc/dynamo/python_compiled_autograd.h,sha256=pnKkQpXyekQfk5B4vtzCgxNWHUjKgwp-4J2lPrOfpyg,469 +torch/include/torch/csrc/dynamo/stackref_bridge.h,sha256=VDxP9T4sWOW0QHU3HAWhvX8LV5dMX0PiXbimAa_Dbgo,618 +torch/include/torch/csrc/dynamo/utils.h,sha256=QhXCgdMkEzSha-lH8EJKO7NnsKg5OVEaWu_gWG8X9do,772 +torch/include/torch/csrc/export/example_upgraders.h,sha256=-mACzEc9kbq3weBPH9VqyGkZPjRdWUt374q6Z3SnuUM,761 +torch/include/torch/csrc/export/pt2_archive_constants.h,sha256=ISFOcIRb202_ZOB7BywNKMDfwOQgoDgjsjNJXigSFBw,5170 +torch/include/torch/csrc/export/pybind.h,sha256=fI_Sphc3RTmoEAd8w5bUsVyY1ZFBaJTvF6mQ_7ls-Q4,396 +torch/include/torch/csrc/export/upgrader.h,sha256=Hpg96dnZyxdzYIfRUblO2D_dwbmVmsIdQ80VbYLD8qk,5603 +torch/include/torch/csrc/functionalization/Module.h,sha256=5ZEw4c7qn1PtmLTX7QH_bjxWsQdgoAZvpUgUeUwmcHE,1308 +torch/include/torch/csrc/functorch/init.h,sha256=HAwFV4NnMH19I76RFwwFuQ6pZVW7OAhVnWuZjoyygZ0,444 +torch/include/torch/csrc/fx/node.h,sha256=82SLiN-PrEtXKlVBK2sECGpVi7SbFbTpLUPn4_LXcu8,384 +torch/include/torch/csrc/inductor/aoti_eager/kernel_holder.h,sha256=cLB3oS4-UnP5kK5mvWlW1gv0gdXuWRl_LAywuwP05Wc,4995 +torch/include/torch/csrc/inductor/aoti_eager/kernel_meta_info.h,sha256=F8bLD2Rl5VQA3J5uIW0juv-D8oYJ4BkvJXGcLIhIqjk,6817 +torch/include/torch/csrc/inductor/aoti_include/array_ref.h,sha256=SFBN5XNKtGL8M4EOlZh4wKWDEfeFawPurJrz7Q8TuyQ,555 +torch/include/torch/csrc/inductor/aoti_include/common.h,sha256=pk3x6OttsruIOjeDW1AfSKAzTewv0PV84F_6JhIMK3g,670 +torch/include/torch/csrc/inductor/aoti_include/cpu.h,sha256=cxf5uxsTPXTmzx9Tal01sNbQMLpGIV71OQsLQAMtFzU,386 +torch/include/torch/csrc/inductor/aoti_include/cuda.h,sha256=5nZAdzyxFteK_Xx9-mpWHCBXFiEZfzPugoI1mabtdbc,455 +torch/include/torch/csrc/inductor/aoti_include/kernel_compile_result.h,sha256=OReE0I8WJRW3C8VPSryAb9YkxLzCUd_H6PQ3xUB8lbI,836 +torch/include/torch/csrc/inductor/aoti_include/mps.h,sha256=tZd4iKD9EXjrnZ5y_umoJ1rX3wMCbN1F7stgzTniRSg,386 +torch/include/torch/csrc/inductor/aoti_include/xpu.h,sha256=8bfAwiElnyY-_ngx2MRNpSg6ZQHikiFp0J1Q1PX5Oe0,454 +torch/include/torch/csrc/inductor/aoti_package/model_package_loader.h,sha256=U2uCo1aAzt3065sEBeLbz_VmGWUGKVEc_3NnGFcSAOw,3126 +torch/include/torch/csrc/inductor/aoti_package/pybind.h,sha256=-QbSC0FRBUlK06XOsjhMkqaoLotj8abv4QS6AgEu4nk,403 +torch/include/torch/csrc/inductor/aoti_runner/model_container_runner.h,sha256=6nV9AD7KkZEFAPw7jA8IZp8tZPdtx4EPDAMjC-afZ1I,7834 +torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cpu.h,sha256=LwhCggPgK5-cGVUcny7a25LSc5ES0dpg4_fJWheASDk,1089 +torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cuda.h,sha256=Ifvnpl6YsnH_8-z1DSgFp31SzoRSRvi2f7QVGDR3oGI,1815 +torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_mps.h,sha256=Q8DXtywT5LCB62h1PjXAg2RGvhIafrROAncYfWpBURs,710 +torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_xpu.h,sha256=b292VzjoXRTNhDZ13TSOUlMCs3tnEgLDw6tFl0LUE6U,1708 +torch/include/torch/csrc/inductor/aoti_runner/pybind.h,sha256=sllydAFs1uLRcUJzr6HhfDKdFR-U6_gdquQWoVLQL30,402 +torch/include/torch/csrc/inductor/aoti_runtime/arrayref_tensor.h,sha256=oB4iEoc4H2Uroj3dWry3KB1KA1Cuqgc4TQmpwsQ34RM,6950 +torch/include/torch/csrc/inductor/aoti_runtime/arrayref_tensor_conversion.h,sha256=nlpKJgBu60U_duWCvEOvv8fj3Re-lM7yAWxJZXQzXHQ,3629 +torch/include/torch/csrc/inductor/aoti_runtime/constant_type.h,sha256=kw7DVntwNZI20Tx0yksFG7tZPHrpJuN7gZmqF09LHl4,781 +torch/include/torch/csrc/inductor/aoti_runtime/cpu_triton_runtime_wrappers.h,sha256=e5N60JNuFsy9obrmESUuH0ujF5QlepoZwkd842AeNH4,3790 +torch/include/torch/csrc/inductor/aoti_runtime/device_utils.h,sha256=7WZbYHzzszss2iZv0kjyRJYU0eVrL4AIYRGsmfB7bm4,2574 +torch/include/torch/csrc/inductor/aoti_runtime/interface.h,sha256=e3sOz47IRPzbjacy1Q_P_gF7sXGQijpzkJFc9rwe1FE,19312 +torch/include/torch/csrc/inductor/aoti_runtime/kernel_context_tls.h,sha256=Sf7m6IbelxB9umC-iCRaZ9c7KMsc8msfp4sg_o_A7FE,4238 +torch/include/torch/csrc/inductor/aoti_runtime/mini_array_ref.h,sha256=5DbABsGXNt8dA4tLwQRDqUq4ccRlXDXzwXjdxAbsB7k,4980 +torch/include/torch/csrc/inductor/aoti_runtime/model.h,sha256=8Ed908j4R9RRKv-EIXiPhnnI6sMefKWZmdTM2scQV3o,2769 +torch/include/torch/csrc/inductor/aoti_runtime/model_base.h,sha256=gc0bPw0ot_ljEksUPijoHVmVdcyxbMiVHJ3YiAoofKo,50235 +torch/include/torch/csrc/inductor/aoti_runtime/model_container.h,sha256=LR0A_9Bao3RjOxxAAD9wATMR7NVzzEiaqOlo3zoAqp4,38518 +torch/include/torch/csrc/inductor/aoti_runtime/scalar_to_tensor.h,sha256=1_eNE1F_kl-XWpwsgc33m1p07_lNK1iasp1cRVQt5NI,1844 +torch/include/torch/csrc/inductor/aoti_runtime/sycl_runtime_wrappers.h,sha256=hMxcxrtb6zyncbzz3fvB3aBYA5CwwFIE6RZYDpbTcRk,6867 +torch/include/torch/csrc/inductor/aoti_runtime/thread_local.h,sha256=kQpIjL_9JLeu-B5C2_PYsv-BhIh8NueCEVupbBdCJyU,4606 +torch/include/torch/csrc/inductor/aoti_runtime/utils.h,sha256=Ck96R5T1ZxV8eOTh6R5g7Ksy74iYtu0tQ_hnB-VHxhU,19591 +torch/include/torch/csrc/inductor/aoti_runtime/utils_cuda.h,sha256=iP8TDGVTQKcAQH5GscGF21TcRPiUggE887Pl_j_n5i8,2079 +torch/include/torch/csrc/inductor/aoti_runtime/utils_xpu.h,sha256=OxYab5unrLFCiIAbqy7iZf5e0_p6IF-YY7NU1VEEHlk,1969 +torch/include/torch/csrc/inductor/aoti_torch/c/macros.h,sha256=dbD2szZ8zECHPYsKCOC8lT4WJj7CnbkKvlGrsBmUl5w,2321 +torch/include/torch/csrc/inductor/aoti_torch/c/shim.h,sha256=uUAzGsFnUj1VPCKQVKssjpPDnsHxpA-GMrOB2Et4HYY,26540 +torch/include/torch/csrc/inductor/aoti_torch/c/shim_cpu.h,sha256=tx_K_GPKYJ2_erq5WfWx4Cj_U__Ze28tvea1kvPBrrI,7490 +torch/include/torch/csrc/inductor/aoti_torch/c/shim_deprecated.h,sha256=84fTR6qD0UVNXY9ammn7K1Fp5Rj9mvKHjCkWtIOEmCg,6551 +torch/include/torch/csrc/inductor/aoti_torch/c/shim_mps.h,sha256=Glt6UjJfHY4BWXQmJ-vYxfCnv6X7iRvcbxsIsLQEE4I,3613 +torch/include/torch/csrc/inductor/aoti_torch/c/shim_xpu.h,sha256=Psqiql3DOXCZaXLv7GwoKCcQi4B4Ihg4t49PvH8YXCY,5982 +torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_aten.h,sha256=mPkNA3q1_Lr9pg3aoeZPqIF9MeiwaKtKuvhfrsbdomk,2100 +torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cpu.h,sha256=kNRHLyQ4oW8OKS_mEl3sQNbm4xjOW7yr8wfbis5L1y0,34214 +torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_cuda.h,sha256=buDX8HwEGY7sSV_5JrkHIdeh37xBfA5SrK9oDa7IQz0,43062 +torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_mps.h,sha256=T8WhIsDrqUxhX9p798X487pjcBmxq_2jIGWD9hz4Kp8,29649 +torch/include/torch/csrc/inductor/aoti_torch/generated/c_shim_xpu.h,sha256=Ft9Y1eFSJA-_aMw91Q9AJjCUoM9_Kzk8LnIy1D73nFQ,34751 +torch/include/torch/csrc/inductor/aoti_torch/generated_enum_converters.h,sha256=9Soz7Yzln75OEmVwfVWdy91867ZHgqvFBfS0Qt-Ne8s,4624 +torch/include/torch/csrc/inductor/aoti_torch/mkldnn_tensor.h,sha256=ZdeZ09ReNHprPAM-vXNUXrFL3uupfCbuwVaOQS7ivLs,625 +torch/include/torch/csrc/inductor/aoti_torch/oss_proxy_executor.h,sha256=6BTVAzjzsPxF1SYniYYLfz0qY3Do7cCgolATTupz40A,5358 +torch/include/torch/csrc/inductor/aoti_torch/proxy_executor.h,sha256=9dWHsPv2dQQcWb504gZAn9-r3iV4xPpX8UH28wYBCZw,1666 +torch/include/torch/csrc/inductor/aoti_torch/tensor_converter.h,sha256=xz-3-D9GdhQfRRw7MSrt1ZgJ4qbNqBk_uQtFtIT22BY,1793 +torch/include/torch/csrc/inductor/aoti_torch/utils.h,sha256=QUMYccDfhDW-u4LCbnzaAGA7lbGoVI9z2FOFO8K-0rk,11924 +torch/include/torch/csrc/inductor/array_ref_impl.h,sha256=r424waXg_g_yI3xTAXohMc4yxGWqAEChQCtm6zGbVZw,3260 +torch/include/torch/csrc/inductor/cpp_prefix.h,sha256=-y0PZu4OKhhDFy99GKAYoVX82yTnOFlHbE3Q48_7xMg,45294 +torch/include/torch/csrc/inductor/cpp_wrapper/array_ref.h,sha256=XKMFQCveJevHKVCHmyiepJa2JBZTCMFrU0kE8lJmsnE,554 +torch/include/torch/csrc/inductor/cpp_wrapper/common.h,sha256=6XSvoy-UIlXMNoUNy0LY5ByeMqQGr-SJ5jnU9pjARII,7632 +torch/include/torch/csrc/inductor/cpp_wrapper/cpu.h,sha256=DsDdKA8bpepv9yp-59zY3HoQa55zmmdgZtRS4y4JXuU,385 +torch/include/torch/csrc/inductor/cpp_wrapper/cuda.h,sha256=rp2P98HM-V1bA6Jqb-ya1P9EsEbdXX35QVjlCLl1bjw,599 +torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/cpu.h,sha256=rOgmA6ZaUHX1Zvj-Tr3qj8Oc_8BYCMmXPE5GAZhj9ZQ,333 +torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/cuda.h,sha256=2x0n7z6ZZ1t0Bo5xEhcyCnoaH0GsvweIfR0fBN_oXZ0,391 +torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/mps.h,sha256=wRwIY3fjx11KMZZuPGffr3sFJilZ39DDGJ9M4UV5_3w,388 +torch/include/torch/csrc/inductor/cpp_wrapper/device_internal/xpu.h,sha256=SulOHp5rrEkUIyWH0wjhPK1ezDtmiX00u3tAnusq1XQ,457 +torch/include/torch/csrc/inductor/cpp_wrapper/lazy_triton_compile.h,sha256=ygHacHyP4GVFPEP9L1Z7utY61HcU0qWsj0WPudee5-U,7232 +torch/include/torch/csrc/inductor/cpp_wrapper/mps.h,sha256=1BbioeTM6zhVciGbOrNx2SHBn7tw_9-z6bBV-QZ8WqA,385 +torch/include/torch/csrc/inductor/cpp_wrapper/xpu.h,sha256=wStJ3gsDAGB6qcUl_X0ihO9pW6noIi9h04THwMJLEO4,450 +torch/include/torch/csrc/inductor/inductor_ops.h,sha256=lln5wsSTK3alK8h3ooWn5VEjKM4m3IewPDdzw9_Xc0w,1349 +torch/include/torch/csrc/inductor/static_launcher/cuda.h,sha256=SACsIIHWgRApKrAXAEojCn1D4mFm3zWiMMndFnmR1Ow,496 +torch/include/torch/csrc/inductor/static_launcher/xpu.h,sha256=ONDk0ocLnY-EgVdgqSnO1OxWjMpK-k-f2eOAwIgW27Y,382 +torch/include/torch/csrc/instruction_counter/Module.h,sha256=Ml9ZG1I-Y6RPLlwR-rnjGTsz77UfWljboJcIEhfjgRw,425 +torch/include/torch/csrc/itt.h,sha256=Hh_KZ49HvlacfiBSGHKCIOxr8lJ7gwwAYpFMGxyvgTI,435 +torch/include/torch/csrc/itt_wrapper.h,sha256=AiJkfyZXHdf_XHd5s6hkf4dxtDYCpUS14iFxmzKuSvA,574 +torch/include/torch/csrc/jit/api/compilation_unit.h,sha256=hUIkZcGmufGNvFGijvHyETh9F7G6Rw7Xh6YJ3t2W-ho,11950 +torch/include/torch/csrc/jit/api/function_impl.h,sha256=4yKX3Evd3u0UwmzAM2Cad1mpScm9JtlNfJE6ri36waY,5995 +torch/include/torch/csrc/jit/api/method.h,sha256=eHbmuglj-sEN05sX-njsaznd-xnGRsV06NyD8CkD6vY,2676 +torch/include/torch/csrc/jit/api/module.h,sha256=STgZ78Nr5-K0dTx8qqXrC-jVzM1Ma4fZPXQRU5FrQjQ,23762 +torch/include/torch/csrc/jit/api/object.h,sha256=ZJEc4KLVU0XMgInnrZ2xxQv8GY0YdpiIEfaJOA7INw4,6349 +torch/include/torch/csrc/jit/backends/backend.h,sha256=Jp65JTXDs4J2ThN_jLXjZZnSL7zK6VghpFSnkqFw9s8,4086 +torch/include/torch/csrc/jit/backends/backend_debug_handler.h,sha256=_QT_zsuAF_buHIuago5qA2sNd8REDXq8ylIALk8gM2s,6586 +torch/include/torch/csrc/jit/backends/backend_debug_info.h,sha256=nu7V5_39nw4mXLK9L71qBYX5K5qpVJoKLw03SmhGzos,2570 +torch/include/torch/csrc/jit/backends/backend_detail.h,sha256=wdFD4DqTtzpkP9gDSiv-7UMirUM6wDDGB7H-HR1QPwY,1333 +torch/include/torch/csrc/jit/backends/backend_exception.h,sha256=zLusJ6DuLALB6i6bVPoGJ5uJXa0AynE1t1wRpEb2ajE,2390 +torch/include/torch/csrc/jit/backends/backend_init.h,sha256=RAFmi0TqARbl-ubYaKTCIL8TNqAGm1qFMPCY3Xx9L30,506 +torch/include/torch/csrc/jit/backends/backend_interface.h,sha256=MX68QIi9QUduProJUDhmZRYrI0v70iFW6T-aIoG_l1o,1413 +torch/include/torch/csrc/jit/backends/backend_preprocess.h,sha256=VqNFjRIHvSl7dzAUIL7By46cYMTxFH2jXRhbK62PHYM,667 +torch/include/torch/csrc/jit/backends/backend_resolver.h,sha256=CYBglxD9roKA4sfXp_54q4ruhOKFu16OWd3Lta8dWGw,506 +torch/include/torch/csrc/jit/backends/coreml/cpp/context.h,sha256=tethBGnuL4WyugUIwuYJ0enleu3p0ayUni8k8fzPNb4,692 +torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLCompiler.h,sha256=reCeVEraZWxNme4d0cnKMjywXuSfMWGE6ZSgTkjEBBc,787 +torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLExecutor.h,sha256=xwIlHZRCswsW26xZ7Ql_fjUTjLBt42ZfNlNrJzf9BuM,668 +torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLFeatureProvider.h,sha256=DkokTYTWbUAlpImXcjhqy7a11H7A5Ty0hJ4fxXmMjtY,604 +torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLModelWrapper.h,sha256=wHqsv6LISy7Xy9B6SkOQQMdSdWBuQIypvi_SHRjpSGA,1176 +torch/include/torch/csrc/jit/backends/coreml/objc/PTMCoreMLTensorSpec.h,sha256=5gsPmrVB6h5S29xNnRgVWAiYrwrKK-51ArG_vJ5J5Mg,902 +torch/include/torch/csrc/jit/backends/xnnpack/compiler/xnn_compiler.h,sha256=ADmstNgU9OkZ5aV11bfLXfUexBpDMyTAIhtzz7o03IY,1036 +torch/include/torch/csrc/jit/backends/xnnpack/executor/xnn_executor.h,sha256=iuAnIUo0qIJ1kY9Uuvj5Nmh2fPzRlvrKcjTdE3EE7Tw,1821 +torch/include/torch/csrc/jit/backends/xnnpack/serialization/serializer.h,sha256=tEkmXQjr76j9w_xXGTJDQf6oqeNXGm11EJ-fhVUq904,3033 +torch/include/torch/csrc/jit/backends/xnnpack/xnnpack_graph_builder.h,sha256=TnVcYkyNAU-TEh-D_K7OezDokOi4o8sYGqi2Sv1vGio,3488 +torch/include/torch/csrc/jit/codegen/cuda/interface.h,sha256=n_0AGEGG0qhy6rCnWJpRk3NwlY7fWXNmxSnms0BrWzY,2118 +torch/include/torch/csrc/jit/codegen/fuser/arg_spec.h,sha256=kEbcFpRmYoos45ISwGCEj7xMeR5yTrTqtRVzkVa-22k,1607 +torch/include/torch/csrc/jit/codegen/fuser/codegen.h,sha256=iUhuS0ExBWQ3dJgW3rXixOfs9wr_Hv4W8_1wBVTB4Jk,999 +torch/include/torch/csrc/jit/codegen/fuser/compiler.h,sha256=XlK31j1-g_YBuW4eNveTsIJhsfLhfS5S75BwtV1-5gY,2088 +torch/include/torch/csrc/jit/codegen/fuser/cpu/fused_kernel.h,sha256=4GspYxscZ_D7qaNhqpb3vOdrp8zOk4kDJrwTftge9SQ,1253 +torch/include/torch/csrc/jit/codegen/fuser/cpu/resource_strings.h,sha256=-mHwdYh9bS9Qp0Rjwjhn1slJ5Dsba7WpaoSyEOnNr1g,2532 +torch/include/torch/csrc/jit/codegen/fuser/cpu/temp_file.h,sha256=fjVmQwk3FzmMZaR-3uVOAWBUnS0Karbb2SRRNFdvuQk,3145 +torch/include/torch/csrc/jit/codegen/fuser/cuda/fused_kernel.h,sha256=QYz6Vg2SZAolMNCXOm97jCKznd5YVGxi1jUf_rKaAfc,1765 +torch/include/torch/csrc/jit/codegen/fuser/cuda/resource_strings.h,sha256=U2eEy18YGE9YHrND5__Pb3qunkDUksRYkMdBxn9U4WE,12410 +torch/include/torch/csrc/jit/codegen/fuser/executor.h,sha256=B7r0NLU-F8utHGO8CRIuCjp204lK1Ch8_bgGgTU3Rws,754 +torch/include/torch/csrc/jit/codegen/fuser/fallback.h,sha256=8caRHyCb87UPKCrvhOIiQ4rwfWYeut2LUL2qHWrxIE0,428 +torch/include/torch/csrc/jit/codegen/fuser/fused_kernel.h,sha256=aisFlx4O0Ur4aqwSMKKeexzBtMU7cz_ZnBJJbL9TCkc,3559 +torch/include/torch/csrc/jit/codegen/fuser/interface.h,sha256=S-tgQYiHs8Yq8aQ6bS45VKTkY9dwS1TZmLEM8O-OSEA,1976 +torch/include/torch/csrc/jit/codegen/fuser/kernel_cache.h,sha256=RRzEWG3xtahznaAG4DjhdrbmXY1Jp6Ndmv8T_hopvb0,1248 +torch/include/torch/csrc/jit/codegen/fuser/kernel_spec.h,sha256=BivQtrvupHG9BAEjCZCXrH71hc_zuojVtWLUjZKh_LA,4655 +torch/include/torch/csrc/jit/codegen/fuser/partition_desc.h,sha256=IddHbNKQdgPgY4ESijYgYkoPamv5Rl5l0KQpgyqU5Bk,2009 +torch/include/torch/csrc/jit/codegen/fuser/tensor_desc.h,sha256=ATarPR55x29jHUU-RznxLnDmHiIax1Hwo35ymAAfT1w,2955 +torch/include/torch/csrc/jit/codegen/fuser/tensor_info.h,sha256=dzENGXbxvP1X-sHViShL8mjKYCtZyCCY9TAaI7EWAoE,790 +torch/include/torch/csrc/jit/codegen/onednn/LlgaTensorImpl.h,sha256=PzwwFiuS1WR8uguOyLfScgiTq8rPY4qwyJwlu6mkZNQ,7944 +torch/include/torch/csrc/jit/codegen/onednn/decompose_silu.h,sha256=p_G-mIPLgMY8jSGFSk0x3Lku8FaVjyluOluZUlo1On4,442 +torch/include/torch/csrc/jit/codegen/onednn/defer_size_check.h,sha256=pE1__qzRiyQxN2cJbvvqWFWKjWPYBo790Ledlv98MhY,436 +torch/include/torch/csrc/jit/codegen/onednn/graph_fuser.h,sha256=CR2zC1oIpjsRncDjPGgK6SeQR2ZGVGG1iuja1UKwiqY,1470 +torch/include/torch/csrc/jit/codegen/onednn/graph_helper.h,sha256=LGewDjvOWFT38EcIBi_JOnHV_I9zOQcBwzFwgcGC7yc,2718 +torch/include/torch/csrc/jit/codegen/onednn/guard_shape.h,sha256=j20gjfQhLQYJqfBBe8L4AnpzjfP7gFbSkd1Bu5DxAg8,438 +torch/include/torch/csrc/jit/codegen/onednn/interface.h,sha256=h47yQa2csCXocYQVkvTHsPb7iyJJjEnqQDfvHc3bXdU,1652 +torch/include/torch/csrc/jit/codegen/onednn/kernel.h,sha256=RDURTHKr-SJMSACT3S2pV2RnC-8P4yCU-V3cu6U1b2s,2949 +torch/include/torch/csrc/jit/codegen/onednn/layout_propagation.h,sha256=A-K9-r745pQok43Myo_xHK9kmxsf5sut9U8ZolAykvc,443 +torch/include/torch/csrc/jit/codegen/onednn/operator.h,sha256=vX10EMXfm62FHTWVTb284rQGQF7vpdeiznLJmkFgPb0,4176 +torch/include/torch/csrc/jit/codegen/onednn/prepare_binary.h,sha256=u2XAd1M6J7MiGAqN_QH8ktm0Y_ppCJ89YPAOEmnqFC0,753 +torch/include/torch/csrc/jit/cuda/cuda.h,sha256=dRaA7N_y1gPx6TIxr-DgVimq5hrhKrsXwWrKxRYx_4s,5411 +torch/include/torch/csrc/jit/frontend/builtin_functions.h,sha256=IZBvfhC3BrCaGLAUUVWmqchlP7aNvLonuPTxlBskFXY,469 +torch/include/torch/csrc/jit/frontend/canonicalize_modified_loop.h,sha256=jsuIx-jMYBiRGMHonSgVsKio2zrmbgjVRqeDiqOVxqw,541 +torch/include/torch/csrc/jit/frontend/concrete_module_type.h,sha256=GCxfEpftkhM8Z1sP5vTssOJ3eIg-ZViluiZEPmZkQZk,9291 +torch/include/torch/csrc/jit/frontend/convert_to_ssa.h,sha256=3zWfz9auCqI1QD7FxwBBjL2_UMe6E3p3G4_A90JG0J4,556 +torch/include/torch/csrc/jit/frontend/edit_distance.h,sha256=kBIcPiahPtaKkOxWxALNLIi6fjke52sFJqNoII-lmbE,483 +torch/include/torch/csrc/jit/frontend/error_report.h,sha256=NUq0IuGQRclkqoYl683WnEpv5aIU79t2XtQzBMR_sEI,2494 +torch/include/torch/csrc/jit/frontend/exit_transforms.h,sha256=AHUnyTGs7X9qs68WAce4PaeNaYnZU-ZiUXq9N6n4p-c,447 +torch/include/torch/csrc/jit/frontend/function_schema_parser.h,sha256=57_4_23I8XMIAQiywm7njeOFDbdDQlgdPnxIpVPkPTQ,1054 +torch/include/torch/csrc/jit/frontend/inline_loop_condition.h,sha256=4tqiJQvvtb7knAxeGN7_2XV47pJwoTZO2qLqPpw4GS0,581 +torch/include/torch/csrc/jit/frontend/ir_emitter.h,sha256=0sEUfd9NIyIK_zS4st3_79jowETO89MCwy0-fPnIRCU,770 +torch/include/torch/csrc/jit/frontend/lexer.h,sha256=Cx1R5H8pdUUOe9H7sIjdAhzA0Sdjr230DnlzDhYQtq4,19234 +torch/include/torch/csrc/jit/frontend/mini_environment.h,sha256=u87AA6rHKGLu_MNWaKLtkIkjb_IIqytdpI24T5Qxeug,1629 +torch/include/torch/csrc/jit/frontend/name_mangler.h,sha256=PRM_e4MlsIKA1wowjkp5vHEGNBTOaB0X5K85wHKKszA,884 +torch/include/torch/csrc/jit/frontend/parse_string_literal.h,sha256=Fznb2iPJ4zUS5wUiMAjIY6q4O91g_VyE93DL5sdDbuw,2548 +torch/include/torch/csrc/jit/frontend/parser.h,sha256=_VFpRbn8WXPLBhYDz70syzCXeSXU0SRYAfe8ZaKvvhI,903 +torch/include/torch/csrc/jit/frontend/parser_constants.h,sha256=0oL1Mg44XC6hXBAUVj99yv1wylrXakght95EY8u7aHw,405 +torch/include/torch/csrc/jit/frontend/resolver.h,sha256=B2JGXlG_IrZbzMoYG21oCz_-4OH6AW40E5s2SLDJdpo,2212 +torch/include/torch/csrc/jit/frontend/schema_matching.h,sha256=5duuKpN_Iu8dwscoEsjSlxNmAshtYyyLEqMtuQEYwrI,2362 +torch/include/torch/csrc/jit/frontend/schema_type_parser.h,sha256=Vq5C0npJSoWJYb-qJ2KlbNIgqrvLphPdOUKpM2Ruix4,1657 +torch/include/torch/csrc/jit/frontend/script_type_parser.h,sha256=J0NaC5d95lNulX8d1gN7A94c2U44hrh0OI85Oo83KTI,1834 +torch/include/torch/csrc/jit/frontend/source_range.h,sha256=WTpKAJWYr5Z0usErf89n08CVfqLQIKEZ6rREHI-8s1U,17189 +torch/include/torch/csrc/jit/frontend/source_ref.h,sha256=5v9iDWib2yT3VnIXOzSlYStz_FimS_fMlV9CXtqdJLI,1543 +torch/include/torch/csrc/jit/frontend/strtod.h,sha256=zBQEJYtFWY-Fvdb6nsS13gggDCnZo8UFQDxv90QZv4M,470 +torch/include/torch/csrc/jit/frontend/sugared_value.h,sha256=JL2MbOpNz_wPqxDqYLkBwDpAfntq8xb3TTblTCtqbs4,28557 +torch/include/torch/csrc/jit/frontend/tracer.h,sha256=7dtbDxVqztjg2MzETszwWcH5F1xPLqAaDLLTAes1KbY,12919 +torch/include/torch/csrc/jit/frontend/tree.h,sha256=BP7V3JcbGgtg7xS2pEYPred8cmGOLfRsdyQlTl5RVyc,6829 +torch/include/torch/csrc/jit/frontend/tree_views.h,sha256=jUVuM_ORa1Fw2JpabQ437wr9bUTbnKjrBJ1SHWRAdXg,37454 +torch/include/torch/csrc/jit/frontend/versioned_symbols.h,sha256=QQs29ujosMvluxrGO2hAW7BFNDKEk2d9F_nTO3Lmmig,849 +torch/include/torch/csrc/jit/ir/alias_analysis.h,sha256=aW6ia8q2mJjNqzru3uhzz8YWxa2EUL69KDjhDVbUTvM,14545 +torch/include/torch/csrc/jit/ir/attributes.h,sha256=43U31D-1q5H9wbAcJT2X6q-YNWjsPQg317KASe2x0wU,5059 +torch/include/torch/csrc/jit/ir/constants.h,sha256=6fLeQ2WAKA5g2gw8Zs-R7XkAXkXk4YXgYUcDwUohf5Y,2262 +torch/include/torch/csrc/jit/ir/graph_node_list.h,sha256=rgOcMU9i8Cl87ZuhS0sSSjeKVHx1lDbAercWE9y7NS0,6608 +torch/include/torch/csrc/jit/ir/graph_utils.h,sha256=f7t71HGhSNU94EvgZvL67Ns4uelB56jQHlK9Nfh0xW0,758 +torch/include/torch/csrc/jit/ir/ir.h,sha256=2nx50rWPYuavIeBYLqMs_EslSn_cKrQvfU7-r6ThG1I,54956 +torch/include/torch/csrc/jit/ir/ir_views.h,sha256=qUTbqSGcKgCwTmjV5CHXJus7xfQTYhA31dViUrrTrKg,4877 +torch/include/torch/csrc/jit/ir/irparser.h,sha256=QR383rzKoILJH2nvRV99BfSLecPlQ0JmNhRUUkdSBY4,1354 +torch/include/torch/csrc/jit/ir/named_value.h,sha256=82WrC4LrBN4TKGqdHMEXgO-n50yfYiUtR2h-Bg30Ny4,2650 +torch/include/torch/csrc/jit/ir/node_hashing.h,sha256=DR0v95_n2vYSlFBwPiJ8ITtCCexa-Yl8QFI3stx6mjM,519 +torch/include/torch/csrc/jit/ir/scope.h,sha256=TavvTgYpeqh6LwT4xq2aNODXtJ9p5jQc37Fq2p_1h2s,7411 +torch/include/torch/csrc/jit/ir/subgraph_matcher.h,sha256=B5qPDxLYTgFYL6JTqJnXpnIMhOXbuhstmRh_j_vNr8E,3381 +torch/include/torch/csrc/jit/ir/type_hashing.h,sha256=8TAouNEGWvMPma9IVod1oqIYHuIggQaFsq8_Zq71yYQ,688 +torch/include/torch/csrc/jit/jit_log.h,sha256=syz7hm-O9pgJaPrw4-5q9GNwPCqfNoR6-idW4okMeOg,5060 +torch/include/torch/csrc/jit/jit_opt_limit.h,sha256=l-n0og_7nXcLMg_ae44PbLXrziAZY1ISo3PmTzCVsww,1635 +torch/include/torch/csrc/jit/mobile/code.h,sha256=E-rv5f8zS38MQixts0_MOe7Ur3sGHLM0Hih0rMcgj5I,1332 +torch/include/torch/csrc/jit/mobile/compatibility/backport.h,sha256=my50F4l06bIP3ScMBpCyHLLkzKVI6R5Teno6DO5MVGw,893 +torch/include/torch/csrc/jit/mobile/compatibility/backport_manager.h,sha256=RiXxwVhpwUkte-nxkn5-ChdWNlo21NliH1XFW25R-Rk,1413 +torch/include/torch/csrc/jit/mobile/compatibility/model_compatibility.h,sha256=dywbWpJUEvz_CiepxNHFc0oATDKtWOJwblheeOvIaFU,3864 +torch/include/torch/csrc/jit/mobile/compatibility/runtime_compatibility.h,sha256=z4MRUqp0Zv4ldMRb6BODecdKaoPZvB8MNeMtwces6P8,1450 +torch/include/torch/csrc/jit/mobile/debug_info.h,sha256=zWiX3q7hHzoNvtlkyeqhm5wi5o-VPa9W41Cb7W3DQ74,2460 +torch/include/torch/csrc/jit/mobile/file_format.h,sha256=qmYV8WP6S0lsCqAkNxf6f9MyOR-GzzQbKTuTOArZe-k,6936 +torch/include/torch/csrc/jit/mobile/flatbuffer_loader.h,sha256=ZemcyJvz1xrViIzqyU9FOpEFKSfs0Zj5KLZFizGbwOk,5028 +torch/include/torch/csrc/jit/mobile/frame.h,sha256=WiI8ygemRG2Cs8kC-XhXSsUEsW4_OPVg7fxVpAB58Sk,1065 +torch/include/torch/csrc/jit/mobile/function.h,sha256=fs89swfvXdN8o1rkHr1YJ7WplNp2GfnzoUbp8qld1lE,3195 +torch/include/torch/csrc/jit/mobile/import.h,sha256=yr-EklN5mCQAZ4UFDu17e1r4Kjje5dpLkhOv3LxYRWk,4094 +torch/include/torch/csrc/jit/mobile/import_data.h,sha256=kqh0Z_dfBXiDhA4cVAURyAn5tmKpjAz71FpwcIj8dzA,1249 +torch/include/torch/csrc/jit/mobile/import_export_common.h,sha256=dLR011fk_eI2oPyJ_s-rSPt0EqhKUHpYiDlBXjfQejE,731 +torch/include/torch/csrc/jit/mobile/interpreter.h,sha256=JUerPsUZ5IqflpfMtbtPOCIW58lD2ZwmAyVXmJqnY5s,901 +torch/include/torch/csrc/jit/mobile/method.h,sha256=oYavtszbUZH2NAe0pM7wkKQtAyr1edu6qwn5PiWq7mo,1078 +torch/include/torch/csrc/jit/mobile/model_tracer/BuildFeatureTracer.h,sha256=K-OXlFb1vxQ9yYmUh9iGcluYaMWrrFpvTyaryo9wX04,1215 +torch/include/torch/csrc/jit/mobile/model_tracer/CustomClassTracer.h,sha256=ZFqxc7Hukxo_Mb4g7ikCxcPvRObAqcfqUxPG-IvQ4_E,1213 +torch/include/torch/csrc/jit/mobile/model_tracer/KernelDTypeTracer.h,sha256=kP9reVHEFkMFMnMr1LR_6CD-352jdMl9dDlCAci3tQM,1466 +torch/include/torch/csrc/jit/mobile/model_tracer/MobileModelRunner.h,sha256=Xfd9FoGNn9_R3oAZaDN4YC35lQzutLYIHIgJyuGztvg,5340 +torch/include/torch/csrc/jit/mobile/model_tracer/OperatorCallTracer.h,sha256=KFHgSJ8NOBDwzrswmf6dNCCW2L2SF8OoqG42NnryF4M,1172 +torch/include/torch/csrc/jit/mobile/model_tracer/TensorUtils.h,sha256=9KJss0Al81LTcQKjbUZJclVKvIqn-0OYrF8rQN2XotA,652 +torch/include/torch/csrc/jit/mobile/model_tracer/TracerRunner.h,sha256=wj-4TNfuyr4Q0yXX5AGbaEI3C7GaGc5o7RTorH3gvHE,1361 +torch/include/torch/csrc/jit/mobile/module.h,sha256=AjMKsMnliGQWiNEY2q6rBJoGg1xq6IvMF5y_QC6_v84,6175 +torch/include/torch/csrc/jit/mobile/nnc/aot_compiler.h,sha256=4QtJt2yncfiqbmu-TdqZXukUJSUoyG299S3SyHwuYMY,884 +torch/include/torch/csrc/jit/mobile/nnc/context.h,sha256=gFDTG6b9go-Oc2gUseF8DNsfvFtdVTlQh1nrzn1PAlA,6870 +torch/include/torch/csrc/jit/mobile/nnc/registry.h,sha256=q_Ba_oX7lIXuiH0Eu6mXvLT1zFEW8X2BhAhGW7EYFv0,1414 +torch/include/torch/csrc/jit/mobile/observer.h,sha256=hVTbIaTwV6srUF07gItgEjCcBrBHw8xcUhLpMji4fm0,4081 +torch/include/torch/csrc/jit/mobile/parse_bytecode.h,sha256=o27oJpF6gCfKzSi8p8m5Gu72LfZXckuzJ6lweJLnCuU,994 +torch/include/torch/csrc/jit/mobile/parse_operators.h,sha256=av7eaS1-HSzMpE57EnjVBcBrr0AzWPyCrKpp3UJW1tU,963 +torch/include/torch/csrc/jit/mobile/prim_ops_registery.h,sha256=nhqJNmc8RtbuOJbMfog5XBknbBnw8lukCYsEnGFVnS4,849 +torch/include/torch/csrc/jit/mobile/profiler_edge.h,sha256=niE7SrUmyxCc4VY-JIRCYDymnDVZ_dscSWwtlI3dv8Y,4742 +torch/include/torch/csrc/jit/mobile/promoted_prim_ops.h,sha256=3lp0XyINie-YHJQbH9bAr1dqcS2L7e5LXcIiLWwDXBA,1297 +torch/include/torch/csrc/jit/mobile/quantization.h,sha256=5yAbohsf1X8ysN-Fdi74gDpcSn2M4JeqBkR-SF1dSYM,1492 +torch/include/torch/csrc/jit/mobile/register_ops_common_utils.h,sha256=qPbFCTpOJiEo2mbQFMdhgA5VYHEg6pTZVntHoTO0Hzs,1941 +torch/include/torch/csrc/jit/mobile/train/export_data.h,sha256=VjByQpzxac0K4d5RSjDZEf7tJXkitv728Sr4ZhxR_jI,1848 +torch/include/torch/csrc/jit/mobile/train/optim/sgd.h,sha256=LQc_NMk3A0J43eJVLbrGme_tf2lonFAUz5xTH_3XoOM,4585 +torch/include/torch/csrc/jit/mobile/train/random.h,sha256=l8ExBi_8l5sQInNEL4XyvgIh5eUWH6H_xci33saSzmc,1773 +torch/include/torch/csrc/jit/mobile/train/sequential.h,sha256=SN3bNiMvPnwhSvmrp9k__pvHli_Xzc2QfFQgdsgN8qk,1478 +torch/include/torch/csrc/jit/mobile/type_parser.h,sha256=Km7FfbDEP84QxWcpTIdLvPMYmpM_g7trabwCUBHLPo0,1702 +torch/include/torch/csrc/jit/mobile/upgrader_mobile.h,sha256=CfF3MVWCIOkQWEbeJj25Ez2jhxR-OzplLf65Oujqwek,1159 +torch/include/torch/csrc/jit/operator_upgraders/upgraders.h,sha256=tBLNg_Aw07Vox9rPhruU1aoMdpadPMCuwdsyDnbuNOc,1638 +torch/include/torch/csrc/jit/operator_upgraders/upgraders_entry.h,sha256=7oBZBxLSNsQZ7E0HLUL2WPbEBtxElBydUtEjAOEvuEQ,776 +torch/include/torch/csrc/jit/operator_upgraders/utils.h,sha256=oD6TyMldIa8D9ygMZ7fmgjOtQTl2hK6Gsmi00gWy-po,1947 +torch/include/torch/csrc/jit/operator_upgraders/version_map.h,sha256=Oq0QWD-3F83cJ1_VmSkv_C8zJW-7Ndwpdfuvwe7fFaI,1141 +torch/include/torch/csrc/jit/passes/add_if_then_else.h,sha256=f0ShcVoByKs00Ld2YqZYXvquWhtqIikV2zornZZkhIc,417 +torch/include/torch/csrc/jit/passes/annotate_warns.h,sha256=02JWzxMLmy_BfOtgIgCmMeA6MMJWOqh1xm3VH4wAdi8,421 +torch/include/torch/csrc/jit/passes/autocast.h,sha256=_qPHpJ7hB1wzcvYWEuzEuEbmD69eteFsNq2IAVQhTEM,496 +torch/include/torch/csrc/jit/passes/bailout_graph.h,sha256=-E0TEJ6zyidaxR7FZTRymeOpVOlGqF2MsJPiQpaZXcs,1344 +torch/include/torch/csrc/jit/passes/batch_mm.h,sha256=DyxWCGNbD3UeqUbNxlUb4mGeKD1rayabjZcO3SVClZ0,385 +torch/include/torch/csrc/jit/passes/canonicalize.h,sha256=v7t65TCLRkIsGRnDhSa2Vlk65tMBGpJ_kMwERKX7NNw,721 +torch/include/torch/csrc/jit/passes/canonicalize_graph_fuser_ops.h,sha256=xN1GwxxzunnJ8gd-M6MtsKR4iy4_zPRWpCyme7EWCV4,399 +torch/include/torch/csrc/jit/passes/check_strict_fusion.h,sha256=MsxAQiu72jflrxZqFGFv8u3-M98BokJpck5ZruquxgY,420 +torch/include/torch/csrc/jit/passes/clear_profiling.h,sha256=5tAIUwLoKnKFfTK-jTGE622dvzxCuguLeqSElDg3wyI,722 +torch/include/torch/csrc/jit/passes/clear_undefinedness.h,sha256=jnc_bdQUATcOY3Jz7fMHoYaBX71k3IIZfqB_NYI8UEs,1104 +torch/include/torch/csrc/jit/passes/common_subexpression_elimination.h,sha256=rofGn5UT4KhFColNDpbnqiXeL5goOP4U0NQutKRNOUU,416 +torch/include/torch/csrc/jit/passes/concat_opt.h,sha256=Z4j3SpgSSm4oteJJPcR8w5455WTVTsSOZrgKYFGO5dA,780 +torch/include/torch/csrc/jit/passes/constant_pooling.h,sha256=En3nfQkAGG3_470VppGHE65MINttbQgqMV2H_Tw6IfQ,399 +torch/include/torch/csrc/jit/passes/constant_propagation.h,sha256=p35UK_K-X2j2XImbtpgrGFpUNO4SXkRxf2m4htvJ_Rw,1543 +torch/include/torch/csrc/jit/passes/create_autodiff_subgraphs.h,sha256=_mlHdBQFWeKNgLAXa2DuUkBNWDekvjaVYYkN8KiTALA,767 +torch/include/torch/csrc/jit/passes/create_functional_graphs.h,sha256=5_fBFCv2Fa6Ns-7LhXrmZBtOL7hlKhIjjTODem5uzQ0,538 +torch/include/torch/csrc/jit/passes/dbr_quantization/remove_redundant_aliases.h,sha256=cMY-yjhfl6j62rOMFYw2usBgHUqA_pemFtc9tjsP4Co,594 +torch/include/torch/csrc/jit/passes/dead_code_elimination.h,sha256=Egpe15Aw5mI7eETml6LIPzIMmhTsEi6m0swVL5CpeGg,1813 +torch/include/torch/csrc/jit/passes/decompose_ops.h,sha256=B9qYNXZWlkJI5Q-RqSPM0UymrH7_748Rd5IWKtwTVQs,390 +torch/include/torch/csrc/jit/passes/device_type_analysis.h,sha256=NFvPZxkTRmVQ6H8iM0hcF_ksf6qiqS38FYAsZQkbdoM,496 +torch/include/torch/csrc/jit/passes/dtype_analysis.h,sha256=GCEVeveWihqGgJphM-DTpPlhNIvcUk3qGYUjUUlvZ1g,643 +torch/include/torch/csrc/jit/passes/eliminate_no_ops.h,sha256=sSidjyAbmaWMv9g-Y_GybSiJOw06wcwHabBXSZ5cuGA,746 +torch/include/torch/csrc/jit/passes/erase_number_types.h,sha256=n37Zgicm7KfOrz5bMFo-oSfjg1V8EXCWdEVwStYT9xM,1042 +torch/include/torch/csrc/jit/passes/fixup_trace_scope_blocks.h,sha256=PRjV9r6yj3s-N1hU1A2DYQSqU2g4I-BbRVRlBNrBh8w,1902 +torch/include/torch/csrc/jit/passes/fold_conv_bn.h,sha256=rGgsRsYYCyvl4oZ3eiHEPFl0NRnhO7sidzFHY-1QR2Q,1224 +torch/include/torch/csrc/jit/passes/fold_linear_bn.h,sha256=o3V0vkB4kiML7iN7KSvGYX20ta-cozpNT2o-9ofvwd8,920 +torch/include/torch/csrc/jit/passes/freeze_module.h,sha256=zsbw3P9Y4vImNTSrHU3a3LCgbtPCC51qJ7q5ArWdkmM,1473 +torch/include/torch/csrc/jit/passes/frozen_concat_linear.h,sha256=R_dFKDX09qS1051w0BQg4QEuy1urm8Rd2nt-6Qhi0f8,506 +torch/include/torch/csrc/jit/passes/frozen_conv_add_relu_fusion.h,sha256=oJ3U7PeMHAuuGK3LDJRwWAVQHU0KRSuzI8-PHM37dKU,558 +torch/include/torch/csrc/jit/passes/frozen_conv_folding.h,sha256=gqsDYKhyF7MI_OpRx7a922ULvGWGpoa4zTW70HFLVxA,1101 +torch/include/torch/csrc/jit/passes/frozen_graph_optimizations.h,sha256=aaRe66_HHQh2uYaDpGH8Od5NzJKDbMqtTdK9I5Nklt0,695 +torch/include/torch/csrc/jit/passes/frozen_linear_folding.h,sha256=YSh0apny-0M41_JuI7Tri2Z1kQf3UZWfrzaKubdir0M,599 +torch/include/torch/csrc/jit/passes/frozen_linear_transpose.h,sha256=c_Dw0bRU5R1w0-nmiPEauljSJgvi88FD3mUgsiCEiJY,515 +torch/include/torch/csrc/jit/passes/frozen_ops_to_mkldnn.h,sha256=cle2FR8ZgXrj4gEaFmqDIcMTg0TNEg3w4L_GTtiTtMs,643 +torch/include/torch/csrc/jit/passes/fuse_linear.h,sha256=VzB0Mw8-Lu4zS1JRwncRxmUMiU9fFOu80orgNp3Y6Ew,997 +torch/include/torch/csrc/jit/passes/fuse_relu.h,sha256=KcwM0AHZQFtb25kONC0f8oW3XYlUBArSZ2Y0oOtQSMo,502 +torch/include/torch/csrc/jit/passes/graph_fuser.h,sha256=nSYOAoLK2QWkUGSCaQ4zI3iTxT6QzFJnRHxrEIuTQGI,1480 +torch/include/torch/csrc/jit/passes/graph_rewrite_helper.h,sha256=WoXBBh9VgNk-MIqbifhEGiX4kh4LU2qs5odFQGXtwsc,1989 +torch/include/torch/csrc/jit/passes/guard_elimination.h,sha256=Q4EZMWjp79bdW-X45G1IdG4TFj1tl6jMKVVNIPXYCUQ,605 +torch/include/torch/csrc/jit/passes/hoist_conv_packed_params.h,sha256=CdAvrvCgDfL7zvtwgHG0AKqrWOdKe_nqbbwaJcOQRlY,440 +torch/include/torch/csrc/jit/passes/inline_autodiff_subgraphs.h,sha256=VZxi6tzq_hzPn3EIzIg2ZtvXBJ6yGfAZc5b7ATbX_ug,504 +torch/include/torch/csrc/jit/passes/inline_fork_wait.h,sha256=OYvgI7lfPVwGsxgnzilm2OJuhkGt6Ltc__35dn0-Owg,776 +torch/include/torch/csrc/jit/passes/inline_forked_closures.h,sha256=8e3yZCxzuikeldUCGUF3XTgAfkeHh6wEyz-KBCulR9k,456 +torch/include/torch/csrc/jit/passes/inliner.h,sha256=ToYyx5gJ37QcV0oTvzDEkDMVJUnb8GYXzk-4hThoCzs,483 +torch/include/torch/csrc/jit/passes/inplace_check.h,sha256=sOI32FKTl3O3s0tHYlg1k_Sn77sEst2-hWueyAj3i2A,390 +torch/include/torch/csrc/jit/passes/insert_guards.h,sha256=AIb_PhMXGon7heho-glI929uIC1Im0meEjOgRZLiIyI,668 +torch/include/torch/csrc/jit/passes/integer_value_refinement.h,sha256=CLQ2zGwDUAv_Y281ot29mm2GgduyL0vK3eujms0Md1Q,463 +torch/include/torch/csrc/jit/passes/lift_closures.h,sha256=td4UuyZdea9dFkD6W7KJODsmMQtFzUloB7ZRJY_zEsc,451 +torch/include/torch/csrc/jit/passes/liveness.h,sha256=Vxa4INJpMYKITv3m8bqOFZfJzDbfDZAfLtMLewxzuUE,879 +torch/include/torch/csrc/jit/passes/loop_unrolling.h,sha256=asj2phSEZGmoy9emUuDzgkc26M2J3kVk5nc6VfTUG-8,1235 +torch/include/torch/csrc/jit/passes/lower_grad_of.h,sha256=QYS_pCq01yGmynQVkT9l0_v1PgmUrWTMs3j5vdWn1KY,577 +torch/include/torch/csrc/jit/passes/lower_graph.h,sha256=rWUkw2SbpYBkvHYsCSnDrqeHXD75Qu2CNPjJJtC8QZ8,979 +torch/include/torch/csrc/jit/passes/lower_tuples.h,sha256=6LHRDOHVsmYyg1ciIF0PdXDX-yf0Wnj42YeXrMISSWQ,895 +torch/include/torch/csrc/jit/passes/metal_rewrite.h,sha256=Aq9hJ1g_b3rQKMBRm5BboxDHVKXCSKYDZ2A_duZ8LQE,835 +torch/include/torch/csrc/jit/passes/mkldnn_rewrite.h,sha256=3VXK9g-dLkqo4FCUmH8MwloWrtA3KtinJYCNeXgD-uA,859 +torch/include/torch/csrc/jit/passes/mobile_optimizer_type.h,sha256=15fTYpsDTiBMHsuAwOxPsTjXIZL37PtFWtZKRgFRn6M,491 +torch/include/torch/csrc/jit/passes/normalize_ops.h,sha256=lXj48gpVeLtNH-4uxdtIKYTCCMgAXEcXwm0pkzDgCU0,765 +torch/include/torch/csrc/jit/passes/onednn_graph_fuser.h,sha256=GBjQKvwNo03pCg9YKeSRbXSn-6QlqFFcvzfLbiU3gfY,1653 +torch/include/torch/csrc/jit/passes/onnx.h,sha256=_UkiWGPLHo91XTx9I-0bagdDtkLgzuNjaI1N9ZLYSYk,1086 +torch/include/torch/csrc/jit/passes/onnx/cast_all_constant_to_floating.h,sha256=dAvOYnKqFVtEHNOkfClRH3eNj7MbSKFcam_kBj4sGwM,471 +torch/include/torch/csrc/jit/passes/onnx/constant_fold.h,sha256=_XQyhSXo2-qnPkq340iCigEeHpih1PVrHls2iSjgm20,947 +torch/include/torch/csrc/jit/passes/onnx/constant_map.h,sha256=5pZuHzoqzXePcJsmaPYCqfEKKnU3sH4uoNwh82NatdY,4676 +torch/include/torch/csrc/jit/passes/onnx/deduplicate_initializers.h,sha256=w1w5ieTjPU34qymJgA_2JGWjoL2bmjx1A7KYQDSzPJ0,501 +torch/include/torch/csrc/jit/passes/onnx/eliminate_unused_items.h,sha256=krk079cOT4rOH11yfKlxBXyD7zx-KH47s6D22eUfaPk,597 +torch/include/torch/csrc/jit/passes/onnx/eval_peephole.h,sha256=-hDeDvDyI7kkdWzqeANeNLyjZ-XhSNCEtFkPrso0_4I,474 +torch/include/torch/csrc/jit/passes/onnx/fixup_onnx_controlflow.h,sha256=QhZj4aOPAdB3mVdIra74SH8ZIDRis6MMDnagak07f-o,475 +torch/include/torch/csrc/jit/passes/onnx/function_extraction.h,sha256=IrN-zKkMc117HwUOPd8rpLrScYQg0BWjVhsKfL3KpNQ,2505 +torch/include/torch/csrc/jit/passes/onnx/function_substitution.h,sha256=UE5MXmhwcKcnThcaJ44yHVQhUJEOYH1Te1cu8ua6dLQ,389 +torch/include/torch/csrc/jit/passes/onnx/helper.h,sha256=RSnKwjRHMLYSn9MBghSauvoIFIEppnUgSwoDodezT9U,2259 +torch/include/torch/csrc/jit/passes/onnx/list_model_parameters.h,sha256=Bjjdu1GfYUC_XzaoNeDd9uFxxI3BtRqHUBeyQsYTFh4,493 +torch/include/torch/csrc/jit/passes/onnx/naming.h,sha256=xARbuBP5w5yHBxa1SqvHvsIgsgSfzjYCLkbYIyOCKKA,1014 +torch/include/torch/csrc/jit/passes/onnx/onnx_log.h,sha256=k7Q3msE4ebSIbatK2SozmuuHhAN6PmDtG5o7na41lgw,838 +torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/autograd_function_process.h,sha256=TzA91rqMukunWZhNt7243zU9XfOm183P5c8xD4y3QoY,429 +torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/common.h,sha256=SwwoOcou_ddWJ-ZZaq9dGO4DUnQVkZ0H2fH-R3je_u8,590 +torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/pattern_conversion.h,sha256=yWht1SKQmZcuKsB72qwwKXcIBtlvzWA53D_S-em-OtI,2349 +torch/include/torch/csrc/jit/passes/onnx/pattern_conversion/pattern_encapsulation.h,sha256=5NhWadoRDuNm59FWVQ_E1vTuD5XUJ9aLvg_7offUD58,1616 +torch/include/torch/csrc/jit/passes/onnx/peephole.h,sha256=CE7EBRjxIdulDb9RKZKCZzDY8_i6ahhbP4Ly1tpep1E,467 +torch/include/torch/csrc/jit/passes/onnx/prepare_division_for_onnx.h,sha256=BMLs0MXEEuJAzJbrSF7RsC0nUBDYEdb1y59QJzDk9gk,705 +torch/include/torch/csrc/jit/passes/onnx/preprocess_for_onnx.h,sha256=YippKvsxqhHWv_oqgC2ZW-RnI-jROrOlQ6V93sCAZOg,409 +torch/include/torch/csrc/jit/passes/onnx/remove_inplace_ops_for_onnx.h,sha256=-hSGx58ku7bXvK-mb020ASWIUnCX2q3W-82DP8zgaPI,455 +torch/include/torch/csrc/jit/passes/onnx/scalar_type_analysis.h,sha256=74SMht0iHAbNST6nalhUdYH4g3maNy3l7HFSQQvGwcQ,534 +torch/include/torch/csrc/jit/passes/onnx/shape_type_inference.h,sha256=SlGyecscNEDgdxVBblR94i56eM2W-I5nHs3FKVXSPB0,4209 +torch/include/torch/csrc/jit/passes/onnx/unpack_quantized_weights.h,sha256=DkcIIjXB_6VqcDWmss6830dM5ICTHG3pgQhqQMOfVuo,681 +torch/include/torch/csrc/jit/passes/pass_manager.h,sha256=LvOMTVmjxz-XJqZKWj9p6k0UwMlRTualwlZQ9Kar8Hs,4803 +torch/include/torch/csrc/jit/passes/peephole.h,sha256=Mo7rrtoHcaYiQXLtAuzLTrq6havHuGUk6S8EI7TwjWc,736 +torch/include/torch/csrc/jit/passes/peephole_alias_sensitive.h,sha256=Sf5RJwOqKFe4iciAVLkp1FrJpjShsvbjVHL5By-XDQs,664 +torch/include/torch/csrc/jit/passes/peephole_dict_idioms.h,sha256=V1wOXOIN92YLg3pFp1SYwO3zuCxe_c7Iwq9coIatUZU,1229 +torch/include/torch/csrc/jit/passes/peephole_list_idioms.h,sha256=y6BBOysIaiX9LXvuefeadCFj2p0s4sko4-GsQYPnxnI,2232 +torch/include/torch/csrc/jit/passes/peephole_non_tensor.h,sha256=skm22Pz51el-KVG0k2jh9gR8wlDOKfcR5NDQPmsHaRE,571 +torch/include/torch/csrc/jit/passes/prepack_folding.h,sha256=kX30fJNLOVaYaUVY2f1iQk8VySYqlOXv3gi6m5vQy8k,587 +torch/include/torch/csrc/jit/passes/quantization/dedup_module_uses.h,sha256=cLkTsvEGzKSDL1wyuvvvBBagD7DnVXlXTcwj3pTF-NE,1055 +torch/include/torch/csrc/jit/passes/quantization/finalize.h,sha256=NOznEDnXUPcF3Li_yCDojROHgq5XIoK7qirjIZe42a4,2549 +torch/include/torch/csrc/jit/passes/quantization/fusion_passes.h,sha256=7MHhqzRUYn7PztFKJ-wXW57JLKNQHmiJ6M06Ybi0VAY,420 +torch/include/torch/csrc/jit/passes/quantization/helper.h,sha256=MMFMaD1PNwvUSsdkkfdf2eK8XKpYuFfzysXyiEp33U0,7713 +torch/include/torch/csrc/jit/passes/quantization/insert_observers.h,sha256=k4Z0aSWRs2a2AiHnJPddEr10qb8XtqaQS4VTIRmICiA,2580 +torch/include/torch/csrc/jit/passes/quantization/insert_quant_dequant.h,sha256=sv9uH-qDkwIiS6PfV9KyTuw7SN_xZo40mAGHL7-TXME,1679 +torch/include/torch/csrc/jit/passes/quantization/quantization_patterns.h,sha256=nVuCWglRGn8GapPIMorfzlmlaNsc8uv6H0BNmKS3-k8,53615 +torch/include/torch/csrc/jit/passes/quantization/quantization_type.h,sha256=1MjTQ7coNAARQy0W3o_hvfMv-3Wl5VhThENqY99fiBc,587 +torch/include/torch/csrc/jit/passes/quantization/register_packed_params.h,sha256=qPhixrMBoFVCr8GWDqs-v4jIiDDai3ytqbv23aMeDWI,743 +torch/include/torch/csrc/jit/passes/refine_tuple_types.h,sha256=97LywtAOszRtA9MQscOX8gLmB2pZzXQZfEz9C4wtaUg,496 +torch/include/torch/csrc/jit/passes/remove_dropout.h,sha256=ANNXHbSIIcRmZpBcoC0ZlsPAsGgJoobsWCGrLK-gMKI,509 +torch/include/torch/csrc/jit/passes/remove_exceptions.h,sha256=BSf7-h68dGHJ4OCbxFH5G53zLAnqgcQDCnwjb0kvnbM,1183 +torch/include/torch/csrc/jit/passes/remove_expands.h,sha256=_wMfo-Lk2Kkru2UWb7wxY5SjZd9ch-_DVvaTdVXoAjY,397 +torch/include/torch/csrc/jit/passes/remove_inplace_ops.h,sha256=ZeX2AINr3DaNyLJT4mGcwIhT2nwwNi-TjFpVD5_tMSQ,525 +torch/include/torch/csrc/jit/passes/remove_mutation.h,sha256=v_hHpZwvYKxAo3S7AcIURHmz-lI3Zv5YXMnuTM-8wFo,2891 +torch/include/torch/csrc/jit/passes/remove_redundant_profiles.h,sha256=zcRHNfhQ46hRnX5G1vNJJGdNf5ln9O2zFZDmf1REyFM,491 +torch/include/torch/csrc/jit/passes/replacement_of_old_operators.h,sha256=Vt8IwExtBSQL8GgsGUMuAonB3K7ZjfkBzRCHUQOv5L4,688 +torch/include/torch/csrc/jit/passes/requires_grad_analysis.h,sha256=NS7EqB2A-1reB4lsvoL4Yp-sxnWfQFNyr7SIaHzhmyU,475 +torch/include/torch/csrc/jit/passes/restore_mutation.h,sha256=eOvMa99BGqwPfZPgiS0QOq5U0BQJAcNHygQHZzcm2BA,2055 +torch/include/torch/csrc/jit/passes/shape_analysis.h,sha256=lmNddX5YF6phTtpKEEj2EuaShFHmG4THQyB7Td0qHbI,1331 +torch/include/torch/csrc/jit/passes/specialize_autogradzero.h,sha256=21kPaHTi-xVHnofwW5P0sK73y-1XsKnl8lMT0SsSy64,885 +torch/include/torch/csrc/jit/passes/subgraph_rewrite.h,sha256=wMJHB3HCrYpqgBex6Kys9oWZ7OB6xt0nfIOK5pE_PSE,4313 +torch/include/torch/csrc/jit/passes/symbolic_shape_analysis.h,sha256=TOMd0js5rYIWV05AFpf-PJq9OYXUoaFBOl707VvPZvk,2332 +torch/include/torch/csrc/jit/passes/symbolic_shape_cache.h,sha256=sXd7qzIrY6LAcp9iudjXKO23O9J4iS2hMVpQw3QS47I,1828 +torch/include/torch/csrc/jit/passes/symbolic_shape_runtime_fusion.h,sha256=4iaGOWsWHkIxvrF_taM9WXTSThyIx6OmM8n1Qp5B4WQ,2596 +torch/include/torch/csrc/jit/passes/tensorexpr_fuser.h,sha256=jyONtWtdCsH3QVkE3KqE5fpTLqzHJB37sb_be1e9w34,2952 +torch/include/torch/csrc/jit/passes/update_differentiable_graph_requires_grad.h,sha256=hwcyT7I6dlZWCmLqedbalUm73IvOfAKMhXlZwUZdWcM,969 +torch/include/torch/csrc/jit/passes/utils/check_alias_annotation.h,sha256=hBYq1dwM4MiGPCY1e89K2uxovD2u01KNkHu-c4A4-4s,841 +torch/include/torch/csrc/jit/passes/utils/memory_dag.h,sha256=PgqnB_pKQxz3le9erTTycryFQ9q1YQTz4eri-0wna5o,6645 +torch/include/torch/csrc/jit/passes/utils/op_registry.h,sha256=2egFx0dFliiCY71fhR1HkJKYJrZEA0v4t-0tAITc65w,1262 +torch/include/torch/csrc/jit/passes/utils/optimization_utils.h,sha256=AiONhxLLO2m3l_G7mcAX1xZigva1RrBJHvUoa78ITNw,473 +torch/include/torch/csrc/jit/passes/utils/subgraph_utils.h,sha256=NTZJ2TZ3LpMsje665S60ulrvfG54IKWMn4PHR0x9Rtw,2614 +torch/include/torch/csrc/jit/passes/value_refinement_utils.h,sha256=nDJhO_jc3-arA7JW5WdnWn-s5EKgx4sMEAxsRGXQSlQ,2861 +torch/include/torch/csrc/jit/passes/variadic_ops.h,sha256=gB8X2YrJJvpMxajBSMk36y4Wb-qGMed2vKIKiDBpzE8,1139 +torch/include/torch/csrc/jit/passes/vulkan_rewrite.h,sha256=2am84jm42Je81wqkg8oNJVsSLY39hhxK7nygP7eCLiI,927 +torch/include/torch/csrc/jit/passes/xnnpack_rewrite.h,sha256=yl8n6WNwyx2L4_aH4hUE1UQrbAWO23sZ3qVB_oZLwB4,1049 +torch/include/torch/csrc/jit/python/init.h,sha256=vNYIEI_xN8J5Mt06W0zqxyNmpg9sVxwgpW4zkp037QI,397 +torch/include/torch/csrc/jit/python/module_python.h,sha256=igT4tAZwKBYHmEtHSUyXp8SM_cpiCsWBbJ2y-u5xO_I,2127 +torch/include/torch/csrc/jit/python/opaque_obj.h,sha256=kZy2BWyyma9BVgtF4Owx_mJ0Aj3CPLn-5eh12pf0CE4,3135 +torch/include/torch/csrc/jit/python/pybind.h,sha256=oRXJuaMzSL5txY51K_YchGAQ5AKXuFO6v0JL3EQ3o1c,8207 +torch/include/torch/csrc/jit/python/pybind_utils.h,sha256=lH_zGcY4SeMvMlYkOzoFLCUfHIveIIFsaOBWKXBSbho,45993 +torch/include/torch/csrc/jit/python/python_arg_flatten.h,sha256=T_5P6SeD4L0HwgiF1EgBaOJTns53ObnKlrWo8uuSwic,3781 +torch/include/torch/csrc/jit/python/python_custom_class.h,sha256=ld9_AGKC_-TTIhJ8Arb18NskKGvOhmKM5Mk4hb9gqRw,666 +torch/include/torch/csrc/jit/python/python_dict.h,sha256=e65iniG3Ub_X1jSODTItW16T6Tj3MzmqiOm_5Akii0A,3648 +torch/include/torch/csrc/jit/python/python_ir.h,sha256=WvU_pTbdoTY5yQQ9wJIv6f4ixvr2pfKZ8bAYW7M9Vws,1947 +torch/include/torch/csrc/jit/python/python_ivalue.h,sha256=RoKOjA5RuPZwble4J_LxmG3vg8Epbd6rSDCnia1nEkg,3936 +torch/include/torch/csrc/jit/python/python_list.h,sha256=sYq8-3ldysEG7wSxTtO9JANKGjqHnQdCyVlFn3XaFpc,5759 +torch/include/torch/csrc/jit/python/python_sugared_value.h,sha256=OWOjMwm4H3Mb9lr1hRca7uvAAIIy2jR3TUvfli7-wfk,11590 +torch/include/torch/csrc/jit/python/python_tracer.h,sha256=4T989L04dccgGxgHBXghLodx48imnb7nUfBxO4GiieU,1472 +torch/include/torch/csrc/jit/python/python_tree_views.h,sha256=RPY1Ogr9vgVgg_hAE3ISyF_xYAWp9If4kdwmcaE9TuE,404 +torch/include/torch/csrc/jit/python/script_init.h,sha256=XgA-WXGN1XrJwXmirEGVqc5UtY_KWNb4fUQX-Thfj2E,406 +torch/include/torch/csrc/jit/python/update_graph_executor_opt.h,sha256=xdKRIbEiJewN_qDogGpAFIuyhaoeX-X0n2_4nB6bAwg,439 +torch/include/torch/csrc/jit/python/utf8_decoding_ignore.h,sha256=B6blNz_2z3iECmAe7j7YLkDvvI8C1qS_3XOQE_Xqz14,433 +torch/include/torch/csrc/jit/resource_guard.h,sha256=SlgztVvYnO7gH67Es8lAgD36-otV1Z4Bwha1Lbf3yfQ,694 +torch/include/torch/csrc/jit/runtime/argument_spec.h,sha256=_mIkr67u1ZpRio_TZO4qvY4NYtuwH9A0iVLXRmih87A,16639 +torch/include/torch/csrc/jit/runtime/autodiff.h,sha256=gk9xNh2dJ_7kotDK_PPTRN7X7GfS1U5o45FqkUpuUYw,4184 +torch/include/torch/csrc/jit/runtime/calculate_necessary_args.h,sha256=VHcSKHiUe_SXS2K7hyc0uG-4OgZQFjZcnzKEgmUz3LU,2535 +torch/include/torch/csrc/jit/runtime/custom_operator.h,sha256=h1APxS6uYOLL9pKJ-xoAcoRb8m0gwaD2lD2S4OOBodc,1308 +torch/include/torch/csrc/jit/runtime/decomposition_registry.h,sha256=rqzNfixCRRvSIACDilIpQSyJ2bcFI0DMJ34B1F92LkQ,1299 +torch/include/torch/csrc/jit/runtime/decomposition_registry_util.h,sha256=x-tYdDgODVbKlfH9CdiePOmbQokrbO3ceTS2Bb_aAtQ,515 +torch/include/torch/csrc/jit/runtime/exception_message.h,sha256=BslHUofsN8BPUqzFUOSbCR4K_vn-6jpuoqMVGyILQhw,868 +torch/include/torch/csrc/jit/runtime/graph_executor.h,sha256=Uf_YQ650NhnpoYN5ZKp78F6NWlmgrANPrs2SPFvkQp0,5237 +torch/include/torch/csrc/jit/runtime/graph_executor_impl.h,sha256=z7RvxYg1R1CgVKtoxxu-cDBhybJddJhgF4fv4voCSVQ,4617 +torch/include/torch/csrc/jit/runtime/graph_iterator.h,sha256=jCz577Ln9PoIwzyx0FEzkHmdqav5fqYC9nJ-_nUNPGE,5192 +torch/include/torch/csrc/jit/runtime/instruction.h,sha256=29MNt2M4kKwP_BhDfpzVJTLAsgDIdUJnUtg4Cft0s7s,5798 +torch/include/torch/csrc/jit/runtime/interpreter.h,sha256=Ae4OGN2Iy6Y2UDGsYHqn6qu2gaLr-K5nbeGU7kHXqtM,5245 +torch/include/torch/csrc/jit/runtime/interpreter/can_emit_inline.h,sha256=y9NZJmjJOWpkZq_E_dI1c2TixH-NoSmaWqzjqmPenuc,4208 +torch/include/torch/csrc/jit/runtime/interpreter/code_impl.h,sha256=Ys8oMsJj-suV9eVd2AOiNT6ajcF_qutC0GRhFyOYhxc,33556 +torch/include/torch/csrc/jit/runtime/interpreter/frame.h,sha256=VeercdUuV2EqaQPgEg_4bANdttPbyxOWtq0cHVlxl-I,1364 +torch/include/torch/csrc/jit/runtime/interpreter/preprocess_graph.h,sha256=nTwhXzmPZROEwL6x3Xa7DSHHelnHkxbUnRZjjQmwIek,655 +torch/include/torch/csrc/jit/runtime/jit_exception.h,sha256=Zc8QecTVAQX8NJmO5jyOlbhiMI85f6cHAPrnrsj-QJc,1423 +torch/include/torch/csrc/jit/runtime/jit_trace.h,sha256=QOfLSGozBn6GWvSU8lZP2ei3H341v5_c56RaQKHo-Do,461 +torch/include/torch/csrc/jit/runtime/logging.h,sha256=dw5NkNpPi_XUNYg7PZ7Y7iBC5ziQull3pL8OsMiU80o,2868 +torch/include/torch/csrc/jit/runtime/operator.h,sha256=QxeTiTRGXBnITzN3J8HLy_XAet13fcSinXc07axWDRA,11869 +torch/include/torch/csrc/jit/runtime/operator_options.h,sha256=aKyUKJcXMUY2coB-r6w7Gn5MqM6Oi_gagAUreCBz3fs,418 +torch/include/torch/csrc/jit/runtime/print_handler.h,sha256=Y8I3uAqbeTiRz0PGKPPuddwV3K-x5TsFUaiHsQx3Tx4,562 +torch/include/torch/csrc/jit/runtime/profiling_graph_executor_impl.h,sha256=VDgNi6zLZCugkS7NMOd_vG4AD-FhLLLNqUJlxF4gDx0,3453 +torch/include/torch/csrc/jit/runtime/profiling_record.h,sha256=wCXL_IPVjkMmPucrAERwv0-7J24uH4BUiArafMW31Xk,8813 +torch/include/torch/csrc/jit/runtime/register_ops_utils.h,sha256=PJofH06R1j7lCH5GiiUIqrJsGSCJAHy_z6VA4Egh1eQ,41018 +torch/include/torch/csrc/jit/runtime/script_profile.h,sha256=N1X3tzFIej3-eVHceltWERDxdGVPZVSCLILcwva1q3I,2890 +torch/include/torch/csrc/jit/runtime/serialized_shape_function_registry.h,sha256=mcuHossgV1v7dKRzyGnfhZFyhXsTzDnaWN6Y9HT9Mjs,610 +torch/include/torch/csrc/jit/runtime/shape_function_registry.h,sha256=uoL-f3SUaAQuiukKBOihRcRjbGI4RW7UYHcnDV3cN6o,497 +torch/include/torch/csrc/jit/runtime/simple_graph_executor_impl.h,sha256=99zYDUdxqtTqzauiZUd8DFazx9gFybNDk3kXzadfvPM,1011 +torch/include/torch/csrc/jit/runtime/slice_indices_adjust.h,sha256=n3jrzM_G9_3ccL-w6g17Klgv7m7OZx8Nt4ueF-AYh6s,1036 +torch/include/torch/csrc/jit/runtime/static/ProcessedNodeInputs.h,sha256=0VsG_EWU4RlKMytyPWszfKkN9r1tsUguema93szWs20,6657 +torch/include/torch/csrc/jit/runtime/static/fusion.h,sha256=tbkTq6d876UIXZJUIwG1E9y0Y9G51l38RPRvcDOehC8,561 +torch/include/torch/csrc/jit/runtime/static/impl.h,sha256=jPxawI7zyfq_6HBqa-9yVa4qbD-ki3EGRPXz29T2vNU,37577 +torch/include/torch/csrc/jit/runtime/static/init.h,sha256=aNaEAVBJYoov2lPcnGzHAgfMYph6jxyAOUfRrxrQK-c,403 +torch/include/torch/csrc/jit/runtime/static/memory_planner.h,sha256=J4ta170Vh1I_hSfwvvzKef8mCqWVPmo2BvPU0J3CEjo,10180 +torch/include/torch/csrc/jit/runtime/static/ops.h,sha256=GrGWJIJhEzrty7e7durcCmLJxUp7GsXp9w7_Y6OxQLA,5835 +torch/include/torch/csrc/jit/runtime/static/passes.h,sha256=Wu3GXnn1CiiP90I5bgtelZQYEn3jFL6arF5X6PsE1MM,3938 +torch/include/torch/csrc/jit/runtime/static/processed_node_wrapper.h,sha256=My4mV4TP1f4HOTVOPj3RQZoKXFIX2haaHuuXnH7Wo9A,6849 +torch/include/torch/csrc/jit/runtime/static/static_method.h,sha256=I9CqnYsJgIzLyVJz-US2O8M0_O6F6J8DgzBOkihoTKY,1578 +torch/include/torch/csrc/jit/runtime/static/te_wrapper.h,sha256=MKHuU07WRx2w7L6AbXVEe9k9PVAUvgmHwZXz_kp4x4s,1399 +torch/include/torch/csrc/jit/runtime/symbolic_script.h,sha256=g3o1hzSledXLC_qGXaW00L5ceN_5f9GkUcsHVj0oh7A,816 +torch/include/torch/csrc/jit/runtime/symbolic_shape_registry.h,sha256=OhMa9p-mfJyzj-iQGgK97aIowSuoWM1_aFwYp5JN76c,3056 +torch/include/torch/csrc/jit/runtime/symbolic_shape_registry_util.h,sha256=x2o-VKti7VMmmQqOIINueRcjcddhyRBLSAhZyYTkFGQ,605 +torch/include/torch/csrc/jit/runtime/vararg_functions.h,sha256=Dg4diTeVlhZDz5qybOePbxEH96ct6Z7O7kVahn_oErg,1402 +torch/include/torch/csrc/jit/runtime/variable_tensor_list.h,sha256=fEV6nglRgQkc_2-Gag2kf9lwJ_z4FV2Q5M7xOjUZs-w,781 +torch/include/torch/csrc/jit/serialization/callstack_debug_info_serialization.h,sha256=QcsfMxPT_pqRc7EASChDRGo24Qs4FWRoXsHqcdDdBSw,2858 +torch/include/torch/csrc/jit/serialization/export.h,sha256=OV8uGt1LFq9OTJjdr93P8nFMLyFz79IWxnPZPnjNtTs,11744 +torch/include/torch/csrc/jit/serialization/export_bytecode.h,sha256=K5fnIyMk2cOEvawaXbJyMwhwPkzwAnCjswZdjiK9Sgo,1622 +torch/include/torch/csrc/jit/serialization/flatbuffer_serializer.h,sha256=zVHXB_S7tz5eQ9_ams7Zs_rfLWZsP_2dSMBNC1ttAKY,3297 +torch/include/torch/csrc/jit/serialization/flatbuffer_serializer_jit.h,sha256=n-sfcJ-3xmrwI5jpCFXoQvSaFEV-gp8tVB_yphdoAXc,426 +torch/include/torch/csrc/jit/serialization/import.h,sha256=CBVFVUcoTm_zaWm7uoqeCR_Zd0Mt-9ViWQ2RZYF-B88,5085 +torch/include/torch/csrc/jit/serialization/import_export_constants.h,sha256=4oXjn6hyyJNAWk5su46kkyjStM189G05kktdT7N43g0,899 +torch/include/torch/csrc/jit/serialization/import_export_functions.h,sha256=LwcXblZza7xkyq0Rka34tHdsd_mTGmyT4tJpoEIsavs,643 +torch/include/torch/csrc/jit/serialization/import_export_helpers.h,sha256=4eXPN8wLr2YGcnCxglW8a3uQP4JarUu6znXfw2Jutt4,905 +torch/include/torch/csrc/jit/serialization/import_read.h,sha256=A5y-7aXZN_AsR_Xs5TeAUFDzu3DKU6pGwuPiv9nCKKo,1086 +torch/include/torch/csrc/jit/serialization/import_source.h,sha256=CsfRD-msOa4zp7bsm3GFRueWXoNKllKtqBnc12E_kQ4,3678 +torch/include/torch/csrc/jit/serialization/mobile_bytecode_generated.h,sha256=lsTXYABe5eo_pIVoaEkB6afoTkB2GZ-m1t4_vPHng5g,98868 +torch/include/torch/csrc/jit/serialization/onnx.h,sha256=qJhopSKUjvWlH2obLaaYCTMrW9W2qnZJVAjN3PNLEQ4,767 +torch/include/torch/csrc/jit/serialization/pickle.h,sha256=pgfxjFeY2B8EbGlNOh1jGnlAN27A9C8yCCpp9RN3AdA,4944 +torch/include/torch/csrc/jit/serialization/pickler.h,sha256=irAEuSyKkGnm_noEteCownc4zn_IhkGUOf2Cr8M3JKY,6589 +torch/include/torch/csrc/jit/serialization/pickler_helper.h,sha256=JP45K7oJ56Carbn1DE4qVTiZpdU4Xp_kbzXgarec2_M,7204 +torch/include/torch/csrc/jit/serialization/python_print.h,sha256=N-gq3PVba8pfhIElWd3BStwWTrR0VpgfM_fOyYZhY6U,1563 +torch/include/torch/csrc/jit/serialization/source_range_serialization.h,sha256=7g9X73noS0b5SL75D4qkmSh9Y5b4eFSaII8TEps4a88,1920 +torch/include/torch/csrc/jit/serialization/source_range_serialization_impl.h,sha256=N3-0_YKngFCYPWVg-vLqjo4NIoJZIHDwubKSEIpWFt8,934 +torch/include/torch/csrc/jit/serialization/storage_context.h,sha256=ndqEnG2nx8IYCScZEGgfSfnK98O8LmTkFsi6nqzGpy8,2741 +torch/include/torch/csrc/jit/serialization/type_name_uniquer.h,sha256=WeGv4RvmdKHQWZkT8cxnS0LXKLkYMVTsfLiGVFFFkfs,1008 +torch/include/torch/csrc/jit/serialization/unpickler.h,sha256=wF1HWI6CT-NqrxfAgrdJBpyBkxIfgGD8p1TLxYhaygA,7938 +torch/include/torch/csrc/jit/tensorexpr/analysis.h,sha256=2ujRn9DusgJSx48wfTBcafF_OmRqI2ZUhSWEON_QUo8,9236 +torch/include/torch/csrc/jit/tensorexpr/block_codegen.h,sha256=rWfhdJdSRI5_Yci_08AdMpAo9DxYL_IGeIxcTFB1qEI,4544 +torch/include/torch/csrc/jit/tensorexpr/bounds_inference.h,sha256=X7rqLiu36NbZ8xyWLHI51dPOxAF0FEB2ZngozgS6FBo,2424 +torch/include/torch/csrc/jit/tensorexpr/bounds_overlap.h,sha256=POI0b5L1nBfL4rdkw8nE_E0-hR_ZFPit_2YluH4tdFw,4726 +torch/include/torch/csrc/jit/tensorexpr/codegen.h,sha256=Gl-PYYGtvgAeIGnXzfIoDlxgaENonD3YbA95eHqwDsQ,7820 +torch/include/torch/csrc/jit/tensorexpr/cpp_codegen.h,sha256=vql6RehQDmUSOGYtaNMfYCnOLkDpUJQbFOIu8kbpB-8,2706 +torch/include/torch/csrc/jit/tensorexpr/cpp_intrinsics.h,sha256=f2nVKYuxGRr0dRpmYBC2s2HouEh_UrCkirRB084kxgI,887 +torch/include/torch/csrc/jit/tensorexpr/cuda_codegen.h,sha256=1tNyoT2slJt8I0eUCv3hvk2vWHCvkgFoIFuC6cpe8l0,8488 +torch/include/torch/csrc/jit/tensorexpr/cuda_random.h,sha256=xNgNZ6ulyIg_RXjBcuLSywKlfFPlfLbYooFQ7o7Igqg,2846 +torch/include/torch/csrc/jit/tensorexpr/eval.h,sha256=di5-_tg9Wxz_zZO1_TfSzETK-BjVWIhrjjHU1AqB0Ps,10097 +torch/include/torch/csrc/jit/tensorexpr/exceptions.h,sha256=h4tscEytrsVBp0FeDu7dQ1a70SyqvhE2zK52gBNLE-c,3475 +torch/include/torch/csrc/jit/tensorexpr/expr.h,sha256=kwHPQLgNNggfMmRuhW-nG_Kx70oBKGCKLvp-pCwyUTU,14435 +torch/include/torch/csrc/jit/tensorexpr/external_functions.h,sha256=TbX1FLAD27y78pp0ibNQbkAtkrRedl819pSEnsCrkkM,3687 +torch/include/torch/csrc/jit/tensorexpr/external_functions_core.h,sha256=-XniYhj7ULLZaIJXLxOmVi5R8M6QoPsppkZ792Xe-rU,707 +torch/include/torch/csrc/jit/tensorexpr/external_functions_registry.h,sha256=pFmM_5RCB22qFInr1mwWoX6hT4vyDDiOMNflfcxlJLE,2560 +torch/include/torch/csrc/jit/tensorexpr/fwd_decls.h,sha256=QoA0Vbh_h-33YrgqSpyn0XvheH9Ubfmy1SQZOkqRrKo,3244 +torch/include/torch/csrc/jit/tensorexpr/graph_opt.h,sha256=nztWGJXqgy2d55nJrA_O1rHuw_32tfUVTDHuQAD_t_Y,4688 +torch/include/torch/csrc/jit/tensorexpr/half_support.h,sha256=9Y-LYGyA0Xqs3NNqzhw4Id-6x2eds0c3AzxgCJ042eY,6143 +torch/include/torch/csrc/jit/tensorexpr/hash_provider.h,sha256=jLdf_4-MfynXkEDYYvxgQM_lvXSdb_WNbkO6RIxouCk,7825 +torch/include/torch/csrc/jit/tensorexpr/intrinsic_symbols.h,sha256=qc_HAjNnjTPricyApZe-ah89dmIydG-_IohjaC3QOKc,674 +torch/include/torch/csrc/jit/tensorexpr/ir.h,sha256=5AXa-hM0bsST1tTzs4WhBAB-BjJTGgE-6cX8kza-IgQ,23233 +torch/include/torch/csrc/jit/tensorexpr/ir_cloner.h,sha256=88KpZ7EwH5QwR694Lo5gWCj_T8aFTEGXeckCtLbxa9w,2597 +torch/include/torch/csrc/jit/tensorexpr/ir_mutator.h,sha256=xIIYd3jGDJwGQNYNJNGY4zTxONONq1WKhrE4AZ2bzJM,2623 +torch/include/torch/csrc/jit/tensorexpr/ir_printer.h,sha256=i9QX1RBE-T_EsYICKb9FmzdRLhVbPwcC21bbV3110HI,4515 +torch/include/torch/csrc/jit/tensorexpr/ir_simplifier.h,sha256=bfo3nS5BWEJIm5P0d1GWxuLFnpUUSjx2Z0tY-YmGscM,15511 +torch/include/torch/csrc/jit/tensorexpr/ir_verifier.h,sha256=3BIXofQLDRbC4f4oXyxtB8hPZmr58EN6TY6bye-3qaI,1567 +torch/include/torch/csrc/jit/tensorexpr/ir_visitor.h,sha256=yGeW-NEbk9Sr3JWyN-BpTqxWAIIkHFeXVJiA3FwYGoM,2441 +torch/include/torch/csrc/jit/tensorexpr/kernel.h,sha256=9WGYY5qqKt2evd4NCe8sK0fEXFjB-5cQgQUkE9QSV_k,13646 +torch/include/torch/csrc/jit/tensorexpr/llvm_codegen.h,sha256=iNG4AcV8blDZASUGlAHJfsKNp8NwPj_STQD6XhXuJ7E,4093 +torch/include/torch/csrc/jit/tensorexpr/llvm_jit.h,sha256=ti8Y7XRaZTbRofvOim-pe8htkhIK7WiApV5MpaOow2c,2274 +torch/include/torch/csrc/jit/tensorexpr/loopnest.h,sha256=ct1Q2yto3BMlMyYcCHRV5nHqRnAjgqzynIqAXgCpVyo,22032 +torch/include/torch/csrc/jit/tensorexpr/loopnest_randomization.h,sha256=QYpdnfuqv9YlA0shpYVSoSC3ZdbBEU1k334eMSpl7X4,563 +torch/include/torch/csrc/jit/tensorexpr/lowerings.h,sha256=uLQ7cEVTUanhRoUj70V77d63qmEtEQ9NxOqnYmYAK-c,1534 +torch/include/torch/csrc/jit/tensorexpr/mem_dependency_checker.h,sha256=uZGsYXWIela0_0tBuKxr5Nj6fgEoJdouzDv4--ofZ-Y,13716 +torch/include/torch/csrc/jit/tensorexpr/operators/conv2d.h,sha256=NKC3IMS43R68jwounzCjcpK5kMXbyi_zHXJ_TEeYutI,3147 +torch/include/torch/csrc/jit/tensorexpr/operators/matmul.h,sha256=1_W_nubAKxRtQElE8cIbHUIMnYUpzGh0S-ubZDcUmpE,857 +torch/include/torch/csrc/jit/tensorexpr/operators/misc.h,sha256=Keqv3pTo-YL1k6Sk1uPn-WmQVKd9k5HOIv1yWKXtGfw,3542 +torch/include/torch/csrc/jit/tensorexpr/operators/norm.h,sha256=iP-nTSjXKVrcIJ0BhRfPi0Ureik5eHY4o-D6GIQST_Y,627 +torch/include/torch/csrc/jit/tensorexpr/operators/operators.h,sha256=_Ry3BgjJ7jD_7tip9TcAr456eHg-MBLFOI5SHIBh0vU,725 +torch/include/torch/csrc/jit/tensorexpr/operators/pointwise.h,sha256=8C9DJI3SpUov7VAGWsLgxd0QJFCvVan4zDiUBZVqkVo,3413 +torch/include/torch/csrc/jit/tensorexpr/operators/quantization.h,sha256=ELez7-v-cjZ4jo1uGghV51V34zyyNn9fNJhqnATQNrg,5543 +torch/include/torch/csrc/jit/tensorexpr/operators/reduction.h,sha256=o5Gm21oXdYuDycCYgzDJmTNYx1ORWT9FBj21QvWlDbc,1359 +torch/include/torch/csrc/jit/tensorexpr/operators/softmax.h,sha256=E5SPmORIGJGA7T-WsbQ17XGeOtEAP40S2RA6qXewEZ4,575 +torch/include/torch/csrc/jit/tensorexpr/reduction.h,sha256=Zo9e20WrMTn9EsjXhKysDghOiOxhF6PcU7U2OsE5pik,9119 +torch/include/torch/csrc/jit/tensorexpr/registerizer.h,sha256=-apv060BtczjGNGMKYGlgaMlR--3McM7Z0CoVyqBGU0,12772 +torch/include/torch/csrc/jit/tensorexpr/stmt.h,sha256=KX9ydeQE8JsiupZEwuNoTgJMTZCfuo02Ozif6Oc3Uq0,24074 +torch/include/torch/csrc/jit/tensorexpr/tensor.h,sha256=uzw4CIqoSprQabliELSqixZV38OH-1gNYWce6a58PMQ,10753 +torch/include/torch/csrc/jit/tensorexpr/tensorexpr_init.h,sha256=g29feo9fFx5y7g8-FTKgkyLz-067Vk1UgEbGJPhBIJ8,497 +torch/include/torch/csrc/jit/tensorexpr/types.h,sha256=ls0n0cz6lJyckv-FRNmAr9qUg3R3ynRJsA7J3Zc9MDM,4536 +torch/include/torch/csrc/jit/tensorexpr/unique_name_manager.h,sha256=SRV0LH8tZ03D2QOWlDf_UypE8KW8OY1taliuZ98eNA8,1079 +torch/include/torch/csrc/jit/tensorexpr/var_substitutor.h,sha256=kyXzHdMPDXrWW6qexm2NdLuZDoOckM047EG7gDpSAyk,1914 +torch/include/torch/csrc/jit/testing/catch_utils.hpp,sha256=9J4-d643UOXpEEozt3uj9IjBEOiYzO8hQl6MSrJvwWA,607 +torch/include/torch/csrc/jit/testing/file_check.h,sha256=kmx_9WCtQPYXNBEY16EtQa7hPG5_hdpQ9oUUQRDRcHQ,2797 +torch/include/torch/csrc/jit/testing/hooks_for_testing.h,sha256=qW-z-AW6Bh843JWoG1EaMaGtWnsCIBhSJ_s2BeZ6HOA,832 +torch/include/torch/csrc/lazy/backend/backend_data.h,sha256=KFer511g6xsjax-CTfHhesSd6iVyK-I9Lu0tm0OLfWA,1434 +torch/include/torch/csrc/lazy/backend/backend_device.h,sha256=FHbt6vo6-M7P6RPmTEHsn-wci86hDzaUKpJtokkDzmo,3165 +torch/include/torch/csrc/lazy/backend/backend_interface.h,sha256=LDrHg3jqgn--27fk9LjLLPvFah-BC5CAJeNyGfpQ0i8,5057 +torch/include/torch/csrc/lazy/backend/lowering_context.h,sha256=ByjZ8kTR6xJQv3djqkb8-FVoTwU7KiaMhQod0sCxbnI,3492 +torch/include/torch/csrc/lazy/core/cache.h,sha256=NPX66NO6k1kTnOuxuoXhvqDKeSggJgYdX9ycmXZS_0s,3979 +torch/include/torch/csrc/lazy/core/config.h,sha256=NTCfI1DLjGKJ_CenoDuhGgOGFA1CNiRKQIPikR1UOTk,1165 +torch/include/torch/csrc/lazy/core/debug_util.h,sha256=WofYQtKMOilg_NYSJJGOVpp0-j620_Xow_uq4OKOHdg,1528 +torch/include/torch/csrc/lazy/core/dynamic_ir.h,sha256=r5M9Jz8i2QslpW347zzyDieFodJ2RKDqeouU9CLhr_o,1651 +torch/include/torch/csrc/lazy/core/hash.h,sha256=JqcW9fbKY4LHGuK2n-TKi3FXzIlOMW7hEftR_o5Lvzo,7853 +torch/include/torch/csrc/lazy/core/helpers.h,sha256=nC50hBHhTPD_RSL5oe3beZlPpSM5J-VbtaHYVwToBxg,2475 +torch/include/torch/csrc/lazy/core/internal_ops/ltc_ops.h,sha256=u7eSsjmKarTO6HoXAQmGB6ovkv4heVKITcGW9z1CdB0,1704 +torch/include/torch/csrc/lazy/core/ir.h,sha256=x-wp2s94Pd5-Ap5BuHPNSY1KLDBqhGmRmJJdypD6_P0,8165 +torch/include/torch/csrc/lazy/core/ir_builder.h,sha256=LFFuUi2tQnknn1vAc3NCMbqYsZkeQ2nfNTgslIKwOEo,4963 +torch/include/torch/csrc/lazy/core/ir_dump_util.h,sha256=wTnx_SqhzRO0Iqj_l0XOZyi2VlG5pxl9c-4x7ZW8Gh8,918 +torch/include/torch/csrc/lazy/core/ir_metadata.h,sha256=4gKlybk5kMnedrHtuxn2VFPw_GA9froaCjFyz74eTmU,1577 +torch/include/torch/csrc/lazy/core/ir_util.h,sha256=N8jZgssPrh2RquBZ1MPnCn76GLaRwP7flOdYfoNbpNQ,1620 +torch/include/torch/csrc/lazy/core/lazy_graph_executor.h,sha256=n3mcTAPhB6YIuYnr2aGF-K4bBsw9HjInrw4QtheXD94,15285 +torch/include/torch/csrc/lazy/core/metrics.h,sha256=wlwOLg_QznDs-jpVtpLZUXH1o3y8Hcp7DM1MGgqcb0M,8505 +torch/include/torch/csrc/lazy/core/multi_wait.h,sha256=g_DRC2nbclyo9wPg59GPkARRRkCblYJJNqIoVIxGYn0,2003 +torch/include/torch/csrc/lazy/core/ops/arithmetic_ir_ops.h,sha256=tm0XXxCP76MrNTvigLQ1ndJk6KuqoMSqcutoDtn2iMU,635 +torch/include/torch/csrc/lazy/core/ops/utils.h,sha256=GImlZp7FQGsmM8HqgcEIAvJaugEUSi1Ti4QrJd1X_R4,1239 +torch/include/torch/csrc/lazy/core/permutation_util.h,sha256=Q9MUTbUEkCcM9J5muU9oNYCgBRZmcC2bdldsBM-N5mY,1506 +torch/include/torch/csrc/lazy/core/shape.h,sha256=hkUJcwT7We7i78k6tn1IJYqxBs6ZbQOFu704igBeqQg,2269 +torch/include/torch/csrc/lazy/core/shape_inference.h,sha256=8tK9gSNtmvLNMsIhrY6j_5XSWYzmDfcNf9youqi2Le0,16119 +torch/include/torch/csrc/lazy/core/tensor.h,sha256=cM7lEIXw4D6wbYk1GetFdqNqai4NIKJXOaz8ZYmSWrc,10134 +torch/include/torch/csrc/lazy/core/tensor_impl.h,sha256=dYQ-izxXl2wfr3OfEkUi-b_FKG-i-fhxuWuPp8CLkGY,2170 +torch/include/torch/csrc/lazy/core/tensor_util.h,sha256=PrHDUfoMAsIrCQMMM2EmwU13pZBR7kaupc0wdWS2upc,2790 +torch/include/torch/csrc/lazy/core/thread_pool.h,sha256=K_THTX12OXQHK-6-Hz9rKnkZOZ-LiGzgRf85XjTGm14,1046 +torch/include/torch/csrc/lazy/core/trie.h,sha256=BSxr1ajdACgUhkgPOat-UgRU54-HPj6YdWFoSvv8juw,2446 +torch/include/torch/csrc/lazy/core/unique.h,sha256=I9Bp4qmGEQL4iBw8gIVUFf6yTE25bmc4T_EOL6aP7eE,1427 +torch/include/torch/csrc/lazy/core/util.h,sha256=HpMCdADPJ5pddLtVHMxCFU1Wz3cRbK1rRzRR-unOjNw,3127 +torch/include/torch/csrc/lazy/generated/LazyIr.h,sha256=BVF84isq233w9Kl5WTNoKaegxwrQV1nl2x-vOnYYoZ8,303908 +torch/include/torch/csrc/lazy/generated/LazyNativeFunctions.h,sha256=WJTZ2sgg-uTP5S1ezpDoGPwNAkxw2b-qcMCF2enP-U0,23419 +torch/include/torch/csrc/lazy/generated/LazyNonNativeIr.h,sha256=yfX5YW8UoOtsp2a12wPFQXHIzR-t7VAZrYrWvGwDSmA,4230 +torch/include/torch/csrc/lazy/python/init.h,sha256=NZYCX2lL9lwbHUnsXw5YgWxETS4lqMJn5ZPCUuz1_nQ,478 +torch/include/torch/csrc/lazy/python/python_util.h,sha256=gWzcbBoLIC17LCUycSWsDWXr1ZnqzQjvFibyIfpaA_0,569 +torch/include/torch/csrc/lazy/ts_backend/config.h,sha256=JPAgsEYiOlNHlNWphPlOEQ77bRs_cvscW90lKvdXqKc,460 +torch/include/torch/csrc/lazy/ts_backend/dynamic_ir.h,sha256=cyUKC1y86Db3LhHl85BrRoQDvtcSZsPsywGw2Z0AhCE,2610 +torch/include/torch/csrc/lazy/ts_backend/ir_builder.h,sha256=R-54wutbGLkaVoEjX71KPDenJHRvCQdX_67CxuVOlaI,2645 +torch/include/torch/csrc/lazy/ts_backend/ops/device_data.h,sha256=DgqgsCp7gzUesP1EdSf5Z0rXKXvQTTeMDsl2r8iOUIk,1544 +torch/include/torch/csrc/lazy/ts_backend/ops/generic.h,sha256=YfpQxCCAq4_QoJEy886VfiMFn4LhD8tzd2FPdnZOWzs,1682 +torch/include/torch/csrc/lazy/ts_backend/ops/to_copy.h,sha256=CTgVgQWvsAiJa1gL9ZF_zU3dAojXWeDgXvdyWHlu3Qs,4344 +torch/include/torch/csrc/lazy/ts_backend/tensor_aten_ops.h,sha256=zjZsB7ks-66zjdNXNjB1yzaaJfgbbLHcYZwGSFCIXuU,777 +torch/include/torch/csrc/lazy/ts_backend/ts_autograd_functions.h,sha256=PF6QsWXwmBJ8as2Bi1S4D6A-QwkNUVdsBEyTnCxsA0A,880 +torch/include/torch/csrc/lazy/ts_backend/ts_backend_impl.h,sha256=nKc9ql84AIFutbgtMpG8AVsrpQz-1-Y5RVpmSJlYi14,1487 +torch/include/torch/csrc/lazy/ts_backend/ts_eager_fallback.h,sha256=zzuu9qy_l3DK__izeiDULKw8BXVHH6_3_VrwD9QZ7Nw,946 +torch/include/torch/csrc/lazy/ts_backend/ts_lowering_context.h,sha256=c5gEgL0G_Pu0BVUY6yT-GTXqIxGz0yCJwzK0IjeAON4,4777 +torch/include/torch/csrc/lazy/ts_backend/ts_node.h,sha256=svuUBEC01SrGzKuSktuyePEGf5LHLij6dzDiSgo8HsE,3605 +torch/include/torch/csrc/lazy/ts_backend/ts_node_lowering.h,sha256=Ae0WcTTYggl-ltP4TJhF4CY_fWLsw6oiL5WW2DNhJWQ,720 +torch/include/torch/csrc/monitor/counters.h,sha256=7ieD0XYP-Cv4APwh1phmsScga3noaEtf4pxGdQinAvQ,8108 +torch/include/torch/csrc/monitor/events.h,sha256=fQupUX1e3RFv3zsbnALg1Z9sXVdFw88fgL_WmXyft-k,2931 +torch/include/torch/csrc/monitor/python_init.h,sha256=ffmFgZ0KuXD-55U1Cl5L5NILNxO1GmFy55Giy78OCKA,381 +torch/include/torch/csrc/mps/Module.h,sha256=Apu7gii0dgPwg9bKgKnTjByEbqlIGalnAcMe_xO8okc,427 +torch/include/torch/csrc/mps/Stream.h,sha256=MN1BQfLVrHyYqFEUjjU_gjyPH6Zuw0s37yBTGw9RHGU,803 +torch/include/torch/csrc/mtia/Module.h,sha256=YFWOdviupcuSSKOYYRkRc0WQvAzgTDm2jFgYg1fMg1M,432 +torch/include/torch/csrc/mtia/profiler/MTIAMemoryProfiler.h,sha256=u6o2GVJoyjszRJ-PtMxVhaqDIjYFPhyKGaxKPM7hUs4,801 +torch/include/torch/csrc/multiprocessing/init.h,sha256=MDM3byavkbVz0s27gK41WWSm2QXYY_D5CzdeQZum3-g,422 +torch/include/torch/csrc/onnx/back_compat.h,sha256=NdCcjbbsoMV9cfLR7VgZG8ZY6Xx3QW67FEPpfBX19VE,1278 +torch/include/torch/csrc/onnx/init.h,sha256=nofikk1oLIWEWuDOtCxajPECVUwk1wfwxT32f-xeuGY,400 +torch/include/torch/csrc/onnx/onnx.h,sha256=iB8JqbKgTU0LEsC-MyZ9CzQMm-vDTwObYrg2JDfyBcU,759 +torch/include/torch/csrc/profiler/api.h,sha256=xGirYXerLVr29MBGKasBpHlty_2R_ubR6PO3tKX1O1I,764 +torch/include/torch/csrc/profiler/collection.h,sha256=iTP7Vvpwc41iLIwH6drpmfhKjNilfH8ksDSWMKqzv1A,22670 +torch/include/torch/csrc/profiler/combined_traceback.h,sha256=dKxMUihbgdnMbjtHvMQ8yUpUesaEC5UyRiNijtQMigo,4158 +torch/include/torch/csrc/profiler/containers.h,sha256=WDZSvZ25EhAZxa6QLBLacg7GG6U3ar_tzJf9sBB7aHU,6248 +torch/include/torch/csrc/profiler/cupti/monitor_native.h,sha256=rWyZC_UfWP-U3c7yXvT4BGMrHBNJ88Uk8qvyZgJjVdA,14245 +torch/include/torch/csrc/profiler/cupti/monitor_pftrace.h,sha256=zsuYPi1njNBDu_FU1lt9mPI3rXeghfGa-99Or2xLoBM,11763 +torch/include/torch/csrc/profiler/cupti/monitor_python.h,sha256=fxG3spxMy2uoYVa2kjopUkgodrx7BVyBlmXa59wCA-k,644 +torch/include/torch/csrc/profiler/data_flow.h,sha256=s21Yb1A7iUE68LqTgu7FiJnPeos1GJCjFqpcDFcC7o0,3878 +torch/include/torch/csrc/profiler/events.h,sha256=QVTGHVeO3B_dz8xeUEEH1EUpK_QxGWFcc2f7-VmXsyk,1290 +torch/include/torch/csrc/profiler/kineto_client_interface.h,sha256=k6Da71DcfA4CuBppIXQHFWx_MzxBxa1DKkQJH8wXBAs,500 +torch/include/torch/csrc/profiler/kineto_metadata.h,sha256=qzOqbxRvv5SNmDUvUMEEq_YYwh8-yGhAZviuTE_OtwQ,1430 +torch/include/torch/csrc/profiler/kineto_shim.h,sha256=Ur7rkmu8b6jKq9tlz_u9bE0Wh3t86CEiLPVZTIuhqDo,4402 +torch/include/torch/csrc/profiler/orchestration/observer.h,sha256=Fw8ijkn5WLoa3yOiQgW1whsDnZivptPivoYnGZAX9OE,7891 +torch/include/torch/csrc/profiler/orchestration/python_tracer.h,sha256=OLJ1Hu4YfWSs0C1QEXwYt1-wLXYuapPkvSsYjeRE01w,2788 +torch/include/torch/csrc/profiler/orchestration/vulkan.h,sha256=JnVjekrFW8Syv2J0DIRh9esqtM6UrgjlSeIafZB3m5Q,1030 +torch/include/torch/csrc/profiler/perf-inl.h,sha256=P3W5T5ZGJO6H6kyGVG6jdJ6IZDz6KN7-j8YhZY_HMng,1658 +torch/include/torch/csrc/profiler/perf.h,sha256=dX35-crTvUn84O5tX42GJFFEyTjvsmLeC3tXHd-LW8I,2847 +torch/include/torch/csrc/profiler/python/combined_traceback.h,sha256=_a1nMBwi4_f_CXlvXoLDI_FrL4lWKhkmb2m6e46q8Qo,1246 +torch/include/torch/csrc/profiler/python/init.h,sha256=ZxXqiKbTO0_Ym1-doIZBz9UgqpeLrJR5U6hSfnnSa4s,1252 +torch/include/torch/csrc/profiler/python/pybind.h,sha256=6yCJymuZHstk5mhrEKwMtL9CHtFIc1yZ0-4U5DokRzs,1515 +torch/include/torch/csrc/profiler/standalone/execution_trace_observer.h,sha256=XEu_BQoKycd7zvUbK-8qo6MsoTZiDlGTyQB4QlS6ndw,882 +torch/include/torch/csrc/profiler/standalone/itt_observer.h,sha256=e1m64SgR2WYIjNv8SpkugKFihDL4L0PoYwnZaGPjXpg,478 +torch/include/torch/csrc/profiler/standalone/nvtx_observer.h,sha256=C6vGiw36g4tlZxw_gYFxGwzHkIPdp1FHKJdbCEICyoM,479 +torch/include/torch/csrc/profiler/standalone/privateuse1_observer.h,sha256=7lrsKkoS165BrnTYC1BWwu-qiOTtq2Y4jFwxVTwTcXE,1675 +torch/include/torch/csrc/profiler/standalone/privateuse1_profiler.h,sha256=45PWDYVg9MCMWZdnTUwAwH2rJ_F606RKQNn0JA-qQDI,3929 +torch/include/torch/csrc/profiler/stubs/base.h,sha256=F7fUVssVS6_IjHPZb5thWw9vro26s8ykVwsazBds5hE,1939 +torch/include/torch/csrc/profiler/unwind/action.h,sha256=9LFKtggxTENmyAtkeJyB-mNJkt6Sl_SpG6_js89wJHc,2233 +torch/include/torch/csrc/profiler/unwind/communicate.h,sha256=9Hw2syApVGUsDyKQiAKXmzWwu9G2xsuIEJGpf-UTFzw,2506 +torch/include/torch/csrc/profiler/unwind/debug_info.h,sha256=_5sgKQQ3zaBPE5Qwo9-RtMmKgFXyd9SKvL9QvPWI6qU,9354 +torch/include/torch/csrc/profiler/unwind/dwarf_enums.h,sha256=FiB4IwZLquC7J5QSlDCZeQSa7_YutAutZX4wi1Umkqc,1397 +torch/include/torch/csrc/profiler/unwind/dwarf_symbolize_enums.h,sha256=02cDTcepBwtkBB2xl6j5kRR3439c7zZv5KDsZs5Moi4,4912 +torch/include/torch/csrc/profiler/unwind/eh_frame_hdr.h,sha256=NGXHq0_cbbCQ5O9GNSexDktFO2IOiXCbIgPPaLl_NQw,2934 +torch/include/torch/csrc/profiler/unwind/fast_symbolizer.h,sha256=tBeWMSZVhAUxibcIYVB9iqwU1DV9pFI_qqCeO8ywAMM,3557 +torch/include/torch/csrc/profiler/unwind/fde.h,sha256=qzv7zS0CqRHPsX50axmZBOQHNKvqF81gXSe_6hzctKw,12885 +torch/include/torch/csrc/profiler/unwind/lexer.h,sha256=qteUGXS78lP8Q6EJU2JanNwUSMqRnkUx7GZBs6Vfws4,4135 +torch/include/torch/csrc/profiler/unwind/line_number_program.h,sha256=93WN5uZJIAdg3zdESlMPDOALhphl8HZKUxvs-Vc2UKI,11079 +torch/include/torch/csrc/profiler/unwind/mem_file.h,sha256=4prncS4riwSZg0ADA9TZrKC7ka08trpPwWqD55p8mZ0,4945 +torch/include/torch/csrc/profiler/unwind/range_table.h,sha256=2fRNVYzs6KNiFkvveN9awqa5oNIxwcxIi8s2F52-0BU,2363 +torch/include/torch/csrc/profiler/unwind/sections.h,sha256=i02YUf5QMuuzJgdfAifWcIOZl8P3Ip4S5SrnqkZKdug,3922 +torch/include/torch/csrc/profiler/unwind/unwind.h,sha256=xaMH9xCsVyhCHotSw6e73aqNRz8d-oCduQlP4vSGtFQ,1387 +torch/include/torch/csrc/profiler/unwind/unwind_error.h,sha256=6SFMi81YnkNMvPRi4_ar_4PMplmX2VJmAP0sVGJZSYI,1152 +torch/include/torch/csrc/profiler/unwind/unwinder.h,sha256=I1rnvUYCiIbqTUfkuY6LECFlOXnzAdTZkgqxU8P3rl4,2672 +torch/include/torch/csrc/profiler/util.h,sha256=g6Ik_c_hymvd69ulVocreOvA9mpcI8NS-ACbrm-rr44,8556 +torch/include/torch/csrc/python_headers.h,sha256=W1ASyJDtRGr7YTipLtmOGZ6N2gzkNjM_8ju-vWUwi-w,903 +torch/include/torch/csrc/serialization.h,sha256=3_Zm2oq56ytJX1nTZXV1xGdum9BkuUusbG739Tty8wE,935 +torch/include/torch/csrc/shim_conversion_utils.h,sha256=WzsYcnAgrlZQ5lbDSZK7e3hTM4vAoVoQbIDPnYFlrQ4,926 +torch/include/torch/csrc/shim_exception_state.h,sha256=6qdB7DvJlziG1Jsrorj956neqjnpJbysQwnx4Drzqa0,1264 +torch/include/torch/csrc/stable/accelerator.h,sha256=c0w2lpOPH2dzDUF2g9X3sOKGvIsYuXCfdCxDM3ceEmk,3605 +torch/include/torch/csrc/stable/c/shim.h,sha256=JlYpi1w6384pYzEIymmJWVmEglnp_6zVGg0ApN9wIpI,13020 +torch/include/torch/csrc/stable/device.h,sha256=c127B_czfZfuAQikoKN5kuiOj3eK-zWs5aMJ09mz0-8,101 +torch/include/torch/csrc/stable/device_inl.h,sha256=XH4CzGEfHs3W9ReCIVhzYjbPqqLAcRiC1WJ44Ic_HHo,1394 +torch/include/torch/csrc/stable/device_struct.h,sha256=ItDv-YgxfSNzDo_IZf9vvA6_vlbC5mfqDJ2YafDii5w,5111 +torch/include/torch/csrc/stable/generator.h,sha256=DeAS7jw4u6XS6JO8eus1nT_eRNH3s-WfIeG9ReZcYD8,107 +torch/include/torch/csrc/stable/generator_inl.h,sha256=cRHnrV68NW0tdNpjyXDNxXE9iPRc1P7s6P-w69LyJhA,1142 +torch/include/torch/csrc/stable/generator_struct.h,sha256=BFqaLYaffJYMOSsxJkF0z9g5N0T8zraLDzkJfbN03lc,2710 +torch/include/torch/csrc/stable/library.h,sha256=0YAybOj8Y_E9TBh4VOyo9OX86ntXZOhyueG2MHAmH98,13604 +torch/include/torch/csrc/stable/macros.h,sha256=ku8XlswqXaRiNM5DOd8Bu631RJOxyxx0wUbZp6HFU9E,7254 +torch/include/torch/csrc/stable/ops.h,sha256=mwdwOBdkNhzW0VhPNSep8H18BvJzDa2UYdKBKerLkh8,50878 +torch/include/torch/csrc/stable/pyobject.h,sha256=uEUvAIyyhc2RByd8ui4E8Dj1Yqml4mCZiu0zRbna7t4,1498 +torch/include/torch/csrc/stable/stableivalue_conversions.h,sha256=Zm5sO9td2ds3mls1sFjQGjUlT2cWXE2N7_DZJetQYVE,41779 +torch/include/torch/csrc/stable/tensor.h,sha256=MIwb6Kq9H9Ry_wh9uij65SEUpw-JYddJ4UI9YFMvf6M,101 +torch/include/torch/csrc/stable/tensor_inl.h,sha256=o3NqwNWrEn28pHIWb2dVAermBbZz0epVMUAdBaIOMqs,3294 +torch/include/torch/csrc/stable/tensor_struct.h,sha256=4r0D6hX1ci5hSMCvXaQ5MfKYJd_vlEEZJ_-fijYXpgw,14911 +torch/include/torch/csrc/stable/version.h,sha256=PyAPQZA1pWbkw2DKdroJ6Ly6FzX9pFXHi-e6FV0OORc,1327 +torch/include/torch/csrc/tensor/python_tensor.h,sha256=W51E9SLaphq9d3dR2CqRLTiOnNrh8q2-hWuFPK4UGDM,1454 +torch/include/torch/csrc/utils.h,sha256=MEEk2pvmH89d8q08Yr31hjOXp9A3xi9pLlHWuUoEDkE,4884 +torch/include/torch/csrc/utils/byte_order.h,sha256=BhoYR327QBjuW7_X6MfbdW2ZcV2bi5x4XOsNuHJGDuw,2508 +torch/include/torch/csrc/utils/cpp_stacktraces.h,sha256=rMp2epRbiAYUnwzeEFtDKUgh4qQtsJfNcJb97fVluDY,484 +torch/include/torch/csrc/utils/cuda_enabled.h,sha256=tHkNXPv0rKNUg_ld-gA61f_7jYZ7AgUf1SkayPhxVhI,424 +torch/include/torch/csrc/utils/device_lazy_init.h,sha256=Lq2sY2b3o9L6sOsLVW3UJ3MsZ-_2NxjRJw4AYLDWF1I,3068 +torch/include/torch/csrc/utils/disable_torch_function.h,sha256=yRtV77beQNgY3W5BUkriZ-1D75tEVRG_mSdtTNve9C4,3181 +torch/include/torch/csrc/utils/generated_serialization_types.h,sha256=e4GISxc3_S999WOlow0ovWRDMa1fRjol_f94QD4NpbY,127920 +torch/include/torch/csrc/utils/init.h,sha256=yFogmRgeaTycae64CMu1uQsaqrZ28T0XiBmcHTRLcqc,447 +torch/include/torch/csrc/utils/invalid_arguments.h,sha256=OYo7VRpe44aNaGGvVJIL7xPSI3rBFkGUHtRGYQyEEX0,556 +torch/include/torch/csrc/utils/nested.h,sha256=eBsEENIGSfa5kjay2Xmc3AIgUDRRN4D9g5A5nKDsJ-o,560 +torch/include/torch/csrc/utils/numpy_stub.h,sha256=iSr881WC_2tdoB55OTK2oUk2yXL8OscXS5oL45TOY3A,653 +torch/include/torch/csrc/utils/object_ptr.h,sha256=E5DaA77ud_7UQEgTYj-QtfT7tISYyWzSLvN_saS65nM,2241 +torch/include/torch/csrc/utils/out_types.h,sha256=mwq_iEveRZqZR9NfUx-XdC4Kr-ltwSVXsi7i27v8RrE,574 +torch/include/torch/csrc/utils/pybind.h,sha256=qIS5PgM6ibIJBReuCTZiTh_-FDHwlUrEJTNcKJHm8hc,14054 +torch/include/torch/csrc/utils/pycfunction_helpers.h,sha256=OaKMH7DhZUQeC6EjF-XjrOK4OW1vfZLP6BUzXQ41-EY,1061 +torch/include/torch/csrc/utils/pyobject_preservation.h,sha256=cLovLQD7UH4Aldb-VzWErYHT_7AL3WOAK9U2aBVQLSU,3806 +torch/include/torch/csrc/utils/python_arg_parser.h,sha256=_XEF1FPgsVgAoIzznWllNUaRvs9Y4HJIWuRHoW1c52A,42696 +torch/include/torch/csrc/utils/python_compat.h,sha256=oUjSjw36XVlm9yu7NOZM_Swz-tR4FXdqPK8EcFJ4-LQ,1281 +torch/include/torch/csrc/utils/python_dispatch.h,sha256=jqjX8Y8ebUUoXE6UZOybFRzMLM5VR94uZmu4fYty7Fg,651 +torch/include/torch/csrc/utils/python_numbers.h,sha256=MCbOG1mXCFmtxe2F9oqzl08CDtQNxe8-muHvmAXQRtA,6383 +torch/include/torch/csrc/utils/python_raii.h,sha256=JLoYiMGFICxaIMoH6u5e4vp6SGE4W2N_EpTxD78NlV4,2912 +torch/include/torch/csrc/utils/python_scalars.h,sha256=Vg01KNA5gFcI4qe8HLVZbwbnaFaywduzxT4KOWc7t6w,6664 +torch/include/torch/csrc/utils/python_strings.h,sha256=OMwR8KfNAUI74wi3lkxJ8XwaiHqCqzULXkloh9hTBrk,4999 +torch/include/torch/csrc/utils/python_stub.h,sha256=JqFk4mKCyu0chr2QF5a1IqXXbi9HPecVk_VhA2TxtCA,310 +torch/include/torch/csrc/utils/python_symnode.h,sha256=TsvNCunai6IiBOL_wAcNpqeWMSh_ftOmtxzT-DPzd4c,10375 +torch/include/torch/csrc/utils/python_torch_function_mode.h,sha256=DxJo0hwTAG1hkq5LWJgXK58NUHiS4CDAbsrsBK_SkVY,1094 +torch/include/torch/csrc/utils/python_tuples.h,sha256=I8rMtebgRbe52cgReGUGwmmNk2HBsukIZaGg3V4VjkA,980 +torch/include/torch/csrc/utils/pythoncapi_compat.h,sha256=9ZKnncRIDr_22WnehcTVL4mLVJ9S1t3_sO9KC_Ch7D8,72696 +torch/include/torch/csrc/utils/schema_info.h,sha256=kAn1bspmNcHr91si2o4ei6k3fuQ1-NvtoT-ISRENK6M,4043 +torch/include/torch/csrc/utils/structseq.h,sha256=2G-lkmF_SYF2ECFSJwOLA6HBYFctjEwcgt924a5jfkw,395 +torch/include/torch/csrc/utils/tensor_apply.h,sha256=utGr0N-b-NAYkc68JEZcyeKrNncROANSHTpEQjidt4k,682 +torch/include/torch/csrc/utils/tensor_dtypes.h,sha256=cfAjJqa_c3rgNnj3ZxtnCRK-Ozyaykiwy9TfeXbilpU,496 +torch/include/torch/csrc/utils/tensor_flatten.h,sha256=-JgUD7iNFqUTEhe6bDougZZkdibYt3QuRmN7CPJBD-g,2999 +torch/include/torch/csrc/utils/tensor_layouts.h,sha256=9iqdB6L0Fzm8LXUjOKgSg8JDxxPNAvc6p_YG_YCCqOc,323 +torch/include/torch/csrc/utils/tensor_list.h,sha256=_dWalILXx6uIho9CQRwN-RW7hiVOikXfvR1Vu7geUYo,421 +torch/include/torch/csrc/utils/tensor_memoryformats.h,sha256=cpcRmvcPxc5pNOKE5gfPi7ACwP-xgxPYSoTgCtMxH2M,599 +torch/include/torch/csrc/utils/tensor_new.h,sha256=jP2vn67UOVi2cfC0syCunTieJ5nMBvvqtsuNXtGh_Hc,4345 +torch/include/torch/csrc/utils/tensor_numpy.h,sha256=pg06imuQjPpJUwxYHu3vZ-V48s9fmo8cxpZGEQNCMKc,1216 +torch/include/torch/csrc/utils/tensor_qschemes.h,sha256=yOncI33ZbiK-oPvZEnvWapNXE0wRSqzZNit4zyCCOz0,428 +torch/include/torch/csrc/utils/tensor_types.h,sha256=z8Fq8XAQUE-NWt-AeOelujtTbpzllUyHm3H4D-Xd3EM,923 +torch/include/torch/csrc/utils/throughput_benchmark-inl.h,sha256=IfWBq_GogXvaqGdGIgdEG1XpFFcPKq-Nr93rlfywZjU,6590 +torch/include/torch/csrc/utils/throughput_benchmark.h,sha256=WcS0hu1H0O6aqlflKnQyuwo9V15e9sv4NR-zA0x2WkU,7191 +torch/include/torch/csrc/utils/torch_dispatch_mode.h,sha256=c-D7EjkxhFiKGeEzuGWzAbE-Iq8rVsqmrklnwamj8G4,2529 +torch/include/torch/csrc/utils/variadic.h,sha256=gbXQ7bGebPOoVsGoLjc4RycltMc1BYLTKcUv_VxUGw8,3630 +torch/include/torch/csrc/utils/verbose.h,sha256=YMrRuUzOz8RuhXUsyIH2uzVkHpXGp6iWrV1mgVwrpqY,392 +torch/include/torch/csrc/xpu/Event.h,sha256=DUja-x8C-w3C3xD_lzTVDY61kgx1PVLn1zWi8m758MQ,623 +torch/include/torch/csrc/xpu/Module.h,sha256=ITvFMk9MWU03WLLy-BOZmpoJnIVF0f70KlIO3dtoTTw,430 +torch/include/torch/csrc/xpu/Stream.h,sha256=6lPNJMuXZqw9O-_PNTb5EY9fXplRF0Jj0JfbV0xXJ7g,691 +torch/include/torch/csrc/xpu/XPUPluggableAllocator.h,sha256=ZAKYjogIIzPBamhYGB5ewStINvWxF1lRt8dCbiXCVpQ,3124 +torch/include/torch/csrc/xpu/memory_snapshot.h,sha256=VSJFwIr4rNRd2iY6UrwQAaacCT3DCbt52jQl4UBdN5o,730 +torch/include/torch/custom_class.h,sha256=5VlzLtPsUMXzuB3wYf1u5p-E0n79-pfLSpYcF-5VfdA,20954 +torch/include/torch/custom_class_detail.h,sha256=aLSxmNUvWdLJBUmQdTyupCbLA2MWmgCnPWZIR2SDpz4,8430 +torch/include/torch/extension.h,sha256=2juzxgbeXcd8wDHl9fCm-8iqxJ8YnqutefZANPuWnkg,467 +torch/include/torch/headeronly/core/DeviceType.h,sha256=7-D-JAHfnN1NFVnfIqbA90cVGpwVBuZLNlZ6WpvGQTU,4272 +torch/include/torch/headeronly/core/Dispatch.h,sha256=cdTOahmNMCFJ_1qKM62sYWYRzooKV7_3nfUY_XxgJ34,3825 +torch/include/torch/headeronly/core/Dispatch_v2.h,sha256=EvuNO8oUdvwYGTM6pOYe0qxYidzwvK1ZuGKtdUvhW38,34829 +torch/include/torch/headeronly/core/Layout.h,sha256=HFoNirxYWVYbAcPO_UtnWv3lhAwY37RKczzFKgf3wKw,948 +torch/include/torch/headeronly/core/MemoryFormat.h,sha256=K7Q7XLCpUnKaFrI0k5D1hGOQK5X7obWQAQkF7a1PVH0,1206 +torch/include/torch/headeronly/core/ScalarType.h,sha256=A2GgN66Rz3KyEIX6BskqrMJ2oHeEMosA-Lm4PCeKV9I,17843 +torch/include/torch/headeronly/core/TensorAccessor.h,sha256=EESC94_W0fAh_xkybh-EPdIOr-PmcUyYF1oOIwIGgzo,14015 +torch/include/torch/headeronly/core/enum_tag.h,sha256=gIRrfz5L3Sngc30QrBhBss0Q_GvJNYcoEUAxCivjZ0c,809 +torch/include/torch/headeronly/cpu/vec/intrinsics.h,sha256=PV2_UwjmjaVTKAc1PjPerISePzJnTLKf5iynUNFmnHM,1917 +torch/include/torch/headeronly/cpu/vec/vec_half.h,sha256=kXa2ne1je1uWnwec2732Zx8jV1gNFlRa7yw1k2X5D9o,1740 +torch/include/torch/headeronly/cuda/Atomic.h,sha256=8pWsgen2FXozxQBd224AFzGbOEQNJlfJ0sXowwAceyM,21169 +torch/include/torch/headeronly/cuda/KernelUtils.h,sha256=DQakR0TeYA4jE72RZT9EHWm3yCWdS9faiQPyI0V4FWg,5034 +torch/include/torch/headeronly/cuda/detail/ROCmMacros.h,sha256=R1s07Ezn4X-giS7UPItw9GGC6O8pzeyAxUAHtVT8t5M,626 +torch/include/torch/headeronly/macros/Export.h,sha256=bC2_b5PrzlYBQdkmBhe2MH2nEOADscHqdLuiBVBQcO8,5599 +torch/include/torch/headeronly/macros/Macros.h,sha256=AZMfLqCEjzX4cBaH3Xz4gCZsfNWTIJltmMbDauUOXFA,27799 +torch/include/torch/headeronly/macros/cmake_macros.h,sha256=b-Stsa62GB_2kD_2ym9YW6yjCTvXoX5m1liJ_4Y3pt8,450 +torch/include/torch/headeronly/util/BFloat16.h,sha256=zVdwWziwVmCEAigHHrDubaxG81DRvfoRSW7KZDeQvmk,15277 +torch/include/torch/headeronly/util/Deprecated.h,sha256=tyNcwEnjhdHs3LbgKssdAQqInoDJXNhgcSg1z2sj3nc,3579 +torch/include/torch/headeronly/util/Exception.h,sha256=B2eveDY234saPM8R_N4TrOb82wDgB15OEZgqBgB9yi8,3433 +torch/include/torch/headeronly/util/Float4_e2m1fn_x2.h,sha256=G734w0W4oOe35KET9Tap746EWyTe7G6SbMmoNHvyt0g,1326 +torch/include/torch/headeronly/util/Float8_e4m3fn.h,sha256=dXD-N8I7Z56qIO7IleIPqB_EgpRtGKa81V5_zkUJCLc,18872 +torch/include/torch/headeronly/util/Float8_e4m3fnuz.h,sha256=hHD8n_B5ZVtktOqv6jxhtdMteaJt-5JVyNehETKcVo4,14815 +torch/include/torch/headeronly/util/Float8_e5m2.h,sha256=YCEB1vgf5rR42qYQc6VoXz46wecBtlfGl5RbXSRrBeM,14852 +torch/include/torch/headeronly/util/Float8_e5m2fnuz.h,sha256=87PtkT3hft5BedgwSL39-4KA4_KRP_dMFWs51XE0nic,14898 +torch/include/torch/headeronly/util/Float8_e8m0fnu.h,sha256=UtF9d4bS2fnTUFA_UHHK7Y3pG1it99XKo3ZiaA67OsE,6938 +torch/include/torch/headeronly/util/Float8_fnuz_cvt.h,sha256=aVJimoCmZgfahBmkRR40USG1eSeAng5hzhclZTa5TDM,1920 +torch/include/torch/headeronly/util/Half.h,sha256=bAIxe5DC0SZbfY0p0_Hzniir9BttlK_OTZHCl2I6kMY,28237 +torch/include/torch/headeronly/util/HeaderOnlyArrayRef.h,sha256=3VEC6O5p0VKZmPjCqxcqQN64ua4LpA8C3zzhK3vxs3Q,8961 +torch/include/torch/headeronly/util/Metaprogramming.h,sha256=jPSAnrndcYsql4SqkbcffUCImefhQJxQmlNfd112EX0,7444 +torch/include/torch/headeronly/util/NumericUtils.h,sha256=Aa0wKaO5NTgLN5ze4p0B7jWxuovG0QbVyCiqdFDJrpM,3400 +torch/include/torch/headeronly/util/TypeList.h,sha256=i4NEYbKIJ1b4AdcdMVZ8saoMHFn4xRRdSAVYMxiC2TY,17334 +torch/include/torch/headeronly/util/TypeSafeSignMath.h,sha256=TG8HMvlJ08YF1SGv3QoLpNbBz5DvZvdlgDcxSIvnB0o,3084 +torch/include/torch/headeronly/util/TypeTraits.h,sha256=C4S0eYZ8fQZnHQAKZcnfMCBE2PrZ8m0W8djVag2_nJE,5698 +torch/include/torch/headeronly/util/bit_cast.h,sha256=-YBNY7PSadYyIoF3IyB-_RvY19evGIVh-Zt9Vi8liT8,1426 +torch/include/torch/headeronly/util/bits.h,sha256=K1SQupBTltkxUVAH28IXO8VQqNf1eLkYqGGMKKT7gmc,1644 +torch/include/torch/headeronly/util/complex.h,sha256=f32C8d7zEXu5UQDVcQ04ipCDzWdvmVh11zovN7HChtE,19947 +torch/include/torch/headeronly/util/complex_utils.h,sha256=FL4EKusqsRK7NmxrzzD15BHiwp9S7yKV0ciylXZCko8,1164 +torch/include/torch/headeronly/util/floating_point_utils.h,sha256=o36InAmLzUt4OsrTbNeM2dNwCT0xbjmkOqYwewTZ1h0,1047 +torch/include/torch/headeronly/util/qint32.h,sha256=NjQBdVMVQoI1SxNNrtgEOOScvOLpgwPrTHIAmIlMSJY,434 +torch/include/torch/headeronly/util/qint8.h,sha256=JIN-Vao78wIx0308UT98URVQZdmXfYX3oTuzqlOi--o,586 +torch/include/torch/headeronly/util/quint2x4.h,sha256=vSoOsu-raTav0QIldQWUhYp9bY88d_HD3Kn_VXdRm9M,483 +torch/include/torch/headeronly/util/quint4x2.h,sha256=Pu82ZJKu21wqi232YMuAmtTWtq7DKaIek56Lr9u-N1c,483 +torch/include/torch/headeronly/util/quint8.h,sha256=2W7tsPA88e_obpE9TqWAeprIXjjZkyqwOqvX6TlGz-s,435 +torch/include/torch/headeronly/util/shim_utils.h,sha256=FuZrkG51N7tqXm4VTUbhgr0rnzQFVbTJIoqy4H8FqKI,1039 +torch/include/torch/headeronly/util/win32-headers.h,sha256=Hwx6Heb2BvTTMDfWYL3yRoXsqMd9xdu1_LRXz2nMzws,858 +torch/include/torch/headeronly/version.h,sha256=d7h2_XQpPtfCPRc1p8ukSmArmcZ5HuxfqU6bfnm2cbs,818 +torch/include/torch/library.h,sha256=JXKj2IREGL25sbqEU40C8HbXnwUMYobuSBEXPXDf-Yc,42440 +torch/include/torch/script.h,sha256=e7ma1b60NplDJbbjKdE0vS98ttRT1GzWH4xHD6jn_MA,723 +torch/jit/__init__.py,sha256=SiT48q3MakNgr5HAMtznarbUnw8UjXXqWJ9oJMHp624,8964 +torch/jit/__pycache__/__init__.cpython-312.pyc,, +torch/jit/__pycache__/_async.cpython-312.pyc,, +torch/jit/__pycache__/_await.cpython-312.pyc,, +torch/jit/__pycache__/_builtins.cpython-312.pyc,, +torch/jit/__pycache__/_check.cpython-312.pyc,, +torch/jit/__pycache__/_dataclass_impls.cpython-312.pyc,, +torch/jit/__pycache__/_decomposition_utils.cpython-312.pyc,, +torch/jit/__pycache__/_decompositions.cpython-312.pyc,, +torch/jit/__pycache__/_freeze.cpython-312.pyc,, +torch/jit/__pycache__/_fuser.cpython-312.pyc,, +torch/jit/__pycache__/_ir_utils.cpython-312.pyc,, +torch/jit/__pycache__/_logging.cpython-312.pyc,, +torch/jit/__pycache__/_monkeytype_config.cpython-312.pyc,, +torch/jit/__pycache__/_pickle.cpython-312.pyc,, +torch/jit/__pycache__/_recursive.cpython-312.pyc,, +torch/jit/__pycache__/_script.cpython-312.pyc,, +torch/jit/__pycache__/_serialization.cpython-312.pyc,, +torch/jit/__pycache__/_shape_functions.cpython-312.pyc,, +torch/jit/__pycache__/_state.cpython-312.pyc,, +torch/jit/__pycache__/_trace.cpython-312.pyc,, +torch/jit/__pycache__/annotations.cpython-312.pyc,, +torch/jit/__pycache__/frontend.cpython-312.pyc,, +torch/jit/__pycache__/generate_bytecode.cpython-312.pyc,, +torch/jit/__pycache__/quantized.cpython-312.pyc,, +torch/jit/__pycache__/supported_ops.cpython-312.pyc,, +torch/jit/__pycache__/unsupported_tensor_ops.cpython-312.pyc,, +torch/jit/_async.py,sha256=EzkIeXnNMFUuJUtuMjFfFo8hAcqSu9z5N1oBAeffiZA,4294 +torch/jit/_await.py,sha256=QlUZT3JcaYXZdRo9jExZs8snNPe7yUUtTcX1_h3Ge80,851 +torch/jit/_builtins.py,sha256=uLorjADjsUuKM71WoBUTdyVzZ4tdn82rHSnRbGmfgDc,6832 +torch/jit/_check.py,sha256=VR83zm_6rZqEq4Mg_cvryoGC0r7NR5ioBHHS_5Q7j00,9771 +torch/jit/_dataclass_impls.py,sha256=3xo2DKMaUZv44Ngw1VYETZ4mqbwPTyX29U1VCItl6Co,6681 +torch/jit/_decomposition_utils.py,sha256=IOugHESe09GNFdtx4geGCppHwGUzp4EPskQXoU3PqG8,510 +torch/jit/_decompositions.py,sha256=Zrc3x4XHhVo9M2je3NfGysiTmL0i8xPaLwTuC-R32vU,4659 +torch/jit/_freeze.py,sha256=PLi_TmxgYB4L_pONaf6jg2QY4qF-03PYT4PnXlZF0zc,9959 +torch/jit/_fuser.py,sha256=Kz_XVHUOxo3zdd6aTJkhFUXw-SokQ5IprovRqLc9fs8,7615 +torch/jit/_ir_utils.py,sha256=QskhtXHHEmqXbfFBA_R8JdMr7OCdIqqZd2JuLEeT1Kw,838 +torch/jit/_logging.py,sha256=jWaacYoHjd_Cao_1hzyPKYiADS7cb7tLQc1gRkZblUQ,257 +torch/jit/_monkeytype_config.py,sha256=xXiFIZrGgOjveJJc3KnJx81CGTOvMNFTPLjqQ1heTew,7322 +torch/jit/_passes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/jit/_passes/__pycache__/__init__.cpython-312.pyc,, +torch/jit/_passes/__pycache__/_property_propagation.cpython-312.pyc,, +torch/jit/_passes/_property_propagation.py,sha256=4L1s-f_Ngp4Abz0Mf5t-BtQlEnyIWV2GPya6N2Om7qE,1438 +torch/jit/_pickle.py,sha256=lV929M0juZlRKP8-OwClLpLwxIb7W-74r055yqNc8wQ,1130 +torch/jit/_recursive.py,sha256=94_l5ClzGhP-0RWRgLFNj9NUjBCSepn_KYlmxEAjXi4,42936 +torch/jit/_script.py,sha256=_OE6wlsdZ_RzwKpOAcxmjD2QYrV1TzLNXv85ppq5HZM,68335 +torch/jit/_script.pyi,sha256=8LgMHIC1_beIEUEsOF0TvA38-oaRPY0WeocOA1-aoSk,9863 +torch/jit/_serialization.py,sha256=Gh5NSoXFDSnzYAqMqnR87MMNfWW1QrbhV5TDLcZUu3E,10679 +torch/jit/_shape_functions.py,sha256=_pwskeDX9i6iOa-2XTP9L1_PcDcBI79NgAWxM1VD-iA,52699 +torch/jit/_state.py,sha256=FurFVWQ_kV70XQZNjaXT9oyCJ9D1tbgzAX3uLiLBKLY,3884 +torch/jit/_trace.py,sha256=AzEop5GZdtKbRgEkdV794OFcFQHnAbzMQGRvDpdTlCk,56356 +torch/jit/annotations.py,sha256=-RrxpktiuCvYBayzsKAtD1SRfec_y-oQLroRGNMEgJ4,18198 +torch/jit/frontend.py,sha256=7QW-kzqT11_bjFahemEfFhVbRZxaN3SzYJcKThwOqps,45380 +torch/jit/generate_bytecode.py,sha256=e-Ltj08oGvI5x-Q3SWgnU0v21B-YQafnhYDj3XJ_C2c,1042 +torch/jit/mobile/__init__.py,sha256=vOfuv1w4w8EZKCzI_xKKHx-7XOnExm-whG9h2HATbRY,8602 +torch/jit/mobile/__pycache__/__init__.cpython-312.pyc,, +torch/jit/quantized.py,sha256=_qdmUEm74_VB2z0Dipf61uuvyefSkNAz0kLSPGxFMmA,3193 +torch/jit/supported_ops.py,sha256=GYnkVhhyLZRi41T2fDawMlbtvZGaf7vIr1S8Z9GAis4,10257 +torch/jit/unsupported_tensor_ops.py,sha256=3xUi019td89AYpNjqPgCckV2ucwEzGWO6XxkZ4fzZ1M,1974 +torch/lib/libaoti_custom_ops.so,sha256=Ktd2DzBnw-n12qE3TJ52Z0KqHuKfj2mNk54pr-OJOGQ,370488 +torch/lib/libbackend_with_compiler.so,sha256=LZsUKzoj-lsnsODgaF5NP7CJsFEvOSj6T8gwczvl5o0,261384 +torch/lib/libc10.so,sha256=nBQtvl8cUpHldgVYa_IuqgfNJ9pyCCWxzwL8L264BH4,1553824 +torch/lib/libgomp.so.1,sha256=3Lm9XMUXsKI89ZI4ZKvu4R7gC6EavpswiTiPUPe6Rig,2115417 +torch/lib/libjitbackend_test.so,sha256=yav-bqvfXnDp2PDoqDOVpdebjf59lDefaLz6Fmb7yR4,213776 +torch/lib/libshm.so,sha256=eEaCGgC-J1DwxxjGk5a9PD5Ukk1S7M40erYQ7pB5FJo,41328 +torch/lib/libshm/alloc_info.h,sha256=7SdVmCqiLa2mfKg-4DaB9rdpJnStPCmgXASpbjqtzBU,104 +torch/lib/libshm/err.h,sha256=j5cpgd5gS8_WgroKTyMLvDHDiXSe0GzbwE-1Sy88mA4,1258 +torch/lib/libshm/libshm.h,sha256=_6sOfY_vSO6mECr6XNIChm7r06uVO2fQRW-CZDOf5gs,1205 +torch/lib/libshm/socket.h,sha256=b_IuucKssZ6iHI_coGieeWw4aePAX9eYHly8l1BNyCs,4322 +torch/lib/libshm_windows/libshm.h,sha256=9MByK00M3an2HH2S8gFjZMUJsFJb96VRYE190Z-ALFo,779 +torch/lib/libtorch.so,sha256=KLPTkm4GdO2n3N8mwn39BctFXWgdEcuE_b9-DfcvP3s,8032 +torch/lib/libtorch_cpu.so,sha256=zD0BAcFlBLoCGr5nlMmBIvdE7Izwd70BePYw8yCySus,438232064 +torch/lib/libtorch_global_deps.so,sha256=Ll1JclmmKWDZX0p3GauuskdFQptJ_99Y5nZyFAIF65k,8264 +torch/lib/libtorch_python.so,sha256=AoJoDK0H0ektkqWGyvJWMoAHLbxNIoN1ml_OY_AaUA8,32676952 +torch/lib/libtorchbind_test.so,sha256=-bxxqyXEi5443iUj5Ap8MfmJ2d3QnWd3EWVy7v_04UE,918152 +torch/library.py,sha256=1f_6aZ857F0TUmNtXAv3d7RaxlNNAVTwI-ZOCH9k_SY,76530 +torch/linalg/__init__.py,sha256=yTx4P-UZ3Dh8C3zNu7GWSL8lhCGR2ElskF1RwxrN7U8,119792 +torch/linalg/__pycache__/__init__.cpython-312.pyc,, +torch/masked/__init__.py,sha256=WljBC5z-aMQ3EB29GNw5BVnONrx14zh1Cgrz7fqJ-1E,928 +torch/masked/__pycache__/__init__.cpython-312.pyc,, +torch/masked/__pycache__/_docs.cpython-312.pyc,, +torch/masked/__pycache__/_ops.cpython-312.pyc,, +torch/masked/_docs.py,sha256=vIWYOofz1IsYzO_Br0CV_JOOdu5s-qWBUGbdiHUnMHk,49469 +torch/masked/_ops.py,sha256=RgVah8tXEyhrxzXQt2Tom2aJ8-uVW6s2EfunbtPpZ2A,67745 +torch/masked/maskedtensor/__init__.py,sha256=yRXNgVmvSu6WET5dYVroutE7gtiXkN1JuBwogvcTvsY,344 +torch/masked/maskedtensor/__pycache__/__init__.cpython-312.pyc,, +torch/masked/maskedtensor/__pycache__/_ops_refs.cpython-312.pyc,, +torch/masked/maskedtensor/__pycache__/binary.cpython-312.pyc,, +torch/masked/maskedtensor/__pycache__/core.cpython-312.pyc,, +torch/masked/maskedtensor/__pycache__/creation.cpython-312.pyc,, +torch/masked/maskedtensor/__pycache__/passthrough.cpython-312.pyc,, +torch/masked/maskedtensor/__pycache__/reductions.cpython-312.pyc,, +torch/masked/maskedtensor/__pycache__/unary.cpython-312.pyc,, +torch/masked/maskedtensor/_ops_refs.py,sha256=iUIohR1D-kldMvpsf7fjs9do2tAThFcfA6PRwAkD-YA,18131 +torch/masked/maskedtensor/binary.py,sha256=8cYTvBPO3P-8I99WQrVr1oLMDrXsfcWPwU-HMu6I4Dk,5496 +torch/masked/maskedtensor/core.py,sha256=wiMFW3HmbdxW8IBOOyoSMQkxm9qPysvBJ_9ed2C9-wg,13058 +torch/masked/maskedtensor/creation.py,sha256=cuKrXLyknX42q3rbZOmrjmqgrFudey8GUh5Fmpu5YOs,605 +torch/masked/maskedtensor/passthrough.py,sha256=kEDm_BwgAN2erALo2NF8SLWX8J9jrAuySd9upW15-40,1447 +torch/masked/maskedtensor/reductions.py,sha256=lpGZNoL58xnxvhKntt2YMeZZUqcrGAzwijWSVhaRAmg,5599 +torch/masked/maskedtensor/unary.py,sha256=F3sO8CbzFYZhpTZxOx4nobOb7RRMgtx_gbY0IRbAXmA,4197 +torch/monitor/__init__.py,sha256=09VJnyTA2zwN2clbG0o6pV3Yf4YdzW2BospVTxNa4WU,1278 +torch/monitor/__pycache__/__init__.cpython-312.pyc,, +torch/mps/__init__.py,sha256=ZC2JPU4jX6yKddR8t5Xwrrnp7oWZi5tUvrSbwB8onXo,9086 +torch/mps/__pycache__/__init__.cpython-312.pyc,, +torch/mps/__pycache__/event.cpython-312.pyc,, +torch/mps/__pycache__/profiler.cpython-312.pyc,, +torch/mps/event.py,sha256=tobbRc_mwlY-8W0QlYxxQQg75sPO-25nLzR9Pw9Ix7Q,1730 +torch/mps/profiler.py,sha256=3N_-LjAbxEak8wFTfmlcJ_mgcVg9UPjdn9aJWesB80I,3578 +torch/mtia/__init__.py,sha256=uE91Ju0ptGP6Dtkguil2HPo-1GYEGng6OCOYZB_g8ew,18991 +torch/mtia/__pycache__/__init__.cpython-312.pyc,, +torch/mtia/__pycache__/_utils.cpython-312.pyc,, +torch/mtia/__pycache__/memory.cpython-312.pyc,, +torch/mtia/__pycache__/mtia_graph.cpython-312.pyc,, +torch/mtia/_utils.py,sha256=WaSYAeK_LXOUQXLKQwEYVrAfjpRhpCe7zcZbNN_KGKY,1912 +torch/mtia/memory.py,sha256=_NQP8NoU3C8ytbaPFMN0tVWONd9Lu4gLh0Xs9wnpxss,2233 +torch/mtia/mtia_graph.py,sha256=tOqt7wSx2HlxHnE7dHmZefXOAMQSEMY_ljBik8Gi-vM,2656 +torch/multiprocessing/__init__.py,sha256=G2aOej6lW6Tf1bm5P0r7I5DV2je9C2eFSnHck86DNJU,3508 +torch/multiprocessing/__pycache__/__init__.cpython-312.pyc,, +torch/multiprocessing/__pycache__/_atfork.cpython-312.pyc,, +torch/multiprocessing/__pycache__/pool.cpython-312.pyc,, +torch/multiprocessing/__pycache__/queue.cpython-312.pyc,, +torch/multiprocessing/__pycache__/reductions.cpython-312.pyc,, +torch/multiprocessing/__pycache__/spawn.cpython-312.pyc,, +torch/multiprocessing/_atfork.py,sha256=NDXE2HR06ENj_1bGrQumxLdTGSDOlP-2bzeNwij7ajA,790 +torch/multiprocessing/pool.py,sha256=HQtd_V3oWKnkpQRrR4cutVFdlwxWwgCiUVPYSQXaU7M,1743 +torch/multiprocessing/queue.py,sha256=OT9KTbNOpqjhun_ZQTXizodE1UOwrpSbJhYRKtAyNmE,1477 +torch/multiprocessing/reductions.py,sha256=tqIGRUpMq2Vw9PuNHG3jhzgTGMIWfI0W2DKaN_B-MSU,22981 +torch/multiprocessing/spawn.py,sha256=_Dhfal6Wuy6zHLJrSf9TVA-5EWHWoXgLvCiXmdQmVsM,12863 +torch/nativert/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/nativert/__pycache__/__init__.cpython-312.pyc,, +torch/nativert/backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/nativert/backends/__pycache__/__init__.cpython-312.pyc,, +torch/nativert/backends/__pycache__/_lower_utils.cpython-312.pyc,, +torch/nativert/backends/__pycache__/_lowered_aoti_module.cpython-312.pyc,, +torch/nativert/backends/_lower_utils.py,sha256=2S0KcY-NadyeIEPGYIG6vDfG9H3nb7ac7SKBwpStX6g,3614 +torch/nativert/backends/_lowered_aoti_module.py,sha256=qBtnm7S4xagZczsqAdqcqmpLHwz-Z65tMvenrbSP3Fc,890 +torch/nested/__init__.py,sha256=Fk5mR2xSeDMFW6eiAR6mSxyYJl1oQX4nvaTkr6ecJ6I,22342 +torch/nested/__pycache__/__init__.cpython-312.pyc,, +torch/nested/_internal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/nested/_internal/__pycache__/__init__.cpython-312.pyc,, +torch/nested/_internal/__pycache__/nested_int.cpython-312.pyc,, +torch/nested/_internal/__pycache__/nested_tensor.cpython-312.pyc,, +torch/nested/_internal/__pycache__/ops.cpython-312.pyc,, +torch/nested/_internal/__pycache__/sdpa.cpython-312.pyc,, +torch/nested/_internal/nested_int.py,sha256=9FoOZfUv3dcUrDOuRsrje6zORe23oqGnALGxEMsoYDc,3319 +torch/nested/_internal/nested_tensor.py,sha256=n3ByrapJ64a8svTREyUWcDCQ2VWEUKEhrOvhGnVYNdU,29219 +torch/nested/_internal/ops.py,sha256=8ShRjB0YS4gGRFO4VPaU9JpQzDP8u0fm4dRpm06img4,97255 +torch/nested/_internal/sdpa.py,sha256=VuI2SW5XWiRyPpZJ1hTkar-ipvKmOTd5cTOoVQKiVYM,35569 +torch/nn/__init__.py,sha256=SGakM4nNGjI1YZwNintPfgNVTV5FrVKhiFXbq5Db8Pk,2425 +torch/nn/__pycache__/__init__.cpython-312.pyc,, +torch/nn/__pycache__/_reduction.cpython-312.pyc,, +torch/nn/__pycache__/common_types.cpython-312.pyc,, +torch/nn/__pycache__/cpp.cpython-312.pyc,, +torch/nn/__pycache__/functional.cpython-312.pyc,, +torch/nn/__pycache__/grad.cpython-312.pyc,, +torch/nn/__pycache__/init.cpython-312.pyc,, +torch/nn/__pycache__/parameter.cpython-312.pyc,, +torch/nn/_reduction.py,sha256=ndJ4VxoNYRrvspg35qJtWdkGi0Cu2XsMv-sa0rBDt-s,1626 +torch/nn/attention/__init__.py,sha256=DZITKtQURhKFT0DbrcdHMQVcfnKx8W6T1KAA06cjI-s,7228 +torch/nn/attention/__pycache__/__init__.cpython-312.pyc,, +torch/nn/attention/__pycache__/_fa3.cpython-312.pyc,, +torch/nn/attention/__pycache__/_fa4.cpython-312.pyc,, +torch/nn/attention/__pycache__/_registry.cpython-312.pyc,, +torch/nn/attention/__pycache__/_utils.cpython-312.pyc,, +torch/nn/attention/__pycache__/bias.cpython-312.pyc,, +torch/nn/attention/__pycache__/flex_attention.cpython-312.pyc,, +torch/nn/attention/__pycache__/varlen.cpython-312.pyc,, +torch/nn/attention/_fa3.py,sha256=TW_aJKQgMNqGPJdloXMCi-H6P7bXW38P6kkqdgOvjN0,21121 +torch/nn/attention/_fa4.py,sha256=xP5HnqFJXRWYwgI_PrT6cffPr-6_ljpca9VonyGRGTQ,14645 +torch/nn/attention/_registry.py,sha256=gD85V4lu2cwtJD6U91RttNy1oZZA0vslni0NwrAvJfY,4463 +torch/nn/attention/_utils.py,sha256=AElRsYvBfPxbPT2xyHq32GTwk_5NgSd1ucR3Jn05CMg,2088 +torch/nn/attention/bias.py,sha256=7nhZruD9ntFfTAg3YGacd9a86UMgbtruvB3ncVJQoIg,13784 +torch/nn/attention/experimental/__init__.py,sha256=VXpUxbEIcm46WvCIT1rgWY3vSN7V7UMT42FqE7UR-9M,111 +torch/nn/attention/experimental/__pycache__/__init__.cpython-312.pyc,, +torch/nn/attention/experimental/__pycache__/_paged_attention.cpython-312.pyc,, +torch/nn/attention/experimental/__pycache__/_scaled_dot_product_attention_quantized.cpython-312.pyc,, +torch/nn/attention/experimental/_paged_attention.py,sha256=r9zNXBmL718JyeAqKWPBU_DRUxyg9gGA1B4J_8Db448,13216 +torch/nn/attention/experimental/_scaled_dot_product_attention_quantized.py,sha256=RwS2dWSK_Nv85Yct-tZ9RWuANeXCrNDNH85R2oWb8Ko,5788 +torch/nn/attention/flex_attention.py,sha256=ITzMEisJYa41Tcvkvv6S-U5V1F-gax34dXwyfSr6oVU,102925 +torch/nn/attention/varlen.py,sha256=1s5oYFSNKxT7e_OQSVBE6Eh4f3Kr86Ojwp3xIlJV8Dk,22608 +torch/nn/backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/nn/backends/__pycache__/__init__.cpython-312.pyc,, +torch/nn/backends/__pycache__/thnn.cpython-312.pyc,, +torch/nn/backends/thnn.py,sha256=DIn1LJwiPPLheO-ePySpWoHesiuc7NUEcfM4X-hyE2Y,154 +torch/nn/common_types.py,sha256=6nu95uJFHkfNYQrVRxzgRWSF-4tVNSzIF7A1h3HWiMI,2089 +torch/nn/cpp.py,sha256=qiuQgs3CT0t-Vy1FcJsrm08DQSHnMcxG09AWIf2hu_A,3100 +torch/nn/functional.py,sha256=lf9AMIW7F5R3oB32Os_d9Z36wPtYgp6Zqci1wv6YiZs,278980 +torch/nn/functional.pyi,sha256=ieN3-tC6EzKOKgAy5ER9WCc7saudZV3oSeTlcJBT1Zs,28270 +torch/nn/grad.py,sha256=xEFG-ZnkxxjBMJajUSoNPqlHLiFFFAZ3wXBvn2kCRYc,9910 +torch/nn/init.py,sha256=WdrV9Ry3ALvjoyOkFp53SJRwwlWCg4WU-Y6OVfgVb30,26593 +torch/nn/intrinsic/__init__.py,sha256=U77fBY1ieLXqAcF7zqx6xx-vyE9mCgeEZkvHW9IbgjA,669 +torch/nn/intrinsic/__pycache__/__init__.cpython-312.pyc,, +torch/nn/intrinsic/modules/__init__.py,sha256=bqi9D10UvQcO_cimMFdlI5HjLEvFOp7Y0hT6g3WOSMQ,517 +torch/nn/intrinsic/modules/__pycache__/__init__.cpython-312.pyc,, +torch/nn/intrinsic/modules/__pycache__/fused.cpython-312.pyc,, +torch/nn/intrinsic/modules/fused.py,sha256=Q6ta4U7JgPoSVs66FPll7Hjhjl_pXcO3pFWKGnBzspk,563 +torch/nn/intrinsic/qat/__init__.py,sha256=7rFxYP3UVmm4gwSlC7aBqXoJF1s0Q4aIdJZuW7ST8wI,59 +torch/nn/intrinsic/qat/__pycache__/__init__.cpython-312.pyc,, +torch/nn/intrinsic/qat/modules/__init__.py,sha256=n9s1HTHyr4Ao5_38irURngF2ZPh7pTJy9eos_oIz3Bs,637 +torch/nn/intrinsic/qat/modules/__pycache__/__init__.cpython-312.pyc,, +torch/nn/intrinsic/qat/modules/__pycache__/conv_fused.cpython-312.pyc,, +torch/nn/intrinsic/qat/modules/__pycache__/linear_fused.cpython-312.pyc,, +torch/nn/intrinsic/qat/modules/__pycache__/linear_relu.cpython-312.pyc,, +torch/nn/intrinsic/qat/modules/conv_fused.py,sha256=YKNHs_Fh3tfSoWmUAgd5APZwerDHpxPyY8KAXXDdMak,833 +torch/nn/intrinsic/qat/modules/linear_fused.py,sha256=qKnc8PyXqHPM--vfXmlD7JQoR5I480vCcYNZu-52-mM,434 +torch/nn/intrinsic/qat/modules/linear_relu.py,sha256=8740qDh1H-F03wWtKB6tQhPFSf2M2Cowyb91sfs02Ww,434 +torch/nn/intrinsic/quantized/__init__.py,sha256=LdqC1LFI5lpIY34H0B2y0QlVtbYp78P_72k9-KMh7h4,322 +torch/nn/intrinsic/quantized/__pycache__/__init__.cpython-312.pyc,, +torch/nn/intrinsic/quantized/dynamic/__init__.py,sha256=Ov25o_5XouCKIqpzK42xcw8dAwVd02tGZqS4XL8BOIM,73 +torch/nn/intrinsic/quantized/dynamic/__pycache__/__init__.cpython-312.pyc,, +torch/nn/intrinsic/quantized/dynamic/modules/__init__.py,sha256=acHjDVSQZsjlTsbUoN4pI-971UJRfjavwMJRJuEOOBk,114 +torch/nn/intrinsic/quantized/dynamic/modules/__pycache__/__init__.cpython-312.pyc,, +torch/nn/intrinsic/quantized/dynamic/modules/__pycache__/linear_relu.cpython-312.pyc,, +torch/nn/intrinsic/quantized/dynamic/modules/linear_relu.py,sha256=z509nJpUu_QTwDUjE_ON9Fbu7n5GfMnOzWju35bEXRk,97 +torch/nn/intrinsic/quantized/modules/__init__.py,sha256=6WHqSE0pA7qaW20FVPWggCar8uawjVKABKVeNdxjNlo,379 +torch/nn/intrinsic/quantized/modules/__pycache__/__init__.cpython-312.pyc,, +torch/nn/intrinsic/quantized/modules/__pycache__/bn_relu.cpython-312.pyc,, +torch/nn/intrinsic/quantized/modules/__pycache__/conv_relu.cpython-312.pyc,, +torch/nn/intrinsic/quantized/modules/__pycache__/linear_relu.cpython-312.pyc,, +torch/nn/intrinsic/quantized/modules/bn_relu.py,sha256=3t9doT82fRh1SytKSivqQgxVfDP41KuvL-R9hz8oSb8,111 +torch/nn/intrinsic/quantized/modules/conv_relu.py,sha256=QWzacsMW7FtkasYvsZ9WqRExBjaMqsxHQHD5tYsZBFA,149 +torch/nn/intrinsic/quantized/modules/linear_relu.py,sha256=Zuj3I1owPTdoovG1-BoogRjn8JX1rMWM-WXYc-QFneU,89 +torch/nn/modules/__init__.py,sha256=ITqoRqXYhAuFwTmuWYyIILp5GRQYpVcbGSnN6dW7o5Q,6701 +torch/nn/modules/__pycache__/__init__.cpython-312.pyc,, +torch/nn/modules/__pycache__/_functions.cpython-312.pyc,, +torch/nn/modules/__pycache__/activation.cpython-312.pyc,, +torch/nn/modules/__pycache__/adaptive.cpython-312.pyc,, +torch/nn/modules/__pycache__/batchnorm.cpython-312.pyc,, +torch/nn/modules/__pycache__/channelshuffle.cpython-312.pyc,, +torch/nn/modules/__pycache__/container.cpython-312.pyc,, +torch/nn/modules/__pycache__/conv.cpython-312.pyc,, +torch/nn/modules/__pycache__/distance.cpython-312.pyc,, +torch/nn/modules/__pycache__/dropout.cpython-312.pyc,, +torch/nn/modules/__pycache__/flatten.cpython-312.pyc,, +torch/nn/modules/__pycache__/fold.cpython-312.pyc,, +torch/nn/modules/__pycache__/instancenorm.cpython-312.pyc,, +torch/nn/modules/__pycache__/lazy.cpython-312.pyc,, +torch/nn/modules/__pycache__/linear.cpython-312.pyc,, +torch/nn/modules/__pycache__/linear_cross_entropy.cpython-312.pyc,, +torch/nn/modules/__pycache__/linear_cross_entropy_options.cpython-312.pyc,, +torch/nn/modules/__pycache__/loss.cpython-312.pyc,, +torch/nn/modules/__pycache__/module.cpython-312.pyc,, +torch/nn/modules/__pycache__/normalization.cpython-312.pyc,, +torch/nn/modules/__pycache__/padding.cpython-312.pyc,, +torch/nn/modules/__pycache__/pixelshuffle.cpython-312.pyc,, +torch/nn/modules/__pycache__/pooling.cpython-312.pyc,, +torch/nn/modules/__pycache__/rnn.cpython-312.pyc,, +torch/nn/modules/__pycache__/sparse.cpython-312.pyc,, +torch/nn/modules/__pycache__/transformer.cpython-312.pyc,, +torch/nn/modules/__pycache__/upsampling.cpython-312.pyc,, +torch/nn/modules/__pycache__/utils.cpython-312.pyc,, +torch/nn/modules/_functions.py,sha256=CZ4TeTry7cEKCojji-_cI_a9qoZ0LqVQgRM5Ldm7Fts,12175 +torch/nn/modules/activation.py,sha256=mx71xtrq85K5Jn-CpyEtoiIzwjuLNEp0lNWEJqK_Nnk,62517 +torch/nn/modules/adaptive.py,sha256=_0vfG4Hvt3ufGCYb-U8Z_Hl6dyapuoVI18zik6ugpq0,12567 +torch/nn/modules/batchnorm.py,sha256=tZpkj-XYfqmPlThAp1VC4M0e-Jv5gSfJ8AuO1QUfHgc,41172 +torch/nn/modules/channelshuffle.py,sha256=1K2PoerBn3WvtN3gfTyLAp6sjMVhADPjgI0eV5XD0WU,1682 +torch/nn/modules/container.py,sha256=Wo4TKE5mK6sISN64DNeRSPkSG4V4l-K_Fkrg5QYUHHU,37531 +torch/nn/modules/conv.py,sha256=7yYdlGN4_LWgR9IRPvcV8EsolO7y8vetYAnJIPLp68E,79713 +torch/nn/modules/distance.py,sha256=z7zUT5-kLio0kqt6r3EwNgDpmPDcoRC6QasilD_yTsk,3372 +torch/nn/modules/dropout.py,sha256=KsCxY7vfpcbHI_rcZjcJm_juQS44bCFQKhIi7baM4Wc,11520 +torch/nn/modules/flatten.py,sha256=Mw9RuxC_4VqUwID7ZxuBeeulcoEqAB17ZtHGbDfQTLI,4406 +torch/nn/modules/fold.py,sha256=o58ibuN2AmkR3o2Qg9ACBwx8iAFTlhaEuyGpucZxr14,13227 +torch/nn/modules/instancenorm.py,sha256=J1ZT_OfHSVwxB1uJpXWyKA64XXW_Ued7PJ3AVAqRVLQ,21522 +torch/nn/modules/lazy.py,sha256=7rS26G5O_l5ahE2r30mPx_CLVg5N2xHEmZavxjuZsI4,11671 +torch/nn/modules/linear.py,sha256=GWGtGh9lDhBLPH940Zry0hv5d-evbD_fJCCq1WPJ4gI,12376 +torch/nn/modules/linear_cross_entropy.py,sha256=fgjyB2j9xOcHfghlA3CpH3R3ItPkGR9caOw4espCyEM,61624 +torch/nn/modules/linear_cross_entropy_options.py,sha256=e5Sg89PFs4KVN3PZsoRwSWsGq9Otj6iwJMbrq_E8j0c,13885 +torch/nn/modules/loss.py,sha256=QV5My7q2O5zCt58JozjMpvoZHAcTik-0GePIQcR0iuA,106989 +torch/nn/modules/module.py,sha256=0Tn8HcmtsXLCCLi0cPxAXYA3YSwPCHaNJ1xbvMKEuck,128414 +torch/nn/modules/normalization.py,sha256=lihLY6IIjH03hxbVEU61tqHActR5EWFw_P0oTFfoS08,15924 +torch/nn/modules/padding.py,sha256=1SW45BoRgFEbjcGNXlCgTSAojW1Cl5EoVtrZBjp9998,31705 +torch/nn/modules/pixelshuffle.py,sha256=N4rqCH-2DvBKLG4ZpJLHUNsv8Ylx2uQHm7VxRop4CWw,3948 +torch/nn/modules/pooling.py,sha256=8o8cZFe7kFB-XHSsGJy13ujx1Ul3zaKuZ3IqFA5w22s,61338 +torch/nn/modules/rnn.py,sha256=kC3uuo_X08krAONVcHGzu0HPdHvUsrnWN1fYhWJoi94,76132 +torch/nn/modules/sparse.py,sha256=SJe1QCw15JyDDtruHqzBscP4At3I5930ESpxx4vqgfU,24262 +torch/nn/modules/transformer.py,sha256=ZR2DvIAN4s4C0ZYlPaLEzdt5HozRjHF2neHEmGQynSw,52308 +torch/nn/modules/upsampling.py,sha256=zmLn5oBzU6g6Er2TmIKq6pGuiqjUt_5ufDbQ1xiENB8,11609 +torch/nn/modules/utils.py,sha256=kS7sezb3cU9-B9swphiw4LaO0kzOlegUliZTHuFtKIk,2601 +torch/nn/parallel/__init__.py,sha256=z43J5FJ5qqe_aVSla6yG0qZ19t_Y9pX3g3BzYJvVuSs,760 +torch/nn/parallel/__pycache__/__init__.cpython-312.pyc,, +torch/nn/parallel/__pycache__/_functions.cpython-312.pyc,, +torch/nn/parallel/__pycache__/comm.cpython-312.pyc,, +torch/nn/parallel/__pycache__/data_parallel.cpython-312.pyc,, +torch/nn/parallel/__pycache__/distributed.cpython-312.pyc,, +torch/nn/parallel/__pycache__/parallel_apply.cpython-312.pyc,, +torch/nn/parallel/__pycache__/replicate.cpython-312.pyc,, +torch/nn/parallel/__pycache__/scatter_gather.cpython-312.pyc,, +torch/nn/parallel/_functions.py,sha256=HHi7gH1S1mwDXLC2ivD3w3e_s3AqO3qgHKelO2mzMOk,6226 +torch/nn/parallel/comm.py,sha256=ogPGR7BU6F8EWlHYpAVjVGdBJrr6uNsfTIVgiZdhAW8,11105 +torch/nn/parallel/data_parallel.py,sha256=dCC7VAilFp53b5FaJIiObG1SBdZkPwM9F3JIhNakKtM,11938 +torch/nn/parallel/distributed.py,sha256=-c9fvBZqX6mlsbZjJudVO_99LIPT8qafrnHkdiMfE_E,120924 +torch/nn/parallel/parallel_apply.py,sha256=tQQAIHez6tVvF3-Zgm17cYFi7MV_JGIZYlzf0rIEqWI,5115 +torch/nn/parallel/replicate.py,sha256=Liqy8_duwGZXezk1s6C9_KMpxxv1PKEekgA-ORd5hsA,7261 +torch/nn/parallel/scatter_gather.py,sha256=kPoOGvZe5zY2JBncFvOVqmHNYUZnCQUDXIopYmYKP0Y,5550 +torch/nn/parameter.py,sha256=Ac4OShDFS5IziNAVETthAom4nnqP9ICeq2XgaxvHU6I,12322 +torch/nn/parameter.pyi,sha256=nWmOqB7CJFdB0wabxODC0yZI5j0N20MhsHb_twxD3Ac,1118 +torch/nn/qat/__init__.py,sha256=vwTKzSE2_xHNzs0rHOr5AGgGNzukn9e0CDtobwcFQdY,330 +torch/nn/qat/__pycache__/__init__.cpython-312.pyc,, +torch/nn/qat/dynamic/__init__.py,sha256=4UEA7Zd6seZcA5yOrmAtiMTvovIg9sH5ULXV5d9e7NU,187 +torch/nn/qat/dynamic/__pycache__/__init__.cpython-312.pyc,, +torch/nn/qat/dynamic/modules/__init__.py,sha256=xnBpUudYrmz9leiWC2UaMEGbDX2eO--nNluoaO_V-LE,78 +torch/nn/qat/dynamic/modules/__pycache__/__init__.cpython-312.pyc,, +torch/nn/qat/dynamic/modules/__pycache__/linear.cpython-312.pyc,, +torch/nn/qat/dynamic/modules/linear.py,sha256=io9A-B4H0RMvMRYuKeVSxRQPsBhdCy5WKfvr5QtKHuo,416 +torch/nn/qat/modules/__init__.py,sha256=f-ps2aVcJ-rxPc73I7ZezCycQAlnyAg6nkuDQYQKuys,480 +torch/nn/qat/modules/__pycache__/__init__.cpython-312.pyc,, +torch/nn/qat/modules/__pycache__/conv.cpython-312.pyc,, +torch/nn/qat/modules/__pycache__/embedding_ops.cpython-312.pyc,, +torch/nn/qat/modules/__pycache__/linear.cpython-312.pyc,, +torch/nn/qat/modules/conv.py,sha256=hOAGSJ7oaQTf_9DWXPWrGGsQ9oPLASiCZaeHX4X3BMI,406 +torch/nn/qat/modules/embedding_ops.py,sha256=0kpyNUF8GiA2OSNW98ZdsWdQ8R2fn7PG0DrpmlcwueQ,437 +torch/nn/qat/modules/linear.py,sha256=cFw8lAcvlWfV__h6uSDi9w4I7snqlWGVAyfY7nnHiMA,392 +torch/nn/quantizable/__init__.py,sha256=O3C0GktZB_Ut6pNTL17JbCzJ2h2hCIK3KH8sVnhSuDs,57 +torch/nn/quantizable/__pycache__/__init__.cpython-312.pyc,, +torch/nn/quantizable/modules/__init__.py,sha256=gr03bjx4iwgg1n8zCu3B1UpgNqhb6UxxSVvwO5894V4,207 +torch/nn/quantizable/modules/__pycache__/__init__.cpython-312.pyc,, +torch/nn/quantizable/modules/__pycache__/activation.cpython-312.pyc,, +torch/nn/quantizable/modules/__pycache__/rnn.cpython-312.pyc,, +torch/nn/quantizable/modules/activation.py,sha256=m8gKPli1OoBlwAng4E2ndP9K3ov2t6D7pN1Zj84nv0g,440 +torch/nn/quantizable/modules/rnn.py,sha256=ymfl_ayTkuUunsNt9186sFOhtapsxsTHVtY_QlKFH9A,429 +torch/nn/quantized/__init__.py,sha256=I4luOzGPauG81OAaU1LDBEYYZf5H2tcReqx3UDLRGeg,757 +torch/nn/quantized/__pycache__/__init__.cpython-312.pyc,, +torch/nn/quantized/__pycache__/functional.cpython-312.pyc,, +torch/nn/quantized/_reference/__init__.py,sha256=VrWZh6FzvyvAi744iiFBcYarBX3Akn6kTarYzEIX0_w,66 +torch/nn/quantized/_reference/__pycache__/__init__.cpython-312.pyc,, +torch/nn/quantized/_reference/modules/__init__.py,sha256=8sFUEypCyt8WkvzsGQSHX0hs1_ktXTQzrKMGCVAXPrI,997 +torch/nn/quantized/_reference/modules/__pycache__/__init__.cpython-312.pyc,, +torch/nn/quantized/_reference/modules/__pycache__/conv.cpython-312.pyc,, +torch/nn/quantized/_reference/modules/__pycache__/linear.cpython-312.pyc,, +torch/nn/quantized/_reference/modules/__pycache__/rnn.cpython-312.pyc,, +torch/nn/quantized/_reference/modules/__pycache__/sparse.cpython-312.pyc,, +torch/nn/quantized/_reference/modules/__pycache__/utils.cpython-312.pyc,, +torch/nn/quantized/_reference/modules/conv.py,sha256=FclYIsMCbXH4erKiBDintHNWDsplOru0QY9LDToSL-s,579 +torch/nn/quantized/_reference/modules/linear.py,sha256=Cu-oS3rGRNtFQX8C8yBiLIeORYswqNnFbVw3ds6PMKQ,450 +torch/nn/quantized/_reference/modules/rnn.py,sha256=A6kV2QXCij5mpFFUTWBQwf6ynKQNJj0VMJbvHqkXa-Y,524 +torch/nn/quantized/_reference/modules/sparse.py,sha256=gSNXDYXlx1IoSrRN0i_pJHJt1znBH3sAPvDpivdfask,467 +torch/nn/quantized/_reference/modules/utils.py,sha256=nBSMp0qUV2OBmuCJYKGmpY6JtRinMoHhwPT2B8VbY08,590 +torch/nn/quantized/dynamic/__init__.py,sha256=lN8JfmyIwtMWNsOD0hWGgKMVPUXuUb5cu6QOvIlEJxg,58 +torch/nn/quantized/dynamic/__pycache__/__init__.cpython-312.pyc,, +torch/nn/quantized/dynamic/modules/__init__.py,sha256=2mJZzn6ZaIzLHTX9dU-aXU7Bcowgq3UsuF3hhByCcbs,972 +torch/nn/quantized/dynamic/modules/__pycache__/__init__.cpython-312.pyc,, +torch/nn/quantized/dynamic/modules/__pycache__/conv.cpython-312.pyc,, +torch/nn/quantized/dynamic/modules/__pycache__/linear.cpython-312.pyc,, +torch/nn/quantized/dynamic/modules/__pycache__/rnn.cpython-312.pyc,, +torch/nn/quantized/dynamic/modules/conv.py,sha256=eT03qZPxErIj3Mm3MoO2em09Kt2RbLH7zjTnMETTiuQ,648 +torch/nn/quantized/dynamic/modules/linear.py,sha256=67W7Cw26T5oIiE4n3RJykC6PX5VypOJU3lQcNP6mohg,448 +torch/nn/quantized/dynamic/modules/rnn.py,sha256=IvRmd5OXkS2nQ6o7PbIAo0ILMjxpUG2TOR2Q1H_yuyE,719 +torch/nn/quantized/functional.py,sha256=jpavS-mvtV2fFn8vuSt3oHGucv0l5A4lXqM21X_uUZ0,271 +torch/nn/quantized/modules/__init__.py,sha256=oNogz5eH2YEYfHjRkYBEqp_XD2GduDqc9StknEGWx40,2101 +torch/nn/quantized/modules/__pycache__/__init__.cpython-312.pyc,, +torch/nn/quantized/modules/__pycache__/activation.cpython-312.pyc,, +torch/nn/quantized/modules/__pycache__/batchnorm.cpython-312.pyc,, +torch/nn/quantized/modules/__pycache__/conv.cpython-312.pyc,, +torch/nn/quantized/modules/__pycache__/dropout.cpython-312.pyc,, +torch/nn/quantized/modules/__pycache__/embedding_ops.cpython-312.pyc,, +torch/nn/quantized/modules/__pycache__/functional_modules.cpython-312.pyc,, +torch/nn/quantized/modules/__pycache__/linear.cpython-312.pyc,, +torch/nn/quantized/modules/__pycache__/normalization.cpython-312.pyc,, +torch/nn/quantized/modules/__pycache__/rnn.cpython-312.pyc,, +torch/nn/quantized/modules/__pycache__/utils.cpython-312.pyc,, +torch/nn/quantized/modules/activation.py,sha256=52tIo-6xSFg2QIuNL-Q7AKs2IiDBCcGFIvWNupA3fjA,528 +torch/nn/quantized/modules/batchnorm.py,sha256=OpxwQosX9Pv53csZ4ZXKhFOkya_tXMbtndDMSETJKV8,437 +torch/nn/quantized/modules/conv.py,sha256=3JBXb4gZOKXHIyWnnPEVxlb-WRDSMiNEUvuofCSNsSw,666 +torch/nn/quantized/modules/dropout.py,sha256=1kVenXsC8wZEzFWXxmMhYacoWB4R44U-RMflxMOo0Y0,421 +torch/nn/quantized/modules/embedding_ops.py,sha256=u0WaFQfWSruX8YAIOOcAGhCzq2UYr1QcAQ88-HMz5FU,526 +torch/nn/quantized/modules/functional_modules.py,sha256=Wbq2xzHqzG_DfFm41Ug4aJMMWA2iFruw0mPW4Xw8KxU,533 +torch/nn/quantized/modules/linear.py,sha256=g4-_sDzbJwLzBLUrcFqBttPrmghSl8abyUMWpFXenOI,460 +torch/nn/quantized/modules/normalization.py,sha256=GfKhFb5fzNHTZ6jcBpfk70h1sgtSRDTFYGKHUVNnfHM,605 +torch/nn/quantized/modules/rnn.py,sha256=NWI5IuH_qaC1YD1ROeoUbodbN3yS0MrZKOhXLmGfPDo,411 +torch/nn/quantized/modules/utils.py,sha256=ZkyzQS1nmLaK5Nvq2eKtSha7mHG3HyM08_5ueUc9FpQ,539 +torch/nn/utils/__init__.py,sha256=IDrUDb4E1qZkMUEfsT0eN0zC9YJyHjbJc0oxtgosE0c,1274 +torch/nn/utils/__pycache__/__init__.cpython-312.pyc,, +torch/nn/utils/__pycache__/_deprecation_utils.cpython-312.pyc,, +torch/nn/utils/__pycache__/_named_member_accessor.cpython-312.pyc,, +torch/nn/utils/__pycache__/_per_sample_grad.cpython-312.pyc,, +torch/nn/utils/__pycache__/clip_grad.cpython-312.pyc,, +torch/nn/utils/__pycache__/convert_parameters.cpython-312.pyc,, +torch/nn/utils/__pycache__/fusion.cpython-312.pyc,, +torch/nn/utils/__pycache__/init.cpython-312.pyc,, +torch/nn/utils/__pycache__/memory_format.cpython-312.pyc,, +torch/nn/utils/__pycache__/parametrizations.cpython-312.pyc,, +torch/nn/utils/__pycache__/parametrize.cpython-312.pyc,, +torch/nn/utils/__pycache__/prune.cpython-312.pyc,, +torch/nn/utils/__pycache__/rnn.cpython-312.pyc,, +torch/nn/utils/__pycache__/spectral_norm.cpython-312.pyc,, +torch/nn/utils/__pycache__/stateless.cpython-312.pyc,, +torch/nn/utils/__pycache__/weight_norm.cpython-312.pyc,, +torch/nn/utils/_deprecation_utils.py,sha256=KB2l-yIWZAA9OI0lT0f2s5WXeFvwvydY4EP0GGDDags,1698 +torch/nn/utils/_expanded_weights/__init__.py,sha256=PHIe9H3l0iuImQ6z3WqMkWIS37FDQVQ16vMo0a08mtA,452 +torch/nn/utils/_expanded_weights/__pycache__/__init__.cpython-312.pyc,, +torch/nn/utils/_expanded_weights/__pycache__/conv_expanded_weights.cpython-312.pyc,, +torch/nn/utils/_expanded_weights/__pycache__/conv_utils.cpython-312.pyc,, +torch/nn/utils/_expanded_weights/__pycache__/embedding_expanded_weights.cpython-312.pyc,, +torch/nn/utils/_expanded_weights/__pycache__/expanded_weights_impl.cpython-312.pyc,, +torch/nn/utils/_expanded_weights/__pycache__/expanded_weights_utils.cpython-312.pyc,, +torch/nn/utils/_expanded_weights/__pycache__/group_norm_expanded_weights.cpython-312.pyc,, +torch/nn/utils/_expanded_weights/__pycache__/instance_norm_expanded_weights.cpython-312.pyc,, +torch/nn/utils/_expanded_weights/__pycache__/layer_norm_expanded_weights.cpython-312.pyc,, +torch/nn/utils/_expanded_weights/__pycache__/linear_expanded_weights.cpython-312.pyc,, +torch/nn/utils/_expanded_weights/conv_expanded_weights.py,sha256=5Kr60dZ4gzcsX-uPJYWw6_9-Afoqu5QgVAmUt-smiDA,2925 +torch/nn/utils/_expanded_weights/conv_utils.py,sha256=zBK395zVXICgn_D27-TuOJHV5ro3W1b3k_z3Z8LcwR4,10814 +torch/nn/utils/_expanded_weights/embedding_expanded_weights.py,sha256=kVjENz7zj9_3fIiF9rNgNbUx7Z78UNSEJRhO9dYjryc,3073 +torch/nn/utils/_expanded_weights/expanded_weights_impl.py,sha256=bkibGEo4InglfM5Uys3QdSwWpQImq1wXyaKGOscqmHs,6405 +torch/nn/utils/_expanded_weights/expanded_weights_utils.py,sha256=l0Kjs3qjXsjwYxVf86g23uI_UufloirP79V4tBp3ALo,7612 +torch/nn/utils/_expanded_weights/group_norm_expanded_weights.py,sha256=Uw86QFNavKYlaNSnbSbBH0ieyQSh3jyChz9fwbKxoO4,3514 +torch/nn/utils/_expanded_weights/instance_norm_expanded_weights.py,sha256=b2nMyxZegXpbvAmN2OAJSBWAlKcXQCSPjl_6aFCUnf0,3638 +torch/nn/utils/_expanded_weights/layer_norm_expanded_weights.py,sha256=X1r7CwjyK-j03S9J6axQPGJ7DQr-yg1mWUNQ3Rip9UE,3289 +torch/nn/utils/_expanded_weights/linear_expanded_weights.py,sha256=6BI2LGjLpH29uFg5ktMxIW7AmxrA83uBPs62YmZOqww,2259 +torch/nn/utils/_named_member_accessor.py,sha256=m5zwqxzn6O2vwfz9lFZhYwewQLQZHVYPJvTlqbM5WgA,14470 +torch/nn/utils/_per_sample_grad.py,sha256=r2XSvB-eGfw7g-TOhHWT_v_w2K4oI3qaK7pHxm9S_iw,5775 +torch/nn/utils/clip_grad.py,sha256=XjDawX6wMRqxoS5G7SSE3stmFlQnZE0mAdE1cKsO5Nc,11465 +torch/nn/utils/convert_parameters.py,sha256=xiTn9HykDVWMwcR_Kx4zTJrTWxtLlfPv3oWYxeSUku4,3213 +torch/nn/utils/fusion.py,sha256=qbwJpB-sZ4tIAvBcfWDb61Hpla6ERwUAHb5Dx8fxEo4,6753 +torch/nn/utils/init.py,sha256=eA5Y0Ti3Qjhd-pCKEx9MpLHjJuz4bA3XNw6W0lC55XE,2250 +torch/nn/utils/memory_format.py,sha256=fYxW9eaJswQSSDeH1Yn2TVC0C_ExJMKWumdhgl5jiEc,8206 +torch/nn/utils/parametrizations.py,sha256=mbnzVjQcTikvZmU2bFt2H1V6NkliEKOiilTYPRfzkVM,26041 +torch/nn/utils/parametrize.py,sha256=aXI_G6STlU6r8hkhd4fYrwnvL0BLQQMC9F-tF1KMHkQ,39229 +torch/nn/utils/prune.py,sha256=46-Ke4KIBxlYokK-2BzWXvfE2jjPjLDMazlGcXYRyRI,59112 +torch/nn/utils/rnn.py,sha256=dwyonizGne8qGfUuzqkbWb2uLeG0FZs-qDaSdu-TT_4,23131 +torch/nn/utils/spectral_norm.py,sha256=FfU4JmZRyFzFd46zY-35yJsv0DBrtCl_HUPjKx3RagM,14711 +torch/nn/utils/stateless.py,sha256=wpatmYruJJu9matEpPf3dI9MMEHc-z6MXf07EbADo9o,11568 +torch/nn/utils/weight_norm.py,sha256=DtJ6FG38Y9eadJsg5DjVqGJpbHMGHWRVSc52qjSqJro,6113 +torch/numa/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/numa/__pycache__/__init__.cpython-312.pyc,, +torch/numa/__pycache__/binding.cpython-312.pyc,, +torch/numa/binding.py,sha256=upM7a6wHuQsPOysWDlWuFIxJU7JaGMXQj3-5mmKAEyw,25218 +torch/onnx/__init__.py,sha256=A1ipr9X8Zd52EBrFVnqGuLiZOxBnDyRloURZwePG8i8,15234 +torch/onnx/__pycache__/__init__.cpython-312.pyc,, +torch/onnx/__pycache__/_constants.cpython-312.pyc,, +torch/onnx/__pycache__/_flags.cpython-312.pyc,, +torch/onnx/__pycache__/errors.cpython-312.pyc,, +torch/onnx/__pycache__/operators.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_helper.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_opset10.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_opset11.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_opset12.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_opset13.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_opset14.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_opset15.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_opset16.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_opset17.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_opset18.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_opset19.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_opset20.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_opset7.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_opset8.cpython-312.pyc,, +torch/onnx/__pycache__/symbolic_opset9.cpython-312.pyc,, +torch/onnx/__pycache__/testing.cpython-312.pyc,, +torch/onnx/__pycache__/utils.cpython-312.pyc,, +torch/onnx/__pycache__/verification.cpython-312.pyc,, +torch/onnx/_constants.py,sha256=KsVyVjgGFLE_G3mr8-ilc3YY6_0zxbKHZsw1OVbQOUo,531 +torch/onnx/_flags.py,sha256=7gg9rPep-Oy_cuneXABiEItasVTVvsp5PJ7cfc_6KLA,1554 +torch/onnx/_internal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/onnx/_internal/__pycache__/__init__.cpython-312.pyc,, +torch/onnx/_internal/__pycache__/_lazy_import.cpython-312.pyc,, +torch/onnx/_internal/_lazy_import.py,sha256=RWu_Nk7U6sIybFCMEMuPG4YrJiZ0LX1tP56a7--61xo,1213 +torch/onnx/_internal/exporter/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/onnx/_internal/exporter/__pycache__/__init__.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_analysis.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_building.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_capture_strategies.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_compat.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_constants.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_core.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_decomp.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_dispatching.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_dynamic_shapes.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_errors.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_exportable_module.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_flags.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_fx_passes.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_input_observer.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_ir_passes.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_isolated.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_onnx_program.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_registration.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_reporting.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_schemas.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_tensors.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_testing.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_type_casting.cpython-312.pyc,, +torch/onnx/_internal/exporter/__pycache__/_verification.cpython-312.pyc,, +torch/onnx/_internal/exporter/_analysis.py,sha256=CFEY_DHJzQNR-8ym2WU1WommKcoLqLyjjdKdThnshGY,9899 +torch/onnx/_internal/exporter/_building.py,sha256=58-BTGMDL7iPECfcvae14p7PWaCEz8VJP3jMrw-lmHs,28459 +torch/onnx/_internal/exporter/_capture_strategies.py,sha256=qbYuNt-rQPVgy2jZab6iex6DDhJ51yn0AGquOOl9lUE,11187 +torch/onnx/_internal/exporter/_compat.py,sha256=4HBcn7Ifmd7OdvngRS3dMTSyYAsfrHnE0Dru5_D8FQA,7552 +torch/onnx/_internal/exporter/_constants.py,sha256=y8ST-ZGRhbGrA_d-oM2xapBMa0hnFcEgLbLxt8pcMn4,378 +torch/onnx/_internal/exporter/_core.py,sha256=Vv1qcYXq9boonPyu3lAMmoeMJgDa-wLiasi0RBfUb1c,73080 +torch/onnx/_internal/exporter/_decomp.py,sha256=mVFktC8pOoFyQnl6UvhpDbHlNZtSvB8Hg5jNcui6eFQ,2938 +torch/onnx/_internal/exporter/_dispatching.py,sha256=_4rGW0B6NRWiPEAGg4TgxvzSgW2BlVkqGizNPdynuI8,2070 +torch/onnx/_internal/exporter/_dynamic_shapes.py,sha256=djj0TF_hAucwvAXd1ZSCeJLFu8gFb567Z7viGQj6ADA,14431 +torch/onnx/_internal/exporter/_errors.py,sha256=VziOIvyap9A_UDRP41HkC_s0J-R13dbCrVLIusF-6A8,535 +torch/onnx/_internal/exporter/_exportable_module.py,sha256=ymWXCMLYKiMruQAF3duzJRArqpp4yH19zTUYKaWEOvc,6807 +torch/onnx/_internal/exporter/_flags.py,sha256=0vyPbWUoBb_BUpGJpR5JRKZJxlXfk312XsdrbZsD9JM,794 +torch/onnx/_internal/exporter/_fx_passes.py,sha256=RJDceCGcbBr_lGpVbQGuSReBRbOTkt7uatRNQtNr9w0,1919 +torch/onnx/_internal/exporter/_input_observer.py,sha256=4PFACZjk1DI4OuffIprMhehIw3SqtJ6pCIjpRakb4nI,52391 +torch/onnx/_internal/exporter/_ir_passes.py,sha256=9XFQqrx0mg9EQfzyMWaCS88zD8lBX0tTgKZjsGiMl3Q,6289 +torch/onnx/_internal/exporter/_isolated.py,sha256=j4Gm7lSEuhQtH34qATkVq0x_aH8Bmn89sGgGMwjwRog,1870 +torch/onnx/_internal/exporter/_onnx_program.py,sha256=iynL3xhJ9JXU5ZJr91GKSPpLGec6IXqHEAKbfgSMLEk,19606 +torch/onnx/_internal/exporter/_registration.py,sha256=8YF6j7PQOeUU4TYcNLQ39mOByMfdF5MLoprYdV-RAT0,12407 +torch/onnx/_internal/exporter/_reporting.py,sha256=J1jlbFLSeVONVV5ue_DO5pcfb-l9tREXxLyJRnNxGKA,7424 +torch/onnx/_internal/exporter/_schemas.py,sha256=mGvy0H7IgrHRJ4dOZv_yywXpAKJydeFJefteEc8hIug,12280 +torch/onnx/_internal/exporter/_tensors.py,sha256=qxJ6FpCQZgA0KOMr_7CvrxQD-88b52prQk9QQ6GeYyE,2567 +torch/onnx/_internal/exporter/_testing.py,sha256=vn4KD6-Cd7pD7NUVEWJv8M_dvCeCWobEucKpjvZQPVg,3993 +torch/onnx/_internal/exporter/_torchlib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/onnx/_internal/exporter/_torchlib/__pycache__/__init__.cpython-312.pyc,, +torch/onnx/_internal/exporter/_torchlib/__pycache__/_tensor_typing.cpython-312.pyc,, +torch/onnx/_internal/exporter/_torchlib/__pycache__/_torchlib_registry.cpython-312.pyc,, +torch/onnx/_internal/exporter/_torchlib/_tensor_typing.py,sha256=nn7mpHTtrzFOllIIuTDfiE0YpX3ino3LK-zpfSQ1QZs,1954 +torch/onnx/_internal/exporter/_torchlib/_torchlib_registry.py,sha256=BG8oUTNKK-FVAo_s2Re8g15oJo2m1QVcSF-MiqlBmig,2886 +torch/onnx/_internal/exporter/_torchlib/ops/__init__.py,sha256=bgyPtdiM9s1nE_1ZdR_6-0y0Tea9o0Qiyts2wWU7EM4,180 +torch/onnx/_internal/exporter/_torchlib/ops/__pycache__/__init__.cpython-312.pyc,, +torch/onnx/_internal/exporter/_torchlib/ops/__pycache__/core.cpython-312.pyc,, +torch/onnx/_internal/exporter/_torchlib/ops/__pycache__/hop.cpython-312.pyc,, +torch/onnx/_internal/exporter/_torchlib/ops/__pycache__/nn.cpython-312.pyc,, +torch/onnx/_internal/exporter/_torchlib/ops/__pycache__/symbolic.cpython-312.pyc,, +torch/onnx/_internal/exporter/_torchlib/ops/__pycache__/symops.cpython-312.pyc,, +torch/onnx/_internal/exporter/_torchlib/ops/core.py,sha256=415-QLOVvAUhteRvi-6C8gylMC-wboQaNFqYoBjvsuM,1561 +torch/onnx/_internal/exporter/_torchlib/ops/hop.py,sha256=umnwD9LvYT4YXcapTpDzW6guvVq2e3mwOWMROVdK7nM,12837 +torch/onnx/_internal/exporter/_torchlib/ops/nn.py,sha256=53YZa-8C4QRG0Kqxv_TEzzmlUkFGeZXxcOEes_AZ70I,14017 +torch/onnx/_internal/exporter/_torchlib/ops/symbolic.py,sha256=ZR470gARvhh1UMMzL3oH7PhaPp9qp7Em2UaEB3wTNgk,4773 +torch/onnx/_internal/exporter/_torchlib/ops/symops.py,sha256=neWmfiEd77VyV9JiwjyefVBJ3PL8a7JRVt3o8zpAKjw,1782 +torch/onnx/_internal/exporter/_type_casting.py,sha256=ZfJSaAagtIWGV_0BTDOnjOtnrZRwoS1f2rKuedkQMbw,1313 +torch/onnx/_internal/exporter/_verification.py,sha256=Vo3MCIcV0ALzSICc_PG5buKbG10HvKUdef1vwjX6HHc,12535 +torch/onnx/_internal/fx/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/onnx/_internal/fx/__pycache__/__init__.cpython-312.pyc,, +torch/onnx/_internal/fx/__pycache__/_pass.cpython-312.pyc,, +torch/onnx/_internal/fx/__pycache__/type_utils.cpython-312.pyc,, +torch/onnx/_internal/fx/_pass.py,sha256=ijrOE4Clp5xEKvTid1WJPDwa2QWqkC5FKMu_FOrZrj0,8638 +torch/onnx/_internal/fx/passes/__init__.py,sha256=mImXwcuJd6IfP3-3RkuLStx9i0ykJK8dhozuZNwRdpA,91 +torch/onnx/_internal/fx/passes/__pycache__/__init__.cpython-312.pyc,, +torch/onnx/_internal/fx/passes/__pycache__/type_promotion.cpython-312.pyc,, +torch/onnx/_internal/fx/passes/type_promotion.py,sha256=AeBlCaaRxjk010J9TJo9XLXyuaRdd2yEyzxafyjtpAM,64668 +torch/onnx/_internal/fx/type_utils.py,sha256=XblXgNj16vBEpGEd5Obl6D1XBuAnSeAFjfeFp0VtRbk,945 +torch/onnx/_internal/torchscript_exporter/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/onnx/_internal/torchscript_exporter/__pycache__/__init__.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/_experimental.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/_globals.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/_type_utils.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/jit_utils.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/onnx_proto_utils.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/registration.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_helper.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset10.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset11.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset12.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset13.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset14.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset15.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset16.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset17.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset18.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset19.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset20.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset7.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset8.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset9.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/utils.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/__pycache__/verification.cpython-312.pyc,, +torch/onnx/_internal/torchscript_exporter/_experimental.py,sha256=sNZuVCJZztlSpM8VxZmdXgd8bOcsQo8C_EqF7quG2Cs,968 +torch/onnx/_internal/torchscript_exporter/_globals.py,sha256=dEltGsC4MJTeVUCaAYm3-L6xpjaNPZkGBNwG7jfM47Q,2801 +torch/onnx/_internal/torchscript_exporter/_type_utils.py,sha256=6VNDSwV-gduyz9YOEyyDiszU0Om0AzLvt_hXmmuMNEY,14020 +torch/onnx/_internal/torchscript_exporter/jit_utils.py,sha256=ZOniUZHM-B_1wihJWhokcZkUi9dKBGKM--CcUzZmkMA,14165 +torch/onnx/_internal/torchscript_exporter/onnx_proto_utils.py,sha256=Iz_QXJoN8MUWTWswjK2BGinni2tzgTXkr3md3lZD6NA,9358 +torch/onnx/_internal/torchscript_exporter/registration.py,sha256=oHZfHRVQEB9bKa3tFa8sQ0Bt9GrjWha49GwTdtS-6OU,11135 +torch/onnx/_internal/torchscript_exporter/symbolic_helper.py,sha256=Bu_cSpsu-Mvh2fiIADkiJHI5Wmy0lOimIQrrTspgfGg,86589 +torch/onnx/_internal/torchscript_exporter/symbolic_opset10.py,sha256=pRej0viryGhxoDY6PbA_sgV2z6DXLsFBl_e8jrF4rHw,37594 +torch/onnx/_internal/torchscript_exporter/symbolic_opset11.py,sha256=HBp_2ACFYH2MIZ8zkzsuUBBfnA0KnAl2AgAnBZ7tPFA,53252 +torch/onnx/_internal/torchscript_exporter/symbolic_opset12.py,sha256=5W_QJD6V7MeCtiRLcN8QBmZT24JKWEuB32wJAOojoxM,15807 +torch/onnx/_internal/torchscript_exporter/symbolic_opset13.py,sha256=Be6Kphjedkm0-rAA_kVx2baxK7TPSkvqJvGc5lPhYh8,41510 +torch/onnx/_internal/torchscript_exporter/symbolic_opset14.py,sha256=AUeXVfoV8Lo2SeYdPR-62vyKTkwk6goUZV0vSw0KlfQ,10426 +torch/onnx/_internal/torchscript_exporter/symbolic_opset15.py,sha256=yUBs1fDhvIx7-aWghD1ZtBbYwlVODGJrb_Tk1HQPEFQ,2892 +torch/onnx/_internal/torchscript_exporter/symbolic_opset16.py,sha256=QRJIIAf0VwR4NseYTKn5K3TGNJ8sBNYsgdbQBfxG0oY,6456 +torch/onnx/_internal/torchscript_exporter/symbolic_opset17.py,sha256=F6OIC5ZH8c1MpNNRURiNwQyFuhwfq3CvEijVedgQybU,8356 +torch/onnx/_internal/torchscript_exporter/symbolic_opset18.py,sha256=nAbSdAcm2QnUj0yYK0nUs6RNjiSQuP_R85I79YDzlOQ,8247 +torch/onnx/_internal/torchscript_exporter/symbolic_opset19.py,sha256=mdWDL5ju6R87V0WlsPnwFidl5EwyPeOb4roJkXLW1fI,536 +torch/onnx/_internal/torchscript_exporter/symbolic_opset20.py,sha256=LUCfXezm0zhOyDiSHhuYJac_y9DoIgTtAzgIJ-UtkOw,2462 +torch/onnx/_internal/torchscript_exporter/symbolic_opset7.py,sha256=d71ZOvg4TYXfi9AP3F3YxtUrqrTXxkcXV6Qj0aSQAI0,2192 +torch/onnx/_internal/torchscript_exporter/symbolic_opset8.py,sha256=jR_c6xodWrKtmz8CaV_1zS4Ywhr-xG4DKBOzRajmETY,15081 +torch/onnx/_internal/torchscript_exporter/symbolic_opset9.py,sha256=2PQs5PiJJ_H99UEYjInDQhl9klx_HxaQPOJph9BOtEs,227169 +torch/onnx/_internal/torchscript_exporter/utils.py,sha256=SDp3jOXlo8tI5rSaOo7SDfjN5Ea24RPnzll7L-g0vb8,76827 +torch/onnx/_internal/torchscript_exporter/verification.py,sha256=ysbe_khOrCWnqkuWhuLA-mGwswtfZp2JYm7tSPuHbxQ,19156 +torch/onnx/errors.py,sha256=7Svwc5kOBcoGNz4d7rZ0Cdh217IkmlDADQZOeFL9flg,3478 +torch/onnx/operators.py,sha256=fS94DP2lYBZwI8qpxN6VWHWuTrvD7VWueC8eonqRbnE,1185 +torch/onnx/ops/__init__.py,sha256=8bbYuxV5wPoYWWyx_5t3ZEFw77nbzVHgzJYHgM3xGv8,20918 +torch/onnx/ops/__pycache__/__init__.cpython-312.pyc,, +torch/onnx/ops/__pycache__/_dtype_mappings.cpython-312.pyc,, +torch/onnx/ops/__pycache__/_impl.cpython-312.pyc,, +torch/onnx/ops/__pycache__/_symbolic_impl.cpython-312.pyc,, +torch/onnx/ops/_dtype_mappings.py,sha256=T2_Rwd7HR5CzErvrphymlsCk0kRZhauZdhZbi0JZb3Y,836 +torch/onnx/ops/_impl.py,sha256=LMioMCIyzBnzP5ks4VkrczesyQzuaeuEmZ9jkngDoac,20481 +torch/onnx/ops/_symbolic_impl.py,sha256=wYwVXb_z_mGblpguM37kf7r8UCywRwVCWhTD1xWsFO0,11483 +torch/onnx/symbolic_helper.py,sha256=Iv78MkbX5PdtLJ9WYAeraBoLudj6Nn2u40g9AvFSSVo,217 +torch/onnx/symbolic_opset10.py,sha256=w4N_coxfbK1_ZpQftOwScoSxOi-iFvVnKIz_VJwUaFg,320 +torch/onnx/symbolic_opset11.py,sha256=Sl-2ruAe2XLgyv7gxTFjdpt0iIwseKjAyFBQpVR9xkM,219 +torch/onnx/symbolic_opset12.py,sha256=uUs-nF9FY8nyfxhyVsijD6n03XJS_S2n3bMbQ6o16OM,219 +torch/onnx/symbolic_opset13.py,sha256=NN5xyRALUcCL0weS5q8KL0oj4OOdinHJI-cwBg24-Zs,219 +torch/onnx/symbolic_opset14.py,sha256=7MajKQZnH3YUIAthLtZvdSz8i13D_MmrDmyumXfqitE,219 +torch/onnx/symbolic_opset15.py,sha256=m1TjL42f8ZvFSHCI8aZpDiHCgyuAQLduxj4x4FBPf-k,219 +torch/onnx/symbolic_opset16.py,sha256=rKKml7c9NraCJMwp9QKZCM6Hc4ccUsrDmJSZYZOMa0w,219 +torch/onnx/symbolic_opset17.py,sha256=uxHbAq5XYollwzau1hEEHv0MCScjPsggYiastIeohsE,219 +torch/onnx/symbolic_opset18.py,sha256=iYq3REr7YPSEtQucYh3x-x4A-4UnVGrFBc0CHv21mWU,219 +torch/onnx/symbolic_opset19.py,sha256=A6b1EhlGoasPVXaCOGVZHAt03P_UK2gM7XtslHx4ZQk,219 +torch/onnx/symbolic_opset20.py,sha256=oTIzDI9e-l2OhfJCeaEWijNuOU7DLPO3jXnOyODU3MI,219 +torch/onnx/symbolic_opset7.py,sha256=CqQck0I-SWnzIME_Ju8aaTFRM1z88vg7J9O3ced_Hac,217 +torch/onnx/symbolic_opset8.py,sha256=xA9pQ8qC7MrUHa3jkHJyKnS9TWH07tU2WPvr8ob-ESs,217 +torch/onnx/symbolic_opset9.py,sha256=BBSZGfeslo9WnqpDEdGZZkmDbjGPiD0CHTigDLpFpyc,386 +torch/onnx/testing.py,sha256=QbAECaWoSos_a1XwM_KBh63qvQVajvlnMDHr0qUnNO4,219 +torch/onnx/utils.py,sha256=GKM_OFGWtdDQDKtI_OmrOsfgEXVRRC3Uu4ZC_7rrkS0,198 +torch/onnx/verification.py,sha256=L6GdYIC4gPAgZu4uXJmib7vG7u_1bkMMnXmee70zveU,343 +torch/optim/__init__.py,sha256=UlB34dwL0qALVbOfmW_z3A1W6jTivVap2iRZ3N1oh1c,2426 +torch/optim/__pycache__/__init__.cpython-312.pyc,, +torch/optim/__pycache__/_adafactor.cpython-312.pyc,, +torch/optim/__pycache__/_functional.cpython-312.pyc,, +torch/optim/__pycache__/_muon.cpython-312.pyc,, +torch/optim/__pycache__/_stateless.cpython-312.pyc,, +torch/optim/__pycache__/adadelta.cpython-312.pyc,, +torch/optim/__pycache__/adagrad.cpython-312.pyc,, +torch/optim/__pycache__/adam.cpython-312.pyc,, +torch/optim/__pycache__/adamax.cpython-312.pyc,, +torch/optim/__pycache__/adamw.cpython-312.pyc,, +torch/optim/__pycache__/asgd.cpython-312.pyc,, +torch/optim/__pycache__/lbfgs.cpython-312.pyc,, +torch/optim/__pycache__/lr_scheduler.cpython-312.pyc,, +torch/optim/__pycache__/nadam.cpython-312.pyc,, +torch/optim/__pycache__/optimizer.cpython-312.pyc,, +torch/optim/__pycache__/radam.cpython-312.pyc,, +torch/optim/__pycache__/rmsprop.cpython-312.pyc,, +torch/optim/__pycache__/rprop.cpython-312.pyc,, +torch/optim/__pycache__/sgd.cpython-312.pyc,, +torch/optim/__pycache__/sparse_adam.cpython-312.pyc,, +torch/optim/__pycache__/swa_utils.cpython-312.pyc,, +torch/optim/_adafactor.py,sha256=p0P7H1m03t5NV6CWB-qo4-NJg-teEMx6Kq-51sNi3oM,28555 +torch/optim/_functional.py,sha256=mY0hO0FIJLQjGAI-tal1BfgOGQ73c6PLmc4lNUnrHqg,3241 +torch/optim/_multi_tensor/__init__.py,sha256=IFaYRp7tJ_Iqqklj35TS27amowzvDlH14-9zwEgTNn4,1013 +torch/optim/_multi_tensor/__init__.pyi,sha256=Q4IMQ5dfkrDDq7ooUZubB4Okb7KHVhWpjx5HUF3f7hY,537 +torch/optim/_multi_tensor/__pycache__/__init__.cpython-312.pyc,, +torch/optim/_muon.py,sha256=wXq7uK9Mk10SWxicONPLrsKV8c_SMtJxK9t14TGEuXI,14991 +torch/optim/_stateless.py,sha256=kyh6zuAvYN3XsQucEg_tB6bi3fowlS7BTb38twksc-I,12742 +torch/optim/adadelta.py,sha256=Y-MnjYDvxsjwvtTABlVp2BjnxknxAjld6nggLBlzklc,16930 +torch/optim/adagrad.py,sha256=0fjX2OnVJqTM6iDRF36Q51Wf-kM5FzcxIWc9H9Izj-E,23018 +torch/optim/adam.py,sha256=b0qW57zNXiM6ZvhGw596naAVfPZXwiddKiaaeKa5CSE,40155 +torch/optim/adamax.py,sha256=V6envhHsN2g9VImDADWce17qTXRNQZ0XjAMGkMkr3fk,17566 +torch/optim/adamw.py,sha256=OcXqoE-DYyKFsRT9CT7rAAaGbkrfWa1QzCjeEuY6hFk,7382 +torch/optim/asgd.py,sha256=FCTvLou1GbuQQw7VX6dKwlSNFXTUijvVch-r2WIofho,16420 +torch/optim/lbfgs.py,sha256=n-sBZ0m9e3psAjN0WmgRxoZ-J6kyMT-qYqrhB8dG6ro,20588 +torch/optim/lr_scheduler.py,sha256=ht4ZRC846IF-4yg4U-9Dd1ZdO2uTanec5_X1mfExKEk,103296 +torch/optim/nadam.py,sha256=detK9J1Z6vbmuqloGCygazuJYx8rR-owCYuna56F9kA,26758 +torch/optim/optimizer.py,sha256=68JRHgoHsYu_ukT2Fmfdru5H8jzchWpDI02JAHAQ_oY,51788 +torch/optim/radam.py,sha256=s3awxMA5MAUP18s6iPNjaW97pIKATcfbUJecKrHzQ2s,24886 +torch/optim/rmsprop.py,sha256=myE89o8QK82NFlYo6vLDlSIN8lgW6h20S2Q2uuELRlg,20717 +torch/optim/rprop.py,sha256=3LFNjHZk0ax1LCcGoE_R_B_-x8G0YjGdseg81tc_g0I,17653 +torch/optim/sgd.py,sha256=5sZHJJzuQcmc0p2kyz_nTJTYmed1yflSMI_K_crkNyU,20342 +torch/optim/sparse_adam.py,sha256=qnWhz6g3ETvzk8WVcEedg_-bMFNQfPQHJt1s7bt6MFc,8047 +torch/optim/swa_utils.py,sha256=TeZ96OMqAUXBIsQAzZjguC7QJfJNavJD3Sl52T4CsM0,23156 +torch/overrides.py,sha256=hsGnVqxEfT4hjmZU50TuSAQsdJJbuL_W-4G2ieB5ZVk,110382 +torch/package/__init__.py,sha256=ZLLvoviHHErV-XQZagde2I4cuNDK49dFLRGUC5oyOFc,388 +torch/package/__pycache__/__init__.cpython-312.pyc,, +torch/package/__pycache__/_digraph.cpython-312.pyc,, +torch/package/__pycache__/_directory_reader.cpython-312.pyc,, +torch/package/__pycache__/_importlib.cpython-312.pyc,, +torch/package/__pycache__/_mangling.cpython-312.pyc,, +torch/package/__pycache__/_mock.cpython-312.pyc,, +torch/package/__pycache__/_package_pickler.cpython-312.pyc,, +torch/package/__pycache__/_package_unpickler.cpython-312.pyc,, +torch/package/__pycache__/_stdlib.cpython-312.pyc,, +torch/package/__pycache__/file_structure_representation.cpython-312.pyc,, +torch/package/__pycache__/find_file_dependencies.cpython-312.pyc,, +torch/package/__pycache__/glob_group.cpython-312.pyc,, +torch/package/__pycache__/importer.cpython-312.pyc,, +torch/package/__pycache__/package_exporter.cpython-312.pyc,, +torch/package/__pycache__/package_importer.cpython-312.pyc,, +torch/package/_digraph.py,sha256=2sWnLmmIPfocHeGiti8SGyfahL5EY6JQFtjfu9-KVR8,5629 +torch/package/_directory_reader.py,sha256=4CzVDaz_zvXlYrgPfIJe5PGxyBHpFhMBGNiJvOeGOLM,1915 +torch/package/_importlib.py,sha256=gK2NYf15YV-dhwV6BY1-ebFTz8g0G1Tc_Tvhh4XwJtM,2956 +torch/package/_mangling.py,sha256=ultKR57Zsk2oEnpwCYGA2XHyA3dBp406yjUxFgHcdCs,1948 +torch/package/_mock.py,sha256=n4L1d-hoa5XO7kyAlxbYMjeZWa2vwQ_-7Ih_dZfH0SA,2866 +torch/package/_package_pickler.py,sha256=aJu-wsZUxM7AFr1VUJI6qClABvKKjoVaKDzHRW8QNoA,5785 +torch/package/_package_unpickler.py,sha256=hBxGPJDOF1wWmGVAfvN4FMCmm1o1Qt4pDKPmCdSdH-k,992 +torch/package/_stdlib.py,sha256=ttgTOJID6PsBLAyeNQ_tMaNXVF7tNEWUcH2_GIwI7WA,552 +torch/package/analyze/__init__.py,sha256=RtjmM0jmYQwfuv9mQoKgZQZBij-GQ4cFcJX7_-aihDg,130 +torch/package/analyze/__pycache__/__init__.cpython-312.pyc,, +torch/package/analyze/__pycache__/find_first_use_of_broken_modules.cpython-312.pyc,, +torch/package/analyze/__pycache__/is_from_package.cpython-312.pyc,, +torch/package/analyze/__pycache__/trace_dependencies.cpython-312.pyc,, +torch/package/analyze/find_first_use_of_broken_modules.py,sha256=0nn7RnQBbM_OvsyNz7AWHR1IL95wMs768O8vdMD2s7s,1114 +torch/package/analyze/is_from_package.py,sha256=5RN5zZTnmZiMxadQGK3OVYl38Q37nYS92FDVXrpQVEw,404 +torch/package/analyze/trace_dependencies.py,sha256=XKXy1kpvyEmLTBT_Du32cWSyyJisuAZoDZxp9vp2zo0,2234 +torch/package/file_structure_representation.py,sha256=uJkvIJanCyW5QFFLGNWg5ICzo812ot_PuGeRGVnSmWE,4734 +torch/package/find_file_dependencies.py,sha256=-47nZhmmsTN92nmLp09KAmymnSzOAiXf5f65-umr_jc,3948 +torch/package/glob_group.py,sha256=z0vFv-xnZOIZKzhcEVnsMmm7aEUZepGPof_7hPJT9Xo,3657 +torch/package/importer.py,sha256=DlW8qeDebvpMOf_ED77XXWlbrtFQIvk-EeTpabZFdj8,10240 +torch/package/package_exporter.py,sha256=TJ8feGZ_aN_IbCYSzSHw-e2rD-WOzjZZPeZ2K5KSp1U,52019 +torch/package/package_importer.py,sha256=WpnAeDSpeMv93v2hvGZsFiHzjf3tqqAEQSQcXC7LNHY,32370 +torch/profiler/__init__.py,sha256=wkycjPawFAc2hKygHPFfcAfdkKKII5tR_Tp4GpGF0tw,1726 +torch/profiler/__pycache__/__init__.cpython-312.pyc,, +torch/profiler/__pycache__/_chrome_trace_export.cpython-312.pyc,, +torch/profiler/__pycache__/_memory_profiler.cpython-312.pyc,, +torch/profiler/__pycache__/_trace_validator.cpython-312.pyc,, +torch/profiler/__pycache__/_utils.cpython-312.pyc,, +torch/profiler/__pycache__/itt.cpython-312.pyc,, +torch/profiler/__pycache__/profiler.cpython-312.pyc,, +torch/profiler/__pycache__/python_tracer.cpython-312.pyc,, +torch/profiler/_chrome_trace_export.py,sha256=KwlCVuLkj1E7fR97_LgraZZEFA5TWrlIExusLkrDwK8,8354 +torch/profiler/_cupti/__init__.py,sha256=tYuSfk0gY6SjUneKBjucB4u0Vz7HqjrpmxtJpz8x09U,270 +torch/profiler/_cupti/__pycache__/__init__.cpython-312.pyc,, +torch/profiler/_cupti/__pycache__/_event_nodes.cpython-312.pyc,, +torch/profiler/_cupti/__pycache__/_graph_deps.cpython-312.pyc,, +torch/profiler/_cupti/__pycache__/_records_base.cpython-312.pyc,, +torch/profiler/_cupti/__pycache__/cupti_python.cpython-312.pyc,, +torch/profiler/_cupti/__pycache__/monitor.cpython-312.pyc,, +torch/profiler/_cupti/__pycache__/monitor_trace.cpython-312.pyc,, +torch/profiler/_cupti/__pycache__/pm_sampling.cpython-312.pyc,, +torch/profiler/_cupti/__pycache__/records.cpython-312.pyc,, +torch/profiler/_cupti/_event_nodes.py,sha256=C-jBez22q3muKpaHt9QVsmXSEE9IQnL8PNsKgcYEqwc,8315 +torch/profiler/_cupti/_graph_deps.py,sha256=r3LItbIKOeL-wo7fzya89QHVKgBkP4DOb_C1-8wxdE4,5367 +torch/profiler/_cupti/_records_base.py,sha256=YZjRHt3gAzFgBz91mMTiANe-AxI_IvhoPBq8RS55aSc,2084 +torch/profiler/_cupti/cupti_python.py,sha256=j5EvGhYg75NI-1_AYxBzPo-V94ZCyOpltmyL8q0xccM,31797 +torch/profiler/_cupti/monitor.py,sha256=YQJhjXyKYiw41Qf5nMlivw6QrG8XkKmDfex9eTaV0a0,79033 +torch/profiler/_cupti/monitor_trace.py,sha256=XCfapaxYn56AEMZNP2uhJMHiFiMsEXumgtunv0XgfU4,104928 +torch/profiler/_cupti/observers/__init__.py,sha256=hFfxcJxvtiiHRgexE9kyTH9fsnYeWmN7-9pizaYkHjk,341 +torch/profiler/_cupti/observers/__pycache__/__init__.cpython-312.pyc,, +torch/profiler/_cupti/observers/__pycache__/base.cpython-312.pyc,, +torch/profiler/_cupti/observers/__pycache__/node_timer.cpython-312.pyc,, +torch/profiler/_cupti/observers/__pycache__/observation_window.cpython-312.pyc,, +torch/profiler/_cupti/observers/__pycache__/profiler.cpython-312.pyc,, +torch/profiler/_cupti/observers/base.py,sha256=n10pDCGAB-Rr40Ty3YisnLut9Y3-iq-lbAoMYFlqKI4,18866 +torch/profiler/_cupti/observers/node_timer.py,sha256=cIfHtAqcpxY10h5Xyb1U_yvN9wKaUYvnUCsrm2dM1U0,14424 +torch/profiler/_cupti/observers/observation_window.py,sha256=hvmqYmuZVedeTW_ZCZZ6kUWhOmxcmAhV8TZWyIAk5Fg,6234 +torch/profiler/_cupti/observers/profiler.py,sha256=xgm0Txv-6RagDQGa4ikKsi0_ygyKBiAr05Px-LA_kr0,50444 +torch/profiler/_cupti/pm_sampling.py,sha256=WYCMhKsiVexS1GQwlE9FTLubV0ZoZG3_xcrjZBzh7KI,20067 +torch/profiler/_cupti/records.py,sha256=tbQu1JVHLt72QIT_ZV2yVoVFelccG1BnXDezIbQlZNk,5495 +torch/profiler/_memory_profiler.py,sha256=UnduSzQy1KPc05JgnBhAAY3Ef2Lz3ZaK0k60BkMvxEc,49563 +torch/profiler/_trace_validator.py,sha256=ViAik0nWJ6UKehuLNUEliDE9a406pudptAg2SphFX2w,11412 +torch/profiler/_utils.py,sha256=k288Qni1b2icIIaQHXgxdR6L3a_zjDj_1-ThKm7GC6Q,8509 +torch/profiler/itt.py,sha256=GwDQYUY-qkdGn6Yg5VuS52aih12iJWLrPxdE3EMEXeg,1830 +torch/profiler/profiler.py,sha256=SIKehqWihIC1xuNlKSBu_uOTqs5_vDFQIMu3ztK2tD4,71315 +torch/profiler/python_tracer.py,sha256=mY1c9wqNHjZPmbJCrxNzduQiXUz2FM3wqYLsPwsEhtI,543 +torch/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/quantization/__init__.py,sha256=qdViHYX73iqc5xiNB9pKD6Ybzp33Wa2Xjv8j0DDA1eA,2810 +torch/quantization/__pycache__/__init__.cpython-312.pyc,, +torch/quantization/__pycache__/_numeric_suite.cpython-312.pyc,, +torch/quantization/__pycache__/_numeric_suite_fx.cpython-312.pyc,, +torch/quantization/__pycache__/_quantized_conversions.cpython-312.pyc,, +torch/quantization/__pycache__/fake_quantize.cpython-312.pyc,, +torch/quantization/__pycache__/fuse_modules.cpython-312.pyc,, +torch/quantization/__pycache__/fuser_method_mappings.cpython-312.pyc,, +torch/quantization/__pycache__/observer.cpython-312.pyc,, +torch/quantization/__pycache__/qconfig.cpython-312.pyc,, +torch/quantization/__pycache__/quant_type.cpython-312.pyc,, +torch/quantization/__pycache__/quantization_mappings.cpython-312.pyc,, +torch/quantization/__pycache__/quantize.cpython-312.pyc,, +torch/quantization/__pycache__/quantize_fx.cpython-312.pyc,, +torch/quantization/__pycache__/quantize_jit.cpython-312.pyc,, +torch/quantization/__pycache__/stubs.cpython-312.pyc,, +torch/quantization/__pycache__/utils.cpython-312.pyc,, +torch/quantization/_numeric_suite.py,sha256=kGqWAUJhc0DKg9RjXhiKRx7dxfmX-M5Y1w9jAEnU0Z0,779 +torch/quantization/_numeric_suite_fx.py,sha256=LkEYZQLt_CRTe4d_9EAvCzpuKKHTmTjYoXLXcawjN-I,752 +torch/quantization/_quantized_conversions.py,sha256=fN9geCvl7_bB5mAS72Nr2T57LWfCmIZFTxZLP7cwc8Q,5203 +torch/quantization/fake_quantize.py,sha256=AZes9LhE_KB-0Q_nV0Qy5kSOY0N9cvv7NPEpdjTwBz4,1015 +torch/quantization/fuse_modules.py,sha256=qdHvwLDuYEu2zJaAKtztSbw157nYTS5rJLCKBbBLPRA,732 +torch/quantization/fuser_method_mappings.py,sha256=QT2XYwG6LRioeQPh0lrmZ2awt05ejXODVO3S1BFgu-I,512 +torch/quantization/fx/__init__.py,sha256=H5nvSncLr3GGfo7gXFANAc3gJ64hDmAXPj048dRKQyU,573 +torch/quantization/fx/__pycache__/__init__.cpython-312.pyc,, +torch/quantization/fx/__pycache__/_equalize.cpython-312.pyc,, +torch/quantization/fx/__pycache__/convert.cpython-312.pyc,, +torch/quantization/fx/__pycache__/fuse.cpython-312.pyc,, +torch/quantization/fx/__pycache__/fusion_patterns.cpython-312.pyc,, +torch/quantization/fx/__pycache__/graph_module.cpython-312.pyc,, +torch/quantization/fx/__pycache__/match_utils.cpython-312.pyc,, +torch/quantization/fx/__pycache__/pattern_utils.cpython-312.pyc,, +torch/quantization/fx/__pycache__/prepare.cpython-312.pyc,, +torch/quantization/fx/__pycache__/quantization_patterns.cpython-312.pyc,, +torch/quantization/fx/__pycache__/quantization_types.cpython-312.pyc,, +torch/quantization/fx/__pycache__/utils.cpython-312.pyc,, +torch/quantization/fx/_equalize.py,sha256=lqBIInk3Gq4t2kdsaO0vpkjpCXriv5WQAgCP2uKlbak,1251 +torch/quantization/fx/convert.py,sha256=hQUg5B8P8CByLc7JIHeBEm15VHyuxPWxv2zFgo5oYmc,387 +torch/quantization/fx/fuse.py,sha256=xKT6NKY-nOHbiUAhvd6UyFLOWaN7IzTXzQkQQRM1OCM,381 +torch/quantization/fx/fusion_patterns.py,sha256=qSu3LbPeOO8dbO14vvA-yHKvoflh8F4Ta6JLCYOfmxU,416 +torch/quantization/fx/graph_module.py,sha256=Q2bphJkn60j97Wvy_gAOol-sAx5VKavZujO5Z1ChBmg,574 +torch/quantization/fx/match_utils.py,sha256=qFqoYdkrjA4jB2Figx-06RzeiN3KGs5WYt68TRqRYKs,457 +torch/quantization/fx/pattern_utils.py,sha256=8YjiPNSE0n9A6pLrlsv92foYAx37EWl93C5tHbxKrUQ,1299 +torch/quantization/fx/prepare.py,sha256=k6hE4OfbcI8r-csnlRP9gd8E4Hbak6NIO-q4E2_TPTg,387 +torch/quantization/fx/quantization_patterns.py,sha256=42Mi20H8zdK1gZFtNu8STWy5aFk4w-Kc8BKAsztGZ0s,2067 +torch/quantization/fx/quantization_types.py,sha256=FC78rHJfePvTdJfTmXfKCBUXtz2mbF1SK7s3401zhZY,396 +torch/quantization/fx/utils.py,sha256=3KZFWzVZPxCpzxlNUxv3xigcpmYg2AmtaOyJfKtfuCM,724 +torch/quantization/observer.py,sha256=J8sHSdsC9i6OqY4_OpzrTOqeHS1fZF_VmN132CZQWsY,1079 +torch/quantization/qconfig.py,sha256=NT4W-h_HrXKX06TnuRxrvfnv5Kwho6Xa4vd7ESA7RHs,944 +torch/quantization/quant_type.py,sha256=wwPL8MSv-G6QV5LogvkL4xRJ28Ido0yA7kPzh2dsIo0,399 +torch/quantization/quantization_mappings.py,sha256=F4DwF6qNFg8h4xhKvp8nBGuLLr5VwNjNjRoSTWFebdI,1148 +torch/quantization/quantize.py,sha256=g8mA0kRJIO2z63PuUcawc9bovat-uVjeUxIKFwvLb-I,804 +torch/quantization/quantize_fx.py,sha256=hBC2pUobd9oeYUliLKlIYE2dQ-6BQvdxg2xTyvkFLa8,736 +torch/quantization/quantize_jit.py,sha256=JNw2_M1d6EITYzYrXlrAsUac_4tX-IDMuAO_7prxhk8,714 +torch/quantization/stubs.py,sha256=ukEM_vZ34I3UdBnhFPn5GFL713MwFlEysXUAfYGshnA,392 +torch/quantization/utils.py,sha256=kOpHHmJ602vEybccn81hVLOHwY0CQ2YdnG9n9kOVcQM,833 +torch/quasirandom.py,sha256=3yn8zdR1JAWHCoVdL4Jz41gZ-EE9PQM2R1e19C17TXI,7948 +torch/random.py,sha256=CyvWXI_fMk4A7Sxk57BspdX_lgUwAQVchjUsCzZo0L4,9835 +torch/return_types.py,sha256=n2BeQf08b5YJcfOkm6JSqVUPDcy5To831qwGVNWiFf8,1537 +torch/return_types.pyi,sha256=9evBEyB6S0JXb_tpr6CWWI-QoGEQQjkHFkBMH2AvYeo,17400 +torch/serialization.py,sha256=SiXn1aRNVc4leBZEUbPPu2W0vxvovbov17ngCNLPkCE,89496 +torch/share/cmake/ATen/ATenConfig.cmake,sha256=H5O_MhtSBME1FmwL6A7LpRbR8jaVC_LrLCNnbSg4fzw,285 +torch/share/cmake/Caffe2/Caffe2Config.cmake,sha256=ZBwtIFmTDVogh8BpCh3idXrSBSxE4U25PJqaSTdp3Jw,5111 +torch/share/cmake/Caffe2/Caffe2Targets-release.cmake,sha256=bCgCVneccoST57752FE1M8IxYnNkUekbFbgx0Uxr7eQ,1624 +torch/share/cmake/Caffe2/Caffe2Targets.cmake,sha256=e3YQpeIt4pSujMRI9NWhW92XvJaBshL5KST7VsfTI-U,6856 +torch/share/cmake/Caffe2/FindCUDAToolkit.cmake,sha256=kl99c2bqe1LwRcg7k8VkwqL99pQ9CF9vTwG-kfKIu84,38768 +torch/share/cmake/Caffe2/FindCUDSS.cmake,sha256=54i8T6FKzYP1KMtHTXaUhsuCuXHogM8SDadMAUNZT8I,2698 +torch/share/cmake/Caffe2/FindCUSPARSELT.cmake,sha256=cjNafMBEzBGv0kZAQqMxdpku0Vyf2Yrn3vJ_OVHxdUQ,3068 +torch/share/cmake/Caffe2/FindSYCLToolkit.cmake,sha256=9rwZhrNbV2J3mjnbWn6ypaize8Ibo4Eq_d-luqFTE7Y,6399 +torch/share/cmake/Caffe2/Modules_CUDA_fix/FindCUDA.cmake,sha256=uH9LCtcsv8VgeuFEyyMTugFUiILpcgM3oEnJZka4AB0,459 +torch/share/cmake/Caffe2/Modules_CUDA_fix/FindCUDNN.cmake,sha256=NKwIx_LRJ3uu9oJC9_apdlRooZ-uR_izK1_deByfEQo,3085 +torch/share/cmake/Caffe2/Modules_CUDA_fix/upstream/CMakeInitializeConfigs.cmake,sha256=v1O1FBKmJWk1h-Zbh8M6qVlP4OqVsmCcYD8zwdVfb6Q,1657 +torch/share/cmake/Caffe2/Modules_CUDA_fix/upstream/FindCUDA.cmake,sha256=vz7pTfsrZCUqr1wtAtEP7gkiTKex3dDaAK4AZLj2hRQ,86626 +torch/share/cmake/Caffe2/Modules_CUDA_fix/upstream/FindCUDA/make2cmake.cmake,sha256=_KLZxL3AhZehZKubThy4o2C_gEH5mm4h3kMpxLHgajU,3925 +torch/share/cmake/Caffe2/Modules_CUDA_fix/upstream/FindCUDA/parse_cubin.cmake,sha256=h3Ka8c-mmE2Majl0s8342faZWVPAaDbO1rM_4m--YzA,3439 +torch/share/cmake/Caffe2/Modules_CUDA_fix/upstream/FindCUDA/run_nvcc.cmake,sha256=xCYQQ4GWx5BsAWYZZEOo79e_Pu_pK7S_pWM-6XNS-Tw,11813 +torch/share/cmake/Caffe2/Modules_CUDA_fix/upstream/FindCUDA/select_compute_arch.cmake,sha256=jRe4wERzokXdKDKpbQYxHd8Ky6jiIM0hqNfWHBcQBug,11887 +torch/share/cmake/Caffe2/Modules_CUDA_fix/upstream/FindPackageMessage.cmake,sha256=ToKFxPt7HSmEA014cFkMZl79quM2gpF7tmcP8h1BuYs,1564 +torch/share/cmake/Caffe2/public/LoadHIP.cmake,sha256=2SCKsOy81pMZEniI6oV8hzEhsY8gStrLe0aJWEWLXcc,18348 +torch/share/cmake/Caffe2/public/cuda.cmake,sha256=nyvhP_qRP11_Fbn0-OuAxAvZrnlp9wUL5wCqplW9zLA,14368 +torch/share/cmake/Caffe2/public/gflags.cmake,sha256=YrTkm-nQX6N3mh3tpY9a-i1_s_lAlifW0V_UZdAHS-M,2620 +torch/share/cmake/Caffe2/public/glog.cmake,sha256=zy1mZaicXNUHxSG7eOZ4ZVnbgk5qN-IuG_-jXUi98nk,2320 +torch/share/cmake/Caffe2/public/mkl.cmake,sha256=y1E6axKvT-AvgfmJrVMptYDVJ5svt723jNuQYIJp_kg,1317 +torch/share/cmake/Caffe2/public/mkldnn.cmake,sha256=6hlrWK4R79BJcxYLzbj7cChstm0qzceH5GGcWSDHwSo,1078 +torch/share/cmake/Caffe2/public/protobuf.cmake,sha256=weW3OuHBIqIt0KpWRWzAnzSCu-AJ9naUfkjxcvaRl5c,4003 +torch/share/cmake/Caffe2/public/utils.cmake,sha256=6tGWsoCiIb2RoJGCocTKXdqzG6gyBZHuOZDi9X43GNI,23530 +torch/share/cmake/Caffe2/public/xpu.cmake,sha256=P9VoWeORu3IIwwM1QEA2dPY5athS9EZJUscc5LAzLR0,2429 +torch/share/cmake/Tensorpipe/TensorpipeTargets-release.cmake,sha256=2wEYgR1y0GLjOCaRaMwe5YHUtN_mzWY235XM_o8Gmd0,1311 +torch/share/cmake/Tensorpipe/TensorpipeTargets.cmake,sha256=RAXhwEsfxVyNly6dk9plaM7jp67a9A54b2RNaEuTY8U,4412 +torch/share/cmake/Torch/TorchConfig.cmake,sha256=MlJLZhGmDy-aCWDqXEwSd1rP7MNNMOhMjTmH0jPXlcE,4892 +torch/share/cmake/Torch/TorchConfigVersion.cmake,sha256=npsE6W9DwmAdYcTSvCp-VHkGCtygrkZ6V4X4ocR0rPo,367 +torch/signal/__init__.py,sha256=UvInN-gZ-pXXT9wvdSjrESHuSVNz5qEcnLMRzycbXiU,46 +torch/signal/__pycache__/__init__.cpython-312.pyc,, +torch/signal/windows/__init__.py,sha256=pqkf3lWIkwGpjDn_njgkrpqzYYCBpC25zEK7iD4FGaI,383 +torch/signal/windows/__pycache__/__init__.cpython-312.pyc,, +torch/signal/windows/__pycache__/windows.cpython-312.pyc,, +torch/signal/windows/windows.py,sha256=wkRs0rhnmkb1rdA-77Ow2tu-j1l9_wCSZkBcv07mHrU,22712 +torch/sparse/__init__.py,sha256=ZcnXraq2sdi-pgHlfJ5J8EMjpR5fyLrGI2O6ja2bDl4,27167 +torch/sparse/__pycache__/__init__.cpython-312.pyc,, +torch/sparse/__pycache__/_semi_structured_conversions.cpython-312.pyc,, +torch/sparse/__pycache__/_semi_structured_ops.cpython-312.pyc,, +torch/sparse/__pycache__/_triton_ops.cpython-312.pyc,, +torch/sparse/__pycache__/_triton_ops_meta.cpython-312.pyc,, +torch/sparse/__pycache__/semi_structured.cpython-312.pyc,, +torch/sparse/_semi_structured_conversions.py,sha256=wAqgnh44rGoe9cuSrhIscwdYkyeMCDVp5WPRU4xBiXc,14095 +torch/sparse/_semi_structured_ops.py,sha256=9zDwlsstAAPAVRxCXRq3SsEsHyHHbX8R-MBcYIAXrcQ,10605 +torch/sparse/_triton_ops.py,sha256=aaqGGUbTcIiyaWaDXi_UwXU75CeeshesIQi1YV-dlRs,89705 +torch/sparse/_triton_ops_meta.py,sha256=2CeKaMhsgsSS6R1yi5IiwtwJmDybhqyQLgXqTEhbYjk,501667 +torch/sparse/semi_structured.py,sha256=BakgZmt9ygjmpzO4bJSz5se9U1IEvtytp4o29BMFtjc,34551 +torch/special/__init__.py,sha256=ajWNLN63S-Ng779N9YkLVETcWty4LGA9UMLjfysAUAU,32034 +torch/special/__pycache__/__init__.cpython-312.pyc,, +torch/storage.py,sha256=v0nyzi16dO34EVhR-ia2jYEgF90TDgJYFVC8dcMWCys,52997 +torch/test/CppSignature_test,sha256=9zl6OGjQBZpZOkfSxXyCdrjkfnLTvzArpVrwaGgMaPk,670488 +torch/test/Dict_test,sha256=KHziLyLY6vn8490H-iqMBRnaYvS22lx8IlULcuYUKGY,948360 +torch/test/IListRef_test,sha256=jS_gYVPleVGiTt2A_3r9WLxqVYYzbDwIz8ZOuCMmZJw,759848 +torch/test/KernelFunction_test,sha256=mQVPI3Kq-07CBTRA66nfkPiz4oQvlvOPnugXDwbS9r4,863256 +torch/test/List_test,sha256=L9D-TqvPzzWUgRhAyjJ2iY9TMuST-WLQ7PygHEWiaf8,1463584 +torch/test/MaybeOwned_test,sha256=mNqnJvu_iT-ORTmHzqNj4oXWqkI8qWiKtyCZnqLvx2A,844448 +torch/test/StorageUtils_test,sha256=sDtHheR6f3D-uWqRoYQbZrrUGiElRiUvg77ZhB66KaA,671016 +torch/test/accelerator_graph_test,sha256=Bzmpemw2Hk0s2W-6iLXwidwGYkLkrYDGQ0ECxwge244,676432 +torch/test/apply_utils_test,sha256=XptgWYPj2ppk2eBMmxVjr6_TWCntrKdrJUmaJzF1PKw,763512 +torch/test/atest,sha256=LAMtntDcOtxvAgmnHEdqgUtTKfSu73nHDcFDsE7Cvs8,752120 +torch/test/backend_fallback_test,sha256=JchkURrho5cAeKZvM53yBip2nnuDxVHL2JLugiU3lEM,708528 +torch/test/basic,sha256=SAtp3Sxl4-lUYF8vUdypOzGk9peXLkT3A3udYrImu_U,800128 +torch/test/broadcast_test,sha256=wA3illaj2HuhmEBI-gwO54RHnG6pwR9EaUw4aRdA-Lk,695104 +torch/test/c10_AllocatorConfig_test,sha256=TcQKvebgb9bwKOWBG3fvGb20qVGGzWbD7lGzyHxMOVg,640160 +torch/test/c10_ArrayRef_test,sha256=eJ0MNYnNb9KLwhbgj-kslMGo54_yhUKzKeLDBwrfNi4,581032 +torch/test/c10_Bitset_test,sha256=x9nAUzLkQ3RT0N_WJTlXHDDytcP_HohJd1ivyoMECnc,626480 +torch/test/c10_CompileTimeFunctionPointer_test,sha256=LvtEXKYP4KkrJDGbi_kKkaGXZ6AcT6stOp7JEfPm1rQ,583784 +torch/test/c10_ConstexprCrc_test,sha256=tp_qhm2Zfhz5BvDt3AHTzzc8YKCxvw1DTFrX-0LC8zA,570056 +torch/test/c10_DeadlockDetection_test,sha256=mUYAJ5mhMfxnyYmcAtwktrwaZjEpsOaSpaBlGee_jJM,578064 +torch/test/c10_DeviceGuard_test,sha256=iwDJkVLEy7f32ffV76oILEGAewYxyBMeSI06YUudix0,636968 +torch/test/c10_Device_test,sha256=njPwRGPWGKXCbYszSWSaP5Kw9QwtIfCtDjnyb0oQlX4,613728 +torch/test/c10_DispatchKeySet_test,sha256=JtVBvAsikvXNeHoeRG3ZOLYfuf-V5ph-16m7kWtjaVg,692288 +torch/test/c10_Enumerate_test,sha256=gtVuaePTfK3tAM8pz4pfHdB_29afaE7sVTT29GWakes,673520 +torch/test/c10_Half_test,sha256=rIWiyFhQkuMV539xQunfjpmnCi40hdYXwhSY-ZL2GDE,593184 +torch/test/c10_InlineDeviceGuard_test,sha256=z9v7akfXSe3okZLAIuqlB2tSGx4p0Y9515F4qf4EUm0,642312 +torch/test/c10_InlineStreamGuard_test,sha256=jRqM_xs9VCrh1NC124gnfG6VCJJuHim80UqjPihOdYA,663160 +torch/test/c10_IntrusiveList_test,sha256=c4lUf_dmqj8ut1vC3WjVozUELrNmJHGF8K-iQ9iecU8,618928 +torch/test/c10_LeftRight_test,sha256=KYoSLIIF96613WXDMkVL6keun-O_6fS2Z8B6qCc8OUY,675744 +torch/test/c10_NetworkFlow_test,sha256=vMkg3ydiH3Fxmwct-z9KJpj4VSO8TV2Ocxi_ntFpAJI,622464 +torch/test/c10_Scalar_test,sha256=6HV1rWrQkIzIuaQFO7hBGWhsV8jy8ePY36ZR0xKHIHE,636112 +torch/test/c10_Semaphore_test,sha256=3NIAJf2xtWkliwH_q8TDcMqNiXK9ci44Uo9P0DjZ92s,577712 +torch/test/c10_SizesAndStrides_test,sha256=CL2ciVA2JPIsp_qFTZ1mN_ONvgXp22z3IeoZdb8uYjA,669192 +torch/test/c10_StreamGuard_test,sha256=syKAgYtTe3nOCGBhy-C3iQ2UtU1nET8DMEOZwFFPeuw,570048 +torch/test/c10_SymInt_test,sha256=52IRjbVH7HJ9iJ51nUvy6QKub-8e0Xh5BAYBf4HowNM,696096 +torch/test/c10_Synchronized_test,sha256=iaVPL64meYbczjZjghia0D9NGMo9cye1T9VqlyZqsxk,588808 +torch/test/c10_ThreadLocalDebugInfo_test,sha256=slCoDUuVE05aj6oRckHhh7uOCywvjMSheYxukkQgg60,648936 +torch/test/c10_ThreadLocal_test,sha256=099AWjK_hJ17WEufW4fQIe52B0Tw6EtSnPuMhaRM9s8,669744 +torch/test/c10_TypeIndex_test,sha256=4hGBv9t2tsogAZRKHVVeTJb2R1CrFI2qf-bZhx-rQJc,615600 +torch/test/c10_TypeSafeSignMath_test,sha256=kYJw4_1bsh0GvT2xh47QSA5_5-K5iBWrQkBC7XwJ5GQ,615616 +torch/test/c10_WaitCounter_test,sha256=2qWH4nmXv8pzybxcrXlePF0pkfRQ3EUEfEBoivnDFPQ,674608 +torch/test/c10_accumulate_test,sha256=XnOG6W8gCCCGM9nz_rCPyIx8ToV-XzbGGm6ZUVZPPOU,610096 +torch/test/c10_bfloat16_test,sha256=-zTWRM6oHagn5O6sX8GsytRQHoJH8vxajFoYfXc3exc,664448 +torch/test/c10_bit_cast_test,sha256=HLjjz3HaB9x0p_O1ccQtnAxAllzVubqhaZph__5bc_o,591176 +torch/test/c10_complex_math_test,sha256=ch2Z3967wBPGJBKvIZOJn0XA4qg3yhoggJAi9XiISfY,673000 +torch/test/c10_complex_test,sha256=c9QqtppLDMR_s0op_RdnymKyS_Kw7p1S2muyOBaMBp4,651288 +torch/test/c10_cow_test,sha256=g0F-L4j5T6QqGx0Q-E7nRXYXIsAshyDMWx0pUx9voJQ,855832 +torch/test/c10_error_test,sha256=Jskw9Ht8yzw_GxlYD5ZxG7N8WMAruyb-QdC9CWvHTn0,576264 +torch/test/c10_exception_test,sha256=BvONYw9WAKckE5HLkFo6epdY_riF8hcokqXw-t9S6JM,618160 +torch/test/c10_flags_test,sha256=f9ZwuaAuI5sRuwyOc3Kj6vMdE-hpIhVxyzhCwbpOg9c,589144 +torch/test/c10_generic_math_test,sha256=l5ibyRD7PlE1_1THf6_Q5XE_TuFGcQaD3X7z36V_POM,585048 +torch/test/c10_intrusive_ptr_benchmark,sha256=zo3TlKMpoCne52QQ5ynQEpSrnwyNs8Q4KoFOMMXI8NI,561000 +torch/test/c10_intrusive_ptr_test,sha256=zvaQRkP2Zy9aCvnPRvh9kLKoGGBUAcO9tAXGEdG7fts,2272256 +torch/test/c10_irange_test,sha256=qaMpvo5S8ZUk-i-LJtUU0I4p1M0P7jbAhr84bpkpRcQ,595504 +torch/test/c10_lazy_test,sha256=qEWrrsuXheWGUALmB9nIAc5yBAKwItmV_Tgb2drl8Zo,637304 +torch/test/c10_logging_test,sha256=knJ8ez8QGf3timjC4pAAR1CebR7RHm6SwGwqytIRn7A,684792 +torch/test/c10_nofatal_test,sha256=dZh_8ea7Y-amH9A1li7U4PowHQ3vGTzWDRx61Fb8STg,586680 +torch/test/c10_optional_test,sha256=NbwRO09QyaxKsL-oEBMHpZKt7aCIxQ4RceUvcBXU1Io,901696 +torch/test/c10_ordered_preserving_dict_test,sha256=iJTBv3WwsiBdVy4FB1M9IE0a2m_niVTK7VocRRZ_cbw,743504 +torch/test/c10_overflows_test,sha256=6GH0isvGLfR-O0HMA3bJGWWF_k3x82ffMvh7paQAuPk,611624 +torch/test/c10_registry_test,sha256=T-IWwk2-0wWY--ZGr4AP2XnEqspcVDrKnRjxTSZXfJc,633240 +torch/test/c10_safe_conv_test,sha256=QxJfMQUgweKaWOqrwx1cF1VYh7LbAoWDQJlnzD5ob7I,615472 +torch/test/c10_small_vector_test,sha256=_enrW2i5YksqqIK0jv-p9epq8r-2S1ulnKyIXUuVH7c,2106912 +torch/test/c10_ssize_test,sha256=51oNuinbtZeCq_3h9adHUA9JmQEkqM0re1JjFzc3QC8,606096 +torch/test/c10_string_util_test,sha256=YYns8rYfWJCnQUL7dXUgUVAuPmTfuVbPWJCvqssVtCU,674224 +torch/test/c10_string_view_test,sha256=HIYwYYgFFsARpFgjepS5co4SESj3ycbnbD8_5j6XQY0,570048 +torch/test/c10_tempfile_test,sha256=RehWYhAHQ34buJnxyul8sWVb0e0mv8IizyDhx_vBqvU,590880 +torch/test/c10_typeid_test,sha256=YEcEXwwGdtcxOT19Lip_0EcHkTYa0jN0Uc5OWl8dBog,655752 +torch/test/cpu_allocator_test,sha256=I3dwKO8pd1URng9VavRoL3eh-UfSmGsshOWyP1IwXuc,654576 +torch/test/cpu_generator_test,sha256=6ZyiEy97S1J91u_oScDIkauFudONgbGqhiT-WVG6NWk,750864 +torch/test/cpu_profiling_allocator_test,sha256=Xo9Ap549-pByvqixGBc3tTRmBDrjWASR7mt21URvALU,680464 +torch/test/cpu_rng_test,sha256=Jno_Ce4S7lsUnOeQxu2u5rsSDqnMXqh6majPB5QgitI,1250768 +torch/test/dlconvertor_test,sha256=Rj6UHBbl4xM5wNcCR7IciHJFpgQIUwa2tUoR2u9CtRs,663176 +torch/test/extension_backend_test,sha256=F4vJehYphtpya7YnTJKCn2WV6MM5jGfb-hLNuEmLlNc,734616 +torch/test/half_test,sha256=q1LHSnNUWwZzx5BS4-L3njvEVFUbpXwM5vGr285APms,710472 +torch/test/index_kernel_utils_test,sha256=hjB6ALXRn5nsjmf8LTtoxJHIONfxnBKHcWJxY9pQ9j8,666200 +torch/test/inline_container_test,sha256=_z5Y16OwJ4fJPBL7APN76f5XpK3HZe64tsvhDU2doLQ,847256 +torch/test/ivalue_test,sha256=AOv5XM4_Xa-HX9fVMmAsFc4QB4MAZ1tI8WNaaf1Xg4c,1182392 +torch/test/kernel_function_legacy_test,sha256=7v9XOfJB1UbInnnBXPHhILkP5V5yVbnz9d22bHwAcB0,1558320 +torch/test/kernel_function_test,sha256=BJqbjEd3mw0SryrXnz2zxr8-L96sNdbiucRb26Qd1Uw,1239008 +torch/test/kernel_lambda_legacy_test,sha256=muJURl7t0ykSelA6hN3s9GcsciOzgC9XIyAVICw3JT4,1742120 +torch/test/kernel_lambda_test,sha256=hcSa8_jQeRGjeUItJs_taYJmk7B2ndPDOIB7e8kRaVk,1407920 +torch/test/kernel_stackbased_test,sha256=gPnB-XWiGPDTqKjhI3MM-PhL_Zt_4E1VSkICk_5H70E,761952 +torch/test/lazy_tensor_test,sha256=rKDpqLzASNJctAePKG0nfHWVeAs4v_9jHPL3g6Vf8-4,645384 +torch/test/legacy_vmap_test,sha256=oQ1y4zYkQ19_5_0dl9aPItQuRj_sgdo6xsa60U_lPp0,910672 +torch/test/make_boxed_from_unboxed_functor_test,sha256=QwtTYO0QE1Lprw-oPjWNL6dEHwHuzITcHq1NJU_oVKU,1208280 +torch/test/math_kernel_test,sha256=LxYshsCRfIpTLOSKwGvGmoOMEriyaYWIDhYq8ZLYSZs,683456 +torch/test/memory_format_test,sha256=Yv8Y3NJqAtP7erCA3FK_KIPbO87ueD3Nz5CDe7g-Oto,679752 +torch/test/memory_overlapping_test,sha256=c-6Hp_LFkP1Yl4-FiuPGv83gTq3LPIHcDFlmuIUlDiw,686032 +torch/test/mobile_memory_cleanup,sha256=he0qjxoZA64hMqkHls_xIcAeXA0GtS6eXUuPWmQ2cJc,633296 +torch/test/native_test,sha256=Emhw_En8luleV3j3YVYsHZj_H5fgfWuc52UGOMl2sxU,711000 +torch/test/op_allowlist_test,sha256=O81L18g3norbpPZdXCQpJEHr4BiKChTLxV-ogDWw3l0,633296 +torch/test/op_registration_test,sha256=onMxRFEslL6W7xTuckihb6IoXMqWqgnI_LzKcbc-ziw,4869336 +torch/test/operator_name_test,sha256=Hl1mHgyjTs2zngQbcmckhJq6LYc1uNzhG666ctSQJHM,654592 +torch/test/operators_test,sha256=EfGgCxYs08cyoh9Ym8OXXMIqa02ay4WQffHn_BPUcI4,653216 +torch/test/packedtensoraccessor_test,sha256=mbeI9iEoNwiQDc5xru9O9c4hbLaMfZYUZUsNGxKjy0k,672592 +torch/test/pow_test,sha256=K9pSplkNaI7WWEj9u-OANSJ-gQlgObDEKmCUIqvm4ss,858000 +torch/test/quantized_test,sha256=i0p5usFwmO7mfFpywy-UEqrEEkzL4931ktehv3MN0TA,725632 +torch/test/reduce_ops_test,sha256=xB9ikg57EZU-SauIWNC7Zs7lvPyXd-kUwhQP22KQCQ8,644512 +torch/test/reportMemoryUsage_test,sha256=IU4pPKquSrD7fYSlnuJJ-mij4q8dEMEM3aCJ_y-oRGk,666944 +torch/test/scalar_tensor_test,sha256=Z0LQvPfJPRiv3L3Z5Wua997vy06ZUlqqIk0M0R-FzWg,714464 +torch/test/scalar_test,sha256=w3CZp6oMnmIc0HKzxbB2FLb_4PeQvQf-L_i_WbEUKts,723304 +torch/test/stride_properties_test,sha256=i_ahleakJFvc4B0eX_4ohbDFle2YnuYtaRqY1U62Bpk,672408 +torch/test/tensor_iterator_test,sha256=YKuFWjBoUqeuvV1rjfXTz4j6Mn_3p0dz_RoBYhVXKtc,1090928 +torch/test/test_parallel,sha256=E6giVJ33dVxju9V35B_gegmgwBCR9A6yB1wFN1lmL_8,710816 +torch/test/thread_init_test,sha256=KDyJEuAgqJhKNIlE_sKvZbSWkv4fngjB51nYo9vUI9c,650624 +torch/test/type_ptr_test,sha256=B0-YG5CYmMbUmL5YcaZWsmPbc0P7EAgmtqAmCv-Zwy8,710280 +torch/test/type_test,sha256=5XvJq1EPbdGzucTorEZiw_K8Wr96wJH8NXPWc2UvY4g,749368 +torch/test/undefined_tensor_test,sha256=2Xf86ZWre2M2pbx6MlfR5HTAiCVPjVMxzoZDnGpNhfo,677544 +torch/test/verify_api_visibility,sha256=roWP2I39ohx6Krhss4BcHd514Ws2vwhmey3Cc3p3gPI,639232 +torch/test/weakref_test,sha256=DLHQvi4K45494nBt9P30be-1L3FVTNLnJA4kHvY6WH4,664336 +torch/test/wrapdim_test,sha256=DJmZGVJPw2NDtaHCa5H1ZtXJoFWpGf89RZO2Q-N6hzI,663416 +torch/test/xla_tensor_test,sha256=dG4OzU_DOr6HCbOFAh6es4MhM-8IQGRxrMZzVxqrcj0,661352 +torch/testing/__init__.py,sha256=KWGXAtM1wGYjenz5lGf2H16r3-qI1ZmOVsHuxHn7S2k,219 +torch/testing/__pycache__/__init__.cpython-312.pyc,, +torch/testing/__pycache__/_comparison.cpython-312.pyc,, +torch/testing/__pycache__/_creation.cpython-312.pyc,, +torch/testing/__pycache__/_utils.cpython-312.pyc,, +torch/testing/_comparison.py,sha256=CU9IxUSOVBXabZhLL7biFsvgz95NCIjC8QjyVds78ME,69868 +torch/testing/_creation.py,sha256=7RGtqdNAvk6SCW5Ja5PztrwufzCO9yPGSBBoprD1yy0,12174 +torch/testing/_internal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/testing/_internal/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/__pycache__/autocast_test_lists.cpython-312.pyc,, +torch/testing/_internal/__pycache__/autograd_function_db.cpython-312.pyc,, +torch/testing/_internal/__pycache__/check_kernel_launches.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_cuda.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_device_type.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_dist_composable.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_distributed.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_dtype.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_fsdp.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_jit.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_methods_invocations.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_mkldnn.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_modules.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_mps.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_nn.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_ops_unbacked.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_optimizers.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_pruning.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_quantization.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_quantized.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_subclass.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_utils.cpython-312.pyc,, +torch/testing/_internal/__pycache__/common_xpu.cpython-312.pyc,, +torch/testing/_internal/__pycache__/composite_compliance.cpython-312.pyc,, +torch/testing/_internal/__pycache__/custom_op_db.cpython-312.pyc,, +torch/testing/_internal/__pycache__/custom_tensor.cpython-312.pyc,, +torch/testing/_internal/__pycache__/dist_utils.cpython-312.pyc,, +torch/testing/_internal/__pycache__/dynamo_pytree_test_utils.cpython-312.pyc,, +torch/testing/_internal/__pycache__/dynamo_test_failures.cpython-312.pyc,, +torch/testing/_internal/__pycache__/fake_config_module.cpython-312.pyc,, +torch/testing/_internal/__pycache__/fake_config_module2.cpython-312.pyc,, +torch/testing/_internal/__pycache__/fake_config_module3.cpython-312.pyc,, +torch/testing/_internal/__pycache__/hop_db.cpython-312.pyc,, +torch/testing/_internal/__pycache__/hypothesis_utils.cpython-312.pyc,, +torch/testing/_internal/__pycache__/inductor_utils.cpython-312.pyc,, +torch/testing/_internal/__pycache__/jit_metaprogramming_utils.cpython-312.pyc,, +torch/testing/_internal/__pycache__/jit_utils.cpython-312.pyc,, +torch/testing/_internal/__pycache__/logging_tensor.cpython-312.pyc,, +torch/testing/_internal/__pycache__/logging_utils.cpython-312.pyc,, +torch/testing/_internal/__pycache__/py312_intrinsics.cpython-312.pyc,, +torch/testing/_internal/__pycache__/quantization_torch_package_models.cpython-312.pyc,, +torch/testing/_internal/__pycache__/static_module.cpython-312.pyc,, +torch/testing/_internal/__pycache__/subclasses.cpython-312.pyc,, +torch/testing/_internal/__pycache__/torchbind_impls.cpython-312.pyc,, +torch/testing/_internal/__pycache__/triton_utils.cpython-312.pyc,, +torch/testing/_internal/__pycache__/two_tensor.cpython-312.pyc,, +torch/testing/_internal/autocast_test_lists.py,sha256=UebIEDySNOBGqMvy6_35gb-631DGLb-uMUnjF5CWNys,28483 +torch/testing/_internal/autograd_function_db.py,sha256=mR_aqHOk6Ib7aZXSW_Y32mfWe7e9iymYw0sJAchdAzY,19755 +torch/testing/_internal/check_kernel_launches.py,sha256=KDW-fjae41C_aetbWyQGeXsEBWpv0cQaM9S57AdbQPo,6027 +torch/testing/_internal/codegen/__init__.py,sha256=8QLhisbHub6VJl6egijnrOPKK5QNAe5FJhfcxEelj4Y,22 +torch/testing/_internal/codegen/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/common_cuda.py,sha256=BcOYeaBq4yM0e8vZzfOnQPAvKGDk3bXxRlMFlSP2tOk,27093 +torch/testing/_internal/common_device_type.py,sha256=k98zZBELA7zTWJuSuzBlgRh1_igV8drTPlcTXgAVyas,91414 +torch/testing/_internal/common_dist_composable.py,sha256=op7rWjCfz8jYmx5o-QfRj6cxPrvcsu0rEIFCHRg0wcA,3576 +torch/testing/_internal/common_distributed.py,sha256=5hgUxqXhPkHB-bq2kBD4wnmEoAV68j0nKtx9CwF-R4g,84840 +torch/testing/_internal/common_dtype.py,sha256=V--JXUiykeTgTbsZ74CZcpennVdI5mE_Utta6ex00ps,6958 +torch/testing/_internal/common_fsdp.py,sha256=HEO2hGU__mGttuMsnX-T_Sj6eEZnV9YZDXuGAMs0PfU,63845 +torch/testing/_internal/common_jit.py,sha256=3TEnvapmxqgf_O31FoBrIJgcGbRp_uERaDJyut39zaU,15823 +torch/testing/_internal/common_methods_invocations.py,sha256=qiT6UpT30DUXvGqT9X4OgxAEz0ddEMTgRCMLzmDRkq8,1322329 +torch/testing/_internal/common_mkldnn.py,sha256=b0E0qdrCqWWWhonniOmNFT7_aE8DwdDB12cqjuvwt4Y,3895 +torch/testing/_internal/common_modules.py,sha256=L-V7ULuSUeGVpf9zuzuCbm6J10_13dtNve3az2dNXd4,248562 +torch/testing/_internal/common_mps.py,sha256=giT6SrSYRrb2ZewSSkZWNPh8Ob9-QaCw3TOdLYVlsdk,35186 +torch/testing/_internal/common_nn.py,sha256=AQiuzbauaFTpAFtSh6VXbRP64af-niFcLxjXyPXfzDY,175156 +torch/testing/_internal/common_ops_unbacked.py,sha256=mdBTcp5chseu4CFg0IbkEQx5S68jjarj6mmwA-5qLEs,7830 +torch/testing/_internal/common_optimizers.py,sha256=tUREyzxSwvHS3zTDa2I-s7rx0SjOAPc6j5bTDHXL9Wg,84110 +torch/testing/_internal/common_pruning.py,sha256=Zx_h0L10PhVi4sOamQ1XdBxG-J2koKmXAsy7U47f6Rw,13653 +torch/testing/_internal/common_quantization.py,sha256=_iPf-qgqGB2XwBdYRtdJOtUJMbjFuvNJQwi8DIrR87g,118661 +torch/testing/_internal/common_quantized.py,sha256=Rhl64Cu7qj1BwPA9bSej4wkQVEpm5N40ST__QHMX6vc,26219 +torch/testing/_internal/common_subclass.py,sha256=8WrtpzEXKOjYG3utE05MihGyc2bXuEU2mHoCJ_ghayo,13614 +torch/testing/_internal/common_utils.py,sha256=fUWZ8SJ2W4SOUfeuS0vO9eEZYv0v_lLtyZqqN6-C8eU,277342 +torch/testing/_internal/common_xpu.py,sha256=6DfF6Qjedm8V8chcFiniExaMJkmGTgfYYrYc9i51pRQ,2294 +torch/testing/_internal/composite_compliance.py,sha256=QyoLKwh7grzb8MqdhxamA7X5Bvo_6YqFAnSAHWf1JXM,26584 +torch/testing/_internal/custom_op_db.py,sha256=nVCM6PzzEz2FvK2a21TvfcqQK36cHdg-uPs8ftq4lB4,20975 +torch/testing/_internal/custom_tensor.py,sha256=f1Yc5nNAanrdQ5gCflY6a-Vs10xZXWYRB8jd5fEKzO4,5337 +torch/testing/_internal/data/__init__.py,sha256=8QLhisbHub6VJl6egijnrOPKK5QNAe5FJhfcxEelj4Y,22 +torch/testing/_internal/data/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/data/__pycache__/network1.cpython-312.pyc,, +torch/testing/_internal/data/__pycache__/network2.cpython-312.pyc,, +torch/testing/_internal/data/network1.py,sha256=ksE5iUCq6Hhp8772pRhqpUna414huKdlzvh92oQgxTc,169 +torch/testing/_internal/data/network2.py,sha256=FlOrR6LuubeOhZHKURvkoWqIGHlvMNX2SyoZ22XPvfg,199 +torch/testing/_internal/dist_utils.py,sha256=k65UPsaoZz28fctTWTybm_KCAL5zJGFTCJ-3QJ5RDhM,7255 +torch/testing/_internal/distributed/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/testing/_internal/distributed/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/distributed/__pycache__/checkpoint_utils.cpython-312.pyc,, +torch/testing/_internal/distributed/__pycache__/common_state_dict.cpython-312.pyc,, +torch/testing/_internal/distributed/__pycache__/ddp_under_dist_autograd_test.cpython-312.pyc,, +torch/testing/_internal/distributed/__pycache__/distributed_test.cpython-312.pyc,, +torch/testing/_internal/distributed/__pycache__/distributed_utils.cpython-312.pyc,, +torch/testing/_internal/distributed/__pycache__/fake_pg.cpython-312.pyc,, +torch/testing/_internal/distributed/__pycache__/multi_threaded_pg.cpython-312.pyc,, +torch/testing/_internal/distributed/__pycache__/rpc_utils.cpython-312.pyc,, +torch/testing/_internal/distributed/_shard/__init__.py,sha256=mIQlHRV-d0Zr3TOwF0Vr4fBPuPk4uNR8rzKPy1EhlPw,27 +torch/testing/_internal/distributed/_shard/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/distributed/_shard/__pycache__/test_common.cpython-312.pyc,, +torch/testing/_internal/distributed/_shard/sharded_tensor/__init__.py,sha256=BOh9GMJ-2QEBeigtlQET1Px7Bte5QXwmNhYYtrqN68I,3568 +torch/testing/_internal/distributed/_shard/sharded_tensor/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/distributed/_shard/sharded_tensor/__pycache__/_test_ops_common.cpython-312.pyc,, +torch/testing/_internal/distributed/_shard/sharded_tensor/__pycache__/_test_st_common.cpython-312.pyc,, +torch/testing/_internal/distributed/_shard/sharded_tensor/_test_ops_common.py,sha256=WTswADrWG_o2-lThoIOrpUiqdkCN68YbuR9yuvvawhY,4259 +torch/testing/_internal/distributed/_shard/sharded_tensor/_test_st_common.py,sha256=pTaeuaGEgXJHa6RR42Zm39i5YnMkp5geZsVBzMLiqpo,1746 +torch/testing/_internal/distributed/_shard/test_common.py,sha256=5siz-NFPOqExt7qHDwk-Lx7j7RBFlfZQR94voBPZ12g,1243 +torch/testing/_internal/distributed/_tensor/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/testing/_internal/distributed/_tensor/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/distributed/_tensor/__pycache__/common_dtensor.cpython-312.pyc,, +torch/testing/_internal/distributed/_tensor/common_dtensor.py,sha256=qP1BMvF25-qWsLyq6eQBqe_zvJiWuN1REuGg-6dhcgc,55766 +torch/testing/_internal/distributed/checkpoint_utils.py,sha256=xxtwj393h3AM_1tT4CTCdB0qd_zyYyCc4xvALUjOFDc,6267 +torch/testing/_internal/distributed/common_state_dict.py,sha256=Yjw1f_RavLCRLcIKC43cbNB696SxgsWQK4ZpsReBZj4,6856 +torch/testing/_internal/distributed/ddp_under_dist_autograd_test.py,sha256=M8ihnSxZGmqXLy0cu1AI1-33XsTynsLtm2Z-hajQeI8,27054 +torch/testing/_internal/distributed/distributed_test.py,sha256=Wv5CgBY7m3CSlV3S8_KRfJFoUAeZqkpwIYHtsJb4nmA,462574 +torch/testing/_internal/distributed/distributed_utils.py,sha256=rZ606dkmJjUfgKsgyRMTYOZATiaXwryb6GRcsbQ3wdg,1932 +torch/testing/_internal/distributed/fake_pg.py,sha256=vRqlX6-b48Jpotyogj5ApuPkrvkbEHFWsdSwLG22kp0,1282 +torch/testing/_internal/distributed/multi_threaded_pg.py,sha256=aSYlD0BzRXvruRJcg4qc-jQroGJCf9e6aKnF_k7ZnZ8,22890 +torch/testing/_internal/distributed/nn/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/testing/_internal/distributed/nn/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/distributed/nn/api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/testing/_internal/distributed/nn/api/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/distributed/nn/api/__pycache__/remote_module_test.cpython-312.pyc,, +torch/testing/_internal/distributed/nn/api/remote_module_test.py,sha256=GohOmmJgmhgehHlcwU55daRtg1zl1NN447dORb_An9E,29751 +torch/testing/_internal/distributed/rpc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/testing/_internal/distributed/rpc/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/__pycache__/dist_autograd_test.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/__pycache__/dist_optimizer_test.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/__pycache__/faulty_agent_rpc_test.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/__pycache__/faulty_rpc_agent_test_fixture.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/__pycache__/rpc_agent_test_fixture.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/__pycache__/rpc_test.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/__pycache__/tensorpipe_rpc_agent_test_fixture.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/dist_autograd_test.py,sha256=dkOBD3hqsnAnbn8qOlse_Ll_1Mdqjtwb_wjKNbCR3YQ,107732 +torch/testing/_internal/distributed/rpc/dist_optimizer_test.py,sha256=HibDFt3xUTuOmm2mXOAnEzCctb48WKGzNPWZ-BRr-hk,10574 +torch/testing/_internal/distributed/rpc/examples/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/testing/_internal/distributed/rpc/examples/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/examples/__pycache__/parameter_server_test.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/examples/__pycache__/reinforcement_learning_rpc_test.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/examples/parameter_server_test.py,sha256=_sm9R6jjnAkl49tk_dOH9dRZIdDEmuAmOy4DUkMa9ck,4568 +torch/testing/_internal/distributed/rpc/examples/reinforcement_learning_rpc_test.py,sha256=JDYkhzz7ZsK-H-IVEPic9Sxu7ZLv0taf1REfAnWgTbM,9268 +torch/testing/_internal/distributed/rpc/faulty_agent_rpc_test.py,sha256=zcYRImWXoIg0qmVWpkPlTKA_t0neQPYyi9YXm8IdgTo,14239 +torch/testing/_internal/distributed/rpc/faulty_rpc_agent_test_fixture.py,sha256=ziVR9Z4tDhdG0omKEvGVfOXDN2I10eeXCcMYJ6G_vYk,2142 +torch/testing/_internal/distributed/rpc/jit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/testing/_internal/distributed/rpc/jit/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/jit/__pycache__/dist_autograd_test.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/jit/__pycache__/rpc_test.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/jit/__pycache__/rpc_test_faulty.cpython-312.pyc,, +torch/testing/_internal/distributed/rpc/jit/dist_autograd_test.py,sha256=71qFYAC8V4__WRgy7UVEX-KVuLNtxtPTUFCo8uuTTF8,4158 +torch/testing/_internal/distributed/rpc/jit/rpc_test.py,sha256=R8YGnkrzlknxwOhUmMNrn9W4tc-G7ADySv9j1-meVTg,46828 +torch/testing/_internal/distributed/rpc/jit/rpc_test_faulty.py,sha256=8TjJOzAvAlbE2qy3izpDBUHnUzog6r7jjEPciYoLs7U,7974 +torch/testing/_internal/distributed/rpc/rpc_agent_test_fixture.py,sha256=y5P27BCxk82IPTVOzov4-Ojr3_tykIOGlLlSEwWEv_w,1874 +torch/testing/_internal/distributed/rpc/rpc_test.py,sha256=nG8GCnSmbys8DsChl2L1SwKFmgW1_2M0sGMp1p2CvkA,226018 +torch/testing/_internal/distributed/rpc/tensorpipe_rpc_agent_test_fixture.py,sha256=6RTlsS0sKBh2iZqvLm_ieqIQpjSuwqlYc7qdgjb96YM,974 +torch/testing/_internal/distributed/rpc_utils.py,sha256=_ytL9c2DUzSMzTVyoOTKg8UJVlINNdy0R4mtFXBR0rI,6615 +torch/testing/_internal/dynamo_pytree_test_utils.py,sha256=5zPqhGQDcqd4Ynshj8cS_TVz_syUcPa_nKWDAKCQ0lY,1059 +torch/testing/_internal/dynamo_test_failures.py,sha256=RHMRhAL0qKlVfHftaisckwbED_660cYHzyxCP4ANHVI,5440 +torch/testing/_internal/fake_config_module.py,sha256=py4Y9FaDJ7vdrG2xgJGVkuySNFyN1fe_pXoSgKlJ3xw,1559 +torch/testing/_internal/fake_config_module2.py,sha256=gk8fSMjiMktUYrbdWi-Yvm4aH6TeOBa-7nnB5SDMZwQ,343 +torch/testing/_internal/fake_config_module3.py,sha256=z6yJU2RkB7XBD22EDgPgRo5VVtr-iDR-U0HLdmMF8JU,220 +torch/testing/_internal/generated/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/testing/_internal/generated/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/generated/__pycache__/annotated_fn_args.cpython-312.pyc,, +torch/testing/_internal/generated/annotated_fn_args.py,sha256=4BuOH_zkgZTtPBGD2ymAYjRK8kfA4Z15WiFTKhgr69A,529920 +torch/testing/_internal/hop_db.py,sha256=KAkkeOeY1UsrPzFXCKDw_9UX8KR9AcoiwS8_bEJXy0g,22848 +torch/testing/_internal/hypothesis_utils.py,sha256=A5S_B-yYVRjDtO4qRTc_biSOuKFqHFe1TYKJhuo20pU,15157 +torch/testing/_internal/inductor_utils.py,sha256=JI3OFEjE6FL7per3NNfhPEaziLjtKsk6qnc2c3uv1Ws,15561 +torch/testing/_internal/jit_metaprogramming_utils.py,sha256=q0ceOCpu7OyInO-cun0Gd_vpXmZZkYe9hdQVLG-16Vw,34129 +torch/testing/_internal/jit_utils.py,sha256=1PS6itD3xWo-IlbnCAyz_bkTiNm2Tz8iNPLLWYJvHFM,33962 +torch/testing/_internal/logging_tensor.py,sha256=kLuLlOecKtF8SDoOxF2A4AfqPliQIice6Wphapbk12I,6791 +torch/testing/_internal/logging_utils.py,sha256=Td5znZuPdpNiGbHNXJ-o0-EJNi4Me6VUWuSL2hosKgU,8937 +torch/testing/_internal/opinfo/__init__.py,sha256=6PWvlARagSjyrZW5xCOA5YGQjLqwaijc36TFX4UrU9g,116 +torch/testing/_internal/opinfo/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/opinfo/__pycache__/core.cpython-312.pyc,, +torch/testing/_internal/opinfo/__pycache__/refs.cpython-312.pyc,, +torch/testing/_internal/opinfo/__pycache__/utils.cpython-312.pyc,, +torch/testing/_internal/opinfo/core.py,sha256=b26OK1vfj3HFuBiFKarHP-roI0UJLBN_aXDY2zDevUo,129389 +torch/testing/_internal/opinfo/definitions/__init__.py,sha256=8IK85dB9S_tx3aiyuUwfSYLKgoGRaBmVnajBKn__Vqk,452 +torch/testing/_internal/opinfo/definitions/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/opinfo/definitions/__pycache__/_masked.cpython-312.pyc,, +torch/testing/_internal/opinfo/definitions/__pycache__/fft.cpython-312.pyc,, +torch/testing/_internal/opinfo/definitions/__pycache__/linalg.cpython-312.pyc,, +torch/testing/_internal/opinfo/definitions/__pycache__/nested.cpython-312.pyc,, +torch/testing/_internal/opinfo/definitions/__pycache__/signal.cpython-312.pyc,, +torch/testing/_internal/opinfo/definitions/__pycache__/sparse.cpython-312.pyc,, +torch/testing/_internal/opinfo/definitions/__pycache__/special.cpython-312.pyc,, +torch/testing/_internal/opinfo/definitions/_masked.py,sha256=hkYu9beFaFh5iAg4gz7vHraomvMdqR6LA_cIyCGhyic,53214 +torch/testing/_internal/opinfo/definitions/fft.py,sha256=-zSoSwaS_37vNXTq-0ATd6RQt6jlYoO_Hpv21KlWyQk,32332 +torch/testing/_internal/opinfo/definitions/linalg.py,sha256=4LGJBeIyrhRQHBbzFVUWGPktLQ-Fp0nFY5WMXhlfsPs,100986 +torch/testing/_internal/opinfo/definitions/nested.py,sha256=NBYahzMS7eMKqlQlDfK02tQEFzIERQYsr5wMt9zUPlw,60962 +torch/testing/_internal/opinfo/definitions/signal.py,sha256=LM2_KWXES706JWWxUyf0oPbuz75WaFZ_fpR_UM0AsCY,15351 +torch/testing/_internal/opinfo/definitions/sparse.py,sha256=GlQF0w9irnemeFfSlSnUcQV1im6-0hwxhcRO3Y9C0Ro,33962 +torch/testing/_internal/opinfo/definitions/special.py,sha256=lJz23NV6Blie3ahmnp3M74IRqjAVugAaHr6tRnmdRQw,38348 +torch/testing/_internal/opinfo/refs.py,sha256=8AK4TpjI2I_4RAirGNEEgUqdOFX3OTRKZzYRzL2FhF8,8601 +torch/testing/_internal/opinfo/utils.py,sha256=AdwLGoe6YCI-iMYJ5NH3OSh85MI6His1zo-sSiIqvn4,9045 +torch/testing/_internal/optests/__init__.py,sha256=o-8t0Cva860Tcw0Ig_-rBr6-9Uuc9bDRWRMG6FgKzbA,372 +torch/testing/_internal/optests/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/optests/__pycache__/aot_autograd.cpython-312.pyc,, +torch/testing/_internal/optests/__pycache__/autograd_registration.cpython-312.pyc,, +torch/testing/_internal/optests/__pycache__/fake_tensor.cpython-312.pyc,, +torch/testing/_internal/optests/__pycache__/generate_tests.cpython-312.pyc,, +torch/testing/_internal/optests/__pycache__/make_fx.cpython-312.pyc,, +torch/testing/_internal/optests/aot_autograd.py,sha256=Wc7O3ADpzSbQf7X82cMXue2vErgHwkuT8z60jAdkaIY,8185 +torch/testing/_internal/optests/autograd_registration.py,sha256=d1hcQqT58qY_re5xsDl7BL17EraIrvAHvcsTjvrKcQM,5850 +torch/testing/_internal/optests/fake_tensor.py,sha256=WuT0PGbogjTGPJeRYo2JiQYoTzj_iZET56L1zkv0W4w,257 +torch/testing/_internal/optests/generate_tests.py,sha256=CNbUqKeZbdtIQ57V6sPk0C6WHrBbn3CbkJy-RXVombs,32418 +torch/testing/_internal/optests/make_fx.py,sha256=cERDt-I8VgMfwqddFNkbnkWnBWPZZegU5Yo0ijAtF5E,3265 +torch/testing/_internal/py312_intrinsics.py,sha256=fYgzb7zJXmlxR7JP5sp9RyxwMo3L5XubgD8M7vagwfE,854 +torch/testing/_internal/quantization_torch_package_models.py,sha256=DnChjrnLG54TWRhINvfTxOFmNZt5WflDBJDpam4fj9w,951 +torch/testing/_internal/static_module.py,sha256=bwmblZ7N3UtKuO6UEJDUUJdqdhxxIpCwvmrJEESauOk,893 +torch/testing/_internal/subclasses.py,sha256=8zo_8ospVkQFG66o92R4So-doE1pwmMzUrQtQV5TBNo,2717 +torch/testing/_internal/test_module/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/testing/_internal/test_module/__pycache__/__init__.cpython-312.pyc,, +torch/testing/_internal/test_module/__pycache__/future_div.cpython-312.pyc,, +torch/testing/_internal/test_module/__pycache__/no_future_div.cpython-312.pyc,, +torch/testing/_internal/test_module/future_div.py,sha256=298hLJlLz2QCJ80OVQXQM6CgN71nbkFMNnkesgzSnY8,114 +torch/testing/_internal/test_module/no_future_div.py,sha256=sksxzWFUupRBbSThS69P366IwnWBNGJe9EqQx8m5EKM,145 +torch/testing/_internal/torchbind_impls.py,sha256=5CUDCO4nc_cOKdc6RPEFuck9Ik3l9MBj2gKjehhxMrA,5638 +torch/testing/_internal/triton_utils.py,sha256=G7b9klHc7V6cUhP5EGQds8c0OVgkzJjfxzEpu7pB8DU,34665 +torch/testing/_internal/two_tensor.py,sha256=OW6MrKArI4emVGfWA3OC6wVU8HAKDZlFyBkA33yiZso,4451 +torch/testing/_utils.py,sha256=qfU2CiPMoNiej2eD4hqMJDAxMT8tviWzxM0HJqxiQ9M,2519 +torch/torch_version.py,sha256=MheXhDr4r0O0mDO_Eaxz7vYLl0HRWr8hnQciPgx4QuI,2530 +torch/types.py,sha256=p9HIFrfGdCQDv7Ws3JwV-v-k1ogXEzrhudBV3zJfzWg,3642 +torch/utils/__init__.py,sha256=zMoIT_1VcmllcYuDNcUEfhrwT5iksaEIlf0mzinvnqM,3891 +torch/utils/__pycache__/__init__.cpython-312.pyc,, +torch/utils/__pycache__/_appending_byte_serializer.cpython-312.pyc,, +torch/utils/__pycache__/_config_module.cpython-312.pyc,, +torch/utils/__pycache__/_content_store.cpython-312.pyc,, +torch/utils/__pycache__/_contextlib.cpython-312.pyc,, +torch/utils/__pycache__/_cpp_embed_headers.cpython-312.pyc,, +torch/utils/__pycache__/_cpp_extension_versioner.cpython-312.pyc,, +torch/utils/__pycache__/_cuda_debug.cpython-312.pyc,, +torch/utils/__pycache__/_cxx_pytree.cpython-312.pyc,, +torch/utils/__pycache__/_device.cpython-312.pyc,, +torch/utils/__pycache__/_dtype_abbrs.cpython-312.pyc,, +torch/utils/__pycache__/_exposed_in.cpython-312.pyc,, +torch/utils/__pycache__/_filelock.cpython-312.pyc,, +torch/utils/__pycache__/_foreach_utils.cpython-312.pyc,, +torch/utils/__pycache__/_functools.cpython-312.pyc,, +torch/utils/__pycache__/_get_clean_triton.cpython-312.pyc,, +torch/utils/__pycache__/_helion.cpython-312.pyc,, +torch/utils/__pycache__/_import_utils.cpython-312.pyc,, +torch/utils/__pycache__/_indented_buffer.cpython-312.pyc,, +torch/utils/__pycache__/_inspect.cpython-312.pyc,, +torch/utils/__pycache__/_mode_utils.cpython-312.pyc,, +torch/utils/__pycache__/_ordered_set.cpython-312.pyc,, +torch/utils/__pycache__/_pallas.cpython-312.pyc,, +torch/utils/__pycache__/_python_dispatch.cpython-312.pyc,, +torch/utils/__pycache__/_pytree.cpython-312.pyc,, +torch/utils/__pycache__/_runtime_estimation.cpython-312.pyc,, +torch/utils/__pycache__/_stats.cpython-312.pyc,, +torch/utils/__pycache__/_thunk.cpython-312.pyc,, +torch/utils/__pycache__/_traceback.cpython-312.pyc,, +torch/utils/__pycache__/_triton.cpython-312.pyc,, +torch/utils/__pycache__/_typing_utils.cpython-312.pyc,, +torch/utils/__pycache__/_zip.cpython-312.pyc,, +torch/utils/__pycache__/backend_registration.cpython-312.pyc,, +torch/utils/__pycache__/bundled_inputs.cpython-312.pyc,, +torch/utils/__pycache__/checkpoint.cpython-312.pyc,, +torch/utils/__pycache__/collect_env.cpython-312.pyc,, +torch/utils/__pycache__/cpp_backtrace.cpython-312.pyc,, +torch/utils/__pycache__/cpp_extension.cpython-312.pyc,, +torch/utils/__pycache__/debug_log.cpython-312.pyc,, +torch/utils/__pycache__/deterministic.cpython-312.pyc,, +torch/utils/__pycache__/dlpack.cpython-312.pyc,, +torch/utils/__pycache__/file_baton.cpython-312.pyc,, +torch/utils/__pycache__/flop_counter.cpython-312.pyc,, +torch/utils/__pycache__/hooks.cpython-312.pyc,, +torch/utils/__pycache__/mkldnn.cpython-312.pyc,, +torch/utils/__pycache__/mobile_optimizer.cpython-312.pyc,, +torch/utils/__pycache__/model_zoo.cpython-312.pyc,, +torch/utils/__pycache__/module_tracker.cpython-312.pyc,, +torch/utils/__pycache__/show_pickle.cpython-312.pyc,, +torch/utils/__pycache__/throughput_benchmark.cpython-312.pyc,, +torch/utils/__pycache__/weak.cpython-312.pyc,, +torch/utils/_appending_byte_serializer.py,sha256=bs9USsaM-2edEomwNuRARE3qpqM6yMvauob3_EChH4s,4064 +torch/utils/_config_module.py,sha256=qHXqfH90zWD715fm_infNE3eE164J5BhOlHURr2YDtw,42750 +torch/utils/_config_typing.pyi,sha256=3g7bbnmNtmLQKbeP_St6LSdCtJm4T7YoUZTAq4Evmfk,1356 +torch/utils/_content_store.py,sha256=MqYoQquVsES1aqifvJBOwz1dQo5yGh54DxdpcEG92Qg,9332 +torch/utils/_contextlib.py,sha256=h93NIJluDu9Nkcc6cr-UOknUp2rMbwEXSxAaWZzGGKw,6388 +torch/utils/_cpp_embed_headers.py,sha256=JEXbg6pJrEuEyc6wTsDYVAJds2U66qZ15-Ik4W1tYdw,1758 +torch/utils/_cpp_extension_versioner.py,sha256=YHjYXX88iLDyZSuhNPJ3O4LS0LkNiqc2HMCW9GJmMSs,1946 +torch/utils/_cuda_debug.py,sha256=7aRnyeJdHZOtYrbTcYXt_pbHVaWcy11WCBNeCysdRiY,6698 +torch/utils/_cxx_pytree.py,sha256=wCeeJE-N6CNKrQZ8ne_J2M-LpbWFWvQNQI5zIPzUBWQ,39530 +torch/utils/_debug_mode/__init__.py,sha256=-UAxBbdHX814m-ssq_tP2v9y0zioXiN-d13nBqOnHEU,671 +torch/utils/_debug_mode/__pycache__/__init__.cpython-312.pyc,, +torch/utils/_debug_mode/__pycache__/_calls.cpython-312.pyc,, +torch/utils/_debug_mode/__pycache__/_mode.cpython-312.pyc,, +torch/utils/_debug_mode/__pycache__/_utils.cpython-312.pyc,, +torch/utils/_debug_mode/_calls.py,sha256=JCyIp6gzv5vGvysWfjldJIX6Zf6Lsvfl8c3gdbERM04,21442 +torch/utils/_debug_mode/_mode.py,sha256=OXayn4_kqMDYltxtyFctqrQ3gt4RGYn-6BaEW23SFII,43363 +torch/utils/_debug_mode/_utils.py,sha256=E_m_hrpdeQut3wr5Fb-cyuI9GJdABmSQkfwHfGR_WI8,8543 +torch/utils/_device.py,sha256=VxuBQa9VHC2KcLpQcXI_clqZpDELIKqwmEUQYsQgy1w,4491 +torch/utils/_dtype_abbrs.py,sha256=88Er-jv67Y-Ur2d33M3BD6CPnIIDj_RWZW0Kmv9uBYA,111 +torch/utils/_exposed_in.py,sha256=BdZbKFvTNdNkns_bTnsscKtH-o-OyJf5WOZS_mZlcXs,720 +torch/utils/_filelock.py,sha256=pzI0dRIiOSru8SdJ_IYI0d3FJqj2PZ0atCQoiGMgTTc,1530 +torch/utils/_foreach_utils.py,sha256=BWAnBP6D5TSRloDeNja7WfPM6Hz4fArfq7TEY_UmZUE,2409 +torch/utils/_functools.py,sha256=uMP2mGzc-LJZ_b0Pb_kf5UJo0ZlcMiBTyTewEcxOnw8,3334 +torch/utils/_get_clean_triton.py,sha256=bzOTGxXekoQ7U4i-NtC-vqZxLmihMxzFezhD1AM2Zjc,6963 +torch/utils/_helion.py,sha256=5J3AXusiOSlt9ALI8O1mtlx7XS9gJ9IHLS7-ZLf4Szo,303 +torch/utils/_import_utils.py,sha256=WKkO4UjWrjJ-Kw_eeveZUMVsvcDc43YB5IxXf2Icy2o,1174 +torch/utils/_indented_buffer.py,sha256=KdubheopZUypOzvFpqYmZ8TJIa_Ltf79UBJlZoj4bdg,7884 +torch/utils/_inspect.py,sha256=FFgrCL8pPZGhceoQ3rztoc3fSt4mqECQhjUykvERcgo,3073 +torch/utils/_mode_utils.py,sha256=sYjEYYBLwkP2g45Acigb32vqjNru3RgCJ-Efd1ol0A8,255 +torch/utils/_ordered_set.py,sha256=XCMvtn58N4_UbhnInekig5dDmwn2ZpltuuF3tIdFVxY,5619 +torch/utils/_pallas.py,sha256=BH-wTLYcKORzViEkPK692LUBuyneJnTaFQYMUchXOUo,3244 +torch/utils/_python_dispatch.py,sha256=1ZLo06q9iOZpafg3uDWDqHEClJTeOQVsuua4m6Zyggw,39579 +torch/utils/_pytree.py,sha256=jspBmRrbCYn9_CJrbwB3_3rdxL_5_-62qxZHLSTYi7E,78984 +torch/utils/_runtime_estimation.py,sha256=u2PLnC9ivVwQMctKelF6G8roY6rwA4Gpo-L32dK9Fyg,5827 +torch/utils/_stats.py,sha256=6tFYMMxr0QGrEZg9qI1Whq-t1uizO3fneCjmjaWyxDA,1041 +torch/utils/_strobelight/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/utils/_strobelight/__pycache__/__init__.cpython-312.pyc,, +torch/utils/_strobelight/__pycache__/cli_function_profiler.cpython-312.pyc,, +torch/utils/_strobelight/cli_function_profiler.py,sha256=g7ZjL4WWrNcd_KtjWQMAyQE41haPAJ0_0TGOZL-vULg,11360 +torch/utils/_sympy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/utils/_sympy/__pycache__/__init__.cpython-312.pyc,, +torch/utils/_sympy/__pycache__/functions.cpython-312.pyc,, +torch/utils/_sympy/__pycache__/interp.cpython-312.pyc,, +torch/utils/_sympy/__pycache__/numbers.cpython-312.pyc,, +torch/utils/_sympy/__pycache__/printers.cpython-312.pyc,, +torch/utils/_sympy/__pycache__/reference.cpython-312.pyc,, +torch/utils/_sympy/__pycache__/singleton_int.cpython-312.pyc,, +torch/utils/_sympy/__pycache__/solve.cpython-312.pyc,, +torch/utils/_sympy/__pycache__/symbol.cpython-312.pyc,, +torch/utils/_sympy/__pycache__/value_ranges.cpython-312.pyc,, +torch/utils/_sympy/functions.py,sha256=s9qoWBm7eWPwvpkeJ6HcztI6H1FyAbiN909xoCCzGFQ,58207 +torch/utils/_sympy/interp.py,sha256=L4PLAiodyr01Gi2hoAqzWe_uUoysSCraX_clLLEiawQ,7583 +torch/utils/_sympy/numbers.py,sha256=6Bhazno63kkUsojNYsObzoHZlobHVzB6DlbtSilGsN8,13342 +torch/utils/_sympy/printers.py,sha256=tmhaeDOQdyGmffogY0XWEudm84o6O4ts39BPf6dugMc,29145 +torch/utils/_sympy/reference.py,sha256=-P3EGzfSnOwhvwOmZ183PBI5MHVtnXrC61hQyaIwtd8,15046 +torch/utils/_sympy/singleton_int.py,sha256=a3KKGoy15wWGEF3fDLH60vpzLDqhfvvUoy_w_36gFf8,3478 +torch/utils/_sympy/solve.py,sha256=TKC7vPm_YgXV3IPW4YqfwK1GT7RyQVNdhgX7_ojYpKM,6377 +torch/utils/_sympy/symbol.py,sha256=KFviOMnEQ3oUjXSWN_2W-uxkGcnbYO9dszXtV8e6WX0,3723 +torch/utils/_sympy/value_ranges.py,sha256=UlxpmnQmdVPYU7aBGsOyJdxaftt5XFe2YIft_vfJ--U,44171 +torch/utils/_thunk.py,sha256=m5ck10KTsFbRFnH0qyv9_exIsG8ujIeLozlGLEhVC8Y,644 +torch/utils/_traceback.py,sha256=jLTvYPVDTxdTWs03vZGrDzTs_cVydzEPOt_-Nu664mc,10274 +torch/utils/_triton.py,sha256=T_UTc0diC4mVgHz-NxH3gm7wYlgc3n0Z55j_vHgfgQo,8043 +torch/utils/_typing_utils.py,sha256=ez9L9GrSvYbXCC5EQp81cRC1gkUNlUfyrR5I6WtK8VQ,2501 +torch/utils/_zip.py,sha256=eBoEuB5X-ARtblldfoAU5JN-lADeWkRE59wtuFKiFPc,2509 +torch/utils/backcompat/__init__.py,sha256=R3Sq5nrFTb96s7Cs-gNFpXfjDtyVahc-dbqXaEVqUnA,678 +torch/utils/backcompat/__pycache__/__init__.cpython-312.pyc,, +torch/utils/backend_registration.py,sha256=Be1Sg3PpR7dViNmB0dNz9is9Y2VYg44riUMMhchkNJY,23967 +torch/utils/benchmark/__init__.py,sha256=VMZoFTt8YGaScu3-5L1uWwMOED8FRYoEBAX37RFJ3c0,411 +torch/utils/benchmark/__pycache__/__init__.cpython-312.pyc,, +torch/utils/benchmark/examples/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/utils/benchmark/examples/__pycache__/__init__.cpython-312.pyc,, +torch/utils/benchmark/examples/__pycache__/compare.cpython-312.pyc,, +torch/utils/benchmark/examples/__pycache__/fuzzer.cpython-312.pyc,, +torch/utils/benchmark/examples/__pycache__/op_benchmark.cpython-312.pyc,, +torch/utils/benchmark/examples/__pycache__/simple_timeit.cpython-312.pyc,, +torch/utils/benchmark/examples/__pycache__/spectral_ops_fuzz_test.cpython-312.pyc,, +torch/utils/benchmark/examples/compare.py,sha256=vCmmcvWlXuf3hLDdZprpNCeV4Dv-7Qn6fTHH9Mqna24,2931 +torch/utils/benchmark/examples/fuzzer.py,sha256=5e2AwlYhk30tRXL4pmkiP4a6wtiHtgm-6A5m5DRM-zg,2658 +torch/utils/benchmark/examples/op_benchmark.py,sha256=4Q5GW6nw5PrltuItZ7L1GIQ_T0WAm-ROiGbNEZi_r8Y,4416 +torch/utils/benchmark/examples/simple_timeit.py,sha256=ioYkChBgAPHwz5gWqTfUFTCiqqk6CRud3Lob1tFe9uM,541 +torch/utils/benchmark/examples/spectral_ops_fuzz_test.py,sha256=Z4r34jAqH9rrDVdnZBj8yMaHigcYrQ2N6iS0O3JDlPU,4787 +torch/utils/benchmark/op_fuzzers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/utils/benchmark/op_fuzzers/__pycache__/__init__.cpython-312.pyc,, +torch/utils/benchmark/op_fuzzers/__pycache__/binary.cpython-312.pyc,, +torch/utils/benchmark/op_fuzzers/__pycache__/sparse_binary.cpython-312.pyc,, +torch/utils/benchmark/op_fuzzers/__pycache__/sparse_unary.cpython-312.pyc,, +torch/utils/benchmark/op_fuzzers/__pycache__/spectral.cpython-312.pyc,, +torch/utils/benchmark/op_fuzzers/__pycache__/unary.cpython-312.pyc,, +torch/utils/benchmark/op_fuzzers/binary.py,sha256=_A--hlOm0zcmwm3JoB_4ggFfNYAHzjFtlK7a3MHmkbI,4144 +torch/utils/benchmark/op_fuzzers/sparse_binary.py,sha256=FfyrCWiRHqxAzK27kp_gqP-zb4V31aT3N9drKRD8URU,4226 +torch/utils/benchmark/op_fuzzers/sparse_unary.py,sha256=TB__9Vo1Q9n6Awp07zMbGj_0nmUb54LCP3YyBRjU_7w,3491 +torch/utils/benchmark/op_fuzzers/spectral.py,sha256=u3ydR5HcQ3DwN0N0IIX9cYRiWDFm32sEw8nCkXa2djU,3632 +torch/utils/benchmark/op_fuzzers/unary.py,sha256=xvApHM3-2cP997UF5gotcTDfUas2tUUkzeUByLgKWV8,3154 +torch/utils/benchmark/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/utils/benchmark/utils/__pycache__/__init__.cpython-312.pyc,, +torch/utils/benchmark/utils/__pycache__/_stubs.cpython-312.pyc,, +torch/utils/benchmark/utils/__pycache__/common.cpython-312.pyc,, +torch/utils/benchmark/utils/__pycache__/compare.cpython-312.pyc,, +torch/utils/benchmark/utils/__pycache__/compile.cpython-312.pyc,, +torch/utils/benchmark/utils/__pycache__/cpp_jit.cpython-312.pyc,, +torch/utils/benchmark/utils/__pycache__/fuzzer.cpython-312.pyc,, +torch/utils/benchmark/utils/__pycache__/sparse_fuzzer.cpython-312.pyc,, +torch/utils/benchmark/utils/__pycache__/timer.cpython-312.pyc,, +torch/utils/benchmark/utils/_stubs.py,sha256=u29cftbrzC0fc9gq-6o78yApgPHNMwBKoXqY4QEiQ1M,1026 +torch/utils/benchmark/utils/common.py,sha256=YaRlKQnlqgRq573xCpHJhi_glOrxYstNta8zDEzaE1c,13760 +torch/utils/benchmark/utils/compare.py,sha256=vGP9rkUnbQLIXDPtZXDaia5pBet7Y8ACLaidC11wQIE,13473 +torch/utils/benchmark/utils/compile.py,sha256=_UWN1f6QW7c0lStHz-Z1j99kF7CIl5G2rqaia-8jQkY,7546 +torch/utils/benchmark/utils/cpp_jit.py,sha256=9sTV4KXXjMy6-8gVCLzFk2EFRq_Qfg39v2MS-KOw3Fc,6976 +torch/utils/benchmark/utils/fuzzer.py,sha256=I1fpGS3SxZ6evdJIYtAUCDLYuZnHe6N9Y9f_NuH01Ps,18778 +torch/utils/benchmark/utils/sparse_fuzzer.py,sha256=Zfd1iQ5zp1BhgGGYVWNo92FEVaao7j2Xlh0U-bH8TVs,5213 +torch/utils/benchmark/utils/timeit_template.cpp,sha256=Wzz-o6Yjgq3tkmUTxeRldQxrsETh48T2hwL8xbOkRSg,1009 +torch/utils/benchmark/utils/timer.py,sha256=zIUHMh1SRwVOfemHtcBGPViqJtD30IPn9piSNGQgSBM,20798 +torch/utils/benchmark/utils/valgrind_wrapper/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/utils/benchmark/utils/valgrind_wrapper/__pycache__/__init__.cpython-312.pyc,, +torch/utils/benchmark/utils/valgrind_wrapper/__pycache__/timer_interface.cpython-312.pyc,, +torch/utils/benchmark/utils/valgrind_wrapper/callgrind.h,sha256=wK1NVdRImF_4WVLlQrXkufunvE0qLr5dw50v86KPIo0,5744 +torch/utils/benchmark/utils/valgrind_wrapper/compat_bindings.cpp,sha256=ysuof0blt-4g76St1LUrdlZLiaCBKjwjwZXE0L4nI74,813 +torch/utils/benchmark/utils/valgrind_wrapper/timer_callgrind_template.cpp,sha256=ILVnffXHThuakEj3hzKv4usmt8rICdXpSTBeWKz7jU4,1676 +torch/utils/benchmark/utils/valgrind_wrapper/timer_interface.py,sha256=EaVk2xhDW1BQaHjlGIhCFoqYeTksXvFRyaqUGy-84Cc,37713 +torch/utils/benchmark/utils/valgrind_wrapper/valgrind.h,sha256=8MpV41sjwR0bIML04pxlLIjVuGhRtWdy1Kmtax4jFLI,422653 +torch/utils/bundled_inputs.py,sha256=zjjXWltxinJ99RM43MgmjedGJCClBHnNw_pJdHM71mI,22700 +torch/utils/checkpoint.py,sha256=hqPTzpKPXjApluWk8YXdR9Qr3-VQITVc7JDDclm4mIc,87894 +torch/utils/collect_env.py,sha256=Bf_D9qgNyNBNIbdQx5xv6AngcDLOMXRhq7v7vBotKE0,31107 +torch/utils/cpp_backtrace.py,sha256=GxSqoJwxCh9nbgm7EJS9KRJ0Mn5UwIwJUje-0vC4C-Y,483 +torch/utils/cpp_extension.py,sha256=kjDXmFp1y8y4qouJpJcyRZL6bDEMjl5HQIAe-we2DO8,147296 +torch/utils/data/__init__.py,sha256=atpjQDmxEyRtlfR9vDgGuJNxGQJq3H8g5drwHgkAK9A,1701 +torch/utils/data/__pycache__/__init__.cpython-312.pyc,, +torch/utils/data/__pycache__/backward_compatibility.cpython-312.pyc,, +torch/utils/data/__pycache__/dataloader.cpython-312.pyc,, +torch/utils/data/__pycache__/dataset.cpython-312.pyc,, +torch/utils/data/__pycache__/distributed.cpython-312.pyc,, +torch/utils/data/__pycache__/graph.cpython-312.pyc,, +torch/utils/data/__pycache__/graph_settings.cpython-312.pyc,, +torch/utils/data/__pycache__/sampler.cpython-312.pyc,, +torch/utils/data/_utils/__init__.py,sha256=WljpZRMdlzAaBffADbfPX_QDkfqM9oOWU9Yc33MRmAc,1607 +torch/utils/data/_utils/__pycache__/__init__.cpython-312.pyc,, +torch/utils/data/_utils/__pycache__/collate.cpython-312.pyc,, +torch/utils/data/_utils/__pycache__/fetch.cpython-312.pyc,, +torch/utils/data/_utils/__pycache__/pin_memory.cpython-312.pyc,, +torch/utils/data/_utils/__pycache__/signal_handling.cpython-312.pyc,, +torch/utils/data/_utils/__pycache__/worker.cpython-312.pyc,, +torch/utils/data/_utils/collate.py,sha256=SniScSuUrKj3jaY9MBf3ekUMxWMZkSlnZxWVhJ1aJfs,15936 +torch/utils/data/_utils/fetch.py,sha256=3F1nYcG5DGCtTDd_LhHLnYOC4pzjz0w8BTkJiUy9E7U,2010 +torch/utils/data/_utils/pin_memory.py,sha256=udNbbwHbVm_kyFFws_4v-8x3LhTwLMu4iiaAINMK8IU,4142 +torch/utils/data/_utils/signal_handling.py,sha256=IPFUW7-PIERaiZcfyo-39E_ZM39apsDfM2zxf4JGV54,3264 +torch/utils/data/_utils/worker.py,sha256=mkpHK9DAe2irfiidgcEBYYsA5e1d-F3mBRsn4WlvUX4,14911 +torch/utils/data/backward_compatibility.py,sha256=hEdTcktD0OuPmwt2eK_F4UkslR-n6D7wd14VSfG1DI4,317 +torch/utils/data/dataloader.py,sha256=eT-OY4_pU7VREbVMbv4AekTMV6vwMbMQX2pIfsZm1Yo,81408 +torch/utils/data/datapipes/__init__.py,sha256=OIYy5fRjiWdLc8SRrug0pOjrXouG0I-f2G8QQB0ynto,88 +torch/utils/data/datapipes/__pycache__/__init__.cpython-312.pyc,, +torch/utils/data/datapipes/__pycache__/_decorator.cpython-312.pyc,, +torch/utils/data/datapipes/__pycache__/_hook_iterator.cpython-312.pyc,, +torch/utils/data/datapipes/__pycache__/_typing.cpython-312.pyc,, +torch/utils/data/datapipes/__pycache__/datapipe.cpython-312.pyc,, +torch/utils/data/datapipes/__pycache__/gen_pyi.cpython-312.pyc,, +torch/utils/data/datapipes/_decorator.py,sha256=XJBHRPD9D49OaMjLzvHcaPEigmeAsdVhi7JjIY3C4DI,7758 +torch/utils/data/datapipes/_hook_iterator.py,sha256=8ZheHHXboo_xA34toGOQVROD6kVS5GJ2xc_jYURv7AY,11973 +torch/utils/data/datapipes/_typing.py,sha256=BXmRFFZ05--BLRJpD-e0ZriBZ8MpAM-zgJXl1rF0xNQ,16294 +torch/utils/data/datapipes/dataframe/__init__.py,sha256=j6gnc1vHYL9elliHkQsCRh9vaKbFRwHa0oMj6AIU2SY,378 +torch/utils/data/datapipes/dataframe/__pycache__/__init__.cpython-312.pyc,, +torch/utils/data/datapipes/dataframe/__pycache__/dataframe_wrapper.cpython-312.pyc,, +torch/utils/data/datapipes/dataframe/__pycache__/dataframes.cpython-312.pyc,, +torch/utils/data/datapipes/dataframe/__pycache__/datapipes.cpython-312.pyc,, +torch/utils/data/datapipes/dataframe/__pycache__/structures.cpython-312.pyc,, +torch/utils/data/datapipes/dataframe/dataframe_wrapper.py,sha256=9_V6cyBVauL0RpEehdWMCroAn1TGqKcM-M7ggGG7spg,3288 +torch/utils/data/datapipes/dataframe/dataframes.py,sha256=WdqoDNSjPnWV1RohBLKf9opZtCBSpw9Cp20_9XDMPDw,14034 +torch/utils/data/datapipes/dataframe/datapipes.py,sha256=yga6OgqN06IdQDPuCYd8T4tr-IzuyMttwYiIkZdM7t0,4653 +torch/utils/data/datapipes/dataframe/structures.py,sha256=7NKwwvZI2CtjpjvA1eJmyFQcbet7cYXdaxSMTFPZdx0,662 +torch/utils/data/datapipes/datapipe.py,sha256=VVX5I_Ulqt3NYtUsPNNROFNalRsflL1zVu8XjIhXE9g,17268 +torch/utils/data/datapipes/datapipe.pyi,sha256=5sTKh4wGFZ0OevMM_n5_K7EQvVpUTadF-ym_CxKlr7g,32732 +torch/utils/data/datapipes/gen_pyi.py,sha256=FR1brWWZ7IfnbsUblKApGwseZ51eORLfooAsf7lxEFE,11798 +torch/utils/data/datapipes/iter/__init__.py,sha256=Mh3NOCQIx3v7WrLqstLcFBuLDz4GRM-cSaBf-kJ6uFY,1862 +torch/utils/data/datapipes/iter/__pycache__/__init__.cpython-312.pyc,, +torch/utils/data/datapipes/iter/__pycache__/callable.cpython-312.pyc,, +torch/utils/data/datapipes/iter/__pycache__/combinatorics.cpython-312.pyc,, +torch/utils/data/datapipes/iter/__pycache__/combining.cpython-312.pyc,, +torch/utils/data/datapipes/iter/__pycache__/filelister.cpython-312.pyc,, +torch/utils/data/datapipes/iter/__pycache__/fileopener.cpython-312.pyc,, +torch/utils/data/datapipes/iter/__pycache__/grouping.cpython-312.pyc,, +torch/utils/data/datapipes/iter/__pycache__/routeddecoder.cpython-312.pyc,, +torch/utils/data/datapipes/iter/__pycache__/selecting.cpython-312.pyc,, +torch/utils/data/datapipes/iter/__pycache__/sharding.cpython-312.pyc,, +torch/utils/data/datapipes/iter/__pycache__/streamreader.cpython-312.pyc,, +torch/utils/data/datapipes/iter/__pycache__/utils.cpython-312.pyc,, +torch/utils/data/datapipes/iter/callable.py,sha256=vGa_hics1TsiXLsCkFS6gQFlC8mj8E_hA8UMRNh9j8c,9114 +torch/utils/data/datapipes/iter/combinatorics.py,sha256=ZmBXzNg1aVZFFoc_Gib_SkVyNnBzFtPNzRaZEyLB7l0,6557 +torch/utils/data/datapipes/iter/combining.py,sha256=8NPrtiSxhMAPQaOICKyWpQOtKoE73dKcYM1V2cqYRmw,28123 +torch/utils/data/datapipes/iter/filelister.py,sha256=pd59x2Ls-g1SpKBm4T5hgln0LHSqCVO8L82rfNVI-VY,2554 +torch/utils/data/datapipes/iter/fileopener.py,sha256=Qz0RAtlb8o2A9-YIMGcRVU2T6RztItmNCuqcGcvPQeA,2889 +torch/utils/data/datapipes/iter/grouping.py,sha256=Cuude_hvJ3KXROh4nZxqkHbIiFfX9zTFGZVq4i_Su5M,12391 +torch/utils/data/datapipes/iter/routeddecoder.py,sha256=AvSxF3p0yx5_6tT6dVkmS1qxwI19s98oEJW2E4Dq0h0,2732 +torch/utils/data/datapipes/iter/selecting.py,sha256=LXpA0_L7TlTGkc5FlZpdzkxEaKqLUAEDoDFnAW3y4Ro,3308 +torch/utils/data/datapipes/iter/sharding.py,sha256=MRUQ2z-E4kn5cezM8PEHBGDu6y320a0IDyhiHp-pIJg,3657 +torch/utils/data/datapipes/iter/streamreader.py,sha256=TWVLV5IUepvqMWcNkEo3cBNbjbNYecXoXRpJ9GKfRGU,1537 +torch/utils/data/datapipes/iter/utils.py,sha256=y4CTzQ6oasBdi4xihoTYopUZ8_4P5eVoOCfk6s_aMSM,2109 +torch/utils/data/datapipes/map/__init__.py,sha256=6weaVqSBgL8DhjqKLXA2mpYjkh8djBYGEl8zwP4RXcY,714 +torch/utils/data/datapipes/map/__pycache__/__init__.cpython-312.pyc,, +torch/utils/data/datapipes/map/__pycache__/callable.cpython-312.pyc,, +torch/utils/data/datapipes/map/__pycache__/combinatorics.cpython-312.pyc,, +torch/utils/data/datapipes/map/__pycache__/combining.cpython-312.pyc,, +torch/utils/data/datapipes/map/__pycache__/grouping.cpython-312.pyc,, +torch/utils/data/datapipes/map/__pycache__/utils.cpython-312.pyc,, +torch/utils/data/datapipes/map/callable.py,sha256=lUC_SHHytKC2yJVi60rQdwxwrJGtxwoRCOkxIYio0k8,1933 +torch/utils/data/datapipes/map/combinatorics.py,sha256=aMSYeaKto3cLhCiCAkYd-xDkV87wqjVS2Dnf8g8m4Gc,4266 +torch/utils/data/datapipes/map/combining.py,sha256=DzasRoKgUt4v-efKM4eoaKJguy8ZgdoLozB7MkZ_Opk,3990 +torch/utils/data/datapipes/map/grouping.py,sha256=k7x6DBhQct1D869iIs7Ej3bzyzALO6mV-RsIl2ore2w,2531 +torch/utils/data/datapipes/map/utils.py,sha256=5oq8xhZHdJjrswR2Zzgef32cdSTMrgvvfrSC8f8EKLo,1813 +torch/utils/data/datapipes/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/utils/data/datapipes/utils/__pycache__/__init__.cpython-312.pyc,, +torch/utils/data/datapipes/utils/__pycache__/common.cpython-312.pyc,, +torch/utils/data/datapipes/utils/__pycache__/decoder.cpython-312.pyc,, +torch/utils/data/datapipes/utils/__pycache__/snapshot.cpython-312.pyc,, +torch/utils/data/datapipes/utils/common.py,sha256=1jAYaiULKbyWeRXBBnQPQg0xcN-WSBBLLgLwMWgOrKs,13856 +torch/utils/data/datapipes/utils/decoder.py,sha256=BOfLfpyctXU8jDKKpvm0_tSOoXTpGdWfv_4iHwrbEH0,12121 +torch/utils/data/datapipes/utils/snapshot.py,sha256=tk8G2YDUdmEjIOMlLxuqOScYD3bxFyHUmyt_rvZA3Ck,3145 +torch/utils/data/dataset.py,sha256=l8RbrZHABlXmjI_HOYJgRJFSW2Ng4CXEc3gZzbf1h5c,20953 +torch/utils/data/distributed.py,sha256=lYZvlTxNcfW5ysXW2vvqZBwU3nYMymmi3d45_3aNc7I,6451 +torch/utils/data/graph.py,sha256=UW1pTUjToHbG35iCuFLYrEll1Qj2Mc96LYQa_tulx5s,5931 +torch/utils/data/graph_settings.py,sha256=ImWDygTKAWFF9-wy0-RkgYh8_0l6HLiEJT3uhQK8jWM,5556 +torch/utils/data/sampler.py,sha256=gX-BikiX8MElaaqI7blRw9mRLMILSkfWK_87cMrfGsU,12738 +torch/utils/debug_log.py,sha256=mV_DZ9ZsuqbWP21OT8fTsZBlbQty5GEMWjMeV6C1j3w,1827 +torch/utils/deterministic.py,sha256=aDwP89FjYTIT-3g2RtWBoagN59_JbqE2BZbgV4HttMU,611 +torch/utils/dlpack.py,sha256=4EMTlYhc_g4C5NFriU4B-R5C9bjOwAGkNn5zRj2eKjA,11245 +torch/utils/file_baton.py,sha256=B67yGDzUCaDx6LZYmCXgcciL9TucXJrHZtz7JywZC50,2093 +torch/utils/flop_counter.py,sha256=N_nSIrTyyWg0i2_dE7ezG8-r1FDPVPD0tCn1NzRcDQY,43420 +torch/utils/hipify/__init__.py,sha256=Jzb_RfgvXCrm_SQ4AfeGVi1N36YybxnM5mpyxrnihgI,33 +torch/utils/hipify/__pycache__/__init__.cpython-312.pyc,, +torch/utils/hipify/__pycache__/constants.cpython-312.pyc,, +torch/utils/hipify/__pycache__/cuda_to_hip_mappings.cpython-312.pyc,, +torch/utils/hipify/__pycache__/hipify_python.cpython-312.pyc,, +torch/utils/hipify/__pycache__/version.cpython-312.pyc,, +torch/utils/hipify/constants.py,sha256=rT3bQVod7V-F3Rc6fk9ix9ZEwZ8muEvb89OvRF9XGK8,1300 +torch/utils/hipify/cuda_to_hip_mappings.py,sha256=uuOTG2eX3uR_LAfZs3t_Xr7F550d_FVJtUNj4ol3oFQ,206381 +torch/utils/hipify/hipify_python.py,sha256=uMtIZPm0ntuJuOq-qpRpMCQJ8-JvIOMAxJSMWyB-7hU,46704 +torch/utils/hipify/version.py,sha256=hwOJuFUEKtsgiOt4l6op9s-hviovM6TK1uCdtRNWY4E,22 +torch/utils/hooks.py,sha256=BkrhCS4_jKZlOhrVb-Sy1YYwP-IyuhhlUF79G-HpEMU,10479 +torch/utils/jit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/utils/jit/__pycache__/__init__.cpython-312.pyc,, +torch/utils/jit/__pycache__/log_extract.cpython-312.pyc,, +torch/utils/jit/log_extract.py,sha256=ow9gm6RPIXXwgGYOVx63uEreA31vzKY-pbaWTjfUR-E,4194 +torch/utils/mkldnn.py,sha256=_cJIonfiRlU-Ph3QCrO_G7JjmX842kbZMikAJCDXsg8,10073 +torch/utils/mobile_optimizer.py,sha256=WjDZfuVnU8wTTprBDBV6EMgf3LdSt--LTxEuCjHn8B0,6414 +torch/utils/model_dump/__init__.py,sha256=IZfRjacOoMdDjh4CnxvwHBY-cemXHVHm-w9bVCdCgJ8,19311 +torch/utils/model_dump/__main__.py,sha256=jYGPuoI11jzWgGKtK1-E550XLfPkrbHq_BRUbLusK-A,79 +torch/utils/model_dump/__pycache__/__init__.cpython-312.pyc,, +torch/utils/model_dump/__pycache__/__main__.cpython-312.pyc,, +torch/utils/model_dump/code.js,sha256=70w_JAT7N8dkWHrpQsA1enZCJK7VJOIy23ukbbbXQAg,19251 +torch/utils/model_dump/htm.mjs,sha256=m-psDFjVL3_BzcZnYkiRT8AIYhFhCY5ERrh_LP4sEH4,1230 +torch/utils/model_dump/preact.mjs,sha256=005yDhrtmGbeMNCyf7SMhNktZT4VisnDde1R-TMD5gk,10078 +torch/utils/model_dump/skeleton.html,sha256=vq4r1yFKZEchXwQmky1zpj3q65MCPDBD7wDt6SqzJGg,384 +torch/utils/model_zoo.py,sha256=o2NC-XaU8fqDXbUBQDv7thQBld_LOK-Ko63GS4x8Iyg,117 +torch/utils/module_tracker.py,sha256=pt9-CzmJYVRSg7U91RQCtU5rRBVGRmro0a9biTeKjCg,5434 +torch/utils/serialization/__init__.py,sha256=urhmq5QqBImvzUxNXw7VkCHllOx41xEyNenyZOWKYQQ,21 +torch/utils/serialization/__pycache__/__init__.cpython-312.pyc,, +torch/utils/serialization/__pycache__/config.cpython-312.pyc,, +torch/utils/serialization/config.py,sha256=01NhAREofDqt4RBG0NS2TRodKXUEyRwpmYw0dnBELdk,654 +torch/utils/show_pickle.py,sha256=gQRZpzpYj1zBCHMxehPmyqvC-9pIobj4-mhYH7cmkvo,5459 +torch/utils/tensorboard/__init__.py,sha256=ZYXvCXkbnXG7fJB_0aD2m1tdKIjo39LFzMqN7fku94w,480 +torch/utils/tensorboard/__pycache__/__init__.cpython-312.pyc,, +torch/utils/tensorboard/__pycache__/_convert_np.cpython-312.pyc,, +torch/utils/tensorboard/__pycache__/_embedding.cpython-312.pyc,, +torch/utils/tensorboard/__pycache__/_onnx_graph.cpython-312.pyc,, +torch/utils/tensorboard/__pycache__/_proto_graph.cpython-312.pyc,, +torch/utils/tensorboard/__pycache__/_pytorch_graph.cpython-312.pyc,, +torch/utils/tensorboard/__pycache__/_utils.cpython-312.pyc,, +torch/utils/tensorboard/__pycache__/summary.cpython-312.pyc,, +torch/utils/tensorboard/__pycache__/writer.cpython-312.pyc,, +torch/utils/tensorboard/_convert_np.py,sha256=Wcss2Qu8wlM9GHrn6m0AVXK8o8wyhsHdoGtxOjuZSPU,882 +torch/utils/tensorboard/_embedding.py,sha256=z6sP-bBDNOsAm-wJfa9GZ66pU9sJUzHKDiomNZ4BcOY,3281 +torch/utils/tensorboard/_onnx_graph.py,sha256=KMnPjhnuLWLp3jJEnaOhUUV-yIk_4Z9S4x8l2A_mko8,1886 +torch/utils/tensorboard/_proto_graph.py,sha256=WMZNB-Vxc_Px-QxHVJFXQW_GaOIqLR3NT4WdZisWIFQ,1964 +torch/utils/tensorboard/_pytorch_graph.py,sha256=x_ACk_1k2XMVJHVvObMTlBi4FiDO2NkyS9xQbmtr8MA,13843 +torch/utils/tensorboard/_utils.py,sha256=Oq6WA632HgbInDQkPN-PlXxgeQeAALRMVXSLm8oeOM4,4307 +torch/utils/tensorboard/summary.py,sha256=w7RpsrRwFE_PNpbSUKa-UJd15OHUSJXP5ZQ8k4VXOc0,34719 +torch/utils/tensorboard/writer.py,sha256=xm6E2YABrp45aAwDD_rF0By3TqTk-FqQmFXqalv-YxM,47341 +torch/utils/throughput_benchmark.py,sha256=JwpH7pWU6Mrvd_oFijTJvFlzGU2SI-a08JJO84ZJogU,6621 +torch/utils/viz/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torch/utils/viz/__pycache__/__init__.cpython-312.pyc,, +torch/utils/viz/__pycache__/_cycles.cpython-312.pyc,, +torch/utils/viz/_cycles.py,sha256=6Q8rRD5diZsEpKnjy0wVUvPU_GNpBoLBxAQy8tz80YU,16984 +torch/utils/weak.py,sha256=37kIF_DXnasHEwz_OvuTguZaeLFRckXV5Gkf1jz7m2M,12227 +torch/version.py,sha256=vyVFwGGGhMfyc1AtcMiWyjpu8_CpTLXT4HE3lpjjFNE,313 +torch/xpu/__init__.py,sha256=OR3VGPT-lEzw59rjf09PY7C1SXP9x-k9dmJ__L2jhSw,54265 +torch/xpu/__pycache__/__init__.cpython-312.pyc,, +torch/xpu/__pycache__/_gpu_trace.cpython-312.pyc,, +torch/xpu/__pycache__/_utils.cpython-312.pyc,, +torch/xpu/__pycache__/graphs.cpython-312.pyc,, +torch/xpu/__pycache__/memory.cpython-312.pyc,, +torch/xpu/__pycache__/random.cpython-312.pyc,, +torch/xpu/__pycache__/streams.cpython-312.pyc,, +torch/xpu/_gpu_trace.py,sha256=xVF2Wike9f8uqlxtwDshiyTFbduMGq0HupoSLb47_70,2364 +torch/xpu/_utils.py,sha256=JTETOkI3J7tp4SFKV3ukRlvQDO-6Qg850KkJ8wO6gh0,1591 +torch/xpu/graphs.py,sha256=Sy95UAJSr28O0E4xLy_akotuoK1OKzmzATi6k5yH5Y4,22187 +torch/xpu/memory.py,sha256=3kZ_v6OJedxapjwr0NOx96vykBaN3mskIu2xbyDVHt4,28260 +torch/xpu/random.py,sha256=dnrrJobYRQJd-6-JcuyoNmbkw7IsMsJM-GnigqsfnlY,5282 +torch/xpu/streams.py,sha256=iRsHzdjqjqSFmXd7ehELgR88yjwo0JSugBXfUptX7ts,6305 +torchgen/__init__.py,sha256=iirTpG38WcCsNMhEbi1dg7_jad6ptk_uzZ-BzaGBFyU,348 +torchgen/__pycache__/__init__.cpython-312.pyc,, +torchgen/__pycache__/code_template.cpython-312.pyc,, +torchgen/__pycache__/context.cpython-312.pyc,, +torchgen/__pycache__/gen.cpython-312.pyc,, +torchgen/__pycache__/gen_aoti_c_shim.cpython-312.pyc,, +torchgen/__pycache__/gen_backend_stubs.cpython-312.pyc,, +torchgen/__pycache__/gen_functionalization_type.cpython-312.pyc,, +torchgen/__pycache__/gen_lazy_tensor.cpython-312.pyc,, +torchgen/__pycache__/gen_schema_utils.cpython-312.pyc,, +torchgen/__pycache__/gen_vmap_plumbing.cpython-312.pyc,, +torchgen/__pycache__/local.cpython-312.pyc,, +torchgen/__pycache__/model.cpython-312.pyc,, +torchgen/__pycache__/native_function_generation.cpython-312.pyc,, +torchgen/__pycache__/utils.cpython-312.pyc,, +torchgen/__pycache__/yaml_utils.cpython-312.pyc,, +torchgen/aoti/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torchgen/aoti/__pycache__/__init__.cpython-312.pyc,, +torchgen/aoti/__pycache__/fallback_ops.cpython-312.pyc,, +torchgen/aoti/fallback_ops.py,sha256=P5TWiWNbPjXVpy7q2mOWOWFVefU4VX3qLYDEkw7yqUM,10381 +torchgen/api/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torchgen/api/__pycache__/__init__.cpython-312.pyc,, +torchgen/api/__pycache__/autograd.cpython-312.pyc,, +torchgen/api/__pycache__/cpp.cpython-312.pyc,, +torchgen/api/__pycache__/dispatcher.cpython-312.pyc,, +torchgen/api/__pycache__/functionalization.cpython-312.pyc,, +torchgen/api/__pycache__/lazy.cpython-312.pyc,, +torchgen/api/__pycache__/meta.cpython-312.pyc,, +torchgen/api/__pycache__/native.cpython-312.pyc,, +torchgen/api/__pycache__/python.cpython-312.pyc,, +torchgen/api/__pycache__/structured.cpython-312.pyc,, +torchgen/api/__pycache__/translate.cpython-312.pyc,, +torchgen/api/__pycache__/ufunc.cpython-312.pyc,, +torchgen/api/__pycache__/unboxing.cpython-312.pyc,, +torchgen/api/autograd.py,sha256=m7XrLLGKnpcNO-pYhkHM5ujMh09vBhhD4dI3_Ri57bs,39666 +torchgen/api/cpp.py,sha256=RmXCcmYPE3nLAp5Dyu3t_95DOYiBTorEOnwl9iSFexo,16922 +torchgen/api/dispatcher.py,sha256=gPrg9tJ0ob1ErXWoGXJDGZTg0MbDCivTALKE7kjITU4,3479 +torchgen/api/functionalization.py,sha256=e5Jv65MTJiQ5LpYUU57Yf7mLRVmCVBhDS4kywZy1l2k,8349 +torchgen/api/lazy.py,sha256=ztV8Uhy6Ke5ArAVNNBREW7e045jaFMXGY8qgVHQ4DPU,17141 +torchgen/api/meta.py,sha256=zJYzviYI2gY9V9yPUyiZ_fShcdm_5LbigqGUH_WfaWw,483 +torchgen/api/native.py,sha256=xpye5SVepNMaHSIFzIfcrG-6BkDxCB3fPdQUPcilf5w,5205 +torchgen/api/python.py,sha256=t7cd92x5jR-lDqyQ4cYRWikF6iB_wS4u_w1cNfdbTis,58080 +torchgen/api/structured.py,sha256=pRq_3dMwQnVYBHkqnvrGykc0AZByQlNE2_2D_aXTDew,5996 +torchgen/api/translate.py,sha256=HqNgESXCwkPG0_nP61KSCeIuhG2et0FinfbVmE5_jt4,19833 +torchgen/api/types/__init__.py,sha256=bQ29sz_GNJGgqoDUsE6i_AcYZq81pOs1ATXQJQhUhLY,144 +torchgen/api/types/__pycache__/__init__.cpython-312.pyc,, +torchgen/api/types/__pycache__/signatures.cpython-312.pyc,, +torchgen/api/types/__pycache__/types.cpython-312.pyc,, +torchgen/api/types/__pycache__/types_base.cpython-312.pyc,, +torchgen/api/types/signatures.py,sha256=hNWM3qWCfyk635BOjyIJm6Fam-pOlr22zgHb_ltYh7k,12884 +torchgen/api/types/types.py,sha256=zbR0AzS8Bze8tYMfAOrOL-j6VVsi3ks3yPt4ULzY8nk,6092 +torchgen/api/types/types_base.py,sha256=v8Ks3hCBZHDWZ-K7tVlNIowqV1wLKnBX-bgITDGzH7E,7171 +torchgen/api/ufunc.py,sha256=lkjsc9zBKYWFScj0dlV0J6fT67kz_doD7PDc2lhEENk,6810 +torchgen/api/unboxing.py,sha256=URZP3o9Myx8piTEwM4g7CSDTrmnQVyutRdNc8koTL88,8089 +torchgen/code_template.py,sha256=3WKyggNeuDRmFKwOiw9dTDJLCpjqhiudfAU2Nw7BGxc,3265 +torchgen/context.py,sha256=TESgCeRyBcLVD3ixrHShmeqQQKV9MSfkuiyXze_JH6o,4024 +torchgen/dest/__init__.py,sha256=qECRwrljRjK-kMdBqfc9X8JPVVPU6XlUuWNEdFD9u0w,805 +torchgen/dest/__pycache__/__init__.cpython-312.pyc,, +torchgen/dest/__pycache__/lazy_ir.cpython-312.pyc,, +torchgen/dest/__pycache__/lazy_ts_lowering.cpython-312.pyc,, +torchgen/dest/__pycache__/native_functions.cpython-312.pyc,, +torchgen/dest/__pycache__/register_dispatch_key.cpython-312.pyc,, +torchgen/dest/__pycache__/ufunc.cpython-312.pyc,, +torchgen/dest/lazy_ir.py,sha256=ODkTTcp36ItMAxjKUEFVYCmNzbBUvG7mJVCEJyaW-9c,29704 +torchgen/dest/lazy_ts_lowering.py,sha256=9QUvL_Z-mGqRfhtK_X2RSEHlGmFOqDr_J8cYJrALUG4,1831 +torchgen/dest/native_functions.py,sha256=zbhIhFjcTCfhlf3D-o384Usl_rcq0PzCQWQoovyhw5k,2312 +torchgen/dest/register_dispatch_key.py,sha256=o9PphzQ2afMfHv_CFU6wHC_JmyavNbq60P9L-ffg0qE,41871 +torchgen/dest/ufunc.py,sha256=GyHbO3xBJYg9cGZhTfALevujG0RxMjbcnn4kDju8Tak,18204 +torchgen/gen.py,sha256=PAV9lM1Z1urAbwIESVX0ghvWcteJXKtGK-NUuT3rFNY,116992 +torchgen/gen_aoti_c_shim.py,sha256=Y1lH2i7BE36jEQ2-tuQZxlvK37eo9hT3Y_0un-dS6S4,31210 +torchgen/gen_backend_stubs.py,sha256=vYp7Jszke3ueM7RDpVl6EDkVpl0hxbEofCgfWhrOzQw,23340 +torchgen/gen_functionalization_type.py,sha256=zl-it1NBvN2xOFDBCo5-DHLjXX17Xfri1LR6SDRY87g,50617 +torchgen/gen_lazy_tensor.py,sha256=GAzbJNqdBcYq5eQoTDOvEcYUXsIbwVy1FAO4pEfXZ0g,23205 +torchgen/gen_schema_utils.py,sha256=-wvIzm5ESeeBqpucXXbFetYjtdm2RJtQ-UXB5rSyW4Q,3350 +torchgen/gen_vmap_plumbing.py,sha256=jcAo7Kx9hX6DWD-9xrorY473o033QE1jxpDBxWOWxKo,9523 +torchgen/local.py,sha256=NPwuRTtAXVEfXOkinBU5trBAyXCa5xdZv2zjQBmmBYg,2227 +torchgen/model.py,sha256=FU3T-DrUauXs5vr4oGBiSOE7D2P-cMq9XXTUMEnsmcw,124327 +torchgen/native_function_generation.py,sha256=NaEY_X50b3MXIRUpxRJxa2HJohSIkJHZAm6p3qOFIuA,30648 +torchgen/operator_versions/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torchgen/operator_versions/__pycache__/__init__.cpython-312.pyc,, +torchgen/operator_versions/__pycache__/gen_mobile_upgraders.cpython-312.pyc,, +torchgen/operator_versions/__pycache__/gen_mobile_upgraders_constant.cpython-312.pyc,, +torchgen/operator_versions/gen_mobile_upgraders.py,sha256=KzE7NikNmgWrxWRKoerJYlAwtZRML0v3UZhwBRlgJrw,12569 +torchgen/operator_versions/gen_mobile_upgraders_constant.py,sha256=C-U6rHQybm_FTcxsz27RMgJDj464NOLhlOzVjSjEn0w,243 +torchgen/packaged/ATen/native/native_functions.yaml,sha256=rhoViYFjINYi8ed_0u2KH4JsIUeRhY0jlKDkrT2wzcc,631091 +torchgen/packaged/ATen/native/tags.yaml,sha256=AT8PbeC4UDBQmZ249o6CvJ8bAJ2ZVdVN0T5qZIyixcA,6218 +torchgen/packaged/ATen/templates/ATenOpList.cpp,sha256=YobnhIm91ECCc6uYD2uDOrvFM4WqutKQbQ5x_Fh_5IE,1059 +torchgen/packaged/ATen/templates/CompositeViewCopyKernels.cpp,sha256=H64AHoCBB7MJIECAHNzki8NiTVPND0hy2vJ-KqiSF2c,2077 +torchgen/packaged/ATen/templates/DispatchKeyFunction.h,sha256=npUU8WpU76sZv8oqUQqBpcV_QHT6RW9j42EVTSA6pvA,702 +torchgen/packaged/ATen/templates/DispatchKeyFunctions.h,sha256=KlLfLZSYEG_7miq0fD8yuFtgVtm2mO4CQ9WiT6xoEpY,1937 +torchgen/packaged/ATen/templates/DispatchKeyFunctions_inl.h,sha256=nlAU0xWHQqRZn7JNV163YgAv5wwlykwsikMyjzZeZkI,824 +torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.cpp,sha256=DYjxJmYQ5Yegq1XW4hakqjvZo5skNWi2f5ZNLPUyQ4c,184 +torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.h,sha256=e8lUNJZ4jt0uMHjio6HOupVpMv83DtAaFBudAG6pEDw,384 +torchgen/packaged/ATen/templates/Function.h,sha256=Z2OimxsHx42itqLZE04H7-RiAPb7UJRzNZQvmVUW6n4,519 +torchgen/packaged/ATen/templates/FunctionalInverses.h,sha256=ikZPokOnPXrImLa9EbaKGPMgB4NsyIH1cuUSgmLyejQ,797 +torchgen/packaged/ATen/templates/Functions.cpp,sha256=Ep7aDznby8ihAU7UDilAeO0dJ1hjKgREVbiR6qlJ04M,3098 +torchgen/packaged/ATen/templates/Functions.h,sha256=W_xrKMuoXaRhohnPldbA0OVqkAi_NYid-pZ9zJQAa8U,4637 +torchgen/packaged/ATen/templates/LazyIr.h,sha256=-aVOIdjB719-6SLBsUURho6x0xdKyXsN6h5QP76HTd8,585 +torchgen/packaged/ATen/templates/LazyNonNativeIr.h,sha256=KQbjyZ0Q8qK8JcgqAaF-M-ZhvRE5UhTj8JIHyceNK9Y,178 +torchgen/packaged/ATen/templates/MethodOperators.h,sha256=ifirYleNPll8bjo_OYaC8jEuLWIJlP0Asy0xjtdGfQo,830 +torchgen/packaged/ATen/templates/NativeFunction.h,sha256=C8rQosVZF3aESwI4IvZitd60sdGov6kvClkDAtnx3Oc,366 +torchgen/packaged/ATen/templates/NativeFunctions.h,sha256=N351coNgM9F_jpdma5OK3DvlNUw2oY51iBXKe5dK81Y,1149 +torchgen/packaged/ATen/templates/NativeMetaFunction.h,sha256=C0alnIY6J-5Mlca9_0ocI7bnFKo5jQ_QTuLzo8iCUDQ,452 +torchgen/packaged/ATen/templates/NativeMetaFunctions.h,sha256=mIOwmpkQY9zYolxUXK39c4nRDyG32vBsqEeSDo76p_k,306 +torchgen/packaged/ATen/templates/Operator.h,sha256=5TqYc2DVGzB2gwuIwC8p4D6KnSDIylKXScnjwLfpdu0,448 +torchgen/packaged/ATen/templates/Operators.cpp,sha256=cjfjkIMtfc8n1w0TDy_JJDJq0DK2cT9DfhkZw3YnTWM,347 +torchgen/packaged/ATen/templates/Operators.h,sha256=oU939CI59Drfg2QlKfkCdU6yVQBVi0y9Ia_kQ0rFC5k,3200 +torchgen/packaged/ATen/templates/RedispatchFunctions.cpp,sha256=pNhfp3gMBw4km2c_4EfeF6ge3DGZi8xtGCnkmjzfpi0,307 +torchgen/packaged/ATen/templates/RedispatchFunctions.h,sha256=HFJ8SLBmg2LNRbsp9MdhHBGGztTGhcjzdWCgYPx5f7c,882 +torchgen/packaged/ATen/templates/RegisterBackendSelect.cpp,sha256=Op-RV7_8UnF_dbxO-hZ8X-7DBnFHsP9s11cM0JkJOWY,752 +torchgen/packaged/ATen/templates/RegisterCodegenUnboxedKernels.cpp,sha256=tux2wSt9RalK0o5AfliXJB3N4diTi-88PwNHOobDbmM,1119 +torchgen/packaged/ATen/templates/RegisterDispatchDefinitions.ini,sha256=hnJyQ-BCtiix4FaiwW1l3Zaq95M8C0lFTwbySsiWMDs,455 +torchgen/packaged/ATen/templates/RegisterDispatchKey.cpp,sha256=7RP7FNPAPjCiYsaq98iAzu5tSPQLynHiD5YfzLFQebg,1393 +torchgen/packaged/ATen/templates/RegisterFunctionalization.cpp,sha256=XwSLhkDBdltLpwLt6tju8BXB0JLWK1MDPb01Gv3agCs,3461 +torchgen/packaged/ATen/templates/RegisterSchema.cpp,sha256=HoLTDNwRhe8xJJucgd6qCkqTglPtxLYCRGCD_4-S0j0,383 +torchgen/packaged/ATen/templates/RegistrationDeclarations.h,sha256=KImic_ILyhxavbGxVna-Ascf--okibalZJlK44a5dic,160 +torchgen/packaged/ATen/templates/TensorBody.h,sha256=U0x2stKYwG3OGRm7utWhpqNqLu3sIr-ivoBq8YtanFQ,28563 +torchgen/packaged/ATen/templates/TensorMethods.cpp,sha256=ZMg24cqkVsPIZzkvwj8fj-FaVfPJnNXIZ85WfeboG2s,1919 +torchgen/packaged/ATen/templates/UfuncCPU.cpp,sha256=LrnISndBkXtdugvOWeRk9ZGYQlztFI5yqytoaZiKOQk,445 +torchgen/packaged/ATen/templates/UfuncCPUKernel.cpp,sha256=paz66F7U6E9e2X-rpbxlVDGcxevcXIOialaEqAaoArc,350 +torchgen/packaged/ATen/templates/UfuncCUDA.cu,sha256=HOBz8yO4QFxxmX_6gCF7L8MJvrGPwGQjoE-qDf8kF9Y,494 +torchgen/packaged/ATen/templates/UnboxingFunctions.cpp,sha256=wwdlYUaaCjXwhlaoqieeO-3fOqoQSBj62j6Is4n-UKY,709 +torchgen/packaged/ATen/templates/UnboxingFunctions.h,sha256=bcs4ET0LLtzs7nSSWhKA8jJzongib5CGlNA5yaExfKw,1026 +torchgen/packaged/ATen/templates/ViewMetaClasses.cpp,sha256=_8f0OdKZjfhK7LzODYmnmwaXjyie-LRnC-rVHxTv-ZM,346 +torchgen/packaged/ATen/templates/ViewMetaClasses.h,sha256=MhYaW9BQoS8iplXAz9IVu6_SY4JMG4eHP-ERqSXsdD0,233 +torchgen/packaged/ATen/templates/ViewMetaClassesPythonBinding.cpp,sha256=ATEHc06ioTG0d02quoCUFyBgaYR3FRV6SX-tkiLiFdY,292 +torchgen/packaged/ATen/templates/aten_interned_strings.h,sha256=_FM2jXAhATj9GZ66dXXUPx72q2uYnzT8iN4hkTz0rmI,805 +torchgen/packaged/ATen/templates/enum_tag.h,sha256=2f71l3hhsetytOYMpzhSywY-vpjF_uiHZgwZFJ8eG2I,389 +torchgen/packaged/autograd/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torchgen/packaged/autograd/__pycache__/__init__.cpython-312.pyc,, +torchgen/packaged/autograd/__pycache__/context.cpython-312.pyc,, +torchgen/packaged/autograd/__pycache__/gen_annotated_fn_args.cpython-312.pyc,, +torchgen/packaged/autograd/__pycache__/gen_autograd.cpython-312.pyc,, +torchgen/packaged/autograd/__pycache__/gen_autograd_functions.cpython-312.pyc,, +torchgen/packaged/autograd/__pycache__/gen_inplace_or_view_type.cpython-312.pyc,, +torchgen/packaged/autograd/__pycache__/gen_python_functions.cpython-312.pyc,, +torchgen/packaged/autograd/__pycache__/gen_trace_type.cpython-312.pyc,, +torchgen/packaged/autograd/__pycache__/gen_variable_factories.cpython-312.pyc,, +torchgen/packaged/autograd/__pycache__/gen_variable_type.cpython-312.pyc,, +torchgen/packaged/autograd/__pycache__/gen_view_funcs.cpython-312.pyc,, +torchgen/packaged/autograd/__pycache__/load_derivatives.cpython-312.pyc,, +torchgen/packaged/autograd/context.py,sha256=aCykxnX--PJ_Tl4CW2GOYAbW25o26ZyirEobqc7ozOk,954 +torchgen/packaged/autograd/deprecated.yaml,sha256=UbtajzWo89jf1Q5sw8JNJIZT5s-iDBagnrGJthtDS2Q,6250 +torchgen/packaged/autograd/derivatives.yaml,sha256=qdgy4Zk6P0eImo1e5S5ENAe70N-JVVDMWgLAG0RlpSY,187713 +torchgen/packaged/autograd/gen_annotated_fn_args.py,sha256=7SpCWSDgEj5pBYtWqsPAseC6Cfvyi_hUt-ST7BSF9hY,4476 +torchgen/packaged/autograd/gen_autograd.py,sha256=p6C9Pjmm1DyvB5QnFPqLs4EnWSR82cSpX975BipgJT8,4617 +torchgen/packaged/autograd/gen_autograd_functions.py,sha256=K2gt-zGHd1r_Nb3_wFA4-naU8ERgRrZX4AsdTNx5B2k,38327 +torchgen/packaged/autograd/gen_inplace_or_view_type.py,sha256=dmhrvrqn6j1bfGQGvKUbgRgbEYeDlfu5RC5nHhCP1-I,22914 +torchgen/packaged/autograd/gen_python_functions.py,sha256=_gNYzvOvLRBCmETuJx6Y-1fvvZDbDw8Z7QQdQbQ4FCY,46586 +torchgen/packaged/autograd/gen_trace_type.py,sha256=-9aNK0u3WKh-HKpRct2weTXksbc9jmtQ9YbbyOBjFOY,19168 +torchgen/packaged/autograd/gen_variable_factories.py,sha256=a0Q5N1zGSVxfES_cnq88tjwOB9P79piRqchTrhWCNPk,4479 +torchgen/packaged/autograd/gen_variable_type.py,sha256=Mi6vznQYA1zADEQZr8c762Aj-R7f_3V_AZE7kk4wF-I,89545 +torchgen/packaged/autograd/gen_view_funcs.py,sha256=LSNYEpzkNZXXFtM2pYpfCMw_QNAF5jm9RTOUMIFwJUM,11817 +torchgen/packaged/autograd/load_derivatives.py,sha256=p23zb3cDROxHqyJb6jSN-x00FeJqyEXyCKuHfIunnnM,41384 +torchgen/packaged/autograd/templates/ADInplaceOrViewType.cpp,sha256=6juXEdMJaxhS1nv6bqUmx-cJLWPyc4Yb3teAeTyEBG4,790 +torchgen/packaged/autograd/templates/Functions.cpp,sha256=j8Ga18okz6DI1ulIL5BErJIskHKQZPhuuNlj5RcgUuE,1478 +torchgen/packaged/autograd/templates/Functions.h,sha256=N5MeYemn7nk_cOhuearwCemcJIETmdjTGlZ2Q3mQEG8,1559 +torchgen/packaged/autograd/templates/TraceType.cpp,sha256=aqACTyrT05ElIiBLJYkfSgxNjwhum6_QUPDAtXwoKqo,695 +torchgen/packaged/autograd/templates/VariableType.cpp,sha256=AG80s3CwhESp-zaewyfHmwmL0cOxOXZJcZxqyn2cIBs,2259 +torchgen/packaged/autograd/templates/VariableType.h,sha256=VthaaDmUZdW4ymC5LCsxFRmVNHbPZdzYVwU0iZTkVKk,1425 +torchgen/packaged/autograd/templates/ViewFuncs.cpp,sha256=oas1Pw6wWyAfRy2uh5K7fGD3qR60LD2Oiv-B5OW6Tvc,269 +torchgen/packaged/autograd/templates/ViewFuncs.h,sha256=7RoIEE9NQ6jWdg3SfdbRsQxACKdscsrnZN45JTJER5I,498 +torchgen/packaged/autograd/templates/annotated_fn_args.py.in,sha256=gRgF9BZmylhyfXrVSAVjg9Y4TUYpq1FgYVd3_hk_9no,199 +torchgen/packaged/autograd/templates/python_enum_tag.cpp,sha256=2cTLq6vaU-qjAXLrChZAnCmpVqA4oDvZLOsBY3GWmDA,495 +torchgen/packaged/autograd/templates/python_fft_functions.cpp,sha256=fjhlDBOj0NNAMTaCAhL0_-OJE-H8Jc2mBDNK7jXoZIo,1909 +torchgen/packaged/autograd/templates/python_functions.cpp,sha256=b20LJcBbbQHQ4hTt-2h__DIuk8uHksD4ZVD5csfM43Q,1121 +torchgen/packaged/autograd/templates/python_functions.h,sha256=_j5WiOT8FT35eK7mTRb_xtr_YYGgOvOhDQjRJC-6ztU,321 +torchgen/packaged/autograd/templates/python_linalg_functions.cpp,sha256=3NyK1tMOYwAsnxyb1k04RPiN9MQkriblY3GnPVOrfSY,1614 +torchgen/packaged/autograd/templates/python_nested_functions.cpp,sha256=dA_L8IGTrYXtko9KyCg6-WpeLJyWHqUopOXhWEEmv8U,1987 +torchgen/packaged/autograd/templates/python_nn_functions.cpp,sha256=8AyIozHVM21KEaVuOPgT-zPfPGj6hpNMC5SiwqUixW0,3501 +torchgen/packaged/autograd/templates/python_return_types.cpp,sha256=tfBL6HOMwk-LckxsWiiCqx-T8XtkaTa50ZV6d56CBCo,1235 +torchgen/packaged/autograd/templates/python_return_types.h,sha256=ZDLPH-bxSjCpeyWLhU6kZsuAxa2pnCgTE57YpxXmDmQ,198 +torchgen/packaged/autograd/templates/python_sparse_functions.cpp,sha256=NW_L2mF7ZrR2FvXtDE7iNfw0BM-wTyUzBa_C1B5RZ7A,1551 +torchgen/packaged/autograd/templates/python_special_functions.cpp,sha256=ibjdT_fAvwxgvdEbXLP-jvqSaQN081N_pSvRgq7Rm60,1930 +torchgen/packaged/autograd/templates/python_torch_functions.cpp,sha256=A2S-MSQCGb9GJrVI7mi-jFr6Q2hIl5Q0xOaf_6NG2LM,2559 +torchgen/packaged/autograd/templates/python_variable_methods.cpp,sha256=T_DqTaMPcUaYBi7faX8P_MxBj5M60woHAUPWHXEokGg,53705 +torchgen/packaged/autograd/templates/variable_factories.h,sha256=g-WOn2XuHBsLNGUk-emw0-KcrNsosDjqAu4NjPJCFA4,5637 +torchgen/selective_build/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torchgen/selective_build/__pycache__/__init__.cpython-312.pyc,, +torchgen/selective_build/__pycache__/operator.cpython-312.pyc,, +torchgen/selective_build/__pycache__/selector.cpython-312.pyc,, +torchgen/selective_build/operator.py,sha256=rA-TkO7eMUnHHysNngoP2fMKJcwRw1wvSeH7Vqq5av8,7209 +torchgen/selective_build/selector.py,sha256=GiA_q-Q_qwyc5s7MzUFkt3f8EwUtxMscYDWtpyo9Qyk,13813 +torchgen/static_runtime/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torchgen/static_runtime/__pycache__/__init__.cpython-312.pyc,, +torchgen/static_runtime/__pycache__/config.cpython-312.pyc,, +torchgen/static_runtime/__pycache__/gen_static_runtime_ops.cpython-312.pyc,, +torchgen/static_runtime/__pycache__/generator.cpython-312.pyc,, +torchgen/static_runtime/config.py,sha256=ZGckbYpoJpi9vmLxVu0yMnYUqNTGhRHWd_2DrBN8oR4,14546 +torchgen/static_runtime/gen_static_runtime_ops.py,sha256=eoYNdqEXbgEG5YMmYeKEMp8hAU9__jrmZ4j_n6DrDpA,7395 +torchgen/static_runtime/generator.py,sha256=pdiU4FSZATPTovtEbfzrXdk4GdkjLAZL2wzOwPCWoXs,29538 +torchgen/utils.py,sha256=R05E4aFW5ZlNRulAzqh0WWHGtB_mb7j9SZybSauizaU,16962 +torchgen/yaml_utils.py,sha256=cQ9aPicmhKYSNfgbTZc4hrg0GPKKxddzZt5FdMHEKEE,1116 diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..1902e863d916ae422d00b1cd28c084fed75c04bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: scikit-build-core 1.0.3 +Root-Is-Purelib: false +Tag: cp312-cp312-manylinux_2_28_x86_64 + diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/entry_points.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..88ccd2f6680310248ca5210a6d1ae9337f09c024 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/entry_points.txt @@ -0,0 +1,17 @@ +[torchrun.logs_specs] +default = torch.distributed.elastic.multiprocessing:DefaultLogsSpecs + +[torch.distributed.backends] +mpi = torch.distributed.distributed_c10d:_register_builtin_mpi_backend +gloo = torch.distributed.distributed_c10d:_register_builtin_gloo_backend +nccl = torch.distributed.distributed_c10d:_register_builtin_nccl_backend +nccl-legacy = torch.distributed.distributed_c10d:_register_builtin_nccl_legacy_backend +nccl2 = torch.distributed.distributed_c10d:_register_builtin_nccl2_backend +nccl-lazy = torch.distributed.distributed_c10d:_register_builtin_nccl_lazy_backend +ucc = torch.distributed.distributed_c10d:_register_builtin_ucc_backend +xccl = torch.distributed.distributed_c10d:_register_builtin_xccl_backend + +[console_scripts] +torchrun = torch.distributed.run:main +torchfrtrace = torch.distributed.flight_recorder.fr_trace:main + diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c23172f7aff0254e4f0f163fb2e6e355cbaec5f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/LICENSE @@ -0,0 +1,84 @@ +From PyTorch: + +Copyright (c) 2016- Facebook, Inc (Adam Paszke) +Copyright (c) 2014- Facebook, Inc (Soumith Chintala) +Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert) +Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) +Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) +Copyright (c) 2011-2013 NYU (Clement Farabet) +Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston) +Copyright (c) 2006 Idiap Research Institute (Samy Bengio) +Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz) + +From Caffe2: + +Copyright (c) 2016-present, Facebook Inc. All rights reserved. + +All contributions by Facebook: +Copyright (c) 2016 Facebook Inc. + +All contributions by Google: +Copyright (c) 2015 Google Inc. +All rights reserved. + +All contributions by Yangqing Jia: +Copyright (c) 2015 Yangqing Jia +All rights reserved. + +All contributions by Kakao Brain: +Copyright 2019-2020 Kakao Brain + +All contributions by Cruise LLC: +Copyright (c) 2022 Cruise LLC. +All rights reserved. + +All contributions by Tri Dao: +Copyright (c) 2024 Tri Dao. +All rights reserved. + +All contributions by Arm: +Copyright (c) 2021, 2023-2025 Arm Limited and/or its affiliates + +All contributions from Caffe: +Copyright(c) 2013, 2014, 2015, the respective contributors +All rights reserved. + +All other contributions: +Copyright(c) 2015, 2016 the respective contributors +All rights reserved. + +Caffe2 uses a copyright model similar to Caffe: each contributor holds +copyright over their contributions to Caffe2. The project versioning records +all such contribution and copyright details. If a contributor wants to further +mark their specific copyright on a particular contribution, they should +indicate their copyright solely in the commit message of the change when it is +committed. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America + and IDIAP Research Institute nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/FP16/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/FP16/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..eabec6c86a3c7117090954b3756012b37b7c3786 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/FP16/LICENSE @@ -0,0 +1,11 @@ +The MIT License (MIT) + +Copyright (c) 2017 Facebook Inc. +Copyright (c) 2017 Georgia Institute of Technology +Copyright 2019 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/FXdiv/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/FXdiv/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f25bb419286df488daf0b7a5dc0bdb804d42afc4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/FXdiv/LICENSE @@ -0,0 +1,10 @@ +The MIT License (MIT) + +Copyright (c) 2017 Facebook Inc. +Copyright (c) 2016-2017 Marat Dukhan + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NNPACK/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NNPACK/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..779b7ccda8b4e467f173df7b9289a0c860cc9597 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NNPACK/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2017 Facebook Inc. +Copyright (c) 2015-2017, Georgia Institute of Technology +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..1e3e238e261289910d1d3978e626703d2107cfe8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/LICENSE.txt @@ -0,0 +1,223 @@ +============================================================================== +NVTX is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/docs/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/docs/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..1e3e238e261289910d1d3978e626703d2107cfe8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/docs/LICENSE.txt @@ -0,0 +1,223 @@ +============================================================================== +NVTX is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/python/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/python/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..1e3e238e261289910d1d3978e626703d2107cfe8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/python/LICENSE.txt @@ -0,0 +1,223 @@ +============================================================================== +NVTX is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/rust/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/rust/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6406aa2d1149e702301f30c1847a9886a6f03c39 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/NVTX/rust/LICENSE @@ -0,0 +1,222 @@ +============================================================================== +nvtx-rs is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Voltron Data + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/VulkanMemoryAllocator/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/VulkanMemoryAllocator/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..a080d9bf71fcf40b4714c6fab0130f6a9d973d7f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/VulkanMemoryAllocator/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (c) 2017-2025 Advanced Micro Devices, Inc. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/XNNPACK/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/XNNPACK/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..aa0e3666823dc336c360c27d8d10abf5efd9c252 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/XNNPACK/LICENSE @@ -0,0 +1,31 @@ +BSD License + +For XNNPACK software + +Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +Copyright 2019 Google LLC + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/aiter/3rdparty/composable_kernel/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/aiter/3rdparty/composable_kernel/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..68f6ae5746ddd5c79829fd7cc7e32584ffd9d822 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/aiter/3rdparty/composable_kernel/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2018- , Advanced Micro Devices, Inc. (Chao Liu, Jing Zhang) +Copyright (c) 2019- , Advanced Micro Devices, Inc. (Letao Qin, Qianfeng Zhang, Liang Huang, Shaojie Wang) +Copyright (c) 2022- , Advanced Micro Devices, Inc. (Anthony Chang, Chunyu Lai, Illia Silin, Adam Osewski, Poyen Chen, Jehandad Khan) +Copyright (c) 2019-2021, Advanced Micro Devices, Inc. (Hanwen Chang) +Copyright (c) 2019-2020, Advanced Micro Devices, Inc. (Tejash Shah) +Copyright (c) 2020 , Advanced Micro Devices, Inc. (Xiaoyan Zhou) +Copyright (c) 2021-2022, Advanced Micro Devices, Inc. (Jianfeng Yan) + +SPDX-License-Identifier: MIT +Copyright (c) 2018-2025, Advanced Micro Devices, Inc. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/aiter/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/aiter/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6311bdec0f330b61adb89cd32f719a43717504ed --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/aiter/LICENSE @@ -0,0 +1,21 @@ +Copyright © Advanced Micro Devices, Inc. All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/benchmark/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/benchmark/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/benchmark/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/composable_kernel/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/composable_kernel/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..68f6ae5746ddd5c79829fd7cc7e32584ffd9d822 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/composable_kernel/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2018- , Advanced Micro Devices, Inc. (Chao Liu, Jing Zhang) +Copyright (c) 2019- , Advanced Micro Devices, Inc. (Letao Qin, Qianfeng Zhang, Liang Huang, Shaojie Wang) +Copyright (c) 2022- , Advanced Micro Devices, Inc. (Anthony Chang, Chunyu Lai, Illia Silin, Adam Osewski, Poyen Chen, Jehandad Khan) +Copyright (c) 2019-2021, Advanced Micro Devices, Inc. (Hanwen Chang) +Copyright (c) 2019-2020, Advanced Micro Devices, Inc. (Tejash Shah) +Copyright (c) 2020 , Advanced Micro Devices, Inc. (Xiaoyan Zhou) +Copyright (c) 2021-2022, Advanced Micro Devices, Inc. (Jianfeng Yan) + +SPDX-License-Identifier: MIT +Copyright (c) 2018-2025, Advanced Micro Devices, Inc. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cpp-httplib/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cpp-httplib/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3e5ed359a2bb16f52c383745c25f14bb7a81c9e4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cpp-httplib/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2017 yhirose + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cpuinfo/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cpuinfo/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3f9a4f020cec01f29e5b9dce6630e02d82f2118d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cpuinfo/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2019 Google LLC +Copyright (c) 2017-2018 Facebook Inc. +Copyright (C) 2012-2017 Georgia Institute of Technology +Copyright (C) 2010-2012 Marat Dukhan + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cpuinfo/deps/clog/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cpuinfo/deps/clog/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..306de3d8f1628f0bf0c9f5c5f9dcff2265ca092b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cpuinfo/deps/clog/LICENSE @@ -0,0 +1,26 @@ +Copyright (C) 2018 Marat Dukhan +Copyright (c) 2017-2018 Facebook Inc. +Copyright (c) 2017 Georgia Institute of Technology + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cudnn_frontend/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cudnn_frontend/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..eef9c4461c4c6c4dea849ad4af5dd9a4d0837f91 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cudnn_frontend/LICENSE.txt @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cutlass/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cutlass/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..e971c5d22b9dafa2b83deaedff8350ca7e653d26 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cutlass/LICENSE.txt @@ -0,0 +1,34 @@ +Copyright (c) 2017 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: BSD-3-Clause + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Certain files within this repository are subject to separate licensing terms: + +- The files located in the `python/CuTeDSL` directory are licensed under the + NVIDIA End User License Agreement (EULA). Please refer to + https://docs.nvidia.com/cutlass/latest/media/docs/pythonDSL/license.html + for the full terms. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cutlass/python/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cutlass/python/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..bad38aaafcbd3b4345abbd755c47aaff0a2a4873 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/cutlass/python/LICENSE.txt @@ -0,0 +1,27 @@ +Copyright (c) 2017 - 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: BSD-3-Clause + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1c8dd93e668d0fee72d84557dd239e5bfde52a6c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/LICENSE @@ -0,0 +1,30 @@ +BSD License + +For FBGEMM software + +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/composable_kernel/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/composable_kernel/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..68f6ae5746ddd5c79829fd7cc7e32584ffd9d822 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/composable_kernel/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2018- , Advanced Micro Devices, Inc. (Chao Liu, Jing Zhang) +Copyright (c) 2019- , Advanced Micro Devices, Inc. (Letao Qin, Qianfeng Zhang, Liang Huang, Shaojie Wang) +Copyright (c) 2022- , Advanced Micro Devices, Inc. (Anthony Chang, Chunyu Lai, Illia Silin, Adam Osewski, Poyen Chen, Jehandad Khan) +Copyright (c) 2019-2021, Advanced Micro Devices, Inc. (Hanwen Chang) +Copyright (c) 2019-2020, Advanced Micro Devices, Inc. (Tejash Shah) +Copyright (c) 2020 , Advanced Micro Devices, Inc. (Xiaoyan Zhou) +Copyright (c) 2021-2022, Advanced Micro Devices, Inc. (Jianfeng Yan) + +SPDX-License-Identifier: MIT +Copyright (c) 2018-2025, Advanced Micro Devices, Inc. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cpuinfo/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cpuinfo/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3f9a4f020cec01f29e5b9dce6630e02d82f2118d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cpuinfo/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2019 Google LLC +Copyright (c) 2017-2018 Facebook Inc. +Copyright (C) 2012-2017 Georgia Institute of Technology +Copyright (C) 2010-2012 Marat Dukhan + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cpuinfo/deps/clog/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cpuinfo/deps/clog/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..306de3d8f1628f0bf0c9f5c5f9dcff2265ca092b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cpuinfo/deps/clog/LICENSE @@ -0,0 +1,26 @@ +Copyright (C) 2018 Marat Dukhan +Copyright (c) 2017-2018 Facebook Inc. +Copyright (c) 2017 Georgia Institute of Technology + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cutlass/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cutlass/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..e08eb49c207f1e24ea797d5162684f8c0329e9c9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cutlass/LICENSE.txt @@ -0,0 +1,34 @@ +Copyright (c) 2017 - 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: BSD-3-Clause + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Certain files within this repository are subject to separate licensing terms: + +- The files located in the `python/CuTeDSL` directory are licensed under the + NVIDIA End User License Agreement (EULA). Please refer to + https://docs.nvidia.com/cutlass/media/docs/pythonDSL/license.html + for the full terms. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cutlass/python/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cutlass/python/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..47016fa73e72d57e7cf3e4b4eca902542ab7faba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/cutlass/python/LICENSE.txt @@ -0,0 +1,27 @@ +Copyright (c) 2017 - 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: BSD-3-Clause + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/googletest/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/googletest/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1941a11f8ce94389160b458927a29ba217542818 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/googletest/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/hipify_torch/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/hipify_torch/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb99203495a5a893e7c7a41c60755b15decacd68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/external/hipify_torch/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-2024, Advanced Micro Devices, Inc. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/fbgemm_gpu/experimental/hstu/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/fbgemm_gpu/experimental/hstu/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5860e4b33f3d9d85fc636137c559331d51783a5b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/fbgemm_gpu/experimental/hstu/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/fbgemm_gpu/src/quantize_ops/mx/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/fbgemm_gpu/src/quantize_ops/mx/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/fbgemm_gpu/src/quantize_ops/mx/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/fbgemm_gpu/test/quantize/mx/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/fbgemm_gpu/test/quantize/mx/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9e841e7a26e4eb057b24511e7b92d42b257a80e5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fbgemm/fbgemm_gpu/test/quantize/mx/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5860e4b33f3d9d85fc636137c559331d51783a5b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/csrc/composable_kernel/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/csrc/composable_kernel/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..68f6ae5746ddd5c79829fd7cc7e32584ffd9d822 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/csrc/composable_kernel/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2018- , Advanced Micro Devices, Inc. (Chao Liu, Jing Zhang) +Copyright (c) 2019- , Advanced Micro Devices, Inc. (Letao Qin, Qianfeng Zhang, Liang Huang, Shaojie Wang) +Copyright (c) 2022- , Advanced Micro Devices, Inc. (Anthony Chang, Chunyu Lai, Illia Silin, Adam Osewski, Poyen Chen, Jehandad Khan) +Copyright (c) 2019-2021, Advanced Micro Devices, Inc. (Hanwen Chang) +Copyright (c) 2019-2020, Advanced Micro Devices, Inc. (Tejash Shah) +Copyright (c) 2020 , Advanced Micro Devices, Inc. (Xiaoyan Zhou) +Copyright (c) 2021-2022, Advanced Micro Devices, Inc. (Jianfeng Yan) + +SPDX-License-Identifier: MIT +Copyright (c) 2018-2025, Advanced Micro Devices, Inc. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/csrc/cutlass/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/csrc/cutlass/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..e08eb49c207f1e24ea797d5162684f8c0329e9c9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/csrc/cutlass/LICENSE.txt @@ -0,0 +1,34 @@ +Copyright (c) 2017 - 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: BSD-3-Clause + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Certain files within this repository are subject to separate licensing terms: + +- The files located in the `python/CuTeDSL` directory are licensed under the + NVIDIA End User License Agreement (EULA). Please refer to + https://docs.nvidia.com/cutlass/media/docs/pythonDSL/license.html + for the full terms. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/csrc/cutlass/python/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/csrc/cutlass/python/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..47016fa73e72d57e7cf3e4b4eca902542ab7faba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/csrc/cutlass/python/LICENSE.txt @@ -0,0 +1,27 @@ +Copyright (c) 2017 - 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: BSD-3-Clause + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/flash_attn/cute/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/flash_attn/cute/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5860e4b33f3d9d85fc636137c559331d51783a5b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/flash_attn/cute/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/third_party/aiter/3rdparty/composable_kernel/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/third_party/aiter/3rdparty/composable_kernel/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..68f6ae5746ddd5c79829fd7cc7e32584ffd9d822 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/third_party/aiter/3rdparty/composable_kernel/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2018- , Advanced Micro Devices, Inc. (Chao Liu, Jing Zhang) +Copyright (c) 2019- , Advanced Micro Devices, Inc. (Letao Qin, Qianfeng Zhang, Liang Huang, Shaojie Wang) +Copyright (c) 2022- , Advanced Micro Devices, Inc. (Anthony Chang, Chunyu Lai, Illia Silin, Adam Osewski, Poyen Chen, Jehandad Khan) +Copyright (c) 2019-2021, Advanced Micro Devices, Inc. (Hanwen Chang) +Copyright (c) 2019-2020, Advanced Micro Devices, Inc. (Tejash Shah) +Copyright (c) 2020 , Advanced Micro Devices, Inc. (Xiaoyan Zhou) +Copyright (c) 2021-2022, Advanced Micro Devices, Inc. (Jianfeng Yan) + +SPDX-License-Identifier: MIT +Copyright (c) 2018-2025, Advanced Micro Devices, Inc. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/third_party/aiter/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/third_party/aiter/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6311bdec0f330b61adb89cd32f719a43717504ed --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flash-attention/third_party/aiter/LICENSE @@ -0,0 +1,21 @@ +Copyright © Advanced Micro Devices, Inc. All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flatbuffers/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flatbuffers/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flatbuffers/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flatbuffers/dart/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flatbuffers/dart/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c02ca2f7a135a36281a16bc70be494d969bcfc10 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flatbuffers/dart/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flatbuffers/swift/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flatbuffers/swift/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/flatbuffers/swift/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fmt/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fmt/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..795fdaec8f2ce6fcc97bbb15d1a6ac073af7bd17 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/fmt/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/gemmlowp/gemmlowp/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/gemmlowp/gemmlowp/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/gemmlowp/gemmlowp/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/gloo/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/gloo/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..221dd2a126789f1092239f05f9d1e976f12ea237 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/gloo/LICENSE @@ -0,0 +1,30 @@ +BSD License + +For Gloo software + +Copyright (c) 2017-present, Facebook, Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/googletest/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/googletest/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1941a11f8ce94389160b458927a29ba217542818 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/googletest/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2956417a74d1013d7e83b15e2d8e42332db0a1d5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2018 Intel Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/mkl-dnn/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/mkl-dnn/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4de7f5cf14b3c9f8fbb74f6935ba826dd77cc8c1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/mkl-dnn/LICENSE @@ -0,0 +1,207 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + ============================================================================ + + Copyright 2016-2025 Intel Corporation + Copyright 2018 YANDEX LLC + Copyright 2019-2025 FUJITSU LIMITED + Copyright 2020-2025 Arm Ltd. and affiliates + Copyright 2020-2025 Codeplay Software Limited + Copyright 2021 Alanna Tempest + Copyright 2022-2023 IBM Corporation + Copyright 2023 KNS Group LLC (YADRO) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + This distribution includes third party software ("third party programs"). + This third party software, even if included with the distribution of + the Intel software, may be governed by separate license terms, including + without limitation, third party license terms, other Intel software license + terms, and open source software license terms. These separate license terms + govern your use of the third party programs as set forth in the + "THIRD-PARTY-PROGRAMS" file. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/mkl-dnn/third_party/gtest/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/mkl-dnn/third_party/gtest/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1941a11f8ce94389160b458927a29ba217542818 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/mkl-dnn/third_party/gtest/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/mkl-dnn/third_party/opencl/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/mkl-dnn/third_party/opencl/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/ideep/mkl-dnn/third_party/opencl/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..840d3e1bce02641f8f044628378c3d1d171ea9b3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/LICENSE @@ -0,0 +1,33 @@ +BSD License + +For Kineto software + +Copyright (c) Meta Platforms, Inc. and affiliates. + +All contributions by Microsoft: +Copyright (c) Microsoft Corporation. (The Azure AI Platform team) + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Meta nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/libkineto/third_party/dynolog_headers/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/libkineto/third_party/dynolog_headers/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b96dcb0480a0b0be0727976e5202a1e7b23edc3f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/libkineto/third_party/dynolog_headers/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/libkineto/third_party/fmt/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/libkineto/third_party/fmt/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1cd1ef92696b65b2ecb0e560e622f0a0e869dcf3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/libkineto/third_party/fmt/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--- Optional exception to the license --- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into a machine-executable object form of such +source code, you may redistribute such embedded portions in such object form +without including the above copyright and permission notices. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/libkineto/third_party/googletest/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/libkineto/third_party/googletest/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1941a11f8ce94389160b458927a29ba217542818 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/kineto/libkineto/third_party/googletest/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/llvm-openmp/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/llvm-openmp/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..90837782e958e9cd32935c5d29b7a9abe4750c51 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/llvm-openmp/LICENSE.txt @@ -0,0 +1,312 @@ +macOS wheels comes bundled with libomp.dylib from LLVM project and uses +pre-built binaries from conda-forge + +============================================================================== +The LLVM Project is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + +============================================================================== +Software from third parties included in the LLVM Project: +============================================================================== +The LLVM Project contains third party software which is under different license +terms. All such code will be identified clearly using at least one of two +mechanisms: +1) It will be in a separate directory tree with its own `LICENSE.txt` or + `LICENSE` file at the top containing the specific license and restrictions + which apply to that software, or +2) It will contain specific license and restriction terms at the top of every + file. + +============================================================================== +Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy): +============================================================================== +University of Illinois/NCSA +Open Source License + +Copyright (c) 2003-2019 University of Illinois at Urbana-Champaign. +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +================================================================================ +Binaries from conda-forge are licensed as follows +================================================================================ +BSD-3-Clause license +Copyright (c) 2015-2022, conda-forge contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mimalloc/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mimalloc/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..53315ebee557ac22f3396ea1781df0440c26bb15 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mimalloc/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018-2025 Microsoft Corporation, Daan Leijen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/miniz-3.0.2/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/miniz-3.0.2/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1982f4bb8f4afa3dcbe803887fb4af7573430e51 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/miniz-3.0.2/LICENSE @@ -0,0 +1,22 @@ +Copyright 2013-2014 RAD Game Tools and Valve Software +Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + +All Rights Reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..241b03e582be2f655d171e8075b6951610713cc6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/LICENSE @@ -0,0 +1,30 @@ +BSD License + +For MSLK software + +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/composable_kernel/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/composable_kernel/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..68f6ae5746ddd5c79829fd7cc7e32584ffd9d822 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/composable_kernel/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2018- , Advanced Micro Devices, Inc. (Chao Liu, Jing Zhang) +Copyright (c) 2019- , Advanced Micro Devices, Inc. (Letao Qin, Qianfeng Zhang, Liang Huang, Shaojie Wang) +Copyright (c) 2022- , Advanced Micro Devices, Inc. (Anthony Chang, Chunyu Lai, Illia Silin, Adam Osewski, Poyen Chen, Jehandad Khan) +Copyright (c) 2019-2021, Advanced Micro Devices, Inc. (Hanwen Chang) +Copyright (c) 2019-2020, Advanced Micro Devices, Inc. (Tejash Shah) +Copyright (c) 2020 , Advanced Micro Devices, Inc. (Xiaoyan Zhou) +Copyright (c) 2021-2022, Advanced Micro Devices, Inc. (Jianfeng Yan) + +SPDX-License-Identifier: MIT +Copyright (c) 2018-2025, Advanced Micro Devices, Inc. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/cutlass/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/cutlass/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..e08eb49c207f1e24ea797d5162684f8c0329e9c9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/cutlass/LICENSE.txt @@ -0,0 +1,34 @@ +Copyright (c) 2017 - 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: BSD-3-Clause + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Certain files within this repository are subject to separate licensing terms: + +- The files located in the `python/CuTeDSL` directory are licensed under the + NVIDIA End User License Agreement (EULA). Please refer to + https://docs.nvidia.com/cutlass/media/docs/pythonDSL/license.html + for the full terms. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/cutlass/python/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/cutlass/python/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..47016fa73e72d57e7cf3e4b4eca902542ab7faba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/cutlass/python/LICENSE.txt @@ -0,0 +1,27 @@ +Copyright (c) 2017 - 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: BSD-3-Clause + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/googletest/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/googletest/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1941a11f8ce94389160b458927a29ba217542818 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/googletest/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/hipify_torch/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/hipify_torch/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb99203495a5a893e7c7a41c60755b15decacd68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/external/hipify_torch/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-2024, Advanced Micro Devices, Inc. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/mslk/attention/flash_attn/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/mslk/attention/flash_attn/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5860e4b33f3d9d85fc636137c559331d51783a5b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/mslk/mslk/attention/flash_attn/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/onnx/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/onnx/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/onnx/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/onnx/third_party/pybind11/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/onnx/third_party/pybind11/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e466b0dfda14f3a7c8ece512937eb99c8b7b6d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/onnx/third_party/pybind11/LICENSE @@ -0,0 +1,29 @@ +Copyright (c) 2016 Wenzel Jakob , All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Please also refer to the file .github/CONTRIBUTING.md, which clarifies licensing of +external contributions to this project including patches, pull requests, etc. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/perfetto/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/perfetto/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..681d40008ee32ddb7e4e1413d6bf82c4f68c5b5b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/perfetto/LICENSE @@ -0,0 +1,285 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +------------------ + +Files: * except those files noted below + + Copyright (c) 2017, The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +------------------ + +Files: src/trace_processor/perfetto_sql/stdlib/chromium/*, protos/third_party/chromium/*, test/trace_processor/diff_tests/stdlib/chrome/* + + Copyright 2015 The Chromium Authors + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following disclaimer + in the documentation and/or other materials provided with the + distribution. + * Neither the name of Google LLC nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +------------------ + +Files: src/trace_processor/perfetto_sql/syntaqlite/syntaqlite_perfetto.{c, h} + + Copyright 2025 The syntaqlite Authors. All rights reserved. + + Machine-generated amalgamation of syntaqlite runtime + Perfetto dialect + sources (https://github.com/LalitMaganti/syntaqlite). Portions derive + from SQLite's public-domain `parse.y` grammar. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +------------------ + +Files: src/trace_processor/perfetto_sql/preprocessor/preprocessor_grammar.{c, h} + +The author disclaims copyright to this source code. In place of a legal notice, here is a blessing: + +May you do good and not evil. +May you find forgiveness for yourself and forgive others. +May you share freely, never taking more than you give. + + +------------------ + +Files: src/base/intrusive_tree.cc + +$OpenBSD: tree.h,v 1.31 2023/03/08 04:43:09 guenther Exp $ + +Copyright 2002 Niels Provos +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..19b305b00060a774a9180fb916c14b49edb2008f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/LICENSE @@ -0,0 +1,32 @@ +Copyright 2008 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Code generated by the Protocol Buffer compiler is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/benchmark/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/benchmark/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/benchmark/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1941a11f8ce94389160b458927a29ba217542818 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/googlemock/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/googlemock/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1941a11f8ce94389160b458927a29ba217542818 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/googlemock/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/googlemock/scripts/generator/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/googlemock/scripts/generator/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..87ea0636510a18a06e490117e717eb1fdf575f19 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/googlemock/scripts/generator/LICENSE @@ -0,0 +1,203 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2007] Neal Norwitz + Portions Copyright [2007] Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/googletest/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/googletest/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1941a11f8ce94389160b458927a29ba217542818 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/googletest/googletest/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/utf8_range/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/utf8_range/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c1f087ecc8250ac9e9207787c89911c926328826 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/protobuf/third_party/utf8_range/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Yibo Cai + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/psimd/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/psimd/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0a117cb6df979fa54425efac9e4e90e171fb5639 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/psimd/LICENSE @@ -0,0 +1,11 @@ +The MIT License (MIT) + +Copyright (c) 2017 Facebook Inc. +Copyright (c) 2014-2017 Georgia Institute of Technology +Copyright 2019 Google LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/pthreadpool/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/pthreadpool/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..27aa856e421b97959e3454523ce7108601f31677 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/pthreadpool/LICENSE @@ -0,0 +1,26 @@ +Copyright 2019 Google LLC +Copyright (c) 2017 Facebook Inc. +Copyright (c) 2015-2017 Georgia Institute of Technology +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/pybind11/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/pybind11/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e466b0dfda14f3a7c8ece512937eb99c8b7b6d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/pybind11/LICENSE @@ -0,0 +1,29 @@ +Copyright (c) 2016 Wenzel Jakob , All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Please also refer to the file .github/CONTRIBUTING.md, which clarifies licensing of +external contributions to this project including patches, pull requests, etc. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/python-peachpy/LICENSE.rst b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/python-peachpy/LICENSE.rst new file mode 100644 index 0000000000000000000000000000000000000000..89a13b8de4acdc8a709c640b1ba1ba4b19e3f9d7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/python-peachpy/LICENSE.rst @@ -0,0 +1,15 @@ +============================== +PeachPy license (2-clause BSD) +============================== + +Copyright (c) 2017, Facebook Inc. +Copyright (c) 2013-2017, Georgia Institute of Technology +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/sleef/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/sleef/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..36b7cd93cdfbac762f5be4c6ce276df2ea6305c2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/sleef/LICENSE.txt @@ -0,0 +1,23 @@ +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/LICENSE.txt b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..e30e3230a50fd240868e3c6508072906479064fa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/LICENSE.txt @@ -0,0 +1,30 @@ +BSD License + +For TensorPipe software + +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Meta nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1941a11f8ce94389160b458927a29ba217542818 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/googlemock/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/googlemock/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1941a11f8ce94389160b458927a29ba217542818 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/googlemock/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/googlemock/scripts/generator/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/googlemock/scripts/generator/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..87ea0636510a18a06e490117e717eb1fdf575f19 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/googlemock/scripts/generator/LICENSE @@ -0,0 +1,203 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2007] Neal Norwitz + Portions Copyright [2007] Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/googletest/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/googletest/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1941a11f8ce94389160b458927a29ba217542818 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/googletest/googletest/LICENSE @@ -0,0 +1,28 @@ +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/libnop/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/libnop/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..516378cdcbc7cf1a95444e02040dd110a50f004d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/libnop/LICENSE @@ -0,0 +1,13 @@ +Copyright 2017 The Native Object Protocols Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/libuv/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/libuv/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6566365d4f238005a3358710e20b2acde266b594 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/libuv/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-present libuv project contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/pybind11/LICENSE b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/pybind11/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6f15578cc4044061e01305227eaefb3dc49f4e11 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch-2.14.0+cpu.dist-info/licenses/third_party/tensorpipe/third_party/pybind11/LICENSE @@ -0,0 +1,29 @@ +Copyright (c) 2016 Wenzel Jakob , All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Please also refer to the file CONTRIBUTING.md, which clarifies licensing of +external contributions to this project including patches, pull requests, etc. diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/checkpoint.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/checkpoint.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0ddfaf73746faa26a3602d125cc907db121e08c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/checkpoint.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/collect_env.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/collect_env.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5271822837ec661c3c0deec8605edb2ebb4d8864 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/collect_env.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/cpp_backtrace.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/cpp_backtrace.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca2aede69456a1a6e7e7adc462d1380b0827c2ba Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/cpp_backtrace.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/cpp_extension.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/cpp_extension.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40f2530d8890bfbfc5312349b9fb3d11e3f7a83d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/cpp_extension.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5f1304b4e59a4eb6dc75cbc9529972fed967ae6a8535dc3d50b113167486561 +size 144363 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/debug_log.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/debug_log.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d058ce99e45c2e34856704fc74c9988f95cadb95 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/debug_log.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/deterministic.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/deterministic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37350cedb0f8fb71d86e8bf97c301eee7162708e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/deterministic.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/dlpack.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/dlpack.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8254e09b1a3fa9a2f7740a48639a2e9d50acb48e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/dlpack.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/file_baton.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/file_baton.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd4bff7233a574b0875b74b04f6bb234d8fc190e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/file_baton.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/flop_counter.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/flop_counter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1c84a1bb1233e2a78976c225b1d3f645af0bce6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/flop_counter.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/hooks.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/hooks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84c18422d40bae760856d943d47c11c81e49f420 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/hooks.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/mkldnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/mkldnn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3de139268c347186bb64aa3b2863e81068b8653 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/mkldnn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/mobile_optimizer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/mobile_optimizer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2aba9a6477f6f7c19b0adcd0bbb3c1e157b29630 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/mobile_optimizer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/model_zoo.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/model_zoo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6d7ab4a207da52a1bfa2e6805e774a515f75423 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/model_zoo.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/module_tracker.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/module_tracker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2e9e15a525819c28accece67909a95c1e990606 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/module_tracker.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/show_pickle.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/show_pickle.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ef2da8a8f872e38da36bc59d60478e804a32927 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/show_pickle.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/throughput_benchmark.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/throughput_benchmark.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d856afafcde5b015dd1f0809d9ad0747098f325 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/throughput_benchmark.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/weak.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/weak.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..663990ab17e911fb69a81cf6022b872b7a2bb088 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/weak.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_appending_byte_serializer.py b/.venv/lib/python3.12/site-packages/torch/utils/_appending_byte_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..82cced0b3dc826484e2d44788e4814b9dbe32693 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_appending_byte_serializer.py @@ -0,0 +1,135 @@ +import base64 +import zlib +from collections.abc import Callable, Iterable +from typing import Generic, TypeVar + + +T = TypeVar("T") + +_ENCODING_VERSION: int = 1 + +__all__ = ["AppendingByteSerializer"] + + +####################################### +# Helper classes +####################################### + +CHECKSUM_DIGEST_SIZE = 4 + + +class BytesWriter: + def __init__(self) -> None: + # Reserve CHECKSUM_DIGEST_SIZE bytes for checksum + self._data = bytearray(CHECKSUM_DIGEST_SIZE) + + def write_uint64(self, i: int) -> None: + self._data.extend(i.to_bytes(8, byteorder="big", signed=False)) + + def write_str(self, s: str) -> None: + payload = base64.b64encode(s.encode("utf-8")) + self.write_bytes(payload) + + def write_bytes(self, b: bytes) -> None: + self.write_uint64(len(b)) + self._data.extend(b) + + def to_bytes(self) -> bytes: + digest = zlib.crc32(self._data[CHECKSUM_DIGEST_SIZE:]).to_bytes( + 4, byteorder="big", signed=False + ) + if len(digest) != CHECKSUM_DIGEST_SIZE: + raise AssertionError("Computed checksum digest has unexpected size") + self._data[0:CHECKSUM_DIGEST_SIZE] = digest + return bytes(self._data) + + +class BytesReader: + def __init__(self, data: bytes) -> None: + # Check for data corruption + if len(data) < CHECKSUM_DIGEST_SIZE: + raise AssertionError("Input data is too short to contain checksum") + digest = zlib.crc32(data[CHECKSUM_DIGEST_SIZE:]).to_bytes( + 4, byteorder="big", signed=False + ) + if len(digest) != CHECKSUM_DIGEST_SIZE: + raise AssertionError("Computed checksum digest has unexpected size") + if data[0:CHECKSUM_DIGEST_SIZE] != digest: + raise RuntimeError( + "Bytes object is corrupted, checksum does not match. " + f"Expected: {data[0:CHECKSUM_DIGEST_SIZE]!r}, Got: {digest!r}" + ) + + self._data = data + self._i = CHECKSUM_DIGEST_SIZE + + def is_finished(self) -> bool: + return len(self._data) == self._i + + def read_uint64(self) -> int: + result = int.from_bytes( + self._data[self._i : self._i + 8], byteorder="big", signed=False + ) + self._i += 8 + return result + + def read_str(self) -> str: + return base64.b64decode(self.read_bytes()).decode("utf-8") + + def read_bytes(self) -> bytes: + size = self.read_uint64() + result = self._data[self._i : self._i + size] + self._i += size + return result + + +####################################### +# AppendingByteSerializer +####################################### + + +class AppendingByteSerializer(Generic[T]): + """ + Provides efficient serialization and deserialization of list of bytes + Note that this does not provide any guarantees around byte order + """ + + _serialize_fn: Callable[[BytesWriter, T], None] + _writer: BytesWriter + + def __init__( + self, + *, + serialize_fn: Callable[[BytesWriter, T], None], + ) -> None: + self._serialize_fn = serialize_fn + self.clear() + + def clear(self) -> None: + self._writer = BytesWriter() + # First 8-bytes are for version + self._writer.write_uint64(_ENCODING_VERSION) + + def append(self, data: T) -> None: + self._serialize_fn(self._writer, data) + + def extend(self, elems: Iterable[T]) -> None: + for elem in elems: + self.append(elem) + + def to_bytes(self) -> bytes: + return self._writer.to_bytes() + + @staticmethod + def to_list(data: bytes, *, deserialize_fn: Callable[[BytesReader], T]) -> list[T]: + reader = BytesReader(data) + if reader.read_uint64() != _ENCODING_VERSION: + raise AssertionError( + f"Encoding version mismatch in AppendingByteSerializer.to_list, \ + got {reader.read_uint64()}" + ) + + result: list[T] = [] + while not reader.is_finished(): + result.append(deserialize_fn(reader)) + return result diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_config_module.py b/.venv/lib/python3.12/site-packages/torch/utils/_config_module.py new file mode 100644 index 0000000000000000000000000000000000000000..2038523a0c97419b21c008c22fe9fd83ad6fca6a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_config_module.py @@ -0,0 +1,1089 @@ +import contextlib +import copy +import functools +import hashlib +import importlib +import inspect +import io +import keyword +import math +import os +import pickle +import tokenize +import unittest +from collections.abc import Callable +from contextvars import ContextVar +from dataclasses import dataclass +from types import FunctionType, ModuleType +from typing import Any, Generic, NoReturn, Optional, TYPE_CHECKING, TypeVar +from typing_extensions import deprecated + +from torch._utils_internal import justknobs_check + + +# Types saved/loaded in configs +CONFIG_TYPES = (int, float, bool, type(None), str, list, set, tuple, dict) + +# Immutable scalar types that don't need deepcopy when returned from configs. +# Everything else is defensively copied to prevent accidental mutation. +_IMMUTABLE_CONFIG_TYPES = (int, float, bool, type(None), str, tuple) + + +# Duplicated, because mypy needs these types statically +T = TypeVar("T", bound=int | float | bool | str | list | set | tuple | dict | None) + + +_UNSET_SENTINEL = object() + + +@dataclass(kw_only=True) +class _Config(Generic[T]): + """Represents a config with richer behaviour than just a default value. + :: + i.e. + foo = Config(justknob="//foo:bar", default=False) + install_config_module(...) + + This configs must be installed with install_config_module to be used + + Precedence Order: + alias: If set, the directly use the value of the alias. + env_name_force: If set, this environment variable has precedence over + everything after this. + If multiple env variables are given, the precedence order is from + left to right. + user_override: If a user sets a value (i.e. foo.bar=True), that + has precedence over everything after this. User overrides are thread-local. + env_name_default: If set, this environment variable will override everything + after this. + If multiple env variables are given, the precedence order is from + left to right. + justknob: If this pytorch installation supports justknobs, that will + override defaults, but will not override the user_override precedence. + default: This value is the lowest precedence, and will be used if nothing is + set. + + Environment Variables: + These are interpreted to be either "0" or "1" to represent true and false. + + Arguments: + justknob: the name of the feature / JK. In OSS this is unused. + default: is the value to default this knob to in OSS. + alias: The alias config to read instead. + env_name_force: The environment variable, or list of, to read that is a FORCE + environment variable. I.e. it overrides everything except for alias. + env_name_default: The environment variable, or list of, to read that changes the + default behaviour. I.e. user overrides take preference. + """ + + default: T | object + justknob: str | None = None + env_name_default: list[str] | None = None + env_name_force: list[str] | None = None + value_type: type | None = None + alias: str | None = None + # Deprecation support + deprecated: bool = False + deprecation_message: str | None = None + + def __post_init__(self) -> None: + self.env_name_default = _Config.string_or_list_of_string_to_list( + self.env_name_default + ) + self.env_name_force = _Config.string_or_list_of_string_to_list( + self.env_name_force + ) + + if self.alias is not None: + if ( + self.default is not _UNSET_SENTINEL + or self.justknob is not None + or self.env_name_default is not None + or self.env_name_force is not None + ): + raise AssertionError( + "if alias is set, none of {default, justknob, \ + env_name_default and env_name_force} can be set" + ) + + @staticmethod + def string_or_list_of_string_to_list( + val: str | list[str] | None, + ) -> list[str] | None: + if val is None: + return None + if isinstance(val, str): + return [val] + if not isinstance(val, list): + raise AssertionError(f"val is not a list, got {type(val)}") + return val + + +# In runtime, we unbox the Config[T] to a T, but typechecker cannot see this, +# so in order to allow for this dynamic behavior to work correctly with +# typechecking we are going to lie to the typechecker that Config[T] returns +# a T. +if TYPE_CHECKING: + + def Config( + default: T | object = _UNSET_SENTINEL, + justknob: str | None = None, + env_name_default: str | list[str] | None = None, + env_name_force: str | list[str] | None = None, + value_type: type | None = None, + alias: str | None = None, + # Deprecation support + deprecated: bool = False, + deprecation_message: str | None = None, + ) -> T: ... + +else: + + def Config( + default: T | object = _UNSET_SENTINEL, + justknob: str | None = None, + env_name_default: str | list[str] | None = None, + env_name_force: str | list[str] | None = None, + value_type: type | None = None, + alias: str | None = None, + # Deprecation support + deprecated: bool = False, + deprecation_message: str | None = None, + ) -> _Config[T]: + return _Config( + default=default, + justknob=justknob, + env_name_default=env_name_default, + env_name_force=env_name_force, + value_type=value_type, + alias=alias, + # Deprecation support + deprecated=deprecated, + deprecation_message=deprecation_message, + ) + + +def _read_env_variable(name: str) -> bool | str | None: + value = os.environ.get(name) + if value == "1": + return True + if value == "0": + return False + return value + + +def install_config_module(module: ModuleType) -> None: + """ + Converts a module-level config into a `ConfigModule()`. + + See _config_typing.pyi for instructions on how to get the converted module to typecheck. + """ + + class ConfigModuleInstance(ConfigModule): + # __annotations__ is written to by Sphinx autodoc + _bypass_keys = { + "_hash_dirty_var", + "_hash_cache_var", + "_get_dict_dirty_keys_var", + "_get_dict_cache_var", + "__annotations__", + } + + def visit( + source: ModuleType | type, + dest: ModuleType | SubConfigProxy, + prefix: str, + ) -> None: + """Walk the module structure and move everything to module._config""" + type_hints = inspect.get_annotations(source) + for key, value in list(source.__dict__.items()): + if ( + key.startswith("__") + or isinstance(value, (ModuleType, FunctionType)) + or ( + hasattr(value, "__module__") + and ( + value.__module__ == "typing" + or value.__module__.startswith("collections.abc") + ) + ) + # Handle from torch.utils._config_module import Config + or (isinstance(value, type) and issubclass(value, _Config)) + ): + continue + + name = f"{prefix}{key}" + annotated_type = type_hints.get(key, None) + if isinstance(value, CONFIG_TYPES): + config[name] = _ConfigEntry( + _Config(default=value, value_type=annotated_type), name + ) + if dest is module: + delattr(module, key) + elif isinstance(value, _Config): + if annotated_type is not None and value.value_type is None: + value.value_type = annotated_type + + config[name] = _ConfigEntry(value, name) + + if dest is module: + delattr(module, key) + elif isinstance(value, type): + if value.__module__ != module.__name__: + raise AssertionError( + f"subconfig class {value} must be defined in module {module.__name__}" + ) + # a subconfig with `class Blah:` syntax + proxy = SubConfigProxy(module, f"{name}.") + visit(value, proxy, f"{name}.") + if dest is module: + setattr(dest, key, proxy) + else: + dest.__dict__[key] = proxy + else: + raise AssertionError(f"Unhandled config {key}={value} ({type(value)})") + + config: dict[str, _ConfigEntry] = {} + + compile_ignored_keys = get_assignments_with_compile_ignored_comments(module) + + visit(module, module, "") + module._config = config # type: ignore[attr-defined] + module._compile_ignored_keys = compile_ignored_keys # type: ignore[attr-defined] + module.__class__ = ConfigModuleInstance + module._hash_dirty_var = ContextVar(f"{module.__name__}._hash_dirty", default=True) # type: ignore[attr-defined] # pyrefly: ignore[missing-attribute] + module._hash_cache_var = ContextVar( # pyrefly: ignore[missing-attribute] + f"{module.__name__}._hash_cache", default=None + ) # type: ignore[attr-defined] + module._get_dict_dirty_keys_var = ContextVar( # pyrefly: ignore[missing-attribute] + f"{module.__name__}._get_dict_dirty_keys", default=None + ) # type: ignore[attr-defined] + module._get_dict_cache_var = ContextVar( # pyrefly: ignore[missing-attribute] + f"{module.__name__}._get_dict_cache", default=None + ) # type: ignore[attr-defined] + + +COMPILE_IGNORED_MARKER = "@compile_ignored" + + +# Gets all the keys (i.e. assignments) with a @compile_ignored comment +def get_assignments_with_compile_ignored_comments(module: ModuleType) -> set[str]: + source_code = inspect.getsource(module) + assignments = set() + + # Tokenize the source code to retrieve comments + tokens = tokenize.tokenize(io.BytesIO(source_code.encode("utf-8")).readline) + current_comment = "", -1 + prev_name = "" + + for token in tokens: + if token.type == tokenize.COMMENT: + prev_name = "" + maybe_current = token.string.strip() + if COMPILE_IGNORED_MARKER in maybe_current: + if current_comment != ("", -1): + raise AssertionError(f"unconsumed {COMPILE_IGNORED_MARKER}") + current_comment = maybe_current, token.start[0] + elif token.type == tokenize.NAME: + # Only accept the first name token, to handle if you have + # something like foo: Bar = ... + if not prev_name: + prev_name = token.string + elif token.type == tokenize.OP and token.string == "=": + # Check if the current assignment follows a comment + # with COMPILE_IGNORED_MARKER + if ( + COMPILE_IGNORED_MARKER in current_comment[0] + and current_comment[1] == token.start[0] - 1 + ): + assignments.add(prev_name) + current_comment = "", -1 # reset + prev_name = "" + if current_comment != ("", -1): + raise AssertionError(f"unconsumed {COMPILE_IGNORED_MARKER}") + return assignments + + +_GetDictCacheKey = tuple[tuple[str, ...], tuple[str, ...], bool] + + +@dataclass +class _ConfigEntry: + # The default value specified in the configuration + default: Any + # The type of the configuration value + value_type: type + # The value specified by the user when they overrode the configuration + # _UNSET_SENTINEL indicates the value is not set. + user_override: ContextVar[object] + # The justknob to check for this config + justknob: str | None = None + # environment variables are read at install time + env_value_force: Any = _UNSET_SENTINEL + env_value_default: Any = _UNSET_SENTINEL + # Used to work around bad assumptions in unittest.mock.patch + # The code to blame is + # https://github.com/python/cpython/blob/94a7a4e22fb8f567090514785c69e65298acca42/Lib/unittest/mock.py#L1637 + # Essentially, mock.patch requires, that if __dict__ isn't accessible + # (which it isn't), that after delattr is called on the object, the + # object must throw when hasattr is called. Otherwise, it doesn't call + # setattr again. + # Technically we'll have an intermediate state of hiding the config while + # mock.patch is unpatching itself, but it calls setattr after the delete + # call so the final state is correct. It's just very unintuitive. + # upstream bug - python/cpython#126886 + hide: bool = False + alias: str | None = None + # Deprecation support + deprecated: bool = False + deprecation_message: str | None = None + _deprecation_warned: bool = False + + def __init__(self, config: _Config, name: str) -> None: + self.default = config.default + self.value_type = ( + config.value_type if config.value_type is not None else type(self.default) + ) + self.justknob = config.justknob + self.alias = config.alias + # Deprecation fields + self.deprecated = config.deprecated + self.deprecation_message = config.deprecation_message + self._deprecation_warned = False + + self.user_override = ContextVar(name, default=_UNSET_SENTINEL) + if config.env_name_default is not None: + for val in config.env_name_default: + if (env_value := _read_env_variable(val)) is not None: + self.env_value_default = env_value + break + if config.env_name_force is not None: + for val in config.env_name_force: + if (env_value := _read_env_variable(val)) is not None: + self.env_value_force = env_value + break + + # Ensure justknobs and envvars are allowlisted types + if self.justknob is not None and self.default is not None: + if not isinstance(self.default, bool): + raise AssertionError( + f"justknobs only support booleans, {self.default} is not a boolean" + ) + if self.value_type is not None and ( + config.env_name_default is not None or config.env_name_force is not None + ): + if self.value_type not in ( + bool, + str, + Optional[bool], # noqa: UP045 + Optional[str], # noqa: UP045 + ): + raise AssertionError( + f"envvar configs only support (optional) booleans or strings, {self.value_type} is neither" + ) + + +class ConfigModule(ModuleType): + # NOTE: This should be kept in sync with _config_typing.pyi. + + # The actual configuration settings. E.g., torch._dynamo.config.debug + # would live as "debug" in the key, and torch._inductor.config.triton.cudagraphs + # maps as "triton.cudagraphs". See discussion on the class for meaning of various sub items + _config: dict[str, _ConfigEntry] + _bypass_keys: set[str] + _compile_ignored_keys: set[str] + _hash_dirty_var: ContextVar[bool] + _hash_cache_var: ContextVar[bytes | None] + # Per-thread cache state, backed by ContextVar so each thread/context gets + # its own dirty set and cache (config values are per-thread via ContextVar). + # None means fully dirty (initial state or >_GET_DICT_DIRTY_KEYS_CAP keys + # changed); empty set means the last _get_dict result is up to date. + _get_dict_dirty_keys_var: ContextVar[set[str] | None] + _get_dict_cache_var: ContextVar[dict[_GetDictCacheKey, dict[str, Any]]] + + def __init__(self) -> None: + raise NotImplementedError( + f"use {__name__}.install_config_module(sys.modules[__name__])" + ) + + def _warn_if_deprecated(self, name: str, config: _ConfigEntry) -> None: + """Issue deprecation warning for config if not already warned.""" + if config.deprecated and not config._deprecation_warned: + import warnings + + msg = f"{self.__name__}.{name} is deprecated" + if config.deprecation_message: + msg += f" and {config.deprecation_message}" + msg += ". It will be removed in a future version of PyTorch." + warnings.warn(msg, FutureWarning, stacklevel=3) + config._deprecation_warned = True + + def __setattr__(self, name: str, value: object) -> None: + if name in self._bypass_keys: + super().__setattr__(name, value) + elif name not in self._config: + raise AttributeError(f"{self.__name__}.{name} does not exist") + else: + # Issue deprecation warning on write (once per config) + config = self._config[name] + self._warn_if_deprecated(name, config) + + if config.alias is not None: + self._set_alias_val(config, value) + else: + config.user_override.set(value) + self._hash_dirty_var.set(True) + self._mark_get_dict_dirty(name) + # Avoid a redundant instance-__dict__ write: hide defaults to False on + # the class and is only ever set True by __delattr__ (the mock.patch + # workaround), so only clear it when it is actually set. + if config.hide: + config.hide = False + + def __getattr__(self, name: str) -> Any: + try: + config = self._config[name] + + if config.hide: + raise AttributeError(f"{self.__name__}.{name} does not exist") + + # Issue deprecation warning on read (once per config) + self._warn_if_deprecated(name, config) + + alias_val = self._get_alias_val(config) + if alias_val is not _UNSET_SENTINEL: + return alias_val + + if config.env_value_force is not _UNSET_SENTINEL: + return config.env_value_force + + user_override = config.user_override.get() + if user_override is not _UNSET_SENTINEL: + return user_override + + if config.env_value_default is not _UNSET_SENTINEL: + return config.env_value_default + + if config.justknob is not None: + # JK only supports bools and ints + return justknobs_check(name=config.justknob, default=config.default) + + # Reference types can still be modified, so copy them to + # user_overrides to prevent accidental mutation of defaults. + if not isinstance(config.default, _IMMUTABLE_CONFIG_TYPES): + config.user_override.set(copy.deepcopy(config.default)) + return config.user_override.get() + return config.default + + except KeyError as e: + # make hasattr() work properly + raise AttributeError(f"{self.__name__}.{name} does not exist") from e + + def __delattr__(self, name: str) -> None: + self._hash_dirty_var.set(True) + self._mark_get_dict_dirty(name) + # must support delete because unittest.mock.patch deletes + # then recreate things + self._config[name].user_override.set(_UNSET_SENTINEL) + self._config[name].hide = True + + def _get_alias_module_and_name( + self, entry: _ConfigEntry + ) -> tuple[ModuleType, str] | None: + alias = entry.alias + if alias is None: + return None + module_name, constant_name = alias.rsplit(".", 1) + try: + module = importlib.import_module(module_name) + except ImportError as e: + raise AttributeError(f"config alias {alias} does not exist") from e + return module, constant_name + + def _get_alias_val(self, entry: _ConfigEntry) -> Any: + data = self._get_alias_module_and_name(entry) + if data is None: + return _UNSET_SENTINEL + module, constant_name = data + constant_value = getattr(module, constant_name) + return constant_value + + def _set_alias_val(self, entry: _ConfigEntry, val: Any) -> None: + data = self._get_alias_module_and_name(entry) + if data is None: + raise AssertionError( + "alias data should not be None when setting alias value" + ) + module, constant_name = data + setattr(module, constant_name, val) + + _GET_DICT_DIRTY_KEYS_CAP = 16 + + def _mark_get_dict_dirty(self, name: str) -> None: + dirty = self._get_dict_dirty_keys_var.get() + if dirty is None: + return + dirty.add(name) + if len(dirty) > self._GET_DICT_DIRTY_KEYS_CAP: + self._get_dict_dirty_keys_var.set(None) + + def _is_default(self, name: str) -> bool: + """ + Returns true if the config is at its default value. + configs overridden by the env are not considered default. + """ + config_val = self._config[name] + # The config is not overridden by the user, and the env_value_default + # is different from the default value (meaning user has set the env to + # change the default value). + not_set_env_default = ( + config_val.env_value_default is _UNSET_SENTINEL + or config_val.env_value_default == config_val.default + ) + not_set_env_force = ( + config_val.env_value_force is _UNSET_SENTINEL + or config_val.env_value_force == config_val.default + ) + + unset = config_val.user_override.get() is _UNSET_SENTINEL + # Handle reference types specially to avoid spammy warnings + if not isinstance(config_val.default, _IMMUTABLE_CONFIG_TYPES): + unset = unset or config_val.user_override.get() == config_val.default + return unset and not_set_env_default and not_set_env_force + + def _get_dict( + self, + ignored_keys: list[str] | None = None, + ignored_prefixes: list[str] | None = None, + skip_default: bool = False, + readonly_values: bool = False, + ) -> dict[str, Any]: + """Export a dictionary of current configuration keys and values. + + This function is designed to provide a single point which handles + accessing config options and exporting them into a dictionary. + This is used by a number of different user facing export methods + which all have slightly different semantics re: how and what to + skip. + If a config is aliased, it skips this config. + + Arguments: + ignored_keys are keys that should not be exported. + ignored_prefixes are prefixes that if a key matches should + not be exported + skip_default does two things. One if a key has not been modified + it skips it. + readonly_values when True, enables caching of the result. + The caller owns the returned dict but must not mutate + its values. When False (default), no caching is used. + """ + + keys_to_update, config = None, None + cache_key = ( + tuple(ignored_keys) if ignored_keys else (), + tuple(ignored_prefixes) if ignored_prefixes else (), + skip_default, + ) + + # Try to take a shortcut and only update dirty keys on top of a cached base. + cache = self._get_dict_cache_var.get() + if readonly_values: + if cache is None: + cache = {} + self._get_dict_cache_var.set(cache) + dirty_keys = self._get_dict_dirty_keys_var.get() + cached = cache.get(cache_key) + if cached is not None and dirty_keys is not None: + # Shortcut: copy the cached base and update only dirty keys. + # The cache entry itself is never mutated. + keys_to_update = dirty_keys + config = dict(cached) + elif dirty_keys is None: + # Fully dirty — clear entire cache and recompute + cache = {} + self._get_dict_cache_var.set(cache) + self._get_dict_dirty_keys_var.set(set()) + + # Recompute everything otherwise. + if keys_to_update is None: + keys_to_update = self._config.keys() + if config is None: + config = {} + + for key in keys_to_update: + entry = self._config[key] + if entry.alias is not None: + config.pop(key, None) + continue + if ignored_keys and key in ignored_keys: + config.pop(key, None) + continue + if ignored_prefixes: + if any(key.startswith(prefix) for prefix in ignored_prefixes): + config.pop(key, None) + continue + if skip_default and self._is_default(key): + config.pop(key, None) + continue + + # Read value directly, bypassing __getattr__ overhead + # (deprecation warnings, alias resolution). + user_override = entry.user_override.get() + if entry.env_value_force is not _UNSET_SENTINEL: + val = entry.env_value_force + elif user_override is not _UNSET_SENTINEL: + val = user_override + elif entry.env_value_default is not _UNSET_SENTINEL: + val = entry.env_value_default + elif entry.justknob is not None: + val = justknobs_check(name=entry.justknob, default=entry.default) + else: + val = entry.default + if not isinstance(val, _IMMUTABLE_CONFIG_TYPES): + val = copy.deepcopy(val) + config[key] = val + + if readonly_values and cache_key not in cache: + cache[cache_key] = dict(config) + return config + + def get_type(self, config_name: str) -> type: + return self._config[config_name].value_type + + def save_config(self) -> bytes: + """Convert config to a pickled blob""" + ignored_keys = getattr(self, "_save_config_ignore", []) + return pickle.dumps( + self._get_dict(ignored_keys=ignored_keys, readonly_values=True), + protocol=2, + ) + + def save_config_portable( + self, *, ignore_private_configs: bool = True, readonly_values: bool = False + ) -> dict[str, Any]: + """Convert config to portable format""" + prefixes = [] + if ignore_private_configs: + prefixes.append("_") + prefixes.extend(getattr(self, "_cache_config_ignore_prefix", [])) + config = self._get_dict( + ignored_prefixes=prefixes, readonly_values=readonly_values + ) + factory_keys = getattr(self, "_cache_config_factory_keys", []) + if factory_keys: + for key in factory_keys: + if key in config and config[key] is not None: + instance = config[key]() + if hasattr(instance, "uuid"): + config[key] = instance.uuid() + else: + raise RuntimeError( + f"Config '{key}' is set to {config[key]} which does not " + f"implement uuid(). Implement uuid() for cache key " + f"participation." + ) + return config + + def codegen_config(self) -> str: + """Convert config to Python statements that replicate current config. + This does NOT include config settings that are at default values. + """ + + # additional imports required + imports = set() + + def get_module_name(func: Callable, add_dot: bool) -> str: + module_name = func.__module__ + if module_name == "builtins": + module_name = "" + if add_dot and module_name != "": + module_name += "." + return module_name + + def add_import(func: Callable) -> None: + module_name = get_module_name(func, False) + if module_name: + imports.add(module_name) + + def list_of_callables_to_string(v: list | set) -> list[str]: + return [f"{get_module_name(item, True)}{item.__name__}" for item in v] + + def importable_callable(v: Any) -> bool: + # functools.partial has no attributes below but is a callable + return callable(v) and hasattr(v, "__module__") and hasattr(v, "__name__") + + def importable_ref(func: Any) -> tuple[str, str] | None: + try: + module_name = getattr(func, "__module__", None) + qualname = getattr(func, "__qualname__", None) + if ( + not callable(func) + or not isinstance(module_name, str) + or not isinstance(qualname, str) + or not module_name + or not qualname + or module_name == "__main__" + or "<" in qualname + ): + return None + names = module_name.split(".") + qualname.split(".") + if any( + not name.isidentifier() or keyword.iskeyword(name) for name in names + ): + return None + resolved = importlib.import_module(module_name) + for name in qualname.split("."): + resolved = getattr(resolved, name) + if resolved is not func: + return None + import_name = "" if module_name == "builtins" else module_name + prefix = f"{import_name}." if import_name else "" + return f"{prefix}{qualname}", import_name + except Exception: + return None + + def serialize_partial_arg(val: Any) -> str: + if type(val) in (type(None), bool, int, str, bytes) or ( + type(val) is float and math.isfinite(val) + ): + return repr(val) + if type(val) not in (list, tuple, dict): + raise ValueError( + f"unsupported functools.partial argument type {type(val).__name__}" + ) + + if type(val) in (list, tuple): + for item in val: + serialize_partial_arg(item) + else: + for key, item in val.items(): + serialize_partial_arg(key) + serialize_partial_arg(item) + return repr(val) + + def get_partial_line(mod, k, v) -> str: # type: ignore[no-untyped-def] + if type(v) is not functools.partial: + return f"# {mod}.{k} omitted: unsupported partial subclass" + func_info = importable_ref(v.func) + if func_info is None: + return f"# {mod}.{k} omitted: partial callable cannot be re-imported" + func_ref, import_name = func_info + try: + parts = [func_ref] + parts.extend(serialize_partial_arg(arg) for arg in v.args) + if v.keywords: + parts.append(f"**{serialize_partial_arg(v.keywords)}") + expression = f"functools.partial({', '.join(parts)})" + compile(expression, "", "eval") + except Exception: + return f"# {mod}.{k} omitted: partial arguments cannot be serialized" + if import_name: + imports.add(import_name) + imports.add("functools") + return f"{mod}.{k} = {expression}" + + def get_config_line(mod, k, v) -> str: # type: ignore[no-untyped-def] + """ + Return a string version of the config line. + Handle v when v is a callable, or a list/dict of callables. Add import statements for callables if necessary. + We assume that the value of a single config won't be a mix of callables and non-callables. + + Example output: + import logging + import _warnings + torch._dynamo.config.reorderable_logging_functions = { _warnings.warn, logging.warn, print } + """ + if isinstance(v, functools.partial): + return get_partial_line(mod, k, v) + elif importable_callable(v): + add_import(v) + return f"{mod}.{k} = {get_module_name(v, True)}{v.__name__}" + elif isinstance(v, (list, set)) and all( + importable_callable(item) for item in v + ): + for item in v: + add_import(item) + v_list = list_of_callables_to_string(v) + if isinstance(v, list): + return f"{mod}.{k} = {v_list}" + else: + return f"{mod}.{k} = {{ {', '.join(v_list)} }}" + else: + return f"{mod}.{k} = {v!r}" + + lines = [] + mod = self.__name__ + for k, v in self._get_dict( + ignored_keys=getattr(self, "_save_config_ignore", []), + skip_default=True, + readonly_values=True, + ).items(): + lines.append(get_config_line(mod, k, v)) + for import_name in imports: + lines.insert(0, f"import {import_name}") + return "\n".join(lines) + + def get_hash(self) -> bytes: + """Hashes the configs that are not compile_ignored""" + if self._hash_dirty_var.get() or self._hash_cache_var.get() is None: + dict_to_hash = self._get_dict( + ignored_keys=list(self._compile_ignored_keys), readonly_values=True + ) + string_to_hash = repr(sorted(dict_to_hash.items())) + self._hash_cache_var.set( + hashlib.md5( + string_to_hash.encode("utf-8"), usedforsecurity=False + ).digest() + ) + self._hash_dirty_var.set(False) + result = self._hash_cache_var.get() + if result is None: + raise AssertionError( + "_hash_cache_var should not be None after recomputation" + ) + return result + + @deprecated( + "`config.to_dict()` has been deprecated. It no longer changes the underlying config." + " use `config.get_config_copy()` instead if you just want a copy of the config, or " + "config.load_config if you need mutable access", + category=FutureWarning, + ) + def to_dict(self) -> dict[str, Any]: + return self.get_config_copy() + + @deprecated( + "`config.shallow_copy_dict()` has been deprecated. It no longer changes the underlying config." + " use `config.get_config_copy()` instead if you just want a copy of the config, or " + "config.load_config if you need mutable access", + category=FutureWarning, + ) + def shallow_copy_dict(self) -> dict[str, Any]: + return self.get_config_copy() + + def load_config(self, maybe_pickled_config: bytes | dict[str, Any]) -> None: + """Restore from a prior call to save_config() or shallow_copy_dict()""" + if not isinstance(maybe_pickled_config, dict): + config = pickle.loads(maybe_pickled_config) + else: + config = maybe_pickled_config + for k, v in config.items(): + if k in self._config: + setattr(self, k, v) + else: + from torch._dynamo.utils import warn_once + + warn_once(f"key {k} with value {v} is not understood by this config") + + def get_config_copy(self) -> dict[str, Any]: + return self._get_dict() + + def get_serializable_config_copy(self) -> dict[str, Any]: + return self._get_dict(ignored_keys=getattr(self, "_save_config_ignore", [])) + + def patch( + self, + arg1: str | dict[str, Any] | None = None, + arg2: Any = None, + **kwargs: dict[str, Any], + ) -> "ContextDecorator": + """ + Decorator and/or context manager to make temporary changes to a config. Note that patched settings are thread-local. + + As a decorator: + + @config.patch("name", val) + @config.patch(name1=val1, name2=val2) + @config.patch({"name1": val1, "name2", val2}) + def foo(...): + ... + + As a context manager: + + with config.patch("name", val): + ... + """ + changes: dict[str, Any] + if arg1 is not None: + if arg2 is not None: + if not isinstance(arg1, str): + raise AssertionError( + "first argument must be a string when passing 2 positional args to patch" + ) + # patch("key", True) syntax + changes = {arg1: arg2} + else: + if not isinstance(arg1, dict): + raise AssertionError( + "first argument must be a dict when passing a single positional arg to patch" + ) + # patch({"key": True}) syntax + changes = arg1 + if kwargs: + raise AssertionError( + "cannot pass both positional and keyword arguments to patch" + ) + else: + # patch(key=True) syntax + changes = kwargs + if arg2 is not None: + raise AssertionError( + "second positional argument is only valid when first argument is a key string" + ) + if not isinstance(changes, dict): + raise AssertionError(f"expected `dict` got {type(changes)}") + config = self + + class ConfigPatch(ContextDecorator): + def __init__(self) -> None: + self.changes = changes + self._prior: ContextVar[tuple[dict[str, Any], ...]] = ContextVar( + f"{config.__name__}.ConfigPatch[{id(self)}]", + default=(), + ) + + def __enter__(self) -> None: + prior: dict[str, Any] = {} + for key in self.changes: + # KeyError on invalid entry + prior[key] = config.__getattr__(key) + prior_stack = self._prior.get() + self._prior.set((*prior_stack, prior)) + try: + for k, v in self.changes.items(): + config.__setattr__(k, v) + except Exception: + self._prior.set(prior_stack) + raise + + def __exit__(self, exc_type, exc_val, exc_tb): # type: ignore[no-untyped-def] + prior_stack = self._prior.get() + if not prior_stack: + raise AssertionError( + "prior should not be empty when exiting ConfigPatch" + ) + prior = prior_stack[-1] + self._prior.set(prior_stack[:-1]) + for k, v in prior.items(): + config.__setattr__(k, v) + + return ConfigPatch() + + def _make_closure_patcher(self, **changes: dict[str, Any]) -> Any: + """ + A lower-overhead version of patch() for things on the critical path. + + Usage: + + # do this off the critical path + change_fn = config.make_closure_patcher(foo=True) + + ... + + revert = change_fn() + try: + ... + finally: + revert() + + """ + config = self._config + + def change() -> Callable[[], None]: + prior = {k: config[k].user_override.get() for k in changes} + for k, v in changes.items(): + config[k].user_override.set(v) + self._hash_dirty_var.set(True) + self._mark_get_dict_dirty(k) + + def revert() -> None: + for k, v in prior.items(): + config[k].user_override.set(v) + self._hash_dirty_var.set(True) + self._mark_get_dict_dirty(k) + + return revert + + return change + + +class ContextDecorator(contextlib.ContextDecorator): + """ + Same as contextlib.ContextDecorator, but with support for + `unittest.TestCase` + """ + + def __enter__(self) -> None: + raise NotImplementedError("NYI") + + def __exit__(self, exc_type, exc_val, exc_tb) -> NoReturn: # type: ignore[no-untyped-def] + raise NotImplementedError("NYI") + + def __call__(self, func: Callable[[Any], Any]) -> Any: + if isinstance(func, type) and issubclass(func, unittest.TestCase): + + class _TestCase(func): # type: ignore[valid-type, misc] + @classmethod + def setUpClass(cls) -> None: + self.__enter__() + try: + super().setUpClass() + except Exception: + self.__exit__(None, None, None) + raise + + @classmethod + def tearDownClass(cls) -> None: + try: + super().tearDownClass() + finally: + self.__exit__(None, None, None) + + _TestCase.__name__ = func.__name__ + _TestCase.__qualname__ = func.__qualname__ + _TestCase.__module__ = func.__module__ + + return _TestCase + + return super().__call__(func) + + +class SubConfigProxy: + """ + Shim to redirect to main config. + `config.triton.cudagraphs` maps to _config["triton.cudagraphs"] + """ + + def __init__(self, config: object, prefix: str) -> None: + # `super().__setattr__` to bypass custom `__setattr__` + super().__setattr__("_config", config) + super().__setattr__("_prefix", prefix) + + def __setattr__(self, name: str, value: object) -> None: + return self._config.__setattr__(self._prefix + name, value) + + def __getattr__(self, name: str) -> Any: + return self._config.__getattr__(self._prefix + name) + + def __delattr__(self, name: str) -> None: + return self._config.__delattr__(self._prefix + name) + + +def get_tristate_env(name: str, default: Any = None) -> bool | None: + value = os.environ.get(name) + if value == "1": + return True + if value == "0": + return False + return default + + +def inherit_fields_from(parent_cls): + def wrapper(child_cls): + for k, v in parent_cls.__dict__.items(): + # copy fields that are not private and not overridden + if not k.startswith("_") and k not in child_cls.__dict__: + setattr(child_cls, k, v) + return child_cls + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_config_typing.pyi b/.venv/lib/python3.12/site-packages/torch/utils/_config_typing.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d145db9364a4180ccd7186fb9387bfb0ade07b3d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_config_typing.pyi @@ -0,0 +1,38 @@ +# mypy: allow-untyped-defs +from typing import Any, TYPE_CHECKING + +""" +This was semi-automatically generated by running + + stubgen torch.utils._config_module.py + +And then manually extracting the methods of ConfigModule and converting them into top-level functions. + +This file should be imported into any file that uses install_config_module like so: + + if TYPE_CHECKING: + from torch.utils._config_typing import * # noqa: F401, F403 + + from torch.utils._config_module import install_config_module + + # adds patch, save_config, etc + install_config_module(sys.modules[__name__]) + +Note that the import should happen before the call to install_config_module(), otherwise runtime errors may occur. +""" + +if not TYPE_CHECKING: # noqa: PYI002 + raise AssertionError("Do not use at runtime") + +def save_config() -> bytes: ... +def save_config_portable( + *, ignore_private_configs: bool = True, readonly_values: bool = False +) -> dict[str, Any]: ... +def codegen_config() -> str: ... +def get_hash() -> bytes: ... +def to_dict() -> dict[str, Any]: ... +def shallow_copy_dict() -> dict[str, Any]: ... +def load_config(config: bytes | dict[str, Any]) -> None: ... +def get_config_copy() -> dict[str, Any]: ... +def get_serializable_config_copy() -> dict[str, Any]: ... +def patch(arg1: str | dict[str, Any] | None = None, arg2: Any = None, **kwargs): ... diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_content_store.py b/.venv/lib/python3.12/site-packages/torch/utils/_content_store.py new file mode 100644 index 0000000000000000000000000000000000000000..eb8cbaffec662e18db7699a7c5fc5120dfb471c3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_content_store.py @@ -0,0 +1,241 @@ +# mypy: allow-untyped-defs +# This module provides a FAST (on GPU) content addressable store for storages +# (and tensors on top of them) with VERY WEAK portability guarantees (e.g., +# don't expect CPU/CUDA to address to the same hash, don't expect it to be +# portable across devices) that is NOT cryptographically secure. In return, +# we are able to hash 40G of tensor data on GPU in less than a second, +# compared to running SHA-1 in CPU which would take a minute or so. The primary +# use case is for efficiently snapshotting intermediate tensor data for +# offline debugging, but it's been put in this module in case you think of +# another use case for it. The hash function could be replaced with a +# straight reimplementation of SHA-1, which would give us much stronger +# portability guarantees. +# +# WARNING: THERE IS NO BC/FC GUARANTEE FOR THIS FORMAT! If you need to format +# shift the result, consider packing it into a single torch.save object +# with traditional view sharing. +# +# Because of the weak portability guarantees, you can only write to the +# content store from a single process; we don't provide any capability +# of "reopening" a content store to add more things to it. But we don't +# assume that you can keep all of the tensors you want to add to the store +# in memory at once, because you probably can't! Nor do we assume that +# you know a priori whether or not two storages can be deduplicated or not. +# +# Note: only storages are content-addressed; tensors are name addressed +# +# Note: our padding strategy means that [1, 0] and [1] int16 tensors would +# map to the same (padded) storage. We think this will be immaterial for most +# users. + +import ctypes +import functools +import hashlib +import os.path +import struct +from collections import defaultdict + +import torch +import torch._prims as prims +import torch._utils +import torch.nn.functional as F +from torch.multiprocessing.reductions import StorageWeakRef + + +def lazy_compile(**compile_kwargs): + """Lazily wrap a function with torch.compile on the first call + + This avoids eagerly importing dynamo. + """ + + def decorate_fn(fn): + @functools.wraps(fn) + def compile_hook(*args, **kwargs): + compiled_fn = torch.compile(fn, **compile_kwargs) + globals()[fn.__name__] = functools.wraps(fn)(compiled_fn) + return compiled_fn(*args, **kwargs) + + return compile_hook + + return decorate_fn + + +# Use of torch.compile is mandatory for (1) good memory usage +# and (2) xor_sum implementation. This is our first instance of +# using PT2 to implement a kernel in PyTorch; if we get AOT capabilities +# it would be good to apply it here. +@lazy_compile(dynamic=True) +def hash_storage_kernel(x): + # The randint calls are carefully written to hit things we + # have lowerings for in inductor. Lack of unsigned 32-bit integer + # is a pain. + a = torch.randint( + -(2**31), 2**31, x.shape, device=x.device, dtype=torch.int32 + ).abs() + a = ((a % (2**31 - 1)) + 1).long() + b = ( + torch.randint(-(2**31), 2**31, x.shape, device=x.device, dtype=torch.int32) + .abs() + .long() + ) + # This is a standard shift-multiply universal hash family + # plus xor sum hash, using Philox to generate random numbers. + # Our Philox RNG is not deterministic across devices so + # don't use this for stable hashing. + # + # This assumes fixed length so you're also obligated to bucket + # by the length of tensor as well + return prims.xor_sum((a * x + b).int(), [0]) + + +# Returns a hex digest of the data in the storage. Guaranteed to be +# SHA-1 if stable_hash=True, otherwise it will consistent for a single +# process run but not necessarily across processes. +def hash_storage(storage: torch.UntypedStorage, *, stable_hash: bool = False) -> str: + import torch._dynamo + from torch._dynamo.utils import is_compile_supported + + device_type = storage.device.type + if stable_hash or not is_compile_supported(device_type): + cpu_storage = storage.cpu() + # TODO: make storage support buffer protocol so this isn't + # necessary + buf = (ctypes.c_byte * cpu_storage.nbytes()).from_address( + cpu_storage.data_ptr() + ) + sha1 = hashlib.sha1(usedforsecurity=False) + sha1.update(buf) + return sha1.hexdigest() + + # TODO: factor this into a random utility + if device_type == "cpu": + generator = torch._C.default_generator + elif device_type == "cuda": + generator = torch.cuda.default_generators[storage.device.index] + elif device_type == "mps": + generator = torch.mps._get_default_mps_generator() + elif device_type == "xpu": + generator = torch.xpu.default_generators[storage.device.index] + else: + raise AssertionError(f"unhandled device type {device_type}") + state = generator.get_state() + try: + generator.manual_seed(0) + x = torch.empty(0, dtype=torch.uint8, device=storage.device).set_(storage) # type: ignore[call-overload] + # The dtype-casting view cannot be compiled, and so the + # padding/reshaping also needs to be done externally even + # though it could be profitably fused + pad = -x.numel() % 4 + if pad > 0: + x = F.pad(x, (0, pad), "constant", 0) + x = x.view(torch.int32) + # We run the 32-bit hash five times with differing parameters to + # reduce chance of collision + ITER = 5 + cs = [hash_storage_kernel(x).item() for _ in range(ITER)] + return struct.pack(">" + "i" * ITER, *cs).hex() + finally: + generator.set_state(state) + + +class ContentStoreWriter: + # Structure: + # storages/ + # 00/ + # 0000..00 + # tensors/ + # name + def __init__(self, loc: str, stable_hash: bool = False) -> None: + self.loc: str = loc + self.seen_storage_hashes: set[str] = set() + self.stable_hash = stable_hash + + # TODO: offer some sort of non-blocking API to speed things up + def write_storage(self, storage: torch.UntypedStorage) -> str: + h = hash_storage(storage, stable_hash=self.stable_hash) + if h in self.seen_storage_hashes: + return h + # TODO: consider not using torch.save for this; we don't actually + # need any metadata for the storage + subfolder = os.path.join(self.loc, "storages") + os.makedirs(subfolder, exist_ok=True) + target = os.path.join(subfolder, h) + if os.path.exists(target): + return h + torch.save(storage, target) + self.seen_storage_hashes.add(h) + return h + + def compute_tensor_metadata(self, t: torch.Tensor, h=None): + if h is None: + h = hash_storage(t.untyped_storage(), stable_hash=self.stable_hash) + return ( + t.dtype, + h, + t.storage_offset(), + tuple(t.shape), + t.stride(), + torch._utils.get_tensor_metadata(t), + ) + + def write_tensor(self, name: str, t: torch.Tensor) -> None: + storage = t.untyped_storage() + h = self.write_storage(storage) + # TODO: Support more advanced snapshotting of requires_grad/grad/etc + d, f = os.path.split(name) + payload = self.compute_tensor_metadata(t, h=h) + subfolder = os.path.join(self.loc, "tensors", d) + os.makedirs(subfolder, exist_ok=True) + torch.save(payload, os.path.join(subfolder, f)) + + +class ContentStoreReader: + def __init__(self, loc: str, *, cache=True) -> None: + self.loc = loc + self.storage_cache: ( + dict[torch.device | None, dict[str, StorageWeakRef]] | None + ) = None + if cache: + self.storage_cache = defaultdict(dict) + + def read_storage(self, h: str, *, device=None) -> torch.UntypedStorage: + if device is not None: + device = torch.device(device) + ws = ( + self.storage_cache[device].get(h) + if self.storage_cache is not None + else None + ) + s: torch.UntypedStorage | None + if ws is not None: + s = torch.UntypedStorage._new_with_weak_ptr(ws.cdata) + if s is not None: + return s + s = torch.load( + os.path.join(self.loc, "storages", h), + weights_only=True, + map_location=device, + )._untyped_storage + if s is None: + raise AssertionError( + f"expected storage for hash {h} in {os.path.join(self.loc, 'storages')}, got None" + ) + if self.storage_cache is not None: + self.storage_cache[device][h] = StorageWeakRef(s) + return s + + def read_tensor_metadata(self, name: str): + fn = os.path.join(self.loc, "tensors", name) + if not os.path.exists(fn): + raise FileNotFoundError(fn) + return torch.load(fn, weights_only=True) + + def read_tensor(self, name: str, *, device=None) -> torch.Tensor: + dtype, h, storage_offset, size, stride, metadata = self.read_tensor_metadata( + name + ) + storage = self.read_storage(h, device=device) + t = torch.tensor([], dtype=dtype, device=storage.device) + t.set_(storage, storage_offset, size, stride) + torch._utils.set_tensor_metadata(t, metadata) + return t diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_contextlib.py b/.venv/lib/python3.12/site-packages/torch/utils/_contextlib.py new file mode 100644 index 0000000000000000000000000000000000000000..f1af9091e75538009b17322a855ea178205cb790 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_contextlib.py @@ -0,0 +1,170 @@ +# mypy: allow-untyped-defs +# Extra utilities for working with context managers that should have been +# in the standard library but are not + +import functools +import inspect +import sys +import warnings +from collections.abc import Callable +from typing import Any, cast, overload, TypeVar +from typing_extensions import Self + + +# Used for annotating the decorator usage of _DecoratorContextManager (e.g., +# 'no_grad' and 'enable_grad'). +# See https://mypy.readthedocs.io/en/latest/generics.html#declaring-decorators +FuncType = Callable[..., Any] +F = TypeVar("F", bound=FuncType) + + +def _wrap_generator(ctx_factory, func): + """ + Wrap each generator invocation with the context manager factory. + + The input should be a function that returns a context manager, + not a context manager itself, to handle one-shot context managers. + """ + + @functools.wraps(func) + def generator_context(*args, **kwargs): + gen = func(*args, **kwargs) + + # Generators are suspended and unsuspended at `yield`, hence we + # make sure the grad mode is properly set every time the execution + # flow returns into the wrapped generator and restored when it + # returns through our `yield` to our caller (see PR #49017). + try: + # Issuing `None` to a generator fires it up + with ctx_factory(): + response = gen.send(None) + + while True: + try: + # Forward the response to our caller and get its next request + request = yield response + + except GeneratorExit: + # Inform the still active generator about its imminent closure + with ctx_factory(): + gen.close() + raise + + except BaseException: + # Propagate the exception thrown at us by the caller + with ctx_factory(): + response = gen.throw(*sys.exc_info()) + + else: + # Pass the last request to the generator and get its response + with ctx_factory(): + response = gen.send(request) + + # We let the exceptions raised above by the generator's `.throw` or + # `.send` methods bubble up to our caller, except for StopIteration + except StopIteration as e: + # The generator informed us that it is done: take whatever its + # returned value (if any) was and indicate that we're done too + # by returning it (see docs for python's return-statement). + return e.value + + return generator_context + + +def context_decorator(ctx, func): + """ + Like contextlib.ContextDecorator. + + But with the following differences: + 1. Is done by wrapping, rather than inheritance, so it works with context + managers that are implemented from C and thus cannot easily inherit from + Python classes + 2. Wraps generators in the intuitive way (c.f. https://bugs.python.org/issue37743) + 3. Errors out if you try to wrap a class, because it is ambiguous whether + or not you intended to wrap only the constructor + + The input argument can either be a context manager (in which case it must + be a multi-shot context manager that can be directly invoked multiple times) + or a callable that produces a context manager. + """ + if callable(ctx) and hasattr(ctx, "__enter__"): + raise AssertionError( + f"Passed in {ctx} is both callable and also a valid context manager " + "(has __enter__), making it ambiguous which interface to use. If you " + "intended to pass a context manager factory, rewrite your call as " + "context_decorator(lambda: ctx()); if you intended to pass a context " + "manager directly, rewrite your call as context_decorator(lambda: ctx)" + ) + + if not callable(ctx): + + def ctx_factory(): + return ctx + + else: + ctx_factory = ctx + + if inspect.isclass(func): + raise RuntimeError( + "Cannot decorate classes; it is ambiguous whether or not only the " + "constructor or all methods should have the context manager applied; " + "additionally, decorating a class at definition-site will prevent " + "use of the identifier as a conventional type. " + "To specify which methods to decorate, decorate each of them " + "individually." + ) + + if inspect.isgeneratorfunction(func): + return _wrap_generator(ctx_factory, func) + + @functools.wraps(func) + def decorate_context(*args, **kwargs): + # pyrefly: ignore [bad-context-manager] + with ctx_factory(): + return func(*args, **kwargs) + + return decorate_context + + +class _DecoratorContextManager: + """Allow a context manager to be used as a decorator.""" + + def __call__(self, orig_func: F) -> F: + if inspect.isclass(orig_func): + warnings.warn( + "Decorating classes is deprecated and will be disabled in " + "future versions. You should only decorate functions or methods. " + "To preserve the current behavior of class decoration, you can " + "directly decorate the `__init__` method and nothing else.", + FutureWarning, + stacklevel=2, + ) + func = cast(F, lambda *args, **kwargs: orig_func(*args, **kwargs)) + else: + func = orig_func + + return cast(F, context_decorator(self.clone, func)) + + def __enter__(self) -> None: + raise NotImplementedError + + def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: + raise NotImplementedError + + def clone(self): + # override this method if your children class takes __init__ parameters + return self.__class__() + + +class _NoParamDecoratorContextManager(_DecoratorContextManager): + """Allow a context manager to be used as a decorator without parentheses.""" + + @overload + def __new__(cls, orig_func: F) -> F: ... # type: ignore[misc] + @overload + def __new__(cls, orig_func: None = None) -> Self: ... + + def __new__(cls, orig_func: F | None = None) -> Self | F: # type: ignore[misc] + if orig_func is None: + return super().__new__(cls) + return cls()(orig_func) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_cpp_embed_headers.py b/.venv/lib/python3.12/site-packages/torch/utils/_cpp_embed_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..88ab41aadffe75dd1bdbe0b3482b414f38b7e093 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_cpp_embed_headers.py @@ -0,0 +1,57 @@ +from collections.abc import Sequence +from pathlib import Path +from re import match as _match + + +def read_file(fname: Path | str) -> list[str]: + with open(fname, encoding="utf-8") as f: + return f.readlines() + + +def _embed_headers( + content: list[str], include_dirs: list[Path], processed_files: set[str] +) -> str: + for line_idx, cur_line in enumerate(content): + # Eliminate warning: `#pragma once in main file` + if cur_line.startswith("#pragma once"): + content[line_idx] = "" + continue + m = _match('^\\s*#include\\s*[<"]([^>"]+)[>"]', cur_line) + if m is None: + continue + for include_dir in include_dirs: + path = include_dir / m[1] + if not path.exists(): + continue + if str(path) in processed_files: + content[line_idx] = "" + continue + processed_files.add(str(path)) + content[line_idx] = _embed_headers( + read_file(path), include_dirs, processed_files + ) + break + return "".join(content) + + +def embed_headers( + fname: str, include_dirs: Sequence[str] | Sequence[Path] | str | None = None +) -> str: + if include_dirs is None: + base_dir = Path(__file__).parent.parent.parent + include_dirs = [base_dir, base_dir / "aten" / "src"] + elif isinstance(include_dirs, str): + include_dirs = [Path(include_dirs)] + else: + include_dirs = [Path(x) for x in include_dirs] + + return _embed_headers(read_file(fname), include_dirs, {fname}) + + +if __name__ == "__main__": + import sys + + if len(sys.argv) < 2: + print(f"Usage:\n {sys.argv[0]} filename") + sys.exit(1) + print(embed_headers(sys.argv[1])) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_cpp_extension_versioner.py b/.venv/lib/python3.12/site-packages/torch/utils/_cpp_extension_versioner.py new file mode 100644 index 0000000000000000000000000000000000000000..d1391dd9aaab0e920276c7046282ea1002346a15 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_cpp_extension_versioner.py @@ -0,0 +1,63 @@ +# mypy: allow-untyped-defs +import collections + + +Entry = collections.namedtuple("Entry", "version, hash") + + +def update_hash(seed, value): + # Good old boost::hash_combine + # https://www.boost.org/doc/libs/1_35_0/doc/html/boost/hash_combine_id241013.html + return seed ^ (hash(value) + 0x9E3779B9 + (seed << 6) + (seed >> 2)) + + +def hash_source_files(hash_value, source_files): + for filename in source_files: + with open(filename, "rb") as file: + hash_value = update_hash(hash_value, file.read()) + return hash_value + + +def hash_build_arguments(hash_value, build_arguments): + for group in build_arguments: + if group: + for argument in group: + hash_value = update_hash(hash_value, argument) + return hash_value + + +class ExtensionVersioner: + def __init__(self) -> None: + self.entries = {} + + def get_version(self, name): + entry = self.entries.get(name) + return None if entry is None else entry.version + + def bump_version_if_changed( + self, + name, + source_files, + build_arguments, + build_directory, + with_cuda, + with_sycl, + is_python_module, + is_standalone, + ): + hash_value = 0 + hash_value = hash_source_files(hash_value, source_files) + hash_value = hash_build_arguments(hash_value, build_arguments) + hash_value = update_hash(hash_value, build_directory) + hash_value = update_hash(hash_value, with_cuda) + hash_value = update_hash(hash_value, with_sycl) + hash_value = update_hash(hash_value, is_python_module) + hash_value = update_hash(hash_value, is_standalone) + + entry = self.entries.get(name) + if entry is None: + self.entries[name] = entry = Entry(0, hash_value) + elif hash_value != entry.hash: + self.entries[name] = entry = Entry(entry.version + 1, hash_value) + + return entry.version diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_cuda_debug.py b/.venv/lib/python3.12/site-packages/torch/utils/_cuda_debug.py new file mode 100644 index 0000000000000000000000000000000000000000..5ca35b27181e434de4c0f5149d6d29a2cd65164e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_cuda_debug.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +import textwrap +import traceback +import weakref +from typing import Any, TYPE_CHECKING + +import torch +from torch import Tensor +from torch.utils._python_dispatch import TorchDispatchMode +from torch.utils._pytree import tree_iter + + +if TYPE_CHECKING: + from torch.cuda import _POOL_HANDLE + + +class _TrackedTensorInfo: + __slots__ = ( + "weakref", + "creation_traceback_py", + "creation_traceback_cpp", + "deletion_traceback_py", + "data_ptr", + "device_index", + "_storage_data_ptr", + ) + + def __init__(self, tensor: Tensor) -> None: + from torch.utils import get_cpp_backtrace + + self.creation_traceback_py = "".join(traceback.format_stack()[:-3]) + self.creation_traceback_cpp = get_cpp_backtrace() + self.deletion_traceback_py: str | None = None + self.data_ptr = tensor.data_ptr() + self.device_index = tensor.device.index + + def on_release(_: weakref.ref[torch.UntypedStorage]) -> None: + try: + self.deletion_traceback_py = "".join(traceback.format_stack()[:-1]) + except Exception: + pass # don't raise under GC + + storage = tensor.untyped_storage() + self._storage_data_ptr = storage.data_ptr() + self.weakref: weakref.ref[torch.UntypedStorage] = weakref.ref( + storage, on_release + ) + + def is_alive(self) -> bool: + storage = self.weakref() + if storage is None: + return False + return storage.data_ptr() == self._storage_data_ptr + + +class _CUDAGraphInputLivenessTracker: + def __init__(self) -> None: + self._external_inputs: dict[int, _TrackedTensorInfo] = {} + self._internal_outputs: set[int] = set() + self._memory_snapshots: dict[_POOL_HANDLE, list[dict[str, Any]]] = {} + self._dispatch_mode: _TensorTrackingMode | None = None + + def start(self) -> None: + self._dispatch_mode = _TensorTrackingMode(self) + self._dispatch_mode.__enter__() + + def stop(self) -> None: + if self._dispatch_mode is not None: + mode, self._dispatch_mode = self._dispatch_mode, None + mode.__exit__(None, None, None) + + def track_external_input(self, tensor: Tensor) -> None: + data_ptr = tensor.data_ptr() + if ( + data_ptr not in self._internal_outputs + and data_ptr not in self._external_inputs + ): + self._external_inputs[data_ptr] = _TrackedTensorInfo(tensor) + + def mark_internal_output(self, tensor: Tensor) -> None: + data_ptr = tensor.data_ptr() + if data_ptr not in self._external_inputs: + self._internal_outputs.add(data_ptr) + + def check_alive(self, capture_pools: list[_POOL_HANDLE]) -> None: + dead = [ + i + for i in self._external_inputs.values() + if not i.is_alive() + and not any( + self._is_tensor_from_capture_pool(i, pool) for pool in capture_pools + ) + ] + if not dead: + return + + def fmt(label: str, tb: str | None) -> str: + return f" {label}:\n{textwrap.indent(tb.strip(), ' ')}\n" if tb else "" + + parts = [f"CUDA graph replay detected {len(dead)} dead tensor(s).\n"] + for i, info in enumerate(dead[:5], 1): + parts.append(f"Dead tensor #{i} (data_ptr={info.data_ptr:#x}):\n") + parts.append(fmt("Creation Traceback (Python)", info.creation_traceback_py)) + parts.append(fmt("Creation Traceback (C++)", info.creation_traceback_cpp)) + parts.append(fmt("Deletion Traceback (Python)", info.deletion_traceback_py)) + if len(dead) > 5: + parts.append(f" ... and {len(dead) - 5} more\n") + parts.append( + fmt("Replay Traceback (Python)", "".join(traceback.format_stack()[:-2])) + ) + raise RuntimeError("".join(parts)) + + def _get_memory_snapshot(self, capture_pool: _POOL_HANDLE) -> list[dict[str, Any]]: + if capture_pool not in self._memory_snapshots: + self._memory_snapshots[capture_pool] = torch.cuda.memory.memory_snapshot( + capture_pool, include_traces=False + ) + return self._memory_snapshots[capture_pool] + + def _is_tensor_from_capture_pool( + self, tensor: _TrackedTensorInfo, capture_pool: _POOL_HANDLE + ) -> bool: + device = tensor.device_index + if device is None: + return False + tensor_ptr = tensor.data_ptr + for meminfo in self._get_memory_snapshot(capture_pool): + if meminfo["device"] != device: + continue + for block in meminfo["blocks"]: + addr = block["address"] + if ( + addr <= tensor_ptr < addr + block["size"] + and "active" in block["state"] + ): + return True + return False + + +class _TensorTrackingMode(TorchDispatchMode): + supports_higher_order_operators = True + + def __init__(self, tracker: _CUDAGraphInputLivenessTracker) -> None: + self._tracker = tracker + + # Mirrors the CUDA dispatch key selection rule: if at least one tensor + # input is a CUDA tensor, the CUDA dispatch key is selected and the op + # runs (and is captured) on GPU. + # See aten/src/ATen/core/dispatch/DispatchKeyExtractor.h for details. + def _selects_cuda_dispatch_key(self, values: object) -> bool: + for v in tree_iter(values): + if isinstance(v, Tensor) and v.is_cuda: + return True + return False + + def __torch_dispatch__( + self, + func: object, + types: object, + args: tuple[object, ...] = (), + kwargs: dict[str, object] | None = None, + ) -> object: + kwargs = kwargs or {} + inputs = [args, kwargs] + if torch.cuda.is_current_stream_capturing() and self._selects_cuda_dispatch_key( + inputs + ): + out = func(*args, **kwargs) # type: ignore[operator] + self._track_inputs(inputs) + self._mark_outputs(out) + else: + out = func(*args, **kwargs) # type: ignore[operator] + return out + + def _track_inputs(self, values: object) -> None: + for v in tree_iter(values): + if not isinstance(v, Tensor) or v.data_ptr() == 0: + continue + if v.is_cuda or v.is_pinned(): + self._tracker.track_external_input(v) + + def _mark_outputs(self, values: object) -> None: + for v in tree_iter(values): + if isinstance(v, Tensor) and v.is_cuda: + self._tracker.mark_internal_output(v) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_cxx_pytree.py b/.venv/lib/python3.12/site-packages/torch/utils/_cxx_pytree.py new file mode 100644 index 0000000000000000000000000000000000000000..6a763f51a4288bc4af2bf0a3a562f406af434e9e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_cxx_pytree.py @@ -0,0 +1,1151 @@ +# Owner(s): ["module: pytree"] + +""" +Contains utility functions for working with nested python data structures. + +A *pytree* is a Python nested data structure. It is a tree in the sense that +nodes are Python collections (e.g., list, tuple, dict) and the leaves are +Python values. Furthermore, a pytree should not contain reference cycles. + +pytrees are useful for working with nested collections of Tensors. For example, +one can use `tree_map` to map a function over all Tensors inside some nested +collection of Tensors and `tree_leaves` to get a flat list of all Tensors +inside some nested collection. pytrees are helpful for implementing nested +collection support for PyTorch APIs. +""" + +import functools +import sys +import types +from collections.abc import Callable, Iterable, Mapping +from typing import Any, overload, TypeAlias, TypeVar +from typing_extensions import deprecated, Self, TypeIs + +import torch.utils._pytree as python_pytree +from torch.torch_version import TorchVersion as _TorchVersion +from torch.utils._pytree import ( + Context, + DumpableContext, + FlattenFn, + FlattenWithKeysFn, + FromDumpableContextFn, + is_namedtuple, + is_namedtuple_class, + is_namedtuple_instance, + is_structseq, + is_structseq_class, + is_structseq_instance, + KeyPath, + PyTree, + ToDumpableContextFn, + UnflattenFn, +) + + +# Do not try to import `optree` package if the static version check already fails. +if not python_pytree._cxx_pytree_dynamo_traceable: + raise ImportError( + f"{__name__} depends on `optree>={python_pytree._optree_minimum_version}`, " + "which is an optional dependency of PyTorch. " + "To use it, please upgrade your optree package via " + "`python3 -m pip install --upgrade optree`" + ) + + +import optree +from optree import PyTreeSpec # direct import for type annotations + + +__all__ = [ + "PyTree", + "Context", + "FlattenFn", + "UnflattenFn", + "DumpableContext", + "ToDumpableContextFn", + "FromDumpableContextFn", + "PyTreeSpec", + "TreeSpec", + "LeafSpec", + "keystr", + "key_get", + "register_pytree_node", + "tree_is_leaf", + "tree_flatten", + "tree_flatten_with_path", + "tree_unflatten", + "tree_iter", + "tree_leaves", + "tree_leaves_with_path", + "tree_structure", + "tree_map", + "tree_map_with_path", + "tree_map_", + "tree_map_only", + "tree_map_only_", + "tree_all", + "tree_any", + "tree_all_only", + "tree_any_only", + "treespec_dumps", + "treespec_loads", + "treespec_pprint", + "is_namedtuple", + "is_namedtuple_class", + "is_namedtuple_instance", + "is_structseq", + "is_structseq_class", + "is_structseq_instance", +] + + +# In-tree installation may have VCS-based versioning. Update the previous static version. +python_pytree._optree_version = _TorchVersion(optree.__version__) # type: ignore[attr-defined] + +__TORCH_DICT_SESSION = optree.dict_insertion_ordered(True, namespace="torch") +__TORCH_DICT_SESSION.__enter__() # enable globally and permanently + + +T = TypeVar("T") +S = TypeVar("S") +U = TypeVar("U") +R = TypeVar("R") + +TreeSpec: TypeAlias = PyTreeSpec +OpTreeUnflattenFn = Callable[[Context, Iterable[Any]], PyTree] + +# Keep deprecated alias for backward compatibility +FlattenFunc = FlattenFn # deprecated +UnflattenFunc = UnflattenFn # deprecated +FlattenWithKeysFunc = FlattenWithKeysFn # deprecated + + +def _reverse_args(func: UnflattenFn) -> OpTreeUnflattenFn: + @functools.wraps(func) + def wrapped(*args: Any, **kwargs: Any) -> Any: + return func(*reversed(args), **kwargs) + + return wrapped + + +def register_pytree_node( + cls: type[Any], + flatten_fn: FlattenFn, + unflatten_fn: UnflattenFn, + *, + serialized_type_name: str | None = None, + to_dumpable_context: ToDumpableContextFn | None = None, + from_dumpable_context: FromDumpableContextFn | None = None, + flatten_with_keys_fn: FlattenWithKeysFn | None = None, +) -> None: + """Register a container-like type as pytree node. + + Args: + cls (type): A Python type to treat as an internal pytree node. + flatten_fn (callable): A function to be used during flattening, taking an instance of + ``cls`` and returning a pair, with (1) an iterable for the children to be flattened + recursively, and (2) some hashable auxiliary data to be stored in the treespec and to be + passed to the ``unflatten_fn``. + unflatten_fn (callable): A function taking two arguments: the auxiliary data that was + returned by ``flatten_fn`` and stored in the treespec, and the unflattened children. + The function should return an instance of ``cls``. + serialized_type_name (str, optional): A keyword argument used to specify the fully + qualified name used when serializing the tree spec. + to_dumpable_context (callable, optional): An optional keyword argument to custom specify how + to convert the context of the pytree to a custom json dumpable representation. This is + used for json serialization, which is being used in :mod:`torch.export` right now. + from_dumpable_context (callable, optional): An optional keyword argument to custom specify + how to convert the custom json dumpable representation of the context back to the + original context. This is used for json deserialization, which is being used in + :mod:`torch.export` right now. + + Example:: + + >>> # xdoctest: +SKIP + >>> # Register a Python type with lambda functions + >>> register_pytree_node( + ... set, + ... lambda s: (sorted(s), None, None), + ... lambda children, _: set(children), + ... ) + """ + if flatten_with_keys_fn is not None: + raise NotImplementedError("KeyPaths are not yet supported in cxx_pytree.") + + _private_register_pytree_node( + cls, + flatten_fn, + unflatten_fn, + serialized_type_name=serialized_type_name, + to_dumpable_context=to_dumpable_context, + from_dumpable_context=from_dumpable_context, + ) + + python_pytree._private_register_pytree_node( + cls, + flatten_fn, + unflatten_fn, + serialized_type_name=serialized_type_name, + to_dumpable_context=to_dumpable_context, + from_dumpable_context=from_dumpable_context, + ) + + +@deprecated( + "`torch.utils._cxx_pytree._register_pytree_node` is deprecated. " + "Please use `torch.utils._cxx_pytree.register_pytree_node` instead.", + category=FutureWarning, +) +def _register_pytree_node( + cls: type[Any], + flatten_fn: FlattenFn, + unflatten_fn: UnflattenFn, + *, + serialized_type_name: str | None = None, + to_dumpable_context: ToDumpableContextFn | None = None, + from_dumpable_context: FromDumpableContextFn | None = None, +) -> None: + """Register a container-like type as pytree node for the C++ pytree only. + + The ``namespace`` argument is used to avoid collisions that occur when different libraries + register the same Python type with different behaviors. It is recommended to add a unique prefix + to the namespace to avoid conflicts with other libraries. Namespaces can also be used to specify + the same class in different namespaces for different use cases. + + .. warning:: + For safety reasons, a ``namespace`` must be specified while registering a custom type. It is + used to isolate the behavior of flattening and unflattening a pytree node type. This is to + prevent accidental collisions between different libraries that may register the same type. + + Args: + cls (type): A Python type to treat as an internal pytree node. + flatten_fn (callable): A function to be used during flattening, taking an instance of + ``cls`` and returning a pair, with (1) an iterable for the children to be flattened + recursively, and (2) some hashable auxiliary data to be stored in the treespec and to be + passed to the ``unflatten_fn``. + unflatten_fn (callable): A function taking two arguments: the auxiliary data that was + returned by ``flatten_fn`` and stored in the treespec, and the unflattened children. + The function should return an instance of ``cls``. + serialized_type_name (str, optional): A keyword argument used to specify the fully + qualified name used when serializing the tree spec. + to_dumpable_context (callable, optional): An optional keyword argument to custom specify how + to convert the context of the pytree to a custom json dumpable representation. This is + used for json serialization, which is being used in :mod:`torch.export` right now. + from_dumpable_context (callable, optional): An optional keyword argument to custom specify + how to convert the custom json dumpable representation of the context back to the + original context. This is used for json deserialization, which is being used in + :mod:`torch.export` right now. + """ + + _private_register_pytree_node( + cls, + flatten_fn, + unflatten_fn, + serialized_type_name=serialized_type_name, + to_dumpable_context=to_dumpable_context, + from_dumpable_context=from_dumpable_context, + ) + + +def _private_register_pytree_node( + cls: type[Any], + flatten_fn: FlattenFn, + unflatten_fn: UnflattenFn, + *, + serialized_type_name: str | None = None, + to_dumpable_context: ToDumpableContextFn | None = None, + from_dumpable_context: FromDumpableContextFn | None = None, +) -> None: + """This is an internal function that is used to register a pytree node type + for the C++ pytree only. End-users should use :func:`register_pytree_node` + instead. + """ + # TODO(XuehaiPan): remove this condition when we make Python pytree out-of-box support + # PyStructSequence types + if not optree.is_structseq_class(cls): + optree.register_pytree_node( + cls, + flatten_fn, + _reverse_args(unflatten_fn), + namespace="torch", + ) + + +def _is_pytreespec_instance( + obj: Any, + /, +) -> TypeIs[TreeSpec | python_pytree.PyTreeSpec]: + if isinstance(obj, (TreeSpec, python_pytree.PyTreeSpec)): + return True + if "torch._dynamo.polyfills.pytree" in sys.modules: + # The PyTorch Dynamo pytree module is not always available, so we check if it is loaded. + # If the PyTorch Dynamo pytree module is loaded, we can check if the treespec + # is an instance of the PyTorch Dynamo TreeSpec class. + import torch._dynamo.polyfills.pytree as dynamo_pytree + + return isinstance(obj, dynamo_pytree.PyTreeSpec) + return False + + +def treespec_leaf() -> TreeSpec: + """Make a treespec representing a leaf node.""" + return optree.treespec_leaf(none_is_leaf=True, namespace="torch") + + +def treespec_tuple(iterable: Iterable[TreeSpec] = (), /) -> TreeSpec: + """Make a tuple treespec from an iterable of child treespecs.""" + return optree.treespec_tuple(iterable, none_is_leaf=True, namespace="torch") + + +def treespec_dict( + mapping: Mapping[Any, TreeSpec] | Iterable[tuple[Any, TreeSpec]] = (), + /, + **kwargs: TreeSpec, +) -> TreeSpec: + """Make a dict treespec from a dict of child treespecs.""" + return optree.treespec_dict( + mapping, + **kwargs, + none_is_leaf=True, + namespace="torch", + ) + + +def tree_is_leaf( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: + """Check if a pytree is a leaf. + + >>> tree_is_leaf(1) + True + >>> tree_is_leaf(None) + True + >>> tree_is_leaf([1, 2, 3]) + False + >>> tree_is_leaf((1, 2, 3), is_leaf=lambda x: isinstance(x, tuple)) + True + >>> tree_is_leaf({"a": 1, "b": 2, "c": 3}) + False + >>> tree_is_leaf({"a": 1, "b": 2, "c": None}) + False + + Args: + tree (pytree): A pytree to check if it is a leaf node. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + A boolean indicating if the pytree is a leaf node. + """ + return optree.tree_is_leaf( + tree, + is_leaf=is_leaf, + none_is_leaf=True, + namespace="torch", + ) + + +def tree_flatten( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> tuple[list[Any], TreeSpec]: + """Flatten a pytree. + + See also :func:`tree_unflatten`. + + The flattening order (i.e., the order of elements in the output list) is deterministic, + corresponding to a left-to-right depth-first tree traversal. + + >>> tree = {"b": (2, [3, 4]), "a": 1, "c": None, "d": 5} + >>> tree_flatten(tree) + ([2, 3, 4, 1, None, 5], PyTreeSpec({'b': (*, [*, *]), 'a': *, 'c': *, 'd': *}, NoneIsLeaf, namespace='torch')) + >>> tree_flatten(1) + ([1], PyTreeSpec(*, NoneIsLeaf, namespace='torch')) + >>> tree_flatten(None) + ([None], PyTreeSpec(*, NoneIsLeaf, namespace='torch')) + >>> from collections import OrderedDict + >>> tree = OrderedDict([("b", (2, [3, 4])), ("a", 1), ("c", None), ("d", 5)]) + >>> tree_flatten(tree) + ([2, 3, 4, 1, None, 5], PyTreeSpec(OrderedDict({'b': (*, [*, *]), 'a': *, 'c': *, 'd': *}), NoneIsLeaf, namespace='torch')) + + Args: + tree (pytree): A pytree to flatten. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + A pair ``(leaves, treespec)`` where the first element is a list of leaf values and the + second element is a treespec representing the structure of the pytree. + """ + return optree.tree_flatten( # type: ignore[return-value] + tree, + is_leaf=is_leaf, + none_is_leaf=True, + namespace="torch", + ) + + +def tree_unflatten(leaves: Iterable[Any], treespec: TreeSpec) -> PyTree: + """Reconstruct a pytree from the treespec and the leaves. + + The inverse of :func:`tree_flatten`. + + >>> tree = {"b": (2, [3, 4]), "a": 1, "c": None, "d": 5} + >>> leaves, treespec = tree_flatten(tree) + >>> tree == tree_unflatten(leaves, treespec) + True + + Args: + leaves (iterable): The list of leaves to use for reconstruction. The list must match the + number of leaves of the treespec. + treespec (TreeSpec): The treespec to reconstruct. + + Returns: + The reconstructed pytree, containing the ``leaves`` placed in the structure described by + ``treespec``. + """ + if not _is_pytreespec_instance(treespec): + if not _is_pytreespec_instance(leaves): + raise TypeError( + f"Expected `treespec` to be an instance of " + f"PyTreeSpec but got item of type {type(treespec)}." + ) + # Allow passing the PyTreeSpec instance as the first argument + # pyrefly: ignore [bad-assignment] + leaves, treespec = treespec, leaves + return treespec.unflatten(leaves) + + +def tree_iter( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> Iterable[Any]: + """Get an iterator over the leaves of a pytree. + + See also :func:`tree_flatten`. + + >>> tree = {"b": (2, [3, 4]), "a": 1, "c": None, "d": 5} + >>> list(tree_iter(tree)) + [2, 3, 4, 1, None, 5] + >>> list(tree_iter(1)) + [1] + >>> list(tree_iter(None)) + [None] + + Args: + tree (pytree): A pytree to flatten. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + An iterator over the leaf values. + """ + return optree.tree_iter( + tree, + is_leaf=is_leaf, + none_is_leaf=True, + namespace="torch", + ) + + +def tree_leaves( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> list[Any]: + """Get the leaves of a pytree. + + See also :func:`tree_flatten`. + + >>> tree = {"b": (2, [3, 4]), "a": 1, "c": None, "d": 5} + >>> tree_leaves(tree) + [2, 3, 4, 1, None, 5] + >>> tree_leaves(1) + [1] + >>> tree_leaves(None) + [None] + + Args: + tree (pytree): A pytree to flatten. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + A list of leaf values. + """ + return optree.tree_leaves( + tree, + is_leaf=is_leaf, + none_is_leaf=True, + namespace="torch", + ) + + +def tree_structure( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> TreeSpec: + """Get the treespec for a pytree. + + See also :func:`tree_flatten`. + + >>> tree = {"b": (2, [3, 4]), "a": 1, "c": None, "d": 5} + >>> tree_structure(tree) + PyTreeSpec({'b': (*, [*, *]), 'a': *, 'c': *, 'd': *}, NoneIsLeaf, namespace='torch') + >>> tree_structure(1) + PyTreeSpec(*, NoneIsLeaf, namespace='torch') + >>> tree_structure(None) + PyTreeSpec(*, NoneIsLeaf, namespace='torch') + + Args: + tree (pytree): A pytree to flatten. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + A treespec object representing the structure of the pytree. + """ + return optree.tree_structure( # type: ignore[return-value] + tree, + is_leaf=is_leaf, + none_is_leaf=True, + namespace="torch", + ) + + +def tree_map( + func: Callable[..., Any], + tree: PyTree, + *rests: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: + """Map a multi-input function over pytree args to produce a new pytree. + + See also :func:`tree_map_`. + + >>> tree_map(lambda x: x + 1, {"x": 7, "y": (42, 64)}) + {'x': 8, 'y': (43, 65)} + >>> tree_map(lambda x: x is None, {"x": 7, "y": (42, 64), "z": None}) + {'x': False, 'y': (False, False), 'z': True} + + If multiple inputs are given, the structure of the tree is taken from the first input; + subsequent inputs need only have ``tree`` as a prefix: + + >>> tree_map(lambda x, y: [x] + y, [5, 6], [[7, 9], [1, 2]]) + [[5, 7, 9], [6, 1, 2]] + + Args: + func (callable): A function that takes ``1 + len(rests)`` arguments, to be applied at the + corresponding leaves of the pytrees. + tree (pytree): A pytree to be mapped over, with each leaf providing the first positional + argument to function ``func``. + rests (tuple of pytree): A tuple of pytrees, each of which has the same structure as + ``tree`` or has ``tree`` as a prefix. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + A new pytree with the same structure as ``tree`` but with the value at each leaf given by + ``func(x, *xs)`` where ``x`` is the value at the corresponding leaf in ``tree`` and ``xs`` + is the tuple of values at corresponding nodes in ``rests``. + """ + return optree.tree_map( + func, + tree, + *rests, + is_leaf=is_leaf, + none_is_leaf=True, + namespace="torch", + ) + + +def tree_map_( + func: Callable[..., Any], + tree: PyTree, + *rests: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: + """Like :func:`tree_map`, but do an inplace call on each leaf and return the original tree. + + See also :func:`tree_map`. + + Args: + func (callable): A function that takes ``1 + len(rests)`` arguments, to be applied at the + corresponding leaves of the pytrees. + tree (pytree): A pytree to be mapped over, with each leaf providing the first positional + argument to function ``func``. + rests (tuple of pytree): A tuple of pytrees, each of which has the same structure as + ``tree`` or has ``tree`` as a prefix. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + The original ``tree`` with the value at each leaf is given by the side-effect of function + ``func(x, *xs)`` (not the return value) where ``x`` is the value at the corresponding leaf + in ``tree`` and ``xs`` is the tuple of values at corresponding nodes in ``rests``. + """ + return optree.tree_map_( + func, + tree, + *rests, + is_leaf=is_leaf, + none_is_leaf=True, + namespace="torch", + ) + + +Type2 = tuple[type[T], type[S]] +Type3 = tuple[type[T], type[S], type[U]] +TypeAny = type[Any] | tuple[type[Any], ...] | types.UnionType + +Fn2 = Callable[[T | S], R] +Fn3 = Callable[[T | S | U], R] +Fn = Callable[[T], R] +FnAny = Callable[[Any], R] + +MapOnlyFn = Callable[[T], Callable[[Any], Any]] + + +# These specializations help with type inference on the lambda passed to this +# function +@overload +def map_only(type_or_types_or_pred: type[T], /) -> MapOnlyFn[Fn[T, Any]]: ... + + +@overload +def map_only(type_or_types_or_pred: Type2[T, S], /) -> MapOnlyFn[Fn2[T, S, Any]]: ... + + +@overload +def map_only( + type_or_types_or_pred: Type3[T, S, U], / +) -> MapOnlyFn[Fn3[T, S, U, Any]]: ... + + +# This specialization is needed for the implementations below that call +@overload +def map_only(type_or_types_or_pred: TypeAny, /) -> MapOnlyFn[FnAny[Any]]: ... + + +@overload +def map_only( + type_or_types_or_pred: Callable[[Any], bool], / +) -> MapOnlyFn[FnAny[Any]]: ... + + +def map_only( + type_or_types_or_pred: TypeAny | Callable[[Any], bool], / +) -> MapOnlyFn[FnAny[Any]]: + """ + Suppose you are writing a tree_map over tensors, leaving everything + else unchanged. Ordinarily you would have to write: + + def go(t): + if isinstance(t, Tensor): + return ... + else: + return t + + With this function, you only need to write: + + @map_only(Tensor) + def go(t): + return ... + + You can also directly use 'tree_map_only' + """ + if isinstance(type_or_types_or_pred, (type, tuple, types.UnionType)): + + def pred(x: Any) -> bool: + return isinstance(x, type_or_types_or_pred) # type: ignore[arg-type] + + elif callable(type_or_types_or_pred): + pred = type_or_types_or_pred # type: ignore[assignment] + else: + raise TypeError("Argument must be a type, a tuple of types, or a callable.") + + def wrapper(func: Callable[[T], Any]) -> Callable[[Any], Any]: + @functools.wraps(func) + def wrapped(x: T) -> Any: + if pred(x): + return func(x) + return x + + return wrapped + + return wrapper + + +@overload +def tree_map_only( + type_or_types_or_pred: type[T], + /, + func: Fn[T, Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only( + type_or_types_or_pred: Type2[T, S], + /, + func: Fn2[T, S, Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only( + type_or_types_or_pred: Type3[T, S, U], + /, + func: Fn3[T, S, U, Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only( + type_or_types_or_pred: TypeAny, + /, + func: FnAny[Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only( + type_or_types_or_pred: Callable[[Any], bool], + /, + func: FnAny[Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +def tree_map_only( + type_or_types_or_pred: TypeAny | Callable[[Any], bool], + /, + func: FnAny[Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: + return tree_map(map_only(type_or_types_or_pred)(func), tree, is_leaf=is_leaf) + + +@overload +def tree_map_only_( + type_or_types_or_pred: type[T], + /, + func: Fn[T, Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only_( + type_or_types_or_pred: Type2[T, S], + /, + func: Fn2[T, S, Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only_( + type_or_types_or_pred: Type3[T, S, U], + /, + func: Fn3[T, S, U, Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only_( + type_or_types_or_pred: TypeAny, + /, + func: FnAny[Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only_( + type_or_types_or_pred: Callable[[Any], bool], + /, + func: FnAny[Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +def tree_map_only_( + type_or_types_or_pred: TypeAny | Callable[[Any], bool], + /, + func: FnAny[Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: + return tree_map_(map_only(type_or_types_or_pred)(func), tree, is_leaf=is_leaf) + + +def tree_all( + pred: Callable[[Any], bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: + flat_args = tree_iter(tree, is_leaf=is_leaf) + return all(map(pred, flat_args)) + + +def tree_any( + pred: Callable[[Any], bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: + flat_args = tree_iter(tree, is_leaf=is_leaf) + return any(map(pred, flat_args)) + + +@overload +def tree_all_only( + type_or_types: type[T], + /, + pred: Fn[T, bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: ... + + +@overload +def tree_all_only( + type_or_types: Type2[T, S], + /, + pred: Fn2[T, S, bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: ... + + +@overload +def tree_all_only( + type_or_types: Type3[T, S, U], + /, + pred: Fn3[T, S, U, bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: ... + + +def tree_all_only( + type_or_types: TypeAny, + /, + pred: FnAny[bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: + flat_args = tree_iter(tree, is_leaf=is_leaf) + return all(pred(x) for x in flat_args if isinstance(x, type_or_types)) + + +@overload +def tree_any_only( + type_or_types: type[T], + /, + pred: Fn[T, bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: ... + + +@overload +def tree_any_only( + type_or_types: Type2[T, S], + /, + pred: Fn2[T, S, bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: ... + + +@overload +def tree_any_only( + type_or_types: Type3[T, S, U], + /, + pred: Fn3[T, S, U, bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: ... + + +def tree_any_only( + type_or_types: TypeAny, + /, + pred: FnAny[bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: + flat_args = tree_iter(tree, is_leaf=is_leaf) + return any(pred(x) for x in flat_args if isinstance(x, type_or_types)) + + +def broadcast_prefix( + prefix_tree: PyTree, + full_tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> list[Any]: + """Return a list of broadcasted leaves in ``prefix_tree`` to match the number of leaves in ``full_tree``. + + If a ``prefix_tree`` is a prefix of a ``full_tree``, this means the ``full_tree`` can be + constructed by replacing the leaves of ``prefix_tree`` with appropriate **subtrees**. + + This function returns a list of leaves with the same size as ``full_tree``. The leaves are + replicated from ``prefix_tree``. The number of replicas is determined by the corresponding + subtree in ``full_tree``. + + >>> broadcast_prefix(1, [1, 2, 3]) + [1, 1, 1] + >>> broadcast_prefix([1, 2, 3], [1, 2, 3]) + [1, 2, 3] + >>> broadcast_prefix([1, 2, 3], [1, 2, 3, 4]) + Traceback (most recent call last): + ... + ValueError: list arity mismatch; expected: 3, got: 4; list: [1, 2, 3, 4]. + >>> broadcast_prefix([1, 2, 3], [1, 2, (3, 4)]) + [1, 2, 3, 3] + >>> broadcast_prefix([1, 2, 3], [1, 2, {"a": 3, "b": 4, "c": (None, 5)}]) + [1, 2, 3, 3, 3, 3] + + Args: + prefix_tree (pytree): A pytree with the same structure as a prefix of ``full_tree``. + full_tree (pytree): A pytree with the same structure as a suffix of ``prefix_tree``. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + A list of leaves in ``prefix_tree`` broadcasted to match the number of leaves in ``full_tree``. + """ + result: list[Any] = [] + + def add_leaves(x: Any, subtree: PyTree) -> None: + subtreespec = tree_structure(subtree, is_leaf=is_leaf) + result.extend([x] * subtreespec.num_leaves) + + tree_map_( + add_leaves, + prefix_tree, + full_tree, + is_leaf=is_leaf, + ) + return result + + +# Broadcasts a pytree to the provided TreeSpec and returns the flattened +# values. If this is not possible, then this function returns None. +# +# For example, given pytree=0 and spec=TreeSpec(list, None, [LeafSpec(), LeafSpec()]), +# would return [0, 0]. This is useful for part of the vmap implementation: +# a user can pass in vmap(fn, in_dims)(*inputs). `in_dims` should be +# broadcastable to the tree structure of `inputs` and we use +# _broadcast_to_and_flatten to check this. +def _broadcast_to_and_flatten( + tree: PyTree, + treespec: TreeSpec, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> list[Any] | None: + if not _is_pytreespec_instance(treespec): + raise TypeError( + f"Expected `treespec` to be an instance of " + f"PyTreeSpec but got item of type {type(treespec)}." + ) + full_tree = tree_unflatten([0] * treespec.num_leaves, treespec) + try: + return broadcast_prefix(tree, full_tree, is_leaf=is_leaf) + except ValueError: + return None + + +def treespec_dumps(treespec: TreeSpec, protocol: int | None = None) -> str: + """Serialize a treespec to a JSON string.""" + if not _is_pytreespec_instance(treespec): + raise TypeError( + f"Expected `treespec` to be an instance of " + f"PyTreeSpec but got item of type {type(treespec)}." + ) + + dummy_tree = tree_unflatten([0] * treespec.num_leaves, treespec) + orig_treespec = python_pytree.tree_structure(dummy_tree) + return python_pytree.treespec_dumps(orig_treespec, protocol=protocol) + + +@functools.lru_cache +def treespec_loads(serialized: str) -> TreeSpec: + """Deserialize a treespec from a JSON string.""" + orig_treespec = python_pytree.treespec_loads(serialized) + dummy_tree = python_pytree.tree_unflatten( + [0] * orig_treespec.num_leaves, + orig_treespec, + ) + treespec = tree_structure(dummy_tree) + return treespec + + +class _Asterisk(str): + __slots__ = () + + def __new__(cls) -> Self: + return super().__new__(cls, "*") + + def __repr__(self) -> str: + return "*" # no quotes + + +_asterisk = _Asterisk() +del _Asterisk + + +def treespec_pprint(treespec: TreeSpec) -> str: + dummy_tree = tree_unflatten([_asterisk] * treespec.num_leaves, treespec) + return repr(dummy_tree) + + +class LeafSpecMeta(type(TreeSpec)): # type: ignore[misc] + def __instancecheck__(self, instance: object) -> bool: + return _is_pytreespec_instance(instance) and instance.is_leaf() + + +@deprecated( + "`isinstance(treespec, LeafSpec)` is deprecated, " + "use `isinstance(treespec, TreeSpec)` and `treespec.is_leaf()` instead.", + category=FutureWarning, +) +class LeafSpec(TreeSpec, metaclass=LeafSpecMeta): # type: ignore[misc,final] + def __new__(cls) -> Self: + return treespec_leaf() # type: ignore[return-value] + + +def tree_flatten_with_path( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> tuple[list[tuple[KeyPath, Any]], TreeSpec]: + """Flattens a pytree like :func:`tree_flatten`, but also returns each leaf's key path. + + Args: + tree: a pytree to flatten. If it contains a custom type, that type must be + registered with an appropriate `tree_flatten_with_path_fn` when registered + with :func:`register_pytree_node`. + is_leaf: An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + Returns: + A tuple where the first element is a list of (key path, leaf) pairs, and the + second element is a :class:`TreeSpec` representing the structure of the flattened + tree. + """ + raise NotImplementedError("KeyPaths are not yet supported in cxx_pytree.") + + +def tree_leaves_with_path( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> list[tuple[KeyPath, Any]]: + """Gets the leaves of a pytree like ``tree_leaves`` and returns each leaf's key path. + + Args: + tree: a pytree. If it contains a custom type, that type must be + registered with an appropriate `tree_flatten_with_path_fn` when registered + with :func:`register_pytree_node`. + is_leaf: An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + Returns: + A list of (key path, leaf) pairs. + """ + raise NotImplementedError("KeyPaths are not yet supported in cxx_pytree.") + + +def tree_map_with_path( + func: Callable[..., Any], + tree: PyTree, + *rests: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: + """Like :func:`tree_map`, but the provided callable takes an additional key path argument. + + Args: + func: A function that takes ``2 + len(rests)`` arguments, to be applied at the + corresponding leaves of the pytrees. The first positional argument + to ``func`` is the key path of the leaf in question. The second + positional argument is the value of the leaf. + tree: A pytree to be mapped over, with each leaf providing the first positional + argument to function ``func``. + rests: A tuple of pytrees, each of which has the same structure as + ``tree`` or has ``tree`` as a prefix. + is_leaf: An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns + A new pytree with the same structure as ``tree`` but with the value at each leaf given by + ``func(keypath, x, *xs)`` where ``keypath`` is the key path at the + corresponding leaf in ``tree``, ``x`` is the value at that leaf, and + ``xs`` is the tuple of values at corresponding nodes in ``rests``. + """ + raise NotImplementedError("KeyPaths are not yet supported in cxx_pytree.") + + +def keystr(kp: KeyPath) -> str: + """Given a key path, return a pretty-printed representation.""" + raise NotImplementedError("KeyPaths are not yet supported in cxx_pytree.") + + +def key_get(obj: Any, kp: KeyPath) -> Any: + """Given an object and a key path, return the value at the key path.""" + raise NotImplementedError("KeyPaths are not yet supported in cxx_pytree.") + + +with python_pytree._NODE_REGISTRY_LOCK: + # pyrefly: ignore [bad-assignment] + python_pytree._cxx_pytree_imported = True + args, kwargs = (), {} # type: ignore[var-annotated] + for args, kwargs in python_pytree._cxx_pytree_pending_imports: + _private_register_pytree_node(*args, **kwargs) + python_pytree._cxx_pytree_pending_imports.clear() + del args, kwargs diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fd40af116d1395a1cc03f300feb2cfd9cf55fb39 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__init__.py @@ -0,0 +1,30 @@ +# mypy: allow-untyped-defs +""" +DebugMode: a debugging TorchDispatchMode that intercepts and logs runtime calls. + +See torch.utils._debug_mode._mode for the full implementation and docstring. +""" + +from torch.utils._debug_mode._calls import ( + _AnnotateCall, + _DebugCall, + _get_call_name, + _OpCall, + _OutputPlacementCall, + _RedistributeCall, + _TritonKernelCall, +) +from torch.utils._debug_mode._mode import ( + DebugInterpreter, + DebugMode, + get_active_debug_mode, +) +from torch.utils._debug_mode._utils import ( + _stringify_shape, + hash_tensor_fn, + norm_hash_fn, + TensorIdTracker, +) + + +__all__ = ["DebugMode", "get_active_debug_mode"] diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..486e5069e7bc2152d6d2f410259f6d14b37727ac Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__pycache__/_calls.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__pycache__/_calls.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50b236847d3ecd6d1c294b8e332b295b95d30874 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__pycache__/_calls.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__pycache__/_mode.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__pycache__/_mode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..993cd26dcee468b50260ca1709c9c05b8a47f250 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__pycache__/_mode.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b91ded4a5488e870c1462e7d49b8db1cfacef066 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/__pycache__/_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/_calls.py b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/_calls.py new file mode 100644 index 0000000000000000000000000000000000000000..aa1fa2eca587075f88e7069ddd4bb0cd5499c117 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/_calls.py @@ -0,0 +1,629 @@ +# mypy: allow-untyped-defs +""" +Call record classes for DebugMode: _DebugCall and its subclasses. +""" + +import math +from typing import Any, TYPE_CHECKING + +import torch + +# Import _utils module for mutable globals +from torch.utils._debug_mode import _utils +from torch.utils._debug_mode._utils import ( + _arg_to_str, + _get_op_name, + _get_stack_trace, + _maybe_get_autograd_trace, + REDISTRIBUTE_FUNC, + TensorIdTracker, +) +from torch.utils._pytree import tree_all, tree_map + + +if TYPE_CHECKING: + from torch._dynamo.device_interface import DeviceInterface + + +class _DebugCall: + """Base class for tracking operator calls in DebugMode""" + + def __init__( + self, + call_depth: int, + record: dict[str, Any] | None = None, + log: dict[str, Any] | None = None, + stack: bool = False, + ) -> None: + self.call_depth = call_depth + if stack: + self.stack_trace = _get_stack_trace() + self.fwd_stack_trace = _maybe_get_autograd_trace() + + # results from dispatch hooks + self.record = record + self.log = log + self.output_str: str | None = None + + def stringify_args( + self, attributes: list[str], tensor_memo: TensorIdTracker | None = None + ) -> None: + """ + To reduce memory consumption, this method stringifies args/kwargs, stores the result, and deletes original args/kwargs. + """ + raise NotImplementedError( + "Subclasses must implement stringify_args(), even if no-op" + ) + + def stringify_output( + self, + output: Any, + attributes: list[str], + tensor_memo: TensorIdTracker | None = None, + ) -> None: + """Store stringified version of call output in self.output_str""" + if tree_all(lambda x: x is None, output): + return + output_str = tree_map(lambda x: _arg_to_str(x, attributes, tensor_memo), output) + self.output_str = f" -> {str(output_str)}" + + def render(self, attributes: list[str]) -> str: + raise NotImplementedError("Subclasses must implement string render()") + + def __repr__(self) -> str: + return self.render([]) + + +class _OpCall(_DebugCall): + """Normal operator call""" + + def __init__( + self, + op, + args: tuple, + kwargs: dict, + call_depth: int, + stack: bool = False, + ) -> None: + super().__init__(call_depth, stack=stack) + self.op = op + self.args = args + self.kwargs = kwargs + + self.args_str: str | None = None + self.kwargs_str: str | None = None + + def stringify_args( + self, attributes: list[str], tensor_memo: TensorIdTracker | None = None + ) -> None: + self.args_str = ", ".join( + _arg_to_str(arg, attributes, tensor_memo) for arg in self.args + ) + if self.kwargs: + self.kwargs_str = ", " + ", ".join( + f"{k}={_arg_to_str(v, attributes, tensor_memo)}" + for k, v in self.kwargs.items() + ) + else: + self.kwargs_str = "" + del self.args + del self.kwargs + + def render(self, attributes: list[str]) -> str: + if self.args_str is not None: + args_str = self.args_str + else: + args_str = ", ".join(_arg_to_str(arg, attributes) for arg in self.args) + + if self.kwargs_str is not None: + kwargs_str = self.kwargs_str + else: + if self.kwargs: + kwargs_str = ", " + ", ".join( + f"{k}={_arg_to_str(v, attributes)}" for k, v in self.kwargs.items() + ) + else: + kwargs_str = "" + + if isinstance(self.op, torch._ops.OpOverload): + op_name = self.op.__qualname__ + elif hasattr(self.op, "__module__") and hasattr(self.op, "__name__"): + op_name = f"{self.op.__module__}.{self.op.__name__}" + else: + op_name = str(self.op) + + base_str = f"{op_name}({args_str}{kwargs_str})" + + if self.output_str: + base_str += self.output_str + if self.log: + base_str += f" # {self.log}" + return base_str + + def __iter__(self): + # for BC; tuple(self) returns (op, args, kwargs, call_depth) + if self.args_str is not None: + yield from [self.op, self.args_str, self.kwargs_str, self.call_depth] + else: + yield from [self.op, self.args, self.kwargs, self.call_depth] + + +class _RedistributeCall(_DebugCall): + def __init__( + self, + arg, + src_placement, + dst_placement, + transform_info_str, + call_depth, + stack=False, + is_explicit=False, + ) -> None: + super().__init__(call_depth, stack=stack) + self.arg = arg + self.src_placement = src_placement + self.dst_placement = dst_placement + self.transform_info_str = transform_info_str + self.is_explicit = is_explicit + self.is_outer_call = isinstance(arg, int) + + self.arg_str: str | None = None + + def stringify_args( + self, attributes: list[str], tensor_memo: TensorIdTracker | None = None + ) -> None: + self.arg_str = f"{_arg_to_str(self.arg, attributes, tensor_memo)}" + del self.arg + + def render(self, attributes: list[str]) -> str: + if self.arg_str is not None: + arg_str = self.arg_str + else: + arg_str = f"{_arg_to_str(self.arg, attributes)}" + + if self.transform_info_str is not None: # prioritize over src/dst placements + placement_str = f"trace: {self.transform_info_str}" + else: + src_placement_str = _arg_to_str(self.src_placement, attributes) + dst_placement_str = _arg_to_str(self.dst_placement, attributes) + placement_str = f"{src_placement_str} -> {dst_placement_str}" + + # DebugMode will add redistribute_input logs at 2 levels, + # once per redistribute decision, and once per redistributed input. + # We only annotate [implicit/explicit] logs on the former (outer-level call). + if self.is_outer_call: + annotation = " [implicit] " + elif self.is_explicit: + annotation = " [explicit] " + else: + annotation = "" + + base_str = f"{REDISTRIBUTE_FUNC}{annotation}({arg_str}, {placement_str})" + if self.output_str: + base_str += self.output_str + return base_str + + def __iter__(self): + # for BC; tuple(self) returns (op, placement info, kwargs, call_depth) + if self.arg_str is not None: + arg = self.arg_str + else: + arg = self.arg + + yield REDISTRIBUTE_FUNC + if self.transform_info_str: + yield [arg, self.transform_info_str] + else: + yield [arg, self.src_placement, self.dst_placement] + yield {} + yield self.call_depth + + +class _OutputPlacementCall(_DebugCall): + """Records output placement for a DTensor op.""" + + def __init__(self, placements_str: str, call_depth: int) -> None: + super().__init__(call_depth) + self.placements_str = placements_str + + def stringify_args( + self, attributes: list[str], tensor_memo: TensorIdTracker | None = None + ) -> None: + pass # Already stringified + + def render(self, attributes: list[str]) -> str: + return f"-> output: {self.placements_str}" + + +class _TritonKernelCall(_DebugCall): + """Triton kernel call from Inductor""" + + def __init__( + self, + kernel_name: str, + kwargs: dict[str, Any], + call_depth: int, + ): + super().__init__(call_depth) + self.kernel_name = kernel_name + self.kwargs = kwargs + self.kwargs_str: str | None = None + + self.pre_hashes: dict[str, Any] | None = None + self.post_hashes: dict[str, Any] | None = None + + def stringify_args( + self, attributes: list[str], tensor_memo: TensorIdTracker | None = None + ) -> None: + # Optionally hash kernel inputs before launch + if hash_fn := _utils._TRITON_INPUT_HASH_FN: + self.pre_hashes = { + k: hash_fn(v) + for k, v in self.kwargs.items() + if isinstance(v, torch.Tensor) + } + + if self.kwargs: + self.kwargs_str = ", ".join( + f"{k}={_arg_to_str(v, attributes, tensor_memo)}" + for k, v in self.kwargs.items() + ) + else: + self.kwargs_str = "" + + def render(self, attributes: list[str]) -> str: + base_str = f"[triton] {self.kernel_name}({self.kwargs_str})" + if self.pre_hashes: + pre_hashes_str = ", ".join(f"{k}: {v}" for k, v in self.pre_hashes.items()) + pre_hashes_str = ( + "\n " + + " " * self.call_depth + + f"# pre-kernel hashes: {{{pre_hashes_str}}}" + ) + else: + pre_hashes_str = "" + if self.post_hashes: + post_hashes_str = ", ".join( + f"{k}: {v}" for k, v in self.post_hashes.items() + ) + post_hashes_str = ( + "\n " + + " " * self.call_depth + + f"# post-kernel hashes: {{{post_hashes_str}}}" + ) + else: + post_hashes_str = "" + return f"{base_str}{pre_hashes_str}{post_hashes_str}\n" + + def finalize(self, device_interface: "DeviceInterface"): + # synchronize -> hash/store kernel results + device_interface.synchronize(device_interface.current_device()) + if _utils._RECORD_TRITON_OUTPUTS: + self.record = { + "output": { + k: v.clone() if isinstance(v, torch.Tensor) else v + for k, v in self.kwargs.items() + } + } + if hash_fn := _utils._TRITON_OUTPUT_HASH_FN: + self.post_hashes = { + k: hash_fn(v) + for k, v in self.kwargs.items() + if isinstance(v, torch.Tensor) + } + + # don't store tensors + del self.kwargs + + def __iter__(self): + yield from [self.kernel_name, (), self.kwargs_str, self.call_depth] + + +class _AnnotateCall(_DebugCall): + """Custom annotation call""" + + def __init__( + self, tag: Any, header: str, call_depth: int, stack: bool = False + ) -> None: + super().__init__(call_depth, stack=stack) + self.tag = tag + self.header = header + + def render(self, attributes: list[str]) -> str: + return f"[{self.header}] {self.tag}" + + def __iter__(self): + yield from [ + f"[{self.header}] {self.tag}", + (), + {}, + self.call_depth, + ] + + +def _serialize_debug_value(value: Any) -> dict[str, Any]: + if value is None or isinstance(value, (bool, int, str)): + return {"type": "scalar", "value": value} + if isinstance(value, float): + if math.isnan(value): + return {"type": "nonfinite_float", "value": "nan"} + if math.isinf(value): + return { + "type": "nonfinite_float", + "value": "inf" if value > 0 else "-inf", + } + return {"type": "scalar", "value": value} + if isinstance(value, tuple): + return { + "type": "tuple", + "items": [_serialize_debug_value(item) for item in value], + } + if isinstance(value, list): + return { + "type": "list", + "items": [_serialize_debug_value(item) for item in value], + } + if isinstance(value, dict): + items = [] + for key, item in value.items(): + if not isinstance(key, str): + raise TypeError( + "DebugMode log serialization only supports dicts with string keys, " + f"but found key {key!r} of type {type(key).__name__}" + ) + items.append([key, _serialize_debug_value(item)]) + return {"type": "dict", "items": items} + raise TypeError( + "DebugMode log serialization only supports JSON-compatible scalar, " + f"tuple, list, and dict values, but found {type(value).__name__}" + ) + + +def _deserialize_debug_value(value: Any) -> Any: + if not isinstance(value, dict): + raise ValueError( + f"Serialized DebugMode value must be a dict, but found {type(value).__name__}" + ) + value_type = value.get("type") + if value_type == "scalar": + return value.get("value") + if value_type == "nonfinite_float": + nonfinite_value = value.get("value") + if nonfinite_value == "nan": + return float("nan") + if nonfinite_value == "inf": + return float("inf") + if nonfinite_value == "-inf": + return float("-inf") + raise ValueError( + f"Unknown serialized DebugMode non-finite float: {nonfinite_value!r}" + ) + if value_type == "tuple": + items = value.get("items") + if not isinstance(items, list): + raise ValueError("Serialized DebugMode tuple must contain an items list") + return tuple(_deserialize_debug_value(item) for item in items) + if value_type == "list": + items = value.get("items") + if not isinstance(items, list): + raise ValueError("Serialized DebugMode list must contain an items list") + return [_deserialize_debug_value(item) for item in items] + if value_type == "dict": + items = value.get("items") + if not isinstance(items, list): + raise ValueError("Serialized DebugMode dict must contain an items list") + result = {} + for item in items: + if not isinstance(item, list) or len(item) != 2: + raise ValueError( + "Serialized DebugMode dict items must be [key, value] pairs" + ) + key, item_value = item + if not isinstance(key, str): + raise ValueError( + "Serialized DebugMode dict keys must be strings, " + f"but found {type(key).__name__}" + ) + result[key] = _deserialize_debug_value(item_value) + return result + raise ValueError(f"Unknown serialized DebugMode value type: {value_type!r}") + + +def _serialize_optional_debug_value(value: Any | None) -> dict[str, Any] | None: + if value is None: + return None + return _serialize_debug_value(value) + + +def _deserialize_optional_debug_value(value: Any | None) -> Any | None: + if value is None: + return None + return _deserialize_debug_value(value) + + +def _serialize_common_call_fields(call: _DebugCall) -> dict[str, Any]: + return { + "call_depth": call.call_depth, + "log": _serialize_optional_debug_value(call.log), + "output_str": call.output_str, + "stack_trace": getattr(call, "stack_trace", None), + "fwd_stack_trace": getattr(call, "fwd_stack_trace", None), + } + + +def _restore_common_call_fields(call: _DebugCall, data: dict[str, Any]) -> None: + call.log = _deserialize_optional_debug_value(data.get("log")) + call.output_str = data.get("output_str") + stack_trace = data.get("stack_trace") + if stack_trace is not None: + call.stack_trace = stack_trace + fwd_stack_trace = data.get("fwd_stack_trace") + if fwd_stack_trace is not None: + call.fwd_stack_trace = fwd_stack_trace + + +def _op_call_args_str(call: _OpCall) -> str: + if call.args_str is not None: + return call.args_str + return ", ".join(_arg_to_str(arg, []) for arg in call.args) + + +def _op_call_kwargs_str(call: _OpCall) -> str: + if call.kwargs_str is not None: + return call.kwargs_str + if call.kwargs: + return ", " + ", ".join( + f"{key}={_arg_to_str(value, [])}" for key, value in call.kwargs.items() + ) + return "" + + +def _redistribute_arg_str(call: _RedistributeCall) -> str: + if call.arg_str is not None: + return call.arg_str + return _arg_to_str(call.arg, []) + + +def _triton_kwargs_str(call: _TritonKernelCall) -> str: + if call.kwargs_str is not None: + return call.kwargs_str + if call.kwargs: + return ", ".join( + f"{key}={_arg_to_str(value, [])}" for key, value in call.kwargs.items() + ) + return "" + + +def _serialized_str(data: dict[str, Any], field: str) -> str: + value = data.get(field) + if not isinstance(value, str): + raise ValueError( + f"Serialized DebugMode call field {field!r} must be a string, " + f"but found {type(value).__name__}" + ) + return value + + +def _serialized_optional_str(data: dict[str, Any], field: str) -> str | None: + value = data.get(field) + if value is None: + return None + if not isinstance(value, str): + raise ValueError( + f"Serialized DebugMode call field {field!r} must be a string or None, " + f"but found {type(value).__name__}" + ) + return value + + +def _serialize_debug_call(call: _DebugCall) -> dict[str, Any]: + data = _serialize_common_call_fields(call) + if isinstance(call, _OpCall): + data.update( + { + "type": "op", + "op_name": _get_call_name(call), + "args_str": _op_call_args_str(call), + "kwargs_str": _op_call_kwargs_str(call), + } + ) + elif isinstance(call, _RedistributeCall): + data.update( + { + "type": "redistribute", + "arg_str": _redistribute_arg_str(call), + "src_placement_str": _arg_to_str(call.src_placement, []), + "dst_placement_str": _arg_to_str(call.dst_placement, []), + "transform_info_str": call.transform_info_str, + "is_explicit": call.is_explicit, + "is_outer_call": call.is_outer_call, + } + ) + elif isinstance(call, _OutputPlacementCall): + data.update( + { + "type": "output_placement", + "placements_str": call.placements_str, + } + ) + elif isinstance(call, _TritonKernelCall): + data.update( + { + "type": "triton_kernel", + "kernel_name": call.kernel_name, + "kwargs_str": _triton_kwargs_str(call), + "pre_hashes": _serialize_optional_debug_value(call.pre_hashes), + "post_hashes": _serialize_optional_debug_value(call.post_hashes), + } + ) + elif isinstance(call, _AnnotateCall): + data.update( + { + "type": "annotate", + "tag": str(call.tag), + "header": call.header, + } + ) + else: + raise TypeError(f"Unsupported DebugMode call type: {type(call).__name__}") + return data + + +def _deserialize_debug_call(data: Any) -> _DebugCall: + if not isinstance(data, dict): + raise ValueError( + f"Serialized DebugMode call must be a dict, but found {type(data).__name__}" + ) + call_type = data.get("type") + call_depth = data.get("call_depth") + if not isinstance(call_depth, int): + raise ValueError("Serialized DebugMode call must contain an integer call_depth") + + if call_type == "op": + call = _OpCall(_serialized_str(data, "op_name"), (), {}, call_depth) + call.args_str = _serialized_str(data, "args_str") + call.kwargs_str = _serialized_str(data, "kwargs_str") + elif call_type == "redistribute": + arg_str = _serialized_str(data, "arg_str") + call = _RedistributeCall( + arg_str, + _serialized_str(data, "src_placement_str"), + _serialized_str(data, "dst_placement_str"), + _serialized_optional_str(data, "transform_info_str"), + call_depth, + is_explicit=bool(data.get("is_explicit")), + ) + call.arg_str = arg_str + # Serialized redistribute calls only keep rendered args, so restore the + # outer-call classification instead of relying on __init__'s arg type. + call.is_outer_call = bool(data.get("is_outer_call")) + elif call_type == "output_placement": + call = _OutputPlacementCall(_serialized_str(data, "placements_str"), call_depth) + elif call_type == "triton_kernel": + call = _TritonKernelCall(_serialized_str(data, "kernel_name"), {}, call_depth) + call.kwargs_str = _serialized_str(data, "kwargs_str") + call.pre_hashes = _deserialize_optional_debug_value(data.get("pre_hashes")) + call.post_hashes = _deserialize_optional_debug_value(data.get("post_hashes")) + elif call_type == "annotate": + call = _AnnotateCall( + _serialized_str(data, "tag"), _serialized_str(data, "header"), call_depth + ) + else: + raise ValueError(f"Unknown serialized DebugMode call type: {call_type!r}") + + _restore_common_call_fields(call, data) + return call + + +def _get_call_name(call: _DebugCall) -> str: + """String identifying _DebugCall (e.g. func, kernel, module name)""" + if isinstance(call, _OpCall): + return _get_op_name(call.op) + elif isinstance(call, _TritonKernelCall): + return call.kernel_name + elif isinstance(call, _AnnotateCall): + return f"[{call.header}] {call.tag}" + elif isinstance(call, _RedistributeCall): + return REDISTRIBUTE_FUNC + else: + return str(call) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/_mode.py b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..3f7fa4364a694bcb71169c3f16e5aa18183b16e9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/_mode.py @@ -0,0 +1,1121 @@ +# mypy: allow-untyped-defs +""" +DebugMode is a debugging TorchDispatchMode that intercepts and logs runtime calls +to a hierarchical string dump. It logs real tensor, DTensor, and optionally FakeTensor +operations, with some additional handling for DTensor internals. + +An example dump from an eager mode DTensor matmul: + + torch.mm(dt$0: f32[8, 8]| S(0), dt$1: f32[8, 32]| S(0)) -> dt$6: f32[8, 32]| S(0) + aten::mm(dt$0: f32[8, 8]| S(0), dt$1: f32[8, 32]| S(0)) + redistribute_input(1, S(0) -> R) + redistribute_input(t$2: f32[1, 32], trace: S(0)->R) + _c10d_functional::all_gather_into_tensor(t$2: f32[1, 32], 8, 0) -> t$3: f32[8, 32] + _c10d_functional::wait_tensor(t$3: f32[8, 32]) -> t$3: f32[8, 32] + aten::mm(t$4: f32[1, 8], t$3: f32[8, 32]) -> t$5: f32[1, 32] + +This mode runs "under" compile, which means it hides itself during compilation, and is re-enabled +at runtime, and DebugMode-related operations won't show up in the compiled region. +DebugMode also provides some visibility into non-torch-dispatch calls (e.g. DTensor redistribute calls, +inductor-generated triton kernels), but requires special handling for these, since dispatch modes +can't intercept them by default. + +The mode also provides some extensions for custom debugging (e.g. adding custom dispatch call hooks +via dispatch_hooks), or numerics debugging (e.g. tensor hashing for bitwise equivalence/closeness, +via log_tensor_hashes). These decorators allow annotating string dumps with additional per-call information, +for any region of runtime code. + +Usage:: + + with DebugMode() as debug_mode: + result = some_pytorch_operation(tensor_input) + print(debug_mode.debug_string()) +""" + +import contextlib +import functools +import json +import logging +import os +from collections.abc import Callable +from typing import Any, IO, TYPE_CHECKING + +import torch +from torch._logging import warning_once +from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode + +# Import _utils module for mutable globals +from torch.utils._debug_mode import _utils +from torch.utils._debug_mode._calls import ( + _AnnotateCall, + _deserialize_debug_call, + _get_call_name, + _OpCall, + _OutputPlacementCall, + _RedistributeCall, + _serialize_debug_call, + _TritonKernelCall, +) +from torch.utils._debug_mode._utils import ( + _compute_rel_diff, + _get_user_stack_trace, + _run_dispatch_hooks, + _run_dispatch_pre_log_hooks, + _stringify_dtensor_spec, + hash_tensor_fn, + norm_hash_fn, + TensorIdTracker, +) +from torch.utils._python_dispatch import ( + _get_current_dispatch_mode, + _get_current_dispatch_mode_stack, + TorchDispatchMode, +) +from torch.utils._pytree import ( + keystr, + tree_all, + tree_map, + tree_map_only, + tree_map_with_path, +) + + +if TYPE_CHECKING: + from torch.distributed._tools.mod_tracker import ModTracker + + +log = logging.getLogger(__name__) + +_SERIALIZED_LOG_FORMAT = "torch.utils._debug_mode.DebugMode.logs" +_SERIALIZED_LOG_VERSION = 1 + + +# Counter for active DebugMode instances (fast path for get_active_debug_mode) +_ACTIVE_DEBUG_MODE_COUNT = 0 + +_annotate_decorated = False + + +def _ensure_annotate_decorated(): + """ + Lazily apply dont_skip_tracing decorator to DebugMode._annotate, to avoid circular import/initialization issues. + """ + global _annotate_decorated + if not _annotate_decorated: + DebugMode._annotate = torch._dynamo.dont_skip_tracing(DebugMode._annotate) # type: ignore[has-type] + + # Mark annotate as side-effectful so aot_eager doesn't DCE it. + from torch.fx.node import _side_effectful_functions + + _side_effectful_functions.add(torch.ops.debug_mode_ops.annotate.default) + + # Register no-op lowering for inductor backend + from torch._inductor.lowering import register_lowering + + @register_lowering(torch.ops.debug_mode_ops.annotate) + def _annotate_lowering(tag: str) -> None: + warning_once(log, 'DebugMode._annotate() is a no-op for backend="inductor"') + return None + + _annotate_decorated = True + + +@torch.library.custom_op("debug_mode_ops::annotate", mutates_args=()) +def _annotate(tag: str) -> None: + # This is special-cased in DebugMode.__torch_dispatch__ + return None + + +@_annotate.register_fake +def _annotate_fake(tag: str) -> None: + return None + + +class DebugInterpreter(torch.fx.Interpreter): + """ + Interpreter class for running aot_eager compiled regions when DebugMode is active, + instead of using the compiled code. This gives us access to fx.Node metadata to decorate + and contextualize DebugMode logs (e.g. nn_module_stack, stack_trace, compiled region boundaries). + + Note: this is currently only enabled with DebugMode(run_compile_with_interpreter=True). + """ + + def __init__(self, module, backend): + super().__init__(module) + self.mode = get_active_debug_mode() + if self.mode is None: + raise RuntimeError("No DebugMode is currently active") + + # for tracking initial nn_module_stack + self.base_nn_module_stack = list(self.mode.current_nn_module_stack) + + # annotate start of region + self.backend = backend + self.mode.operators.append( + _AnnotateCall( + "enter", f"{self.backend} region (compile)", self.mode.call_depth + ) + ) + + def run_node(self, n: torch.fx.Node) -> Any: + if self.mode is None: + raise RuntimeError("No DebugMode is currently active") + + # handling of nn.Module stack + if self.mode.record_nn_module and n.op not in ["placeholder", "output"]: + self.mode._handle_fx_nn_module_stack( + self.base_nn_module_stack, + n.meta.get("nn_module_stack", {}), + n.meta.get("fwd_nn_module_stack", {}), + ) + + # override stack trace with n.meta + if ( + self.mode.record_stack_trace + and n.op not in ["placeholder", "output"] + and (stack_trace := n.meta.get("stack_trace", None)) is not None + ): + with self.mode.set_fx_stack_trace(stack_trace): + return super().run_node(n) + else: + return super().run_node(n) + + def run(self, *args, **kwargs): + if self.mode is None: + raise RuntimeError("No DebugMode is currently active") + result = super().run(*args) + + # reset nn.Module stack to pre-compiled region value + if len(self.mode.current_nn_module_stack) < len(self.base_nn_module_stack): + warning_once( + log, "unexpected handling of nn_module_stack in DebugInterpreter" + ) + while len(self.mode.current_nn_module_stack) > len(self.base_nn_module_stack): + self.mode._exit_nn_module_call() + + # annotate end of region + self.mode.operators.append( + _AnnotateCall( + "exit", f"{self.backend} region (compile)", self.mode.call_depth + ) + ) + + return result + + +class DebugMode(TorchDispatchMode): + def __init__( + self, + *, + record_torchfunction=False, + record_faketensor=False, + record_realtensor=True, + record_tensor_attributes=None, + record_nn_module=False, + store_original_args=False, + record_stack_trace=False, + record_output=True, + record_ids=False, + record_profiler_context=True, + record_localtensor=True, + run_compile_with_interpreter=False, + ) -> None: + super().__init__() + import torch.distributed.tensor # noqa: F401 + + _ensure_annotate_decorated() + self.supports_higher_order_operators = True + + # Pushes DebugMode onto the torchfunction stack, and records __torch_function__ calls as well. + # WARNING: currently incompatible with torch.compile due to dynamo guard failures. + self.record_torchfunction = record_torchfunction + + # Records __torch_dispatch__ calls on FakeTensors. + self.record_faketensor = record_faketensor + + # Records __torch_dispatch__ calls on real tensors. + self.record_realtensor = record_realtensor + + # Records __torch_dispatch__ calls on LocalTensor. + self.record_localtensor = record_localtensor + + # Optional list[str] of tensor attributes, to be annotated in the string dump. + self.record_tensor_attributes = record_tensor_attributes or [] + + # Uses ModTracker to record nn.Module entrances. + # This flag currently has no effect on torch.compiled-regions. + self.record_nn_module = record_nn_module + + self.module_tracker: ModTracker | None = None + if self.record_nn_module: + self.module_tracker_setup() + + # If True, stores call args/kwargs in logs, without immediately stringifying. + # Defaults to False for memory concerns. + self.store_original_args = store_original_args + + # For stack trace recording, stores log call stack traces in .stack_trace. + # For backward graph nodes, will also store the corresponding forward stack traces in .fwd_stack_trace. + # NOTE: this is only available if autograd tracebacks are being set during the forward pass, + # e.g. via DebugMode(record_stack_trace=True), or torch.autograd.set_detect_anomaly(). + self.record_stack_trace = record_stack_trace + + # Records call outputs in logs (e.g. for __torch_dispatch__, __torch_function__, redistribute_input) + self.record_output: bool = record_output + + # Annotates string dumps with graph-style tensor ids, e.g. op($1, $2) -> $3. + self.record_ids: bool = record_ids + + # Annotates string dumps with profiler.record_function contexts from runtime code. + # Currently does not preserve contexts inside torch.compile-d regions. + self.record_profiler_context: bool = record_profiler_context + + # For aot_eager compiled regions, wraps the compiled fx.GraphModule with a DebugInterpreter, + # and uses it at runtime for node metadata visibility. + self.run_compile_with_interpreter: bool = run_compile_with_interpreter + + self.reset() + + def reset(self) -> None: + self.operators = [] + self.call_depth = 0 + self._tensor_memo = TensorIdTracker() + self._output_info: dict[int, object] = {} + self.ignored_record_functions = 0 + self.current_nn_module_stack = [] + self.fx_stack_trace = None + + def _track_op_output(self, op_index, result) -> None: + """Assign IDs to output tensors and store in output_info""" + self._output_info[op_index] = result + + # Without this override, running torch.compile under DebugMode + # will force torch.compile to always use the "eager" backend + # With this, DebugMode will not take effect on torch.compile + @classmethod + def ignore_compile_internals(cls) -> bool: + return True + + def _record_call(self, call) -> None: + if _utils._IN_INDUCTOR_BENCHMARK: + return + + if str(call).startswith("profiler::_record_function"): + return + + if not self.store_original_args: + call.stringify_args( + self.record_tensor_attributes, + self._tensor_memo if self.record_ids else None, + ) + if self.fx_stack_trace: + call.stack_trace = call.fwd_stack_trace = self.fx_stack_trace + self.operators.append(call) + + def _record_call_output(self, call, output) -> None: + if not self.record_output: + return + call.stringify_output( + output, + self.record_tensor_attributes, + self._tensor_memo if self.record_ids else None, + ) + + def __torch_function__(self, func, types, args=(), kwargs=None): + if kwargs is None: + kwargs = {} + + call = _OpCall( + func, args, kwargs, self.call_depth, stack=self.record_stack_trace + ) + self._record_call(call) + + try: + self.call_depth += 1 + result = func(*args, **kwargs) + self._record_call_output(call, result) + return result + finally: + self.call_depth -= 1 + + def _maybe_record_function(self, tag): + # filter out tags that appear noisy, or aren't runtime-related + if any( + tag.startswith(prefix) + for prefix in [ + # assuming these are from benchmarking, not the actual runtime call + "CachingAutotuner.", + "InductorBenchmarker.", + # inductor compilation + "compile_fx..", + ] + ): + self.ignored_record_functions += 1 + return + + call = _AnnotateCall( + tag, "record function", self.call_depth, stack=self.record_stack_trace + ) + self.operators.append(call) + self.call_depth += 1 + + def _maybe_exit_record_function(self): + if self.ignored_record_functions < 0: + raise AssertionError( + f"ignored_record_functions is negative: {self.ignored_record_functions}" + ) + if self.ignored_record_functions > 0: + self.ignored_record_functions -= 1 + else: + self.call_depth -= 1 + + def __torch_dispatch__(self, func, types, args=(), kwargs=None): + if kwargs is None: + kwargs = {} + + # Handle record_function entries + if self.record_profiler_context: + if func == torch.ops.profiler._record_function_enter_new.default: + if len(args) != 1: + raise AssertionError(f"expected 1 arg, got {len(args)}") + self._maybe_record_function(args[0]) + elif func == torch.ops.profiler._record_function_exit._RecordFunction: + self._maybe_exit_record_function() + + # Handle DebugMode._annotate() + if func is torch.ops.debug_mode_ops.annotate.default: + if len(args) != 1: + raise AssertionError(f"expected 1 arg, got {len(args)}") + self._handle_annotate(args[0]) + return + + from torch.distributed._functional_collectives import AsyncCollectiveTensor + from torch.distributed._local_tensor import LocalTensor + + # Record the operation with its call depth + call = None + if torch.distributed.tensor.DTensor in types: + call = _OpCall( + func, args, kwargs, self.call_depth, stack=self.record_stack_trace + ) + self._record_call(call) + return NotImplemented + elif FakeTensor in types or isinstance( + _get_current_dispatch_mode(), FakeTensorMode + ): + if self.record_faketensor: + if func != torch.ops.prim.device.default: + call = _OpCall( + func, + args, + kwargs, + self.call_depth + 1, + stack=self.record_stack_trace, + ) + self._record_call(call) + # TODO: check the context manager + elif LocalTensor in types: + if self.record_localtensor: + call = _OpCall( + func, + args, + kwargs, + self.call_depth + 1, + stack=self.record_stack_trace, + ) + self._record_call(call) + elif AsyncCollectiveTensor in types: + # Record AsyncCollectiveTensor operations so debugging/tracing tools can see them + if self.record_realtensor: + call = _OpCall( + func, + args, + kwargs, + self.call_depth + 1, + stack=self.record_stack_trace, + ) + self._record_call(call) + elif len(types) == 0: + if self.record_realtensor: + call = _OpCall( + func, + args, + kwargs, + self.call_depth + 1, + stack=self.record_stack_trace, + ) + self._record_call(call) + + # Run pre-hooks before executing the operation to hash inputs + # We have to run before the func() call in case there's any + # in-place mutation + if call: + _run_dispatch_pre_log_hooks(call, func, types, args, kwargs) + + result = func(*args, **kwargs) + if call: + self._record_call_output(call, result) + _run_dispatch_hooks(call, func, types, args, kwargs, result) + + return result + + def __enter__(self): + global _ACTIVE_DEBUG_MODE_COUNT + _ACTIVE_DEBUG_MODE_COUNT += 1 + if self.record_torchfunction: + torch._C._push_on_torch_function_stack(self) + + super().__enter__() + if self.record_nn_module: + self.module_tracker.__enter__() # type: ignore[attribute, union-attr] + + if self.record_stack_trace: + self.anomaly_for_traces = torch.autograd.set_detect_anomaly( + True, check_nan=False + ) + self.anomaly_for_traces.__enter__() + return self + + # pyrefly: ignore [bad-override] + def __exit__(self, *args): + global _ACTIVE_DEBUG_MODE_COUNT + _ACTIVE_DEBUG_MODE_COUNT -= 1 + super().__exit__(*args) + if self.record_nn_module: + self.module_tracker.__exit__() # type: ignore[attribute, union-attr] + if self.record_torchfunction: + torch._C._pop_torch_function_stack() + if self.record_stack_trace: + self.anomaly_for_traces.__exit__(*args) + + @contextlib.contextmanager + def set_fx_stack_trace(self, stack_trace): + self.fx_stack_trace = stack_trace + try: + yield + finally: + self.fx_stack_trace = None + + def _enter_nn_module_call(self, fqn, header): + call = _AnnotateCall( + fqn, header, self.call_depth + 1, stack=self.record_stack_trace + ) + self.operators.append(call) + self.current_nn_module_stack.append(fqn) + self.call_depth += 1 + + def _exit_nn_module_call(self): + self.call_depth -= 1 + self.current_nn_module_stack.pop() + + def module_tracker_setup(self) -> None: + from torch.distributed._tools.mod_tracker import ModTracker + + self.module_tracker = ModTracker() + + # module pre-fw hook: record module call + def pre_fw_hook(module, input) -> None: + fqn = self.module_tracker._get_mod_name(module) # type: ignore[attribute, union-attr] + self._enter_nn_module_call(fqn, "nn.Mod") + + # module post-fw hook: decrement call depth + def post_fw_hook(module, input, output) -> None: + self._exit_nn_module_call() + + self.module_tracker.register_user_hooks(pre_fw_hook, post_fw_hook) + + def _handle_fx_nn_module_stack( + self, + base_stack: list[str], + nn_module_stack: dict[str, tuple[str, Any]] | None, + fwd_nn_module_stack: dict[str, tuple[str, Any]] | None, + ) -> None: + """ + Called when DebugInterpreter observes nn_module_stack or fwd_nn_module_stack metadata + from executing the compiled GraphModule. + + If the current module stack is mismatched with what's currently tracked in DebugMode + (current_nn_module_stack), we adjust call depth and add new [nn.Module] log entries accordingly. + """ + + nn_module_stack = nn_module_stack or {} + fwd_nn_module_stack = fwd_nn_module_stack or {} + if nn_module_stack and fwd_nn_module_stack: + raise AssertionError( + "Expecting at most one of nn_module_stack and fwd_nn_module_stack." + ) + + is_fwd = nn_module_stack + stack = nn_module_stack if is_fwd else fwd_nn_module_stack + + # forward stack + current_stack = self.current_nn_module_stack + new_stack = base_stack + [v[0] for v in stack.values()] + + entered = set(new_stack) - set(current_stack) + exited = set(current_stack) - set(new_stack) + + # Decrement depth for exited modules + for _ in exited: + self._exit_nn_module_call() + if self.call_depth < 0: + raise AssertionError("Unexpectedly, DebugMode call_depth is negative") + + # Add [nn.Module] entries for newly entered modules + for fqn in sorted(entered): + self._enter_nn_module_call( + fqn, "nn.Mod (compile)" if is_fwd else "nn.Mod (compile bwd)" + ) + + self.current_nn_module_stack = new_stack + + @contextlib.contextmanager + def record_redistribute_calls( + self, + arg, + src_placement, + dst_placement, + transform_info_str: str | None = None, + is_explicit: bool = False, + ): + try: + self._record_call( + _RedistributeCall( + arg, + src_placement=src_placement, + dst_placement=dst_placement, + transform_info_str=transform_info_str, + call_depth=self.call_depth + 1, + stack=self.record_stack_trace, + is_explicit=is_explicit, + ) + ) + self.call_depth += 1 + yield + finally: + self.call_depth -= 1 + + def record_output_placements(self, output_spec) -> None: + """Record output placements for a DTensor op as a separate line.""" + if not self.record_output: + return + from torch.distributed.tensor._dtensor_spec import DTensorSpec + + placements_str = str( + tree_map_only(DTensorSpec, _stringify_dtensor_spec, output_spec) + ) + call = _OutputPlacementCall(placements_str, self.call_depth + 1) + self._record_call(call) + + def record_triton_kernel( + self, kernel_name: str, kwargs: dict[str, Any] + ) -> _TritonKernelCall: + call = _TritonKernelCall(kernel_name, kwargs, self.call_depth + 1) + call.stringify_args(self.record_tensor_attributes) + self.operators.append(call) + return call + + def debug_string(self, show_stack_trace: bool | None = None) -> str: + """ + show_stack_trace: option to display one-line stack trace summaries above groups + of operations (similar to gm.print_readable() style). + Requires record_stack_trace=True. + if None, uses self.record_stack_trace, otherwise overrides it. + """ + show_stack_trace = ( + self.record_stack_trace if show_stack_trace is None else show_stack_trace + ) + + with torch._C.DisableTorchFunction(): + if not show_stack_trace: + result = "\n".join( + " " + + " " * op.call_depth + + op.render(self.record_tensor_attributes) + for op in self.operators + ) + return result + + # Group operations by stack trace + lines = [] + prev_stack_summary = None + + for op in self.operators: + # Get the stack trace: prefer fwd_stack_trace, fallback to stack_trace + stack_trace = None + if hasattr(op, "fwd_stack_trace") and op.fwd_stack_trace: + stack_trace = op.fwd_stack_trace + elif hasattr(op, "stack_trace") and op.stack_trace: + stack_trace = op.stack_trace + + stack_summary = None + if stack_trace: + stack_summary = _get_user_stack_trace(stack_trace) + + if stack_summary and stack_summary != prev_stack_summary: + # add blank line before stack trace comment for readability + if lines: # don't add blank line at the very start + lines.append("") + indent = " " * (op.call_depth + 1) + lines.append(indent + "# " + stack_summary) + prev_stack_summary = stack_summary + + # Add the operation line + line = ( + " " + + " " * op.call_depth + + op.render(self.record_tensor_attributes) + ) + lines.append(line) + + return "\n".join(lines) + + @staticmethod + @contextlib.contextmanager + def dispatch_hooks( + record_hook: Callable | None = None, + log_hook: Callable | None = None, + pre_log_hook: Callable | None = None, + ): + """ + Allows installing post-hooks on arguments to intercepted __torch_dispatch__ calls; + hook signatures are expected as (func, types, args, kwargs, result), + i.e. __torch_dispatch__ args + return value. + + Logging hook outputs are stored in call.log and annotate calls in debug_string(), + while recording hook outputs are just stored in call.record. + For now hooks are expected to return dictionaries. + + pre_log_hook signature is (func, types, args, kwargs, call) and is executed before + the operation. It allows capturing state before in-place mutations. + """ + if record_hook: + _utils._DISPATCH_RECORD_HOOKS.append(record_hook) + if log_hook: + _utils._DISPATCH_LOG_HOOKS.append(log_hook) + if pre_log_hook: + _utils._DISPATCH_PRE_LOG_HOOKS.append(pre_log_hook) + try: + yield + finally: + if record_hook: + _utils._DISPATCH_RECORD_HOOKS.pop() + if log_hook: + _utils._DISPATCH_LOG_HOOKS.pop() + if pre_log_hook: + _utils._DISPATCH_PRE_LOG_HOOKS.pop() + + @staticmethod + @contextlib.contextmanager + def record_outputs(): + """ + Hook for storing cloned output tensors in .record["output"]. + """ + + def dispatch_hook(func, types, args, kwargs, result): + out = tree_map( + lambda x: x.clone() if isinstance(x, torch.Tensor) else x, result + ) + return {"output": out} + + try: + _old_record_triton = _utils._RECORD_TRITON_OUTPUTS + _utils._RECORD_TRITON_OUTPUTS = True + with DebugMode.dispatch_hooks(record_hook=dispatch_hook): + yield + finally: + _utils._RECORD_TRITON_OUTPUTS = _old_record_triton + + @staticmethod + @contextlib.contextmanager + def log_tensor_hashes( + hash_fn: Callable | str | list[str] = "norm", hash_inputs: bool = False + ): + """ + Installs hook for tensor hash logging. + + hash_fn: One of: + - Custom-defined hash function + - String: one of ("norm", "hash_tensor") + - "norm": uses norm_hash_fn; basically tensor's L1 norm + - "hash_tensor": uses torch.hash_tensor (XOR sum reduction) + - List of strings: returns tuple of hashes from above options + hash_inputs: if True, also hashes tensors in (args, kwargs), storing them in "input_hash". + Input hashes are captured before the operation executes, so they reflect the state before + any in-place mutations. + """ + + def hash_fn_option(hash_type): + if not isinstance(hash_type, str) or hash_type not in [ + "norm", + "hash_tensor", + ]: + raise AssertionError( + f"hash_type must be 'norm' or 'hash_tensor', got {hash_type!r}" + ) + return functools.partial( + norm_hash_fn if hash_type == "norm" else hash_tensor_fn, use_scalar=True + ) + + if callable(hash_fn): + fn = hash_fn + elif isinstance(hash_fn, str): + fn = hash_fn_option(hash_fn) + elif isinstance(hash_fn, list): + fns = [hash_fn_option(fn) for fn in hash_fn] + fn = lambda x: tuple(fn(x) for fn in fns) # noqa: E731 + else: + raise NotImplementedError( + f"log_tensor_hashes() expected hash_fn to be callable, str, or list[str], but found {type(hash_fn)}" + ) + + def _tree_hash(obj): + return tree_map( + lambda x: fn(x) if isinstance(x, torch.Tensor) else None, obj + ) + + def _dispatch_pre_log_hook(func, types, args, kwargs, call): + """Pre-hook to capture input hashes before operation executes""" + if "empty" in str(func) or "profiler" in str(func): + return None + + if hash_inputs: + # Capture input hashes before the operation + input_hash = _tree_hash((args, kwargs)) + if not tree_all(lambda x: x is None, input_hash): + return {"input_hash": input_hash} + return None + + def _dispatch_post_hook(func, types, args, kwargs, result): + """Post-hook to capture output hashes after operation executes""" + if "empty" in str(func) or "profiler" in str(func): + return None + + out = {} + out["hash"] = _tree_hash(result) + + if tree_all(lambda x: x is None, out.values()): + return None + return out + + try: + if hash_inputs: + _old_input_hfn = _utils._TRITON_INPUT_HASH_FN + _utils._TRITON_INPUT_HASH_FN = fn + _old_output_hfn = _utils._TRITON_OUTPUT_HASH_FN + _utils._TRITON_OUTPUT_HASH_FN = fn + with DebugMode.dispatch_hooks( + log_hook=_dispatch_post_hook, + pre_log_hook=_dispatch_pre_log_hook if hash_inputs else None, + ): + yield + finally: + if hash_inputs: + _utils._TRITON_INPUT_HASH_FN = _old_input_hfn # type: ignore[assignment] + _utils._TRITON_OUTPUT_HASH_FN = _old_output_hfn + + @staticmethod + @contextlib.contextmanager + def _benchmarking_inductor(): + """ + Context manager for disabling logging during inductor benchmarking, + so logs don't contain all kernels launched from autotuning. + """ + try: + _utils._IN_INDUCTOR_BENCHMARK = True + yield + finally: + _utils._IN_INDUCTOR_BENCHMARK = False + + @property + def logs(self): + return list(self.operators) + + @staticmethod + def save_logs(logs: list, destination: str | os.PathLike | IO[str]) -> None: + """ + Save DebugMode logs to a JSON file so they can be loaded and compared in + another Python process. + + Args: + logs: logs from a DebugMode run (from debug_mode.logs) + destination: path or text file object to write + """ + data = { + "format": _SERIALIZED_LOG_FORMAT, + "version": _SERIALIZED_LOG_VERSION, + "logs": [_serialize_debug_call(call) for call in logs], + } + if isinstance(destination, (str, os.PathLike)): + with open(destination, "w", encoding="utf-8") as f: + json.dump(data, f, allow_nan=False) + f.write("\n") + else: + json.dump(data, destination, allow_nan=False) + destination.write("\n") + + @staticmethod + def load_logs(source: str | os.PathLike | IO[str]) -> list: + """ + Load logs saved by DebugMode.save_logs(). + + Args: + source: path or text file object to read + + Returns: + A list of DebugMode log records suitable for check_hash_mismatches(). + """ + if isinstance(source, (str, os.PathLike)): + with open(source, encoding="utf-8") as f: + data = json.load(f) + else: + data = json.load(source) + + if not isinstance(data, dict): + raise ValueError( + f"Serialized DebugMode logs must be a dict, but found {type(data).__name__}" + ) + if data.get("format") != _SERIALIZED_LOG_FORMAT: + raise ValueError( + "Serialized DebugMode logs have an unrecognized format: " + f"{data.get('format')!r}" + ) + if data.get("version") != _SERIALIZED_LOG_VERSION: + raise ValueError( + "Serialized DebugMode logs have an unsupported version: " + f"{data.get('version')!r}" + ) + logs = data.get("logs") + if not isinstance(logs, list): + raise ValueError("Serialized DebugMode logs must contain a logs list") + return [_deserialize_debug_call(call) for call in logs] + + def _handle_annotate(self, tag): + """Handles DebugMode._annotate()""" + call = _AnnotateCall(tag, "annotate", self.call_depth, self.record_stack_trace) + self.operators.append(call) + + @staticmethod + def _annotate(tag: Any) -> None: + """ + If an active DebugMode exists, adds an "[annotate] " entry to the logs. Useful for contextualizing logs. + Implemented with a custom op. + """ + torch.ops.debug_mode_ops.annotate(tag) + + @staticmethod + def check_hash_mismatches( + logs1: list, logs2: list, compare_inputs: bool = False + ) -> list[dict]: + """ + Compares tensor hashes between two DebugMode runs, for checking run-to-run numerical divergence. + + This first validates the two log sequences have identical structure (same operations, input shapes/dtypes, etc.), + then compares tensor hash values, and returns a list of call outputs where mismatches were found. + Expects input logs to have been run with log_tensor_hashes, and looks for hashes in .log["hash"] & .log["input_hash"] + (or .post_hashes & .pre_hashes for triton kernels). + + note: skips checking log pairs where hashes aren't present, but will raise if present in one & not the other. + + Args: + logs1: logs from the first DebugMode run (from debug_mode.logs) + logs2: logs from the second DebugMode run + compare_inputs: If True, also compare input tensor hashes (default: only output checking) + + Returns: + List of dictionaries describing hash mismatches. Each dict contains: + - call_type: "torch op" or "triton kernel" + - call: Operator/kernel name + - arg_name: For triton kernels, the argument name; None for torch ops + - pytree_path: For torch ops, the pytree path to the differing tensor; None for kernels + - hash1: Hash value from the first run + - hash2: Hash value from the second run + - rel_diff: Relative difference between hash values + - is_input_hash: True if this is an input hash, False for output hash + + Raises: + ValueError: If logs have different lengths, call types, operator names, or call depths + + Usage:: + + # Process 1: run the first model config and save its logs + with DebugMode() as debug_mode, DebugMode.log_tensor_hashes(): + model_config_1(x) + DebugMode.save_logs(debug_mode.logs, "run1.json") + + # Process 2: run the second model config and save its logs + with DebugMode() as debug_mode, DebugMode.log_tensor_hashes(): + model_config_2(x) + DebugMode.save_logs(debug_mode.logs, "run2.json") + + logs1 = DebugMode.load_logs("run1.json") + logs2 = DebugMode.load_logs("run2.json") + mismatches = DebugMode.check_hash_mismatches(logs1, logs2) + for m in mismatches: + print(f"{m['call']}: hash diff {m['rel_diff']:.2e}") + """ + if len(logs1) != len(logs2): + raise ValueError(f"Log lengths don't match: {len(logs1)} vs {len(logs2)}") + + difference_info = [] + for i, (log1, log2) in enumerate(zip(logs1, logs2)): + # check call type + call1_type = type(log1).__name__ + call2_type = type(log2).__name__ + if call1_type != call2_type: + raise ValueError( + f"Call types don't match at index {i}: {call1_type} vs {call2_type}" + ) + call_type = call1_type + + # check call name + op1_name, op2_name = _get_call_name(log1), _get_call_name(log2) + if op1_name != op2_name: + raise ValueError( + f"Operators don't match at index {i}: {call_type}[{op1_name}] vs {call_type}[{op2_name}]" + ) + op_name = op1_name + + # check call depth + if log1.call_depth != log2.call_depth: + raise ValueError( + f"Call depths for {call_type}[{op_name}] don't match at index {i}: {log1.call_depth} vs {log2.call_depth}" + ) + + # Redistribute: call args should be the same + if isinstance(log1, _RedistributeCall): + if log1.render([]) != log2.render([]): + raise ValueError( + f"Redistribute calls don't match at index {i}: {log1} vs {log2}" + ) + + # Triton kernel: same arg names, arg types + elif isinstance(log1, _TritonKernelCall): + if log1.kwargs_str != log2.kwargs_str: + raise ValueError( + f"Triton kernel call args don't match for {log1.kernel_name} at index {i}:" + f"\n\nlog1: {log1.kwargs_str}\n\nlog2: {log2.kwargs_str}" + ) + + def compare_triton_hashes(hashes1, hashes2, is_input): + if set(hashes1.keys()) != set(hashes2.keys()): # type: ignore[union-attr] + raise AssertionError( + f"hash key mismatch: {set(hashes1.keys())} vs {set(hashes2.keys())}" + ) + for key in hashes1: + if hashes1[key] != hashes2[key]: + difference_info.append( + { + "call_type": "triton kernel", + "call": op_name, + "arg_name": key, + "pytree_path": None, + "hash1": hashes1[key], + "hash2": hashes2[key], + "rel_diff": _compute_rel_diff( + hashes1[key], hashes2[key] + ), + "is_input_hash": is_input, + } + ) + + # check output hashes + has_post_1, has_post_2 = ( + log1.post_hashes is not None, + log2.post_hashes is not None, + ) + if has_post_1 != has_post_2: + raise ValueError( + f"Triton kernel post-hash presence inconsistent for {log1.kernel_name} " + f"at index {i}: log1 has post_hashes={has_post_1}, log2 has post_hashes={has_post_2}" + ) + + if has_post_1: + compare_triton_hashes( + log1.post_hashes, log2.post_hashes, is_input=False + ) + + # maybe check input hashes + if compare_inputs: + has_pre_1, has_pre_2 = ( + log1.pre_hashes is not None, + log2.pre_hashes is not None, + ) + if has_pre_1 != has_pre_2: + raise ValueError( + f"Triton kernel pre-hash presence inconsistent for {log1.kernel_name} " + f"at index {i}: log1 has pre_hashes={has_pre_1}, log2 has pre_hashes={has_pre_2}" + ) + + if has_pre_1: + compare_triton_hashes( + log1.pre_hashes, log2.pre_hashes, is_input=True + ) + + # regular log calls + elif isinstance(log1, _OpCall): + + def compare_op_hashes(hashes1, hashes2, is_input): + def _helper(keypath, hash1, hash2): + if hash1 != hash2: + difference_info.append( + { + "call_type": "torch op", + "call": op_name, + "arg_name": None, + "pytree_path": keystr(keypath), + "hash1": hash1, + "hash2": hash2, + "rel_diff": _compute_rel_diff(hash1, hash2), + "is_input_hash": is_input, + } + ) + + tree_map_with_path(_helper, hashes1, hashes2) + + # check output hashes + has_hash1 = log1.log is not None and "hash" in log1.log + has_hash2 = log2.log is not None and "hash" in log2.log + if has_hash1 != has_hash2: + raise ValueError( + f"Output hash presence inconsistent for triton kernel {call_type}[{op_name}] " + f"at index {i}: log1 has hash={has_hash1}, log2 has hash={has_hash2}" + ) + + if has_hash1: + compare_op_hashes( + log1.log["hash"], # type: ignore[union-attr] + log2.log["hash"], + is_input=False, + ) + + # maybe check input hashes + if compare_inputs: + has_hash1 = log1.log is not None and "input_hash" in log1.log + has_hash2 = log2.log is not None and "input_hash" in log2.log + if has_hash1 != has_hash2: + raise ValueError( + f"Input hash presence inconsistent for triton kernel {call_type}[{op_name}] " + f"at index {i}: log1 has input_hash={has_hash1}, log2 has input_hash={has_hash2}" + ) + + if has_hash1: + compare_op_hashes( + log1.log["input_hash"], # type: ignore[union-attr] + log2.log["input_hash"], + is_input=True, + ) + + return difference_info + + +def get_active_debug_mode() -> DebugMode | None: + # Fast path: if no DebugMode is active, skip the stack walk + if _ACTIVE_DEBUG_MODE_COUNT == 0: + return None + debug_mode = None + for mode in _get_current_dispatch_mode_stack(): + if isinstance(mode, DebugMode): + debug_mode = mode + break + return debug_mode diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/_utils.py b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..77089c0d31821f576f20fa6226c755cd7f6ab62f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_debug_mode/_utils.py @@ -0,0 +1,251 @@ +# mypy: allow-untyped-defs +""" +Utility functions for DebugMode: tensor formatting, hashing, stack traces, and hook runners. +""" + +import inspect +import os +import traceback +import weakref +from collections.abc import Callable +from typing import TYPE_CHECKING + +import torch +from torch._subclasses.fake_tensor import is_fake_tensor +from torch.fx.graph import _parse_stack_trace +from torch.utils._dtype_abbrs import dtype_abbrs +from torch.utils._pytree import tree_map +from torch.utils._traceback import CapturedTraceback +from torch.utils.weak import WeakIdRef + + +if TYPE_CHECKING: + from torch.utils._debug_mode._calls import _DebugCall + + +REDISTRIBUTE_FUNC = "redistribute_input" + +# Tracks if we're in inductor benchmarking, and temporarily disables logging +# (for ignoring autotuning kernel launches which don't affect the user-facing result) +_IN_INDUCTOR_BENCHMARK: bool = False +# For record_outputs, log_tensor_hashes hooks for triton kernels. +# Stores kernel outputs in call.record["output"] +_RECORD_TRITON_OUTPUTS: bool = False +# Annotates kernel output hashes, and stores them in call.post_hashes +_TRITON_OUTPUT_HASH_FN: Callable | None = None +# Annotates kernel input hashes, and stores them in call.pre_hashes +_TRITON_INPUT_HASH_FN: Callable | None = None + +# registered dispatch call hooks +_DISPATCH_RECORD_HOOKS: list[Callable] = [] +_DISPATCH_LOG_HOOKS: list[Callable] = [] +_DISPATCH_PRE_LOG_HOOKS: list[Callable] = [] + + +def _stringify_shape(shape) -> str: + return f"[{', '.join([str(x) for x in shape])}]" + + +def _stringify_device_mesh(mesh) -> str: + return f"DM({', '.join([str(s) for s in mesh.shape])})" + + +def _stringify_placement(placement) -> str: + return f"[{', '.join([str(p) for p in placement])}]" + + +def _stringify_attributes(tensor, attributes) -> str: + pairs = {} + for attr in attributes: + if hasattr(tensor, attr): + pairs[attr] = getattr(tensor, attr) + if len(pairs) == 0: + return "" + return f"{{{', '.join([f'{k}={v}' for k, v in pairs.items()])}}}" + + +def _stringify_dtensor_spec(spec) -> str: + from torch.distributed.tensor._dtensor_spec import DTensorSpec + + return DTensorSpec.format_shard_order_str(spec.placements, spec.shard_order) + + +class TensorIdTracker: + def __init__(self) -> None: + self.tensor_memo: dict[WeakIdRef, int] = {} + self.next_tensor_id = 0 + + def _id(self, tensor) -> int: + with torch._C._DisablePythonDispatcher(): + o = WeakIdRef(tensor) + + def del_memo() -> None: + self.tensor_memo.pop(o, None) + + weakref.finalize(tensor, del_memo) + if o not in self.tensor_memo: + self.tensor_memo[o] = self.next_tensor_id + self.next_tensor_id += 1 + return self.tensor_memo[o] + + +def _tensor_debug_string(tensor, attributes, tensor_memo=None) -> str: + """Convert tensor to debug string representation.""" + + if isinstance(tensor, torch.Tensor): + tensor_debug_str = f"{dtype_abbrs[tensor.dtype]}{_stringify_shape(tensor.shape)}{_stringify_attributes(tensor, attributes)}" + id_str = f"${tensor_memo._id(tensor)}" if tensor_memo is not None else "" + if isinstance(tensor, torch.distributed.tensor.DTensor): + # omitted device mesh + return f"dt{id_str}: {tensor_debug_str}| {_stringify_dtensor_spec(tensor._spec)}" + elif is_fake_tensor(tensor): + return f"ft{id_str}: {tensor_debug_str}" + else: + return f"t{id_str}: {tensor_debug_str}" + else: + raise RuntimeError(f"Unsupported tensor type: {type(tensor)}") + + +def _arg_to_str(arg, attributes, tensor_memo=None) -> str: + from torch.distributed.tensor._dtensor_spec import DTensorSpec + + def to_str(x): + if isinstance(x, torch.Tensor): + return _tensor_debug_string(x, attributes, tensor_memo) + elif isinstance(x, DTensorSpec): + return _stringify_dtensor_spec(x) + return x + + arg = tree_map(to_str, arg) + return str(arg) + + +def norm_hash_fn(t: torch.Tensor, use_scalar: bool = False) -> torch.Tensor | float: + """ + from Observer. Computes a hash for a tensor by converting it to float (if needed), making it contiguous, + replacing NaN/inf values with fixed numbers, and then computing the L1 norm in float64 or complex128. + This is used to generate a deterministic summary value for tensor comparison. + """ + with torch._C._DisablePythonDispatcher(): + if not (t.is_floating_point() or t.is_complex()): + t = t.float() + t = t.contiguous() + + if t.is_complex(): + t_float = t.to(dtype=torch.complex128) + else: + t_float = t.to(dtype=torch.float64) + + out = t_float.norm(p=1) + if use_scalar: + return out.item() + return out + + +def _compute_rel_diff(hash1, hash2): + # Relative difference: |hash1 - hash2| / max(|hash1|, |hash2|, eps) + numerator = abs(hash1 - hash2) + denominator = max(abs(hash1), abs(hash2), 1e-10) + return numerator / denominator + + +def hash_tensor_fn(t: torch.Tensor, use_scalar: bool = False) -> torch.Tensor | int: + """ + wrapper over torch.hash_tensor + """ + if isinstance(t, torch.distributed.tensor.DTensor): + t = t.to_local() + + if t.is_floating_point(): + t_clean = t.to(dtype=torch.float64) + elif t.is_complex(): + t_clean = t.to(dtype=torch.complex128).view(torch.float64) + else: + t_clean = t.to(dtype=torch.int64) + + if t.numel() > 0: + out = torch.hash_tensor(t_clean) + else: + out = torch.zeros((), device=t_clean.device, dtype=torch.uint64) + + if use_scalar: + return out.item() # type: ignore[attribute] + return out + + +def _get_stack_trace() -> str: + from torch.fx.experimental.symbolic_shapes import uninteresting_files + + summary = CapturedTraceback.extract().summary() + summary = summary[:-4] # filter out DebugMode frames + summary = [ + frame for frame in summary if frame.filename not in uninteresting_files() + ] + summary = traceback.StackSummary.from_list(summary) + return "".join(summary.format()) + + +def _get_user_stack_trace(stack_trace_str: str) -> str | None: + # Extract user code stack trace, filtering out torch internals. + torch_dir = os.path.dirname(inspect.getfile(torch)) + filter_fn = lambda file, name, code: not file.startswith(torch_dir + os.path.sep) # noqa: E731 + trace = _parse_stack_trace(stack_trace_str, filter_fn=filter_fn) + if trace: + return f"File: {trace.file}:{trace.lineno} in {trace.name}, code: {trace.code}" + return None + + +def _maybe_get_autograd_trace() -> str | None: + if torch._C._current_autograd_node() is not None: + tb = torch._C._current_autograd_node().metadata.get("traceback_") # type: ignore[attr-defined] + if tb: + return "".join(tb) + return None + + +def _get_op_name(op) -> str: + if isinstance(op, torch._ops.OpOverload): + op_name = op.__qualname__ + elif hasattr(op, "__module__") and hasattr(op, "__name__"): + op_name = f"{op.__module__}.{op.__name__}" + else: + op_name = str(op) + return op_name + + +def _run_hook(hook, *args): + out = hook(*args) + if out is not None and not isinstance(out, dict): + raise AssertionError(f"hook must return None or dict, got {type(out).__name__}") + return out + + +def _run_dispatch_pre_log_hooks(call: "_DebugCall", func, types, args, kwargs) -> None: + if _DISPATCH_PRE_LOG_HOOKS: + for hook in _DISPATCH_PRE_LOG_HOOKS: + hook_out = _run_hook(hook, func, types, args, kwargs, call) + if hook_out is not None: + # Store pre-hook results in call.log + if call.log is None: + call.log = {} + call.log.update(hook_out) + + +def _run_dispatch_hooks(call: "_DebugCall", func, types, args, kwargs, result) -> None: + if _DISPATCH_RECORD_HOOKS: + record = {} + for hook in _DISPATCH_RECORD_HOOKS: + hook_out = _run_hook(hook, func, types, args, kwargs, result) + if hook_out is not None: + record.update(hook_out) + if record: + call.record = record + + if _DISPATCH_LOG_HOOKS: + # Preserve existing log from pre-hooks (e.g., input_hash) + if call.log is None: + call.log = {} + for hook in _DISPATCH_LOG_HOOKS: + hook_out = _run_hook(hook, func, types, args, kwargs, result) + if hook_out is not None: + call.log.update(hook_out) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_device.py b/.venv/lib/python3.12/site-packages/torch/utils/_device.py new file mode 100644 index 0000000000000000000000000000000000000000..8b93bbef8193a339c62b8948998a17d28d8796c0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_device.py @@ -0,0 +1,137 @@ +# mypy: allow-untyped-defs +import functools + +import torch +from torch._C import _len_torch_function_stack +from torch.overrides import _pop_mode, _push_mode, TorchFunctionMode +from torch.utils._contextlib import context_decorator + + +CURRENT_DEVICE: torch.device | None = None + + +@functools.lru_cache(1) +def _device_constructors(): + return { + # standard ones + torch.empty, + torch.empty_permuted, + torch.empty_strided, + torch.empty_quantized, + torch.ones, + torch.arange, + torch.bartlett_window, + torch.blackman_window, + torch.eye, + torch.fft.fftfreq, + torch.fft.rfftfreq, + torch.full, + torch.hamming_window, + torch.hann_window, + torch.kaiser_window, + torch.linspace, + torch.logspace, + torch.nested.nested_tensor, + # This function doesn't actually take a device argument + # torch.normal, + torch.rand, + torch.randn, + torch.randint, + torch.randperm, + torch.range, + torch.sparse_coo_tensor, + torch.sparse_compressed_tensor, + torch.sparse_csr_tensor, + torch.sparse_csc_tensor, + torch.sparse_bsr_tensor, + torch.sparse_bsc_tensor, + torch.tril_indices, + torch.triu_indices, + torch.zeros, + torch.asarray, + # weird ones + torch.tensor, + torch.as_tensor, + torch.scalar_tensor, + # *_like may contain device kwarg, but the user implicitly + # expects a specific device even when kwarg unused. + # torch.zeros_like, + # torch.randint_like, + # torch.randn_like, + # torch.ones_like, + # torch.full_like, + # torch.empty_like, + } + + +# NB: This is directly called from C++ in torch/csrc/Device.cpp +class DeviceContext(TorchFunctionMode): + def __init__(self, device) -> None: + self.device = torch.device(device) + self.prev_mode: DeviceContext | None = None + + def __enter__(self): + global CURRENT_DEVICE + self.old_device = CURRENT_DEVICE + CURRENT_DEVICE = self.device + # We need to put the device at the bottom of the stack + # If we set default device within a function mode context + # exiting that context mode will pop the device function mode off + # of the stack incorrectly + cur_stack = [_pop_mode() for _ in range(_len_torch_function_stack())] + + _push_mode(self) + + for mode in reversed(cur_stack): + if isinstance(mode, DeviceContext): + self.prev_mode = mode + else: + _push_mode(mode) + + def __exit__(self, exc_type, exc_val, exc_tb): + global CURRENT_DEVICE + CURRENT_DEVICE = self.old_device + cur_stack = [] + # Invariant: there should only be one DeviceContext on the stack at any time + # (At the bottom), pop all modes until we hit the bottom, assert it's a DeviceContext + # or else someone else has popped it! + for _ in range(_len_torch_function_stack() - 1): + mode = _pop_mode() + if isinstance(mode, DeviceContext): + raise AssertionError( + "Found nested DeviceContext on the mode stack where none expected" + ) + cur_stack.append(mode) + + if _len_torch_function_stack() > 0: + mode = _pop_mode() + if not isinstance(mode, DeviceContext): + raise AssertionError( + "Expected a DeviceContext at the bottom of the mode stack" + ) + if self.prev_mode is not None: + _push_mode(self.prev_mode) + + for mode in reversed(cur_stack): + _push_mode(mode) + + def __torch_function__(self, func, types, args=(), kwargs=None): + kwargs = kwargs or {} + if func in _device_constructors() and kwargs.get("device") is None: + kwargs["device"] = self.device + return func(*args, **kwargs) + + +# NB: This is directly called from C++ in torch/csrc/Device.cpp +def device_decorator(device, func): + return context_decorator(lambda: device, func) + + +def set_device(device): + """ + Set the default device inside of the wrapped function by decorating it with this function. + + If you would like to use this as a context manager, use device as a + context manager directly, e.g., ``with torch.device(device)``. + """ + return lambda func: device_decorator(torch.device(device), func) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_dtype_abbrs.py b/.venv/lib/python3.12/site-packages/torch/utils/_dtype_abbrs.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f3539a13e5a97d9100fcfe24f1abd4f1cee5c8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_dtype_abbrs.py @@ -0,0 +1,5 @@ +import torch + + +# Used for testing and logging +dtype_abbrs = {dt: dt.abbr for dt in torch._C._get_all_dtypes()} diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_exposed_in.py b/.venv/lib/python3.12/site-packages/torch/utils/_exposed_in.py new file mode 100644 index 0000000000000000000000000000000000000000..2cca4ce240ad99afd44b8347135300b8c48ae66f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_exposed_in.py @@ -0,0 +1,21 @@ +from collections.abc import Callable +from typing import TypeVar + + +F = TypeVar("F") + + +# Allows one to expose an API in a private submodule publicly as per the definition +# in PyTorch's public api policy. +# +# It is a temporary solution while we figure out if it should be the long-term solution +# or if we should amend PyTorch's public api policy. The concern is that this approach +# may not be very robust because it's not clear what __module__ is used for. +# However, both numpy and jax overwrite the __module__ attribute of their APIs +# without problem, so it seems fine. +def exposed_in(module: str) -> Callable[[F], F]: + def wrapper(fn: F) -> F: + fn.__module__ = module + return fn + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_filelock.py b/.venv/lib/python3.12/site-packages/torch/utils/_filelock.py new file mode 100644 index 0000000000000000000000000000000000000000..a291f59b4ba7fc1d9c1ecca703a6ae1fdf8e4cf1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_filelock.py @@ -0,0 +1,41 @@ +from types import TracebackType +from typing_extensions import Self + +from filelock import FileLock as base_FileLock + +from torch.monitor import _WaitCounter + + +class FileLock(base_FileLock): + """ + This behaves like a normal file lock. + + However, it adds waitcounters for acquiring and releasing the filelock + as well as for the critical region within it. + + pytorch.filelock.enter - While we're acquiring the filelock. + pytorch.filelock.region - While we're holding the filelock and doing work. + pytorch.filelock.exit - While we're releasing the filelock. + """ + + def __enter__(self) -> Self: + self.region_counter = _WaitCounter("pytorch.filelock.region").guard() + with _WaitCounter("pytorch.filelock.enter").guard(): + result = super().__enter__() + self.region_counter.__enter__() + return result + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.region_counter.__exit__() + with _WaitCounter("pytorch.filelock.exit").guard(): + # Returns nothing per + # https://github.com/tox-dev/filelock/blob/57f488ff8fdc2193572efe102408fb63cfefe4e4/src/filelock/_api.py#L379 + super().__exit__(exc_type, exc_value, traceback) + # Returns nothing per + # https://github.com/pytorch/pytorch/blob/0f6bfc58a2cfb7a5c052bea618ab62becaf5c912/torch/csrc/monitor/python_init.cpp#L315 + return None diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_foreach_utils.py b/.venv/lib/python3.12/site-packages/torch/utils/_foreach_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e88720a93ce3fad081a9ab05c6f7042b603f0e9a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_foreach_utils.py @@ -0,0 +1,60 @@ +from typing import TypeAlias + +import torch +from torch import Tensor +from torch.autograd.grad_mode import no_grad + + +def _get_foreach_kernels_supported_devices() -> list[str]: + r"""Return the device type list that supports foreach kernels.""" + return ["cuda", "xpu", "mtia", torch._C._get_privateuse1_backend_name()] + + +def _get_fused_kernels_supported_devices() -> list[str]: + r"""Return the device type list that supports fused kernels in optimizer.""" + return [ + "mps", + "cuda", + "xpu", + "hpu", + "cpu", + "mtia", + torch._C._get_privateuse1_backend_name(), + ] + + +TensorListList: TypeAlias = list[list[Tensor | None]] +Indices: TypeAlias = list[int] +_foreach_supported_types = [torch.Tensor] + + +# This util function splits tensors into groups by device and dtype, which is useful before sending +# tensors off to a foreach implementation, which requires tensors to be on one device and dtype. +# If tensorlistlist contains more than one tensorlist, the following assumptions are made BUT NOT verified: +# - tensorlists CAN be None +# - all tensors in the first specified list cannot be None +# - given an index i, all specified tensorlist[i]s match in dtype and device +# with_indices (bool, optional): whether to track previous indices as the last list per dictionary entry. +# It comes in handy if there are Nones or literals in the tensorlists that are getting scattered out. +# Whereas mutating a tensor in the resulting split-up tensorlists WILL propagate changes back to the +# original input tensorlists, changing up Nones/literals WILL NOT propagate, and manual propagation +# may be necessary. Check out torch/optim/sgd.py for an example. +@no_grad() +def _group_tensors_by_device_and_dtype( + tensorlistlist: TensorListList, + with_indices: bool = False, +) -> dict[tuple[torch.device, torch.dtype], tuple[TensorListList, Indices]]: + return torch._C._group_tensors_by_device_and_dtype(tensorlistlist, with_indices) + + +def _device_has_foreach_support(device: torch.device) -> bool: + return ( + device.type in (_get_foreach_kernels_supported_devices() + ["cpu"]) + and not torch.jit.is_scripting() + ) + + +def _has_foreach_support(tensors: list[Tensor], device: torch.device) -> bool: + return _device_has_foreach_support(device) and all( + t is None or type(t) in _foreach_supported_types for t in tensors + ) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_functools.py b/.venv/lib/python3.12/site-packages/torch/utils/_functools.py new file mode 100644 index 0000000000000000000000000000000000000000..c09731634fc81c53a48ebc454589913f1320b560 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_functools.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import functools +import threading +from concurrent.futures import ThreadPoolExecutor +from typing import Concatenate, TYPE_CHECKING, TypeVar +from typing_extensions import ParamSpec + + +if TYPE_CHECKING: + from collections.abc import Callable + from concurrent.futures import Future + + +_P = ParamSpec("_P") +_T = TypeVar("_T") +_C = TypeVar("_C") + +# Sentinel used to indicate that cache lookup failed. +_cache_sentinel = object() + +_prefetch_executor = ThreadPoolExecutor(max_workers=2) + + +def prefetchable_cache(func: Callable[[], _T]) -> Callable[[], _T]: + """ + Like functools.cache but with a prefetch() method that starts computing + the value in a background thread, and a set() method for prepopulating. + """ + _cache: _T | object = _cache_sentinel + _lock = threading.Lock() + _future: Future[_T] | None = None + + def wrapper() -> _T: + nonlocal _cache, _future + with _lock: + if _cache is not _cache_sentinel: + return _cache # type: ignore[return-value] + if _future is not None: + _cache = _future.result() + _future = None + return _cache # type: ignore[return-value] + _cache = func() + return _cache # type: ignore[return-value] + + def set_val(val: _T) -> None: + nonlocal _cache + with _lock: + if _cache is not _cache_sentinel: + raise RuntimeError("prefetchable_cache value already set") + _cache = val + + def clear() -> None: + nonlocal _cache, _future + with _lock: + _cache = _cache_sentinel + _future = None + + def prefetch() -> None: + nonlocal _future + with _lock: + if _cache is not _cache_sentinel or _future is not None: + return + _future = _prefetch_executor.submit(func) + + wrapper.set = set_val # type: ignore[attr-defined] + wrapper.clear = clear # type: ignore[attr-defined] + wrapper.prefetch = prefetch # type: ignore[attr-defined] + return wrapper + + +def cache_method( + f: Callable[Concatenate[_C, _P], _T], +) -> Callable[Concatenate[_C, _P], _T]: + """ + Like `@functools.cache` but for methods. + + `@functools.cache` (and similarly `@functools.lru_cache`) shouldn't be used + on methods because it caches `self`, keeping it alive + forever. `@cache_method` ignores `self` so won't keep `self` alive (assuming + no cycles with `self` in the parameters). + + Footgun warning: This decorator completely ignores self's properties so only + use it when you know that self is frozen or won't change in a meaningful + way (such as the wrapped function being pure). + """ + cache_name = "_cache_method_" + f.__name__ + + @functools.wraps(f) + def wrap(self: _C, *args: _P.args, **kwargs: _P.kwargs) -> _T: + if kwargs: + raise AssertionError("cache_method does not accept keyword arguments") + if not (cache := getattr(self, cache_name, None)): + cache = {} + setattr(self, cache_name, cache) + cached_value = cache.get(args, _cache_sentinel) + if cached_value is not _cache_sentinel: + return cached_value + value = f(self, *args, **kwargs) + cache[args] = value + return value + + return wrap diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_get_clean_triton.py b/.venv/lib/python3.12/site-packages/torch/utils/_get_clean_triton.py new file mode 100644 index 0000000000000000000000000000000000000000..333481e17044c97e05aaae221cbe5a3003621325 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_get_clean_triton.py @@ -0,0 +1,200 @@ +# mypy: allow-untyped-defs +import argparse +import os +import re +import subprocess +import sys +from pathlib import Path + + +def remove_triton_function_declaration(source_code: str) -> str: + remove_head = re.sub(r"(\n.+\s\'\'\'\n)", "\n", source_code) + remove_tail = re.sub(r"(\'\'\'\,.+)", "\n", remove_head) + return remove_tail + + +def remove_async_compile(source_code: str) -> str: + remove_top_level = str.replace(source_code, "async_compile = AsyncCompile()", "") + remove_compile = str.replace(remove_top_level, "async_compile.wait(globals())", "") + remove_del = str.replace(remove_compile, "del async_compile", "") + return remove_del + + +def rename_kernels(source_code: str) -> str: + pattern = r"(\w+)\s*=\s*async_compile\.triton\('triton_',\s" + triton_kernel_decl = "def triton_" + matches = [ + (match.end(), match.group(1)) + for match in re.finditer(pattern, source_code, re.DOTALL) + ] + + # Starting from the last match to avoid issues with shifting indices after replacements + for end_index, captured_string in reversed(matches): + # Find the index of the next "B" after the current match + index_of_B = source_code.find(triton_kernel_decl, end_index) + if index_of_B != -1: + # Replace the triton_kernel_decl with the captured string + source_code = ( + source_code[:index_of_B] + + f"def {captured_string}" + + source_code[index_of_B + len(triton_kernel_decl) :] + ) + else: + # If triton_kernel_decl is not found after the current match, continue to the next + continue + + return source_code + + +def merge_params(original_params: list[str], new_params: list[str]) -> list[str]: + for idx in range(len(new_params)): + if new_params[idx] == "T": + new_params[idx] = original_params[idx] + return new_params + + +def add_launch_params( + original: str, kernel_to_params: dict[str, tuple[str, str]] +) -> str: + # Regex to match the function call in the original string + pattern = r"(\w+)\.run\((.*)\)" + + def replace(match) -> str: + # Extract parts from the regex match + func_name = match.group(1) + params = match.group(2) + new_params, grid = kernel_to_params[func_name] + new_params = merge_params(params.split(", "), new_params.split(", ")) + + # Format the new function call + new_string = f"{func_name}[{grid}]({', '.join(new_params)})" + return new_string + + transformed = re.sub(pattern, replace, original) + + remove_inductor_wrappers = re.sub( + r"@triton_heuristics[^@]*@triton.jit", + r"@triton.jit", + transformed, + flags=re.DOTALL, + ) + + return remove_inductor_wrappers + + +def process_file( + input_filename: str, output_filename: str, auto_generate_params: bool = True +) -> str: + with open(input_filename) as file: + source_code = file.read() + + transformed_code = source_code + if "def triton_(" in source_code: + raise RuntimeError( + "Need to run original Pytorch code generating kernels with TORCHINDUCTOR_UNIQUE_KERNEL_NAMES=1" + ) + # transformed_code = rename_kernels(transformed_code) + transformed_code = remove_triton_function_declaration(transformed_code) + transformed_code = remove_async_compile(transformed_code) + + launch_params_filename = f"{input_filename}.launch_params" + + # Auto-generate launch_params if they don't exist and auto_generate_params is True + if not os.path.exists(launch_params_filename) and auto_generate_params: + print(f"Launch params file {launch_params_filename} not found. Generating...") + try: + # Set environment variable and run the input file + env = os.environ.copy() + env["TORCHINDUCTOR_DUMP_LAUNCH_PARAMS"] = "1" + + result = subprocess.run( + [sys.executable, input_filename], + env=env, + capture_output=True, + text=True, + cwd=os.path.dirname(input_filename) or ".", + ) + + if result.returncode != 0: + print(f"Error running {input_filename}:") + print(f"stdout: {result.stdout}") + print(f"stderr: {result.stderr}") + raise RuntimeError( + f"Failed to generate launch params. Command failed with return code {result.returncode}" + ) + + print(f"Successfully generated {launch_params_filename}") + + except Exception as e: + raise RuntimeError( + f"Failed to generate launch params by running {input_filename}: {str(e)}" + ) from e + + if not os.path.exists(launch_params_filename): + raise RuntimeError( + f"Missing {launch_params_filename}. Run `TORCHINDUCTOR_DUMP_LAUNCH_PARAMS=1 python {input_filename}` first." + ) + + with open(launch_params_filename) as f: + launch_params_meta = f.readlines() + + split_params = [i.split("|") for i in launch_params_meta] + kernel_args_grid = {a.strip(): (b.strip(), c.strip()) for a, b, c in split_params} + transformed_code = add_launch_params(transformed_code, kernel_args_grid) + + with open(output_filename, "w") as file: + file.write(transformed_code) + print(f"Successfully generated {output_filename}") + return transformed_code + + +def get_clean_triton( + input_path: Path, + output_path: Path = Path("triton_only_repro.py"), + auto_generate_params: bool = True, +): + """Run experiments and output results to file + + Args: + input_path (Path): Path to inductor generated output code + output_path (Path): Path to write out the new python file + auto_generate_params (bool): Whether to automatically generate launch_params if missing + """ + return process_file(str(input_path), str(output_path), auto_generate_params) + + +if __name__ == "__main__": + """Sample usage: + # Running sweep + python _get_clean_triton.py output_code.py + + # To disable auto-generation of launch params: + python _get_clean_triton.py output_code.py --no-auto-generate + """ + parser = argparse.ArgumentParser( + description="Clean Inductor generated code to remove Inductor dependencies" + ) + + # Add the arguments + parser.add_argument( + "input_path", type=Path, help="Path to inductor generated output code" + ) + parser.add_argument( + "--output_path", + type=Path, + default=Path("triton_only_repro.py"), + help="Path to write out the clean triton output", + ) + parser.add_argument( + "--no-auto-generate", + action="store_true", + help="Disable automatic generation of launch_params file", + ) + + # Parse the arguments + args = parser.parse_args() + + # Call the function with parsed arguments + result = get_clean_triton( + args.input_path, args.output_path, not args.no_auto_generate + ) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_helion.py b/.venv/lib/python3.12/site-packages/torch/utils/_helion.py new file mode 100644 index 0000000000000000000000000000000000000000..bf40e869769993bf4cc764a5a2069451de90cfc9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_helion.py @@ -0,0 +1,15 @@ +import functools + + +@functools.cache +def has_helion_package() -> bool: + try: + import helion # type: ignore[import-untyped, import-not-found] # noqa: F401 + except ImportError: + return False + return True + + +@functools.cache +def has_helion() -> bool: + return has_helion_package() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_import_utils.py b/.venv/lib/python3.12/site-packages/torch/utils/_import_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..47e48fb7144e5d60f82f746b0dc862677f322552 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_import_utils.py @@ -0,0 +1,37 @@ +import functools +import importlib.util +from types import ModuleType + + +def _check_module_exists(name: str) -> bool: + r"""Returns if a top-level module with :attr:`name` exists *without** + importing it. This is generally safer than try-catch block around a + `import X`. It avoids third party libraries breaking assumptions of some of + our tests, e.g., setting multiprocessing start method when imported + (see librosa/#747, torchvision/#544). + """ + try: + spec = importlib.util.find_spec(name) + return spec is not None + except ImportError: + return False + + +@functools.lru_cache +def dill_available() -> bool: + return _check_module_exists("dill") + + +@functools.lru_cache +def import_dill() -> ModuleType | None: + if not dill_available(): + return None + + import dill + + # XXX: By default, dill writes the Pickler dispatch table to inject its + # own logic there. This globally affects the behavior of the standard library + # pickler for any user who transitively depends on this module! + # Undo this extension to avoid altering the behavior of the pickler globally. + dill.extend(use_dill=False) + return dill diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_indented_buffer.py b/.venv/lib/python3.12/site-packages/torch/utils/_indented_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..4b3f034cec9102843d841748e6d1aac9d6b7fccf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_indented_buffer.py @@ -0,0 +1,234 @@ +""" +IndentedBuffer: a line-oriented buffer that tracks indentation as source is +appended and renders it (optionally with a line map for traceback remapping). + +This is the shared primitive underneath inductor's codegen buffers +(torch._inductor.utils re-exports these names and subclasses IndentedBuffer for +its JIT/AOTI variants), dynamo's guard codegen (IndentedBufferWithPrefix), and +AOTAutograd's runtime-wrapper codegen (PySourceBuilder). It lives in torch.utils +so those layers can share it without importing across the _functorch -> _inductor +edge or pulling in the heavy torch._inductor.utils module. The cluster depends +only on the standard library. +""" + +from __future__ import annotations + +import contextlib +import math +import textwrap +from dataclasses import dataclass +from io import StringIO +from typing import Any, NamedTuple, TYPE_CHECKING +from typing_extensions import Self + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Sequence + + +class LineContext(NamedTuple): + context: Any + + +@dataclass +class ValueWithLineMap: + value: str + line_map: list[tuple[int, LineContext]] + + +class IndentedBuffer: + tabwidth = 4 + + def __init__(self, initial_indent: int = 0) -> None: + self._lines: list[DeferredLineBase | LineContext | str] = [] + self._indent = initial_indent + + @contextlib.contextmanager + def set_tabwidth(self, tabwidth: int) -> Iterator[None]: + prev = self.tabwidth + try: + self.tabwidth = tabwidth + yield + finally: + self.tabwidth = prev + + def getvaluewithlinemap(self) -> ValueWithLineMap: + buf = StringIO() + p = 1 + linemap: list[tuple[int, LineContext]] = [] + for li in self._lines: + if isinstance(li, DeferredLineBase): + line = li() + if line is None: + continue + elif isinstance(li, LineContext): + linemap.append((p, li.context)) + continue + else: + line = li + if not isinstance(line, str): + raise AssertionError(f"Expected str, got {type(line)}") + buf.write(line) + buf.write("\n") + p += 1 + line.count("\n") + return ValueWithLineMap(buf.getvalue(), linemap) + + def getvalue(self) -> str: + return self.getvaluewithlinemap().value + + def getrawvalue(self) -> str: + buf = StringIO() + for li in self._lines: + if isinstance(li, DeferredLineBase): + line = li() + if line is None: + continue + elif isinstance(li, LineContext): + continue + else: + line = li + if not isinstance(line, str): + raise AssertionError(f"Expected str, got {type(line)}") + # backslash implies line continuation + if line.endswith("\\"): + buf.write(line[:-1]) + else: + buf.write(line) + buf.write("\n") + return buf.getvalue() + + def get_lines_ref(self): + return self._lines + + def clear(self) -> None: + self._lines.clear() + + def __bool__(self) -> bool: + return bool(self._lines) + + def prefix(self) -> str: + return " " * (self._indent * self.tabwidth) + + def newline(self) -> None: + self.writeline("\n") + + def writeline(self, line: LineContext | DeferredLineBase | str) -> None: + if isinstance(line, LineContext): + self._lines.append(line) + elif isinstance(line, DeferredLineBase): + self._lines.append(line.with_prefix(self.prefix())) + elif line.strip(): + self._lines.append(f"{self.prefix()}{line}") + else: + self._lines.append("") + + def writeline_jit(self, line: LineContext | DeferredLineBase | str) -> None: + """Write to JIT buffer only. On a plain IndentedBuffer, same as writeline.""" + self.writeline(line) + + def writeline_aot(self, line: LineContext | DeferredLineBase | str) -> None: + """Write to AOTI buffer only. No-op on a plain IndentedBuffer.""" + + def splice_jit(self, other_code: IndentedBuffer | str, strip: bool = False) -> None: + """Splice to JIT buffer only. On a plain IndentedBuffer, same as splice.""" + self.splice(other_code, strip=strip) + + def splice_aot(self, other_code: IndentedBuffer | str, strip: bool = False) -> None: + """Splice to AOTI buffer only. No-op on a plain IndentedBuffer.""" + + def writelines(self, lines: Sequence[LineContext | DeferredLineBase | str]) -> None: + for line in lines: + self.writeline(line) + + def indent(self, offset: int = 1) -> contextlib.AbstractContextManager[None]: + @contextlib.contextmanager + def ctx() -> Iterator[None]: + self._indent += offset + try: + yield + finally: + self._indent -= offset + + return ctx() + + def do_indent(self, offset: int = 1) -> None: + self._indent += offset + + def do_unindent(self, offset: int = 1) -> None: + self._indent -= offset + + def splice(self, other_code: IndentedBuffer | str, strip: bool = False) -> None: + if isinstance(other_code, IndentedBuffer): + dedent = float("inf") + + for line in other_code._lines: + if not isinstance(line, LineContext) and line: + dedent = min(dedent, len(line) - len(line.lstrip())) + if math.isinf(dedent): + dedent = 0 + for line in other_code._lines: + if isinstance(line, LineContext): + self._lines.append(line) + else: + IndentedBuffer.writeline(self, line[int(dedent) :]) + else: + other_code = textwrap.dedent(other_code) + if strip: + other_code = other_code.lstrip() + if not other_code: + return + other_code = other_code.rstrip() + for s in other_code.split("\n"): + IndentedBuffer.writeline(self, s) + + def map(self, func: Callable[[Any], Any]) -> IndentedBuffer: + res = IndentedBuffer(initial_indent=self._indent) + res._lines = [func(line) for line in self._lines] + return res + + def __repr__(self) -> str: + return f"{type(self)}({self.getvalue()})" + + def __add__(self, other: Self) -> IndentedBuffer: + if self._indent != other._indent: + raise AssertionError(f"Indent mismatch: {self._indent} != {other._indent}") + res = IndentedBuffer(initial_indent=self._indent) + # TODO(rec): or should this be self.__class__(initial_indent=self._indent)? + res.writelines(self._lines) + res.writelines(other._lines) + return res + + def contains(self, new_line: DeferredLineBase | LineContext | str) -> bool: + return new_line in self._lines + + +class DeferredLineBase: + """A line that can be 'unwritten' at a later time""" + + def __init__(self, line: str): + if not line.strip(): + line = "" + self.line = line + + def __call__(self) -> str | None: + """Returns either self.line or None to indicate the line has been 'unwritten'""" + raise NotImplementedError + + def _new_line(self, line: str) -> Self: + """Returns a new deferred line with the same condition""" + raise NotImplementedError + + def with_prefix(self, prefix: str) -> Self: + return self._new_line(f"{prefix}{self.line}") + + def lstrip(self) -> Self: + return self._new_line(self.line.lstrip()) + + def __getitem__(self, index: int | slice) -> Self: + return self._new_line(self.line[index]) + + def __bool__(self) -> bool: + return bool(self.line) + + def __len__(self) -> int: + return len(self.line) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_inspect.py b/.venv/lib/python3.12/site-packages/torch/utils/_inspect.py new file mode 100644 index 0000000000000000000000000000000000000000..67d29b9bc706935bf1c06dbbaff1029178fc137a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_inspect.py @@ -0,0 +1,90 @@ +import inspect +from typing import Any + + +def _signature_metadata( + sig: inspect.Signature, +) -> tuple[tuple[inspect.Parameter, ...], bool, int]: + """ + Returns tuple(sig.parameters.values()), if any has VAR_POSITIONAL or VAR_KEYWORD, and the max_positional + """ + params = tuple(sig.parameters.values()) + has_var_args = False + max_positional = 0 + + for p in params: + kind = p.kind + if kind in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD): + has_var_args = True + if kind in ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + ): + max_positional += 1 + + return params, has_var_args, max_positional + + +def _fast_bind( + sig: inspect.Signature, *args: Any, **kwargs: Any +) -> inspect.BoundArguments: + """ + Fast path for inspect.Signature.bind() for signatures without + VAR_POSITIONAL or VAR_KEYWORD parameters. Falls back to sig.bind() + for signatures that contain *args or **kwargs. + """ + params, has_var_args, max_positional = _signature_metadata(sig) + + # fallback for complex signatures + if has_var_args: + return sig.bind(*args, **kwargs) + + len_args = len(args) + + if len_args > max_positional: + raise TypeError( + f"Too many positional arguments: expected max {max_positional}, got {len_args}" + ) + + arguments: dict[str, Any] = {} + arg_i = 0 + + for p in params: + name = p.name + kind = p.kind + + if kind is inspect.Parameter.POSITIONAL_ONLY: + if name in kwargs: + raise TypeError( + f"Got some positional-only arguments passed as keyword arguments: '{name}'" + ) + if arg_i < len_args: + arguments[name] = args[arg_i] + arg_i += 1 + elif p.default is inspect.Parameter.empty: + raise TypeError(f"Missing required argument '{name}'") + + elif kind is inspect.Parameter.POSITIONAL_OR_KEYWORD: + if arg_i < len_args: + if name in kwargs: + raise TypeError(f"Multiple values for argument '{name}'") + arguments[name] = args[arg_i] + arg_i += 1 + elif name in kwargs: + arguments[name] = kwargs[name] + elif p.default is inspect.Parameter.empty: + raise TypeError(f"Missing required argument '{name}'") + + elif kind is inspect.Parameter.KEYWORD_ONLY: + if name in kwargs: + arguments[name] = kwargs[name] + elif p.default is inspect.Parameter.empty: + raise TypeError(f"Missing required argument '{name}'") + + # disallow extra keyword arguments not in the signature + # cause kwargs have been processed by sig.bind at the beginning + for name in kwargs: + if name not in sig.parameters: + raise TypeError(f"Got an unexpected keyword argument '{name}'") + + return inspect.BoundArguments(sig, arguments) # type: ignore[arg-type] diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_mode_utils.py b/.venv/lib/python3.12/site-packages/torch/utils/_mode_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b79b52b13449e829b6168bceeb07f254cb6c6180 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_mode_utils.py @@ -0,0 +1,15 @@ +# mypy: allow-untyped-defs +from typing import TypeVar + +import torch + + +T = TypeVar("T") + + +# returns if all are the same mode +def all_same_mode(modes): + return all(tuple(mode == modes[0] for mode in modes)) + + +no_dispatch = torch._C._DisableTorchDispatch diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_ordered_set.py b/.venv/lib/python3.12/site-packages/torch/utils/_ordered_set.py new file mode 100644 index 0000000000000000000000000000000000000000..3d218395308f3fb9e4a6156d64d4d3032ed4c0bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_ordered_set.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +from collections.abc import ( + Hashable, + Iterable, + Iterator, + MutableSet, + Reversible, + Set as AbstractSet, +) +from typing import Any, cast, TypeVar + + +T = TypeVar("T", bound=Hashable) +T_co = TypeVar("T_co", bound=Hashable, covariant=True) + +__all__ = ["OrderedSet"] + + +class OrderedSet(MutableSet[T], Reversible[T]): + """ + Insertion ordered set, similar to OrderedDict. + """ + + __slots__ = ("_dict",) + + def __init__(self, iterable: Iterable[T] | None = None) -> None: + self._dict = dict.fromkeys(iterable, None) if iterable is not None else {} + + @staticmethod + def _from_dict(dict_inp: dict[T, None]) -> OrderedSet[T]: + s: OrderedSet[T] = OrderedSet() + s._dict = dict_inp + return s + + # + # Required overridden abstract methods + # + def __contains__(self, elem: object) -> bool: + return elem in self._dict + + def __iter__(self) -> Iterator[T]: + return iter(self._dict) + + def __len__(self) -> int: + return len(self._dict) + + def __reversed__(self) -> Iterator[T]: + return reversed(self._dict) + + def add(self, elem: T) -> None: + self._dict[elem] = None + + def discard(self, elem: T) -> None: + self._dict.pop(elem, None) + + def clear(self) -> None: + # overridden because MutableSet impl is slow + self._dict.clear() + + # Unimplemented set() methods in _collections_abc.MutableSet + + @classmethod + def _wrap_iter_in_set(cls, other: Any) -> Any: + """ + Wrap non-Set Iterables in OrderedSets + + Some of the magic methods are more strict on input types than + the public apis, so we need to wrap inputs in sets. + """ + + if not isinstance(other, AbstractSet) and isinstance(other, Iterable): + return cls(other) + else: + return other + + def pop(self) -> T: + if not self: + raise KeyError("pop from an empty set") + return self._dict.popitem()[0] + + def copy(self) -> OrderedSet[T]: + return OrderedSet._from_dict(self._dict.copy()) + + def difference(self, *others: Iterable[T]) -> OrderedSet[T]: + res = self.copy() + res.difference_update(*others) + return res + + def difference_update(self, *others: Iterable[T]) -> None: + for other in others: + self -= other # type: ignore[arg-type] + + def update(self, *others: Iterable[T]) -> None: + for other in others: + self |= other + + def intersection(self, *others: Iterable[T]) -> OrderedSet[T]: + res = self.copy() + for other in others: + if other is not self: + res &= other # type: ignore[arg-type] + return res + + def intersection_update(self, *others: Iterable[T]) -> None: + for other in others: + self &= other # type: ignore[arg-type] + + def issubset(self, other: Iterable[T]) -> bool: + return self <= self._wrap_iter_in_set(other) + + def issuperset(self, other: Iterable[T]) -> bool: + return self >= self._wrap_iter_in_set(other) + + def symmetric_difference(self, other: Iterable[T]) -> OrderedSet[T]: + return self ^ other # type: ignore[operator] + + def symmetric_difference_update(self, other: Iterable[T]) -> None: + self ^= other # type: ignore[arg-type] + + def union(self, *others: Iterable[T]) -> OrderedSet[T]: + res = self.copy() + for other in others: + if other is self: + continue + res |= other + return res + + # Specify here for correct type inference, otherwise would + # return AbstractSet[T] + def __sub__(self, other: AbstractSet[T_co]) -> OrderedSet[T]: + # following cpython set impl optimization + if isinstance(other, OrderedSet) and (len(self) * 4) > len(other): + out = self.copy() + out -= other + return out + return cast(OrderedSet[T], super().__sub__(other)) + + def __ior__(self, other: Iterable[T]) -> OrderedSet[T]: # type: ignore[misc, override] # noqa: PYI034 + if isinstance(other, OrderedSet): + self._dict.update(other._dict) + return self + return super().__ior__(other) # type: ignore[arg-type] + + def __eq__(self, other: object) -> bool: + if isinstance(other, OrderedSet): + return self._dict == other._dict + return super().__eq__(other) + + def __ne__(self, other: object) -> bool: + if isinstance(other, OrderedSet): + return self._dict != other._dict + return super().__ne__(other) + + def __or__(self, other: AbstractSet[T_co]) -> OrderedSet[T]: + return cast(OrderedSet[T], super().__or__(other)) + + def __and__(self, other: AbstractSet[T_co]) -> OrderedSet[T]: + # MutableSet impl will iterate over other, iter over smaller of two sets + if isinstance(other, OrderedSet) and len(self) < len(other): + # pyrefly: ignore [unsupported-operation, bad-return] + return other & self + return cast(OrderedSet[T], super().__and__(other)) + + def __xor__(self, other: AbstractSet[T_co]) -> OrderedSet[T]: + return cast(OrderedSet[T], super().__xor__(other)) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({list(self)})" + + def __getstate__(self) -> list[T]: + return list(self._dict.keys()) + + def __setstate__(self, state: list[T]) -> None: + self._dict = dict.fromkeys(state, None) + + def __reduce__(self) -> tuple[type[OrderedSet[T]], tuple[list[T]]]: + return (OrderedSet, (list(self),)) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_pallas.py b/.venv/lib/python3.12/site-packages/torch/utils/_pallas.py new file mode 100644 index 0000000000000000000000000000000000000000..336bf7e599fe6bf7061035804c294e28b311e43f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_pallas.py @@ -0,0 +1,120 @@ +import functools + +import torch + + +@functools.cache +def has_jax_package() -> bool: + """Check if JAX is installed.""" + try: + import jax # noqa: F401 # type: ignore[import-not-found] + + return True + except ImportError: + return False + + +@functools.cache +def has_pallas_package() -> bool: + """Check if Pallas (JAX experimental) is available.""" + if not has_jax_package(): + return False + try: + from jax.experimental import ( # noqa: F401 # type: ignore[import-not-found] + pallas as pl, + ) + + return True + except ImportError: + return False + + +@functools.cache +def get_jax_version(fallback: tuple[int, int, int] = (0, 0, 0)) -> tuple[int, int, int]: + """Get JAX version as (major, minor, patch) tuple.""" + try: + import jax # type: ignore[import-not-found] + + version_parts = jax.__version__.split(".") + major, minor, patch = (int(v) for v in version_parts[:3]) + return (major, minor, patch) + except (ImportError, ValueError, AttributeError): + return fallback + + +@functools.cache +def has_jax_cuda_backend() -> bool: + """Check if JAX has CUDA backend support with SM90+ (required by Mosaic GPU).""" + if not has_jax_package(): + return False + try: + import jax # type: ignore[import-not-found] + + # Check if CUDA backend is available + devices = jax.devices("gpu") + if len(devices) == 0: + return False + + # Mosaic GPU requires SM90+ (compute capability 9.0+) + if torch.cuda.is_available(): + major, minor = torch.cuda.get_device_capability() + if major < 9: + return False + + return True + except Exception: + return False + + +@functools.cache +def has_jax_tpu_backend() -> bool: + """Check if JAX has TPU backend support.""" + if not has_jax_package(): + return False + try: + import jax # type: ignore[import-not-found] + + # Check if TPU backend is available + devices = jax.devices("tpu") + return len(devices) > 0 + except Exception: + return False + + +@functools.cache +def has_torch_tpu() -> bool: + """Check if torch_tpu is installed and available.""" + # The TPU module is an autoloaded out-of-tree backend. + tpu_module = getattr(torch, "tpu", None) + return tpu_module is not None + + +@functools.cache +def has_cpu_pallas() -> bool: + """Checks for a full Pallas-on-CPU environment.""" + return has_pallas_package() + + +@functools.cache +def has_cuda_pallas() -> bool: + """Checks for a full Pallas-on-CUDA environment.""" + return has_pallas_package() and torch.cuda.is_available() and has_jax_cuda_backend() + + +@functools.cache +def has_tpu_pallas() -> bool: + """Checks for a full Pallas-on-TPU environment.""" + return has_pallas_package() and has_jax_tpu_backend() and has_torch_tpu() + + +@functools.cache +def has_pallas() -> bool: + """ + Check if Pallas backend is fully available for use. + + Requirements: + - JAX package installed + - Pallas (jax.experimental.pallas) available + - A compatible backend (CUDA or TPU) is available in both PyTorch and JAX. + """ + return has_cpu_pallas() or has_cuda_pallas() or has_tpu_pallas() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_python_dispatch.py b/.venv/lib/python3.12/site-packages/torch/utils/_python_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..ddafd9d7b203802158922b9af548e272cf4bbf71 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_python_dispatch.py @@ -0,0 +1,975 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import contextlib +import functools +import warnings +from collections import deque +from dataclasses import dataclass +from typing import cast, overload, Protocol, TYPE_CHECKING +from typing_extensions import TypeIs + +import torch +import torchgen +import torchgen.model +from torch._C import ( + _get_dispatch_stack_at, + _len_torch_dispatch_stack, + _pop_torch_dispatch_stack, + _push_on_torch_dispatch_stack, + DispatchKey, +) +from torch._C._dynamo.guards import set_is_in_mode_without_ignore_compile_internals + + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + + from torch._custom_class_base import CustomClassBase + + +# TODO: Limitations and things about enable_torch_dispatch_mode we should fix before exposing it: +# - We need a better user-facing api for _DisableTorchDispatch that +# is able to selectively disable __torch_dispatch__ of a particular class. +# - It doesn't work with the tensor constructors (torch.tensor, torch.Tensor) +# - Better name (see https://github.com/pytorch/pytorch/pull/63496#discussion_r694091694) + +_is_in_torch_dispatch_mode = False +_is_in_non_infra_torch_dispatch_mode = False +# If inside any mode that has ignore_compile_internals() = False +_is_in_any_mode_without_ignore_compile_internals = False + + +def is_in_torch_dispatch_mode(include_infra_modes: bool = True) -> bool: + return ( + _is_in_torch_dispatch_mode + if include_infra_modes + else _is_in_non_infra_torch_dispatch_mode + ) + + +def is_in_any_mode_without_ignore_compile_internals() -> bool: + return _is_in_any_mode_without_ignore_compile_internals + + +def any_torch_dispatch_mode_on_stack() -> bool: + stack_len = torch._C._len_torch_dispatch_stack() + + for idx in range(stack_len): + mode = _get_dispatch_stack_at(idx) + + # Apply filters first + if mode.is_infra_mode(): + continue + + if mode.ignore_compile_internals(): + continue + + return True + return False + + +class TorchDispatchMode: + """ + A ``TorchDispatchMode`` allows you to override the meaning of all + ``__torch_dispatch__`` overridable functions within a dynamic scope, + without having to actually create a tensor subclass or manually + monkey-patch functions in the PyTorch API. Some common situations + where you should use a mode: + + * You want to override the meaning of factory functions, or other + functions that do not otherwise take a tensor as an argument + (these cannot be overridden with tensor subclasses). + + * You want to override the behavior of all functions without needing + to wrap your inputs in tensor subclasses; e.g., if you are just + interested in logging intermediate computations. + + * You want to control the order of execution of various tensor + subclasses explicitly, rather than implicitly via the return of + ``NotImplemented``. + + Independent subclasses of :class:`TorchDispatchMode` are compositional: + modes can be pushed onto a stack using ``with MyMode():``. + When you call functions in the PyTorch API inside your + ``__torch_dispatch__`` implementation, by default, they will forward on to + the next mode on the mode stack. If you want recursively call back into + your current ``__torch_dispatch__`` implementation, either explicitly + invoke ``self.__torch_dispatch__(...)``, or use the context manager + ``self`` to make PyTorch + API self-referential (beware of infinite loops, in this case!) + """ + + # - When False, custom torch dispatch mode will error out explicitly when a hop + # is called under the mode. + # - When True, custom torch dispatch mode's __torch_dispatch__ will be triggered. + # Mode authors can implement how the mode interacts with higher order operators. + supports_higher_order_operators = False + + def __init_subclass__(cls, **kwargs): + super().__init_subclass__(**kwargs) + if cls._should_skip_dynamo(): + if "__torch_dispatch__" in cls.__dict__: + raw = cls.__dict__["__torch_dispatch__"] + if not isinstance(raw, classmethod): + cls.__torch_dispatch__ = torch._disable_dynamo(raw, recursive=True) + + def __init__(self, _dispatch_key=None): + if _dispatch_key is not None: + if not isinstance(_dispatch_key, torch._C.DispatchKey): + raise AssertionError("_dispatch_key must be a torch._C.DispatchKey") + self.__dict__["_dispatch_key"] = _dispatch_key + + self.old_dispatch_mode_flags: deque[bool] = deque() + self.old_non_infra_dispatch_mode_flags: deque[bool] = deque() + self.old_without_ignore_compile_internals_dispatch_mode_flags: deque[bool] = ( + deque() + ) + + def _lazy_init_old_dispatch_mode_flags(self): + if not hasattr(self, "old_dispatch_mode_flags"): + self.old_dispatch_mode_flags: deque[bool] = deque() # type: ignore[no-redef] + + if not hasattr(self, "old_non_infra_dispatch_mode_flags"): + self.old_non_infra_dispatch_mode_flags: deque[bool] = deque() # type: ignore[no-redef] + + if not hasattr( + self, "old_without_ignore_compile_internals_dispatch_mode_flags" + ): + self.old_without_ignore_compile_internals_dispatch_mode_flags: deque[ # type: ignore[no-redef] + bool + ] = deque() + + def __torch_dispatch__(self, func, types, args=(), kwargs=None): + raise NotImplementedError + + def __enter__(self): + global _is_in_torch_dispatch_mode + global _is_in_non_infra_torch_dispatch_mode + global _is_in_any_mode_without_ignore_compile_internals + + # Previously, there wasn't any state in this class' constructor + # super calls were added to existing modes, but for any new modes + # this will replicate the previous behavior of not strictly needing + # to call super().__init__() + self._lazy_init_old_dispatch_mode_flags() + self.old_dispatch_mode_flags.append(_is_in_torch_dispatch_mode) + _is_in_torch_dispatch_mode = True + self.old_non_infra_dispatch_mode_flags.append( + _is_in_non_infra_torch_dispatch_mode + ) + _is_in_non_infra_torch_dispatch_mode = ( + _is_in_non_infra_torch_dispatch_mode or not self.is_infra_mode() + ) + self.old_without_ignore_compile_internals_dispatch_mode_flags.append( + _is_in_any_mode_without_ignore_compile_internals + ) + _is_in_any_mode_without_ignore_compile_internals = ( + _is_in_any_mode_without_ignore_compile_internals + or not self.ignore_compile_internals() + ) + set_is_in_mode_without_ignore_compile_internals( + _is_in_any_mode_without_ignore_compile_internals + ) + _push_mode(self) + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + mb_dk_or_mode_key = self.__dict__.get("_dispatch_key", None) + if mb_dk_or_mode_key is None: + # Today, mode keys are not used at all in the per-dispatch-key-mode logic (for pre-dispatch) + # We should probably revisit this. + mb_dk_or_mode_key = self.__dict__.get("_mode_key", None) + global _is_in_torch_dispatch_mode + _is_in_torch_dispatch_mode = self.old_dispatch_mode_flags.pop() + global _is_in_non_infra_torch_dispatch_mode + _is_in_non_infra_torch_dispatch_mode = ( + self.old_non_infra_dispatch_mode_flags.pop() + ) + global _is_in_any_mode_without_ignore_compile_internals + _is_in_any_mode_without_ignore_compile_internals = ( + self.old_without_ignore_compile_internals_dispatch_mode_flags.pop() + ) + set_is_in_mode_without_ignore_compile_internals( + _is_in_any_mode_without_ignore_compile_internals + ) + _pop_mode(mb_dk_or_mode_key) + + @classmethod + def push(cls, *args, **kwargs): + warnings.warn( + "`Mode.push()` is no longer necessary and can be replaced with just `with Mode()`", + stacklevel=2, + ) + instance = cls(*args, **kwargs) + return instance + + @classmethod + def is_infra_mode(cls) -> bool: + return False + + @classmethod + def _should_skip_dynamo(cls) -> bool: + """Skip Dynamo when the flag is set to True + + This is temporary measure to rollout a feature + that skips PT2 compilation inside __torch_dispatch__ + frames. + + If this flag is off, we would expect following: + + class YoloMode(TorchDispatchMode): + @classmethod + def _should_skip_dynamo(cls): + return False + def __torch_dispatch__(self, func, types, args=(), kwargs=None): + return torch.ops.aten.mul.Tensor(args[0], args[1]) + + x = torch.ones(5) + with YoloMode(): + out = torch.compile(torch.add, backend=backend, fullgraph=True)(x, x) + + # instead of recursively disabling, we are compiling into __torch_dispatch__ + assert len(backend.graphs) == 1 + """ + return True + + @classmethod + def ignore_compile_internals(cls) -> bool: + """Ignore operators that are compiled via torch.compile. + + If ``True``, then this TorchDispatchMode ignores operators that + are optimized by :func:`torch.compile`. Mechanically, this involves + turning off the TorchDispatchMode throughout the whole compilation process, + and turning it back on for the runtime of the compiled artifact(s). + For example, + + @torch.compile + def f(x): + return x.sin().cos() + + with LoggingMode(): + f(x) + + The above example will not log anything if + ``LoggingMode.ignore_compile_internals()`` is True. + torch.compile will fuse sin() and cos() into a single operation + and this TorchDispatchMode will not be passed sin and cos. + + If ``False`` (default), :func:`torch.compile` will respect + the eager semantics of passing this TorchDispatchMode all + operators that would have run during eager execution. + The way this will usually happen is that :func:`torch.compile` + will just fallback to eager-mode PyTorch. + """ + if cls.is_infra_mode(): + return True + return False + + +def _get_current_dispatch_mode() -> TorchDispatchMode | None: + """ + Return the top user mode on the stack (the next one that would be + executed) if there are any. + """ + stack_len = _len_torch_dispatch_stack() + if stack_len > 0: + return _get_dispatch_stack_at(stack_len - 1) + return None + + +def _detect_infra_mode(key): + if key not in ( + torch._C._TorchDispatchModeKey.FUNCTIONAL, + torch._C._TorchDispatchModeKey.PROXY, + ): + raise AssertionError( + f"key must be either FUNCTIONAL ({torch._C._TorchDispatchModeKey.FUNCTIONAL}) \ + or PROXY ({torch._C._TorchDispatchModeKey.PROXY}) _TorchDispatchModeKey, \ + got {key}" + ) + from torch._ops import _get_dispatch_mode_pre_dispatch + + pre_dispatch_mode = _get_dispatch_mode_pre_dispatch(key) + post_dispatch_mode = torch._C._get_dispatch_mode(key) + + if pre_dispatch_mode is not None and post_dispatch_mode is not None: + raise AssertionError( + "At most one of pre_dispatch_mode and post_dispatch_mode may be active" + ) + + if pre_dispatch_mode is None: + return post_dispatch_mode + + return pre_dispatch_mode + + +def _unset_infra_mode(key): + from torch._ops import _get_dispatch_mode_pre_dispatch, unset_mode_pre_dispatch + + pre_dispatch_mode = _get_dispatch_mode_pre_dispatch(key) + post_dispatch_mode = torch._C._get_dispatch_mode(key) + if pre_dispatch_mode and post_dispatch_mode: + raise AssertionError( + "Can't have active infra mode on both pre and post dispatch mode stack" + ) + + if pre_dispatch_mode: + mode = unset_mode_pre_dispatch(key) + return mode + if post_dispatch_mode: + return torch._C._unset_dispatch_mode(key) + + +def _disable_infra_mode(key): + if key not in ( + torch._C._TorchDispatchModeKey.FUNCTIONAL, + torch._C._TorchDispatchModeKey.PROXY, + ): + raise AssertionError( + "key must be either FUNCTIONAL or PROXY _TorchDispatchModeKey" + ) + mode_unset = _unset_infra_mode(key) + try: + yield mode_unset + finally: + if mode_unset is not None: + _push_mode(mode_unset) + + +def _get_current_dispatch_mode_stack() -> list[TorchDispatchMode]: + """ + Returns the current stack of dispatch modes, with the most recent + (i.e., the one that will be processed first) at the end of the + list (standard stack convention). + """ + stack_len = _len_torch_dispatch_stack() + return [_get_dispatch_stack_at(i) for i in range(stack_len)] + + +def _push_mode(mode: TorchDispatchMode) -> None: + k = mode._dispatch_key if hasattr(mode, "_dispatch_key") else None + if k is not None and k != torch._C.DispatchKey.PreDispatch: + raise AssertionError( + "mode._dispatch_key must be None or DispatchKey.PreDispatch" + ) + if k is None: + _push_on_torch_dispatch_stack(mode) + return + + from torch._ops import _set_mode_pre_dispatch, get_cached_ops + + # See Note [Not Caching Per-Dispatch-Key Mode Handlers] + # Clear the cache of every op that has been used so far, for this particular key. + ks = torch._C._functionality_to_backend_keys(k) + for op in get_cached_ops(): + for key in ks: + op._uncache_dispatch(key) + _set_mode_pre_dispatch(mode) + + +def _pop_mode(k: DispatchKey | torch._C._TorchDispatchModeKey | None = None): + if k == torch._C.DispatchKey.PreDispatch: # type: ignore[attr-defined] + from torch._ops import _pop_mode_from_pre_dispatch + + return _pop_mode_from_pre_dispatch() + + if k is None or isinstance(k, torch._C._TorchDispatchModeKey): + return _pop_torch_dispatch_stack(k) + + +@contextlib.contextmanager +def _pop_mode_temporarily(k: DispatchKey | None = None): + old = _pop_mode(k) + try: + yield old + finally: + _push_mode(old) + + +@contextlib.contextmanager +def _disable_current_modes(): + from torch._ops import ( + _len_torch_dispatch_stack_pre_dispatch, + _pop_mode_from_pre_dispatch, + ) + from torch._subclasses.functional_tensor import FunctionalTensorMode + from torch._subclasses.schema_check_mode import SchemaCheckMode + from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode + + mode_len_pre_dispatch = _len_torch_dispatch_stack_pre_dispatch() + old_pre_dispatch_modes = [ + _pop_mode_from_pre_dispatch() for _ in range(mode_len_pre_dispatch) + ] + + has_proxy_mode_in_pre_dispatch = False + has_functional_mode_in_pre_dispatch = False + has_schema_check_mode_in_pre_dispatch = False + + for i in old_pre_dispatch_modes: + if isinstance(i, ProxyTorchDispatchMode): + has_proxy_mode_in_pre_dispatch = True + if isinstance(i, FunctionalTensorMode): + has_functional_mode_in_pre_dispatch = True + if isinstance(i, SchemaCheckMode): + has_schema_check_mode_in_pre_dispatch = True + + mode_len = _len_torch_dispatch_stack() + old_modes = [_pop_mode() for _ in range(mode_len)] + + for old in old_modes: + if ( + isinstance(old, FunctionalTensorMode) + and has_functional_mode_in_pre_dispatch + ): + raise AssertionError( + "Can't have FunctionalMode available both in PreDispatch and Python Key" + ) + if isinstance(old, ProxyTorchDispatchMode) and has_proxy_mode_in_pre_dispatch: + raise AssertionError( + "Can't have ProxyTorchDispatchMode available both in PreDispatch and Python Key" + ) + if isinstance(old, SchemaCheckMode) and has_schema_check_mode_in_pre_dispatch: + raise AssertionError( + "Can't have SchemaCheckMode available both in PreDispatch and Python Key" + ) + + # Manually disable proxy and fake modes, if any are active + try: + yield old_pre_dispatch_modes + old_modes + finally: + for mode in reversed(old_modes): + _push_mode(mode) + for mode in reversed(old_pre_dispatch_modes): + _push_mode(mode) + + +class BaseTorchDispatchMode(TorchDispatchMode): + def __torch_dispatch__(self, func, types, args=(), kwargs=None): + if kwargs is None: + kwargs = {} + return func(*args, **kwargs) + + +# Python typing cannot express Intersection[torch.Tensor, Protocol], so this +# protocol repeats the Tensor members that call sites commonly use after +# is_traceable_wrapper_subclass() narrows a value to this protocol. +class TraceableWrapperSubclass(Protocol): + """ + Canonical protocol for wrapper tensor subclasses that PT2 can trace through. + + ``__tensor_flatten__`` must return stable attribute names for the inner + values that participate in tracing together with any metadata needed to + rebuild the outer subclass. + + ``__tensor_unflatten__`` must reconstruct an equivalent wrapper subclass + instance from the flattened inner values, metadata, and requested outer + size/stride. Callers may pass tensor attrs and registered reference-type + opaques in ``inner_tensors``. The returned tensor is expected to preserve + the requested outer size/stride. If ``attrs, metadata = + x.__tensor_flatten__()``, then ``type(x).__tensor_unflatten__`` must round- + trip from ``{name: getattr(x, name) for name in attrs}``, ``metadata``, + ``x.size()``, and ``x.stride()`` to an equivalent instance of ``x``. + + ``__tensor_unflatten__`` may be implemented as either a ``@staticmethod`` + or a ``@classmethod``; the runtime check below intentionally uses duck + typing to support both forms, even though static type checkers may only + recognize the ``@staticmethod`` form as conforming to this protocol. + """ + + def __tensor_flatten__(self) -> tuple[Sequence[str], object]: ... + + @staticmethod + def __tensor_unflatten__( + inner_tensors: Mapping[str, torch.Tensor | CustomClassBase], + metadata: object, + outer_size: Sequence[int | torch.SymInt], + outer_stride: Sequence[int | torch.SymInt], + ) -> torch.Tensor: ... + + shape: torch._C.Size + + @overload + def stride(self, dim: None = None) -> tuple[int, ...]: ... + + @overload + def stride(self, dim: int) -> int: ... + + @overload + def size(self, dim: None = None) -> tuple[int, ...]: ... + + @overload + def size(self, dim: int) -> int: ... + + def storage_offset(self) -> int: ... + + def dim(self) -> int: ... + + @overload + def to( + self, + dtype: torch.types._dtype, + non_blocking: bool = False, + copy: bool = False, + *, + memory_format: torch.memory_format | None = None, + ) -> torch.Tensor: ... + + @overload + def to( + self, + device: torch._prims_common.DeviceLikeType | None = None, + dtype: torch.types._dtype | None = None, + non_blocking: bool = False, + copy: bool = False, + *, + memory_format: torch.memory_format | None = None, + ) -> torch.Tensor: ... + + @overload + def to( + self, + other: torch.Tensor, + non_blocking: bool = False, + copy: bool = False, + *, + memory_format: torch.memory_format | None = None, + ) -> torch.Tensor: ... + + +TensorWithFlatten = TraceableWrapperSubclass + + +def _has_traceable_wrapper_subclass_protocol(t: object) -> bool: + return hasattr(t, "__tensor_flatten__") and hasattr(t, "__tensor_unflatten__") + + +def is_traceable_wrapper_subclass(t: object) -> TypeIs[TraceableWrapperSubclass]: + """ + Returns whether ``t`` is a tensor subclass that matches the + ``TraceableWrapperSubclass`` protocol at runtime. + + See ``TraceableWrapperSubclass`` for the canonical flatten/unflatten + contract. Matching the protocol is necessary but not sufficient for full + PT2 support: the subclass's ``__torch_dispatch__`` implementation must also + desugar into traceable dispatcher operations and preserve aliasing semantics + with ``return_and_correct_aliasing()`` when needed. + """ + is_subclass = isinstance(t, torch.Tensor) and type(t) is not torch.Tensor + return is_subclass and _has_traceable_wrapper_subclass_protocol(t) + + +def is_traceable_wrapper_subclass_type( + t: type, +) -> TypeIs[type[TraceableWrapperSubclass]]: + """Same as above, but takes a type argument instead of an instance.""" + return ( + issubclass(t, torch.Tensor) + and t is not torch.Tensor + and _has_traceable_wrapper_subclass_protocol(t) + ) + + +def transform_subclass(t, callback, outer_size=None, outer_stride=None): + """ + Given a traceable, wrapper tensor subclass ``t`` that implements + ``__torch_dispatch__`` and holds some inner tensors, + and a callback of type ``Callable[[str, torch.Tensor], torch.Tensor]``, + `transform_subclass` will construct a fresh instance of the wrapper tensor subclass. + It will do so by grabbing each inner tensor attribute from the wrapper, + passing them into ``callback`` to get a transformed tensor, + and putting each transformed tensor into the fresh tensor subclass instance. + + Note: this function will not handle ensuring that the fresh subclass + gets the same (autograd, and aliasing) metadata as the original tensor. + This is generally handled in other subsystems like AOTAutograd. + """ + outer_size = outer_size if outer_size is not None else t.size() + outer_stride = outer_stride if outer_stride is not None else t.stride() + + attrs, ctx = t.__tensor_flatten__() + transformed_tensors_dict = {} + for attr in attrs: + transformed_tensors_dict[attr] = callback(attr, getattr(t, attr)) + sub = type(t).__tensor_unflatten__( + transformed_tensors_dict, ctx, outer_size, outer_stride + ) + + # NB: Purposefully guard here to simplify the inner / outer symbols. + # Using sym_eq() for symbolic comparison can result in an expression that's too + # difficult to guard on, so we use == here. + if sub.shape != outer_size: + raise AssertionError( + f"Expected return value from {type(t)}__tensor_unflatten__() to have " + f"shape equal to {outer_size}, but got: {sub.shape}" + ) + if sub.stride() != outer_stride: + raise AssertionError( + f"Expected return value from {type(t)}__tensor_unflatten__() to have " + f"stride equal to {outer_stride}, but got: {sub.stride()}" + ) + + return sub + + +def _correct_storage_aliasing(func, schema_info, args, outs) -> None: + """ + Given: an OpOverload, a SchemaInfo (cached information from torchgen about schema), + and the inputs/outputs to the OpOverload, + this function checks to see if func is a view operator + (by checking if any of the outputs in the op's schema + are immutable aliases of inputs). + If so, this function manually aliases the storage of the output tensor + with its corresponding input tensor alias. + It does this by unsafely overwriting the storage field of the output tensor + to be the same storage as the input. + """ + if not isinstance(func, torch._ops.OpOverload): + raise AssertionError(f"func must be an OpOverload, got {type(args)}") + if not isinstance(args, tuple): + raise AssertionError(f"args must be a tuple, got {type(args)}") + if not isinstance(outs, (list, tuple)): + raise AssertionError(f"outs must be a list or tuple, got {type(args)}") + + def alias_non_inplace_storage(arg, ret) -> None: + # This is hopefully a reasonable assert: + # subclasses that rely on this API for output aliasing + # should always return wrapper tensor subclasses for us to manually alias. + # in theory if a subclass that needs this API wants to sometimes return + # plain tensors, we could remove the assert and just not perform the aliasing, + # but it seems safer to learn more about this case first. + # + # Performance note: This is all just to assert that the argument and result + # types match, checking that is cheaper than is_traceable_wrapper_subclass_type, + # and multiple returns are relatively unlikely, so just check up front! + arg_type = type(arg) + ret_type = type(ret) + if arg_type is not ret_type and ( + is_traceable_wrapper_subclass_type(arg_type) + or is_traceable_wrapper_subclass_type(ret_type) + ): + ret_list = ret if isinstance(ret, list) else [ret] + for r in ret_list: + if type(arg) is not type(r): + raise AssertionError( + f"Called {str(func)} with input of type {type(arg)}\n" + f"and output of type {type(ret)}. But expected types to match." + ) + # Need to call a non-dispatcher helper, because we explicitly do **not** + # want our subclass to intercept the set_() call. + # instead, our subclass should directly have its storage swapped out. + # we **explicitly** don't want to reset the sizes on ret, if the storage implies a size change. + # Why? + # The purpose of this API is *not* to change the size/strides of our output- we assume it's already correct. + # We just want to "fix up" the storage aliasing, without modifying or output's metadata. + # Example: out = inp.expand(inp.shape[0], inp.shape[0]) + # This requires swapping the storage of out to be the same as inp, + # but we do *not* want it to change the sizes/strides that were compute for out. + + if isinstance(ret, list): + for r in ret: + torch._functionalize_unsafe_set(r, arg) + else: + if not isinstance(ret, torch.Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(ret)}") + torch._functionalize_unsafe_set(ret, arg) + + for arg_idx, return_idx in schema_info.read_only_alias_match_indexes: + alias_non_inplace_storage(args[arg_idx], outs[return_idx]) + + +def _get_write_alias(x) -> str | None: + alias_set = x.alias_set + if not alias_set or not x.is_write: + return None + # torchscript allows for complicated alias sets, but our dispatcher ops only really involve simple aliasing + if len(alias_set) != 1: + raise AssertionError("Expected alias_set to contain exactly one element") + # timeit says next(iter(alias_set)) is faster than list(alias_set)[0] even for + # set of size 1 on Python 3.13. + return next(iter(alias_set)) + + +# This abstracts over the fact that in return_and_correct_aliasing, +# we sometimes use torchgen schema parsing (for aten ops, since torchscript's schema parsing is sometimes buggy), +# and sometimes use torchscript schema parsing (for custom ops, for which torchgen parsing is untested). +@dataclass +class AliasInfo: + alias_set: set[str] + is_write: bool + name: str | None + + +@dataclass +class SchemaInfo: + args: list[AliasInfo] + outs: list[AliasInfo] + + is_inplace_view_op: bool + + # [_get_write_alias(x) for x in outs]. Guaranteed to contain no Nones; we coerce + # all-Nones result to empty list instead, and we don't support + # some-but-not-all-Nones. + outs_write_aliases: list[str] | None + + # List of (arg_idx, return_idx) where args[arg_idx].alias_set & + # outs[out_idx].alias_set is not empty, and not args[arg_idx].is_write. + read_only_alias_match_indexes: list[tuple[int, int]] + + +# Given an OpOverload, returns schema information on it. +# This is cached for efficiency, since it can involve running torchgen +@functools.cache +def get_alias_info(func) -> SchemaInfo: + # For ATen ops: use torchgen (since torchscript parser doesn't handle alias annotations + # properly for some ops that output tensorlists) + if func.namespace == "aten": + torchgen_schema_str = str(func._schema) + if not torchgen_schema_str.startswith("aten::"): + raise AssertionError( + "Expected torchgen schema string to start with 'aten::'" + ) + # remove the aten:: namespace, which is added by the torchscript parser, + # and torchgen doesn't know how to handle + torchgen_schema_str = torchgen_schema_str[6:] + import re + + # the torchscript parser ends up converting int[2]=1 into int[2]=[1, 1], + # which torchgen chokes on. + torchgen_schema_str = re.sub(r"=\[[0, ]+\]", "=0", torchgen_schema_str) + torchgen_schema_str = re.sub(r"=\[[1, ]+\]", "=1", torchgen_schema_str) + # for aten::rot90 / aten:fft_* + torchgen_schema_str = re.sub( + r"=\[(-?[0-9]+), (-?[0-9]+)\]", r"=[\1,\2]", torchgen_schema_str + ) + torchgen_schema = torchgen.model.FunctionSchema.parse(torchgen_schema_str) + arg_schemas = [ + AliasInfo( + alias_set=( + set() if a.annotation is None else set(a.annotation.alias_set) + ), + is_write=a.annotation is not None and a.annotation.is_write, + name=a.name, + ) + for a in torchgen_schema.arguments.flat_all + ] + out_schemas = [ + AliasInfo( + alias_set=( + set() if a.annotation is None else set(a.annotation.alias_set) + ), + is_write=a.annotation is not None and a.annotation.is_write, + name=a.name, + ) + for a in torchgen_schema.returns + ] + else: + # For non-aten ops, torchgen is untested so we rely on torchscript schema parsing + arg_schemas = [ + AliasInfo( + alias_set=( + set() if a.alias_info is None else set(a.alias_info.before_set) + ), + is_write=a.alias_info is not None and a.alias_info.is_write, + name=a.name, + ) + for a in func._schema.arguments + ] + out_schemas = [ + AliasInfo( + alias_set=( + set() if a.alias_info is None else set(a.alias_info.before_set) + ), + is_write=a.alias_info is not None and a.alias_info.is_write, + name=a.name, + ) + for a in func._schema.returns + ] + read_only_alias_match_indexes = [] + for arg_idx, schema_arg in enumerate(arg_schemas): + for return_idx, schema_out in enumerate(out_schemas): + is_read_only_alias_match = ( + schema_arg.alias_set & schema_out.alias_set + ) and not schema_arg.is_write + if is_read_only_alias_match: + read_only_alias_match_indexes.append((arg_idx, return_idx)) + + outs_write_aliases_list: list[str | None] = [ + _get_write_alias(r) for r in out_schemas + ] + non_nones = sum(x is not None for x in outs_write_aliases_list) + if non_nones == 0: + outs_write_aliases: list[str] | None = None + elif non_nones != len(outs_write_aliases_list): + # simplifying assumption: we don't have **any** ops with return types like "-> (Tensor(a!), Tensor)" + raise RuntimeError("Unsupported schema: " + str(func._schema)) + else: + outs_write_aliases = cast(list[str], outs_write_aliases_list) + + schema_info = SchemaInfo( + args=arg_schemas, + outs=out_schemas, + # This check is surprisingly expensive because pybind11 enum_s are + # inefficient. Just cache it. + is_inplace_view_op=torch.Tag.inplace_view in func.tags, + outs_write_aliases=outs_write_aliases, + read_only_alias_match_indexes=read_only_alias_match_indexes, + ) + return schema_info + + +def autograd_would_have_decomposed( + func: torch._ops.OpOverload, flat_args: Sequence[torch.Tensor | object] +) -> bool: + """ + Suppose that an operator has CompositeImplicitAutograd decomp registered. + Would autograd have used this decomposition? It will only use it if there + isn't an explicit backend registration for the device as well. This function + will tell if this would have occurred. + + Why do we need to apply these decompositions later? When inference mode is + on, the autograd key is bypassed entirely, so a lower level mode cannot rely + on the decomposition having been applied. It's easy to accidentally never apply + the decomposition, resulting in an operator showing up in a graph that + is unexpected. + + Why do we need to AVOID applying the decomposition when autograd wouldn't + have decomposed? If autograd doesn't decompose, this means in eager mode + we would have run the fused kernel. It must be possible to trace this + fused kernel directly into the graph for fidelity with eager (NB: a user + has the option of then further decomposing at proxy tensor mode via + decomposition table, but we must preserve it to proxy mode to have the + choice.) + + Why does functionalization need to also perform the test here? This is + because some CompositeImplicitAutograd decompositions are not functional. + If we are eventually going to decompose, we need to do this while we can + still turn functionalization back on, so those decompositions get functionalized. + So an early decomposition in functionalization may still be necessary. Note that + if proxy tensor decomposition process could turn functionalization back on, this + wouldn't be necessary, and maybe that is a useful thing to do anyway because + the decomposition table is user specified and a user could violate the functional + decomp requirement with a bad decomp. If this happened, then you could always + pass through functionalization. + """ + has_backend_registration = False + for a in flat_args: + if isinstance(a, torch.Tensor): + backend_key = torch._C._parse_dispatch_key( + torch._C._dispatch_key_for_device(a.device.type) + ) + if backend_key is None: + raise AssertionError( + f"failed to parse dispatch key for device {a.device.type}" + ) + # TODO: use func.has_kernel_for_dispatch_key(backend_key) + # but this one checks py_impl and CompositeImplicitAutograd + # incorrectly shows up as has backend reg here + has_backend_registration = torch._C._dispatch_has_kernel_for_dispatch_key( + func.name(), backend_key + ) + + # in theory we should take all backend keys and take the highest priority one + # to properly mimic the dispatcher, + # this just grabs the first tensor and takes its device key + break + return not has_backend_registration + + +def return_and_correct_aliasing(func, args, kwargs, out): + """ + This function should be used by wrapper tensor ``__torch_dispatch__`` subclasses + that would like to work with torch.compile. It ensures that the subclass + properly implements the aliasing behavior of every op, + which is needed for correctness in AOTAutograd. + This function will handle: + + * When we see a view op, we will alias the storages of any + input and output tensor subclasses + + * When we see an inplace or out= op, we will directly + return the corresponding input tensor, instead of returning + a (potentially) fresh output tensor. + """ + + # Caching here because torchgen parsing is definitely not fast, and this function is called + # once for every op in the graph during functionalization. + schema_info = get_alias_info(func) + + def get_arg_from_alias(output_alias, schema_info, args, kwargs): + new_args, new_kwargs = torch.fx.operator_schemas.normalize_function( # type: ignore[misc] + func, args=args, kwargs=kwargs + ) + + arg_indices = [ + i for i, a in enumerate(schema_info.args) if output_alias in a.alias_set + ] + # For any dispatcher op with an output alias, we expect it to map to exactly one alias in the schema's input arguments. + if len(arg_indices) != 1: + raise AssertionError( + "Expected exactly one argument index for the given output alias" + ) + idx = arg_indices[0] + arg_info = schema_info.args[idx] + if arg_info.name is not None and arg_info.name in new_kwargs: + return new_kwargs[arg_info.name] + return new_args[idx] + + # Fix up the storages of any outs so that they point to the same storage as the input, + # if func is a view op. + _correct_storage_aliasing( + func, schema_info, args, (out,) if not isinstance(out, tuple) else out + ) + + # For inplace_view ops in particular, we'll try hard to make sure that the wrapper subclass's + # metadata is set correctly. + if schema_info.is_inplace_view_op: + # no_dispatch() to make sure that we secretly change the metadata on the wrapper, + # but don't end up dispatching the op anywhere else. + mutated_args = [ + x + for i, x in enumerate(args) + if _get_write_alias(schema_info.args[i]) is not None + ] + # Assumption: we have a very small number of inplace_view ops that follow a strict schema: + # there is only a single argument that gets its metadata mutated. + if len(mutated_args) != 1: + raise AssertionError( + "expected exactly one mutated arg for inplace_view ops" + ) + # This check exists because we generally *do* want to update the metadata of any wrapper subclasses, + # but FunctionalTensor is special: it overrides all size/stride calls to plumb to the inner tensor. + # so we don't actually need to update the metadata (and attempting to do so causes errors) + from torch._subclasses.functional_tensor import FunctionalTensor + + if not isinstance(mutated_args[0], FunctionalTensor): + with torch.utils._mode_utils.no_dispatch(): + # See Note: [Fake Tensor Dispatch Keys] + # we're borrowing the way it modifies dispatch key TLS. + meta_in_tls = torch._C._meta_in_tls_dispatch_include() + torch._C._set_meta_in_tls_dispatch_include(True) + try: + func(*args, **kwargs) + finally: + torch._C._set_meta_in_tls_dispatch_include(meta_in_tls) + + # Next: we need to make sure to return inputs directly, if the output is a mutable alias (e.g. add_()). + + schema_info_outs_write_aliases = schema_info.outs_write_aliases + # simple case: none of our outputs have mutable aliases, so we can return the output as-is + if schema_info_outs_write_aliases is None: + return out + + if len(schema_info_outs_write_aliases) == 1: + return get_arg_from_alias( + schema_info_outs_write_aliases[0], schema_info, args, kwargs + ) + + # In the multi-return case, all aten ops return a tuple / list, so cast accordingly. + outs_to_return = type(out)( + [ + (get_arg_from_alias(write_alias, schema_info, args, kwargs)) + for write_alias in schema_info_outs_write_aliases + ] + ) + return outs_to_return diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_pytree.py b/.venv/lib/python3.12/site-packages/torch/utils/_pytree.py new file mode 100644 index 0000000000000000000000000000000000000000..a044e7c1769c3a76673b0a1fdd95b9110aa387c2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_pytree.py @@ -0,0 +1,2270 @@ +# Owner(s): ["module: pytree"] + +""" +Contains utility functions for working with nested python data structures. + +A *pytree* is a Python nested data structure. It is a tree in the sense that +nodes are Python collections (e.g., list, tuple, dict) and the leaves are +Python values. Furthermore, a pytree should not contain reference cycles. + +pytrees are useful for working with nested collections of Tensors. For example, +one can use `tree_map` to map a function over all Tensors inside some nested +collection of Tensors and `tree_leaves` to get a flat list of all Tensors +inside some nested collection. pytrees are helpful for implementing nested +collection support for PyTorch APIs. + +This pytree implementation is not very performant due to Python overhead +To improve the performance we can move parts of the implementation to C++. +""" + +import dataclasses +import functools +import importlib +import importlib.metadata +import json +import logging +import sys +import threading +import types +import warnings +from collections import defaultdict, deque, namedtuple, OrderedDict +from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence +from enum import Enum +from typing import ( + Any, + cast, + ClassVar, + Final, + Generic, + NoReturn, + overload, + Protocol, + TYPE_CHECKING, + TypeAlias, + TypeVar, +) +from typing_extensions import deprecated, NamedTuple, Self, TypeIs + +from torch.torch_version import TorchVersion as _TorchVersion + + +log = logging.getLogger(__name__) + + +if TYPE_CHECKING: + import torch.utils._cxx_pytree as cxx_pytree + + +__all__ = [ + "PyTree", + "Context", + "FlattenFn", + "UnflattenFn", + "DumpableContext", + "ToDumpableContextFn", + "FromDumpableContextFn", + "PyTreeSpec", + "TreeSpec", + "LeafSpec", + "keystr", + "key_get", + "register_pytree_node", + "tree_is_leaf", + "tree_flatten", + "tree_flatten_with_path", + "tree_unflatten", + "tree_iter", + "tree_leaves", + "tree_leaves_with_path", + "tree_structure", + "tree_map", + "tree_map_with_path", + "tree_map_", + "tree_map_only", + "tree_map_only_", + "tree_all", + "tree_any", + "tree_all_only", + "tree_any_only", + "treespec_dumps", + "treespec_loads", + "treespec_pprint", + "is_namedtuple", + "is_namedtuple_class", + "is_namedtuple_instance", + "is_structseq", + "is_structseq_class", + "is_structseq_instance", +] + + +T = TypeVar("T") +S = TypeVar("S") +U = TypeVar("U") +R = TypeVar("R") + + +DEFAULT_TREESPEC_SERIALIZATION_PROTOCOL = 1 +NO_SERIALIZED_TYPE_NAME_FOUND = "NO_SERIALIZED_TYPE_NAME_FOUND" + + +class KeyEntry(Protocol): + def __hash__(self) -> int: ... + + def __eq__(self, other: object) -> bool: ... + + def __str__(self) -> str: ... + + def get(self, parent: Any) -> Any: ... + + +class EnumEncoder(json.JSONEncoder): + def default(self, obj: object) -> str | dict[str, Any]: + if isinstance(obj, Enum): + return { + "__enum__": True, + "fqn": f"{obj.__class__.__module__}:{obj.__class__.__qualname__}", + "name": obj.name, + } + return cast(str, super().default(obj)) + + +Context = Any +PyTree = Any +FlattenFn = Callable[[PyTree], tuple[list[Any], Context]] +UnflattenFn = Callable[[Iterable[Any], Context], PyTree] +DumpableContext = Any # Any json dumpable text +ToDumpableContextFn = Callable[[Context], DumpableContext] +FromDumpableContextFn = Callable[[DumpableContext], Context] +ToStrFunc = Callable[["TreeSpec", list[str]], str] # deprecated +MaybeFromStrFunc = Callable[[str], tuple[Any, Context, str] | None] # deprecated +KeyPath = tuple[KeyEntry, ...] +FlattenWithKeysFn = Callable[[PyTree], tuple[list[tuple[KeyEntry, Any]], Any]] + +# Keep deprecated alias for backward compatibility +FlattenFunc = FlattenFn # deprecated +UnflattenFunc = UnflattenFn # deprecated +FlattenWithKeysFunc = FlattenWithKeysFn # deprecated + + +# A NodeDef holds two callables: +# - flatten_fn should take the collection and return a flat list of values. +# It can also return some context that is used in reconstructing the +# collection. +# - unflatten_fn should take a flat list of values and some context +# (returned by flatten_fn). It returns the collection by reconstructing +# it from the list and the context. +# - flatten_with_keys_fn, which is a callable that takes a +# pytree and returns a list of (keypath, value) pairs and a context. +class NodeDef(NamedTuple): + type: type[Any] + flatten_fn: FlattenFn + unflatten_fn: UnflattenFn + flatten_with_keys_fn: FlattenWithKeysFn | None + + +_NODE_REGISTRY_LOCK = threading.RLock() +SUPPORTED_NODES: dict[type[Any], NodeDef] = {} + + +# _SerializeNodeDef holds the following: +# - typ: the type of the node (e.g., "Dict", "List", etc) +# - serialized_type_name: the fully qualified name of the type, e.g. "collections.OrderedDict" +# - to_dumpable_context takes a TreeSpec, and returns a serialized string format of the +# context, and the version number +# - from_dumpable_context takes in a string representation of the context, and the +# version, and returns the deserialized context +class _SerializeNodeDef(NamedTuple): + typ: type[Any] + serialized_type_name: str + to_dumpable_context: ToDumpableContextFn | None + from_dumpable_context: FromDumpableContextFn | None + + +SUPPORTED_SERIALIZED_TYPES: dict[type[Any], _SerializeNodeDef] = {} +SERIALIZED_TYPE_TO_PYTHON_TYPE: dict[str, type[Any]] = {} + +# NB: we try really hard to not import _cxx_pytree (which depends on optree) +# as much as possible. This is for isolation: a user who is not using C++ pytree +# shouldn't pay for it, and it helps makes things like cpython upgrades easier. +_optree_minimum_version = _TorchVersion("0.13.0") +try: + _optree_version = importlib.metadata.version("optree") +except importlib.metadata.PackageNotFoundError: + # No optree package found + _cxx_pytree_dynamo_traceable = _cxx_pytree_exists = False + _optree_version = _TorchVersion("0.0.0a0") +else: + _optree_version = _TorchVersion(_optree_version) + if _optree_version < _optree_minimum_version: + # optree package less than our required minimum version. + # Pretend the optree package doesn't exist. + # NB: We will raise ImportError if the user directly tries to + # `import torch.utils._cxx_pytree` (look in that file for the check). + _cxx_pytree_dynamo_traceable = _cxx_pytree_exists = False + else: + _cxx_pytree_dynamo_traceable = _cxx_pytree_exists = True + +_cxx_pytree_imported = False +_cxx_pytree_pending_imports: list[Any] = [] + + +def register_pytree_node( + cls: type[Any], + flatten_fn: FlattenFn, + unflatten_fn: UnflattenFn, + *, + serialized_type_name: str | None = None, + to_dumpable_context: ToDumpableContextFn | None = None, + from_dumpable_context: FromDumpableContextFn | None = None, + flatten_with_keys_fn: FlattenWithKeysFn | None = None, +) -> None: + """Register a container-like type as pytree node. + + Note: + :func:`register_dataclass` is a simpler way of registering a container-like + type as a pytree node. + + Args: + cls: the type to register + flatten_fn: A callable that takes a pytree and returns a flattened + representation of the pytree and additional context to represent the + flattened pytree. + unflatten_fn: A callable that takes a flattened version of the pytree, + additional context, and returns an unflattened pytree. + serialized_type_name: A keyword argument used to specify the fully qualified + name used when serializing the tree spec. + to_dumpable_context: An optional keyword argument to custom specify how + to convert the context of the pytree to a custom json dumpable + representation. This is used for json serialization, which is being + used in torch.export right now. + from_dumpable_context: An optional keyword argument to custom specify how + to convert the custom json dumpable representation of the context + back to the original context. This is used for json deserialization, + which is being used in torch.export right now. + flatten_with_keys_fn: An optional keyword argument to specify how to + access each pytree leaf's keypath when flattening and tree-mapping. + Like ``flatten_fn``, but in place of a List[leaf], it should return + a List[(keypath, leaf)]. + """ + with _NODE_REGISTRY_LOCK: + if cls in SUPPORTED_NODES: + raise ValueError(f"{cls} is already registered as pytree node.") + + _private_register_pytree_node( + cls, + flatten_fn, + unflatten_fn, + serialized_type_name=serialized_type_name, + to_dumpable_context=to_dumpable_context, + from_dumpable_context=from_dumpable_context, + flatten_with_keys_fn=flatten_with_keys_fn, + ) + + if not _cxx_pytree_exists: + return + + if _cxx_pytree_imported: + import torch.utils._cxx_pytree as cxx_pytree + + cxx_pytree._private_register_pytree_node( + cls, + flatten_fn, + unflatten_fn, + serialized_type_name=serialized_type_name, + to_dumpable_context=to_dumpable_context, + from_dumpable_context=from_dumpable_context, + ) + else: + args = (cls, flatten_fn, unflatten_fn) + kwargs = { + "serialized_type_name": serialized_type_name, + "to_dumpable_context": to_dumpable_context, + "from_dumpable_context": from_dumpable_context, + } + _cxx_pytree_pending_imports.append((args, kwargs)) + + +def register_dataclass( + cls: type[Any], + *, + field_names: list[str] | None = None, + drop_field_names: list[str] | None = None, + serialized_type_name: str | None = None, +) -> None: + """ + Registers a type that has the semantics of a ``dataclasses.dataclass`` type + as a pytree node. + + This is a simpler API than :func:`register_pytree_node` for registering + a dataclass or a custom class with the semantics of a dataclass. + + Args: + cls: The python type to register. The class must have the semantics of a + dataclass; in particular, it must be constructed by passing the fields + in. + field_names (Optional[List[str]]): A list of field names that correspond + to the **non-constant data** in this class. This list must contain + all the fields that are used to initialize the class. This argument + is optional if ``cls`` is a dataclass, in which case the fields will + be taken from ``dataclasses.fields()``. + drop_field_names (Optional[List[str]]): A list of field names that + should not be included in the pytree. + serialized_type_name: A keyword argument used to specify the fully + qualified name used when serializing the tree spec. This is only + needed for serializing the treespec in torch.export. + + Example: + + >>> from torch import Tensor + >>> from dataclasses import dataclass + >>> import torch.utils._pytree as pytree + >>> + >>> @dataclass + >>> class Point: + >>> x: Tensor + >>> y: Tensor + >>> + >>> pytree.register_dataclass(Point) + >>> + >>> point = Point(torch.tensor(0), torch.tensor(1)) + >>> point = pytree.tree_map(lambda x: x + 1, point) + >>> assert torch.allclose(point.x, torch.tensor(1)) + >>> assert torch.allclose(point.y, torch.tensor(2)) + + """ + drop_field_names = drop_field_names or [] + + if not dataclasses.is_dataclass(cls): + if field_names is None: + raise ValueError( + "field_names must be specified with a list of all fields used to " + f"initialize {cls}, as it is not a dataclass." + ) + elif field_names is None: + field_names = [f.name for f in dataclasses.fields(cls) if f.init] + else: + dataclass_init_fields = {f.name for f in dataclasses.fields(cls) if f.init} + dataclass_init_fields.difference_update(drop_field_names) + + if dataclass_init_fields != set(field_names): + error_msg = "field_names does not include all dataclass fields.\n" + + if missing := dataclass_init_fields - set(field_names): + error_msg += ( + f"Missing fields in `field_names`: {missing}. If you want " + "to include these fields in the pytree, please add them " + "to `field_names`, otherwise please add them to " + "`drop_field_names`.\n" + ) + + if unexpected := set(field_names) - dataclass_init_fields: + error_msg += ( + f"Unexpected fields in `field_names`: {unexpected}. " + "Please remove these fields, or add them to `drop_field_names`.\n" + ) + + raise ValueError(error_msg) + + def _flatten_fn(obj: Any) -> tuple[list[Any], Context]: + flattened = [] + flat_names = [] + none_names = [] + for name in field_names: + val = getattr(obj, name) + if val is not None: + flattened.append(val) + flat_names.append(name) + else: + none_names.append(name) + return flattened, [flat_names, none_names] + + def _unflatten_fn(values: Iterable[Any], context: Context) -> Any: + flat_names, none_names = context + return cls( + **dict(zip(flat_names, values, strict=True)), **dict.fromkeys(none_names) + ) + + def _flatten_fn_with_keys(obj: Any) -> tuple[list[Any], Context]: + flattened, (flat_names, _none_names) = _flatten_fn(obj) # type: ignore[misc] + return [ + (GetAttrKey(k), v) for k, v in zip(flat_names, flattened, strict=True) + ], flat_names + + _private_register_pytree_node( + cls, + _flatten_fn, + _unflatten_fn, + serialized_type_name=serialized_type_name, + flatten_with_keys_fn=_flatten_fn_with_keys, + ) + + +CONSTANT_NODES: set[type] = set() + + +def register_constant(cls: type[Any]) -> None: + """Registers a type as a pytree node with no leaves. + + In a :func:`torch.compile` region, if instances of these types get passed to + :func:`torch._dynamo.nonstrict_trace`-ed function, they treated as a + constant (sometimes referred to as "static"): + + 1. if the instance object existed before the :func:`torch.compile` region, + we _assume_ no mutation will happen to it inside the :func:`torch.compile` + region, require that it has non-default `__eq__` and `__hash__` methods, and + we guard on the instance based on its `__eq__` method, i.e., if a new + instance fails to match any instances from the previous compilations, + :func:`torch.compile` will recompile the function using the new instance. + + 2. else if the instance object is created inside the :func:`torch.compile` + region, we currently don't support using it in a + :func:`torch._dynamo.nonstrict_trace`-ed function. + + In general, if your class holds Tensors or dynamic int/float/bool (values that + may change from run-to-run of a function being compiled), then you probably + do not want to register it as a constant. + + Otherwise if you want to pass instance of a class to a + :func:`torch._dynamo.nonstrict_trace`-ed function, but you either can't use + :func:`register_pytree_node` on the class, or the class is "constant" enough + that you don't want to bother using :func:`register_pytree_node`, you should + consider using this function. + + Args: + cls: the type to register as a constant. This type must be hashable. + + Example: + + >>> from dataclasses import dataclass + >>> import torch.utils._pytree as pytree + >>> + >>> @dataclass(frozen=True) + >>> class Config: + >>> norm: str + >>> + >>> pytree.register_constant(Config) + >>> + >>> config = Config("l2") + >>> values, spec = pytree.tree_flatten(config) + >>> assert len(values) == 0 + + """ + if cls.__eq__ is object.__eq__: # type: ignore[comparison-overlap] + raise TypeError( + "register_constant(cls) expects `cls` to have a non-default `__eq__` implementation." + ) + + # Class with a custom `__eq__` without `__hash__` won't inherit the default + # `__hash__` from object; see https://stackoverflow.com/a/1608907. + if cls.__hash__ is None: # type: ignore[comparison-overlap] + raise TypeError( + "register_constant(cls) expects `cls` to have a non-default `__hash__` implementation." + ) + + def _flatten(x): # type: ignore[no-untyped-def] + return [], ConstantNode(x) + + def _unflatten(_, context): # type: ignore[no-untyped-def] + return context.value + + def _flatten_with_keys(x): # type: ignore[no-untyped-def] + return [], ConstantNode(x) + + with _NODE_REGISTRY_LOCK: + _private_register_pytree_node( + cls, + _flatten, + _unflatten, + flatten_with_keys_fn=_flatten_with_keys, + ) + CONSTANT_NODES.add(cls) + + +def is_constant_class(cls: type[Any]) -> bool: + return isinstance(cls, type) and cls in CONSTANT_NODES + + +@dataclasses.dataclass(frozen=True, slots=True) +class ConstantNode(Generic[T]): + value: T + + +def _is_constant_holder(spec: "TreeSpec") -> bool: + """Checks if the spec is from a pytree registered with register_constant""" + return isinstance(spec._context, ConstantNode) + + +def _retrieve_constant(spec: "TreeSpec") -> Any: + """Given a spec from a pytree registered with register_constant, retrieves the constant""" + if not _is_constant_holder(spec): + raise AssertionError("spec does not correspond to a registered constant pytree") + return tree_unflatten([], spec) + + +def _register_namedtuple( + cls: type[Any], + *, + serialized_type_name: str, +) -> None: + """ + Registers a namedtuple as a valid pytree node. By default namedtuples are + valid pytree nodes, but they are not serializable. This API provides the + argument `serialized_type_name` which allows these namedtuples to be + serialized. + + Args: + cls: the dataclass type to register + serialized_type_name: The serialized name for the dataclass. This is + required if you want to serialize the pytree TreeSpec containing this + namedtuple. + """ + _private_register_pytree_node( + cls, + _namedtuple_flatten, + _namedtuple_unflatten, + serialized_type_name=serialized_type_name, + to_dumpable_context=_namedtuple_serialize, + from_dumpable_context=_namedtuple_deserialize, + flatten_with_keys_fn=_namedtuple_flatten_with_keys, + ) + + +@deprecated( + "`torch.utils._pytree._register_pytree_node` is deprecated. " + "Please use `torch.utils._pytree.register_pytree_node` instead.", + category=FutureWarning, +) +def _register_pytree_node( + cls: type[Any], + flatten_fn: FlattenFn, + unflatten_fn: UnflattenFn, + to_str_fn: ToStrFunc | None = None, # deprecated + maybe_from_str_fn: MaybeFromStrFunc | None = None, # deprecated + *, + serialized_type_name: str | None = None, + to_dumpable_context: ToDumpableContextFn | None = None, + from_dumpable_context: FromDumpableContextFn | None = None, + flatten_with_keys_fn: FlattenWithKeysFn | None = None, +) -> None: + """Register a container-like type as pytree node for the Python pytree only. + + Args: + cls: the type to register + flatten_fn: A callable that takes a pytree and returns a flattened + representation of the pytree and additional context to represent the + flattened pytree. + unflatten_fn: A callable that takes a flattened version of the pytree, + additional context, and returns an unflattened pytree. + serialized_type_name: A keyword argument used to specify the fully qualified + name used when serializing the tree spec. + to_dumpable_context: An optional keyword argument to custom specify how + to convert the context of the pytree to a custom json dumpable + representation. This is used for json serialization, which is being + used in torch.export right now. + from_dumpable_context: An optional keyword argument to custom specify how + to convert the custom json dumpable representation of the context + back to the original context. This is used for json deserialization, + which is being used in torch.export right now. + flatten_with_keys_fn: An optional keyword argument to specify how to + access each pytree leaf's keypath when flattening and tree-mapping. + Like ``flatten_fn``, but in place of a List[leaf], it should return + a List[(keypath, leaf)]. + """ + if to_str_fn is not None or maybe_from_str_fn is not None: + warnings.warn( + "`to_str_fn` and `maybe_from_str_fn` is deprecated. " + "Please use `to_dumpable_context` and `from_dumpable_context` instead.", + FutureWarning, + stacklevel=2, + ) + + _private_register_pytree_node( + cls, + flatten_fn, + unflatten_fn, + serialized_type_name=serialized_type_name, + to_dumpable_context=to_dumpable_context, + from_dumpable_context=from_dumpable_context, + flatten_with_keys_fn=flatten_with_keys_fn, + ) + + +def _deregister_pytree_node( + cls: type[Any], +) -> None: + """This is an internal function that is used to deregister a pytree node type + for the Python pytree only. This should be only used inside PyTorch. + """ + with _NODE_REGISTRY_LOCK: + del SUPPORTED_NODES[cls] + node_def = SUPPORTED_SERIALIZED_TYPES[cls] + del SERIALIZED_TYPE_TO_PYTHON_TYPE[node_def.serialized_type_name] + del SUPPORTED_SERIALIZED_TYPES[cls] + CONSTANT_NODES.discard(cls) + + +def _private_register_pytree_node( + cls: type[Any], + flatten_fn: FlattenFn, + unflatten_fn: UnflattenFn, + *, + serialized_type_name: str | None = None, + to_dumpable_context: ToDumpableContextFn | None = None, + from_dumpable_context: FromDumpableContextFn | None = None, + flatten_with_keys_fn: FlattenWithKeysFn | None = None, +) -> None: + """This is an internal function that is used to register a pytree node type + for the Python pytree only. End-users should use :func:`register_pytree_node` + instead. + """ + from torch._library.opaque_object import is_custom_class + + if isinstance(cls, type) and is_custom_class(cls): + # TODO: remove this allowance once downstream callers stop calling + # register_constant on Enum subclasses. Enums are now natively + # supported as opaque value types and don't need pytree registration. + import enum + + if issubclass(cls, enum.Enum): + log.warning( + "%s is an Enum subclass and is now natively supported by " + "torch.compile as an opaque value type. Calling " + "register_constant() on Enum subclasses is deprecated and " + "will be an error in a future release.", + cls, + ) + else: + raise ValueError( + f"{cls} cannot be registered as a pytree as it has been " + "registered as an opaque object. Opaque objects must be pytree leaves." + ) + + with _NODE_REGISTRY_LOCK: + if cls in SUPPORTED_NODES: + # TODO: change this warning to an error after OSS/internal stabilize + warnings.warn( + f"{cls} is already registered as pytree node. " + "Overwriting the previous registration.", + stacklevel=2, + ) + + node_def = NodeDef(cls, flatten_fn, unflatten_fn, flatten_with_keys_fn) + SUPPORTED_NODES[cls] = node_def + + if (to_dumpable_context is None) ^ (from_dumpable_context is None): + raise ValueError( + f"Both to_dumpable_context and from_dumpable_context for {cls} must " + "be None or registered." + ) + + if serialized_type_name is None: + serialized_type_name = NO_SERIALIZED_TYPE_NAME_FOUND + + serialize_node_def = _SerializeNodeDef( + cls, + serialized_type_name, + to_dumpable_context, + from_dumpable_context, + ) + SUPPORTED_SERIALIZED_TYPES[cls] = serialize_node_def + SERIALIZED_TYPE_TO_PYTHON_TYPE[serialized_type_name] = cls + + +@dataclasses.dataclass(frozen=True, slots=True) +class SequenceKey(Generic[T]): + idx: int + + def __str__(self) -> str: + return f"[{self.idx!r}]" + + def get(self, sequence: Sequence[T]) -> T: + return sequence[self.idx] + + +K = TypeVar("K", bound=Hashable) + + +@dataclasses.dataclass(frozen=True, slots=True) +class MappingKey(Generic[K, T]): + key: K + + def __str__(self) -> str: + return f"[{self.key!r}]" + + def get(self, mapping: Mapping[K, T]) -> T: + return mapping[self.key] + + +@dataclasses.dataclass(frozen=True, slots=True) +class GetAttrKey: + name: str + + def __str__(self) -> str: + return f".{self.name}" + + def get(self, obj: Any) -> Any: + return getattr(obj, self.name) + + +# Reference: https://github.com/metaopt/optree/blob/main/optree/typing.py +def is_namedtuple(obj: object | type) -> bool: + """Return whether the object is an instance of namedtuple or a subclass of namedtuple.""" + cls = obj if isinstance(obj, type) else type(obj) + return is_namedtuple_class(cls) + + +# Reference: https://github.com/metaopt/optree/blob/main/optree/typing.py +def is_namedtuple_class(cls: type) -> bool: + """Return whether the class is a subclass of namedtuple.""" + return ( + isinstance(cls, type) + and issubclass(cls, tuple) + and isinstance(getattr(cls, "_fields", None), tuple) + and all(type(field) is str for field in cls._fields) # type: ignore[attr-defined] + and callable(getattr(cls, "_make", None)) + and callable(getattr(cls, "_asdict", None)) + ) + + +# Reference: https://github.com/metaopt/optree/blob/main/optree/typing.py +def is_namedtuple_instance(obj: object) -> bool: + """Return whether the object is an instance of namedtuple.""" + return is_namedtuple_class(type(obj)) + + +_T_co = TypeVar("_T_co", covariant=True) + + +# Reference: https://github.com/metaopt/optree/blob/main/optree/typing.py +class structseq(tuple[_T_co, ...]): + """A generic type stub for CPython's ``PyStructSequence`` type.""" + + __slots__: ClassVar[tuple[()]] = () + + n_fields: Final[int] # type: ignore[misc] + n_sequence_fields: Final[int] # type: ignore[misc] + n_unnamed_fields: Final[int] # type: ignore[misc] + + def __init_subclass__(cls) -> NoReturn: + """Prohibit subclassing.""" + raise TypeError("type 'structseq' is not an acceptable base type") + + def __new__( + cls: type[Self], + sequence: Iterable[_T_co], + # pyrefly: ignore [bad-function-definition] + dict: dict[str, Any] = ..., + ) -> Self: + raise NotImplementedError + + +# Reference: https://github.com/metaopt/optree/blob/main/optree/typing.py +def is_structseq(obj: object | type) -> bool: + """Return whether the object is an instance of PyStructSequence or a class of PyStructSequence.""" + cls = obj if isinstance(obj, type) else type(obj) + return is_structseq_class(cls) + + +# Set if the type allows subclassing (see CPython's Include/object.h) +Py_TPFLAGS_BASETYPE: int = 1 << 10 + + +# Reference: https://github.com/metaopt/optree/blob/main/optree/typing.py +def is_structseq_class(cls: type) -> bool: + """Return whether the class is a class of PyStructSequence.""" + return ( + isinstance(cls, type) + # Check direct inheritance from `tuple` rather than `issubclass(cls, tuple)` + and cls.__bases__ == (tuple,) + # Check PyStructSequence members + and isinstance(getattr(cls, "n_fields", None), int) + and isinstance(getattr(cls, "n_sequence_fields", None), int) + and isinstance(getattr(cls, "n_unnamed_fields", None), int) + # Check the type does not allow subclassing + and not bool(cls.__flags__ & Py_TPFLAGS_BASETYPE) # only works for CPython + ) + + +# Reference: https://github.com/metaopt/optree/blob/main/optree/typing.py +def is_structseq_instance(obj: object) -> bool: + """Return whether the object is an instance of PyStructSequence.""" + return is_structseq_class(type(obj)) + + +def _tuple_flatten(d: tuple[T, ...]) -> tuple[list[T], Context]: + return list(d), None + + +def _tuple_flatten_with_keys( + d: tuple[T, ...], +) -> tuple[list[tuple[KeyEntry, T]], Context]: + values, context = _tuple_flatten(d) + # pyrefly: ignore [bad-return] + return [(SequenceKey(i), v) for i, v in enumerate(values)], context + + +def _tuple_unflatten(values: Iterable[T], context: Context) -> tuple[T, ...]: + return tuple(values) + + +def _list_flatten(d: list[T]) -> tuple[list[T], Context]: + return d, None + + +def _list_flatten_with_keys(d: list[T]) -> tuple[list[tuple[KeyEntry, T]], Context]: + values, context = _list_flatten(d) + # pyrefly: ignore [bad-return] + return [(SequenceKey(i), v) for i, v in enumerate(values)], context + + +def _list_unflatten(values: Iterable[T], context: Context) -> list[T]: + return list(values) + + +def _dict_flatten(d: dict[Any, T]) -> tuple[list[T], Context]: + return list(d.values()), list(d.keys()) + + +def _dict_flatten_with_keys( + d: dict[Any, T], +) -> tuple[list[tuple[KeyEntry, T]], Context]: + values, context = _dict_flatten(d) + # pyrefly: ignore [bad-return] + return [(MappingKey(k), v) for k, v in zip(context, values, strict=True)], context + + +def _dict_unflatten(values: Iterable[T], context: Context) -> dict[Any, T]: + return dict(zip(context, values, strict=True)) + + +def _namedtuple_flatten(d: NamedTuple) -> tuple[list[Any], Context]: + return list(d), type(d) + + +def _namedtuple_flatten_with_keys( + d: NamedTuple, +) -> tuple[list[tuple[KeyEntry, Any]], Context]: + values, context = _namedtuple_flatten(d) + # pyrefly: ignore [bad-return] + return ( + [ + (GetAttrKey(field), v) + for field, v in zip(context._fields, values, strict=True) + ], + context, + ) + + +def _namedtuple_unflatten(values: Iterable[T], context: Context) -> NamedTuple: + return cast(NamedTuple, context(*values)) + + +def _namedtuple_serialize(context: Context) -> DumpableContext: + if context not in SUPPORTED_SERIALIZED_TYPES: + raise NotImplementedError( + f"Can't serialize TreeSpec of namedtuple class {context} because we " + "didn't register a serialized_type_name. Please register using " + "`_register_namedtuple`." + ) + + serialize_node_def = SUPPORTED_SERIALIZED_TYPES[context] + serialized_type_name = serialize_node_def.serialized_type_name + + if serialized_type_name == NO_SERIALIZED_TYPE_NAME_FOUND: + raise NotImplementedError( + f"Can't serialize TreeSpec of namedtuple class {context} because we " + "couldn't find a serialized_type_name. Please register using " + "`_register_namedtuple`." + ) + return serialized_type_name + + +def _namedtuple_deserialize(dumpable_context: DumpableContext) -> Context: + if dumpable_context not in SERIALIZED_TYPE_TO_PYTHON_TYPE: + raise NotImplementedError( + f"Can't deserialize TreeSpec of namedtuple class {dumpable_context} " + "because we couldn't find a serialized name." + ) + + typ = SERIALIZED_TYPE_TO_PYTHON_TYPE[dumpable_context] + return typ + + +def _ordereddict_flatten(d: OrderedDict[Any, T]) -> tuple[list[T], Context]: + return list(d.values()), list(d.keys()) + + +def _ordereddict_flatten_with_keys( + d: OrderedDict[Any, T], +) -> tuple[list[tuple[KeyEntry, T]], Context]: + values, context = _ordereddict_flatten(d) + # pyrefly: ignore [bad-return] + return [(MappingKey(k), v) for k, v in zip(context, values, strict=True)], context + + +def _ordereddict_unflatten( + values: Iterable[T], + context: Context, +) -> OrderedDict[Any, T]: + return OrderedDict((key, value) for key, value in zip(context, values, strict=True)) + + +_odict_flatten = _ordereddict_flatten +_odict_unflatten = _ordereddict_unflatten + + +def _defaultdict_flatten(d: defaultdict[Any, T]) -> tuple[list[T], Context]: + values, dict_context = _dict_flatten(d) + return values, [d.default_factory, dict_context] + + +def _defaultdict_flatten_with_keys( + d: defaultdict[Any, T], +) -> tuple[list[tuple[KeyEntry, T]], Context]: + values, context = _defaultdict_flatten(d) + _, dict_context = context + # pyrefly: ignore [bad-return] + return [ + (MappingKey(k), v) for k, v in zip(dict_context, values, strict=True) + ], context + + +def _defaultdict_unflatten( + values: Iterable[T], + context: Context, +) -> defaultdict[Any, T]: + default_factory, dict_context = context + return defaultdict(default_factory, _dict_unflatten(values, dict_context)) + + +def _defaultdict_serialize(context: Context) -> DumpableContext: + default_factory, dict_context = context + json_defaultdict = { + "default_factory_module": default_factory.__module__, + "default_factory_name": default_factory.__qualname__, + "dict_context": dict_context, + } + return json_defaultdict + + +def _defaultdict_deserialize(dumpable_context: DumpableContext) -> Context: + if not isinstance(dumpable_context, dict): + raise AssertionError("dumpable_context must be a dict") + + expected_keys = { + "default_factory_module", + "default_factory_name", + "dict_context", + } + if set(dumpable_context) != expected_keys: + raise AssertionError( + f"dumpable_context keys must be {expected_keys}, got {set(dumpable_context)}" + ) + + default_factory_module = dumpable_context["default_factory_module"] + default_factory_name = dumpable_context["default_factory_name"] + if not isinstance(default_factory_module, str): + raise AssertionError("default_factory_module must be a string") + if not isinstance(default_factory_name, str): + raise AssertionError("default_factory_name must be a string") + module = importlib.import_module(default_factory_module) + default_factory = getattr(module, default_factory_name) + + dict_context = dumpable_context["dict_context"] + return [default_factory, dict_context] + + +def _deque_flatten(d: deque[T]) -> tuple[list[T], Context]: + return list(d), d.maxlen + + +def _deque_flatten_with_keys( + d: deque[T], +) -> tuple[list[tuple[KeyEntry, T]], Context]: + values, context = _deque_flatten(d) + # pyrefly: ignore [bad-return] + return [(SequenceKey(i), v) for i, v in enumerate(values)], context + + +def _deque_unflatten(values: Iterable[T], context: Context) -> deque[T]: + return deque(values, maxlen=context) + + +_private_register_pytree_node( + tuple, + _tuple_flatten, + _tuple_unflatten, + serialized_type_name="builtins.tuple", + flatten_with_keys_fn=_tuple_flatten_with_keys, +) +_private_register_pytree_node( + list, + _list_flatten, + _list_unflatten, + serialized_type_name="builtins.list", + flatten_with_keys_fn=_list_flatten_with_keys, +) +_private_register_pytree_node( + dict, + _dict_flatten, + _dict_unflatten, + serialized_type_name="builtins.dict", + flatten_with_keys_fn=_dict_flatten_with_keys, +) +_private_register_pytree_node( + namedtuple, # type: ignore[arg-type] + _namedtuple_flatten, + _namedtuple_unflatten, + serialized_type_name="collections.namedtuple", + to_dumpable_context=_namedtuple_serialize, + from_dumpable_context=_namedtuple_deserialize, + flatten_with_keys_fn=_namedtuple_flatten_with_keys, +) +_private_register_pytree_node( + OrderedDict, + _ordereddict_flatten, + _ordereddict_unflatten, + serialized_type_name="collections.OrderedDict", + flatten_with_keys_fn=_ordereddict_flatten_with_keys, +) +_private_register_pytree_node( + defaultdict, + _defaultdict_flatten, + _defaultdict_unflatten, + serialized_type_name="collections.defaultdict", + to_dumpable_context=_defaultdict_serialize, + from_dumpable_context=_defaultdict_deserialize, + flatten_with_keys_fn=_defaultdict_flatten_with_keys, +) +_private_register_pytree_node( + deque, + _deque_flatten, + _deque_unflatten, + serialized_type_name="collections.deque", + flatten_with_keys_fn=_deque_flatten_with_keys, +) + + +STANDARD_DICT_TYPES: frozenset[type] = frozenset({dict, OrderedDict, defaultdict}) +# pyrefly: ignore [no-matching-overload] +BUILTIN_TYPES: frozenset[type] = frozenset( + # pyrefly: ignore [bad-argument-type] + { + tuple, + list, + dict, + namedtuple, # type: ignore[arg-type] + OrderedDict, + defaultdict, + deque, + }, +) + + +@deprecated( + "torch.utils._pytree._is_namedtuple_instance is private and will be removed in a future release. " + "Please use torch.utils._pytree.is_namedtuple_instance instead.", + category=FutureWarning, +) +def _is_namedtuple_instance(tree: Any) -> bool: + return is_namedtuple_instance(tree) + + +def _get_node_type(tree: Any) -> Any: + node_type = type(tree) + # All namedtuple types are implicitly registered as pytree nodes. + # XXX: Other parts of the codebase expect namedtuple types always return + # `namedtuple` instead of the actual namedtuple type. Even if the type + # is explicitly registered. + if is_namedtuple_class(node_type): + return namedtuple + return node_type + + +# A leaf is defined as anything that is not a Node. +def tree_is_leaf( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: + """Check if a pytree is a leaf. + + >>> tree_is_leaf(1) + True + >>> tree_is_leaf(None) + True + >>> tree_is_leaf([1, 2, 3]) + False + >>> tree_is_leaf((1, 2, 3), is_leaf=lambda x: isinstance(x, tuple)) + True + >>> tree_is_leaf({"a": 1, "b": 2, "c": 3}) + False + >>> tree_is_leaf({"a": 1, "b": 2, "c": None}) + False + """ + if is_leaf is not None and is_leaf(tree): + return True + return _get_node_type(tree) not in SUPPORTED_NODES + + +@deprecated( + "torch.utils._pytree._is_leaf is private and will be removed in a future release. " + "Please use torch.utils._pytree.tree_is_leaf instead.", + category=FutureWarning, +) +def _is_leaf(tree: PyTree, is_leaf: Callable[[PyTree], bool] | None = None) -> bool: + return tree_is_leaf(tree, is_leaf=is_leaf) + + +# A TreeSpec represents the structure of a pytree. It holds: +# "type": the type of root Node of the pytree +# context: some context that is useful in unflattening the pytree +# children(): specs for each child of the root Node +# num_nodes: the total number of nodes +# num_leaves: the number of leaves +# num_children: the number of children of the root Node (i.e., len(children())) +# is_leaf(): whether the root Node is a leaf +@dataclasses.dataclass(init=False, frozen=True, eq=True, repr=False, slots=True) +class TreeSpec: + """Representing the structure of the pytree.""" + + type: Any + _context: Context + _children: list[Self] + + num_nodes: int = dataclasses.field(init=False) + num_leaves: int = dataclasses.field(init=False) + num_children: int = dataclasses.field(init=False) + + def __init__( + self, + type: Any, + context: Context, # keep for backward compatibility + children_specs: list[Self], # keep for backward compatibility + ) -> None: + object.__setattr__(self, "type", type) + object.__setattr__(self, "_context", context) + object.__setattr__(self, "_children", children_specs) + self.__post_init__() + + def __post_init__(self) -> None: + if self.type is None: + if self._context is not None: + raise AssertionError("leaf node should not have a context") + if len(self._children) != 0: + raise AssertionError("leaf node should not have children") + num_nodes = 1 + num_leaves = 1 + num_children = 0 + else: + num_nodes = 1 + num_leaves = 0 + for child in self._children: + num_nodes += child.num_nodes + num_leaves += child.num_leaves + num_children = len(self._children) + object.__setattr__(self, "num_nodes", num_nodes) + object.__setattr__(self, "num_leaves", num_leaves) + object.__setattr__(self, "num_children", num_children) + + def __repr__(self, indent: int = 0) -> str: + repr_prefix: str = f"TreeSpec({self.type.__name__}, {self._context}, [" + children_specs_str: str = "" + if self.num_children > 0: + indent += 2 + children_specs_str += self._children[0].__repr__(indent) + children_specs_str += "," if self.num_children > 1 else "" + children_specs_str += ",".join( + [ + "\n" + " " * indent + child.__repr__(indent) + for child in self._children[1:] + ] + ) + repr_suffix: str = f"{children_specs_str}])" + return repr_prefix + repr_suffix + + def __eq__(self, other: PyTree) -> bool: + if self is other: + return True + elif other.__class__ is self.__class__: + if str(self.type) != str(other.type): + return False + if self._context != other._context: + return False + elif self._children != other._children: + return False + return True + return NotImplemented + + @property + def context(self) -> Context: + return self._context + + @property + @deprecated( + "`treespec.children_specs` is deprecated. " + "Use `treespec.child(index)` to access a single child, " + "or `treespec.children()` to get all children.", + category=FutureWarning, + ) + def children_specs(self) -> list[Self]: + return self._children + + def is_leaf(self) -> bool: + """Test whether the treespec represents a leaf.""" + return self.num_nodes == 1 and self.num_leaves == 1 + + def children(self) -> list[Self]: + """Get all the child treespecs.""" + return self._children.copy() + + def child(self, index: int) -> Self: + """Get the child treespec at the given index.""" + return self._children[index] + + def flatten_up_to(self, tree: PyTree) -> list[PyTree]: + """Flatten the subtrees in ``tree`` up to the structure of this treespec and return a list of subtrees.""" + + def helper(treespec: TreeSpec, node: PyTree, subtrees: list[PyTree]) -> None: + if treespec.is_leaf(): + subtrees.append(node) + return + + node_type = _get_node_type(node) + if treespec.type not in BUILTIN_TYPES: + # Always require custom node types to match exactly + if node_type != treespec.type: + raise ValueError( + f"Type mismatch; " + f"expected {treespec.type!r}, but got {node_type!r}.", + ) + flatten_fn = SUPPORTED_NODES[node_type].flatten_fn + children, context = flatten_fn(node) + if len(children) != treespec.num_children: + raise ValueError( + f"Node arity mismatch; " + f"expected {treespec.num_children}, but got {len(children)}.", + ) + if context != treespec._context: + raise ValueError( + f"Node context mismatch for custom node type {treespec.type!r}.", + ) + else: + # For builtin dictionary types, we allow some flexibility + # Otherwise, we require exact matches + both_standard_dict = ( + treespec.type in STANDARD_DICT_TYPES + and node_type in STANDARD_DICT_TYPES + ) + if not both_standard_dict and node_type != treespec.type: + raise ValueError( + f"Node type mismatch; " + f"expected {treespec.type!r}, but got {node_type!r}.", + ) + if len(node) != treespec.num_children: + raise ValueError( + f"Node arity mismatch; " + f"expected {treespec.num_children}, but got {len(node)}.", + ) + + if both_standard_dict: + # dictionary types are compatible with each other + dict_context = ( + treespec._context + if treespec.type is not defaultdict + # ignore mismatch of `default_factory` for defaultdict + else treespec._context[1] + ) + expected_keys = dict_context + got_key_set = set(node) + expected_key_set = set(expected_keys) + if got_key_set != expected_key_set: + missing_keys = expected_key_set.difference(got_key_set) + extra_keys = got_key_set.difference(expected_key_set) + message = "" + if missing_keys: + message += f"; missing key(s): {missing_keys}" + if extra_keys: + message += f"; extra key(s): {extra_keys}" + raise ValueError(f"Node keys mismatch{message}.") + children = [node[key] for key in expected_keys] + else: + # node_type is treespec.type + flatten_fn = SUPPORTED_NODES[node_type].flatten_fn + children, context = flatten_fn(node) + if ( + node_type is not deque # ignore mismatch of `maxlen` for deque + ) and context != treespec._context: + raise ValueError( + f"Node context mismatch for node type {treespec.type!r}; " + f"expected {treespec._context!r}, but got {context!r}.", # namedtuple type mismatch + ) + + for subtree, subspec in zip(children, treespec._children, strict=True): + helper(subspec, subtree, subtrees) + + subtrees: list[PyTree] = [] + helper(self, tree, subtrees) + return subtrees + + def unflatten(self, leaves: Iterable[Any]) -> PyTree: + """Reconstruct a pytree from the leaves.""" + if not isinstance(leaves, (list, tuple)): + leaves = list(leaves) + if len(leaves) != self.num_leaves: + raise ValueError( + f"treespec.unflatten(leaves): `leaves` has length {len(leaves)} " + f"but the spec refers to a pytree that holds {self.num_leaves} " + f"items ({self}).", + ) + if self.is_leaf(): + return leaves[0] + + unflatten_fn = SUPPORTED_NODES[self.type].unflatten_fn + + # Recursively unflatten the children + start = 0 + end = 0 + child_pytrees = [] + for child_spec in self._children: + end += child_spec.num_leaves + child_pytrees.append(child_spec.unflatten(leaves[start:end])) + start = end + + return unflatten_fn(child_pytrees, self._context) + + def __hash__(self) -> int: + node_type = self.type + if node_type is defaultdict: + default_factory, dict_context = self._context + hashable_context = (default_factory, tuple(dict_context)) + elif node_type in (dict, OrderedDict): + hashable_context = tuple(self._context) + elif node_type is None or node_type in BUILTIN_TYPES: + hashable_context = self._context + elif isinstance(self._context, ConstantNode): + hashable_context = self._context.value + else: + # The context for user-defined node types might not be hashable. + # Ignore it for hashing. + # This does not break the correctness that equal objects imply the + # same hash. This might increase the hash collision rate, but we + # don't care about that. + hashable_context = None + return hash((node_type, hashable_context, tuple(self._children))) + + +PyTreeSpec: TypeAlias = TreeSpec + + +# NOTE: subclassing a dataclass is subtle. In order to enable reasoning about +# this class with `dataclasses.fields`, etc., while having a simplified +# constructor that takes no argument, we wrap with `dataclass(init=True, ...)` +# again, with fields that have `init=False`. +@deprecated( + "`isinstance(treespec, LeafSpec)` is deprecated, " + "use `isinstance(treespec, TreeSpec) and treespec.is_leaf()` instead.", + category=FutureWarning, +) +@dataclasses.dataclass(init=False, frozen=True, eq=False, repr=False, slots=True) +class LeafSpec(TreeSpec): + type: Any = dataclasses.field(default=None, init=False) + _context: Context = dataclasses.field(default=None, init=False) + _children: list[Self] = dataclasses.field(default_factory=list, init=False) + + def __init__(self) -> None: + # On Python 3.10.0, the dataclass-generated __init__ for frozen+slots + # dataclasses doesn't populate init=False fields with simple defaults, + # causing copy.deepcopy to fail with AttributeError. Avoid the bug by + # providing a custom __init__ (init=False above) instead. + object.__setattr__(self, "type", None) + object.__setattr__(self, "_context", None) + object.__setattr__(self, "_children", []) + object.__setattr__(self, "num_nodes", 1) + object.__setattr__(self, "num_leaves", 1) + object.__setattr__(self, "num_children", 0) + + def __repr__(self, indent: int = 0) -> str: + return "*" + + def __reduce__(self) -> tuple[Callable[[], "LeafSpec"], tuple[()]]: + # Reconstruct via the factory rather than the deprecated LeafSpec + # constructor, so copy/pickle round-trips don't emit the FutureWarning + # and reuse the shared singleton. + return (treespec_leaf, ()) + + +# All leaves are equivalent, so represent with a single object to save on +# object construction time +with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", category=FutureWarning, module=__name__, append=False + ) + _LEAF_SPEC = LeafSpec() + + +def treespec_leaf() -> LeafSpec: + """Make a treespec representing a leaf node.""" + return _LEAF_SPEC + + +def treespec_tuple(iterable: Iterable[TreeSpec] = (), /) -> TreeSpec: + """Make a tuple treespec from an iterable of child treespecs.""" + children = list(iterable) + if any(not isinstance(child, TreeSpec) for child in children): + raise ValueError(f"Expected a tuple of TreeSpec values, got: {children!r}.") + return TreeSpec(tuple, None, children) + + +def treespec_dict( + mapping: Mapping[Any, TreeSpec] | Iterable[tuple[Any, TreeSpec]] = (), + /, + **kwargs: TreeSpec, +) -> TreeSpec: + """Make a dict treespec from a dict of child treespecs.""" + dct = dict(mapping, **kwargs) + if any(not isinstance(child, TreeSpec) for child in dct.values()): + raise ValueError(f"Expected a dictionary of TreeSpec values, got: {dct!r}.") + return TreeSpec(dict, list(dct.keys()), list(dct.values())) + + +def _is_pytreespec_instance( + obj: Any, +) -> TypeIs["TreeSpec | cxx_pytree.PyTreeSpec"]: + if isinstance(obj, TreeSpec): + return True + if "torch.utils._cxx_pytree" in sys.modules: + # The C++ pytree module is not always available, so we check if it is loaded. + # If the C++ pytree module is loaded, we can check if the treespec + # is an instance of the C++ TreeSpec class. + import torch.utils._cxx_pytree as cxx_pytree + + if isinstance(obj, cxx_pytree.PyTreeSpec): + return True + if "torch._dynamo.polyfills.pytree" in sys.modules: + # The PyTorch Dynamo pytree module is not always available, so we check if it is loaded. + # If the PyTorch Dynamo pytree module is loaded, we can check if the treespec + # is an instance of the PyTorch Dynamo TreeSpec class. + import torch._dynamo.polyfills.pytree as dynamo_pytree + + return isinstance(obj, dynamo_pytree.PyTreeSpec) + return False + + +def _ensure_python_treespec_instance( + treespec: "TreeSpec | cxx_pytree.PyTreeSpec", +) -> TreeSpec: + if isinstance(treespec, TreeSpec): + return treespec + + if not _is_pytreespec_instance(treespec): + raise TypeError( + f"Expected `treespec` to be an instance of " + f"PyTreeSpec but got item of type {type(treespec)}." + ) + dummy_tree = treespec.unflatten([0] * treespec.num_leaves) + return tree_structure(dummy_tree) + + +def tree_flatten( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> tuple[list[Any], TreeSpec]: + """Flattens a pytree into a list of values and a TreeSpec that can be used + to reconstruct the pytree. + """ + + def helper(node: PyTree, leaves: list[Any]) -> TreeSpec: + if tree_is_leaf(node, is_leaf=is_leaf): + leaves.append(node) + return _LEAF_SPEC + + node_type = _get_node_type(node) + flatten_fn = SUPPORTED_NODES[node_type].flatten_fn + children, context = flatten_fn(node) + + # Recursively flatten the children + subspecs = [helper(child, leaves) for child in children] + return TreeSpec(node_type, context, subspecs) + + leaves: list[Any] = [] + treespec = helper(tree, leaves) + return leaves, treespec + + +def tree_unflatten(leaves: Iterable[Any], treespec: TreeSpec) -> PyTree: + """Given a list of values and a TreeSpec, builds a pytree. + This is the inverse operation of `tree_flatten`. + """ + if not _is_pytreespec_instance(treespec): + if not _is_pytreespec_instance(leaves): + raise TypeError( + f"Expected `treespec` to be an instance of " + f"PyTreeSpec but got item of type {type(treespec)}." + ) + # Allow passing the PyTreeSpec instance as the first argument + leaves, treespec = treespec, leaves + return treespec.unflatten(leaves) + + +def tree_iter( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> Iterable[Any]: + """Get an iterator over the leaves of a pytree.""" + if tree_is_leaf(tree, is_leaf=is_leaf): + yield tree + else: + node_type = _get_node_type(tree) + flatten_fn = SUPPORTED_NODES[node_type].flatten_fn + child_pytrees, _ = flatten_fn(tree) + + # Recursively flatten the children + for child in child_pytrees: + yield from tree_iter(child, is_leaf=is_leaf) + + +def tree_leaves( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> list[Any]: + """Get a list of leaves of a pytree.""" + return list(tree_iter(tree, is_leaf=is_leaf)) + + +def tree_structure( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> TreeSpec: + """Get the TreeSpec for a pytree.""" + return tree_flatten(tree, is_leaf=is_leaf)[1] + + +def tree_map( + func: Callable[..., Any], + tree: PyTree, + *rests: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: + """Map a multi-input function over pytree args to produce a new pytree. + + See also :func:`tree_map_`. + + >>> tree_map(lambda x: x + 1, {"x": 7, "y": (42, 64)}) + {'x': 8, 'y': (43, 65)} + >>> tree_map(lambda x: x is None, {"x": 7, "y": (42, 64), "z": None}) + {'x': False, 'y': (False, False), 'z': True} + + If multiple inputs are given, the structure of the tree is taken from the first input; + subsequent inputs need only have ``tree`` as a prefix: + + >>> tree_map(lambda x, y: [x] + y, [5, 6], [[7, 9], [1, 2]]) + [[5, 7, 9], [6, 1, 2]] + + Args: + func (callable): A function that takes ``1 + len(rests)`` arguments, to be applied at the + corresponding leaves of the pytrees. + tree (pytree): A pytree to be mapped over, with each leaf providing the first positional + argument to function ``func``. + rests (tuple of pytree): A tuple of pytrees, each of which has the same structure as + ``tree`` or has ``tree`` as a prefix. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + A new pytree with the same structure as ``tree`` but with the value at each leaf given by + ``func(x, *xs)`` where ``x`` is the value at the corresponding leaf in ``tree`` and ``xs`` + is the tuple of values at corresponding nodes in ``rests``. + """ + leaves, treespec = tree_flatten(tree, is_leaf=is_leaf) + flat_args = [leaves] + [treespec.flatten_up_to(r) for r in rests] + return treespec.unflatten(map(func, *flat_args)) + + +def tree_map_( + func: Callable[..., Any], + tree: PyTree, + *rests: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: + """Like :func:`tree_map`, but do an inplace call on each leaf and return the original tree. + + See also :func:`tree_map`. + + Args: + func (callable): A function that takes ``1 + len(rests)`` arguments, to be applied at the + corresponding leaves of the pytrees. + tree (pytree): A pytree to be mapped over, with each leaf providing the first positional + argument to function ``func``. + rests (tuple of pytree): A tuple of pytrees, each of which has the same structure as + ``tree`` or has ``tree`` as a prefix. + is_leaf (callable, optional): An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns: + The original ``tree`` with the value at each leaf is given by the side-effect of function + ``func(x, *xs)`` (not the return value) where ``x`` is the value at the corresponding leaf + in ``tree`` and ``xs`` is the tuple of values at values at corresponding nodes in ``rests``. + """ + leaves, treespec = tree_flatten(tree, is_leaf=is_leaf) + flat_args = [leaves] + [treespec.flatten_up_to(r) for r in rests] + deque(map(func, *flat_args), maxlen=0) # consume and exhaust the iterable + return tree + + +Type2 = tuple[type[T], type[S]] +Type3 = tuple[type[T], type[S], type[U]] +TypeAny = type[Any] | tuple[type[Any], ...] | types.UnionType + +Fn2 = Callable[[T | S], R] +Fn3 = Callable[[T | S | U], R] +Fn = Callable[[T], R] +FnAny = Callable[[Any], R] + +MapOnlyFn = Callable[[T], Callable[[Any], Any]] + + +# These specializations help with type inference on the lambda passed to this +# function +@overload +def map_only(type_or_types_or_pred: type[T], /) -> MapOnlyFn[Fn[T, Any]]: ... + + +@overload +def map_only(type_or_types_or_pred: Type2[T, S], /) -> MapOnlyFn[Fn2[T, S, Any]]: ... + + +@overload +def map_only( + type_or_types_or_pred: Type3[T, S, U], / +) -> MapOnlyFn[Fn3[T, S, U, Any]]: ... + + +# This specialization is needed for the implementations below that call +@overload +def map_only(type_or_types_or_pred: TypeAny, /) -> MapOnlyFn[FnAny[Any]]: ... + + +@overload +def map_only( + type_or_types_or_pred: Callable[[Any], bool], / +) -> MapOnlyFn[FnAny[Any]]: ... + + +def map_only( + type_or_types_or_pred: TypeAny | Callable[[Any], bool], / +) -> MapOnlyFn[FnAny[Any]]: + """ + Suppose you are writing a tree_map over tensors, leaving everything + else unchanged. Ordinarily you would have to write: + + def go(t): + if isinstance(t, Tensor): + return ... + else: + return t + + With this function, you only need to write: + + @map_only(Tensor) + def go(t): + return ... + + You can also directly use 'tree_map_only' + """ + if isinstance(type_or_types_or_pred, (type, tuple, types.UnionType)): + + def pred(x: Any) -> bool: + return isinstance(x, type_or_types_or_pred) # type: ignore[arg-type] + + elif callable(type_or_types_or_pred): + pred = type_or_types_or_pred # type: ignore[assignment] + else: + raise TypeError("Argument must be a type, a tuple of types, or a callable.") + + def wrapper(func: Callable[[T], Any]) -> Callable[[Any], Any]: + @functools.wraps(func) + def wrapped(x: T) -> Any: + if pred(x): + return func(x) + return x + + return wrapped + + return wrapper + + +@overload +def tree_map_only( + type_or_types_or_pred: type[T], + /, + func: Fn[T, Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only( + type_or_types_or_pred: Type2[T, S], + /, + func: Fn2[T, S, Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only( + type_or_types_or_pred: Type3[T, S, U], + /, + func: Fn3[T, S, U, Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only( + type_or_types_or_pred: TypeAny, + /, + func: FnAny[Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only( + type_or_types_or_pred: Callable[[Any], bool], + /, + func: FnAny[Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +def tree_map_only( + type_or_types_or_pred: TypeAny | Callable[[Any], bool], + /, + func: FnAny[Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: + return tree_map(map_only(type_or_types_or_pred)(func), tree, is_leaf=is_leaf) + + +@overload +def tree_map_only_( + type_or_types_or_pred: type[T], + /, + func: Fn[T, Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only_( + type_or_types_or_pred: Type2[T, S], + /, + func: Fn2[T, S, Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only_( + type_or_types_or_pred: Type3[T, S, U], + /, + func: Fn3[T, S, U, Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only_( + type_or_types_or_pred: TypeAny, + /, + func: FnAny[Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +@overload +def tree_map_only_( + type_or_types_or_pred: Callable[[Any], bool], + /, + func: FnAny[Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: ... + + +def tree_map_only_( + type_or_types_or_pred: TypeAny | Callable[[Any], bool], + /, + func: FnAny[Any], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: + return tree_map_(map_only(type_or_types_or_pred)(func), tree, is_leaf=is_leaf) + + +def tree_all( + pred: Callable[[Any], bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: + flat_args = tree_iter(tree, is_leaf=is_leaf) + return all(map(pred, flat_args)) + + +def tree_any( + pred: Callable[[Any], bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: + flat_args = tree_iter(tree, is_leaf=is_leaf) + return any(map(pred, flat_args)) + + +@overload +def tree_all_only( + type_or_types: type[T], + /, + pred: Fn[T, bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: ... + + +@overload +def tree_all_only( + type_or_types: Type2[T, S], + /, + pred: Fn2[T, S, bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: ... + + +@overload +def tree_all_only( + type_or_types: Type3[T, S, U], + /, + pred: Fn3[T, S, U, bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: ... + + +def tree_all_only( + type_or_types: TypeAny, + /, + pred: FnAny[bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: + flat_args = tree_iter(tree, is_leaf=is_leaf) + return all(pred(x) for x in flat_args if isinstance(x, type_or_types)) + + +@overload +def tree_any_only( + type_or_types: type[T], + /, + pred: Fn[T, bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: ... + + +@overload +def tree_any_only( + type_or_types: Type2[T, S], + /, + pred: Fn2[T, S, bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: ... + + +@overload +def tree_any_only( + type_or_types: Type3[T, S, U], + /, + pred: Fn3[T, S, U, bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: ... + + +def tree_any_only( + type_or_types: TypeAny, + /, + pred: FnAny[bool], + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> bool: + flat_args = tree_iter(tree, is_leaf=is_leaf) + return any(pred(x) for x in flat_args if isinstance(x, type_or_types)) + + +# Broadcasts a pytree to the provided TreeSpec and returns the flattened +# values. If this is not possible, then this function returns None. +# +# For example, given pytree=0 and spec=TreeSpec(list, None, [LeafSpec(), LeafSpec()]), +# would return [0, 0]. This is useful for part of the vmap implementation: +# a user can pass in vmap(fn, in_dims)(*inputs). `in_dims` should be +# broadcastable to the tree structure of `inputs` and we use +# _broadcast_to_and_flatten to check this. +def _broadcast_to_and_flatten( + tree: PyTree, + treespec: TreeSpec, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> list[Any] | None: + def broadcast_prefix( + prefix_tree: PyTree, + full_tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, + ) -> list[Any]: + result: list[Any] = [] + + def add_leaves(x: Any, subtree: PyTree) -> None: + subtreespec = tree_structure(subtree, is_leaf=is_leaf) + result.extend([x] * subtreespec.num_leaves) + + tree_map_( + add_leaves, + prefix_tree, + full_tree, + is_leaf=is_leaf, + ) + return result + + full_tree = tree_unflatten([0] * treespec.num_leaves, treespec) + try: + return broadcast_prefix(tree, full_tree, is_leaf=is_leaf) + except ValueError: + return None + + +@dataclasses.dataclass +class _TreeSpecSchema: + """ + _TreeSpecSchema is the schema used to serialize the TreeSpec + It contains the following fields: + - type: A string name of the type. null for the case of a LeafSpec. + - context: Any format which is json dumpable + - children_spec: A list of children serialized specs. + """ + + type: str | None + context: DumpableContext + children_spec: list["_TreeSpecSchema"] + + +class _ProtocolFn(NamedTuple): + treespec_to_json: Callable[[TreeSpec], DumpableContext] + json_to_treespec: Callable[[DumpableContext], TreeSpec] + + +_SUPPORTED_PROTOCOLS: dict[int, _ProtocolFn] = {} + + +def _treespec_to_json(treespec: TreeSpec) -> _TreeSpecSchema: + if treespec.is_leaf(): + return _TreeSpecSchema(None, None, []) + + if treespec.type not in SUPPORTED_SERIALIZED_TYPES: + raise NotImplementedError( + f"Serializing {treespec.type} in pytree is not registered.", + ) + + serialize_node_def = SUPPORTED_SERIALIZED_TYPES[treespec.type] + + serialized_type_name = serialize_node_def.serialized_type_name + + if serialized_type_name == NO_SERIALIZED_TYPE_NAME_FOUND: + raise NotImplementedError( + f"No registered serialization name for {treespec.type} found. " + "Please update your _register_pytree_node call with a `serialized_type_name` kwarg." + ) + + if serialize_node_def.to_dumpable_context is None: + try: + serialized_context = json.dumps(treespec._context, cls=EnumEncoder) + except TypeError as e: + raise TypeError( + "Unable to serialize context. " + "Please make the context json dump-able, or register a " + "custom serializer using _register_pytree_node." + ) from e + else: + serialized_context = serialize_node_def.to_dumpable_context(treespec._context) + + child_schemas = [_treespec_to_json(child) for child in treespec._children] + + return _TreeSpecSchema(serialized_type_name, serialized_context, child_schemas) + + +def enum_object_hook(obj: dict[str, Any]) -> Enum | dict[str, Any]: + if "__enum__" in obj: + modname, _, classname = obj["fqn"].partition(":") + mod = importlib.import_module(modname) + enum_cls = mod + for attr in classname.split("."): + enum_cls = getattr(enum_cls, attr) + enum_cls = cast(type[Enum], enum_cls) + + return enum_cls[obj["name"]] + return obj + + +def _json_to_treespec(json_schema: DumpableContext) -> TreeSpec: + if ( + json_schema["type"] is None + and json_schema["context"] is None + and len(json_schema["children_spec"]) == 0 + ): + return _LEAF_SPEC + + if json_schema["type"] not in SERIALIZED_TYPE_TO_PYTHON_TYPE: + raise NotImplementedError( + f"Deserializing {json_schema['type']} in pytree is not registered.", + ) + + typ = SERIALIZED_TYPE_TO_PYTHON_TYPE[json_schema["type"]] + serialize_node_def = SUPPORTED_SERIALIZED_TYPES[typ] + + if serialize_node_def.from_dumpable_context is None: + try: + context = json.loads(json_schema["context"], object_hook=enum_object_hook) + except TypeError as ex: + raise TypeError( + "Unable to deserialize context. " + "Please make the context json load-able, or register a " + "custom serializer using _register_pytree_node.", + ) from ex + else: + context = serialize_node_def.from_dumpable_context(json_schema["context"]) + + children_specs = [ + _json_to_treespec(child_string) for child_string in json_schema["children_spec"] + ] + + return TreeSpec(typ, context, children_specs) + + +_SUPPORTED_PROTOCOLS[1] = _ProtocolFn(_treespec_to_json, _json_to_treespec) + + +def treespec_dumps(treespec: TreeSpec, protocol: int | None = None) -> str: + treespec = _ensure_python_treespec_instance(treespec) + + if protocol is None: + protocol = DEFAULT_TREESPEC_SERIALIZATION_PROTOCOL + + if protocol in _SUPPORTED_PROTOCOLS: + json_spec = _SUPPORTED_PROTOCOLS[protocol].treespec_to_json(treespec) + else: + raise ValueError( + f"Unknown protocol {protocol}. " + f"Available protocols: {list(_SUPPORTED_PROTOCOLS.keys())}", + ) + + str_spec = json.dumps((protocol, dataclasses.asdict(json_spec)), cls=EnumEncoder) + return str_spec + + +@functools.lru_cache +def treespec_loads(serialized: str) -> TreeSpec: + protocol, json_schema = json.loads(serialized) + + if protocol in _SUPPORTED_PROTOCOLS: + return _SUPPORTED_PROTOCOLS[protocol].json_to_treespec(json_schema) + raise ValueError( + f"Unknown protocol {protocol}. " + f"Available protocols: {list(_SUPPORTED_PROTOCOLS.keys())}", + ) + + +class _Asterisk(str): + __slots__ = () + + def __new__(cls) -> Self: + return super().__new__(cls, "*") + + def __repr__(self) -> str: + return "*" # no quotes + + +_asterisk = _Asterisk() +del _Asterisk + + +def treespec_pprint(treespec: TreeSpec) -> str: + dummy_tree = tree_unflatten([_asterisk] * treespec.num_leaves, treespec) + return repr(dummy_tree) + + +# TODO(angelayi): remove this function after OSS/internal stabilize +@deprecated( + "`pytree_to_str` is deprecated. Please use `treespec_dumps` instead.", + category=FutureWarning, +) +def pytree_to_str(treespec: TreeSpec) -> str: + return treespec_dumps(treespec) + + +# TODO(angelayi): remove this function after OSS/internal stabilize +@deprecated( + "`str_to_pytree` is deprecated. Please use `treespec_loads` instead.", + category=FutureWarning, +) +def str_to_pytree(json: str) -> TreeSpec: + return treespec_loads(json) + + +def arg_tree_leaves(*args: PyTree, **kwargs: PyTree) -> list[Any]: + """Get a flat list of arguments to this function + + A slightly faster version of tree_leaves((args, kwargs)) + """ + leaves: list[Any] = [] + for a in args: + leaves.extend(tree_iter(a)) + for a in kwargs.values(): + leaves.extend(tree_iter(a)) + return leaves + + +def tree_flatten_with_path( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> tuple[list[tuple[KeyPath, Any]], TreeSpec]: + """Flattens a pytree like :func:`tree_flatten`, but also returns each leaf's key path. + + Args: + tree: a pytree to flatten. If it contains a custom type, that type must be + registered with an appropriate `tree_flatten_with_path_fn` when registered + with :func:`register_pytree_node`. + is_leaf: An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + Returns: + A tuple where the first element is a list of (key path, leaf) pairs, and the + second element is a :class:`TreeSpec` representing the structure of the flattened + tree. + """ + _, treespec = tree_flatten(tree, is_leaf) + return list(_generate_key_paths((), tree, is_leaf)), treespec + + +def tree_leaves_with_path( + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> list[tuple[KeyPath, Any]]: + """Gets the leaves of a pytree like ``tree_leaves`` and returns each leaf's key path. + + Args: + tree: a pytree. If it contains a custom type, that type must be + registered with an appropriate `tree_flatten_with_path_fn` when registered + with :func:`register_pytree_node`. + is_leaf: An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + Returns: + A list of (key path, leaf) pairs. + """ + return list(_generate_key_paths((), tree, is_leaf)) + + +def _generate_key_paths( + key_path: KeyPath, + tree: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> Iterable[tuple[KeyPath, Any]]: + if is_leaf and is_leaf(tree): + yield key_path, tree + return + + node_type = _get_node_type(tree) + handler = SUPPORTED_NODES.get(node_type) + if not handler: + # This is a leaf + yield key_path, tree + return + + flatten_with_keys = handler.flatten_with_keys_fn + if flatten_with_keys: + key_children, _ = flatten_with_keys(tree) + for k, c in key_children: + yield from _generate_key_paths((*key_path, k), c, is_leaf) + else: + # We registered this pytree but didn't add a flatten_with_keys_fn, complain. + raise ValueError( + f"Did not find a flatten_with_keys_fn for type: {node_type}. " + "Please pass a flatten_with_keys_fn argument to register_pytree_node." + ) + + +def tree_map_with_path( + func: Callable[..., Any], + tree: PyTree, + *rests: PyTree, + is_leaf: Callable[[PyTree], bool] | None = None, +) -> PyTree: + """Like :func:`tree_map`, but the provided callable takes an additional key path argument. + + Args: + func: A function that takes ``2 + len(rests)`` arguments, to be applied at the + corresponding leaves of the pytrees. The first positional argument + to ``func`` is the key path of the leaf in question. The second + positional argument is the value of the leaf. + tree: A pytree to be mapped over, with each leaf providing the first positional + argument to function ``func``. + rests: A tuple of pytrees, each of which has the same structure as + ``tree`` or has ``tree`` as a prefix. + is_leaf: An extra leaf predicate function that will be called at each + flattening step. The function should have a single argument with signature + ``is_leaf(node) -> bool``. If it returns :data:`True`, the whole subtree being treated + as a leaf. Otherwise, the default pytree registry will be used to determine a node is a + leaf or not. If the function is not specified, the default pytree registry will be used. + + Returns + A new pytree with the same structure as ``tree`` but with the value at each leaf given by + ``func(keypath, x, *xs)`` where ``keypath`` is the key path at the + corresponding leaf in ``tree``, ``x`` is the value at that leaf, and + ``xs`` is the tuple of values at corresponding nodes in ``rests``. + """ + keypath_leaves, treespec = tree_flatten_with_path(tree, is_leaf) + keypath_leaves = list(zip(*keypath_leaves, strict=True)) + all_keypath_leaves = keypath_leaves + [treespec.flatten_up_to(r) for r in rests] + return treespec.unflatten(func(*xs) for xs in zip(*all_keypath_leaves, strict=True)) + + +def keystr(kp: KeyPath) -> str: + """Given a key path, return a pretty-printed representation.""" + return "".join([str(k) for k in kp]) + + +def key_get(obj: Any, kp: KeyPath) -> Any: + """Given an object and a key path, return the value at the key path.""" + for k in kp: + obj = k.get(obj) + return obj diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_runtime_estimation.py b/.venv/lib/python3.12/site-packages/torch/utils/_runtime_estimation.py new file mode 100644 index 0000000000000000000000000000000000000000..9961b3e2cc29b202c7d604633afb2e98b5923c28 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_runtime_estimation.py @@ -0,0 +1,188 @@ +import torch +from torch._inductor.analysis.device_info import datasheet_dram_bw_gbs, datasheet_tops +from torch._inductor.utils import get_device_tflops, get_gpu_dram_gbps +from torch.fx.experimental.symbolic_shapes import ( + optimization_hint, + statically_known_true, +) +from torch.utils._ordered_set import OrderedSet + +from .flop_counter import flop_registry + + +aten = torch.ops.aten + +_FLOAT_TYPES = OrderedSet( + [ + torch.float16, + torch.bfloat16, + torch.float32, + torch.float64, + ] +) + +# No fall-back kernel needed/exists for view ops +_VIEW_OPS = OrderedSet( + [ + aten.lift_fresh, + aten.t, + aten.transpose, + aten.view, + aten.detach, + aten._unsafe_view, + aten.split, + aten.adjoint, + aten.as_strided, + aten.diagonal, + aten.expand, + aten.expand_as, + aten.movedim, + aten.permute, + aten.select, + aten.squeeze, + aten.mT, + aten.mH, + aten.real, + aten.imag, + aten.view_as, + aten.unflatten, + aten.unfold, + aten.unbind, + aten.unsqueeze, + aten.vsplit, + aten.hsplit, + aten.split_with_sizes, + aten.swapaxes, + aten.swapdims, + aten.chunk, + ] +) +# We can ignore benchmarking tensor create ops +_CREATE_OPS = OrderedSet( + [ + aten.randint, + aten.randn, + aten.rand, + aten.randn_like, + aten.rand_like, + aten.randint_like, + aten.arange, + aten.ones_like, + aten.zeros_like, + ] +) + +_IGNORE_OPS = _VIEW_OPS | _CREATE_OPS + + +def flops_to_ns( + flops: float | int, dtype: "torch.dtype", gpu_type: str | None = None +) -> float: + """Convert a FLOPs count to estimated nanoseconds on the GPU. + + Uses 75% of theoretical peak and converts FLOPs to MACs (divide by 2). + + If ``gpu_type`` names a device in the datasheet, its pinned datasheet + TFLOPS are used instead of querying the current device, making the + estimate deterministic and hardware-independent. + """ + if gpu_type is not None: + is_tf32 = torch.backends.cuda.matmul.fp32_precision == "tf32" + tflops = datasheet_tops(dtype, is_tf32=is_tf32, device_name=gpu_type) + if tflops is None: + raise ValueError( + f"gpu_type {gpu_type!r} has no datasheet entry for {dtype}" + ) + else: + tflops = get_device_tflops(dtype) + peak_gpu_flops = tflops * 1e12 + if peak_gpu_flops == 0: + return 0.0 + macs = flops / 2 + return (macs / (0.75 * peak_gpu_flops)) * 1e9 + + +def get_compute_time( + func_packet, args, kwargs, out, out_dtypes, node_meta=None, gpu_type=None +) -> float: # type: ignore[no-untyped-def] + """ + Estimates the compute time of an aten operator. + + Args: + func_packet: The operator overload packet. + args: The arguments to the operator. + kwargs: The keyword arguments to the operator. + out: The output of the operator. + out_dtypes: The output data types. + node_meta: Optional FX node meta dict. Passed through to the flop + formula as ``_node_meta`` kwarg so formulas can read annotations + like ``sparsity_hint``. + gpu_type: Optional datasheet device name to pin the peak FLOPS to + instead of querying the current device. + + Returns: + float: The estimated compute time in nanoseconds. + """ + if func_packet in flop_registry: + if len(out_dtypes) != 1: + raise AssertionError( + f"Only support single out dtype got {out_dtypes} for {func_packet}" + ) + dtype = out_dtypes.pop() + flop_count_func = flop_registry[func_packet] + extra_kwargs = {} + if node_meta is not None: + extra_kwargs["_node_meta"] = node_meta + flop_count = flop_count_func(*args, **kwargs, out_val=out, **extra_kwargs) + return flops_to_ns(flop_count, dtype, gpu_type=gpu_type) + return 0.0 + + +def get_num_bytes(t: torch.Tensor) -> int: + """ + Calculates the memory consumption of a tensor. + + Args: + t (torch.Tensor): The input tensor. + + Returns: + int: The memory consumption of the tensor in bytes. + """ + real_numel = 1 + for size, stride in zip(t.shape, t.stride()): + # For dims with stride=0 (expanded/broadcast), only 1 element accessed + if not statically_known_true(stride == 0): + real_numel *= optimization_hint(size, fallback=0) + + return real_numel * t.element_size() + + +def get_transfer_time(flat_args_kwargs, flat_outs, gpu_type=None) -> float: # type: ignore[no-untyped-def] + """ + Estimates the memory transfer time of input and output tensors. + + Args: + flat_args_kwargs (List[torch.Tensor]): The flat list of arguments and keyword arguments. + flat_outs (List[torch.Tensor]): The flat list of outputs. + gpu_type: Optional datasheet device name to pin the DRAM bandwidth to + instead of querying the current device. + + Returns: + float: The estimated memory transfer time in nanoseconds. + """ + if gpu_type is not None: + gpu_memory_bandwidth = datasheet_dram_bw_gbs(gpu_type) + if gpu_memory_bandwidth is None: + raise ValueError(f"gpu_type {gpu_type!r} not found in datasheet") + else: + gpu_memory_bandwidth = get_gpu_dram_gbps() + read_bytes = sum( + get_num_bytes(t) for t in flat_args_kwargs if isinstance(t, torch.Tensor) + ) + write_bytes = sum( + get_num_bytes(t) for t in flat_outs if isinstance(t, torch.Tensor) + ) + counted_bytes = read_bytes + write_bytes + # The GPU memory bandwidth is in GB/s so the transfer time is in nanoseconds + transfer_time = counted_bytes / gpu_memory_bandwidth + return transfer_time diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_stats.py b/.venv/lib/python3.12/site-packages/torch/utils/_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..b8a2978c3ea7066c56070382d0d4866faf58ab8d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_stats.py @@ -0,0 +1,31 @@ +# NOTE! PLEASE KEEP THIS FILE *FREE* OF TORCH DEPS! IT SHOULD BE IMPORTABLE ANYWHERE. +# IF YOU FEEL AN OVERWHELMING URGE TO ADD A TORCH DEP, MAKE A TRAMPOLINE FILE A LA torch._dynamo.utils +# AND SCRUB AWAY TORCH NOTIONS THERE. +import collections +import functools +from collections import OrderedDict +from collections.abc import Callable +from typing import TypeVar +from typing_extensions import ParamSpec + + +simple_call_counter: OrderedDict[str, int] = collections.OrderedDict() + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +def count_label(label: str) -> None: + prev = simple_call_counter.setdefault(label, 0) + simple_call_counter[label] = prev + 1 + + +def count(fn: Callable[_P, _R]) -> Callable[_P, _R]: + @functools.wraps(fn) + def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R: + if fn.__qualname__ not in simple_call_counter: + simple_call_counter[fn.__qualname__] = 0 + simple_call_counter[fn.__qualname__] = simple_call_counter[fn.__qualname__] + 1 + return fn(*args, **kwargs) + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_strobelight/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/_strobelight/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_strobelight/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_strobelight/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d6270788509b68359dddbe09b1be2f4ba4b9356 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_strobelight/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_strobelight/__pycache__/cli_function_profiler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_strobelight/__pycache__/cli_function_profiler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f76f61a343be35127f40ea0180933657a8c38389 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_strobelight/__pycache__/cli_function_profiler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_strobelight/cli_function_profiler.py b/.venv/lib/python3.12/site-packages/torch/utils/_strobelight/cli_function_profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..d2e1595bf2a1477b33ed00446d86e6cdea267a8f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_strobelight/cli_function_profiler.py @@ -0,0 +1,313 @@ +# mypy: disallow-untyped-defs + +import functools +import logging +import os +import re +import subprocess +import time +from collections.abc import Callable, Sequence +from threading import Lock +from typing import Any, TypeVar +from typing_extensions import ParamSpec + + +logger = logging.getLogger("strobelight_function_profiler") + +console_handler = logging.StreamHandler() +formatter = logging.Formatter( + "%(name)s, line %(lineno)d, %(asctime)s, %(levelname)s: %(message)s" +) +console_handler.setFormatter(formatter) + +logger.addHandler(console_handler) +logger.setLevel(logging.INFO) +logger.propagate = False + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +class StrobelightCLIProfilerError(Exception): + """ + Raised when an error happens during strobelight profiling + """ + + +def _pid_namespace_link(pid: int | None = None) -> str: + """Returns the link to the process's namespace, example: pid:[4026531836]""" + PID_NAMESPACE_PATH = "/proc/{}/ns/pid" + pid = pid or os.getpid() + return os.readlink(PID_NAMESPACE_PATH.format(pid)) + + +def _pid_namespace(pid: int | None = None) -> int: + """Returns the process's namespace id""" + pid = pid or os.getpid() + link = _pid_namespace_link(pid) + return int(link[link.find("[") + 1 : -1]) + + +def _command_to_string(command: Sequence[str]) -> str: + return " ".join(command) + + +class StrobelightCLIFunctionProfiler: + """ + Note: this is a meta only tool. + + StrobelightCLIFunctionProfiler can be used to profile a python function and + generate a strobelight link with the results. It works on meta servers but + does not requires an fbcode target. + When stop_at_error is false(default), error during profiling does not prevent + the work function from running. + + Check function_profiler_example.py for an example. + """ + + # This lock is used to make sure only one thread is running the profiler at any point. + _lock = Lock() + + def __init__( + self, + *, + stop_at_error: bool = False, + max_profile_duration_sec: int = 60 * 10, + sample_each: float = 1e7, # sample each sample_each cycles. + run_user_name: str = "pytorch-strobelight-ondemand", + timeout_wait_for_running_sec: int = 60, + timeout_wait_for_finished_sec: int = 60, + recorded_env_variables: list[str] | None = None, + sample_tags: list[str] | None = None, + stack_max_len: int = 127, + async_stack_max_len: int = 127, + ) -> None: + self.stop_at_error = stop_at_error + self.max_profile_duration_sec = max_profile_duration_sec + self.sample_each = sample_each + self.run_user_name = run_user_name + self.timeout_wait_for_running_sec = timeout_wait_for_running_sec + self.timeout_wait_for_finished_sec = timeout_wait_for_finished_sec + # Results of the most recent run. + # Tracks the strobelight run id of the most recent run + self.current_run_id: int | None = None + self.sample_tags = sample_tags + + def _run_async(self) -> None: + processId = os.getpid() + namespace = _pid_namespace(processId) + command = [ + "strobeclient", + "run", + "--profiler", + "pyperf", + "--event", + "cycles", + "--async", + "--sample-interval", + f"{int(self.sample_each)}", + "--duration-ms", + f"{int(self.max_profile_duration_sec * 1000)}", + "--pid", + f"{namespace}:{processId}", + ] + + if self.sample_tags: + command.append("--sample-tags") + command.append(",".join(self.sample_tags)) + + logger.debug("running command: %s", _command_to_string(command)) + result = subprocess.run(command, capture_output=True) + output = result.stderr.decode("utf-8") + logger.debug("output:\n{%s}", output) + + if result.returncode != 0: + raise StrobelightCLIProfilerError( + f"failed to start strobelight profiling, error in run_async:{output}" + ) + + if match := re.search(r"INFO Run Id: (-?\d+)", output): + self.current_run_id = int(match.group(1)) + return + + raise StrobelightCLIProfilerError( + f"failed to start strobelight profiling, unexpected result {output}" + ) + + def _wait_for_running(self, counter: int = 0) -> None: + if counter > 20: + raise StrobelightCLIProfilerError( + "wait_for_running called more than 20 times" + ) + + command = ["strobeclient", "getRunStatus", "--run-id", f"{self.current_run_id}"] + logger.debug("running command: %s", _command_to_string(command)) + result = subprocess.run(command, capture_output=True) + output = result.stderr.decode("utf-8") + logger.debug("output:\n{%s}", output) + + if result.returncode != 0: + raise StrobelightCLIProfilerError( + f"failed to start strobelight profiling, error in wait_for_running:{output}" + ) + + if match := re.search("Profile run status: (.*)", output): + current_status = match.group(1) + if current_status == "RUNNING": + return + elif current_status == "PREPARING": + time.sleep(10) + self._wait_for_running(counter + 1) + return + else: + raise StrobelightCLIProfilerError(f"unexpected {current_status} phase") + + raise StrobelightCLIProfilerError(f"unexpected output\n: {output} ") + + def _stop_run(self) -> None: + command = ["strobeclient", "stopRun", "--run-id", str(self.current_run_id)] + logger.debug("running command: %s", _command_to_string(command)) + result = subprocess.run(command, capture_output=True) + output = result.stderr.decode("utf-8") + logger.debug("output:\n{%s}", output) + + if result.returncode != 0: + raise StrobelightCLIProfilerError( + f"failed to stop strobelight profiling, return code is not 0 :{output}" + ) + + if match := re.search("INFO ::1:(.*)", output): + current_status = match.group(1) + if current_status.__contains__("Success!"): + return + else: + raise StrobelightCLIProfilerError( + f"failed to stop strobelight profiling, got {current_status} result" + ) + + raise StrobelightCLIProfilerError(f"unexpected output\n: {output} ") + + def _get_results(self) -> None: + command = ["strobeclient", "getRunStatus", "--run-id", str(self.current_run_id)] + logger.debug("running command: %s", _command_to_string(command)) + result = subprocess.run(command, capture_output=True) + output = result.stderr.decode("utf-8") + logger.debug("output:\n{%s}", output) + + if result.returncode != 0: + raise StrobelightCLIProfilerError( + f"failed to extract profiling results, return code is not 0 : {output}" + ) + + if match := re.search("INFO ::1:(.*)", output): + current_status = match.group(1) + if current_status.__contains__("Profile run status: PROCESSING"): + time.sleep(10) + self._get_results() + return + elif not current_status.__contains__("Profile run finished with SUCCESS"): + raise StrobelightCLIProfilerError( + f"failed to extract profiling results, unexpected response {output}" + ) + + for item in re.findall( + r"(Total samples(.*)|GraphProfiler(.*)|Icicle view \(python stack\)(.*))", + output, + ): + logger.info(item[0]) + + def _stop_strobelight_no_throw( + self, + collect_results: bool, + ) -> None: + try: + # call stop run + self._stop_run() + logger.info("strobelight profiling stopped") + + logger.debug("collection stopped") + + if not collect_results: + return + + self._get_results() + except Exception: + logger.warning("error during stop_strobelight", exc_info=True) + + # Return true if strobelight started and is running. Never throw. + def _start_strobelight(self) -> bool: + strobelight_started = False + try: + self._run_async() + strobelight_started = True + logger.info("strobelight run id is: %s", self.current_run_id) + self._wait_for_running() + logger.info("strobelight profiling running") + return True + + except Exception: + logger.warning("error during start_strobelight:", exc_info=True) + if strobelight_started: + self._stop_strobelight_no_throw(collect_results=False) + return False + + def profile( + self, work_function: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs + ) -> _R | None: + self.current_run_id = None + + if locked := StrobelightCLIFunctionProfiler._lock.acquire(False): + if not locked: + if self.stop_at_error: + raise StrobelightCLIProfilerError("concurrent runs not supported") + + logger.warning("concurrent runs not supported") + return work_function(*args, **kwargs) + + started = self._start_strobelight() + if not started: + if self.stop_at_error: + StrobelightCLIFunctionProfiler._lock.release() + raise StrobelightCLIProfilerError( + "failed to start strobelight profiling" + ) + result = work_function(*args, **kwargs) + StrobelightCLIFunctionProfiler._lock.release() + return result + + try: + logger.debug("collection started") + result = work_function(*args, **kwargs) + self._stop_strobelight_no_throw(collect_results=True) + StrobelightCLIFunctionProfiler._lock.release() + return result + except Exception as error: + logger.warning("work function throw exception", exc_info=True) + self._stop_strobelight_no_throw(collect_results=False) + StrobelightCLIFunctionProfiler._lock.release() + raise error + return None + + +# A function decorator that wraps profile, if no profiler is provided one with +# default args is created. A function can be annotated as: +# @strobelight() +# @strobelight(profiler = StrobelightFunctionProfiler(stop_at_error=True,..)) +# @strobelight(stop_at_error=True,...) +def strobelight( + profiler: StrobelightCLIFunctionProfiler | None = None, **kwargs: Any +) -> Callable[[Callable[_P, _R]], Callable[_P, _R | None]]: + if not profiler: + profiler = StrobelightCLIFunctionProfiler(**kwargs) + + def strobelight_inner( + work_function: Callable[_P, _R], + ) -> Callable[_P, _R | None]: + @functools.wraps(work_function) + def wrapper_function(*args: _P.args, **kwargs: _P.kwargs) -> _R | None: + # pyrefly: ignore [bad-argument-type] + return profiler.profile(work_function, *args, **kwargs) + + return wrapper_function + + return strobelight_inner diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3022c20d809bc826c4b01d87b07e26a86cec7f28 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da6440be3f537c40949b61f8d089b0fade22eebe Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/functions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/interp.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/interp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae78148f228b70154a55adb5f272606e113a9ab5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/interp.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/numbers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/numbers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1f2ba5d61a631a776d980086d9bcf7336e94a8b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/numbers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/printers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/printers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe8405981739546405260159e621500e91ed36a3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/printers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/reference.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/reference.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e023c604c605b35ff66a13cb8c5c45bad8001b9c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/reference.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/singleton_int.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/singleton_int.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..029ab955640d219696fc96409b5f172f70f0cfcc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/singleton_int.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/solve.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/solve.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..809ad2edf11a7954dbf7bc006b17f941b4f644ec Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/solve.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/symbol.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/symbol.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48819b24346d1a1a72284279e3a926fe865c4b0a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/symbol.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/value_ranges.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/value_ranges.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9eb0aef79977235ada961a2294bc799f26a18044 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/__pycache__/value_ranges.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/functions.py b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..36fa1b6724e16e08516e067ee8c00103c6894984 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/functions.py @@ -0,0 +1,1568 @@ +import functools +import math +import operator +import sys +from collections.abc import Callable +from typing import SupportsFloat, TYPE_CHECKING, TypeVar +from typing_extensions import TypeVarTuple, Unpack + +import sympy +from sympy import S +from sympy.core import sympify +from sympy.core.expr import Expr +from sympy.core.function import Application +from sympy.core.logic import _torf, fuzzy_and, fuzzy_or +from sympy.core.numbers import equal_valued +from sympy.core.operations import LatticeOp, ShortCircuit +from sympy.core.sorting import ordered +from sympy.core.traversal import walk +from sympy.printing.precedence import PRECEDENCE +from sympy.utilities.iterables import sift + +from torch.torch_version import TorchVersion + +from .numbers import int_oo, IntInfinity, is_infinite + + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator, Sequence + + +_T = TypeVar("_T", bound=SupportsFloat) +_Ts = TypeVarTuple("_Ts") + +# sympy.gcd on wide Add expressions triggers expensive polynomial-GCD +# (dmp_sqr / dmp_rr_div) that scales poorly in the number of symbols. +# safe_gcd() falls back to simple_floordiv_gcd past this threshold. +_MAX_ADD_TERMS_FOR_POLY_GCD = 20 + + +def _is_wide_add(expr: sympy.Basic) -> bool: + return isinstance(expr, sympy.Add) and len(expr.args) > _MAX_ADD_TERMS_FOR_POLY_GCD + + +def safe_gcd(a: sympy.Basic, b: sympy.Basic) -> sympy.Basic: + """Like sympy.gcd but avoids polynomial-GCD on wide Add expressions, + falling back to simple_floordiv_gcd instead.""" + if _is_wide_add(a) or _is_wide_add(b): + return simple_floordiv_gcd(a, b) + return sympy.gcd(a, b) + + +# Portions of this file are adapted from the Sympy codebase, which was +# licensed as follows: +# +# Copyright (c) 2006-2023 SymPy Development Team +# +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# a. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# b. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# c. Neither the name of SymPy nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR +# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +# DAMAGE. + +__all__ = [ + "FloorDiv", + "ModularIndexing", + "Where", + "PythonMod", + "Mod", + "CleanDiv", + "CeilToInt", + "FloorToInt", + "CeilDiv", + "IntTrueDiv", + "FloatTrueDiv", + "LShift", + "RShift", + "IsNonOverlappingAndDenseIndicator", + "TruncToFloat", + "TruncToInt", + "RoundToInt", + "RoundDecimal", + "ToFloat", + "FloatPow", + "PowByNatural", + "Identity", +] + + +def _is_symbols_binary_summation(expr: sympy.Expr) -> bool: + # No need to check that two args are not the same, since expr is pre-optimized but we do it anyway. + return ( + isinstance(expr, sympy.Expr) + and expr.is_Add + and len(expr._args) == 2 + and expr._args[0].is_symbol + and expr._args[1].is_symbol + and expr._args[0] is not expr._args[1] + ) + + +def _keep_float( + f: Callable[[Unpack[_Ts]], _T], +) -> Callable[[Unpack[_Ts]], _T | sympy.Float]: + @functools.wraps(f) + def inner(*args: Unpack[_Ts]) -> _T | sympy.Float: + r: _T | sympy.Float = f(*args) + if any(isinstance(a, sympy.Float) for a in args) and not isinstance( + r, sympy.Float + ): + r = sympy.Float(float(r)) + return r + + # pyrefly: ignore [bad-return] + return inner + + +def fuzzy_eq(x: bool | None, y: bool | None) -> bool | None: + if None in (x, y): + return None + return x == y + + +def simple_floordiv_gcd(p: sympy.Basic, q: sympy.Basic) -> sympy.Basic: + """ + Fast path for sympy.gcd, using a simple factoring strategy. + + We try to rewrite p and q in the form n*e*p1 + n*e*p2 and n*e*q0, + where n is the greatest common integer factor and e is the largest + syntactic common factor (i.e., common sub-expression) in p and q. + Then the gcd returned is n*e, cancelling which we would be left with + p1 + p2 and q0. + + Note that further factoring of p1 + p2 and q0 might be possible with + sympy.factor (which uses domain-specific theories). E.g., we are unable + to find that x*y + x + y + 1 is divisible by x + 1. More generally, + when q is of the form q1 + q2 (instead of being already factored) it + might be necessary to fall back on sympy.gcd. + """ + + def integer_coefficient(x: sympy.Basic) -> int: + integer_coefficients: list[int] = [ + abs(int(arg)) + for arg in sympy.Mul.make_args(x) + if isinstance(arg, (int, sympy.Integer)) + ] + return math.prod(integer_coefficients) + + def integer_factor(expr: sympy.Basic) -> int: + integer_factors: Iterable[int] = map( + integer_coefficient, sympy.Add.make_args(expr) + ) + return functools.reduce(math.gcd, integer_factors) + + gcd: int = math.gcd(integer_factor(p), integer_factor(q)) + p, q = p / gcd, q / gcd # type: ignore[operator, assignment] # remove in py3.12 + + base_splits: list[tuple[sympy.Basic, ...]] = list( + map(sympy.Mul.make_args, sympy.Add.make_args(p)) + ) + divisor_split: tuple[sympy.Basic, ...] = sympy.Mul.make_args(q) + for x in divisor_split: + if all(x in base_split for base_split in base_splits): + gcd = gcd * x # type: ignore[operator] # remove in py3.12 + return gcd # type: ignore[return-value] # remove in py3.12 + + +# It would be nice to have assertions on whether or not inputs is_integer +# However, with bugs like https://github.com/sympy/sympy/issues/26620 sympy +# sometimes inconsistently reports floats as integers. +# +# What we can assume from sympy is that if something is an int, it +# definitely is is_integer, but if it is a float it may or may not +# be is_integer. So we are unable to do strong asserts that things +# are NOT integers. + + +# TODO: In Triton, // rounds to zero, but in Python, it is floor division. +# When we can prove both arguments are non-negative, we should just have a +# GenericFloorDiv (name pending) which can codegen efficiently in Python/C, +# and then PythonFloorDiv and CIntDiv which have the appropriate rounding +# semantics. +# +# Right now, FloorDiv de facto changes behavior if arguments are negative or +# not, this can potentially cause correctness issues. +class FloorDiv(sympy.Function): + """ + We maintain this so that: + 1. We can use divisibility guards to simplify FloorDiv(a, b) to a / b. + 2. Printing out the expression is nicer (compared to say, representing a//b as (a - a % b) / b) + + NB: This is Python-style floor division, round to -Inf + """ + + nargs: tuple[int, ...] = (2,) + precedence: int = 35 # lower precedence than add + is_integer: bool = True + + @property + def base(self) -> sympy.Basic: + return self.args[0] + + @property + def divisor(self) -> sympy.Basic: + return self.args[1] + + def _sympystr(self, printer: sympy.printing.StrPrinter) -> str: + base = printer.parenthesize(self.base, PRECEDENCE["Atom"] - 0.5) + divisor = printer.parenthesize(self.divisor, PRECEDENCE["Atom"] - 0.5) + return f"({base}//{divisor})" + + # Automatic evaluation. + # https://docs.sympy.org/latest/guides/custom-functions.html#best-practices-for-eval + @classmethod + def eval(cls, base: sympy.Integer, divisor: sympy.Integer) -> sympy.Basic | None: + # python test/test_dynamic_shapes.py -k TestDimConstraints.test_dim_constraints_solve_full + # Assert triggered by inequality solver + # assert base.is_integer, base + # assert divisor.is_integer, divisor + + # We don't provide the same error message as in Python because SymPy + # makes it difficult to check the types. + if divisor.is_zero: + raise ZeroDivisionError("division by zero") + if is_infinite(base) and is_infinite(divisor): + return sympy.nan + if base is sympy.nan or divisor is sympy.nan: + return sympy.nan + + if base.is_zero: + return sympy.S.Zero + if base.is_integer and equal_valued(divisor, 1): + return base + if base.is_integer and equal_valued(divisor, -1): + return sympy.Mul(base, -1) + if base == divisor: + return sympy.S.One + + if ( + isinstance(base, sympy.Number) + and isinstance(divisor, sympy.Number) + and (is_infinite(base) or is_infinite(divisor)) + ): + r = float(base) / float(divisor) + if r == math.inf: + return int_oo + elif r == -math.inf: + return -int_oo + elif math.isnan(r): + return sympy.nan + else: + return sympy.Integer(math.floor(r)) + if isinstance(base, sympy.Integer) and isinstance(divisor, sympy.Integer): + return sympy.Integer(int(base) // int(divisor)) + if isinstance(base, FloorDiv): + return FloorDiv(base.args[0], base.args[1] * divisor) + + # Expands (x + y) // b into x // b + y // b. + # This only works if floor is an identity, i.e. x / b is an integer. + if isinstance(divisor, sympy.Integer): + quotients = 0 + terms: list[sympy.Expr] = [] + for term in sympy.Add.make_args(base): + quotient = term / divisor + + # This is a sympy bug fixed in https://github.com/sympy/sympy/pull/28442 + # sympy can generate a quotient with (1/22)*.... such that quotient.is_integer is True + # FloorDiv should not allow that as output. see + quotient_is_integer = None + if isinstance(quotient, sympy.Mul) and TorchVersion( + sympy.__version__ + ) < TorchVersion("1.15.0"): + rationals = quotient.atoms(sympy.Rational) + all_rationals_ints = all(r.q == 1 for r in rationals) + quotient_is_integer = quotient.is_integer and all_rationals_ints + else: + quotient_is_integer = quotient.is_integer + + if quotient_is_integer: + terms.append(term) + quotients += quotient + + if len(terms) != 0: + # Passing evaluate = False since expression will be optimized during the subtraction post its construction. + return ( + FloorDiv(base - sympy.Add(*terms, evaluate=False), divisor) + + quotients + ) + + try: + gcd = simple_floordiv_gcd(base, divisor) + if equal_valued(gcd, 1) and isinstance(divisor, sympy.Add): + gcd = safe_gcd(base, divisor) + if not equal_valued(gcd, 1): + return FloorDiv( + sympy.simplify(base / gcd), sympy.simplify(divisor / gcd) + ) + except sympy.PolynomialError: + pass # https://github.com/pytorch/pytorch/issues/108276 + + return None + + def _eval_is_nonnegative(self) -> bool | None: + p, q = self.args[:2] + if all([p.is_integer, q.is_integer, p.is_nonnegative, q.is_nonnegative]): + return True + return None + + +class ModularIndexing(sympy.Function): + """ + ModularIndexing(a, b, c) => (a // b) % c where % is the C modulus + """ + + nargs: tuple[int, ...] = (3,) + is_integer: bool = True + precedence: int = 35 # lower precedence than add + + @classmethod + def eval( + cls, base: sympy.Integer, divisor: sympy.Integer, modulus: sympy.Integer + ) -> sympy.Basic | None: + if base == 0 or modulus == 1: + return sympy.S.Zero + if ( + isinstance(base, sympy.Integer) + and isinstance(divisor, sympy.Integer) + and isinstance(modulus, sympy.Integer) + ): + return (base // divisor) % modulus + + try: + if divisor != 1: + gcd = safe_gcd(base, divisor) + if gcd != 1: + return ModularIndexing( + sympy.simplify(base / gcd), + sympy.simplify(divisor / gcd), + modulus, + ) + except sympy.PolynomialError: + pass # https://github.com/pytorch/pytorch/issues/108276 + + # Guard on width: the per-term gcd calls are cheap (via safe_gcd), + # but the result feeds into downstream sympy.expand() which blows up + # on wide Add expressions (e.g. in sizevars.simplify). + if isinstance(base, sympy.Add) and not _is_wide_add(base): + new_terms: list[sympy.Integer] = [] + all_nonnegative: bool = True + for term in base.args: + if safe_gcd(term, modulus * divisor) != modulus * divisor: + if term.is_nonnegative is not True: + # workaround for https://github.com/triton-lang/triton/issues/619, + # if terms are not provably nonnegative, // can produce + # the wrong result + # TODO if https://github.com/triton-lang/triton/issues/619 is fixed + # this optimization would become valid + all_nonnegative = False + break + else: + new_terms.append(term) + + if len(new_terms) != len(base.args) and all_nonnegative: + return ModularIndexing(sum(new_terms), divisor, modulus) + + if isinstance(base, FloorDiv): + return ModularIndexing(base.args[0], base.args[1] * divisor, modulus) + + return None + + def _eval_is_nonnegative(self) -> bool | None: + p, q = self.args[:2] + return fuzzy_eq(p.is_nonnegative, q.is_nonnegative) # type: ignore[attr-defined] + + +class Where(sympy.Function): + """ + Good ol' ternary operator + """ + + nargs: tuple[int, ...] = (3,) + precedence: int = 35 # lower precedence than add + + def _eval_is_integer(self) -> bool | None: + return True if self.args[1].is_integer and self.args[2].is_integer else None # type: ignore[attr-defined] + + def _eval_is_nonnegative(self) -> bool | None: + return ( + True + if self.args[1].is_nonnegative and self.args[2].is_nonnegative # type: ignore[attr-defined] + else None + ) + + def _eval_is_positive(self) -> bool | None: + return True if self.args[1].is_positive and self.args[2].is_positive else None # type: ignore[attr-defined] + + @classmethod + def eval(cls, c: sympy.Basic, p: sympy.Basic, q: sympy.Basic) -> sympy.Basic | None: + if c == sympy.true: + return p + elif c == sympy.false: + return q + return None + + +# Python-style modulus: take sign from RHS +class PythonMod(sympy.Function): + nargs: tuple[int, ...] = (2,) + + precedence: int = 35 # lower precedence than add + is_integer: bool = True + + @classmethod + def eval(cls, p: sympy.Expr, q: sympy.Expr) -> sympy.Expr | None: + # python test/dynamo/test_export.py -k ExportTests.test_trivial_constraint + # Triggered by sympy.solvers.inequalities.reduce_inequalities + # assert p.is_integer, p + # assert q.is_integer, q + + if q.is_zero: + raise ZeroDivisionError("Modulo by zero") + + # Three cases: + # 1. p == 0 + # 2. p is either q or -q + # 3. p is integer and q == 1 + if p is S.Zero or p in (q, -q) or q == 1: + return S.Zero + + # Evaluate if they are both literals. + if q.is_Number and p.is_Number: + return p % q + + # If q == 2, it's a matter of whether p is odd or even. + if q.is_Number and q == 2: + if p.is_even: + return S.Zero + if p.is_odd: + return S.One + + # If p is a multiple of q. + r = p / q + if r.is_integer: + return S.Zero + + # If p < q and its ratio is positive, then: + # - floor(p / q) = 0 + # - p % q = p - floor(p / q) * q = p + less = p < q + # pyrefly: ignore [missing-attribute] + if less.is_Boolean and bool(less) and r.is_positive: + return p + + if sympy.Mod(p, q) == 0: + return S.Zero + + return None + + # NB: args[1] for PythonMod + def _eval_is_nonnegative(self) -> bool | None: + return True if self.args[1].is_positive else None # type: ignore[attr-defined] + + def _eval_is_nonpositive(self) -> bool | None: + return True if self.args[1].is_negative else None # type: ignore[attr-defined] + + def _ccode(self, printer: sympy.printing.codeprinter.CodePrinter) -> str: + p = printer.parenthesize(self.args[0], PRECEDENCE["Atom"] - 0.5) + q = printer.parenthesize(self.args[1], PRECEDENCE["Atom"] - 0.5) + abs_q = str(q) if self.args[1].is_positive else f"abs({q})" + return f"({p} % {q}) < 0 ? {p} % {q} + {abs_q} : {p} % {q}" + + +# Generic modulus: only defined on non-negative arguments +class Mod(sympy.Function): + nargs = (2,) + precedence: int = 35 # lower precedence than add + + is_integer = True + is_nonnegative = True + + @classmethod + def eval(cls, p: sympy.Expr, q: sympy.Expr) -> sympy.Expr | None: + # This was adapted from: sympy/core/mod.py + + # Triggered by + # python test/test_dynamic_shapes.py -k TestDimConstraints.test_dim_constraints_solve_full + # assert p.is_integer, p + # assert q.is_integer, q + + if q.is_zero: + raise ZeroDivisionError("Modulo by zero") + + # Three cases: + # 1. p == 0 + # 2. p is either q or -q + # 3. p is integer and q == 1 + if p is S.Zero or p in (q, -q) or q == 1: + return S.Zero + + # Evaluate if they are both literals. + if q.is_Number and p.is_Number: + if p < 0: + raise AssertionError(p) + if q < 1: + raise AssertionError(q) + return p % q + + # If q == 2, it's a matter of whether p is odd or even. + if q.is_Number and q == 2: + if p.is_even: + return S.Zero + if p.is_odd: + return S.One + + # If p is a multiple of q. + r = p / q + if r.is_integer: + return S.Zero + + # If p < q and its ratio is positive, then: + # - floor(p / q) = 0 + # - p % q = p - floor(p / q) * q = p + less = p < q + if less.is_Boolean and bool(less) and r.is_positive: + return p + + +class CleanDiv(FloorDiv): + """ + Div where we can assume no rounding. + This is to enable future optimizations. + """ + + +# Don't use sympy ceiling/floor as they will attempt simplifications involving +# frac +class CeilToInt(sympy.Function): + is_integer = True + + @classmethod + def eval(cls, number: sympy.Expr) -> sympy.Basic | None: + # assert number.is_integer is not True, number + if number in (sympy.oo, int_oo): + return int_oo + if number in (-sympy.oo, -int_oo): + return -int_oo + if isinstance(number, sympy.Number): + return sympy.Integer(math.ceil(float(number))) + return None + + def _ccode(self, printer: sympy.printing.codeprinter.CodePrinter) -> str: + number = printer._print(self.args[0]) + return f"(int64_t)(ceil({number}))" + + +class FloorToInt(sympy.Function): + is_integer = True + + @classmethod + def eval(cls, number: sympy.Expr) -> sympy.Basic | None: + if number in (sympy.oo, int_oo): + return int_oo + if number in (-sympy.oo, -int_oo): + return -int_oo + if isinstance(number, sympy.Integer): + return number + if isinstance(number, sympy.Number): + return sympy.Integer(math.floor(float(number))) + return None + + def _ccode(self, printer: sympy.printing.codeprinter.CodePrinter) -> str: + number = printer._print(self.args[0]) + return f"(int64_t)(floor({number}))" + + +class CeilDiv(sympy.Function): + """ + Div used in indexing that rounds up. + """ + + is_integer = True + + def __new__(cls, base: sympy.Expr, divisor: sympy.Expr) -> sympy.Basic: + base = sympy.sympify(base) + divisor = sympy.sympify(divisor) + if sympy.gcd(base, divisor) == divisor: + return CleanDiv(base, divisor) + else: + return FloorDiv(base + (divisor - 1), divisor) + + +class LShift(sympy.Function): + is_integer = True + + @classmethod + def eval(cls, base: sympy.Expr, shift: sympy.Expr) -> sympy.Basic: + if shift.is_negative: + raise ValueError("negative shift count") + return base * PowByNatural(sympy.Integer(2), shift) + + +class RShift(sympy.Function): + is_integer = True + + @classmethod + def eval(cls, base: sympy.Expr, shift: sympy.Expr) -> sympy.Basic: + if shift.is_negative: + raise ValueError("negative shift count") + return FloorDiv(base, PowByNatural(sympy.Integer(2), shift)) + + +class MinMaxBase(Expr, LatticeOp): # type: ignore[misc] + def __new__(cls, *original_args: sympy.Expr, **assumptions: bool) -> sympy.Basic: + from sympy.core.parameters import global_parameters + + evaluate = assumptions.pop("evaluate", global_parameters.evaluate) + args = (sympify(arg) for arg in original_args) + + # See the comment in _satisfy_unique_summations_symbols. + unique_summations_symbols = ( + None + if not evaluate + else cls._satisfy_unique_summations_symbols(original_args) + ) + + if evaluate: + try: + # first standard filter, for cls.zero and cls.identity + # also reshape Max(a, Max(b, c)) to Max(a, b, c) + args = frozenset(cls._new_args_filter(args)) # type: ignore[assignment] + except ShortCircuit: + return cls.zero # type: ignore[attr-defined] + + # No need to run _collapse_arguments and _find_localzeros, see the comment + # in _satisfy_unique_summations_symbols. + if unique_summations_symbols is None: + # remove redundant args that are easily identified + args = cls._collapse_arguments(args, **assumptions) + + # find local zeros + args = cls._find_localzeros(args, **assumptions) + + args = frozenset(args) + + if not args: + return cls.identity # type: ignore[attr-defined] + + if len(args) == 1: + return list(args).pop() + + # base creation + obj = Expr.__new__(cls, *ordered(args), **assumptions) + obj._argset = args + + obj.unique_summations_symbols = unique_summations_symbols + return obj + + @classmethod + def _collapse_known_multiplicative_terms( + cls, values: set[sympy.Expr] + ) -> sympy.Expr | None: + if len(values) != 2: + return None + + a, b = values + a_coeff, a_term = a.as_coeff_Mul() + b_coeff, b_term = b.as_coeff_Mul() + if a_term != b_term: + return None + + if not (a_coeff.is_comparable and b_coeff.is_comparable): + return None + + if a_coeff == b_coeff: + return a + + if a_term.is_nonnegative: + a_is_smaller = a_coeff < b_coeff + elif a_term.is_nonpositive: + a_is_smaller = a_coeff > b_coeff + else: + return None + + if cls is Min: + return a if a_is_smaller else b + if cls is Max: + return b if a_is_smaller else a + + raise AssertionError(f"impossible {cls}") + + @classmethod + def _satisfy_unique_summations_symbols( + cls, args: "Sequence[sympy.Expr]" + ) -> set[sympy.core.symbol.Symbol] | None: + """ + One common case in some models is building expressions of the form + max(max(max(a+b...), c+d), e+f) which is simplified to max(a+b, c+d, e+f, ...). + For such expressions, we call the Max constructor X times (once for each nested + max) and the expression gets flattened. + + An expensive cost in constructing those expressions is running _collapse_arguments + and _find_localzeros. However, those two optimizations are unnecessary when the args + to max are all of the form a+b, c+d, ..etc where each term uses a unique set of symbols. + + This function is used to detect such properties of the expressions we are building + and if so inform that we do not need to run those optimizations. To detect those, + we store a property in the expression that tells that this expression is a min/max + operation over terms that use unique symbols "unique_summations_symbols". This property + also memoize the set of symbols used in all the terms to make it faster to detect this + property inductively. + + When we apply max to add a new term, all we need to do is check if the new term uses + unique symbols (with respect to existing terms and itself). + Example: + t = Max(a+b, c+d) ==> satisfies the property + Max(t, h+j) ==> h,j not in [a,b,c,d] => satisfy the property. + + The function returns None if the new expression does not satisfy the unique_summations_symbols + property. Otherwise, it returns a new set of unique symbols. + """ + if len(args) != 2: + return None + + (lhs, rhs) = ( + (args[1], args[0]) + if isinstance(args[1], MinMaxBase) + else (args[0], args[1]) + ) + + if not _is_symbols_binary_summation(rhs): + return None + + # base case max(a+b, c+d) ==> satisfies the property if a+b and c+d use unique symbols. + if _is_symbols_binary_summation(lhs): + return cls._unique_symbols(args) + + # inductive case max(t, h+j) ==> satisfies the property if h, j not in t.unique_summations_symbols + if isinstance(lhs, MinMaxBase): + lhs_unique_summations_symbols = getattr( + lhs, "unique_summations_symbols", None + ) + if lhs_unique_summations_symbols is not None: + return cls._unique_symbols([rhs], lhs_unique_summations_symbols) + + return None + + @classmethod + def _unique_symbols( + cls, + args: "Iterable[sympy.Expr]", + initial_set: set[sympy.core.symbol.Symbol] | None = None, + ) -> set[sympy.core.symbol.Symbol] | None: + """ + Return seen_symbols if all atoms in all args are all unique symbols, + else returns None. initial_set can be used to represent initial value for seen_symbols + """ + seen_symbols = set() if initial_set is None else initial_set.copy() + for arg in args: + for element in arg.atoms(): + if not isinstance(element, sympy.core.symbol.Symbol): + return None + elif element in seen_symbols: + return None + else: + seen_symbols.add(element) + return seen_symbols + + @classmethod + def _collapse_arguments( + cls, args: "Iterable[sympy.Expr]", **assumptions: bool + ) -> "Iterable[sympy.Expr]": + """Remove redundant args. + + Examples + ======== + + >>> from sympy import Min, Max + >>> from sympy.abc import a, b, c, d, e + + Any arg in parent that appears in any + parent-like function in any of the flat args + of parent can be removed from that sub-arg: + + >>> Min(a, Max(b, Min(a, c, d))) + Min(a, Max(b, Min(c, d))) + + If the arg of parent appears in an opposite-than parent + function in any of the flat args of parent that function + can be replaced with the arg: + + >>> Min(a, Max(b, Min(c, d, Max(a, e)))) + Min(a, Max(b, Min(a, c, d))) + """ + if not args: + return args + args = list(ordered(args)) + if cls is Min: + other = Max + else: + other = Min # type: ignore[assignment] + + # find global comparable max of Max and min of Min if a new + # value is being introduced in these args at position 0 of + # the ordered args + if args[0].is_number: + sifted = mins, maxs = [], [] # type: ignore[var-annotated] + for i in args: + for v in walk(i, Min, Max): + if v.args[0].is_comparable: + sifted[isinstance(v, Max)].append(v) + small = Min.identity + for i in mins: + v = i.args[0] + if v.is_number and (v < small) == True: # noqa: E712 + small = v + big = Max.identity + for i in maxs: + v = i.args[0] + if v.is_number and (v > big) == True: # noqa: E712 + big = v + # at the point when this function is called from __new__, + # there may be more than one numeric arg present since + # local zeros have not been handled yet, so look through + # more than the first arg + if cls is Min: + for arg in args: + if not arg.is_number: + break + if (arg < small) == True: # noqa: E712 + small = arg + elif cls == Max: + for arg in args: + if not arg.is_number: + break + if (arg > big) == True: # noqa: E712 + big = arg + T = None + if cls is Min: + if small != Min.identity: + other = Max + T = small + elif big != Max.identity: + other = Min # type: ignore[assignment] + T = big + if T is not None: + # remove numerical redundancy + for i in range(len(args)): + a = args[i] + if isinstance(a, other): + a0 = a.args[0] + if ( # noqa: E712 + (a0 > T) if other == Max else (a0 < T) + ) == True: + args[i] = cls.identity # type: ignore[attr-defined] + + # remove redundant symbolic args + def do(ai: sympy.Expr, a: sympy.Expr) -> sympy.Expr: + if not isinstance(ai, (Min, Max)): + return ai + cond = a in ai.args + if not cond: + return ai.func(*[do(i, a) for i in ai.args], evaluate=False) + if isinstance(ai, cls): + return ai.func(*[do(i, a) for i in ai.args if i != a], evaluate=False) + return a + + for i, a in enumerate(args): + args[i + 1 :] = [do(ai, a) for ai in args[i + 1 :]] + + # factor out common elements as for + # Min(Max(x, y), Max(x, z)) -> Max(x, Min(y, z)) + # and vice versa when swapping Min/Max -- do this only for the + # easy case where all functions contain something in common; + # trying to find some optimal subset of args to modify takes + # too long + + def factor_minmax(args: list[sympy.Expr]) -> list[sympy.Expr]: + is_other = lambda arg: isinstance(arg, other) # noqa: E731 + other_args, remaining_args = sift(args, is_other, binary=True) + if not other_args: + return args + + # Min(Max(x, y, z), Max(x, y, u, v)) -> {x,y}, ({z}, {u,v}) + arg_sets = [set(arg.args) for arg in other_args] + common = set.intersection(*arg_sets) + if not common: + return args + + new_other_args = list(common) + arg_sets_diff = [arg_set - common for arg_set in arg_sets] + + # If any set is empty after removing common then all can be + # discarded e.g. Min(Max(a, b, c), Max(a, b)) -> Max(a, b) + if all(arg_sets_diff): + other_args_diff = [other(*s, evaluate=False) for s in arg_sets_diff] + new_other_args.append(cls(*other_args_diff, evaluate=False)) + + other_args_factored = other(*new_other_args, evaluate=False) + return remaining_args + [other_args_factored] + + if len(args) > 1: + args = factor_minmax(args) + + return args + + @classmethod + def _new_args_filter( + cls, arg_sequence: "Iterable[sympy.Expr]" + ) -> "Iterator[sympy.Expr]": + """ + Generator filtering args. + + first standard filter, for cls.zero and cls.identity. + Also reshape ``Max(a, Max(b, c))`` to ``Max(a, b, c)``, + and check arguments for comparability + """ + for arg in arg_sequence: + # pre-filter, checking comparability of arguments + if ( + not isinstance(arg, Expr) + or arg.is_extended_real is False + or (arg.is_number and not arg.is_comparable) + ): + raise ValueError(f"The argument '{arg}' is not comparable.") + + if arg == cls.zero: # type: ignore[attr-defined] + raise ShortCircuit(arg) + elif arg == cls.identity: # type: ignore[attr-defined] + continue + elif arg.func == cls: + yield from arg.args + else: + yield arg + + @classmethod + def _find_localzeros( + cls, values: "Iterable[sympy.Expr]", **options: bool + ) -> set[sympy.Expr]: + """ + Sequentially allocate values to localzeros. + + When a value is identified as being more extreme than another member it + replaces that member; if this is never true, then the value is simply + appended to the localzeros. + + Unlike the sympy implementation, we only look for zero and one, we don't + do generic is connected test pairwise which is slow + """ + + # First, collapse all numeric arguments + other_values = set() + num_value = None + for arg in values: + if arg.is_Number: + if num_value is None: + num_value = arg + else: + if cls is Max: + num_value = max(num_value, arg) + elif cls is Min: + num_value = min(num_value, arg) + else: + raise AssertionError(f"impossible {cls}") + else: + other_values.add(arg) + + # Special cases when there is only one symbolic value + if num_value is None: + collapsed_value = cls._collapse_known_multiplicative_terms(other_values) + if collapsed_value is not None: + return {collapsed_value} + return other_values + + if len(other_values) == 0: + return {num_value} + + if len(other_values) == 1: + other_value = next(iter(other_values)) + if num_value in (0.0, 0) and other_value.is_nonnegative: + return other_values if cls is Max else {num_value} + if num_value == 1 and other_value.is_positive: + return other_values if cls is Max else {num_value} + + other_values.add(num_value) + return other_values + + _eval_is_algebraic = lambda s: _torf(i.is_algebraic for i in s.args) # noqa: E731 + _eval_is_antihermitian = lambda s: _torf( # noqa: E731 + i.is_antihermitian for i in s.args + ) + _eval_is_commutative = lambda s: _torf( # noqa: E731 + i.is_commutative for i in s.args + ) + _eval_is_complex = lambda s: _torf(i.is_complex for i in s.args) # noqa: E731 + _eval_is_composite = lambda s: _torf(i.is_composite for i in s.args) # noqa: E731 + _eval_is_even = lambda s: _torf(i.is_even for i in s.args) # noqa: E731 + _eval_is_finite = lambda s: _torf(i.is_finite for i in s.args) # noqa: E731 + _eval_is_hermitian = lambda s: _torf(i.is_hermitian for i in s.args) # noqa: E731 + _eval_is_imaginary = lambda s: _torf(i.is_imaginary for i in s.args) # noqa: E731 + _eval_is_infinite = lambda s: _torf(i.is_infinite for i in s.args) # noqa: E731 + _eval_is_integer = lambda s: _torf(i.is_integer for i in s.args) # noqa: E731 + _eval_is_irrational = lambda s: _torf(i.is_irrational for i in s.args) # noqa: E731 + _eval_is_negative = lambda s: _torf(i.is_negative for i in s.args) # noqa: E731 + _eval_is_noninteger = lambda s: _torf(i.is_noninteger for i in s.args) # noqa: E731 + _eval_is_nonnegative = lambda s: _torf( # noqa: E731 + i.is_nonnegative for i in s.args + ) + _eval_is_nonpositive = lambda s: _torf( # noqa: E731 + i.is_nonpositive for i in s.args + ) + _eval_is_nonzero = lambda s: _torf(i.is_nonzero for i in s.args) # noqa: E731 + _eval_is_odd = lambda s: _torf(i.is_odd for i in s.args) # noqa: E731 + _eval_is_polar = lambda s: _torf(i.is_polar for i in s.args) # noqa: E731 + _eval_is_positive = lambda s: _torf(i.is_positive for i in s.args) # noqa: E731 + _eval_is_prime = lambda s: _torf(i.is_prime for i in s.args) # noqa: E731 + _eval_is_rational = lambda s: _torf(i.is_rational for i in s.args) # noqa: E731 + _eval_is_real = lambda s: _torf(i.is_real for i in s.args) # noqa: E731 + _eval_is_extended_real = lambda s: _torf( # noqa: E731 + i.is_extended_real for i in s.args + ) + _eval_is_transcendental = lambda s: _torf( # noqa: E731 + i.is_transcendental for i in s.args + ) + _eval_is_zero = lambda s: _torf(i.is_zero for i in s.args) # noqa: E731 + + +class Max(MinMaxBase, Application): # type: ignore[misc] + r""" + Return, if possible, the maximum value of the list. + """ + + zero = S.Infinity + identity = S.NegativeInfinity + + def _eval_is_positive(self): # type:ignore[override] + return fuzzy_or(a.is_positive for a in self.args) # type: ignore[attr-defined] + + def _eval_is_nonnegative(self): # type:ignore[override] + return fuzzy_or(a.is_nonnegative for a in self.args) # type: ignore[attr-defined] + + def _eval_is_negative(self): # type:ignore[override] + return fuzzy_and(a.is_negative for a in self.args) + + +class Min(MinMaxBase, Application): # type: ignore[misc] + """ + Return, if possible, the minimum value of the list. + """ + + zero = S.NegativeInfinity + identity = S.Infinity + + def _eval_is_positive(self): # type:ignore[override] + return fuzzy_and(a.is_positive for a in self.args) # type: ignore[attr-defined] + + def _eval_is_nonnegative(self): # type:ignore[override] + return fuzzy_and(a.is_nonnegative for a in self.args) # type: ignore[attr-defined] + + def _eval_is_negative(self): # type:ignore[override] + return fuzzy_or(a.is_negative for a in self.args) + + +def safe_pow(base: sympy.Integer, exp: sympy.Integer) -> int | IntInfinity: + sign = 1 + if base < 0: + base = -base + sign = 1 if exp % 2 == 0 else -1 + return sign * _safe_pow(base, exp) + + +# Prevent people from overflowing pow +def _safe_pow(base: sympy.Integer, exponent: sympy.Integer) -> int | IntInfinity: + if exponent < 0: + raise ValueError("Exponent must be non-negative.") + + if exponent == 0: + return 1 + + half_exp = safe_pow(base, exponent // 2) + if half_exp is int_oo: + return int_oo + + # TODO: microoptimization is to avoid overflowing into arbitrary precision + # and detect overflow prior to doing operations + + result = half_exp * half_exp + if result > sys.maxsize: + return int_oo + + if exponent % 2 == 1: + result *= base + if result > sys.maxsize: + return int_oo + + return result + + +class PowByNatural(sympy.Function): + is_integer = True + + precedence: int = 50 # precedence of mul + + @classmethod + def eval(cls, base: sympy.Expr, exp: sympy.Expr) -> sympy.Basic | None: + if isinstance(base, sympy.Integer) and isinstance(exp, sympy.Integer): + r = safe_pow(base, exp) + if r in (-int_oo, int_oo): + return r + return sympy.Integer(r) + if isinstance(exp, sympy.Integer): + # Rely on regular sympy Pow for this (note that iterated + # multiplication turns into a Pow anyway, you can't escape!!) + return sympy.Pow(base, exp) + if exp in (int_oo, sympy.oo): + if base.is_nonnegative: + return int_oo + elif base.is_negative: + return sympy.zoo # this is apparently what (-2)**sympy.oo does + # NB: do NOT translate into sympy.Pow, we will lose knowledge that exp + # is a natural number if we do + return None + + +# base is assumed to be nonnegative, thereby prevent complex numbers from +# occurring +class FloatPow(sympy.Function): + is_real = True + + precedence: int = 60 # precedence of pow + + @classmethod + def eval(cls, base: sympy.Expr, exp: sympy.Expr) -> sympy.Basic | None: + # NB: These test sympy.Number, not sympy.Float, because: + # - Sometimes we may have sympy.oo or int_oo, and that's not a Float + # (but coerces to math.Inf) + # - Sometimes Float(0.0) will unpredictably decay to Integer(0), + # but we should still accept it in floatey contexts + if isinstance(base, sympy.Number) and isinstance(exp, sympy.Number): + return sympy.Float(float(base) ** float(exp)) + # NB: do not do any nontrivial reasoning + return None + + +# Overloaded to be compatible with regular Python. +# https://github.com/pytorch/pytorch/issues/90900 +# +# In particular, sympy division is willing to simplify x/x == 1 +# where 1 is an integer, but this must be a float if x was float. +class FloatTrueDiv(sympy.Function): + is_real = True + + precedence: int = 35 # lower precedence than add + + @classmethod + def eval(cls, base: sympy.Expr, divisor: sympy.Expr) -> sympy.Basic | None: + # assert base.is_integer is not True, base + # assert divisor.is_integer is not True, divisor + + if divisor.is_zero: + raise ZeroDivisionError("division by zero") + + if isinstance(base, sympy.Number) and isinstance(divisor, sympy.Number): + return sympy.Float(float(base) / float(divisor)) + return None + + +# Overloaded to be compatible with regular Python. We distinguish this from +# FloatTrueDiv, because the code generation has to be different for this case: +# Python has a fancy algorithm for integer true division that isn't just +# "promote both arguments to float and use float division", so you need to +# codegen it differently. While technically you can work it out from the +# types of the input, this is often inconvenient to do in Inductor codegen, +# so just have a different operator +# NB: Right now, Inductor codegen doesn't implement this correctly lol +class IntTrueDiv(sympy.Function): + is_real = True + + precedence: int = 35 # lower precedence than add + + @classmethod + def eval(cls, base: sympy.Expr, divisor: sympy.Expr) -> sympy.Basic | None: + if divisor.is_zero: + raise ZeroDivisionError("division by zero") + + if ( + isinstance(base, sympy.Number) + and isinstance(divisor, sympy.Number) + and (is_infinite(base) or is_infinite(divisor)) + ): + # Don't have to worry about precision here, you're getting zero or + # inf from the division + return sympy.Float(float(base) / float(divisor)) + if isinstance(base, sympy.Integer) and isinstance(divisor, sympy.Integer): + return sympy.Float(int(base) / int(divisor)) + return None + + def _ccode(self, printer: sympy.printing.codeprinter.CodePrinter) -> str: + base = printer.parenthesize(self.args[0], PRECEDENCE["Atom"] - 0.5) + divisor = printer.parenthesize(self.args[1], PRECEDENCE["Atom"] - 0.5) + return f"((int){base}/(int){divisor})" + + +# TODO: As an indicator, this != 0 implies == 1 (and vice versa). +# Because we do not have the ability to guard on the stride permutation +# at the moment, it is hard to make further inferences when this is true, +# as although we know the tensor is contiguous in *some* layout, we don't +# know which one (however, you could, for example, make the inference that +# reshaping this to a 1D tensor can be guard-free.) +class IsNonOverlappingAndDenseIndicator(sympy.Function): + is_integer = True + + @classmethod + def eval(cls, *args: sympy.Expr) -> int | None: + if len(args) % 2 != 0: + raise AssertionError( + f"expected an even number of arguments, got {len(args)}" + ) + dim = len(args) // 2 + sizes = args[0:dim] + strides = args[dim:] + + # sym_node imported in torch.__init__. Local import to avoid an import cycle + from torch.fx.experimental.symbolic_shapes import ( + eval_is_non_overlapping_and_dense, + ) + + if all(isinstance(a, sympy.Integer) for a in args): + return eval_is_non_overlapping_and_dense( + [int(a) for a in sizes], [int(a) for a in strides] + ) + + if dim == 1: + # Manually implement the rank one short circuit + if strides[0].is_Number and strides[0] == 1: + return 1 + + if sizes[0].is_Number and sizes[0] < 2: + return 1 + + # return 0 case covered by case above + + # TODO: Inability to access size-obliviousness sucks: if we have a + # size oblivious test on a size-like unbacked SymInt, we could + # confidently return zero when we have a size-like u0 stride + # and a size-like u1 size. Maybe a fancy ValueRanges analysis for + # this function could help figure this out. + + if all(isinstance(a, sympy.Integer) for a in strides): + if dim == 0: + raise AssertionError("dim must not be zero") + # When all strides are integral, we can sort, and the size for the + # largest stride doesn't matter and can be arbitrarily symbolic + s_sizes, s_strides = zip( + *sorted(zip(sizes, strides, strict=True), key=operator.itemgetter(1)), + strict=True, + ) + # Put something arbitrary in the max size spot, it'll be ignored + if all(isinstance(a, sympy.Integer) for a in s_sizes[:-1]): + s_sizes = s_sizes[:-1] + (42,) + # We can reuse the regular eval, because it is invariant to + # permutation of dimensions + return eval_is_non_overlapping_and_dense( + [int(a) for a in s_sizes], [int(a) for a in s_strides] + ) + + return None + + +# NB: this is inconsistent with math.trunc in Python +class TruncToFloat(sympy.Function): + is_real = True + + @classmethod + def eval(cls, number: sympy.Expr) -> sympy.Basic | None: + if number in (sympy.oo, -sympy.oo): + return number + # assert number.is_integer is not True, number + if isinstance(number, sympy.Number): + # NB: It is safe to use truncation to integer, which is what + # math.trunc does, as Python integers are arbitrary precision and + # so we are guaranteed not to lose precision when we do this + return sympy.Float(math.trunc(float(number))) + return None + + +class TruncToInt(sympy.Function): + is_integer = True + + @classmethod + def eval(cls, number: sympy.Expr) -> sympy.Basic | None: + # assert number.is_integer is not True, number + if number in (sympy.oo, int_oo): + return int_oo + if number in (-sympy.oo, -int_oo): + return -int_oo + if isinstance(number, sympy.Number): + return sympy.Integer(math.trunc(float(number))) + return None + + def _ccode(self, printer: sympy.printing.codeprinter.CodePrinter) -> str: + number = printer._print(self.args[0]) + return f"(int64_t)(trunc({number}))" + + +# This is float -> int +class RoundToInt(sympy.Function): + is_integer = True + + @classmethod + def eval(cls, number: sympy.Expr) -> sympy.Basic | None: + # assert number.is_integer is not True, number + + if number is sympy.oo: + return int_oo + if number is -sympy.oo: + return -int_oo + if isinstance(number, sympy.Number): + return sympy.Integer(round(float(number), 0)) + return None + + +# To get float -> int, Python style round semantics. +# +# x = PyFloat_AsDouble(self); +# if (o_ndigits == Py_None) { +# /* single-argument round or with None ndigits: +# * round to nearest integer */ +# rounded = round(x); +# if (fabs(x-rounded) == 0.5) +# /* halfway case: round to even */ +# rounded = 2.0*round(x/2.0); +# return PyLong_FromDouble(rounded); +# } + + +# NB: Like Round, this only ever returns floats. ndigits cannot be None +class RoundDecimal(sympy.Function): + is_real = True + + @classmethod + def eval(cls, number: sympy.Expr, ndigits: sympy.Expr) -> sympy.Basic | None: + # assert number.is_integer is not True, number + + if isinstance(number, sympy.Number) and isinstance(ndigits, sympy.Integer): + return sympy.Float(round(float(number), int(ndigits))) + return None + + +class ToFloat(sympy.Function): + is_real = True + + @classmethod + def eval(cls, number: sympy.Expr) -> sympy.Basic | None: + if number in [sympy.oo, -sympy.oo]: + return number + + if isinstance(number, sympy.Integer): + return sympy.Float(int(number)) + if number is int_oo: + return sympy.oo + if number is -int_oo: + return -sympy.oo + return None + + def _ccode(self, printer: sympy.printing.codeprinter.CodePrinter) -> str: + number = printer._print(self.args[0]) + return f"(double)({number})" + + +class Identity(sympy.Function): + """ + Prevents expansion and other optimizations + """ + + precedence = 10 + + def __repr__(self) -> str: # type: ignore[override] + return f"Identity({self.args[0]})" + + def _sympystr(self, printer: sympy.printing.StrPrinter) -> str: + """Controls how sympy's StrPrinter prints this""" + return f"({printer.doprint(self.args[0])})" + + def _eval_is_real(self) -> bool | None: + return self.args[0].is_real + + def _eval_is_integer(self) -> bool | None: + return self.args[0].is_integer # type: ignore[attr-defined] + + @property + def is_number(self) -> bool: + # Treat Identity as numeric only when the argument is comparable. + # This avoids creating numeric non-comparable Identity(I) terms. + return bool(self.args[0].is_number and self.args[0].is_comparable) + + @property + def is_comparable(self) -> bool: + # Delegate comparability to the wrapped argument. + return bool(self.args[0].is_comparable) + + def _eval_expand_identity(self, **hints: bool) -> sympy.Expr: + # Removes the identity op. + return self.args[0] + + def __int__(self) -> int: + return int(self.args[0]) + + def _identity_atom_compare( + self, other: sympy.Expr | int, op: Callable[[sympy.Expr, sympy.Expr], bool] + ) -> sympy.logic.boolalg.BooleanAtom | None: + """ + Fast path for comparing wrapped numeric atomics against other numeric atomics. + Keep compound expressions on SymPy's default symbolic path. + """ + arg = self.args[0] + if isinstance(other, int): + other = sympy.Integer(other) + if not isinstance(other, sympy.Expr): + return None + if not (arg.is_Atom and arg.is_number and arg.is_comparable): + return None + if not (other.is_Atom and other.is_number and other.is_comparable): + return None + return sympy.S.true if op(arg, other) else sympy.S.false + + def __ge__(self, other: sympy.Expr) -> sympy.Basic: + out = self._identity_atom_compare(other, lambda a, b: a >= b) + return out if out is not None else super().__ge__(other) + + def __gt__(self, other: sympy.Expr) -> sympy.Basic: + out = self._identity_atom_compare(other, lambda a, b: a > b) + return out if out is not None else super().__gt__(other) + + def __le__(self, other: sympy.Expr) -> sympy.Basic: + out = self._identity_atom_compare(other, lambda a, b: a <= b) + return out if out is not None else super().__le__(other) + + def __lt__(self, other: sympy.Expr) -> sympy.Basic: + out = self._identity_atom_compare(other, lambda a, b: a < b) + return out if out is not None else super().__lt__(other) + + def __float__(self) -> float: + return float(self.args[0]) + + +def make_opaque_unary_fn(name: str) -> type[sympy.Function]: + class OpaqueUnaryFn(sympy.Function): + """ + Unlike the builtin sympy functions on real numbers like sympy.sqrt, + these equivalents do not do any nontrivial reasoning besides + constant propagation. This helps avoid performing transformations + that are valid for real numbers but are invalid for floating point; + in particular, while we are willing to make optimizations that change + numerics for Tensor compute, we are NOT willing to make optimizations + that change numerics for size compute. + """ + + _torch_handler_name = name + _torch_unpickler = make_opaque_unary_fn + + @classmethod + def eval(cls, a: sympy.Expr) -> sympy.Basic | None: + if isinstance(a, (sympy.Integer, sympy.Float)): + # Python converts to float64 before computing, c.f. + # >>> math.sin(2**53+1) + # -0.848925964814655 + # >>> math.sin(float(2**53+1)) + # -0.848925964814655 + try: + return sympy.Float(getattr(math, name)(float(a))) + # Just use sympy semantics for infinity/overflow, you might get some + # weird objects but ask silly questions, get silly answers + except OverflowError: + return getattr(sympy, name)(a) + elif a in [sympy.oo, -sympy.oo, sympy.zoo, -sympy.zoo, int_oo, -int_oo]: + if a is int_oo: + a = sympy.oo + if a is -int_oo: + a = -sympy.oo + if name == "log2": + return sympy.log(a, 2) + return getattr(sympy, name)(a) + return None + + nm = "OpaqueUnaryFn_" + name + OpaqueUnaryFn.__name__ = nm + OpaqueUnaryFn.__qualname__ = nm + + return OpaqueUnaryFn + + +# Keep in sync with math_op_names in torch/fx/experimental/sym_node.py +OpaqueUnaryFn_sqrt = make_opaque_unary_fn("sqrt") +OpaqueUnaryFn_cos = make_opaque_unary_fn("cos") +OpaqueUnaryFn_cosh = make_opaque_unary_fn("cosh") +OpaqueUnaryFn_sin = make_opaque_unary_fn("sin") +OpaqueUnaryFn_sinh = make_opaque_unary_fn("sinh") +OpaqueUnaryFn_tan = make_opaque_unary_fn("tan") +OpaqueUnaryFn_tanh = make_opaque_unary_fn("tanh") +OpaqueUnaryFn_asin = make_opaque_unary_fn("asin") +OpaqueUnaryFn_acos = make_opaque_unary_fn("acos") +OpaqueUnaryFn_atan = make_opaque_unary_fn("atan") +OpaqueUnaryFn_exp = make_opaque_unary_fn("exp") +OpaqueUnaryFn_log = make_opaque_unary_fn("log") +OpaqueUnaryFn_asinh = make_opaque_unary_fn("asinh") +OpaqueUnaryFn_log2 = make_opaque_unary_fn("log2") + + +def make_opaque_bitwise_fn(name: str, real_op_name: str) -> type[sympy.Function]: + if name == "bitwise_and": + prec = PRECEDENCE["BitwiseAnd"] + elif name == "bitwise_xor": + prec = PRECEDENCE["BitwiseXor"] + elif name == "bitwise_or": + prec = PRECEDENCE["BitwiseOr"] + else: + raise AssertionError(f"unrecognized {name}") + + class BitwiseFn(sympy.Function): + _torch_handler_name = name + precedence: int = prec + _torch_unpickler = functools.partial( + make_opaque_bitwise_fn, real_op_name=real_op_name + ) + + @classmethod + def eval(cls, a: sympy.Expr, b: sympy.Expr) -> sympy.Basic | None: + if a.is_Boolean and b.is_Boolean: + return getattr(operator, real_op_name)(a, b) + if a.is_Boolean: + a = sympy.Integer(1 if a else 0) + if b.is_Boolean: + b = sympy.Integer(1 if b else 0) + if isinstance(a, (sympy.Integer, int)) and isinstance( + b, (sympy.Integer, int) + ): + return sympy.Integer(getattr(operator, real_op_name)(int(a), int(b))) + return None + + nm = "BitwiseFn_" + name + BitwiseFn.__name__ = nm + BitwiseFn.__qualname__ = nm + + return BitwiseFn + + +BitwiseFn_bitwise_and = make_opaque_bitwise_fn("bitwise_and", "and_") +BitwiseFn_bitwise_or = make_opaque_bitwise_fn("bitwise_or", "or_") +BitwiseFn_bitwise_xor = make_opaque_bitwise_fn("bitwise_xor", "xor") diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/interp.py b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/interp.py new file mode 100644 index 0000000000000000000000000000000000000000..f0640e45ca11975a08a31d38747f3b2ee4dc7c0a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/interp.py @@ -0,0 +1,239 @@ +""" +This is a simple interpreter for Sympy expressions that dispatches to +classes following the torch._inductor.virtualized calling convention. +For directness, the interpreter takes the handler directly rather than +consulting the TLS. It does not use most of the methods on the full +handler; only those with corresponding Sympy expressions. To see an example +of a full handler, see torch.utils._sympy.value_ranges.ValueRangeAnalysis. +""" + +import functools +import logging +from collections.abc import Callable +from typing import Any + +import sympy +from sympy.logic.boolalg import Boolean as SympyBoolean, BooleanAtom + +import torch + +from .functions import ( + BitwiseFn_bitwise_and, + BitwiseFn_bitwise_or, + BitwiseFn_bitwise_xor, + CeilToInt, + CleanDiv, + FloatPow, + FloatTrueDiv, + FloorDiv, + FloorToInt, + Identity, + IntTrueDiv, + IsNonOverlappingAndDenseIndicator, + Max, + Min, + Mod, + ModularIndexing, + OpaqueUnaryFn_log2, + PowByNatural, + PythonMod, + RoundDecimal, + RoundToInt, + ToFloat, + TruncToFloat, + TruncToInt, + Where, +) + + +log = logging.getLogger(__name__) + + +# TODO: Dedupe this with SYMPY_INTERP + + +@functools.cache +def handlers() -> dict[type[sympy.Basic], str]: + # TODO add CeilDiv (it doesn't appear in the index_expr) + + # TODO default to some decompositions if the interpreter doesn't have them + # like decomposing ModularIndexing or implementing Le(a,b) as Ge(b, a) + + HANDLERS = { + sympy.Or: "or_", + sympy.And: "and_", + sympy.Eq: "eq", + sympy.Ne: "ne", + sympy.Lt: "lt", + sympy.Gt: "gt", + sympy.Le: "le", + sympy.Ge: "ge", + sympy.Not: "not_", + IntTrueDiv: "int_truediv", + FloatTrueDiv: "truediv", + FloorDiv: "floordiv", + CleanDiv: "floordiv", # TODO: hmm? + TruncToFloat: "trunc", + Where: "where", + sympy.Add: "add", + sympy.Mul: "mul", + FloatPow: "pow", + PowByNatural: "pow_by_natural", + # sympy simplifies x * x into Pow(x, 2), so we need to handle this. + # Do NOT use builtin Pow for floats + # TODO: There is a hazard here, if we have float * float it will + # also get turned into Pow(float, 2) but we don't want this because + # pow_by_natural is assumed to only be integers. Probably the fix is + # to add a FloatMul to impede this optimization + sympy.Pow: "pow_by_natural", + Mod: "mod", + PythonMod: "python_mod", + # TODO: Inductor can generate these, but it's ill-specified which + # semantics were intended here. Needs to be cleaned up along with + # FloorDiv in a bigger cleanup + sympy.Mod: "mod", + sympy.Abs: "abs", + sympy.log: "log", + sympy.exp: "exp", + sympy.Min: "minimum", + sympy.Max: "maximum", + Min: "minimum", + Max: "maximum", + ModularIndexing: "modular_indexing", + sympy.functions.elementary.piecewise.ExprCondPair: "expr_cond_pair", + sympy.Piecewise: "piecewise", + Identity: "identity", + IsNonOverlappingAndDenseIndicator: "is_non_overlapping_and_dense_indicator", + RoundDecimal: "round_decimal", + # TODO: do the rest of the opaque unary functions... + OpaqueUnaryFn_log2: "log2", + BitwiseFn_bitwise_and: "bitwise_and", + BitwiseFn_bitwise_or: "bitwise_or", + BitwiseFn_bitwise_xor: "bitwise_xor", + } + # TODO: This is kind of pointless, we shouldn't be generating sympy.sin + # for these functions, they should be Opaque instead + for name in ["cos", "sin", "tan", "sinh", "cosh", "tanh", "asin", "acos", "atan"]: + HANDLERS[getattr(sympy, name)] = name + + return HANDLERS + + +ASSOCIATIVE_OPS = {"minimum", "maximum", "mul", "add", "and_", "or_"} + + +def _run_sympy_handler( + analysis: Any, + args: list[Any], + expr: sympy.Basic, + index_dtype: torch.dtype = torch.int64, +) -> Any: + # Special cases + if isinstance(expr, sympy.Pow) and isinstance( + expr.args[1], sympy.core.numbers.Half + ): + return analysis.sqrt(args[0]) + if isinstance(expr, ToFloat): + return analysis.to_dtype(args[0], torch.float64) + + # These handlers are special because they take an extra dtype argument + # specifying what they should convert to, and we need to appropriately set + # this up when we convert from Sympy. A reasonable default when you + # are translating is to conservatively do int64, and then narrow these + # arguments later when you discover you can narrow the index range. But + # if you already know that 32-bit indexing is OK, you can directly do the + # sympy translation with index_dtype=torch.int32 + INDEX_DTYPE_HANDLERS = { + TruncToInt: "trunc_to_int", + sympy.floor: "floor_to_int", + sympy.ceiling: "ceil_to_int", + FloorToInt: "floor_to_int", + CeilToInt: "ceil_to_int", + RoundToInt: "round_to_int", + } + if (handler_name := INDEX_DTYPE_HANDLERS.get(expr.func)) is not None: + return getattr(analysis, handler_name)(*args, index_dtype) + + # Fastpath for n-ary integral addition + if expr.func is sympy.Add and expr.is_integer and hasattr(analysis, "sym_sum"): + r = analysis.sym_sum(args) + log.debug("sym_sum(%s) -> %s", args, r) + return r + + if expr.func is sympy.Pow: + exp = expr.args[1] + if exp.is_integer and exp.is_nonnegative: + handler_name = "pow_by_natural" + else: + handler_name = "pow" + elif hasattr(expr.func, "_torch_handler_name"): + handler_name = expr.func._torch_handler_name + else: + handler_name = handlers()[expr.func] + handler = getattr(analysis, handler_name) + try: + if handler_name in ASSOCIATIVE_OPS: + if len(args) <= 1: + raise AssertionError("associative op needs >1 args") + acc = handler(args[0], args[1]) + for i in range(2, len(args)): + acc = handler(acc, args[i]) + log.debug("%s(%s) -> %s", handler_name, args, acc) + return acc + else: + r = handler(*args) + log.debug("%s(%s) -> %s", handler_name, args, r) + return r + except NotImplementedError: + raise + except Exception: + log.warning("failed while executing %s(%s)", handler_name, args) + raise + + +_nil = object() + + +def sympy_interp( + analysis: Any, + env: dict[sympy.Symbol, Any], + expr: sympy.Expr | SympyBoolean, + *, + index_dtype: torch.dtype = torch.int64, + missing_handler: Callable[[sympy.Symbol], object] | None = None, +) -> Any: + # Handle base cases + dtype = None + if isinstance(expr, BooleanAtom): + dtype = torch.bool + elif isinstance(expr, sympy.Integer): + dtype = torch.int64 + elif isinstance(expr, sympy.Number): + dtype = torch.double + + if dtype is not None: + return analysis.constant(expr, dtype) + elif isinstance(expr, sympy.Symbol): + if (r := env.get(expr, _nil)) is not _nil: + return r + elif missing_handler: + return missing_handler(expr) + else: + raise KeyError(expr) + + # Recursive case + return _run_sympy_handler( + analysis, + [ + sympy_interp( + analysis, + env, + arg, + index_dtype=index_dtype, + missing_handler=missing_handler, + ) + for arg in expr.args + ], + expr, + index_dtype=index_dtype, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/numbers.py b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/numbers.py new file mode 100644 index 0000000000000000000000000000000000000000..0f1d1f3870d33004bad37eb24698e138b547e65e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/numbers.py @@ -0,0 +1,422 @@ +from typing import Any + +import mpmath.libmp as mlib # type: ignore[import-untyped] +import sympy +from sympy import Expr +from sympy.core.decorators import _sympifyit +from sympy.core.expr import AtomicExpr +from sympy.core.numbers import Number +from sympy.core.parameters import global_parameters +from sympy.core.singleton import S, Singleton + + +# pyrefly: ignore [invalid-inheritance] +class IntInfinity(Number, metaclass=Singleton): + r"""Positive integer infinite quantity. + + Integer infinity is a value in an extended integers which + is greater than all other integers. We distinguish it from + sympy's existing notion of infinity in that it reports that + it is_integer. + + Infinity is a singleton, and can be accessed by ``S.IntInfinity``, + or can be imported as ``int_oo``. + """ + + # NB: We can't actually mark this as infinite, as integer and infinite are + # inconsistent assumptions in sympy. We also report that we are complex, + # different from sympy.oo + + is_integer = True + is_commutative = True + is_number = True + is_extended_real = True + is_comparable = True + is_extended_positive = True + is_prime = False + + # Ensure we get dispatched to before plain numbers + _op_priority = 100.0 + + __slots__: tuple[str, ...] = () + + def __new__(cls) -> "IntInfinity": + return AtomicExpr.__new__(cls) + + def _sympystr(self, printer: Any) -> str: + return "int_oo" + + def _eval_subs(self, old: sympy.Basic, new: sympy.Basic) -> sympy.Basic | None: + if self == old: + return new + return None + + # We could do these, not sure about it + """ + def _eval_evalf(self, prec=None): + return Float('inf') + + def evalf(self, prec=None, **options): + return self._eval_evalf(prec) + """ + + @_sympifyit("other", NotImplemented) + def __add__(self, other: sympy.Expr) -> sympy.Expr: + if isinstance(other, Number) and global_parameters.evaluate: + if other in (S.Infinity, S.NegativeInfinity): + return other + if other in (S.NegativeIntInfinity, S.NaN): + return S.NaN + return self + return Number.__add__(self, other) + + __radd__ = __add__ + + @_sympifyit("other", NotImplemented) + def __sub__(self, other: sympy.Expr) -> sympy.Expr: + if isinstance(other, Number) and global_parameters.evaluate: + if other is S.Infinity: + return S.NegativeInfinity + if other is S.NegativeInfinity: + return S.Infinity + if other in (S.IntInfinity, S.NaN): + return S.NaN + return self + return Number.__sub__(self, other) + + @_sympifyit("other", NotImplemented) + def __rsub__(self, other: sympy.Expr) -> sympy.Expr: + return (-self).__add__(other) + + @_sympifyit("other", NotImplemented) + def __mul__(self, other: sympy.Expr) -> sympy.Expr: + if isinstance(other, Number) and global_parameters.evaluate: + if other.is_zero or other is S.NaN: + return S.NaN + if other.is_extended_positive: + return self + return S.NegativeIntInfinity + return Number.__mul__(self, other) + + __rmul__ = __mul__ + + @_sympifyit("other", NotImplemented) + def __truediv__(self, other: sympy.Expr) -> sympy.Expr: + if isinstance(other, Number) and global_parameters.evaluate: + if other in ( + S.Infinity, + S.IntInfinity, + S.NegativeInfinity, + S.NegativeIntInfinity, + S.NaN, + ): + return S.NaN + if other.is_extended_nonnegative: + return S.Infinity # truediv produces float + return S.NegativeInfinity # truediv produces float + return Number.__truediv__(self, other) + + def __abs__(self) -> sympy.Expr: + return S.IntInfinity + + def __neg__(self) -> sympy.Expr: + return S.NegativeIntInfinity + + def _eval_power(self, expt: sympy.Expr) -> sympy.Expr | None: + if expt.is_extended_positive: + return S.IntInfinity + if expt.is_extended_negative: + return S.Zero + if expt is S.NaN: + return S.NaN + if expt is S.ComplexInfinity: + return S.NaN + if expt.is_extended_real is False and expt.is_number: + from sympy.functions.elementary.complexes import re + + expt_real = re(expt) + if expt_real.is_positive: + return S.ComplexInfinity + if expt_real.is_negative: + return S.Zero + if expt_real.is_zero: + return S.NaN + + return self ** expt.evalf() + return None + + def _as_mpf_val(self, prec: int) -> Any: + return mlib.finf + + def __hash__(self) -> int: + return super().__hash__() + + def __eq__(self, other: object) -> bool: + return other is S.IntInfinity + + def __ne__(self, other: object) -> bool: + return other is not S.IntInfinity + + def __gt__(self, other: sympy.Expr) -> sympy.logic.boolalg.BooleanAtom: + if other is S.Infinity: + return sympy.false # sympy.oo > int_oo + elif other is S.IntInfinity: + return sympy.false # consistency with sympy.oo + else: + return sympy.true + + def __ge__(self, other: sympy.Expr) -> sympy.logic.boolalg.BooleanAtom: + if other is S.Infinity: + return sympy.false # sympy.oo > int_oo + elif other is S.IntInfinity: + return sympy.true # consistency with sympy.oo + else: + return sympy.true + + def __lt__(self, other: sympy.Expr) -> sympy.logic.boolalg.BooleanAtom: + if other is S.Infinity: + return sympy.true # sympy.oo > int_oo + elif other is S.IntInfinity: + return sympy.false # consistency with sympy.oo + else: + return sympy.false + + def __le__(self, other: sympy.Expr) -> sympy.logic.boolalg.BooleanAtom: + if other is S.Infinity: + return sympy.true # sympy.oo > int_oo + elif other is S.IntInfinity: + return sympy.true # consistency with sympy.oo + else: + return sympy.false + + @_sympifyit("other", NotImplemented) + def __mod__(self, other: sympy.Expr) -> sympy.Expr: + if not isinstance(other, Expr): + return NotImplemented + return S.NaN + + __rmod__ = __mod__ + + def floor(self) -> "IntInfinity": + return self + + def ceiling(self) -> "IntInfinity": + return self + + +int_oo = S.IntInfinity + + +def is_infinite(expr: sympy.Basic) -> bool: + """Check if an expression is any type of infinity (positive or negative). + + This handles both sympy's built-in infinities (oo, -oo) and PyTorch's + integer infinities (int_oo, -int_oo). + + Note: We cannot rely on sympy's is_finite property because IntInfinity + and NegativeIntInfinity have is_integer=True, which implies is_finite=True + in sympy's assumption system. + """ + return expr in ( + S.Infinity, + S.NegativeInfinity, + S.IntInfinity, + S.NegativeIntInfinity, + ) + + +# pyrefly: ignore [invalid-inheritance] +class NegativeIntInfinity(Number, metaclass=Singleton): + """Negative integer infinite quantity. + + NegativeInfinity is a singleton, and can be accessed + by ``S.NegativeInfinity``. + + See Also + ======== + + IntInfinity + """ + + # Ensure we get dispatched to before plain numbers + _op_priority = 100.0 + + is_integer = True + is_extended_real = True + is_commutative = True + is_comparable = True + is_extended_negative = True + is_number = True + is_prime = False + + __slots__: tuple[str, ...] = () + + def __new__(cls) -> "NegativeIntInfinity": + return AtomicExpr.__new__(cls) + + def _eval_subs(self, old: sympy.Basic, new: sympy.Basic) -> sympy.Basic | None: + if self == old: + return new + return None + + def _sympystr(self, printer: Any) -> str: + return "-int_oo" + + """ + def _eval_evalf(self, prec=None): + return Float('-inf') + + def evalf(self, prec=None, **options): + return self._eval_evalf(prec) + """ + + @_sympifyit("other", NotImplemented) + def __add__(self, other: sympy.Expr) -> sympy.Expr: + if isinstance(other, Number) and global_parameters.evaluate: + if other is S.Infinity: + return S.Infinity + if other in (S.IntInfinity, S.NaN): + return S.NaN + return self + return Number.__add__(self, other) + + __radd__ = __add__ + + @_sympifyit("other", NotImplemented) + def __sub__(self, other: sympy.Expr) -> sympy.Expr: + if isinstance(other, Number) and global_parameters.evaluate: + if other is S.NegativeInfinity: + return S.Infinity + if other in (S.NegativeIntInfinity, S.NaN): + return S.NaN + return self + return Number.__sub__(self, other) + + @_sympifyit("other", NotImplemented) + def __rsub__(self, other: sympy.Expr) -> sympy.Expr: + return (-self).__add__(other) + + @_sympifyit("other", NotImplemented) + def __mul__(self, other: sympy.Expr) -> sympy.Expr: + if isinstance(other, Number) and global_parameters.evaluate: + if other.is_zero or other is S.NaN: + return S.NaN + if other.is_extended_positive: + return self + return S.IntInfinity + return Number.__mul__(self, other) + + __rmul__ = __mul__ + + @_sympifyit("other", NotImplemented) + def __truediv__(self, other: sympy.Expr) -> sympy.Expr: + if isinstance(other, Number) and global_parameters.evaluate: + if other in ( + S.Infinity, + S.IntInfinity, + S.NegativeInfinity, + S.NegativeIntInfinity, + S.NaN, + ): + return S.NaN + if other.is_extended_nonnegative: + return self + return S.Infinity # truediv returns float + return Number.__truediv__(self, other) + + def __abs__(self) -> sympy.Expr: + return S.IntInfinity + + def __neg__(self) -> sympy.Expr: + return S.IntInfinity + + def _eval_power(self, expt: sympy.Expr) -> sympy.Expr | None: + if expt.is_number: + if expt in ( + S.NaN, + S.Infinity, + S.NegativeInfinity, + S.IntInfinity, + S.NegativeIntInfinity, + ): + return S.NaN + + if isinstance(expt, sympy.Integer) and expt.is_extended_positive: + if expt.is_odd: + return S.NegativeIntInfinity + else: + return S.IntInfinity + + inf_part = S.IntInfinity**expt + s_part = S.NegativeOne**expt + if inf_part == 0 and s_part.is_finite: + return inf_part + if ( + inf_part is S.ComplexInfinity + and s_part.is_finite + and not s_part.is_zero + ): + return S.ComplexInfinity + return s_part * inf_part + return None + + def _as_mpf_val(self, prec: int) -> Any: + return mlib.fninf + + def __hash__(self) -> int: + return super().__hash__() + + def __eq__(self, other: object) -> bool: + return other is S.NegativeIntInfinity + + def __ne__(self, other: object) -> bool: + return other is not S.NegativeIntInfinity + + def __gt__(self, other: sympy.Expr) -> sympy.logic.boolalg.BooleanAtom: + if other is S.NegativeInfinity: + return sympy.true # -sympy.oo < -int_oo + elif other is S.NegativeIntInfinity: + return sympy.false # consistency with sympy.oo + else: + return sympy.false + + def __ge__(self, other: sympy.Expr) -> sympy.logic.boolalg.BooleanAtom: + if other is S.NegativeInfinity: + return sympy.true # -sympy.oo < -int_oo + elif other is S.NegativeIntInfinity: + return sympy.true # consistency with sympy.oo + else: + return sympy.false + + def __lt__(self, other: sympy.Expr) -> sympy.logic.boolalg.BooleanAtom: + if other is S.NegativeInfinity: + return sympy.false # -sympy.oo < -int_oo + elif other is S.NegativeIntInfinity: + return sympy.false # consistency with sympy.oo + else: + return sympy.true + + def __le__(self, other: sympy.Expr) -> sympy.logic.boolalg.BooleanAtom: + if other is S.NegativeInfinity: + return sympy.false # -sympy.oo < -int_oo + elif other is S.NegativeIntInfinity: + return sympy.true # consistency with sympy.oo + else: + return sympy.true + + @_sympifyit("other", NotImplemented) + def __mod__(self, other: sympy.Expr) -> sympy.Expr: + if not isinstance(other, Expr): + return NotImplemented + return S.NaN + + __rmod__ = __mod__ + + def floor(self) -> "NegativeIntInfinity": + return self + + def ceiling(self) -> "NegativeIntInfinity": + return self + + def as_powers_dict(self) -> dict[sympy.Expr, int]: + return {S.NegativeOne: 1, S.IntInfinity: 1} diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/printers.py b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/printers.py new file mode 100644 index 0000000000000000000000000000000000000000..08ca780f9ebd641c8a3543e8b563e0f0748d063b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/printers.py @@ -0,0 +1,671 @@ +import sys +from typing import Literal + +import sympy +from sympy.printing.precedence import PRECEDENCE, precedence +from sympy.printing.str import StrPrinter + + +INDEX_TYPE = "int64_t" +INDEX_TYPE_MAX = (1 << 63) - 1 +INDEX_TYPE_MIN = -1 << 63 + + +# This printer contains rules that are supposed to be generic for both C/C++ and +# Python +class ExprPrinter(StrPrinter): + # override this so that _print_FloorDiv is used + printmethod = "_torch_sympystr" + + def _print_Mul(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, "*", precedence(expr)) + + def _print_Not(self, expr: sympy.Expr) -> str: + # pyrefly: ignore [missing-attribute] + return f"not ({self._print(expr.args[0])})" + + def _print_Add(self, expr: sympy.Expr, order: str | None = None) -> str: + return self.stringify(expr.args, " + ", precedence(expr)) + + def _print_Relational(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, f" {expr.rel_op} ", precedence(expr)) + + def _print_BitwiseFn_bitwise_and(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " & ", PRECEDENCE["BitwiseAnd"]) + + def _print_BitwiseFn_bitwise_or(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"]) + + def _print_BitwiseFn_bitwise_xor(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " ^ ", PRECEDENCE["BitwiseXor"]) + + # NB: this is OK to put here, because Mod is only defined for positive + # numbers, and so across C/Python its behavior is consistent + def _print_Mod(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " % ", PRECEDENCE["Atom"] - 0.5) + + def _print_FloatTrueDiv(self, expr: sympy.Expr) -> str: + s = self.stringify(expr.args, " / ", PRECEDENCE["Atom"] - 0.5) + return f"({s})" + + def _print_CleanDiv(self, expr: sympy.Expr) -> str: + return self._print_FloorDiv(expr) + + def _print_Identity(self, expr: sympy.Expr) -> str: + # pyrefly: ignore [missing-attribute] + return self._print(expr.args[0]) + + def _print_Float(self, expr: sympy.Expr) -> str: + if expr._prec == 53: + # IEEE-754 double precision have 53 bits. SymPy prints them with + # 15 digits, but we need 17 for round-trip correctness + return str(sympy.Float(expr, dps=17)) + else: + # We don't use other precisions in pytorch + return str(expr) + + # This must be implemented because sympy will collect x * x into Pow(x, 2), without + # any explicit intervention. We print it just like x * x, notably, we + # never generate sympy.Pow with floats. + # + # NB: this pow by natural, you should never have used builtin sympy.pow + # for FloatPow, and a symbolic exponent should be PowByNatural. These + # means exp is guaranteed to be integer. + def _print_Pow(self, expr: sympy.Expr) -> str: + base, exp = expr.args + if exp != int(exp): + raise AssertionError(exp) + exp = int(exp) + if exp < 0: + raise AssertionError(f"exponent must be non-negative, got {exp}") + if exp > 0: + return self.stringify([base] * exp, "*", PRECEDENCE["Mul"]) + return "1" + + # Explicit NotImplemented functions are to prevent default sympy printing + # behavior, which will just barf out ToFloat(...) to your IR. The error + # message is better here because it tells you which printer class it needs + # to go in. + + def _print_ToFloat(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_ToFloat not implemented for {type(self)}") + + def _print_Infinity(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_Infinity not implemented for {type(self)}") + + def _print_NegativeInfinity(self, expr: sympy.Expr) -> str: + raise NotImplementedError( + f"_print_NegativeInfinity not implemented for {type(self)}" + ) + + def _print_NaN(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_NaN not implemented for {type(self)}") + + def _print_FloorDiv(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_FloorDiv not implemented for {type(self)}") + + def _print_PythonMod(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_PythonMod not implemented for {type(self)}") + + def _print_IntTrueDiv(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_IntTrueDiv not implemented for {type(self)}") + + def _print_PowByNatural(self, expr: sympy.Expr) -> str: + raise NotImplementedError( + f"_print_PowByNatural not implemented for {type(self)}" + ) + + def _print_FloatPow(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_FloatPow not implemented for {type(self)}") + + def _print_TruncToInt(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_TruncToInt not implemented for {type(self)}") + + def _print_RoundToInt(self, expr: sympy.Expr) -> str: + raise NotImplementedError(f"_print_RoundToInt not implemented for {type(self)}") + + def _print_RoundDecimal(self, expr: sympy.Expr) -> str: + raise NotImplementedError( + f"_print_RoundDecimal not implemented for {type(self)}" + ) + + # NB: Some float operations are INTENTIONALLY not implemented for + # printers. You can implement them as a quick unblock, but it is better + # to ask yourself why we haven't done this computation in the Tensor + # universe instead + + def _print_TruncToFloat(self, expr: sympy.Expr) -> str: + raise NotImplementedError( + f"_print_TruncToFloat not implemented for {type(self)}" + ) + + +class PythonPrinter(ExprPrinter): + def _print_ToFloat(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("ToFloat expects exactly one argument") + # NB: We use sym_float here because the printer is used for cache + # serialization, and cache guards get evaluated with SymInt to + # propagate guards to the parent ShapeEnv. However, this comes at a + # runtime cost for guards involving float. If this is unacceptable + # overhead, what you want to do is have two separate printers for + # SymInt, one for when the inputs are guaranteed to be int, and + # another for when they could be SymInt. + # + # NB: sym_min/sym_max also have this problem, but I chose not to fix + # those. + # + # See https://github.com/pytorch/pytorch/issues/142507 for more + # context. + # pyrefly: ignore [missing-attribute] + return f"torch.sym_float({self._print(expr.args[0])})" + + def _print_And(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " and ", precedence(expr)) + + def _print_Or(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " or ", precedence(expr)) + + def _print_ModularIndexing(self, expr: sympy.Expr) -> str: + x, div, mod = ( + self.parenthesize(arg, PRECEDENCE["Atom"] - 0.5) for arg in expr.args + ) + if div != "1": + x = f"({x} // {div})" + return f"({x} % {mod})" + + def _print_Infinity(self, expr: sympy.Expr) -> str: + return "math.inf" + + def _print_NegativeInfinity(self, expr: sympy.Expr) -> str: + return "-math.inf" + + def _print_NaN(self, expr: sympy.Expr) -> str: + return "math.nan" + + # WARNING: this is dangerous for Triton, which has C-style modulus + def _print_PythonMod(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " % ", PRECEDENCE["Atom"] - 0.5) + + # WARNING: this is dangerous for Triton, which has C-style modulus + def _print_FloorDiv(self, expr: sympy.Expr) -> str: + x, div = (self.parenthesize(arg, PRECEDENCE["Atom"] - 0.5) for arg in expr.args) + return f"{x} // {div}" + + # WARNING: this is dangerous for Triton, when lhs, rhs > 2**53, Python + # does a special algorithm + def _print_IntTrueDiv(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " / ", PRECEDENCE["Atom"] - 0.5) + + def _helper_sqrt(self, expr: sympy.Expr) -> str: + # NB: We use torch._sym_sqrt here instead of math.sqrt because the + # guard expression may be evaluated with SymInt/SymFloat inputs (e.g. + # during cache hit re-evaluation in evaluate_guards_expression). + # math.sqrt on a SymFloat triggers evaluate_expr which forces + # concretization/specialization of the symbol, creating spurious + # guards that didn't exist in the original program. + # torch._sym_sqrt properly propagates through the symbolic system + # without forcing specialization. + # See https://github.com/pytorch/pytorch/issues/152435 + # pyrefly: ignore [missing-attribute] + return f"torch._sym_sqrt({self._print(expr)})" + + def _print_OpaqueUnaryFn_sqrt(self, expr: sympy.Expr) -> str: + return self._helper_sqrt(expr.args[0]) + + def _print_FloatPow(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " ** ", PRECEDENCE["Pow"]) + + # TODO: Not sure this works with Triton, even when base/exp are integral + def _print_PowByNatural(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " ** ", PRECEDENCE["Pow"]) + + def _print_floor(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("floor expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.floor({self._print(expr.args[0])})" + + def _print_FloorToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("FloorToInt expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.floor({self._print(expr.args[0])})" + + def _print_TruncToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("TruncToInt expects exactly one argument") + # This also could have been int(), they'll do the same thing for float + # pyrefly: ignore [missing-attribute] + return f"math.trunc({self._print(expr.args[0])})" + + def _print_ceiling(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("ceiling expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.ceil({self._print(expr.args[0])})" + + def _print_CeilToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("CeilToInt expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.ceil({self._print(expr.args[0])})" + + def _print_Abs(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("Abs expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"abs({self._print(expr.args[0])})" + + # NB: It's expected that we've made explicit any promotion in the sympy + # expression, so it doesn't matter that Python max/min doesn't perform + # promotion + def _print_Max(self, expr: sympy.Expr) -> str: + if len(expr.args) < 2: + raise AssertionError("Max expects at least two arguments") + # pyrefly: ignore [missing-attribute] + return f"max({', '.join(map(self._print, expr.args))})" + + def _print_Min(self, expr: sympy.Expr) -> str: + if len(expr.args) < 2: + raise AssertionError("Min expects at least two arguments") + # pyrefly: ignore [missing-attribute] + return f"min({', '.join(map(self._print, expr.args))})" + + def _print_OpaqueUnaryFn_cos(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("cos expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.cos({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_cosh(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("cosh expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.cosh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_acos(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("acos expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.acos({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_sin(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("sin expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.sin({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_sinh(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("sinh expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.sinh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_asin(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("asin expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.asin({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_tan(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("tan expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.tan({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_tanh(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("tanh expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.tanh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_atan(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("atan expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.atan({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_log2(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("log2 expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.log2({self._print(expr.args[0])})" + + def _print_RoundToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("RoundToInt expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"round({self._print(expr.args[0])})" + + def _print_RoundDecimal(self, expr: sympy.Expr) -> str: + if len(expr.args) != 2: + raise AssertionError("RoundDecimal expects exactly two arguments") + number, ndigits = expr.args + if not isinstance(ndigits, sympy.Integer): + raise TypeError("ndigits must be an instance of sympy.Integer") + # pyrefly: ignore [missing-attribute] + return f"round({self._print(number)}, {ndigits})" + + def _print_Piecewise(self, expr: sympy.Expr) -> str: + # Convert Piecewise(expr_cond_pairs) to nested ternary expressions + # Piecewise((e1, c1), (e2, c2), ..., (eN, cN)) + # becomes: e1 if c1 else (e2 if c2 else (... else eN)) + result: str | None = None + for expr_i, cond_i in reversed(expr.args): + # pyrefly: ignore [missing-attribute] + expr_str = self._print(expr_i) + if cond_i == True: # noqa: E712 + # This is the default case + result = expr_str + else: + # pyrefly: ignore [missing-attribute] + cond_str = self._print(cond_i) + if result is None: + result = expr_str + else: + result = f"({expr_str} if {cond_str} else {result})" + return result if result else "0" + + +class CppPrinter(ExprPrinter): + def _print_Integer(self, expr: sympy.Expr) -> str: + suffix = "LL" if sys.platform in ["darwin", "win32"] else "L" + i = int(expr) + if i > INDEX_TYPE_MAX or i < INDEX_TYPE_MIN: + raise OverflowError(f"{i} too big to convert to {INDEX_TYPE}") + elif i == INDEX_TYPE_MIN: + if i != (-1) << 63: + raise AssertionError("unexpected minimum index type value") + # Writing -9223372036854775808L makes the value overflow + # as it is parsed as -(9223372036854775808L) by the C/C++ compiler + return f"(-1{suffix} << 63)" + return f"{i}{suffix}" + + def _print_Where(self, expr: sympy.Expr) -> str: + c, p, q = ( + self.parenthesize(arg, PRECEDENCE["Atom"] - 0.5) for arg in expr.args + ) + return f"{c} ? {p} : {q}" + + def _print_Or(self, expr: sympy.Expr) -> str: + return self.stringify(expr.args, " || ", precedence(expr)) + + def _print_Piecewise(self, expr: sympy.Expr) -> str: + # Convert Piecewise(expr_cond_pairs) to nested ternary operators + # Piecewise((e1, c1), (e2, c2), ..., (eN, cN)) + # becomes: c1 ? e1 : (c2 ? e2 : (... : eN)) + result: str | None = None + for expr_i, cond_i in reversed(expr.args): + expr_str = self.parenthesize(expr_i, PRECEDENCE["Atom"] - 0.5) + if cond_i == True: # noqa: E712 + # This is the default case + result = expr_str + else: + cond_str = self.parenthesize(cond_i, PRECEDENCE["Atom"] - 0.5) + if result is None: + result = expr_str + else: + result = f"{cond_str} ? {expr_str} : {result}" + return f"({result})" if result else "0" + + def _print_ModularIndexing(self, expr: sympy.Expr) -> str: + x, div, mod = expr.args + x = self.doprint(x) + if div != 1: + div = self.doprint(div) + if expr.is_integer: + x = f"c10::div_floor_integer(static_cast({x}), static_cast({div}))" + else: + x = f"c10::div_floor_floating(static_cast({x}), static_cast({div}))" + mod = self.doprint(mod) + return f"(static_cast<{INDEX_TYPE}>({x}) % static_cast<{INDEX_TYPE}>({mod}))" + + def _print_FloorDiv(self, expr: sympy.Expr) -> str: + x, div = expr.args + x = self.doprint(x) + div = self.doprint(div) + if expr.is_integer: + return f"c10::div_floor_integer(static_cast({x}), static_cast({div}))" + return f"c10::div_floor_floating(static_cast({x}), static_cast({div}))" + + def _print_floor(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("floor expects exactly one argument") + # pyrefly: ignore [missing-attribute] + r = f"std::floor({self._print(expr.args[0])})" + return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r + + def _print_FloorToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("FloorToInt expects exactly one argument") + # pyrefly: ignore [missing-attribute] + r = f"std::floor({self._print(expr.args[0])})" + return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r + + def _print_TruncToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("TruncToInt expects exactly one argument") + # pyrefly: ignore [missing-attribute] + r = f"std::trunc({self._print(expr.args[0])})" + return f"static_cast<{INDEX_TYPE}>({r})" + + def _print_TruncToFloat(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("TruncToFloat expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"std::trunc({self._print(expr.args[0])})" + + def _print_ToFloat(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("ToFloat expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"static_cast({self._print(expr.args[0])})" + + def _print_PythonMod(self, expr: sympy.Expr) -> str: + x, div = expr.args + x = self.doprint(x) + div = self.doprint(div) + return f"c10::div_mod({x}, {div})" + + def _print_IntTrueDiv(self, expr: sympy.Expr) -> str: + lhs, rhs = expr.args + # TODO: This is only accurate up to 2**53 + # pyrefly: ignore [missing-attribute] + return f"static_cast({self._print(lhs)}) / static_cast({self._print(rhs)})" + + # TODO: PowByNatural: we need to implement our own int-int pow. Do NOT + # use std::pow, that operates on floats + def _print_PowByNatural(self, expr: sympy.Expr) -> str: + # Implement the special-case of 2**x for now + base, exp = expr.args + if base == 2: + # pyrefly: ignore [missing-attribute] + return f"(1 << ({self._print(exp)}))" + raise NotImplementedError( + f"_print_PowByNatural not implemented for {type(self)}" + ) + + def _print_FloatPow(self, expr: sympy.Expr) -> str: + base, exp = expr.args + # pyrefly: ignore [missing-attribute] + return f"std::pow({self._print(base)}, {self._print(exp)})" + + def _print_Pow(self, expr: sympy.Expr) -> str: + # Uses float constants to perform FP div + base, exp = expr.args + + if exp == 0.5 or exp == -0.5: + # pyrefly: ignore [missing-attribute] + base = self._print(base) + return f"std::sqrt({base})" if exp == 0.5 else f"1.0/std::sqrt({base})" + if exp.is_integer: + exp = int(exp) + if exp > 0: + r = self.stringify([base] * exp, "*", PRECEDENCE["Mul"]) + elif exp < -1: + r = ( + "1.0/(" + + self.stringify([base] * abs(exp), "*", PRECEDENCE["Mul"]) + + ")" + ) + elif exp == -1: + # pyrefly: ignore [missing-attribute] + r = "1.0/" + self._print(base) + else: # exp == 0 + r = "1.0" + + return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r + else: + # TODO: float vs double + return f"std::pow({base}, {float(exp)})" + + def _print_Rational(self, expr: sympy.Expr) -> str: + # Uses float constants to perform FP div + if expr.q == 1: + r = f"{expr.p}" + else: + r = f"{expr.p}.0/{expr.q}.0" + return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r + + def _print_ceiling(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("ceiling expects exactly one argument") + # pyrefly: ignore [missing-attribute] + r = f"std::ceil({self._print(expr.args[0])})" + return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r + + def _print_CeilToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("CeilToInt expects exactly one argument") + # pyrefly: ignore [missing-attribute] + r = f"std::ceil({self._print(expr.args[0])})" + return f"static_cast<{INDEX_TYPE}>({r})" if expr.is_integer else r + + def _print_min_max(self, expr: sympy.Expr, name: Literal["min", "max"]) -> str: + # pyrefly: ignore [missing-attribute] + args = [self._print(a) for a in expr.args] + if not expr.is_integer: + args = [f"static_cast({arg})" for arg in args] + if len(args) == 2: + return f"std::{name}({args[0]}, {args[1]})" + # Initializer list overload + il = "{" + ", ".join(args) + "}" + return f"std::{name}({il})" + + if len(args) == 2: + return f"std::{name}(static_cast<{INDEX_TYPE}>({args[0]}), static_cast<{INDEX_TYPE}>({args[1]}))" + else: + # Initializer list overload + il = "{" + ", ".join(args) + "}" + return f"std::{name}<{INDEX_TYPE}>({il})" + + def _print_Min(self, expr: sympy.Expr) -> str: + return self._print_min_max(expr, "min") + + def _print_Max(self, expr: sympy.Expr) -> str: + return self._print_min_max(expr, "max") + + def _print_Abs(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("Abs expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"std::abs({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_cos(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("cos expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"std::cos({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_cosh(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("cosh expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"std::cosh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_acos(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("acos expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"std::acos({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_sin(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("sin expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"math.sin({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_sinh(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("sinh expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"std::sinh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_asin(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("asin expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"std::asin({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_tan(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("tan expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"std::tan({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_tanh(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("tanh expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"std::tanh({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_atan(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("atan expects exactly one argument") + # pyrefly: ignore [missing-attribute] + return f"std::atan({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_sqrt(self, expr: sympy.Expr) -> str: + # pyrefly: ignore [missing-attribute] + return f"std::sqrt({self._print(expr.args[0])})" + + def _print_OpaqueUnaryFn_log2(self, expr: sympy.Expr) -> str: + # pyrefly: ignore [missing-attribute] + return f"std::log2({self._print(expr.args[0])})" + + def _print_RoundToInt(self, expr: sympy.Expr) -> str: + if len(expr.args) != 1: + raise AssertionError("RoundToInt expects exactly one argument") + # TODO: dispatch to llrint depending on index type + # pyrefly: ignore [missing-attribute] + return f"std::lrint({self._print(expr.args[0])})" + + def _print_RoundDecimal(self, expr: sympy.Expr) -> str: + if len(expr.args) != 2: + raise AssertionError("RoundDecimal expects exactly two arguments") + number, ndigits = expr.args + if number.is_integer: + # ndigits < 0 should have been filtered by the sympy function + if ndigits >= 0: + raise AssertionError("ndigits must be negative for integer inputs") + raise ValueError( + f"For integer inputs, only non-negative ndigits are currently supported, but got {ndigits}." + ) + number_str = self.parenthesize(number, PRECEDENCE["Mul"]) + return f"static_cast(std::nearbyint(1e{ndigits} * {number_str}) * 1e{-ndigits})" + + def _print_BooleanTrue(self, expr: sympy.Expr) -> str: + return "true" + + def _print_BooleanFalse(self, expr: sympy.Expr) -> str: + return "false" + + def _print_Infinity(self, expr: sympy.Expr) -> str: + return "std::numeric_limits::infinity()" + + def _print_NegativeInfinity(self, expr: sympy.Expr) -> str: + return f"-{self._print_Infinity(expr)}" + + def _print_NaN(self, expr: sympy.Expr) -> str: + return "std::numeric_limits::quiet_NaN()" diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/reference.py b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..72c0287f83f7e2d3de9314b35b5f4f767796a0bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/reference.py @@ -0,0 +1,633 @@ +# mypy: allow-untyped-defs +import math +import operator +from typing import NoReturn + +import sympy + +import torch +from torch.utils._sympy.functions import ( + _keep_float, + BitwiseFn_bitwise_and, + BitwiseFn_bitwise_or, + BitwiseFn_bitwise_xor, + FloatPow, + FloatTrueDiv, + FloorDiv, + IntTrueDiv, + Max, + Min, + Mod, + OpaqueUnaryFn_exp, + OpaqueUnaryFn_log, + OpaqueUnaryFn_log2, + OpaqueUnaryFn_sqrt, + PowByNatural, + RoundDecimal, + RoundToInt, + ToFloat, + TruncToInt, +) + + +# The sympy interpretation of operators. It will also sometimes work with +# plain int/float, but if you do certain operations you will get out a +# sympy.Basic in the end. If you want the Python/FX traceable interpretation, +# check PythonReferenceAnalysis. +# NB: For magic methods this needs to use normal magic methods +# so that test_magic_methods works +class ReferenceAnalysis: + @staticmethod + def constant(c, dtype): + return sympy.sympify(c) + + @staticmethod + def or_(a, b): + return a | b + + @staticmethod + def and_(a, b): + return a & b + + @staticmethod + def eq(a, b): + if isinstance(a, sympy.Expr) or isinstance(b, sympy.Expr): + return sympy.Eq(a, b) + return a == b + + @classmethod + def ne(cls, a, b): + return cls.not_(cls.eq(a, b)) + + @staticmethod + def lt(a, b): + return a < b + + @staticmethod + def gt(a, b): + return a > b + + @staticmethod + def le(a, b): + return a <= b + + @staticmethod + def ge(a, b): + return a >= b + + @staticmethod + def not_(a): + if isinstance(a, bool): + raise AssertionError("not_ needs sympy expr") + return ~a + + @staticmethod + def reciprocal(x): + return FloatTrueDiv(1.0, x) + + @staticmethod + def square(x): + return PowByNatural(x, 2) + + @staticmethod + def trunc_to_int(x, dtype): + return TruncToInt(x) + + @staticmethod + def ceil_to_int(x, dtype): + return sympy.ceiling(x) + + @staticmethod + def floor_to_int(x, dtype): + return sympy.floor(x) + + @staticmethod + def floor(x): + return _keep_float(sympy.floor)(x) + + @staticmethod + def ceil(x): + return _keep_float(sympy.ceiling)(x) + + @staticmethod + def to_dtype(x, dtype): + if dtype == torch.float64: + return ToFloat(x) + raise NotImplementedError(f"to_dtype {dtype} NYI") + + @staticmethod + def mod(x, y): + return Mod(x, y) + + @staticmethod + def abs(x): + return abs(x) + + @staticmethod + def neg(x): + return -x + + @staticmethod + def truediv(a, b): + return FloatTrueDiv(a, b) + + @staticmethod + def int_truediv(a, b): + return IntTrueDiv(a, b) + + @staticmethod + def floordiv(a, b): + return FloorDiv(a, b) + + @staticmethod + def truncdiv(a, b) -> NoReturn: + raise NotImplementedError("TODO: truncdiv") + + @staticmethod + def add(a, b): + return _keep_float(operator.add)(a, b) + + @classmethod + def sym_sum(cls, args): + return sympy.Add(*args) + + @staticmethod + def mul(a, b): + return _keep_float(operator.mul)(a, b) + + @staticmethod + def sub(a, b): + return _keep_float(operator.sub)(a, b) + + @staticmethod + def exp(x): + return OpaqueUnaryFn_exp(x) + + @staticmethod + def log(x): + return OpaqueUnaryFn_log(x) + + @staticmethod + def log2(x): + return OpaqueUnaryFn_log2(x) + + @staticmethod + def sqrt(x): + return OpaqueUnaryFn_sqrt(x) + + @staticmethod + def pow(a, b): + # pyrefly: ignore [bad-argument-count, bad-argument-type] + return _keep_float(FloatPow)(a, b) + + @staticmethod + def pow_by_natural(a, b): + return PowByNatural(a, b) + + @staticmethod + def minimum(a, b): + return Min(a, b) + + @staticmethod + def maximum(a, b): + return Max(a, b) + + @staticmethod + def round_to_int(a, dtype): + return RoundToInt(a) + + @staticmethod + def round_decimal(a, b): + return RoundDecimal(a, b) + + @staticmethod + def bitwise_and(a, b): + return BitwiseFn_bitwise_and(a, b) + + @staticmethod + def bitwise_or(a, b): + return BitwiseFn_bitwise_or(a, b) + + @staticmethod + def bitwise_xor(a, b): + return BitwiseFn_bitwise_xor(a, b) + + +# Unlike ReferenceAnalysis, does NOT sympyify, instead, works with plain +# Python types and is FX traceable. Inheritance here is purely for code +# sharing (TODO: considering splitting out a BaseReferenceAnalysis). +class PythonReferenceAnalysis(ReferenceAnalysis): + @staticmethod + def constant(c, dtype): + if dtype is torch.int64: + return int(c) + elif dtype is torch.double: + return float(c) + elif dtype is torch.bool: + return bool(c) + else: + raise AssertionError(f"unrecognized dtype {dtype}") + + @staticmethod + def not_(a): + return torch.sym_not(a) + + @classmethod + def sym_sum(cls, args): + if len(args) == 0: + return 0 + if len(args) == 1: + return args[0] + acc = cls.add(args[0], args[1]) + for i in range(2, len(args)): + acc = cls.add(acc, args[i]) + return acc + + @staticmethod + def floordiv(a, b): + return a // b + + @staticmethod + def mod(x, y): + return x % y + + @staticmethod + def python_mod(x, y): + return x % y + + @staticmethod + def truncdiv(a, b): + return a / b + + @staticmethod + def to_dtype(x, dtype): + if dtype == torch.float64: + return torch.sym_float(x) + raise NotImplementedError(f"to_dtype {dtype} NYI") + + @staticmethod + def exp(x) -> NoReturn: + raise AssertionError("exp is not valid shape sympy expr") + + @staticmethod + def log(x) -> NoReturn: + raise AssertionError("log is not valid shape sympy expr") + + @staticmethod + def log2(x): + return torch._sym_log2(x) # type: ignore[attr-defined] + + @staticmethod + def sqrt(x): + return torch._sym_sqrt(x) # type: ignore[attr-defined] + + @staticmethod + def minimum(a, b): + return torch.sym_min(a, b) + + @staticmethod + def maximum(a, b): + return torch.sym_max(a, b) + + @staticmethod + def floor_to_int(x, dtype): + return math.floor(x) + + @staticmethod + def ceil_to_int(x, dtype): + return math.ceil(x) + + @staticmethod + def floor(x): + return float(math.floor(x)) + + @staticmethod + def ceil(x): + return float(math.ceil(x)) + + @staticmethod + def truediv(a, b): + return a / b + + @staticmethod + def pow(a, b): + return a**b + + @staticmethod + def pow_by_natural(a, b): + # Pray that safe_pow is not needed here lol. In particular, this + # never participates in VR low/high ranges, so overflow should be + # unlikely + return a**b + + @staticmethod + def round_to_int(a, dtype): + return round(a) + + @staticmethod + def round_decimal(a, b): + return round(a, ndigits=b) + + @staticmethod + def bitwise_and(a, b): + return a & b + + @staticmethod + def bitwise_or(a, b): + return a | b + + @staticmethod + def bitwise_xor(a, b): + return a ^ b + + @staticmethod + def expr_cond_pair(expr, cond): + return (expr, cond) + + @staticmethod + def piecewise(*pairs): + # Build nested sym_ite from right to left. + # Piecewise((e1, c1), (e2, c2), ..., (en, True)) becomes + # sym_ite(c1, e1, sym_ite(c2, e2, ... en)) + result = pairs[-1][0] + for expr, cond in reversed(pairs[:-1]): + result = torch.sym_ite(cond, expr, result) + return result + + +# Like PythonReferenceAnalysis, but some export-unfriendly choices of +# operators to make things faster +class OptimizedPythonReferenceAnalysis(PythonReferenceAnalysis): + @staticmethod + def sym_sum(args): + return torch.sym_sum(args) + + @staticmethod + def floor_to_int(x, dtype): + if isinstance(x, (int, float)): + return math.floor(x) + return x + + @staticmethod + def ceil_to_int(x, dtype): + if isinstance(x, (int, float)): + return math.ceil(x) + return x + + @staticmethod + def trunc_to_int(x, dtype): + if isinstance(x, (int, float)): + return math.trunc(x) + return x + + +def _to_dtype(x: torch.Tensor, dtype: torch.dtype) -> torch.Tensor: + return torch.ops.prims.convert_element_type.default(x, dtype) + + +# Suppose we have some int/float arguments. This diagram commutes: +# +# int/float -- PythonReferenceAnalysis.op --> int/float +# | | +# | | +# torch.tensor(..., dtype=torch.int64/torch.float64) +# | | +# V V +# Tensor -- TensorReferenceAnalysis.op --> Tensor +# +# NB: int before and after must be representable in int64 (we will +# insert guards accordingly.) +# +# This is guaranteed to be FX traceable with OpOverloads only. +class TensorReferenceAnalysis: + # NB: This is actually dead, because with Proxy tracing the factory + # function isn't traced correctly. Here for completeness. + @staticmethod + def constant(c, dtype): + d: int | float | bool + if dtype is torch.int64: + d = int(c) + elif dtype is torch.double: + d = float(c) + elif dtype is torch.bool: + d = bool(c) + else: + raise AssertionError(f"unrecognized dtype {dtype}") + return torch.ops.aten.scalar_tensor.default(d, dtype=dtype) + + @staticmethod + def or_(a, b): + return torch.ops.aten.logical_or.default(a, b) + + @staticmethod + def and_(a, b): + return torch.ops.aten.logical_and.default(a, b) + + @staticmethod + def bitwise_and(a, b): + return torch.ops.aten.bitwise_and(a, b) + + @staticmethod + def bitwise_or(a, b): + return torch.ops.aten.bitwise_or(a, b) + + @staticmethod + def bitwise_xor(a, b): + return torch.ops.aten.bitwise_xor(a, b) + + @staticmethod + def eq(a, b): + return torch.ops.aten.eq.Tensor(a, b) + + @classmethod + def ne(cls, a, b): + return torch.ops.aten.ne.Tensor(a, b) + + @staticmethod + def lt(a, b): + return torch.ops.aten.lt.Tensor(a, b) + + @staticmethod + def gt(a, b): + return torch.ops.aten.gt.Tensor(a, b) + + @staticmethod + def le(a, b): + return torch.ops.aten.le.Tensor(a, b) + + @staticmethod + def ge(a, b): + return torch.ops.aten.ge.Tensor(a, b) + + @staticmethod + def not_(a): + return torch.ops.aten.logical_not.default(a) + + @staticmethod + def reciprocal(x): + return torch.ops.aten.reciprocal.default(x) + + @staticmethod + def square(x): + # TODO: maybe composite implicit autograd doesn't work here? + return torch.ops.aten.square.default(x) + + @staticmethod + def trunc_to_int(x, dtype): + return _to_dtype(torch.ops.aten.trunc.default(x), dtype) + + @staticmethod + def ceil_to_int(x, dtype): + return _to_dtype(torch.ops.aten.ceil.default(x), dtype) + + @staticmethod + def floor_to_int(x, dtype): + return _to_dtype(torch.ops.aten.floor.default(x), dtype) + + @staticmethod + def floor(x): + return torch.ops.aten.floor.default(x) + + @staticmethod + def ceil(x): + return torch.ops.aten.ceil.default(x) + + @staticmethod + def to_dtype(x, dtype): + return _to_dtype(x, dtype) + + @staticmethod + def mod(x, y) -> NoReturn: + # TODO: https://github.com/pytorch/pytorch/pull/133654 + raise NotImplementedError( + "no C-style modulus operation available from frontend atm" + ) + + @staticmethod + def abs(x): + return torch.ops.aten.abs.default(x) + + @staticmethod + def neg(x): + return torch.ops.aten.neg.default(x) + + @staticmethod + def truediv(a, b): + return torch.ops.aten.true_divide.Tensor(a, b) + + @staticmethod + def int_truediv(a, b): + raise NotImplementedError( + "Python int truediv difficult to implement in PyTorch atm" + ) + + # TODO: This is wrong, CPython has a custom implementation of true + # division that results in higher precision when the floats are + # sufficiently large. Short term fix: add a guard here + # pyrefly: ignore [unreachable] + return torch.ops.aten.true_divide.default( + _to_dtype(a, torch.float64), _to_dtype(b, torch.float64) + ) + + @staticmethod + def floordiv(a, b): + return torch.ops.aten.div.Tensor_mode(a, b, rounding_mode="floor") + + @staticmethod + def truncdiv(a, b) -> NoReturn: + raise NotImplementedError( + "no C-style truncdiv operation available from frontend atm" + ) + + @staticmethod + def add(a, b): + return torch.ops.aten.add.Tensor(a, b) + + @staticmethod + def mul(a, b): + return torch.ops.aten.mul.Tensor(a, b) + + @staticmethod + def sub(a, b): + return torch.ops.aten.sub.Tensor(a, b) + + @staticmethod + def exp(x): + return torch.ops.aten.exp.default(x) + + @staticmethod + def log(x): + return torch.ops.aten.log.default(x) + + @staticmethod + def log2(x): + return torch.ops.aten.log2.default(x) + + @staticmethod + def sqrt(x): + return torch.ops.aten.sqrt.default(x) + + @staticmethod + def sin(x): + return torch.ops.aten.sin.default(x) + + @staticmethod + def cos(x): + return torch.ops.aten.cos.default(x) + + @staticmethod + def tanh(x): + return torch.ops.aten.tanh.default(x) + + @staticmethod + def sinh(x): + return torch.ops.aten.sinh.default(x) + + @staticmethod + def cosh(x): + return torch.ops.aten.cosh.default(x) + + @staticmethod + def tan(x): + return torch.ops.aten.tan.default(x) + + @staticmethod + def acos(x): + return torch.ops.aten.acos.default(x) + + @staticmethod + def atan(x): + return torch.ops.aten.atan.default(x) + + @staticmethod + def asin(x): + return torch.ops.aten.asin.default(x) + + @staticmethod + def pow(a, b): + return torch.ops.aten.pow.Tensor_Tensor(a, b) + + @staticmethod + def pow_by_natural(a, b): + # NB: pow handles int x int fine + return torch.ops.aten.pow.Tensor_Tensor(a, b) + + @staticmethod + def minimum(a, b): + return torch.ops.aten.minimum.default(a, b) + + @staticmethod + def maximum(a, b): + return torch.ops.aten.maximum.default(a, b) + + @staticmethod + def round_to_int(a, dtype): + return torch.ops.aten.round.default(a) + + @staticmethod + def round_decimal(a, b) -> NoReturn: + raise NotImplementedError( + "round decimal doesn't support Tensor second argument atm" + ) + + # return torch.ops.aten.round.decimals(a, b) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/singleton_int.py b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/singleton_int.py new file mode 100644 index 0000000000000000000000000000000000000000..d0d7fea5da3ed8c9d3123589170b7fd883c75ce2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/singleton_int.py @@ -0,0 +1,101 @@ +from typing import Any + +import sympy +from sympy.multipledispatch import dispatch + + +__all__ = ["SingletonInt"] + + +class SingletonInt(sympy.AtomicExpr): + # This is probably not super important unless we are in multiple dispatch + # situations with other more exotic Expr types. + _op_priority = 99999 + _val: int + _coeff: int + + def __new__( + cls, *args: Any, coeff: int | None = None, **kwargs: Any + ) -> "SingletonInt": + instance = super().__new__(cls, *args, **kwargs) + return instance + + # The semantics of this class should match that of NestedIntSymNodeImpl in + # c10/core/NestedIntSymNodeImpl.h + def __init__(self, val: int, *, coeff: int = 1) -> None: + self._val = val + self._coeff = coeff + super().__init__() + + # See NOTE [ Inequalities with nested int ] + def _eval_Eq(self, other: sympy.Basic) -> sympy.logic.boolalg.BooleanAtom: + if ( + isinstance(other, SingletonInt) + and other._val == self._val + and self._coeff == other._coeff + ): + return sympy.true + else: + return sympy.false + + # This is necessary so that calling expr.free_symbols on exprs that contain + # this Singleton does not error + @property + def free_symbols(self) -> set[sympy.Symbol]: + return set() + + def __mul__(self, other: int) -> "SingletonInt": + if isinstance(other, SingletonInt): + raise ValueError( + "SingletonInt cannot be multiplied by another SingletonInt" + ) + return SingletonInt(self._val, coeff=self._coeff * other) + + def __rmul__(self, other: int) -> "SingletonInt": + if isinstance(other, SingletonInt): + raise ValueError( + "SingletonInt cannot be multiplied by another SingletonInt" + ) + return SingletonInt(self._val, coeff=self._coeff * other) + + # Make sure we promptly raise an error instead of falling back to building + # an expression tree. There are probably more ops, how can we be exhaustive? + def __add__(self, other: object) -> "SingletonInt": + raise NotImplementedError("NYI") + + def __sub__(self, other: object) -> "SingletonInt": + raise NotImplementedError("NYI") + + def __truediv__(self, other: object) -> "SingletonInt": + raise NotImplementedError("NYI") + + def __floordiv__(self, other: object) -> "SingletonInt": + raise NotImplementedError("NYI") + + def __mod__(self, other: object) -> "SingletonInt": + raise NotImplementedError("NYI") + + +# See NOTE [ Inequalities with nested int ] +@dispatch(sympy.Integer, SingletonInt) +def _eval_is_ge(a: sympy.Integer, b: SingletonInt) -> sympy.logic.boolalg.BooleanAtom: + if a < 2: + return sympy.false + raise ValueError("Symbolic SingletonInt: Relation is indeterminate") + + +@dispatch(SingletonInt, sympy.Integer) # type: ignore[no-redef] +def _eval_is_ge(a: SingletonInt, b: sympy.Integer) -> sympy.logic.boolalg.BooleanAtom: + if b <= 2: + return sympy.true + raise ValueError("Symbolic SingletonInt: Relation is indeterminate") + + +@dispatch(SingletonInt, SingletonInt) # type: ignore[no-redef] +def _eval_is_ge(a: SingletonInt, b: SingletonInt) -> sympy.logic.boolalg.BooleanAtom: + if a._val == b._val: + if a._coeff >= b._coeff: + return sympy.true + else: + return sympy.false + raise ValueError("Symbolic SingletonInt: Relation is indeterminate") diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/solve.py b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..3bd5e1484601ffa1c7c2743ffa228c536cd54fb5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/solve.py @@ -0,0 +1,179 @@ +import logging + +import sympy + +from torch.utils._sympy.functions import FloorDiv + + +log = logging.getLogger(__name__) + +_MIRROR_REL_OP: dict[type[sympy.Basic], type[sympy.Rel]] = { + sympy.Eq: sympy.Eq, + sympy.Ne: sympy.Ne, + sympy.Ge: sympy.Le, + sympy.Gt: sympy.Lt, + sympy.Le: sympy.Ge, + sympy.Lt: sympy.Gt, +} + +INEQUALITY_TYPES = (sympy.Gt, sympy.Ge, sympy.Lt, sympy.Le) + + +def mirror_rel_op(type: type) -> type[sympy.Rel] | None: + return _MIRROR_REL_OP.get(type) + + +# Tries to simplify 'expr', so as to leave only 'thing' in the left-hand side. +# +# Returns a tuple of: +# 1. The simplified expression +# 2. The expression on the right-hand side +# +# Returns 'None' if it can't reach a state where the only thing in the left +# hand side is 'thing'. +# +# 'trials': number of times 'try_solve' will try to isolate 'thing' to the +# left-hand side. +# +# 'floordiv_inequality': flag to enable conversion of 'FloorDiv' into +# inequalities. +def try_solve( + expr: sympy.Basic, + thing: sympy.Basic, + trials: int = 5, + floordiv_inequality: bool = True, +) -> tuple[sympy.Rel, sympy.Expr] | None: + mirror = mirror_rel_op(type(expr)) + + # Ignore unsupported expressions: + # - Those that are not relational operations + # - Those that don't have a mirror (just avoiding unexpected classes) + if not isinstance(expr, sympy.Rel) or mirror is None: + log.debug("expression with unsupported type: %s", type(expr)) + return None + + lhs_has_thing = expr.lhs.has(thing) + rhs_has_thing = expr.rhs.has(thing) + + # Give up when 'thing' appears on both sides of the relational expression. + # That is because, as is, we assume the thing we are trying to isolate is + # only on the right-hand side. + if lhs_has_thing and rhs_has_thing: + log.debug("thing (%s) found in both sides of expression: %s", thing, expr) + return None + + # Try considering both LHS and RHS by mirroring the original expression: + # a < b ==> b > a + expressions = [] + + # Add each version of 'expr' if 'thing' is in its left-hand side. + if lhs_has_thing: + expressions.append(expr) + if rhs_has_thing: + expressions.append(mirror(expr.rhs, expr.lhs)) + + for e in expressions: + if e is None: + continue + + if not isinstance(e, sympy.Rel): + raise AssertionError("expected sympy.Rel") + + for _ in range(trials): + trial = _try_isolate_lhs(e, thing, floordiv_inequality=floordiv_inequality) + # Stop if there was no change in this trial. + if trial == e: + break + e = trial # type: ignore[assignment] + + # Return if we were able to isolate 'thing' on the left-hand side. + if isinstance(e, sympy.Rel) and e.lhs == thing: + log.debug("solved: %s ---> %s", expr, e) + return e, e.rhs + + return None + + +def _try_isolate_lhs( + e: sympy.Basic, thing: sympy.Basic, floordiv_inequality: bool +) -> sympy.Basic: + op = type(e) + + if isinstance(e, sympy.Rel): + # Move any constants in the left-hand side to the right-hand side. + lhs_not_thing = ( + sum(a for a in e.lhs.args if not a.has(thing)) + if isinstance(e.lhs, sympy.Add) + else 0 + ) + e = op(e.lhs - lhs_not_thing, e.rhs - lhs_not_thing) # type: ignore[attr-defined] + + # Divide both sides by the factors that don't contain thing. + if isinstance(e, sympy.Rel) and isinstance(e.lhs, sympy.Mul): + lhs, rhs = e.args + other = sympy.Mul(*[a for a in lhs.args if not a.has(thing)]) + + # If we can't tell whether 'other' is negative or positive, we do nothing. + # That is because we don't know whether we have mirror the operation or not. + # We also divide only when we know 'rhs' is not zero. + if not (isinstance(e, INEQUALITY_TYPES) and other.is_negative is None) and not ( + not isinstance(e, INEQUALITY_TYPES) and rhs.is_zero + ): + # Divide both sides by 'other'. + lhs = lhs / other + rhs = rhs / other + + # If 'e' is an inequality and 'other' is negative, we have to + # mirror the expression. + if isinstance(e, INEQUALITY_TYPES) and other.is_negative: + op = mirror_rel_op(op) # type: ignore[assignment] + + if op is None: + raise AssertionError("expected op to be not None") + e = op(lhs, rhs) + + ################################################################################ + # left-hand side is FloorDiv + ################################################################################ + # + # Given the expression: a // b op c + # where 'op' is a relational operation, these rules only work if: + # - b > 0 + # - c is an integer + if ( + floordiv_inequality + and isinstance(e, sympy.Rel) + and isinstance(e.lhs, FloorDiv) + and e.lhs.divisor.is_positive + and e.rhs.is_integer + ): + # a // b == expr + # => a >= (b * expr) and a < (b * (expr + 1)) + if isinstance(e, sympy.Eq): + numerator, denominator = e.lhs.args + return sympy.And( + sympy.Ge(numerator, (e.rhs * denominator)), + sympy.Lt(numerator, ((e.rhs + 1) * denominator)), + ) + # a // b != expr + # => a < (b * expr) or a >= (b * (expr + 1)) + if isinstance(e, sympy.Ne): + numerator, denominator = e.lhs.args + return sympy.Or( + sympy.Lt(numerator, (e.rhs * denominator)), + sympy.Ge(numerator, ((e.rhs + 1) * denominator)), + ) + # The transformations below only work if b is positive. + # Note: we only have this information for constants. + # a // b > expr => a >= b * (expr + 1) + # a // b >= expr => a >= b * expr + if isinstance(e, (sympy.Gt, sympy.Ge)): + quotient = e.rhs if isinstance(e, sympy.Ge) else (e.rhs + 1) + return sympy.Ge(e.lhs.args[0], (quotient * e.lhs.args[1])) + # a // b < expr => a < b * expr + # a // b <= expr => a < b * (expr + 1) + if isinstance(e, (sympy.Lt, sympy.Le)): + quotient = e.rhs if isinstance(e, sympy.Lt) else (e.rhs + 1) + return sympy.Lt(e.lhs.args[0], (quotient * e.lhs.args[1])) + + return e diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/symbol.py b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/symbol.py new file mode 100644 index 0000000000000000000000000000000000000000..9ffab0568472af68554c170b06a4ac3010687d6f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/symbol.py @@ -0,0 +1,100 @@ +""" +This file contains canonical definitions for our symbol naming conventions, +across torch.fx.experimental.symbolic_shapes and torch._inductor. The +intention is: + +1. To make it easily greppable where all the sites we use a prefix are +2. Make it possible to easily tell if we can introduce a new prefix without + introducing a conflict + +You can occasionally test if prefixes have been hardcoded by renaming prefixes +in this file and seeing what breaks. +""" + +from collections.abc import Iterable +from enum import auto, Enum + +import sympy + + +class SymT(Enum): + SIZE = auto() + FLOAT = auto() + UNBACKED_INT = auto() + UNBACKED_FLOAT = auto() + # Inductor: The intermediates in inner_fn tmp0, one generated per ops call. + # If one of these shows up in an indexing expression, that means an + # indirect load is happening. + TMP = auto() + # Inductor: Placeholder variable that is later replaced with TMP + INDIRECT = auto() + # Inductor: Some size expressions are replaced with a precomputed size ps0 + # which is computed host side, and then directly reused in the kernel, so + # we don't repeatedly recompute it on device. + PRECOMPUTED_SIZE = auto() + # Inductor: An indexing variable i0 in loops IR which ranges over non-reduced + # dim in the loop + INDEX = auto() + # Inductor: A reduction indexing (r0, r1) variables in loops IR which ranges over + # reduced dim(s) in the loop + R0_INDEX = auto() + R1_INDEX = auto() + # Inductor: In templated kernels torch._inductor.kernel, we have a hook to + # store the final output and append epilogue fusions. To do this, we must + # know what the indexes the outputs range over. NB: These will also + # advertise as INDEX, this is... probably OK? + TEMPLATE_INDEX = auto() + # Inductor: iteration domain for blockIdx.x/blockIdx.y + XBLOCK = auto() + YBLOCK = auto() + ZBLOCK = auto() + # Inductor: this is used solely for dynamic_reshape_indexer + VIEW = auto() + # Alternate (non-modular) indexing used in halide kernels + HALIDE = auto() + + +# Invariant: there must not be a prefix which is a prefix of another string, +# as this introduces ambiguity +prefix_str = { + SymT.SIZE: "s", # integer + SymT.UNBACKED_INT: "u", # integer + # Prefix z here is chosen to avoid false aliasing in symbol_is_type test + # DO NOT add a "z" type. You also need to avoid conflicts on these + # prefixes but this is somewhat easier to manage + SymT.FLOAT: "zf", + SymT.UNBACKED_FLOAT: "zuf", + SymT.TMP: "tmp", + SymT.PRECOMPUTED_SIZE: "ps", + SymT.INDEX: "i", + SymT.R0_INDEX: "r0_", + SymT.R1_INDEX: "r1_", + SymT.TEMPLATE_INDEX: "idx", + SymT.XBLOCK: "x", + SymT.YBLOCK: "y", + SymT.ZBLOCK: "z", + SymT.INDIRECT: "indirect", # false aliasing? + SymT.VIEW: "view", + SymT.HALIDE: "h", +} + + +def make_symbol(prefix: SymT, idx: int, **kwargs: bool | None) -> sympy.Symbol: + # TODO: maybe put the assumptions here directly + return sympy.Symbol(f"{prefix_str[prefix]}{idx}", **kwargs) + + +# This type is a little wider than it should be, because free_symbols says +# that it contains Basic, rather than Symbol +def symbol_is_type(sym: sympy.Basic, prefix: SymT | Iterable[SymT]) -> bool: + if not isinstance(sym, sympy.Symbol): + raise AssertionError("expected sympy.Symbol") + name_str = sym.name.lower() # Match capitalized names like XBLOCK, RBLOCK + if isinstance(prefix, SymT): + return name_str.startswith(prefix_str[prefix]) + else: + return name_str.startswith(tuple(prefix_str[p] for p in prefix)) + + +def free_symbol_is_type(e: sympy.Expr, prefix: SymT | Iterable[SymT]) -> bool: + return any(symbol_is_type(v, prefix) for v in e.free_symbols) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_sympy/value_ranges.py b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/value_ranges.py new file mode 100644 index 0000000000000000000000000000000000000000..528331a213fe31306a9bf7fa323e41808a280d3b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_sympy/value_ranges.py @@ -0,0 +1,1306 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import dataclasses +import functools +import itertools +import logging +import math +import operator +from collections.abc import Callable +from typing import Generic, overload, SupportsFloat, TYPE_CHECKING, TypeGuard, TypeVar +from typing_extensions import TypeIs + +import sympy +from sympy.logic.boolalg import Boolean as SympyBoolean, BooleanAtom + +import torch +from torch._logging import LazyString +from torch._prims_common import dtype_to_type + +from .functions import ( + _keep_float, + FloatTrueDiv, + FloorDiv, + IntTrueDiv, + Mod, + OpaqueUnaryFn_exp, + OpaqueUnaryFn_log, + OpaqueUnaryFn_log2, + OpaqueUnaryFn_sqrt, + PowByNatural, + PythonMod, + RoundDecimal, + RoundToInt, + safe_pow, + ToFloat, + TruncToFloat, + TruncToInt, +) +from .interp import sympy_interp +from .numbers import int_oo, IntInfinity, NegativeIntInfinity + + +log = logging.getLogger(__name__) + +__all__ = ["ValueRanges", "bound_sympy"] + +_T = TypeVar("_T", sympy.Expr, SympyBoolean) + + +class ValueRangeError(RuntimeError): + pass + + +# Like sympify, but supports less stuff, and also ensures that direct +# sympy expressions don't have free variables +def simple_sympify(e): + if isinstance(e, bool): + return sympy.true if e else sympy.false + elif isinstance(e, int): + return sympy.Integer(e) + elif isinstance(e, float): + # infinity is special; we use it to bracket integers as well + if math.isinf(e): + return sympy.oo if e > 0 else -sympy.oo + return sympy.Float(e) + elif isinstance(e, sympy.Expr): + if not getattr(e, "is_number", False): + raise AssertionError(e) + # NaNs can occur when doing things like 0 * sympy.oo, but it is better + # if the operator notices this and takes care of it, because sometimes + # the NaN is inappropriate (for example, for ints, the [-oo, oo] range + # should go to zero when multiplied with [0, 0]) + if e == sympy.nan: + raise AssertionError("sympy expression is NaN") + return e + elif isinstance(e, BooleanAtom): + return e + else: + raise AssertionError(f"not simple sympy type {type(e)}: {e}") + + +# Sympy atomics only. Unlike <=, it also works on Sympy bools. +def sympy_generic_le(lower, upper): + if isinstance(lower, sympy.Expr): + if not isinstance(upper, sympy.Expr): + raise AssertionError( + "upper must be a sympy.Expr when lower is a sympy.Expr" + ) + # instead of lower <= upper, we do upper >= lower since upper is mostly int_oo + # and we have better code paths there. + return upper >= lower + else: + # only negative condition is True > False + if not isinstance(lower, SympyBoolean) or not isinstance(upper, SympyBoolean): + raise AssertionError((lower, upper)) + return not (lower and not upper) + + +def vr_is_bool(vr: ValueRanges[_T]) -> TypeGuard[ValueRanges[SympyBoolean]]: + return vr.is_bool + + +def vr_is_expr(vr: ValueRanges[_T]) -> TypeGuard[ValueRanges[sympy.Expr]]: + return not vr.is_bool + + +def is_sympy_integer(value) -> TypeIs[sympy.Integer]: + return isinstance(value, sympy.Integer) + + +ExprIn = int | float | sympy.Expr +BoolIn = bool | SympyBoolean +AllIn = ExprIn | BoolIn +ExprFn = Callable[[sympy.Expr], sympy.Expr] +ExprFn2 = Callable[[sympy.Expr, sympy.Expr], sympy.Expr] +BoolFn = Callable[[SympyBoolean], SympyBoolean] +BoolFn2 = Callable[[SympyBoolean, SympyBoolean], SympyBoolean] +AllFn = ExprFn | BoolFn +AllFn2 = ExprFn2 | BoolFn2 + + +@dataclasses.dataclass(frozen=True) +class ValueRanges(Generic[_T]): + if TYPE_CHECKING: + # ruff doesn't understand circular references but mypy does + # pyrefly: ignore [unbound-name] + ExprVR = ValueRanges[sympy.Expr] # noqa: F821 + # pyrefly: ignore [unbound-name] + BoolVR = ValueRanges[SympyBoolean] # noqa: F821 + AllVR = ExprVR | BoolVR + + # Although the type signature here suggests you can pass any + # sympy expression, in practice the analysis here only works + # with constant sympy expressions + lower: _T + upper: _T + is_bool: bool + is_int: bool + is_float: bool + + def __repr__(self) -> str: + return f"VR[{self.lower}, {self.upper}]" + + @overload + def __init__( + self: ValueRanges[sympy.Expr], + lower: ExprIn, + upper: ExprIn, + ) -> None: ... + + @overload + def __init__( # type: ignore[misc] + self: ValueRanges[SympyBoolean], + lower: BoolIn, + upper: BoolIn, + ) -> None: ... + + def __init__(self, lower: AllIn, upper: AllIn) -> None: + lower = simple_sympify(lower) + upper = simple_sympify(upper) + # TODO: when the bounds have free variables, this may be + # nontrivial to actually verify + try: + if not sympy_generic_le(lower, upper): + raise ValueRangeError(f"Invalid ranges [{lower}:{upper}]") + except TypeError as e: + raise TypeError(f"Could not compare {lower} <= {upper}") from e + + is_bool_lower = isinstance(lower, SympyBoolean) + is_bool_upper = isinstance(upper, SympyBoolean) + if is_bool_lower != is_bool_upper: + raise AssertionError((lower, upper)) + + # Warning: is_int/is_float is best effort. We do pretty well in + # Dynamo, but in Inductor these attributes are often wrong because we + # are not very rigorous in dtype analysis. This is also why we need + # the flexible analysis for is_int: sometimes a sympy.oo pops in for + # an integer bound. I would /like/ for us not to do this, but it's + # too hard to push the invariant through right now. + if isinstance(lower, sympy.Integer) and upper == sympy.oo: + upper = int_oo + if isinstance(upper, sympy.Integer) and lower == -sympy.oo: + lower = -int_oo + # NB: [-int_oo, -int_oo] and [int_oo, int_oo] are allowed + integer_types = (sympy.Integer, NegativeIntInfinity, IntInfinity) + is_int_lower = isinstance(lower, integer_types) + is_int_upper = isinstance(upper, integer_types) + + # Because this is a frozen class + object.__setattr__(self, "lower", lower) + object.__setattr__(self, "upper", upper) + # Unlike bool/int in Python, we don't report bools are ints + # + # NB: is_bool_lower == is_bool_upper, so we only need to check one + object.__setattr__(self, "is_bool", is_bool_lower) + object.__setattr__( + self, + "is_int", + not self.is_bool and is_int_lower and is_int_upper, + ) + """ + # This assert is just impossible right now, too many sympy bugs + if self.is_int: + # NB: sympy will sometimes randomly lose the float-ness of zero, + # so we also need to account for that in the assertion here. + # See also https://github.com/sympy/sympy/issues/26620 + assert isinstance(lower, sympy.Integer) or lower in [-sympy.oo, 0], ( + lower, + upper, + ) + assert isinstance(upper, sympy.Integer) or upper in [sympy.oo, 0], (lower, upper) + """ + # NB: [-oo, oo] always advertises as float! + object.__setattr__(self, "is_float", not self.is_bool and not self.is_int) + if not self.is_bool and not self.is_int and not self.is_float: + raise AssertionError((lower, upper)) + + def boolify(self) -> ValueRanges[SympyBoolean]: + if vr_is_bool(self): + return self + elif self == ValueRanges.unknown(): + return ValueRanges.unknown_bool() + else: + raise AssertionError(f"not bool like {self}") + + def __contains__(self, x: AllIn) -> bool: + return ValueRanges.wrap(x).issubset(self) + + def issubset(self, other): + if other is self.unknown_int(): + return True + return sympy_generic_le(other.lower, self.lower) and sympy_generic_le( + self.upper, other.upper + ) + + def tighten(self, other) -> ValueRanges: + """Given two ValueRanges, returns their intersection""" + return self & other + + # Intersection + @overload + def __and__( + self: ValueRanges[sympy.Expr], + other: ValueRanges[sympy.Expr], + ) -> ValueRanges[sympy.Expr]: ... + + @overload + def __and__( # type: ignore[misc] + self: ValueRanges[SympyBoolean], + other: ValueRanges[SympyBoolean], + ) -> ValueRanges[SympyBoolean]: ... + + def __and__(self: AllVR, other: AllVR) -> AllVR: + if other in (ValueRanges.unknown(), ValueRanges.unknown_int()): + return self + if self in (ValueRanges.unknown(), ValueRanges.unknown_int()): + return other + if self.is_bool != other.is_bool: + raise AssertionError((self, other)) + if self.is_int != other.is_int: + raise AssertionError((self, other)) + if self.is_float != other.is_float: + raise AssertionError((self, other)) + if self.is_bool: + return ValueRanges( + sympy.Or(self.lower, other.lower), sympy.And(self.upper, other.upper) + ) + else: + return ValueRanges( + sympy.Max(self.lower, other.lower), sympy.Min(self.upper, other.upper) + ) + + # Union + @overload + def __or__( + self: ValueRanges[sympy.Expr], + other: ValueRanges[sympy.Expr], + ) -> ValueRanges[sympy.Expr]: ... + + @overload + def __or__( # type: ignore[misc] + self: ValueRanges[SympyBoolean], + other: ValueRanges[SympyBoolean], + ) -> ValueRanges[SympyBoolean]: ... + + def __or__(self: AllVR, other: AllVR) -> AllVR: + if ValueRanges.unknown() in (self, other): + return ValueRanges.unknown() + if self.is_bool != other.is_bool: + raise AssertionError((self, other)) + if self.is_int != other.is_int: + raise AssertionError((self, other)) + if self.is_float != other.is_float: + raise AssertionError((self, other)) + if self.is_bool: + return ValueRanges( + sympy.And(self.lower, other.lower), sympy.Or(self.upper, other.upper) + ) + else: + return ValueRanges( + sympy.Min(self.lower, other.lower), sympy.Max(self.upper, other.upper) + ) + + def is_singleton(self) -> bool: + return self.lower == self.upper + + @staticmethod + @functools.cache + def unknown() -> ValueRanges[sympy.Expr]: + return ValueRanges(-sympy.oo, sympy.oo) + + @staticmethod + @functools.cache + def unknown_int() -> ValueRanges[sympy.Expr]: + return ValueRanges(-int_oo, int_oo) + + @staticmethod + @functools.cache + def unknown_bool() -> ValueRanges[SympyBoolean]: + return ValueRanges(sympy.false, sympy.true) + + @overload + @staticmethod + # work around the fact that bool and int overlap + def wrap(arg: ExprIn | ExprVR) -> ExprVR: # type: ignore[overload-overlap] + ... + + @overload + @staticmethod + def wrap(arg: BoolIn | BoolVR) -> BoolVR: # type: ignore[misc] + ... + + @staticmethod + def wrap(arg: AllIn | AllVR) -> AllVR: + if isinstance(arg, ValueRanges): + return arg + if isinstance(arg, float) and math.isnan(arg): + return ValueRanges.unknown() + # arg is either ExprIn or BoolIn, but we don't know it here + return ValueRanges(arg, arg) # type: ignore[arg-type] + + @staticmethod + def increasing_map(x: ExprIn | ExprVR, fn: ExprFn) -> ExprVR: + """Increasing: x <= y => f(x) <= f(y).""" + x = ValueRanges.wrap(x) + return ValueRanges(fn(x.lower), fn(x.upper)) + + @overload + @staticmethod + def decreasing_map(x: ExprIn | ExprVR, fn: ExprFn) -> ExprVR: ... + + @overload + @staticmethod + def decreasing_map(x: BoolIn | BoolVR, fn: BoolFn) -> BoolVR: # type: ignore[misc] + ... + + @staticmethod + def decreasing_map(x: AllIn | AllVR, fn: AllFn) -> AllVR: + """Decreasing: x <= y => f(x) >= f(y).""" + x = ValueRanges.wrap(x) + # consistently either Expr or Bool, but we don't know it here + return ValueRanges(fn(x.upper), fn(x.lower)) # type: ignore[arg-type] + + @staticmethod + def monotone_map(x: ExprIn | ExprVR, fn: ExprFn) -> ExprVR: + """It's increasing or decreasing.""" + x = ValueRanges.wrap(x) + l = fn(x.lower) + u = fn(x.upper) + return ValueRanges(min(l, u), max(l, u)) + + @staticmethod + def convex_min_zero_map(x: ExprIn | ExprVR, fn: ExprFn) -> ExprVR: + """Fn is convex and has a minimum at 0.""" + x = ValueRanges.wrap(x) + if 0 in x: + upper = max(fn(x.lower), fn(x.upper)) + upper = simple_sympify(upper) + if isinstance(upper, sympy.Float) or upper == sympy.oo: + return ValueRanges(0.0, upper) + return ValueRanges(0, upper) + return ValueRanges.monotone_map(x, fn) + + @overload + @staticmethod + def coordinatewise_increasing_map( + x: ExprIn | ExprVR, + y: ExprIn | ExprVR, + fn: ExprFn2, + ) -> ExprVR: ... + + @overload + @staticmethod + def coordinatewise_increasing_map( # type: ignore[misc] + x: BoolIn | BoolVR, + y: BoolIn | BoolVR, + fn: BoolFn2, + ) -> BoolVR: ... + + @staticmethod + def coordinatewise_increasing_map( + x: AllIn | AllVR, + y: AllIn | AllVR, + fn: AllFn2, + ) -> AllVR: + """ + It's increasing on each coordinate. + + Mathematically: + For every 1 <= i <= n and x_i <= y_i we have that + f(x1, .., xn) <= f(x1, , yi, ..., xn) + """ + x, y = ValueRanges.wrap(x), ValueRanges.wrap(y) + return ValueRanges( + fn(x.lower, y.lower), # type: ignore[arg-type] + fn(x.upper, y.upper), # type: ignore[arg-type] + ) + + @classmethod + def coordinatewise_monotone_map(cls, x, y, fn): + """It's increasing or decreasing on each coordinate.""" + x, y = cls.wrap(x), cls.wrap(y) + products = [ + fn(a, b) + for a, b in itertools.product([x.lower, x.upper], [y.lower, y.upper]) + ] + return ValueRanges(min(products), max(products)) + + +class SymPyValueRangeAnalysis: + """ + It gives bounds on a SymPy operator given bounds on its arguments + See the function `bound_sympy` for a function that applies this logic to a full SymPy expression + """ + + @staticmethod + def constant(value, dtype): + if isinstance(value, ValueRanges): + if not value.is_singleton(): + raise AssertionError("ValueRanges must be a singleton for constant()") + value = value.lower + # NB: value is NOT a sympy expression, it's a constant! + is_python = isinstance(value, (int, float, bool)) + if not is_python and not isinstance( + value, (BooleanAtom, sympy.Integer, sympy.Number) + ): + raise AssertionError(f"not a supported constant type: {type(value)}") + + # using nan makes subsequent computation throw, and for the purposes of optimization + # returning -math.inf - math.inf is equivalent to giving up + if isinstance(value, SupportsFloat) and math.isnan(value): + if dtype == torch.bool: + return ValueRanges.unknown_bool() + elif dtype.is_floating_point: + return ValueRanges.unknown() + else: + return ValueRanges.unknown_int() + + if is_python: + type_ = dtype_to_type(dtype) + value = type_(value) + else: + # We do a type check on a best-effort basis + # We don't want to force a cast to sympy.Float if the value is Rational to avoid losing precision + if dtype == torch.bool: + if not isinstance(value, BooleanAtom): + raise AssertionError("expected BooleanAtom for bool dtype") + elif dtype.is_floating_point: + # pyrefly: ignore [missing-attribute] + if value.is_finite and not value.is_real: + raise AssertionError( + "expected float-like sympy value for float dtype" + ) + else: + # dtype is intXX + if not getattr(value, "is_integer", False): + raise AssertionError("expected integer sympy value for int dtype") + + r = ValueRanges.wrap(value) + return r + + @staticmethod + def to_dtype(a, dtype, src_dtype=None): + if dtype == torch.float64: + # pyrefly: ignore [bad-argument-type] + return ValueRanges.increasing_map(a, ToFloat) + elif dtype == torch.bool: + return ValueRanges.unknown_bool() + elif not dtype.is_floating_point: + return ValueRanges.unknown_int() + return ValueRanges.unknown() + + @staticmethod + def trunc_to_int(a, dtype): + # pyrefly: ignore [bad-argument-type] + return ValueRanges.increasing_map(a, TruncToInt) + + @staticmethod + def not_(a): + a = ValueRanges.wrap(a) + a = a.boolify() + if not a.is_bool: + raise AssertionError("not_ expects a boolean ValueRanges") + return ValueRanges.decreasing_map(a, sympy.Not) + + @staticmethod + def or_(a, b): + return ValueRanges.coordinatewise_increasing_map(a, b, sympy.Or) + + @staticmethod + def and_(a, b): + return ValueRanges.coordinatewise_increasing_map(a, b, sympy.And) + + @staticmethod + def _bool_to_int(x): + if x.is_singleton(): + return ValueRanges.wrap(sympy.Integer(1 if x.lower else 0)) + else: + return ValueRanges(sympy.Integer(0), sympy.Integer(1)) + + @classmethod + def bitwise_and(cls, a, b): + a, b = ValueRanges.wrap(a), ValueRanges.wrap(b) + if a.is_bool and b.is_bool: + return cls.and_(a, b) + if a.is_bool: + a = cls._bool_to_int(a) + if b.is_bool: + b = cls._bool_to_int(b) + lower = min(a.lower, b.lower) + if lower < 0 and lower != -sympy.oo and lower != -int_oo: + # If both lower bounds are negative, then bits start like + # 1...10..., so the smallest possible value is 1...101...1. + # Thus, we need to find the next smallest power of 2 (inclusive). + try: + lower = -(1 << int(-lower - 1).bit_length()) + except Exception: + lower = -int_oo + else: + lower = 0 + return ValueRanges(lower, max(a.upper, b.upper)) + + @classmethod + def bitwise_or(cls, a, b): + a, b = ValueRanges.wrap(a), ValueRanges.wrap(b) + if a.is_bool and b.is_bool: + return cls.or_(a, b) + if a.is_bool: + a = cls._bool_to_int(a) + if b.is_bool: + b = cls._bool_to_int(b) + upper = max(a.upper, b.upper) + if upper == 0: + upper = 0 + elif upper > 0 and upper != sympy.oo and upper != int_oo: + # If both upper bounds are positive, then the largest + # possible value is 01...1, so we need to find + # next largest power of 2 (exclusive), minus 1 + try: + upper = (1 << int(upper).bit_length()) - 1 + except Exception: + upper = int_oo + elif upper < 0: + upper = -1 + return ValueRanges(min(a.lower, b.lower), upper) + + @classmethod + def bitwise_xor(cls, a, b): + a, b = ValueRanges.wrap(a), ValueRanges.wrap(b) + if a.is_bool and b.is_bool: + bounds = { + a.lower ^ b.lower, + a.lower ^ b.upper, + a.upper ^ b.lower, + a.upper ^ b.upper, + } + + has_false = any(bound == sympy.false for bound in bounds) + has_true = any(bound == sympy.true for bound in bounds) + + if has_false and has_true: + lower, upper = sympy.false, sympy.true + elif has_true: + lower = upper = sympy.true + elif has_false: + lower = upper = sympy.false + else: + raise AssertionError(f"Non-boolean xor result: {bounds}") + + return ValueRanges(lower, upper) + if a.is_bool: + a = cls._bool_to_int(a) + if b.is_bool: + b = cls._bool_to_int(b) + if ( + a.lower == a.upper + and b.lower == b.upper + and is_sympy_integer(a.lower) + and is_sympy_integer(b.lower) + ): + value_range = a.lower ^ b.lower + return ValueRanges(value_range, value_range) + return ValueRanges(-int_oo, int_oo) + + @classmethod + def eq(cls, a, b): + a = ValueRanges.wrap(a) + b = ValueRanges.wrap(b) + if a.is_singleton() and b.is_singleton() and a.lower == b.lower: + return ValueRanges.wrap(sympy.true) + # sympy booleans do not support ordered comparison (bool >/< raises), so + # map them to {0, 1} before the disjoint-range test below. + if a.is_bool: + a = cls._bool_to_int(a) + if b.is_bool: + b = cls._bool_to_int(b) + if a.lower > b.upper or b.lower > a.upper: # ranges disjoint + return ValueRanges.wrap(sympy.false) + return ValueRanges(sympy.false, sympy.true) + + @classmethod + def ne(cls, a, b): + return cls.not_(cls.eq(a, b)) + + @classmethod + def identity(cls, a): + return ValueRanges.wrap(a) + + @classmethod + def lt(cls, a, b): + a = ValueRanges.wrap(a) + b = ValueRanges.wrap(b) + if a.is_bool != b.is_bool: + raise AssertionError( + "operands must both be boolean ValueRanges or both non-boolean" + ) + if a.is_bool: + return cls.and_(cls.not_(a), b) + else: + if a.upper < b.lower: + return ValueRanges.wrap(sympy.true) + elif a.lower >= b.upper: + return ValueRanges.wrap(sympy.false) + return ValueRanges(sympy.false, sympy.true) + + @classmethod + def gt(cls, a, b): + return cls.lt(b, a) + + @classmethod + def le(cls, a, b): + return cls.not_(cls.gt(a, b)) + + @classmethod + def ge(cls, a, b): + return cls.not_(cls.lt(a, b)) + + @staticmethod + def add(a, b): + return ValueRanges.coordinatewise_increasing_map( + a, b, _keep_float(operator.add) + ) + + @classmethod + def mul(cls, a, b): + a = ValueRanges.wrap(a) + b = ValueRanges.wrap(b) + + if a.is_bool != b.is_bool: + raise AssertionError( + "operands must both be boolean ValueRanges or both non-boolean" + ) + if a.is_bool: + return cls.and_(a, b) + + def safe_mul(a, b): + # Make unknown() * wrap(0.0) == wrap(0.0) + if a == 0.0 or a == 0: + return a + elif b == 0.0 or b == 0: + return b + else: + return a * b + + return ValueRanges.coordinatewise_monotone_map(a, b, _keep_float(safe_mul)) + + @staticmethod + def int_truediv(a, b): + a = ValueRanges.wrap(a) + b = ValueRanges.wrap(b) + if 0 in b or ((-int_oo in a or int_oo in a) and (-int_oo in b or int_oo in b)): + return ValueRanges.unknown() + else: + return ValueRanges.coordinatewise_monotone_map( + a, + b, + _keep_float(IntTrueDiv), + ) + + @staticmethod + def truediv(a, b): + a = ValueRanges.wrap(a) + b = ValueRanges.wrap(b) + if 0 in b or ( + (-sympy.oo in a or sympy.oo in a) and (-sympy.oo in b or sympy.oo in b) + ): + return ValueRanges.unknown() + else: + return ValueRanges.coordinatewise_monotone_map( + a, + b, + _keep_float(FloatTrueDiv), + ) + + @staticmethod + def floordiv(a, b): + a = ValueRanges.wrap(a) + b = ValueRanges.wrap(b) + + # TODO We shall assume division is always valid probably. + if 0 in b: + if b.lower >= 0 and a.lower >= 0: + return ValueRanges(0, int_oo) + if b.upper <= 0 and a.upper <= 0: + return ValueRanges(0, int_oo) + if b.upper <= 0 and a.lower >= 0: + return ValueRanges(-int_oo, 0) + if b.lower >= 0 and a.upper <= 0: + return ValueRanges(-int_oo, 0) + return ValueRanges.unknown_int() + products = [] + for x, y in itertools.product([a.lower, a.upper], [b.lower, b.upper]): + r = FloorDiv(x, y) + if r is sympy.nan: + products.append((sympy.sign(x) * sympy.sign(y)) * int_oo) + else: + products.append(r) + + return ValueRanges(min(products), max(products)) + + @classmethod + def mod(cls, x, y): + x = ValueRanges.wrap(x) + y = ValueRanges.wrap(y) + # nb. We implement C semantics + + def c_mod(a, b): + ret = abs(a) % abs(b) + if a < 0: + ret *= -1 + return ret + + def c_div(a, b): + x = a / b + return sympy.Integer(x) if x.is_finite and x not in (int_oo, -int_oo) else x + + if 0 in y: + return ValueRanges.unknown_int() + elif y.is_singleton(): + y_val = abs(y.lower) + # If it wraps, we need to take the whole interval + + # The function is locally linear if they are in the same class + if c_div(x.lower, y_val) == c_div(x.upper, y_val): + return ValueRanges.increasing_map(x, lambda u: c_mod(u, y_val)) + if x.upper < 0: + # Negative case + return ValueRanges(-y_val + 1, 0) + elif x.lower > 0: + # Positive case + return ValueRanges(0, y_val - 1) + else: + # Mixed case + lower = max(-y_val + 1, x.lower) + upper = min(y_val - 1, x.upper) + return ValueRanges(lower, upper) + else: + # Too difficult, we bail out + upper = cls.abs(y).upper - 1 + return ValueRanges(-upper, upper) + + @classmethod + def python_mod(cls, x, y): + """Python-style modulo: result has same sign as divisor. + + Assumes valid input where y is never 0. + - When y > 0: result is in [0, y - 1] + - When y < 0: result is in [y + 1, 0] + """ + + x = ValueRanges.wrap(x) + y = ValueRanges.wrap(y) + if x.lower >= 0 and y.lower >= 0: + return SymPyValueRangeAnalysis.mod(x, y) + lower = y.lower + 1 if y.lower < 0 else 0 + upper = y.upper - 1 if y.upper > 0 else 0 + return ValueRanges(lower, upper) + + @classmethod + def modular_indexing(cls, a, b, c): + return cls.mod(cls.floordiv(a, b), c) + + @classmethod + def is_non_overlapping_and_dense_indicator(cls, *args): + return ValueRanges.unknown_int() + + @classmethod + def pow_by_natural(cls, a, b): + a = ValueRanges.wrap(a) + b = ValueRanges.wrap(b) + if a.is_singleton() and b.is_singleton(): + return ValueRanges.wrap(safe_pow(a.lower, b.lower)) + # NB: Exclude zero, because zero is special + elif a.lower >= 1: + # We should know that b >= 0 but we may have forgotten this fact due + # to replacements, so don't assert it, but DO clamp it to prevent + # degenerate problems + # pyrefly: ignore [no-matching-overload] + return ValueRanges.coordinatewise_increasing_map( + a, b & ValueRanges(0, int_oo), PowByNatural + ) + elif b.is_singleton(): + if b.lower % 2 == 0: + # x^n where n is even + return ValueRanges.convex_min_zero_map( + a, lambda x: safe_pow(x, b.lower) + ) + else: + # x^n where n is odd + return ValueRanges.increasing_map(a, lambda x: safe_pow(x, b.lower)) + else: + # a is potentially negative, and we don't know if the exponent is + # even or odd. So just conservatively set the upper and lower + # bound based on what the maximum absolute value could be, in both + # directions + max_base = max(a.upper, -a.lower) + return ValueRanges( + -(safe_pow(max_base, b.upper)), safe_pow(max_base, b.upper) + ) + + @classmethod + def pow(cls, a, b): + return ValueRanges.unknown() + + # We could implement all this, but for floating point pow, is there + # really a point? + """ + a = ValueRanges.wrap(a) + b = ValueRanges.wrap(b) + + # Not implemented yet. It's a bit tricky + # If you want to implement it, compute the partial derivatives of a ** b + # and check the ranges where the function is increasing / decreasing + # Another non-tight way of doing this is defaulting to doing noting that for a > 0, a ** b == exp(b * log(a)) + # If this second option is implemented, be careful about the types and possible infinities here and there. + if not b.is_singleton(): + return ValueRanges.unknown() + + b = b.lower + if a.is_singleton(): + a = a.lower + r = a**b + if not r.is_finite: + return ValueRanges.unknown() + return ValueRanges.wrap(r) + + if b == 0: + if not a.lower.is_finite: + return ValueRanges.unknown() + return ValueRanges.wrap(1.0) + + if b < 0: + a = cls.reciprocal(a) + b = -b + + if a == ValueRanges.unknown(): + return ValueRanges.unknown() + + # If the base is positive, then we're good, otherwise nothing's defined + if a.lower >= 0: + return ValueRanges.increasing_map(a, lambda x: x**b) + else: + return ValueRanges.unknown() + """ + + @staticmethod + def reciprocal(x): + """Needed as it's used in pow, but it won't appear on a SymPy expression""" + x = ValueRanges.wrap(x) + if 0 in x: + return ValueRanges.unknown() + else: + return ValueRanges.decreasing_map(x, lambda y: FloatTrueDiv(1.0, y)) # type: ignore[operator] + + @staticmethod + def abs(x): + return ValueRanges.convex_min_zero_map(x, abs) + + @staticmethod + def exp(x): + return ValueRanges.increasing_map(x, OpaqueUnaryFn_exp) + + @staticmethod + def log(x): + x = ValueRanges.wrap(x) + if x.lower <= 0: + return ValueRanges.unknown() + return ValueRanges.increasing_map(x, OpaqueUnaryFn_log) + + @staticmethod + def log2(x): + x = ValueRanges.wrap(x) + if x.lower <= 0: + return ValueRanges.unknown() + return ValueRanges.increasing_map(x, OpaqueUnaryFn_log2) + + @classmethod + def minimum(cls, a, b): + a, b = ValueRanges.wrap(a), ValueRanges.wrap(b) + if a.is_bool != b.is_bool: + raise AssertionError( + "operands must both be boolean ValueRanges or both non-boolean" + ) + if a.is_bool: + return cls.and_(a, b) + return cls.min_or_max(a, b, sympy.Min) + + @classmethod + def maximum(cls, a, b): + a, b = ValueRanges.wrap(a), ValueRanges.wrap(b) + if a.is_bool != b.is_bool: + raise AssertionError( + "operands must both be boolean ValueRanges or both non-boolean" + ) + if a.is_bool: + return cls.or_(a, b) + return cls.min_or_max(a, b, sympy.Max) + + @staticmethod + def min_or_max(a, b, fn): + a = ValueRanges.wrap(a) + b = ValueRanges.wrap(b) + return ValueRanges.coordinatewise_increasing_map(a, b, fn) + + @classmethod + def floor_to_int(cls, x, dtype): + return ValueRanges.increasing_map(x, sympy.functions.elementary.integers.floor) + + @classmethod + def ceil_to_int(cls, x, dtype): + return ValueRanges.increasing_map( + x, sympy.functions.elementary.integers.ceiling + ) + + # I think these implementations are sound. The hazard here is that sympy + # will carry out the floor/ceil at too high precision and then something + # bad will happen when we convert it to float. + # + # For truncation, the implementation is clearly sound, because the desired + # target float is always exactly representable, since you're just chopping + # off bits the mantissa. But what about ceil/floor? + # + # The important constraint here is that we're not defining floor on + # arbitrary real numbers, only representable float numbers. So we can + # take advantage of the fact that before we reach the first + # unrepresentable integer in floating point space, we have the range of + # numbers corresponding to exponent zero: all integers, with no fractional + # amounts. floor/ceil is an identity operation in this case. In the + # range below here, representable floating point numbers are spaced + # exactly 1/2 apart, and notably, both the floor/ceil are defined floating + # point numbers. There is no "gap" as you step up to the next exponent. + + @classmethod + def floor(cls, x): + return ValueRanges.increasing_map( + x, _keep_float(sympy.functions.elementary.integers.floor) + ) + + @classmethod + def ceil(cls, x): + return ValueRanges.increasing_map( + x, _keep_float(sympy.functions.elementary.integers.ceiling) + ) + + @classmethod + def round_decimal(cls, number, ndigits): + if not ndigits.is_singleton(): + return ValueRanges.unknown() + + ndigits = ndigits.lower + # We can't use functools.partial here since sympy doesn't support keyword arguments, but we have to bind + # the second parameter. + fn = lambda number: RoundDecimal(number, ndigits) # type: ignore[misc, assignment] # noqa: E731 + + return ValueRanges.increasing_map(number, fn) + + @classmethod + def round_to_int(cls, number, dtype): + # pyrefly: ignore [bad-argument-type] + return ValueRanges.increasing_map(number, RoundToInt) + + # It's used in some models on symints + @staticmethod + def sqrt(x): + x = ValueRanges.wrap(x) + if x.lower < 0: + return ValueRanges.unknown() + return ValueRanges.increasing_map(x, OpaqueUnaryFn_sqrt) + + @staticmethod + def where(a, b, c): + b = ValueRanges.wrap(b) + c = ValueRanges.wrap(c) + a = a.boolify() + # We sometimes write unknown without specifying the type correctly + # In particular, we do that when initialising the bounds for loads in bounds.py + if b.is_bool != c.is_bool and ValueRanges.unknown() not in (b, c): + raise AssertionError( + "where() requires b and c to have the same boolean-ness or allow unknown()" + ) + if b.is_bool: + return ValueRanges(sympy.And(b.lower, c.lower), sympy.Or(b.upper, c.upper)) + else: + return ValueRanges(sympy.Min(b.lower, c.lower), sympy.Max(b.upper, c.upper)) + + # expr_cond_pair is used to represent a single (expr, condition) pair in piecewise. + # We just return the value range of the expression and its corresponding condition as a tuple + # and defer the analysis to piecewise + @staticmethod + def expr_cond_pair(a, b): + b = b.boolify() + return (a, b) + + # piecewise function can be used to convert a SymBool to SymInt: + # int_expr = Piecewise((1, bool_expr), (0, True)), it evaluates to 1 when sym_bool is True and 0 otherwise. + # + # ranges is a sequence of (expr_range, condition_range) pairs. The range pair is constructed in expr_cond_pair. + # The ValueRange of Piecewise is just the union of all expr ranges whose condition expr can be True. + @staticmethod + def piecewise(*ranges): + init_range = None + for expr_range, cond_range in ranges: + if sympy.true in cond_range: + if init_range is None: + init_range = expr_range + else: + init_range = init_range | expr_range + return init_range + + @staticmethod + def cos(x): + # TODO: We should tighten value ranges + # If input range span is pi + 2*pi*k, then output range is (-1, 1) + # otherwise the minimum of the value of the function on the extremes + return ValueRanges(-1.0, 1.0) + + @staticmethod + def cosh(x): + return ValueRanges(0.0, sympy.oo) + """ + x = ValueRanges.wrap(x) + if x.lower > 0: + return ValueRanges.increasing_map(x, OpaqueUnaryFn_cosh) + elif x.upper < 0: + return ValueRanges.decreasing_map(x, OpaqueUnaryFn_cosh) + return ValueRanges(0.0, sympy.oo) + """ + + @staticmethod + def sin(x): + # TODO: We should tighten value ranges + # See details on cos + return ValueRanges(-1.0, 1.0) + + @staticmethod + def sinh(x): + # return ValueRanges.increasing_map(x, OpaqueUnaryFn_sinh) + return ValueRanges(-sympy.oo, sympy.oo) + + @staticmethod + def tan(x): + return ValueRanges(-sympy.oo, sympy.oo) + + @staticmethod + def tanh(x): + # return ValueRanges.increasing_map(x, OpaqueUnaryFn_tanh) + return ValueRanges(-sympy.oo, sympy.oo) + + @staticmethod + def asin(x): + return ValueRanges(-sympy.oo, sympy.oo) + """ + x = ValueRanges.wrap(x) + if -1 <= x.lower and x.upper <= 1: + return ValueRanges.increasing_map(x, OpaqueUnaryFn_asinh) + return ValueRanges.unknown() + """ + + @staticmethod + def acos(x): + return ValueRanges(-sympy.oo, sympy.oo) + """ + x = ValueRanges.wrap(x) + if -1 <= x.lower and x.upper <= 1: + return ValueRanges.decreasing_map(x, OpaqueUnaryFn_acos) + return ValueRanges.unknown() + """ + + @staticmethod + def atan(x): + return ValueRanges(-sympy.oo, sympy.oo) + # return ValueRanges.increasing_map(x, OpaqueUnaryFn_atan) + + @staticmethod + def trunc(x): + # pyrefly: ignore [bad-argument-type] + return ValueRanges.increasing_map(x, TruncToFloat) + + +def _default_symbol_range(s: sympy.Symbol) -> ValueRanges: + if s.is_integer: + if s.is_positive: + return ValueRanges(1, int_oo) + if s.is_nonnegative: + return ValueRanges(0, int_oo) + return ValueRanges.unknown_int() + return ValueRanges.unknown() + + +def _bound_sympy_for_rewrite_guard( + expr: sympy.Expr, ranges: dict[sympy.Symbol, ValueRanges] +) -> ValueRanges | None: + try: + return sympy_interp( + SymPyValueRangeAnalysis, + ranges, + expr, + missing_handler=_default_symbol_range, + ) + except (AttributeError, KeyError, NotImplementedError): + return None + + +def _definitely_ge_value(value: sympy.Expr, lower: int) -> bool: + try: + return bool(value >= lower) + except TypeError: + return False + + +def _definitely_ge( + expr: sympy.Expr, lower: int, ranges: dict[sympy.Symbol, ValueRanges] +) -> bool: + if lower == 0 and expr.is_nonnegative: + return True + if lower == 1 and expr.is_positive: + return True + + if isinstance(expr, sympy.Symbol): + vr = ranges.get(expr) + if isinstance(vr, ValueRanges): + return bool(vr.lower >= lower) + + vr = _bound_sympy_for_rewrite_guard(expr, ranges) + return vr is not None and _definitely_ge_value(vr.lower, lower) + + +def _mod_rewrite_is_valid( + mod: type[sympy.Function], + base: sympy.Expr, + divisor: sympy.Expr, + ranges: dict[sympy.Symbol, ValueRanges], +) -> bool: + if not _definitely_ge(divisor, 1, ranges): + return False + return mod is PythonMod or _definitely_ge(base, 0, ranges) + + +def _rewrite_mod_subtraction( + base: sympy.Expr, + divisor: sympy.Expr, + coeff: sympy.Expr, +) -> sympy.Expr: + return coeff * FloorDiv(base, divisor) * divisor + + +def _terms_of_add(expr: sympy.Expr) -> dict[sympy.Expr, sympy.Expr]: + terms: dict[sympy.Expr, sympy.Expr] = {} + for term in sympy.Add.make_args(expr): + coeff, factor = term.as_coeff_Mul() + terms[factor] = terms.get(factor, sympy.S.Zero) + coeff + return terms + + +def _rewrite_mod_subtractions_in_add( + expr: sympy.Add, ranges: dict[sympy.Symbol, ValueRanges] +) -> sympy.Expr: + terms = _terms_of_add(expr) + + replacements = [] + for factor, mod_coeff in tuple(terms.items()): + if mod_coeff == 0 or mod_coeff.is_integer is not True: + continue + + mod = factor.func + if mod not in (PythonMod, Mod, sympy.Mod): + continue + + base, divisor = factor.args + if not _mod_rewrite_is_valid(mod, base, divisor, ranges): + continue + + matched_terms = [] + for base_factor, base_coeff in _terms_of_add(base).items(): + if base_coeff.is_integer is not True: + break + + term_coeff = terms.get(base_factor, sympy.S.Zero) + needed_coeff = -mod_coeff * base_coeff + if needed_coeff == 0: + continue + if term_coeff == 0 or term_coeff * needed_coeff <= 0: + break + if needed_coeff > 0 and term_coeff < needed_coeff: + break + if needed_coeff < 0 and term_coeff > needed_coeff: + break + + matched_terms.append((base_factor, needed_coeff)) + else: + for base_factor, needed_coeff in matched_terms: + terms[base_factor] -= needed_coeff + terms[factor] = sympy.S.Zero + replacements.append(_rewrite_mod_subtraction(base, divisor, -mod_coeff)) + + if not replacements: + return expr + + new_terms = [] + for factor, coeff in terms.items(): + if coeff == 0: + continue + if factor == 1: + new_terms.append(coeff) + elif coeff == 1: + new_terms.append(factor) + else: + new_terms.append(coeff * factor) + + return sympy.Add(*new_terms, *replacements) + + +def _rewrite_for_value_range_analysis( + expr: sympy.Basic, ranges: dict[sympy.Symbol, ValueRanges] +) -> sympy.Basic: + """Preserve simple dependencies that interval arithmetic would lose.""" + if not expr.args: + return expr + + args = tuple(_rewrite_for_value_range_analysis(arg, ranges) for arg in expr.args) + if args != expr.args: + expr = expr.func(*args) + + if isinstance(expr, sympy.Add): + return _rewrite_mod_subtractions_in_add(expr, ranges) + + return expr + + +def bound_sympy( + expr: sympy.Expr, ranges: dict[sympy.Symbol, ValueRanges] | None = None +) -> ValueRanges: + log.debug( + "bound_sympy(%s)%s", + expr, + LazyString( + lambda: ( + "\n" + + "\n".join( + f" {k}: {r}" for k, r in ranges.items() if k in expr.free_symbols + ) + if ranges + else "" + ) + ), + ) + if isinstance(expr, sympy.Number): + return ValueRanges.wrap(expr) + + ranges = ranges or {} + + # If there's a tracing context, augment available constrained ranges. + context = torch._guards.TracingContext.try_get() + if context and context.fake_mode and context.fake_mode.shape_env: + if ranges: + ranges = {**context.fake_mode.shape_env.var_to_range, **ranges} + else: + ranges = context.fake_mode.shape_env.var_to_range + + if expr.has(PythonMod, Mod, sympy.Mod): + expr = _rewrite_for_value_range_analysis(expr, ranges) + + return sympy_interp( + SymPyValueRangeAnalysis, ranges, expr, missing_handler=_default_symbol_range + ) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_thunk.py b/.venv/lib/python3.12/site-packages/torch/utils/_thunk.py new file mode 100644 index 0000000000000000000000000000000000000000..b5ab598077f4e8d3d9de9169a1352918771f07f6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_thunk.py @@ -0,0 +1,29 @@ +from collections.abc import Callable +from typing import Generic, TypeVar + + +R = TypeVar("R") + + +class Thunk(Generic[R]): + """ + A simple lazy evaluation implementation that lets you delay + execution of a function. It properly handles releasing the + function once it is forced. + """ + + f: Callable[[], R] | None + r: R | None + + __slots__ = ["f", "r"] + + def __init__(self, f: Callable[[], R]) -> None: + self.f = f + self.r = None + + def force(self) -> R: + if self.f is None: + return self.r # type: ignore[return-value] + self.r = self.f() + self.f = None + return self.r diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_traceback.py b/.venv/lib/python3.12/site-packages/torch/utils/_traceback.py new file mode 100644 index 0000000000000000000000000000000000000000..f5415002092a23350f7d7d3436388d34b1eb9501 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_traceback.py @@ -0,0 +1,260 @@ +# mypy: allow-untyped-defs +import contextlib +import inspect +import os.path +import tempfile +import traceback +from types import TracebackType + + +# This file contains utilities for ensuring dynamically compile()'d +# code fragments display their line numbers in backtraces. +# +# The constraints: +# +# - We don't have control over the user exception printer (in particular, +# we cannot assume the linecache trick will work, c.f. +# https://stackoverflow.com/q/50515651/23845 ) +# +# - We don't want to create temporary files every time we compile() +# some code; file creation should happen lazily only at exception +# time. Arguably, you *should* be willing to write out your +# generated Python code to file system, but in some situations +# (esp. library code) it would violate user expectation to write +# to the file system, so we try to avoid it. In particular, we'd +# like to keep the files around, so users can open up the files +# mentioned in the trace; if the file is invisible, we want to +# avoid clogging up the filesystem. +# +# If this is not a constraint for you, there is a substantially simpler +# way to implement the functionality in this PR: instead of using +# eval/exec directly, just always write a Python file to filesystem +# and compile that. +# +# - You have control over a context where the compiled code will get +# executed, so that we can interpose while the stack is unwinding +# (otherwise, we have no way to interpose on the exception printing +# process.) +# +# There are two things you have to do to make use of the utilities here: +# +# - When you compile your source code, you must save its string source +# in its f_globals under the magic name "__compile_source__" +# +# - Before running the compiled code, enter the +# report_compile_source_on_error() context manager. + + +@contextlib.contextmanager +def report_compile_source_on_error(): + try: + yield + except Exception as exc: + tb = exc.__traceback__ + + # Walk the traceback, looking for frames that have + # source attached + stack = [] + while tb is not None: + filename = tb.tb_frame.f_code.co_filename + source = tb.tb_frame.f_globals.get("__compile_source__") + + if filename == "" and source is not None: + # What black magic are we doing here? Intuitively, what + # we would like to do is overwrite the co_filename on any + # frames that were generated from exec/eval so that they + # point to a temporary file that has the actual line + # information, so Python's default error printer can print + # useful line information on it. + # + # Writing out the temporary file is easy. But overwriting + # co_filename is not! You can't modify the code object + # associated with a frame. You can, however, reconstruct + # a traceback with entirely new frames from scratch, so that's + # what we do. But there's another problem, which is how to + # make the frame? + # + # The black magic is we make a frankenstein frame and code + # object which resembles the original frame/code enough so + # that it will print properly under traceback and the default + # error printer, but IT IS NOT THE ORIGINAL FRAME (you + # couldn't, e.g., execute its code with different variables + # and expect it to work.) + + # Don't delete the temporary file so the user can inspect it + # TODO: This creates a temporary file for every frame, but we + # technically only need one per distinct __compile_source__ + with tempfile.NamedTemporaryFile( + mode="w", delete=False, suffix=".py" + ) as f: + f.write(source) + # Create a frame. Python doesn't let you construct + # FrameType directly, so just make one with compile + frame = tb.tb_frame + code = compile("__inspect_currentframe()", f.name, "eval") + code = code.replace(co_name=frame.f_code.co_name) + # Python 3.11 only + if hasattr(frame.f_code, "co_linetable"): + # We can't copy ALL of the metadata over, because you + # can cause Python to segfault this way. What exactly + # do we need? We need enough information for + # traceback to be able to print the exception + # correctly. Code reading Lib/traceback.py reveals + # that traceback calls code.co_positions() in order to + # get the augmented line/col numbers. Objects/codeobject.c, + # specifically _PyCode_InitAddressRange, reveals that + # this iterator is initialized from co_linetable and + # co_firstfileno. So copy these we must! + code = code.replace( # type: ignore[call-arg] + co_linetable=frame.f_code.co_linetable, # type: ignore[attr-defined] + co_firstlineno=frame.f_code.co_firstlineno, # type: ignore[attr-defined] + ) + fake_frame = eval( + code, + frame.f_globals, + {**frame.f_locals, "__inspect_currentframe": inspect.currentframe}, + ) + fake_tb = TracebackType(None, fake_frame, tb.tb_lasti, tb.tb_lineno) + stack.append(fake_tb) + else: + stack.append(tb) + + tb = tb.tb_next + + # Reconstruct the linked list + tb_next = None + for tb in reversed(stack): + tb.tb_next = tb_next + tb_next = tb + + raise exc.with_traceback(tb_next) # noqa: B904 + + +def shorten_filename(fn, *, base=None): + """Shorten a source filepath, with the assumption that torch/ subdirectories don't need to be shown to user.""" + if base is None: + base = os.path.dirname(os.path.dirname(__file__)) + # Truncate torch/foo.py to foo.py + try: + prefix = os.path.commonpath([fn, base]) + except ValueError: + return fn + else: + return fn[len(prefix) + 1 :] + + +def format_frame(frame, *, base=None, line=False) -> str: + """ + Format a FrameSummary in a short way, without printing full absolute path or code. + + The idea is the result fits on a single line. + """ + extra_line = "" + if line: + extra_line = f"{frame.line} # " + return f"{extra_line}{shorten_filename(frame.filename, base=base)}:{frame.lineno} in {frame.name}" + + +def format_traceback_short(tb): + """Format a TracebackType in a short way, printing only the inner-most frame.""" + return format_frame(traceback.extract_tb(tb)[-1]) + + +class CapturedTraceback: + __slots__ = ["tb", "skip"] + + def __init__(self, tb, skip=0) -> None: + self.tb = tb + self.skip = skip + + def cleanup(self) -> None: + self.tb = None + + def summary(self): + import torch._C._profiler + + if self.tb is None: + # TODO: Maybe indicate that the traceback was elided? + return traceback.StackSummary() + + return _extract_symbolized_tb( + torch._C._profiler.symbolize_tracebacks([self.tb])[0], self.skip + ) + + def __getstate__(self): + return ( + None, + { + "tb": None, # TB is not pickleable + "skip": self.skip, + }, + ) + + @staticmethod + def extract(*, script=False, cpp=False, skip=0): + """ + Like traceback.extract_stack(), but faster (approximately 20x faster); it + is fast enough that you can unconditionally log stacks this way as part of + normal execution. It returns a torch._C._profiler.CapturedTraceback + object that must be formatted specially with format_captured_tb. + + By default, this only reports Python backtraces (like extract_stack). You + can set the script/cpp kwargs to also turn on TorchScript/C++ trace + reporting. + """ + import torch._C._profiler + + if script or cpp: + if skip != 0: + raise AssertionError("skip with script/cpp NYI") + + return CapturedTraceback( + torch._C._profiler.gather_traceback(python=True, script=script, cpp=cpp), + # Elide extract() frame if we don't have script/cpp frames. If + # we do have those frames, it doesn't work so force zero. + 0 if script or cpp else skip + 1, + ) + + def format(self): + """ + Formats a single torch._C._profiler.CapturedTraceback into a list of + strings equivalent to the output of traceback.format_list. Note that if + pass it CapturedTraceback with C++ traces, it is better not to use this + function and use the batch formatting API format_captured_tbs to amortize + the cost of symbolization + """ + return traceback.format_list(self.summary()) + + @staticmethod + def format_all(tbs): + """ + Bulk version of CapturedTraceback.format. Returns a list of list of strings. + """ + import torch._C._profiler + + # Directly populate tracebacks that already have cached summaries + rs: list[list[str] | None] = [] + delayed_idxs = [] + for i, tb in enumerate(tbs): + if tb.tb is None: + rs.append([]) + else: + rs.append(None) + delayed_idxs.append(i) + + torch._C._profiler.symbolize_tracebacks([tbs[i].tb for i in delayed_idxs]) + for i in delayed_idxs: + rs[i] = traceback.format_list(tbs[i].summary()) + + return rs + + +def _extract_symbolized_tb(tb, skip): + """ + Given a symbolized traceback from symbolize_tracebacks, return a StackSummary object of + pre-processed stack trace entries. + """ + stack = traceback.StackSummary() + for f in reversed(tb[skip:]): + stack.append(traceback.FrameSummary(f["filename"], f["line"], f["name"])) + return stack diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_triton.py b/.venv/lib/python3.12/site-packages/torch/utils/_triton.py new file mode 100644 index 0000000000000000000000000000000000000000..a8e78dbda6ef5f42f9a756eb135cbea55e141dd9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_triton.py @@ -0,0 +1,282 @@ +import functools +import hashlib +import os +from typing import Any + + +_FAILED_TO_MAP_SEGMENT_FROM_SHARED_OBJECT = "failed to map segment from shared object" + + +def _triton_cache_dir_for_error_message() -> str | None: + if triton_cache_dir := os.environ.get("TRITON_CACHE_DIR"): + return triton_cache_dir + + try: + from triton.runtime.cache import knobs + + return knobs.cache.dir + except (AttributeError, ImportError): + return None + + +def _raise_triton_cache_load_error(exc: BaseException) -> None: + cache_dir = _triton_cache_dir_for_error_message() + if "TRITON_CACHE_DIR" in os.environ: + cache_dir_msg = f" (TRITON_CACHE_DIR={cache_dir})" + else: + cache_dir_msg = f" ({cache_dir})" if cache_dir else "" + raise ImportError( + f"{exc}. This usually means Triton's cache directory{cache_dir_msg} is on " + "a filesystem mounted with noexec, so the dynamic loader cannot map " + "generated shared objects. Set TRITON_CACHE_DIR to a directory on an " + "executable filesystem." + ) from exc + + +@functools.cache +def has_triton_package() -> bool: + try: + import triton # noqa: F401 + + return True + except ImportError: + return False + + +@functools.cache +def get_triton_version(fallback: tuple[int, int] = (0, 0)) -> tuple[int, int]: + try: + import triton + + major, minor = tuple(int(v) for v in triton.__version__.split(".")[:2]) + return (major, minor) + except ImportError: + return fallback + + +@functools.cache +def _device_supports_tensor_descriptor() -> bool: + import torch + + return ( + torch.cuda.is_available() + and torch.cuda.get_device_capability() >= (9, 0) + and not torch.version.hip + ) or has_triton_cpu_backend() + + +@functools.cache +def has_triton_cpu_backend() -> bool: + if has_triton_package(): + import triton + + return "cpu" in triton.backends.backends + + return False + + +@functools.cache +def has_triton_experimental_host_tma() -> bool: + if has_triton_package(): + if _device_supports_tensor_descriptor(): + try: + from triton.tools.experimental_descriptor import ( # noqa: F401 + create_1d_tma_descriptor, + create_2d_tma_descriptor, + ) + + try: + from triton.tools.experimental_descriptor import enable_in_pytorch + + return enable_in_pytorch() + except ImportError: + return True + except ImportError: + pass + + return False + + +@functools.cache +def has_triton_tensor_descriptor_host_tma() -> bool: + if has_triton_package(): + if _device_supports_tensor_descriptor(): + try: + from triton.tools.tensor_descriptor import ( # noqa: F401 + TensorDescriptor, + ) + + return True + except ImportError: + pass + + return False + + +@functools.cache +def has_triton_tma() -> bool: + return has_triton_tensor_descriptor_host_tma() or has_triton_experimental_host_tma() + + +@functools.cache +def has_triton_tma_device() -> bool: + if has_triton_package(): + import torch + + if ( + ( + torch.cuda.is_available() + and torch.cuda.get_device_capability() >= (9, 0) + and not torch.version.hip + ) + or torch.xpu.is_available() + or has_triton_cpu_backend() + ): + # old API + try: + from triton.language.extra.cuda import ( # noqa: F401 + experimental_device_tensormap_create1d, + experimental_device_tensormap_create2d, + ) + + return True + except ImportError: + pass + + # new API + try: + from triton.language import make_tensor_descriptor # noqa: F401 + + return True + except ImportError: + pass + + return False + + +@functools.cache +def has_datacenter_blackwell_tma_device() -> bool: + import torch + + if ( + torch.cuda.is_available() + and torch.cuda.get_device_capability() >= (10, 0) + and torch.cuda.get_device_capability() < (11, 0) + and not torch.version.hip + ): + return has_triton_tma_device() and has_triton_tensor_descriptor_host_tma() + + return False + + +@functools.lru_cache(None) +def has_triton_stable_tma_api() -> bool: + if has_triton_package(): + import torch + + if ( + ( + torch.cuda.is_available() + and torch.cuda.get_device_capability() >= (9, 0) + and not torch.version.hip + ) + or torch.xpu.is_available() + or has_triton_cpu_backend() + ): + try: + from triton.language import make_tensor_descriptor # noqa: F401 + + return True + except ImportError: + pass + return False + + +@functools.cache +def has_triton_reduction_ordering() -> bool: + """Whether the available Triton exposes inner-tree reduction ordering.""" + if has_triton_package(): + try: + from triton.language import ReductionOrdering + + return hasattr(ReductionOrdering, "INNER_TREE") + except ImportError: + pass + return False + + +@functools.cache +def has_triton() -> bool: + if not has_triton_package(): + return False + + from torch._inductor.config import triton_disable_device_detection + + if triton_disable_device_detection: + return False + + from torch._dynamo.device_interface import get_registered_device_interfaces + from torch._dynamo.exc import TritonUnavailableError + + # A device supports Triton if it is available, reports Triton capability, and + # its Triton backend is actually built. Capability is gated first so that + # raise_if_triton_unavailable() only surfaces missing-backend errors (and + # not, e.g., CUDA's GPUTooOldForTriton for sub-capable devices). We catch the + # specific TritonUnavailableError rather than RuntimeError so unexpected + # errors are not silently swallowed. + for name, device_interface in get_registered_device_interfaces(): + if ":" in name: + continue + if not ( + device_interface.is_available() and device_interface.is_triton_capable() + ): + continue + try: + device_interface.raise_if_triton_unavailable() + except TritonUnavailableError: + continue + return True + return False + + +@functools.cache +def triton_backend() -> Any: + from triton.compiler.compiler import make_backend + from triton.runtime.driver import driver + + try: + target = driver.active.get_current_target() + return make_backend(target) + except (ImportError, OSError) as e: + if _FAILED_TO_MAP_SEGMENT_FROM_SHARED_OBJECT in str(e): + _raise_triton_cache_load_error(e) + raise + + +def _extern_libs_key(backend: Any) -> str: + """Return a cache key fragment for extern libs (e.g. libdevice.10.bc). + + These files affect codegen but are not covered by triton_key() (Python + sources only) or backend.hash() (ptxas version and arch only). + """ + opts = backend.parse_options({}) + extern_libs = getattr(opts, "extern_libs", None) + if not extern_libs: + return "" + parts = [] + for name, path in sorted(extern_libs): + if os.path.isfile(path): + with open(path, "rb") as f: + parts.append(f"{name}-{hashlib.sha256(f.read()).hexdigest()}") + return "-".join(parts) + + +@functools.cache +def triton_hash_with_backend() -> str: + from torch._inductor.runtime.triton_compat import triton_key + + backend = triton_backend() + key = f"{triton_key()}-{backend.hash()}" + + # Hash is upper case so that it can't contain any Python keywords. + return hashlib.sha256(key.encode("utf-8")).hexdigest().upper() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_typing_utils.py b/.venv/lib/python3.12/site-packages/torch/utils/_typing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4c59ac453dd81aee9c9660edea5710ee86bbe185 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_typing_utils.py @@ -0,0 +1,76 @@ +"""Miscellaneous utilities to aid with typing.""" + +from collections.abc import Callable +from typing import Any, cast, Concatenate, TypeVar +from typing_extensions import ParamSpec + + +# Helper to turn Optional[T] into T when we know None either isn't +# possible or should trigger an exception. +T = TypeVar("T") + + +def not_none(obj: T | None) -> T: + if obj is None: + raise TypeError("Invariant encountered: value was None when it should not be") + return obj + + +_P = ParamSpec("_P") +_R = TypeVar("_R") +_A1 = TypeVar("_A1") + + +def copy_func_params( + source_func: Callable[_P, Any], +) -> Callable[[Callable[..., _R]], Callable[_P, _R]]: + """Cast the decorated function's call signature to the source_func's. + + Usage: + def upstream_func(a: int, b: float, *, double: bool = False) -> float: ... + @copy_func_params(upstream_func) + def enhanced(a: int, b: float, *args: Any, double: bool = False, **kwargs: Any) -> str: ... + """ + + def return_func(func: Callable[..., _R]) -> Callable[_P, _R]: + return cast(Callable[_P, _R], func) + + return return_func + + +def copy_method_params( + source_method: Callable[Concatenate[Any, _P], Any], +) -> Callable[[Callable[..., _R]], Callable[Concatenate[_A1, _P], _R]]: + """Cast the decorated *method*'s call signature to the source_method's. + Keeps the first argument type (e.g., self/cls). + """ + + def return_func(func: Callable[..., _R]) -> Callable[Concatenate[_A1, _P], _R]: + return cast(Callable[Concatenate[_A1, _P], _R], func) + + return return_func + + +# stricter variants to preserve the origin callers Return Type too. +# TODO: consider folding both these into the above variants with an optional +# parameter to control whether to copy the return type or not. +def copy_func_sig( + source_func: Callable[_P, _R], +) -> Callable[[Callable[..., _R]], Callable[_P, _R]]: + """Cast the decorated function's call signature and return type to the source_func's.""" + + def _return(func: Callable[..., _R]) -> Callable[_P, _R]: + return cast(Callable[_P, _R], func) + + return _return + + +def copy_method_sig( + source_method: Callable[Concatenate[_A1, _P], _R], +) -> Callable[[Callable[..., _R]], Callable[Concatenate[_A1, _P], _R]]: + """Cast the decorated *method*'s call signature to the source_method and return type.""" + + def _return(func: Callable[..., _R]) -> Callable[Concatenate[_A1, _P], _R]: + return cast(Callable[Concatenate[_A1, _P], _R], func) + + return _return diff --git a/.venv/lib/python3.12/site-packages/torch/utils/_zip.py b/.venv/lib/python3.12/site-packages/torch/utils/_zip.py new file mode 100644 index 0000000000000000000000000000000000000000..c4bfbcb0b9b637f82fba7c9722cd6fbc5690555c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/_zip.py @@ -0,0 +1,86 @@ +# mypy: allow-untyped-defs +import argparse +import glob +import os +from pathlib import Path +from zipfile import ZipFile + + +# Exclude some standard library modules to: +# 1. Slim down the final zipped file size +# 2. Remove functionality we don't want to support. +DENY_LIST = [ + # Interface to unix databases + "dbm", + # ncurses bindings (terminal interfaces) + "curses", + # Tcl/Tk GUI + "tkinter", + "tkinter", + # Tests for the standard library + "test", + "tests", + "idle_test", + "__phello__.foo.py", + # importlib frozen modules. These are already baked into CPython. + "_bootstrap.py", + "_bootstrap_external.py", +] + +strip_file_dir = "" + + +def remove_prefix(text, prefix): + if text.startswith(prefix): + return text[len(prefix) :] + return text + + +def write_to_zip(file_path, strip_file_path, zf, prepend_str="") -> None: + stripped_file_path = prepend_str + remove_prefix(file_path, strip_file_dir + "/") + path = Path(stripped_file_path) + if path.name in DENY_LIST: + return + zf.write(file_path, stripped_file_path) + + +def main() -> None: + global strip_file_dir + parser = argparse.ArgumentParser(description="Zip py source") + parser.add_argument("paths", nargs="*", help="Paths to zip.") + parser.add_argument( + "--install-dir", "--install_dir", help="Root directory for all output files" + ) + parser.add_argument( + "--strip-dir", + "--strip_dir", + help="The absolute directory we want to remove from zip", + ) + parser.add_argument( + "--prepend-str", + "--prepend_str", + help="A string to prepend onto all paths of a file in the zip", + default="", + ) + parser.add_argument("--zip-name", "--zip_name", help="Output zip name") + + args = parser.parse_args() + + zip_file_name = args.install_dir + "/" + args.zip_name + strip_file_dir = args.strip_dir + prepend_str = args.prepend_str + with ZipFile(zip_file_name, mode="w") as zf: + for p in sorted(args.paths): + if os.path.isdir(p): + files = glob.glob(p + "/**/*.py", recursive=True) + for file_path in sorted(files): + # strip the absolute path + write_to_zip( + file_path, strip_file_dir + "/", zf, prepend_str=prepend_str + ) + else: + write_to_zip(p, strip_file_dir + "/", zf, prepend_str=prepend_str) + + +if __name__ == "__main__": + main() # pragma: no cover diff --git a/.venv/lib/python3.12/site-packages/torch/utils/backcompat/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/backcompat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f6ec989be1e078ba857d30b06a91e1dc54131e4b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/backcompat/__init__.py @@ -0,0 +1,27 @@ +# mypy: allow-untyped-defs +from torch._C import ( + _get_backcompat_broadcast_warn, + _get_backcompat_keepdim_warn, + _set_backcompat_broadcast_warn, + _set_backcompat_keepdim_warn, +) + + +class Warning: + def __init__(self, setter, getter) -> None: + self.setter = setter + self.getter = getter + + def set_enabled(self, value) -> None: + self.setter(value) + + def get_enabled(self): + return self.getter() + + enabled = property(get_enabled, set_enabled) + + +broadcast_warning = Warning( + _set_backcompat_broadcast_warn, _get_backcompat_broadcast_warn +) +keepdim_warning = Warning(_set_backcompat_keepdim_warn, _get_backcompat_keepdim_warn) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/backcompat/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/backcompat/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52b6ef0cb74ee46e0b3f43230697b5ff104796ff Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/backcompat/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/backend_registration.py b/.venv/lib/python3.12/site-packages/torch/utils/backend_registration.py new file mode 100644 index 0000000000000000000000000000000000000000..cb0201564719b103f5234133d9d3272de49ad8bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/backend_registration.py @@ -0,0 +1,578 @@ +# mypy: allow-untyped-defs + +import torch +from torch._C import _get_privateuse1_backend_name, _rename_privateuse1_backend +from torch.overrides import handle_torch_function, has_torch_function_unary + + +__all__ = [ + "rename_privateuse1_backend", + "generate_methods_for_privateuse1_backend", +] + +# TODO: Should use `torch._C._get_privateuse1_backend_name()` to get +# renamed-backend name for `privateuse1`, but the func will cause an +# error with torch.jit.script, so we use the global variable named +# `_privateuse1_backend_name`. +_privateuse1_backend_name = "privateuseone" + + +def _rename_profiler_activity(backend_name: str) -> None: + """Mirror the privateuse1 rename in ProfilerActivity so users can write e.g. + ProfilerActivity. instead of ProfilerActivity.PrivateUse1.""" + from torch._C._profiler import ProfilerActivity + + alias = backend_name.upper() + setattr(ProfilerActivity, alias, ProfilerActivity.PrivateUse1) + + pu1 = ProfilerActivity.PrivateUse1 + original_repr = ProfilerActivity.__repr__ + original_str = ProfilerActivity.__str__ + + def custom_repr(self): + if self == pu1: + return f"" + return original_repr(self) + + def custom_str(self): + if self == pu1: + return f"ProfilerActivity.{alias}" + return original_str(self) + + ProfilerActivity.__repr__ = custom_repr + ProfilerActivity.__str__ = custom_str + ProfilerActivity.name = property( # type: ignore[assignment] + lambda self: alias if self == pu1 else original_str(self).split(".")[-1] + ) + + +def _rename_device_type(backend_name: str) -> None: + from torch._C._autograd import DeviceType + + alias = backend_name.upper() + setattr(DeviceType, alias, DeviceType.PrivateUse1) + + pu1 = DeviceType.PrivateUse1 + original_repr = DeviceType.__repr__ + original_str = DeviceType.__str__ + + def custom_repr(self): + if self == pu1: + return f"" + return original_repr(self) + + def custom_str(self): + if self == pu1: + return f"DeviceType.{alias}" + return original_str(self) + + DeviceType.__repr__ = custom_repr + DeviceType.__str__ = custom_str + DeviceType.name = property( # type: ignore[assignment] + lambda self: alias if self == pu1 else original_str(self).split(".")[-1] + ) + + +def rename_privateuse1_backend(backend_name: str) -> None: + r""" + Rename the privateuse1 backend device to make it more convenient to use as a device name within PyTorch APIs. + + The steps are: + + (1) (In C++) implement kernels for various torch operations, and register them + to the PrivateUse1 dispatch key. + (2) (In python) call torch.utils.rename_privateuse1_backend("foo") + + You can now use "foo" as an ordinary device string in python. + + Note: this API can only be called once per process. Attempting to change + the external backend after it's already been set will result in an error. + + Note(AMP): If you want to support AMP on your device, you can register a custom backend module. + The backend must register a custom backend module with ``torch._register_device_module("foo", BackendModule)``. + BackendModule needs to have the following API's: + + (1) ``get_amp_supported_dtype() -> List[torch.dtype]`` + get the supported dtypes on your "foo" device in AMP, maybe the "foo" device supports one more dtype. + + Note(random): If you want to support to set seed for your device, BackendModule needs to have the following API's: + + (1) ``_is_in_bad_fork() -> bool`` + Return ``True`` if now it is in bad_fork, else return ``False``. + + (2) ``manual_seed_all(seed int) -> None`` + Sets the seed for generating random numbers for your devices. + + (3) ``device_count() -> int`` + Returns the number of "foo"s available. + + (4) ``get_rng_state(device: Union[int, str, torch.device] = 'foo') -> Tensor`` + Returns a list of ByteTensor representing the random number states of all devices. + + (5) ``set_rng_state(new_state: Tensor, device: Union[int, str, torch.device] = 'foo') -> None`` + Sets the random number generator state of the specified "foo" device. + + And there are some common funcs: + + (1) ``is_available() -> bool`` + Returns a bool indicating if "foo" is currently available. + + (2) ``current_device() -> int`` + Returns the index of a currently selected device. + + For more details, see https://pytorch.org/tutorials/advanced/extend_dispatcher.html#get-a-dispatch-key-for-your-backend + For an existing example, see https://github.com/bdhirsh/pytorch_open_registration_example + + Example:: + + >>> # xdoctest: +SKIP("failing") + >>> torch.utils.rename_privateuse1_backend("foo") + # This will work, assuming that you've implemented the right C++ kernels + # to implement torch.ones. + >>> a = torch.ones(2, device="foo") + + """ + _rename_privateuse1_backend(backend_name) + global _privateuse1_backend_name + _privateuse1_backend_name = backend_name + _rename_profiler_activity(backend_name) + _rename_device_type(backend_name) + + +def _check_register_once(module, attr) -> None: + if hasattr(module, attr): + raise RuntimeError( + f"The custom device module of {module} has already been registered with {attr}" + ) + + +def _normalization_device( + custom_backend_name: str, device: int | str | torch.device | None = None +) -> int: + def _get_current_device_index(): + _get_device_index = "current_device" + if hasattr(torch, custom_backend_name) and hasattr( + getattr(torch, custom_backend_name), _get_device_index + ): + return getattr(getattr(torch, custom_backend_name), _get_device_index)() + else: + # The default device index is 0. + return 0 + + if device is None: + return _get_current_device_index() + # if isinstance(device, str), this means that the parameter passed in is in the string format "foo:0" + # convert str object to torch.device object, and then process it uniformly + elif isinstance(device, str): + device = torch.device(device) + + # variable device can only be torch.device type or int type + if isinstance(device, torch.device): + if device.type != custom_backend_name: + raise RuntimeError(f"Invalid device, must be {custom_backend_name} device") + elif device.index is None: + device_idx = _get_current_device_index() + else: + device_idx = device.index + # if isinstance(device, int), we can take the index number directly + else: + device_idx = device + return device_idx + + +def _generate_tensor_methods_for_privateuse1_backend(custom_backend_name: str) -> None: + @property # type: ignore[misc] + def wrap_tensor_backend(self: torch.Tensor) -> bool: + if has_torch_function_unary(self): + # TODO mypy doesn't support @property, see: https://github.com/python/mypy/issues/6185 + return handle_torch_function(wrap_tensor_backend.__get__, (self,), self) # type: ignore[attr-defined] + return self.device.type == custom_backend_name + + _check_register_once(torch.Tensor, f"is_{custom_backend_name}") + wrap_tensor_backend.fget.__name__ = f"is_{custom_backend_name}" # type: ignore[attr-defined] + setattr(torch.Tensor, f"is_{custom_backend_name}", wrap_tensor_backend) + + def wrap_tensor_to( + self: torch.Tensor, + device: int | torch.device | None = None, + non_blocking=False, + **kwargs, + ) -> torch.Tensor: + r"""Perform Tensor device conversion. Call the to operator implementation. + + .. note:: + If the ``self`` Tensor already + has the correct :class:`torch.device`, then ``self`` is returned. + Otherwise, the returned tensor is a copy of ``self`` with the desired :class:`torch.device`. + + Args: + device (int, optional): if specified, all parameters will be copied to that device + non_blocking (bool): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. Otherwise, + the argument has no effect. + **kwargs (dict): For compatibility, may contain the key ``memory_format`` argument. + """ + if has_torch_function_unary(self): + return handle_torch_function( + wrap_tensor_to, + (self,), + self, + device=device, + non_blocking=False, + **kwargs, + ) + device_idx = _normalization_device(custom_backend_name, device) + return self.to( + device=torch.device(f"{custom_backend_name}:{device_idx}"), + non_blocking=non_blocking, + **kwargs, + ) + + _check_register_once(torch.Tensor, custom_backend_name) + wrap_tensor_to.__name__ = custom_backend_name + setattr(torch.Tensor, custom_backend_name, wrap_tensor_to) + + +def _generate_module_methods_for_privateuse1_backend(custom_backend_name: str) -> None: + # Generate Module attributes and methods depends on Tensor methods, + # so we need to check whether Tensor methods is already registered. + if not hasattr(torch.Tensor, custom_backend_name): + raise RuntimeError( + f"Can not automatically generate {custom_backend_name}() method for torch.nn.Module." + f"Because torch.Tensor doesn't have the method {custom_backend_name}()." + f"For this error, you can try setting for_tensor=True." + ) + + def wrap_module_to( + # pyrefly: ignore [invalid-type-var] + self: torch.nn.modules.module.T, + device: int | torch.device | None = None, + ) -> torch.nn.modules.module.T: # pyrefly: ignore [invalid-type-var] + r"""Move all model parameters and buffers to the custom device. + + This also makes associated parameters and buffers different objects. So + it should be called before constructing optimizer if the module will + live on device while being optimized. + + .. note:: + This method modifies the module in-place. + + Args: + device (int, optional): if specified, all parameters will be copied to that device + """ + # pyrefly: ignore [missing-attribute] + return self._apply(lambda t: getattr(t, custom_backend_name)(device)) + + _check_register_once(torch.nn.Module, custom_backend_name) + setattr(torch.nn.Module, custom_backend_name, wrap_module_to) + + +def _generate_packed_sequence_methods_for_privateuse1_backend( + custom_backend_name: str, +) -> None: + # Generate PackedSequence Module attributes and methods depends on Tensor methods, + # so we need to check whether Tensor methods is already registered. + if not hasattr(torch.Tensor, f"is_{custom_backend_name}") or not hasattr( + torch.Tensor, custom_backend_name + ): + raise RuntimeError( + f"Can not automatically generate is_{custom_backend_name}() or " + f"{custom_backend_name}() method for torch.nn.utils.rnn.PackedSequence." + f"Because torch.Tensor doesn't have the method is_{custom_backend_name}()" + f"or {custom_backend_name}()." + f"For this error, you can try setting for_tensor=True." + ) + + @property # type: ignore[misc] + def wrap_tensor_backend(self: torch.nn.utils.rnn.PackedSequence) -> bool: + return self.data.device.type == custom_backend_name + + _check_register_once(torch.nn.utils.rnn.PackedSequence, f"is_{custom_backend_name}") + setattr( + torch.nn.utils.rnn.PackedSequence, + f"is_{custom_backend_name}", + wrap_tensor_backend, + ) + + def wrap_module_to( + self: torch.nn.utils.rnn.PackedSequence, *args, **kwargs + ) -> torch.nn.utils.rnn.PackedSequence: + r"""Move all model parameters and buffers to the custom device. + + This also makes associated parameters and buffers different objects. So + it should be called before constructing optimizer if the module will + live on device while being optimized. + + .. note:: + This method modifies the module in-place. + + Args: + device (int, optional): if specified, all parameters will be copied to that device + """ + ex = torch.tensor((), dtype=self.data.dtype, device=self.data.device).to( + *args, + **kwargs, + ) + if ex.device.type == custom_backend_name: + return self.to(*args, **kwargs) + kwargs.update({"device": custom_backend_name}) + + return self.to(*args, **kwargs) + + _check_register_once(torch.nn.utils.rnn.PackedSequence, custom_backend_name) + setattr(torch.nn.utils.rnn.PackedSequence, custom_backend_name, wrap_module_to) + + +def _generate_storage_methods_for_privateuse1_backend( + custom_backend_name: str, unsupported_dtype: list[torch.dtype] | None = None +) -> None: + # Attribute is registered in the _StorageBase class + # and UntypedStorage obtains through inheritance. + @property # type: ignore[misc] + def wrap_storage_backend(self: torch.storage._StorageBase) -> bool: + r"""Return the internal :class:`torch.UntypedStorage`.""" + return self.device.type == custom_backend_name + + _check_register_once(torch.storage._StorageBase, f"is_{custom_backend_name}") + setattr( + torch.storage._StorageBase, f"is_{custom_backend_name}", wrap_storage_backend + ) + + def wrap_storage_to(self, device=None, non_blocking=False): + r"""Return a copy of this object in custom device memory. + + If this object is already in device memory and on the correct device, then + no copy is performed and the original object is returned. + + Args: + device (int): The destination device id. Defaults to the current device. + non_blocking (bool): If ``True`` and the source is in pinned memory, + the copy will be asynchronous with respect to the host. Otherwise, + the argument has no effect. + """ + # There should be a judgment related to storage device and a judgment related to storage type, + # but it depends on the extended function, so this part is temporarily omitted in the automatic generation. + device_idx = _normalization_device(custom_backend_name, device) + + if getattr(self, f"is_{custom_backend_name}"): + # storage has already on expected device. + if self.get_device() == device_idx: + return self + # For sparse storage, custom need to extend the implementation by themselves. + if self.is_sparse: + raise RuntimeError( + f"Can not support a sparse storage move to {custom_backend_name} backend" + ) + # create untyped_storage and copy data + untyped_storage = torch.UntypedStorage( + self.size(), device=torch.device(f"{custom_backend_name}:{device_idx}") + ) + untyped_storage.copy_(self, non_blocking) + return untyped_storage + + _check_register_once(torch.storage._StorageBase, custom_backend_name) + setattr(torch.storage._StorageBase, custom_backend_name, wrap_storage_to) + + # Register the corresponding attribute for the TypedStorage class. + # When the TypedStorage class is removed, the registration is also removed. + + @property # type: ignore[misc] + def wrap_typed_storage_backend(self: torch.storage.TypedStorage) -> bool: + torch.storage._warn_typed_storage_removal() + return self._untyped_storage.device.type == custom_backend_name + + _check_register_once(torch.TypedStorage, f"is_{custom_backend_name}") + setattr( + torch.storage.TypedStorage, + f"is_{custom_backend_name}", + wrap_typed_storage_backend, + ) + + def wrap_typed_storage_to( + self: torch.storage.TypedStorage, device=None, non_blocking=False, **kwargs + ) -> torch.storage.TypedStorage: + torch.storage._warn_typed_storage_removal() + if unsupported_dtype and self.dtype in unsupported_dtype: + raise RuntimeError( + f"Cannot create {custom_backend_name} storage " + f"as {self.dtype} dtype is not supported by this backend" + ) + custom_backend_storage: torch.UntypedStorage = getattr( + self._untyped_storage, custom_backend_name + )(device, non_blocking, **kwargs) + return self._new_wrapped_storage(custom_backend_storage) + + _check_register_once(torch.TypedStorage, custom_backend_name) + setattr(torch.TypedStorage, custom_backend_name, wrap_typed_storage_to) + + +def generate_methods_for_privateuse1_backend( + for_tensor: bool = True, + for_module: bool = True, + for_packed_sequence: bool = True, + for_storage: bool = False, + unsupported_dtype: list[torch.dtype] | None = None, +) -> None: + r""" + Automatically generate attributes and methods for the custom backend after rename privateuse1 backend. + + In the default scenario, storage-related methods will not be generated automatically. + + When you implement kernels for various torch operations, and register them to the PrivateUse1 dispatch key. + And call the function torch.rename_privateuse1_backend("foo") to rename your backend name. + At this point, you can easily register specific methods and attributes by calling this function. + Just like torch.Tensor.foo(), torch.Tensor.is_foo, torch.Storage.foo(), torch.Storage.is_foo. + + Note: We recommend you use generic functions (check devices are equal or to(device=)). + We provide these methods for convenience only and they will be "monkey patched" onto the objects + and so will not be properly typed. For Storage methods generate, if you need to support sparse data storage, + you need to extend the implementation yourself. + + Args: + for_tensor (bool): whether register related methods for torch.Tensor class. + for_module (bool): whether register related methods for torch.nn.Module class. + for_storage (bool): whether register related methods for torch.Storage class. + unsupported_dtype (List[torch.dtype]): takes effect only when the storage method needs to be generated, + indicating that the storage does not support the torch.dtype type. + + Example:: + + >>> # xdoctest: +SKIP("failing") + >>> torch.utils.rename_privateuse1_backend("foo") + >>> torch.utils.generate_methods_for_privateuse1_backend() + # Then automatically generate backend-related attributes and methods. + >>> a = torch.tensor(2).foo() + >>> a.is_foo + >>> hasattr(torch.nn.Module, 'foo') + """ + custom_backend_name = _get_privateuse1_backend_name() + + if for_tensor: + _generate_tensor_methods_for_privateuse1_backend(custom_backend_name) + + if for_module: + _generate_module_methods_for_privateuse1_backend(custom_backend_name) + + if for_storage: + _generate_storage_methods_for_privateuse1_backend( + custom_backend_name, unsupported_dtype + ) + + if for_packed_sequence: + _generate_packed_sequence_methods_for_privateuse1_backend(custom_backend_name) + + +def _get_custom_mod_func(func_name: str): + r""" + Return the func named `func_name` defined in custom device module. If not defined, + return `None`. And the func is registered with `torch.utils.rename_privateuse1_backend('foo')` + and `torch._register_device_module('foo', BackendModule)`. + If the custom device module or the func is not defined, it will give warning or error message. + Args: + func_name (str): return the callable func named func_name defined in custom device module. + Example:: + class DummyfooModule: + @staticmethod + def is_available(): + return True + @staticmethod + def func_name(*args, **kwargs): + .... + torch.utils.rename_privateuse1_backend("foo") + torch._register_device_module("foo", DummyfooModule) + foo_is_available_func = torch.utils.backend_registration._get_custom_mod_func("is_available") + if foo_is_available_func: + foo_is_available = foo_is_available_func() + func_ = torch.utils.backend_registration._get_custom_mod_func("func_name") + if func_: + result = func_(*args, **kwargs) + Attention: This function is not meant to be used directly by users, which is why + it is marked as private. It is a convenience function for backend implementers to + more easily call the hooks into their backend extensions. + """ + if not isinstance(func_name, str): + raise AssertionError(f"func_name must be `str`, but got `{type(func_name)}`.") + backend_name = _get_privateuse1_backend_name() + custom_device_mod = getattr(torch, backend_name, None) + function = getattr(custom_device_mod, func_name, None) + if custom_device_mod is None or function is None: + message = f"Try to call torch.{backend_name}.{func_name}. The backend must register a custom backend " + message += f"module with `torch._register_device_module('{backend_name}', BackendModule)`. And " + message += f"BackendModule needs to have the following API's:\n `{func_name}(*args, **kwargs)`. \n" + raise RuntimeError(message) + return function + + +class _DummyBackendModule: + def is_initialized(self) -> bool: + return True + + def is_available(self) -> bool: + return True + + def current_device(self) -> int: + return 0 + + def _is_in_bad_fork(self) -> bool: + return False + + def manual_seed_all(self, seed: int) -> None: + pass + + def device_count(self) -> int: + return 1 + + +class _DummyPrivateUse1Hook(torch._C._acc.PrivateUse1Hooks): + def is_available(self) -> bool: + return True + + def has_primary_context(self, dev_id) -> bool: + return True + + def is_built(self) -> bool: + return True + + +class _DummyDeviceGuard(torch._C._acc.DeviceGuard): + def type_(self): + return torch._C._autograd.DeviceType.PrivateUse1 + + +def _setup_privateuseone_for_python_backend( + rename=None, backend_module=None, hook=None, device_guard=None +) -> None: + """This function will prepare the PrivateUse1 dispatch key to be used as a python backend. + + WARNING: this API is experimental and might change without notice. + + Formally, this registers things that Pytorch expects a registered backend + in C++ to have: including device guards, hooks, and backend modules and what not. + + after this call, one can use `torch.library` to write Ops for this dispatch key + and expect it to behave like a backend registered in C++. + + See the unit test at test/test_privateuseone_python_backend.py for more details. + + Args: + rename: str | None, if passed in, we will rename privateuseone backend to + the name given. + backend_module: object | None, if passed in None, we will use DummyBackendModule + hook: object | None, if passed in None, we will use DummyPrivateUse1Hook + device_guard: object | None, if passed in None, we will use DummyDeviceGuard + """ + # NOTE: the ordering of which these functions are called is important. + if rename is not None: + torch.utils.rename_privateuse1_backend(rename) + else: + rename = "privateuseone" + torch.utils.generate_methods_for_privateuse1_backend() + if backend_module is None: + backend_module = _DummyBackendModule() + if hook is None: + hook = _DummyPrivateUse1Hook() + if device_guard is None: + device_guard = _DummyDeviceGuard() + torch._register_device_module(rename, backend_module) # type: ignore[bad-argument-type] + torch._C._acc.register_python_privateuseone_hook(hook) + torch._C._acc.register_python_privateuseone_device_guard(device_guard) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9e814aaf4671ca35484c43bc38677849d02a81ec --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/__init__.py @@ -0,0 +1,6 @@ +from torch.utils.benchmark.utils.common import * # noqa: F403 +from torch.utils.benchmark.utils.timer import * # noqa: F403 +from torch.utils.benchmark.utils.compare import * # noqa: F403 +from torch.utils.benchmark.utils.fuzzer import * # noqa: F403 +from torch.utils.benchmark.utils.valgrind_wrapper.timer_interface import * # noqa: F403 +from torch.utils.benchmark.utils.sparse_fuzzer import * # noqa: F403 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..809299c828b2ccd3dbf3b70f82f2ae5fef150182 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0e8c6be5df7c2d2c79557aecaf235018b76146f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/compare.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/compare.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..939cd9728d73ae4f0560552cf5298128a05af96f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/compare.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/fuzzer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/fuzzer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c7e960e9a3680b1399e5f0badc5b64ce3162ef1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/fuzzer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/op_benchmark.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/op_benchmark.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99db2246fbee5e19a7b533d0821954dae8f34297 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/op_benchmark.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/simple_timeit.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/simple_timeit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ece855c4ea29c408827a5b0316d69702bf11334c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/simple_timeit.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/spectral_ops_fuzz_test.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/spectral_ops_fuzz_test.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2962aab955be4f52dad9f0baadda906ceca8d2e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/__pycache__/spectral_ops_fuzz_test.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/compare.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..1c266e7cf9a6e604c94dfb28f19f31f1649220f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/compare.py @@ -0,0 +1,99 @@ +# mypy: allow-untyped-defs +"""Example of Timer and Compare APIs: + +$ python -m examples.compare +""" + +import pickle +import sys +import time + +import torch + +import torch.utils.benchmark as benchmark_utils + + +class FauxTorch: + """Emulate different versions of pytorch. + + In normal circumstances this would be done with multiple processes + writing serialized measurements, but this simplifies that model to + make the example clearer. + """ + def __init__(self, real_torch, extra_ns_per_element) -> None: + self._real_torch = real_torch + self._extra_ns_per_element = extra_ns_per_element + + def extra_overhead(self, result): + # time.sleep has a ~65 us overhead, so only fake a + # per-element overhead if numel is large enough. + numel = int(result.numel()) + if numel > 5000: + time.sleep(numel * self._extra_ns_per_element * 1e-9) + return result + + def add(self, *args, **kwargs): + return self.extra_overhead(self._real_torch.add(*args, **kwargs)) + + def mul(self, *args, **kwargs): + return self.extra_overhead(self._real_torch.mul(*args, **kwargs)) + + def cat(self, *args, **kwargs): + return self.extra_overhead(self._real_torch.cat(*args, **kwargs)) + + def matmul(self, *args, **kwargs): + return self.extra_overhead(self._real_torch.matmul(*args, **kwargs)) + + +def main() -> None: + tasks = [ + ("add", "add", "torch.add(x, y)"), + ("add", "add (extra +0)", "torch.add(x, y + zero)"), + ] + + serialized_results = [] + repeats = 2 + timers = [ + benchmark_utils.Timer( + stmt=stmt, + globals={ + "torch": torch if branch == "master" else FauxTorch(torch, overhead_ns), + "x": torch.ones((size, 4)), + "y": torch.ones((1, 4)), + "zero": torch.zeros(()), + }, + label=label, + sub_label=sub_label, + description=f"size: {size}", + env=branch, + num_threads=num_threads, + ) + for branch, overhead_ns in [("master", None), ("my_branch", 1), ("severe_regression", 5)] + for label, sub_label, stmt in tasks + for size in [1, 10, 100, 1000, 10000, 50000] + for num_threads in [1, 4] + ] + + for i, timer in enumerate(timers * repeats): + serialized_results.append(pickle.dumps( + timer.blocked_autorange(min_run_time=0.05) + )) + print(f"\r{i + 1} / {len(timers) * repeats}", end="") + sys.stdout.flush() + print() + + comparison = benchmark_utils.Compare([ + pickle.loads(i) for i in serialized_results + ]) + + print("== Unformatted " + "=" * 80 + "\n" + "/" * 95 + "\n") + comparison.print() + + print("== Formatted " + "=" * 80 + "\n" + "/" * 93 + "\n") + comparison.trim_significant_figures() + comparison.colorize() + comparison.print() + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/fuzzer.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/fuzzer.py new file mode 100644 index 0000000000000000000000000000000000000000..80a4e733928d8b059919d847da1b461d55dd7402 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/fuzzer.py @@ -0,0 +1,86 @@ +# mypy: allow-untyped-defs +"""Example of the Timer and Fuzzer APIs: + +$ python -m examples.fuzzer +""" + +import sys + +import torch.utils.benchmark as benchmark_utils + + +def main() -> None: + add_fuzzer = benchmark_utils.Fuzzer( + parameters=[ + [ + benchmark_utils.FuzzedParameter( + name=f"k{i}", + minval=16, + maxval=16 * 1024, + distribution="loguniform", + ) for i in range(3) + ], + benchmark_utils.FuzzedParameter( + name="d", + distribution={2: 0.6, 3: 0.4}, + ), + ], + tensors=[ + [ + benchmark_utils.FuzzedTensor( + name=name, + size=("k0", "k1", "k2"), + dim_parameter="d", + probability_contiguous=0.75, + min_elements=64 * 1024, + max_elements=128 * 1024, + ) for name in ("x", "y") + ], + ], + seed=0, + ) + + n = 250 + measurements = [] + for i, (tensors, tensor_properties, _) in enumerate(add_fuzzer.take(n=n)): + x, x_order = tensors["x"], str(tensor_properties["x"]["order"]) + y, y_order = tensors["y"], str(tensor_properties["y"]["order"]) + shape = ", ".join(tuple(f'{i:>4}' for i in x.shape)) + + description = "".join([ + f"{x.numel():>7} | {shape:<16} | ", + f"{'contiguous' if x.is_contiguous() else x_order:<12} | ", + f"{'contiguous' if y.is_contiguous() else y_order:<12} | ", + ]) + + timer = benchmark_utils.Timer( + stmt="x + y", + globals=tensors, + description=description, + ) + + measurements.append(timer.blocked_autorange(min_run_time=0.1)) + measurements[-1].metadata = {"numel": x.numel()} + print(f"\r{i + 1} / {n}", end="") + sys.stdout.flush() + print() + + # More string munging to make pretty output. + print(f"Average attempts per valid config: {1. / (1. - add_fuzzer.rejection_rate):.1f}") + + def time_fn(m): + return m.median / m.metadata["numel"] + measurements.sort(key=time_fn) + + template = f"{{:>6}}{' ' * 19}Size Shape{' ' * 13}X order Y order\n{'-' * 80}" + print(template.format("Best:")) + for m in measurements[:15]: + print(f"{time_fn(m) * 1e9:>4.1f} ns / element {m.description}") + + print("\n" + template.format("Worst:")) + for m in measurements[-15:]: + print(f"{time_fn(m) * 1e9:>4.1f} ns / element {m.description}") + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/op_benchmark.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/op_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..eb8ce87f34bbab9fd5be53557daef6bb6edd6bdd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/op_benchmark.py @@ -0,0 +1,109 @@ +# mypy: allow-untyped-defs +"""Example use of Timer and op fuzzers to measure kernel performance. + +$ python -m examples.op_benchmark +""" + +import numpy as np +import torch + +from torch.utils.benchmark import Timer +from torch.utils.benchmark.op_fuzzers.binary import BinaryOpFuzzer +from torch.utils.benchmark.op_fuzzers.unary import UnaryOpFuzzer +import operator + + +_MEASURE_TIME = 1.0 + + +def assert_dicts_equal(dict_0, dict_1) -> None: + """Builtin dict comparison will not compare numpy arrays. + + e.g.:: + + x = {"a": np.ones((2, 1))} + x == x # Raises ValueError + """ + if set(dict_0.keys()) != set(dict_0.keys()): + raise AssertionError("dicts must have the same keys") + if all(np.all(v != dict_1[k]) for k, v in dict_0.items() if k != "dtype"): + raise AssertionError("dict values differ for keys other than 'dtype'") + + +def run(n, stmt, fuzzer_cls) -> None: + float_iter = fuzzer_cls(seed=0, dtype=torch.float32).take(n) + int_iter = fuzzer_cls(seed=0, dtype=torch.int32).take(n) + raw_results = [] + for i, (float_values, int_values) in enumerate(zip(float_iter, int_iter, strict=True)): + float_tensors, float_tensor_params, float_params = float_values + int_tensors, int_tensor_params, int_params = int_values + + # This benchmark assumes that the two fuzzers generate identically + # sized and strided Tensors, since the same seed is used. + assert_dicts_equal(float_params, int_params) + assert_dicts_equal(float_tensor_params["x"], int_tensor_params["x"]) + + float_measurement, int_measurement = ( + Timer( + stmt, + globals=tensors, + ).blocked_autorange(min_run_time=_MEASURE_TIME) + for tensors in (float_tensors, int_tensors) + ) + + descriptions = [] + for name in float_tensors: + shape_str = "(" + ", ".join([ + f"2 ** {int(np.log2(i))}" + if 2 ** int(np.log2(i)) == i and i > 1 + else str(i) + for i in float_tensors[name].shape + ]) + ")" + order = float_tensor_params[name]["order"] + order_str = ("" if all(order == np.arange(len(order))) else str(tuple(order))) + steps = float_tensor_params[name]["steps"] + steps_str = str(steps) if sum(steps) > len(steps) else "" + descriptions.append((name, shape_str, order_str, steps_str)) + raw_results.append((float_measurement, int_measurement, descriptions)) + + print(f"\r{i + 1} / {n}", end="") + print() + + parsed_results, name_len, shape_len, order_len, steps_len = [], 0, 0, 0, 0 + for float_measurement, int_measurement, descriptions in raw_results: + t_float = float_measurement.median * 1e6 + t_int = int_measurement.median * 1e6 + rel_diff = abs(t_float - t_int) / (t_float + t_int) * 2 + parsed_results.append((t_float, t_int, rel_diff, descriptions)) + for name, shape, order, steps in descriptions: + name_len = max(name_len, len(name)) + shape_len = max(shape_len, len(shape)) + order_len = max(order_len, len(order)) + steps_len = max(steps_len, len(steps)) + + parsed_results.sort(key=operator.itemgetter(2)) + + print(f"stmt: {stmt}") + print(f" diff faster{'':>17}{' ' * name_len} ", end="") + print(f"{'shape'.ljust(shape_len)}{'':>16}{'order'.ljust(order_len)}", end="") + print(f" steps\n{'-' * 100}") + for results, spacer in [(parsed_results[:10], "..."), (parsed_results[-10:], "")]: + for t_float, t_int, rel_diff, descriptions in results: + time_str = [f"{rel_diff * 100:>4.1f}% {'int' if t_int < t_float else 'float':<20}"] + time_str.extend(["".ljust(len(time_str[0])) for _ in descriptions[:-1]]) + for t_str, (name, shape, order, steps) in zip(time_str, descriptions, strict=True): + name = f"{name}:".ljust(name_len + 1) + shape = shape.ljust(shape_len + 10) + order = order.ljust(order_len) + print(f"{t_str} {name} {shape}| {order} | {steps}") + print(spacer) + + +def main() -> None: + run(n=100, stmt="torch.median(x, dim=0)", fuzzer_cls=UnaryOpFuzzer) + run(n=100, stmt="torch.square(x)", fuzzer_cls=UnaryOpFuzzer) + run(n=100, stmt="x + y", fuzzer_cls=BinaryOpFuzzer) + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/simple_timeit.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/simple_timeit.py new file mode 100644 index 0000000000000000000000000000000000000000..8137d4d8791975b46b1314c2f3a05ed048dbdcd3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/simple_timeit.py @@ -0,0 +1,25 @@ +"""Trivial use of Timer API: + +$ python -m examples.simple_timeit +""" + +import torch + +import torch.utils.benchmark as benchmark_utils + + +def main() -> None: + timer = benchmark_utils.Timer( + stmt="x + y", + globals={"x": torch.ones((4, 8)), "y": torch.ones((1, 8))}, + label="Broadcasting add (4x8)", + ) + + for i in range(3): + print(f"Run: {i}\n{'-' * 40}") + print(f"timeit:\n{timer.timeit(10000)}\n") + print(f"autorange:\n{timer.blocked_autorange()}\n\n") + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/spectral_ops_fuzz_test.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/spectral_ops_fuzz_test.py new file mode 100644 index 0000000000000000000000000000000000000000..81a33c34bc8229a44838ea93c29af34895061c53 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/examples/spectral_ops_fuzz_test.py @@ -0,0 +1,114 @@ +# mypy: allow-untyped-defs +"""Microbenchmarks for the torch.fft module""" +from argparse import ArgumentParser +from collections import namedtuple +from collections.abc import Iterable + +import torch +import torch.fft +from torch.utils import benchmark +from torch.utils.benchmark.op_fuzzers.spectral import SpectralOpFuzzer + + +def _dim_options(ndim): + if ndim == 1: + return [None] + elif ndim == 2: + return [0, 1, None] + elif ndim == 3: + return [0, 1, 2, (0, 1), (0, 2), None] + raise ValueError(f"Expected ndim in range 1-3, got {ndim}") + + +def run_benchmark(name: str, function: object, dtype: torch.dtype, seed: int, device: str, samples: int, + probability_regular: float): + cuda = device == 'cuda' + spectral_fuzzer = SpectralOpFuzzer(seed=seed, dtype=dtype, cuda=cuda, + probability_regular=probability_regular) + results = [] + for tensors, tensor_params, params in spectral_fuzzer.take(samples): + shape = [params['k0'], params['k1'], params['k2']][:params['ndim']] + str_shape = ' x '.join([f"{s:<4}" for s in shape]) + sub_label = f"{str_shape} {'' if tensor_params['x']['is_contiguous'] else '(discontiguous)'}" + for dim in _dim_options(params['ndim']): + for nthreads in (1, 4, 16) if not cuda else (1,): + measurement = benchmark.Timer( + stmt='func(x, dim=dim)', + globals={'func': function, 'x': tensors['x'], 'dim': dim}, + label=f"{name}_{device}", + sub_label=sub_label, + description=f"dim={dim}", + num_threads=nthreads, + ).blocked_autorange(min_run_time=1) + measurement.metadata = { + 'name': name, + 'device': device, + 'dim': dim, + 'shape': shape, + } + measurement.metadata.update(tensor_params['x']) + results.append(measurement) + return results + + +Benchmark = namedtuple('Benchmark', ['name', 'function', 'dtype']) +BENCHMARKS = [ + Benchmark('fft_real', torch.fft.fftn, torch.float32), + Benchmark('fft_complex', torch.fft.fftn, torch.complex64), + Benchmark('ifft', torch.fft.ifftn, torch.complex64), + Benchmark('rfft', torch.fft.rfftn, torch.float32), + Benchmark('irfft', torch.fft.irfftn, torch.complex64), +] +BENCHMARK_MAP = {b.name: b for b in BENCHMARKS} +BENCHMARK_NAMES = [b.name for b in BENCHMARKS] +DEVICE_NAMES = ['cpu', 'cuda'] + +def _output_csv(file, results) -> None: + file.write('benchmark,device,num_threads,numel,shape,contiguous,dim,mean (us),median (us),iqr (us)\n') + for measurement in results: + metadata = measurement.metadata + device, dim, shape, name, numel, contiguous = ( + metadata['device'], metadata['dim'], metadata['shape'], + metadata['name'], metadata['numel'], metadata['is_contiguous']) + + if isinstance(dim, Iterable): + dim_str = '-'.join(str(d) for d in dim) + else: + dim_str = str(dim) + shape_str = 'x'.join(str(s) for s in shape) + + print(name, device, measurement.task_spec.num_threads, numel, shape_str, contiguous, dim_str, # type: ignore[possibly-undefined] + measurement.mean * 1e6, measurement.median * 1e6, measurement.iqr * 1e6, + sep=',', file=file) + + +if __name__ == '__main__': + parser = ArgumentParser(description=__doc__) + parser.add_argument('--device', type=str, choices=DEVICE_NAMES, nargs='+', default=DEVICE_NAMES) + parser.add_argument('--bench', type=str, choices=BENCHMARK_NAMES, nargs='+', default=BENCHMARK_NAMES) + parser.add_argument('--seed', type=int, default=0) + parser.add_argument('--samples', type=int, default=10) + parser.add_argument('--probability-regular', '--probability_regular', type=float, default=1.0) + parser.add_argument('-o', '--output', type=str) + args = parser.parse_args() + + num_benchmarks = len(args.device) * len(args.bench) + i = 0 + results = [] + for device in args.device: + for bench in (BENCHMARK_MAP[b] for b in args.bench): + results += run_benchmark( + name=bench.name, function=bench.function, dtype=bench.dtype, + seed=args.seed, device=device, samples=args.samples, + probability_regular=args.probability_regular) + i += 1 + print(f'Completed {bench.name} benchmark on {device} ({i} of {num_benchmarks})') + + if args.output is not None: + with open(args.output, 'w') as f: + _output_csv(f, results) + + compare = benchmark.Compare(results) + compare.trim_significant_figures() + compare.colorize() + compare.print() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f7b59aae8423d59ec03dc3025849c646aca9482 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/binary.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/binary.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b93061920cc394c64512a412bd0da8455c2369ab Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/binary.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/sparse_binary.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/sparse_binary.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dd654de2b5cad07ef766f80d970dfc79acd7424 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/sparse_binary.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/sparse_unary.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/sparse_unary.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df1305fe737faf85a55793a3b762b45de8333d21 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/sparse_unary.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/spectral.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/spectral.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e311511fec219bbe4f74772380b81c7524cec1d2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/spectral.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/unary.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/unary.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed6ee12fa1372a19154cd271cd84d446340ec142 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/__pycache__/unary.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/binary.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/binary.py new file mode 100644 index 0000000000000000000000000000000000000000..e53c310111bec8166e6090f351e39153dbe400aa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/binary.py @@ -0,0 +1,107 @@ +# mypy: allow-untyped-defs +import numpy as np +import torch + +from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedTensor + + +_MIN_DIM_SIZE = 16 +_MAX_DIM_SIZE = 16 * 1024 ** 2 +_POW_TWO_SIZES = tuple(2 ** i for i in range( + int(np.log2(_MIN_DIM_SIZE)), + int(np.log2(_MAX_DIM_SIZE)) + 1, +)) + + +class BinaryOpFuzzer(Fuzzer): + def __init__(self, seed, dtype=torch.float32, cuda=False) -> None: + super().__init__( + parameters=[ + # Dimensionality of x and y. (e.g. 1D, 2D, or 3D.) + FuzzedParameter("dim", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True), + + # Shapes for `x` and `y`. + # It is important to test all shapes, however + # powers of two are especially important and therefore + # warrant special attention. This is done by generating + # both a value drawn from all integers between the min and + # max allowed values, and another from only the powers of two + # (both distributions are loguniform) and then randomly + # selecting between the two. + # Moreover, `y` will occasionally have singleton + # dimensions in order to test broadcasting. + [ + FuzzedParameter( + name=f"k_any_{i}", + minval=_MIN_DIM_SIZE, + maxval=_MAX_DIM_SIZE, + distribution="loguniform", + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k_pow2_{i}", + distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES} + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k{i}", + distribution={ + ParameterAlias(f"k_any_{i}"): 0.8, + ParameterAlias(f"k_pow2_{i}"): 0.2, + }, + strict=True, + ) for i in range(3) + ], + + [ + FuzzedParameter( + name=f"y_k{i}", + distribution={ + ParameterAlias(f"k{i}"): 0.8, + 1: 0.2, + }, + strict=True, + ) for i in range(3) + ], + + # Steps for `x` and `y`. (Benchmarks strided memory access.) + [ + FuzzedParameter( + name=f"{name}_step_{i}", + distribution={1: 0.8, 2: 0.06, 4: 0.06, 8: 0.04, 16: 0.04}, + ) + for i in range(3) + for name in ("x", "y") + ], + + # Repeatable entropy for downstream applications. + FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"), + ], + tensors=[ + FuzzedTensor( + name="x", + size=("k0", "k1", "k2"), + steps=("x_step_0", "x_step_1", "x_step_2"), + probability_contiguous=0.75, + min_elements=4 * 1024, + max_elements=32 * 1024 ** 2, + max_allocation_bytes=2 * 1024**3, # 2 GB + dim_parameter="dim", + dtype=dtype, + cuda=cuda, + ), + FuzzedTensor( + name="y", + size=("y_k0", "y_k1", "y_k2"), + steps=("x_step_0", "x_step_1", "x_step_2"), + probability_contiguous=0.75, + max_allocation_bytes=2 * 1024**3, # 2 GB + dim_parameter="dim", + dtype=dtype, + cuda=cuda, + ), + ], + seed=seed, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/sparse_binary.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/sparse_binary.py new file mode 100644 index 0000000000000000000000000000000000000000..8e6269464e0d53d2c3c51ed5406d7c88598fec79 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/sparse_binary.py @@ -0,0 +1,107 @@ +# mypy: allow-untyped-defs +import numpy as np +import torch + +from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedSparseTensor + + +_MIN_DIM_SIZE = 16 +_MAX_DIM_SIZE = 16 * 1024 ** 2 +_POW_TWO_SIZES = tuple(2 ** i for i in range( + int(np.log2(_MIN_DIM_SIZE)), + int(np.log2(_MAX_DIM_SIZE)) + 1, +)) + + +class BinaryOpSparseFuzzer(Fuzzer): + def __init__(self, seed, dtype=torch.float32, cuda=False) -> None: + super().__init__( + parameters=[ + # Dimensionality of x and y. (e.g. 1D, 2D, or 3D.) + FuzzedParameter("dim_parameter", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True), + FuzzedParameter( + name="sparse_dim", + distribution={1: 0.4, 2: 0.4, 3: 0.2}, + strict=True + ), + # Shapes for `x` and `y`. + # It is important to test all shapes, however + # powers of two are especially important and therefore + # warrant special attention. This is done by generating + # both a value drawn from all integers between the min and + # max allowed values, and another from only the powers of two + # (both distributions are loguniform) and then randomly + # selecting between the two. + # Moreover, `y` will occasionally have singleton + # dimensions in order to test broadcasting. + [ + FuzzedParameter( + name=f"k_any_{i}", + minval=_MIN_DIM_SIZE, + maxval=_MAX_DIM_SIZE, + distribution="loguniform", + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k_pow2_{i}", + distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES} + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k{i}", + distribution={ + ParameterAlias(f"k_any_{i}"): 0.8, + ParameterAlias(f"k_pow2_{i}"): 0.2, + }, + strict=True, + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"y_k{i}", + distribution={ + ParameterAlias(f"k{i}"): 1.0}, + strict=True, + ) for i in range(3) + ], + FuzzedParameter( + name="density", + distribution={0.1: 0.4, 0.05: 0.3, 0.01: 0.3}, + ), + FuzzedParameter( + name="coalesced", + distribution={True: 0.5, False: 0.5}, + ), + # Repeatable entropy for downstream applications. + FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"), + ], + tensors=[ + FuzzedSparseTensor( + name="x", + size=("k0", "k1", "k2"), + dim_parameter="dim_parameter", + sparse_dim="sparse_dim", + density="density", + coalesced="coalesced", + min_elements=4 * 1024, + max_elements=32 * 1024 ** 2, + dtype=dtype, + cuda=cuda, + ), + FuzzedSparseTensor( + name="y", + size=("y_k0", "y_k1", "y_k2"), + dim_parameter="dim_parameter", + sparse_dim="sparse_dim", + density="density", + coalesced="coalesced", + min_elements=4 * 1024, + max_elements=32 * 1024 ** 2, + dtype=dtype, + cuda=cuda, + ), + ], + seed=seed, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/sparse_unary.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/sparse_unary.py new file mode 100644 index 0000000000000000000000000000000000000000..18921becd078cb3140a1705078dd57f4a597a2ec --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/sparse_unary.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np +import torch + +if TYPE_CHECKING: + from torch.types import _dtype + +from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedSparseTensor + +__all__ = ["UnaryOpSparseFuzzer"] + +_MIN_DIM_SIZE = 16 +_MAX_DIM_SIZE = 16 * 1024 ** 2 +_POW_TWO_SIZES = tuple(2 ** i for i in range( + int(np.log2(_MIN_DIM_SIZE)), + int(np.log2(_MAX_DIM_SIZE)) + 1, +)) + +class UnaryOpSparseFuzzer(Fuzzer): + def __init__(self, seed: int | None, dtype: _dtype | None = None, cuda: bool = False) -> None: + if dtype is None: + dtype = getattr(torch, 'float32', None) + super().__init__( + parameters=[ + # Sparse dim parameter of x. (e.g. 1D, 2D, or 3D.) + FuzzedParameter("dim_parameter", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True), + FuzzedParameter( + name="sparse_dim", + distribution={1: 0.4, 2: 0.4, 3: 0.2}, + strict=True + ), + # Shapes for `x`. + # It is important to test all shapes, however + # powers of two are especially important and therefore + # warrant special attention. This is done by generating + # both a value drawn from all integers between the min and + # max allowed values, and another from only the powers of two + # (both distributions are loguniform) and then randomly + # selecting between the two. + [ + FuzzedParameter( + name=f"k_any_{i}", + minval=_MIN_DIM_SIZE, + maxval=_MAX_DIM_SIZE, + distribution="loguniform", + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k_pow2_{i}", + distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES} + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k{i}", + distribution={ + ParameterAlias(f"k_any_{i}"): 0.8, + ParameterAlias(f"k_pow2_{i}"): 0.2, + }, + strict=True, + ) for i in range(3) + ], + FuzzedParameter( + name="density", + distribution={0.1: 0.4, 0.05: 0.3, 0.01: 0.3}, + ), + FuzzedParameter( + name="coalesced", + distribution={True: 0.5, False: 0.5}, + ), + FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"), + ], + tensors=[ + FuzzedSparseTensor( + name="x", + size=("k0", "k1", "k2"), + dim_parameter="dim_parameter", + sparse_dim="sparse_dim", + min_elements=4 * 1024, + max_elements=32 * 1024 ** 2, + density="density", + coalesced="coalesced", + dtype=dtype, + cuda=cuda, + ), + ], + seed=seed, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/spectral.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..c324e338dca5da3d2b8b9a55e7d89f108d6783dd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/spectral.py @@ -0,0 +1,94 @@ +# mypy: allow-untyped-defs +import math + +import torch +from torch.utils import benchmark +from torch.utils.benchmark import FuzzedParameter, FuzzedTensor, ParameterAlias + + +__all__ = ['SpectralOpFuzzer'] + +MIN_DIM_SIZE = 16 +MAX_DIM_SIZE = 16 * 1024 + +def power_range(upper_bound, base): + return (base ** i for i in range(int(math.log(upper_bound, base)) + 1)) + +# List of regular numbers from MIN_DIM_SIZE to MAX_DIM_SIZE +# These numbers factorize into multiples of prime factors 2, 3, and 5 only +# and are usually the fastest in FFT implementations. +REGULAR_SIZES = [] +for i in power_range(MAX_DIM_SIZE, 2): + for j in power_range(MAX_DIM_SIZE // i, 3): + ij = i * j + for k in power_range(MAX_DIM_SIZE // ij, 5): + ijk = ij * k + if ijk > MIN_DIM_SIZE: + REGULAR_SIZES.append(ijk) +REGULAR_SIZES.sort() + +class SpectralOpFuzzer(benchmark.Fuzzer): + def __init__(self, *, seed: int, dtype=torch.float64, + cuda: bool = False, probability_regular: float = 1.0) -> None: + super().__init__( + parameters=[ + # Dimensionality of x. (e.g. 1D, 2D, or 3D.) + FuzzedParameter("ndim", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True), + + # Shapes for `x`. + # It is important to test all shapes, however + # regular sizes are especially important to the FFT and therefore + # warrant special attention. This is done by generating + # both a value drawn from all integers between the min and + # max allowed values, and another from only the regular numbers + # (both distributions are loguniform) and then randomly + # selecting between the two. + [ + FuzzedParameter( + name=f"k_any_{i}", + minval=MIN_DIM_SIZE, + maxval=MAX_DIM_SIZE, + distribution="loguniform", + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k_regular_{i}", + distribution={size: 1. / len(REGULAR_SIZES) for size in REGULAR_SIZES} + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k{i}", + distribution={ + ParameterAlias(f"k_regular_{i}"): probability_regular, + ParameterAlias(f"k_any_{i}"): 1 - probability_regular, + }, + strict=True, + ) for i in range(3) + ], + + # Steps for `x`. (Benchmarks strided memory access.) + [ + FuzzedParameter( + name=f"step_{i}", + distribution={1: 0.8, 2: 0.06, 4: 0.06, 8: 0.04, 16: 0.04}, + ) for i in range(3) + ], + ], + tensors=[ + FuzzedTensor( + name="x", + size=("k0", "k1", "k2"), + steps=("step_0", "step_1", "step_2"), + probability_contiguous=0.75, + min_elements=4 * 1024, + max_elements=32 * 1024 ** 2, + max_allocation_bytes=2 * 1024**3, # 2 GB + dim_parameter="ndim", + dtype=dtype, + cuda=cuda, + ), + ], + seed=seed, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/unary.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/unary.py new file mode 100644 index 0000000000000000000000000000000000000000..6008adfe459218cd0e239efede5a3f1cd35ee61b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/op_fuzzers/unary.py @@ -0,0 +1,82 @@ +# mypy: allow-untyped-defs +import numpy as np +import torch + +from torch.utils.benchmark import Fuzzer, FuzzedParameter, ParameterAlias, FuzzedTensor + + +_MIN_DIM_SIZE = 16 +_MAX_DIM_SIZE = 16 * 1024 ** 2 +_POW_TWO_SIZES = tuple(2 ** i for i in range( + int(np.log2(_MIN_DIM_SIZE)), + int(np.log2(_MAX_DIM_SIZE)) + 1, +)) + + +class UnaryOpFuzzer(Fuzzer): + def __init__(self, seed, dtype=torch.float32, cuda=False) -> None: + super().__init__( + parameters=[ + # Dimensionality of x. (e.g. 1D, 2D, or 3D.) + FuzzedParameter("dim", distribution={1: 0.3, 2: 0.4, 3: 0.3}, strict=True), + + # Shapes for `x`. + # It is important to test all shapes, however + # powers of two are especially important and therefore + # warrant special attention. This is done by generating + # both a value drawn from all integers between the min and + # max allowed values, and another from only the powers of two + # (both distributions are loguniform) and then randomly + # selecting between the two. + [ + FuzzedParameter( + name=f"k_any_{i}", + minval=_MIN_DIM_SIZE, + maxval=_MAX_DIM_SIZE, + distribution="loguniform", + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k_pow2_{i}", + distribution={size: 1. / len(_POW_TWO_SIZES) for size in _POW_TWO_SIZES} + ) for i in range(3) + ], + [ + FuzzedParameter( + name=f"k{i}", + distribution={ + ParameterAlias(f"k_any_{i}"): 0.8, + ParameterAlias(f"k_pow2_{i}"): 0.2, + }, + strict=True, + ) for i in range(3) + ], + + # Steps for `x`. (Benchmarks strided memory access.) + [ + FuzzedParameter( + name=f"x_step_{i}", + distribution={1: 0.8, 2: 0.06, 4: 0.06, 8: 0.04, 16: 0.04}, + ) for i in range(3) + ], + + # Repeatable entropy for downstream applications. + FuzzedParameter(name="random_value", minval=0, maxval=2 ** 32 - 1, distribution="uniform"), + ], + tensors=[ + FuzzedTensor( + name="x", + size=("k0", "k1", "k2"), + steps=("x_step_0", "x_step_1", "x_step_2"), + probability_contiguous=0.75, + min_elements=4 * 1024, + max_elements=32 * 1024 ** 2, + max_allocation_bytes=2 * 1024**3, # 2 GB + dim_parameter="dim", + dtype=dtype, + cuda=cuda, + ), + ], + seed=seed, + ) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83e581e00b9998d09a22c70207cf5828625f9c70 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/_stubs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/_stubs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d49ac250ea860b3744a2cc22b4737b03937703ec Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/_stubs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2570deb735e47d64933ced48c9593e2277098fa Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/compare.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/compare.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b611067bea6c87bc968f5b0fc3df2232af1ed7dc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/compare.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/compile.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/compile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..887b67fe46716cad51053cf1ff3cfa5db3988e79 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/compile.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/cpp_jit.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/cpp_jit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e942d4bbe60a6b32f9dfaf1b085fd6376565883e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/cpp_jit.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/fuzzer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/fuzzer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..181338a45de8d6a15af714994c3c06cbcb904bd0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/fuzzer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/sparse_fuzzer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/sparse_fuzzer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d82d655fc518640f8bd6ec075753caf4a0db8ea4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/sparse_fuzzer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/timer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/timer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2dec91150ecd5190546e66695491e744ba555a9f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/__pycache__/timer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/_stubs.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/_stubs.py new file mode 100644 index 0000000000000000000000000000000000000000..c91e3d12b29e1c050edbadaebb877d7fc0761e57 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/_stubs.py @@ -0,0 +1,42 @@ +from typing import Any +from collections.abc import Callable +from typing_extensions import Protocol, runtime_checkable + + +class TimerClass(Protocol): + """This is the portion of the `timeit.Timer` API used by benchmark utils.""" + def __init__( + self, + stmt: str, + setup: str, + timer: Callable[[], float], + globals: dict[str, Any], + **kwargs: Any, + ) -> None: + ... + + def timeit(self, number: int) -> float: + ... + + +@runtime_checkable +class TimeitModuleType(Protocol): + """Modules generated from `timeit_template.cpp`.""" + def timeit(self, number: int) -> float: + ... + + +class CallgrindModuleType(Protocol): + """Replicates the valgrind endpoints in `torch._C`. + + These bindings are used to collect Callgrind profiles on earlier versions + of PyTorch and will eventually be removed. + """ + __file__: str + __name__: str + + def _valgrind_supported_platform(self) -> bool: + ... + + def _valgrind_toggle(self) -> None: + ... diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/common.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/common.py new file mode 100644 index 0000000000000000000000000000000000000000..e28957a33be35fe8587f0a400138b31dbde47ee2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/common.py @@ -0,0 +1,359 @@ +"""Base shared classes and utilities.""" + +import collections +import contextlib +import dataclasses +import os +import shutil +import tempfile +import textwrap +import time +from typing import cast, Any +from collections.abc import Iterable, Iterator +import uuid + +import torch + + +__all__ = ["TaskSpec", "Measurement", "select_unit", "unit_to_english", "trim_sigfig", "ordered_unique", "set_torch_threads"] + + +_MAX_SIGNIFICANT_FIGURES = 4 +_MIN_CONFIDENCE_INTERVAL = 25e-9 # 25 ns + +# Measurement will include a warning if the distribution is suspect. All +# runs are expected to have some variation; these parameters set the +# thresholds. +_IQR_WARN_THRESHOLD = 0.1 +_IQR_GROSS_WARN_THRESHOLD = 0.25 + + +@dataclasses.dataclass(init=True, repr=False, eq=True, frozen=True) +class TaskSpec: + """Container for information used to define a Timer. (except globals)""" + stmt: str + setup: str + global_setup: str = "" + label: str | None = None + sub_label: str | None = None + description: str | None = None + env: str | None = None + num_threads: int = 1 + + @property + def title(self) -> str: + """Best effort attempt at a string label for the measurement.""" + if self.label is not None: + return self.label + (f": {self.sub_label}" if self.sub_label else "") + elif "\n" not in self.stmt: + return self.stmt + (f": {self.sub_label}" if self.sub_label else "") + return ( + f"stmt:{f' ({self.sub_label})' if self.sub_label else ''}\n" + f"{textwrap.indent(self.stmt, ' ')}" + ) + + def setup_str(self) -> str: + return ( + "" if (self.setup == "pass" or not self.setup) + else f"setup:\n{textwrap.indent(self.setup, ' ')}" if "\n" in self.setup + else f"setup: {self.setup}" + ) + + def summarize(self) -> str: + """Build TaskSpec portion of repr string for other containers.""" + sections = [ + self.title, + self.description or "", + self.setup_str(), + ] + return "\n".join([f"{i}\n" if "\n" in i else i for i in sections if i]) + +_TASKSPEC_FIELDS = tuple(i.name for i in dataclasses.fields(TaskSpec)) + + +@dataclasses.dataclass(init=True, repr=False) +class Measurement: + """The result of a Timer measurement. + + This class stores one or more measurements of a given statement. It is + serializable and provides several convenience methods + (including a detailed __repr__) for downstream consumers. + """ + number_per_run: int + raw_times: list[float] + task_spec: TaskSpec + metadata: dict[Any, Any] | None = None # Reserved for user payloads. + + def __post_init__(self) -> None: + self._sorted_times: tuple[float, ...] = () + self._warnings: tuple[str, ...] = () + self._median: float = -1.0 + self._mean: float = -1.0 + self._p25: float = -1.0 + self._p75: float = -1.0 + + def __getattr__(self, name: str) -> Any: + # Forward TaskSpec fields for convenience. + if name in _TASKSPEC_FIELDS: + return getattr(self.task_spec, name) + return super().__getattribute__(name) + + # ========================================================================= + # == Convenience methods for statistics =================================== + # ========================================================================= + # + # These methods use raw time divided by number_per_run; this is an + # extrapolation and hides the fact that different number_per_run will + # result in different amortization of overheads, however if Timer has + # selected an appropriate number_per_run then this is a non-issue, and + # forcing users to handle that division would result in a poor experience. + @property + def times(self) -> list[float]: + return [t / self.number_per_run for t in self.raw_times] + + @property + def median(self) -> float: + self._lazy_init() + return self._median + + @property + def mean(self) -> float: + self._lazy_init() + return self._mean + + @property + def iqr(self) -> float: + self._lazy_init() + return self._p75 - self._p25 + + @property + def significant_figures(self) -> int: + """Approximate significant figure estimate. + + This property is intended to give a convenient way to estimate the + precision of a measurement. It only uses the interquartile region to + estimate statistics to try to mitigate skew from the tails, and + uses a static z value of 1.645 since it is not expected to be used + for small values of `n`, so z can approximate `t`. + + The significant figure estimation used in conjunction with the + `trim_sigfig` method to provide a more human interpretable data + summary. __repr__ does not use this method; it simply displays raw + values. Significant figure estimation is intended for `Compare`. + """ + self._lazy_init() + n_total = len(self._sorted_times) + lower_bound = int(n_total // 4) + upper_bound = int(torch.tensor(3 * n_total / 4).ceil()) + interquartile_points: tuple[float, ...] = self._sorted_times[lower_bound:upper_bound] + std = torch.tensor(interquartile_points).std(unbiased=False).item() + sqrt_n = torch.tensor(len(interquartile_points)).sqrt().item() + + # Rough estimates. These are by no means statistically rigorous. + confidence_interval = max(1.645 * std / sqrt_n, _MIN_CONFIDENCE_INTERVAL) + relative_ci = torch.tensor(self._median / confidence_interval).log10().item() + num_significant_figures = int(torch.tensor(relative_ci).floor()) + return min(max(num_significant_figures, 1), _MAX_SIGNIFICANT_FIGURES) + + @property + def has_warnings(self) -> bool: + self._lazy_init() + return bool(self._warnings) + + def _lazy_init(self) -> None: + if self.raw_times and not self._sorted_times: + self._sorted_times = tuple(sorted(self.times)) + _sorted_times = torch.tensor(self._sorted_times, dtype=torch.float64) + self._median = _sorted_times.quantile(.5).item() + self._mean = _sorted_times.mean().item() + self._p25 = _sorted_times.quantile(.25).item() + self._p75 = _sorted_times.quantile(.75).item() + + def add_warning(msg: str) -> None: + rel_iqr = self.iqr / self.median * 100 + self._warnings += ( + f" WARNING: Interquartile range is {rel_iqr:.1f}% " + f"of the median measurement.\n {msg}", + ) + + if not self.meets_confidence(_IQR_GROSS_WARN_THRESHOLD): + add_warning("This suggests significant environmental influence.") + elif not self.meets_confidence(_IQR_WARN_THRESHOLD): + add_warning("This could indicate system fluctuation.") + + + def meets_confidence(self, threshold: float = _IQR_WARN_THRESHOLD) -> bool: + return self.iqr / self.median < threshold + + @property + def title(self) -> str: + return self.task_spec.title + + @property + def env(self) -> str: + return ( + "Unspecified env" if self.taskspec.env is None + else cast(str, self.taskspec.env) + ) + + @property + def as_row_name(self) -> str: + return self.sub_label or self.stmt or "[Unknown]" + + def __repr__(self) -> str: + """ + Example repr: + + Broadcasting add (4x8) + Median: 5.73 us + IQR: 2.25 us (4.01 to 6.26) + 372 measurements, 100 runs per measurement, 1 thread + WARNING: Interquartile range is 39.4% of the median measurement. + This suggests significant environmental influence. + """ + self._lazy_init() + skip_line, newline = "MEASUREMENT_REPR_SKIP_LINE", "\n" + n = len(self._sorted_times) + time_unit, time_scale = select_unit(self._median) + iqr_filter = '' if n >= 4 else skip_line + + repr_str = f""" +{super().__repr__()} +{self.task_spec.summarize()} + {'Median: ' if n > 1 else ''}{self._median / time_scale:.2f} {time_unit} + {iqr_filter}IQR: {self.iqr / time_scale:.2f} {time_unit} ({self._p25 / time_scale:.2f} to {self._p75 / time_scale:.2f}) + {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 ''} +{newline.join(self._warnings)}""".strip() + + return "\n".join(l for l in repr_str.splitlines(keepends=False) if skip_line not in l) + + @staticmethod + def merge(measurements: Iterable["Measurement"]) -> list["Measurement"]: + """Convenience method for merging replicates. + + Merge will extrapolate times to `number_per_run=1` and will not + transfer any metadata. (Since it might differ between replicates) + """ + grouped_measurements: collections.defaultdict[TaskSpec, list[Measurement]] = collections.defaultdict(list) + for m in measurements: + grouped_measurements[m.task_spec].append(m) + + def merge_group(task_spec: TaskSpec, group: list["Measurement"]) -> "Measurement": + times: list[float] = [] + for m in group: + # Different measurements could have different `number_per_run`, + # so we call `.times` which normalizes the results. + times.extend(m.times) + + return Measurement( + number_per_run=1, + raw_times=times, + task_spec=task_spec, + metadata=None, + ) + + return [merge_group(t, g) for t, g in grouped_measurements.items()] + + +def select_unit(t: float) -> tuple[str, float]: + """Determine how to scale times for O(1) magnitude. + + This utility is used to format numbers for human consumption. + """ + time_unit = {-3: "ns", -2: "us", -1: "ms"}.get(int(torch.tensor(t).log10().item() // 3), "s") + time_scale = {"ns": 1e-9, "us": 1e-6, "ms": 1e-3, "s": 1}[time_unit] + return time_unit, time_scale + + +def unit_to_english(u: str) -> str: + return { + "ns": "nanosecond", + "us": "microsecond", + "ms": "millisecond", + "s": "second", + }[u] + + +def trim_sigfig(x: float, n: int) -> float: + """Trim `x` to `n` significant figures. (e.g. 3.14159, 2 -> 3.10000)""" + if n != int(n): + raise AssertionError("Number of significant figures must be an integer") + magnitude = int(torch.tensor(x).abs().log10().ceil().item()) + scale = 10 ** (magnitude - n) + return float(torch.tensor(x / scale).round() * scale) + + +def ordered_unique(elements: Iterable[Any]) -> list[Any]: + return list(collections.OrderedDict(dict.fromkeys(elements)).keys()) + + +@contextlib.contextmanager +def set_torch_threads(n: int) -> Iterator[None]: + prior_num_threads = torch.get_num_threads() + try: + torch.set_num_threads(n) + yield + finally: + torch.set_num_threads(prior_num_threads) + + +def _make_temp_dir(prefix: str | None = None, gc_dev_shm: bool = False) -> str: + """Create a temporary directory. The caller is responsible for cleanup. + + This function is conceptually similar to `tempfile.mkdtemp`, but with + the key additional feature that it will use shared memory if the + `BENCHMARK_USE_DEV_SHM` environment variable is set. This is an + implementation detail, but an important one for cases where many Callgrind + measurements are collected at once. (Such as when collecting + microbenchmarks.) + + This is an internal utility, and is exported solely so that microbenchmarks + can reuse the util. + """ + use_dev_shm: bool = (os.getenv("BENCHMARK_USE_DEV_SHM") or "").lower() in ("1", "true") + if use_dev_shm: + root = "/dev/shm/pytorch_benchmark_utils" + if os.name != "posix": + raise AssertionError(f"tmpfs (/dev/shm) is POSIX only, current platform is {os.name}") + if not os.path.exists("/dev/shm"): + raise AssertionError("This system does not appear to support tmpfs (/dev/shm).") + os.makedirs(root, exist_ok=True) + + # Because we're working in shared memory, it is more important than + # usual to clean up ALL intermediate files. However we don't want every + # worker to walk over all outstanding directories, so instead we only + # check when we are sure that it won't lead to contention. + if gc_dev_shm: + for i in os.listdir(root): + owner_file = os.path.join(root, i, "owner.pid") + if not os.path.exists(owner_file): + continue + + with open(owner_file) as f: + owner_pid = int(f.read()) + + if owner_pid == os.getpid(): + continue + + try: + # https://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid-in-python + os.kill(owner_pid, 0) + + except OSError: + print(f"Detected that {os.path.join(root, i)} was orphaned in shared memory. Cleaning up.") + shutil.rmtree(os.path.join(root, i)) + + else: + root = tempfile.gettempdir() + + # We include the time so names sort by creation time, and add a UUID + # to ensure we don't collide. + name = f"{prefix or tempfile.gettempprefix()}__{int(time.time())}__{uuid.uuid4()}" + path = os.path.join(root, name) + os.makedirs(path, exist_ok=False) + + if use_dev_shm: + with open(os.path.join(path, "owner.pid"), "w") as f: + f.write(str(os.getpid())) + + return path diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/compare.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..c1e232e6e04260f277254c9b181c63dfeaadee62 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/compare.py @@ -0,0 +1,345 @@ +# mypy: allow-untyped-defs +"""Display class to aggregate and print the results of many measurements.""" +import collections +import enum +import itertools as it + +from torch.utils.benchmark.utils import common +from torch import tensor as _tensor +import operator + +__all__ = ["Colorize", "Compare"] + +BEST = "\033[92m" +GOOD = "\033[34m" +BAD = "\033[2m\033[91m" +VERY_BAD = "\033[31m" +BOLD = "\033[1m" +TERMINATE = "\033[0m" + + +class Colorize(enum.Enum): + NONE = "none" + COLUMNWISE = "columnwise" + ROWWISE = "rowwise" + + +# Classes to separate internal bookkeeping from what is rendered. +class _Column: + def __init__( + self, + grouped_results: list[tuple[common.Measurement | None, ...]], + time_scale: float, + time_unit: str, + trim_significant_figures: bool, + highlight_warnings: bool, + ) -> None: + self._grouped_results = grouped_results + self._flat_results = [*it.chain.from_iterable(grouped_results)] + self._time_scale = time_scale + self._time_unit = time_unit + self._trim_significant_figures = trim_significant_figures + self._highlight_warnings = ( + highlight_warnings + and any(r.has_warnings for r in self._flat_results if r) + ) + leading_digits = [ + int(_tensor(r.median / self._time_scale).log10().ceil()) if r else None + for r in self._flat_results + ] + unit_digits = max(d for d in leading_digits if d is not None) + decimal_digits = min( + max(m.significant_figures - digits, 0) + for digits, m in zip(leading_digits, self._flat_results, strict=True) + if (m is not None) and (digits is not None) + ) if self._trim_significant_figures else 1 + length = unit_digits + decimal_digits + (1 if decimal_digits else 0) + self._template = f"{{:>{length}.{decimal_digits}f}}{{:>{7 if self._highlight_warnings else 0}}}" + + def get_results_for(self, group): + return self._grouped_results[group] + + def num_to_str(self, value: float | None, estimated_sigfigs: int, spread: float | None): + if value is None: + return " " * len(self.num_to_str(1, estimated_sigfigs, None)) + + if self._trim_significant_figures: + value = common.trim_sigfig(value, estimated_sigfigs) + + return self._template.format( + value, + f" (! {spread * 100:.0f}%)" if self._highlight_warnings and spread is not None else "") + + +def optional_min(seq): + l = list(seq) + return None if len(l) == 0 else min(l) + + +class _Row: + def __init__(self, results, row_group, render_env, env_str_len, + row_name_str_len, time_scale, colorize, num_threads=None) -> None: + super().__init__() + self._results = results + self._row_group = row_group + self._render_env = render_env + self._env_str_len = env_str_len + self._row_name_str_len = row_name_str_len + self._time_scale = time_scale + self._colorize = colorize + self._columns: tuple[_Column, ...] = () + self._num_threads = num_threads + + def register_columns(self, columns: tuple[_Column, ...]) -> None: + self._columns = columns + + def as_column_strings(self): + concrete_results = [r for r in self._results if r is not None] + env = f"({concrete_results[0].env})" if self._render_env else "" + env = env.ljust(self._env_str_len + 4) + output = [" " + env + concrete_results[0].as_row_name] + for m, col in zip(self._results, self._columns or (), strict=False): + if m is None: + output.append(col.num_to_str(None, 1, None)) + else: + output.append(col.num_to_str( + m.median / self._time_scale, + m.significant_figures, + m.iqr / m.median if m.has_warnings else None + )) + return output + + @staticmethod + def color_segment(segment, value, best_value): + if value <= best_value * 1.01 or value <= best_value + 100e-9: + return BEST + BOLD + segment + TERMINATE * 2 + if value <= best_value * 1.1: + return GOOD + BOLD + segment + TERMINATE * 2 + if value >= best_value * 5: + return VERY_BAD + BOLD + segment + TERMINATE * 2 + if value >= best_value * 2: + return BAD + segment + TERMINATE * 2 + + return segment + + def row_separator(self, overall_width): + return ( + [f"{self._num_threads} threads: ".ljust(overall_width, "-")] + if self._num_threads is not None else [] + ) + + def finalize_column_strings(self, column_strings, col_widths): + best_values = [-1 for _ in column_strings] + if self._colorize == Colorize.ROWWISE: + row_min = min(r.median for r in self._results if r is not None) + best_values = [row_min for _ in column_strings] + elif self._colorize == Colorize.COLUMNWISE: + best_values = [ + optional_min(r.median for r in column.get_results_for(self._row_group) if r is not None) + for column in (self._columns or ()) + ] + + row_contents = [column_strings[0].ljust(col_widths[0])] + for col_str, width, result, best_value in zip(column_strings[1:], col_widths[1:], self._results, best_values, strict=False): + col_str = col_str.center(width) + if self._colorize != Colorize.NONE and result is not None and best_value is not None: + col_str = self.color_segment(col_str, result.median, best_value) + row_contents.append(col_str) + return row_contents + + +class Table: + def __init__( + self, + results: list[common.Measurement], + colorize: Colorize, + trim_significant_figures: bool, + highlight_warnings: bool + ) -> None: + if len({r.label for r in results}) != 1: + raise AssertionError("All results must share the same label") + + self.results = results + self._colorize = colorize + self._trim_significant_figures = trim_significant_figures + self._highlight_warnings = highlight_warnings + self.label = results[0].label + self.time_unit, self.time_scale = common.select_unit( + min(r.median for r in results) + ) + + self.row_keys = common.ordered_unique([self.row_fn(i) for i in results]) + self.row_keys.sort(key=operator.itemgetter(slice(2))) # preserve stmt order + self.column_keys = common.ordered_unique([self.col_fn(i) for i in results]) + self.rows, self.columns = self.populate_rows_and_columns() + + @staticmethod + def row_fn(m: common.Measurement) -> tuple[int, str | None, str]: + return m.num_threads, m.env, m.as_row_name + + @staticmethod + def col_fn(m: common.Measurement) -> str | None: + return m.description + + def populate_rows_and_columns(self) -> tuple[tuple[_Row, ...], tuple[_Column, ...]]: + rows: list[_Row] = [] + columns: list[_Column] = [] + ordered_results: list[list[common.Measurement | None]] = [ + [None for _ in self.column_keys] + for _ in self.row_keys + ] + row_position = {key: i for i, key in enumerate(self.row_keys)} + col_position = {key: i for i, key in enumerate(self.column_keys)} + for r in self.results: + i = row_position[self.row_fn(r)] + j = col_position[self.col_fn(r)] + ordered_results[i][j] = r + + unique_envs = {r.env for r in self.results} + render_env = len(unique_envs) > 1 + env_str_len = max(len(i) for i in unique_envs) if render_env else 0 + + row_name_str_len = max(len(r.as_row_name) for r in self.results) + + prior_num_threads = -1 + prior_env = "" + row_group = -1 + rows_by_group: list[list[list[common.Measurement | None]]] = [] + for (num_threads, env, _), row in zip(self.row_keys, ordered_results, strict=True): + thread_transition = (num_threads != prior_num_threads) + if thread_transition: + prior_num_threads = num_threads + prior_env = "" + row_group += 1 + rows_by_group.append([]) + rows.append( + _Row( + results=row, + row_group=row_group, + render_env=(render_env and env != prior_env), + env_str_len=env_str_len, + row_name_str_len=row_name_str_len, + time_scale=self.time_scale, + colorize=self._colorize, + num_threads=num_threads if thread_transition else None, + ) + ) + rows_by_group[-1].append(row) + prior_env = env + + for i in range(len(self.column_keys)): + grouped_results = [tuple(row[i] for row in g) for g in rows_by_group] + column = _Column( + grouped_results=grouped_results, + time_scale=self.time_scale, + time_unit=self.time_unit, + trim_significant_figures=self._trim_significant_figures, + highlight_warnings=self._highlight_warnings,) + columns.append(column) + + rows_tuple, columns_tuple = tuple(rows), tuple(columns) + for ri in rows_tuple: + ri.register_columns(columns_tuple) + return rows_tuple, columns_tuple + + def render(self) -> str: + string_rows = [[""] + self.column_keys] + string_rows.extend(r.as_column_strings() for r in self.rows) + num_cols = max(len(i) for i in string_rows) + for sr in string_rows: + sr.extend(["" for _ in range(num_cols - len(sr))]) + + col_widths = [max(len(j) for j in i) for i in zip(*string_rows, strict=True)] + finalized_columns = [" | ".join(i.center(w) for i, w in zip(string_rows[0], col_widths, strict=True))] + overall_width = len(finalized_columns[0]) + for string_row, row in zip(string_rows[1:], self.rows, strict=True): + finalized_columns.extend(row.row_separator(overall_width)) + finalized_columns.append(" | ".join(row.finalize_column_strings(string_row, col_widths))) + + newline = "\n" + has_warnings = self._highlight_warnings and any(ri.has_warnings for ri in self.results) + return f""" +[{(' ' + (self.label or '') + ' ').center(overall_width - 2, '-')}] +{newline.join(finalized_columns)} + +Times are in {common.unit_to_english(self.time_unit)}s ({self.time_unit}). +{'(! XX%) Measurement has high variance, where XX is the IQR / median * 100.' + newline if has_warnings else ""}"""[1:] + + +class Compare: + """Helper class for displaying the results of many measurements in a + formatted table. + + The table format is based on the information fields provided in + :class:`torch.utils.benchmark.Timer` (`description`, `label`, `sub_label`, + `num_threads`, etc). + + The table can be directly printed using :meth:`print` or casted as a `str`. + + For a full tutorial on how to use this class, see: + https://pytorch.org/tutorials/recipes/recipes/benchmark.html + + Args: + results: List of Measurement to display. + """ + def __init__(self, results: list[common.Measurement]) -> None: + self._results: list[common.Measurement] = [] + self.extend_results(results) + self._trim_significant_figures = False + self._colorize = Colorize.NONE + self._highlight_warnings = False + + def __str__(self) -> str: + return "\n".join(self._render()) + + def extend_results(self, results) -> None: + """Append results to already stored ones. + + All added results must be instances of ``Measurement``. + """ + for r in results: + if not isinstance(r, common.Measurement): + raise ValueError( + "Expected an instance of `Measurement`, " f"got {type(r)} instead." + ) + self._results.extend(results) + + def trim_significant_figures(self) -> None: + """Enables trimming of significant figures when building the formatted table.""" + self._trim_significant_figures = True + + def colorize(self, rowwise=False) -> None: + """Colorize formatted table. + + Colorize columnwise by default. + """ + self._colorize = Colorize.ROWWISE if rowwise else Colorize.COLUMNWISE + + def highlight_warnings(self) -> None: + """Enables warning highlighting when building formatted table.""" + self._highlight_warnings = True + + def print(self) -> None: + """Print formatted table""" + print(str(self)) + + def _render(self): + results = common.Measurement.merge(self._results) + grouped_results = self._group_by_label(results) + output = [self._layout(group) for group in grouped_results.values()] + return output + + def _group_by_label(self, results: list[common.Measurement]): + grouped_results: collections.defaultdict[str, list[common.Measurement]] = collections.defaultdict(list) + for r in results: + grouped_results[r.label].append(r) + return grouped_results + + def _layout(self, results: list[common.Measurement]): + table = Table( + results, + self._colorize, + self._trim_significant_figures, + self._highlight_warnings + ) + return table.render() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/compile.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/compile.py new file mode 100644 index 0000000000000000000000000000000000000000..711be6912827e584ef29df5a681c4e9634439da9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/compile.py @@ -0,0 +1,194 @@ +# mypy: allow-untyped-defs +from typing import Any, cast +from collections.abc import Callable + +import torch +import torch._dynamo +from torch._dynamo.testing import CompileCounterWithBackend +from torch.utils.benchmark import Timer + + +__all__ = ["bench_all", "benchmark_compile"] + + +_warned_tensor_cores = False +_default_float_32_precision = torch.get_float32_matmul_precision() + +try: + + from tabulate import tabulate + + HAS_TABULATE = True +except ModuleNotFoundError: + HAS_TABULATE = False + tabulate = None # type: ignore[assignment] + print("tabulate is not installed, please pip install tabulate to use this utility") + +if HAS_TABULATE: + def _enable_tensor_cores() -> None: + global _warned_tensor_cores + + if torch.cuda.is_available(): + if torch.backends.cuda.matmul.allow_tf32 is False and torch.cuda.get_device_capability() >= (8, 0): + torch.set_float32_matmul_precision("high") + if not _warned_tensor_cores: + print("Your GPU supports tensor cores") + print("we will enable it automatically by setting `torch.set_float32_matmul_precision('high')`") + _warned_tensor_cores = True + + def _disable_tensor_cores() -> None: + torch.set_float32_matmul_precision(_default_float_32_precision) + + def bench_loop( + model: torch.nn.Module | Callable, + sample_input: torch.Tensor | Any, + num_iters: int = 5, + optimizer: torch.optim.Optimizer | None = None, + loss_fn: Callable | None = None, + ): + # Define the statement and setup for the benchmark + if optimizer and loss_fn: + # Training mode + stmt = """ + output = model(sample_input) + loss = loss_fn(output) if loss_fn else output.sum() + loss.backward() + optimizer.step() + optimizer.zero_grad() + """ + else: + # Inference mode + stmt = "model(sample_input)" + + # Create the Timer object + timer = Timer( + stmt=stmt, + globals={"model": model, "sample_input": sample_input, "optimizer": optimizer, "loss_fn": loss_fn}, + ) + + + result = timer.timeit(number=num_iters) + + # Get the average time per iteration in milliseconds + avg_time = result.mean * 1000 + return round(avg_time, 2) + + def benchmark_compile( + model: torch.nn.Module | Callable, + sample_input: torch.Tensor | Any, + num_iters: int = 5, + backend: str | None = None, + mode: str | None = "default", + optimizer: torch.optim.Optimizer | None = None, + loss_fn : torch.nn.Module | Callable | None = None, + ): + """ + Use this utility to benchmark torch.compile + """ + if backend: + try: + torch._dynamo.reset() + compile_counter_with_backend = CompileCounterWithBackend(backend) + opt_model = torch.compile(model, backend=compile_counter_with_backend, mode=mode) + + # Compilation only happens after the first inference + compilation_time = bench_loop(opt_model, sample_input, 1, optimizer, loss_fn) + + running_time = bench_loop(opt_model, sample_input, num_iters, optimizer, loss_fn) + + if compile_counter_with_backend.frame_count == 0: + raise RuntimeError("No compilation occurred during benchmarking.") + + if compile_counter_with_backend.frame_count > 1: + raise RuntimeError("Recompilation occurred during benchmarking.") + + except Exception as e: + print(e) + print(f"Failed to compile {backend} with mode {mode}") + return None, None + else: + opt_model = model + compilation_time = None + running_time = bench_loop(opt_model, sample_input, num_iters, optimizer, loss_fn) + + compilation_time = round(compilation_time, 2) if compilation_time else None + running_time = round(running_time, 2) if running_time else None + + + return compilation_time, running_time + + + def bench_all( + model : torch.nn.Module | Callable, + sample_input: torch.Tensor | Any, + num_iters : int = 5, + optimizer: torch.optim.Optimizer | None = None, + loss_fn : torch.nn.Module | Callable | None = None, + ): + """ + This is a simple utility that can be used to benchmark torch.compile + In particular it ensures that your GPU is setup to use tensor cores if it supports its + It also tries out all the main backends and prints a table of results so you can easily compare them all + Many of the backends have their own optional dependencies so please pip install them separately + + You will get one table for inference and another for training + If you'd like to leverage this utility for training make sure to pass in a torch.optim.Optimizer + + The important warnings are + Your GPU supports tensor cores + we will enable it automatically by setting `torch.set_float32_matmul_precision('high')` + + If a compilation fails for any reason including the dependency not being included + then we will print Failed to compile {backend} with mode {mode} + """ + field_names = ["Train/Inference", "Backend", "Mode", "Compilation Time", "Average Running Time"] + table = [] + + + eager_time = None + torch._dynamo.reset() + _, eager_time = benchmark_compile(model, sample_input, num_iters, None, None, optimizer) + table.append( + [("Training" if optimizer else "Inference"), "Eager", "-", "-", f"{eager_time} ms"] + ) + + for backend in torch._dynamo.list_backends(): + + if backend == "inductor": + mode_options = cast(list[str | None], list(torch._inductor.list_mode_options().keys())) + [None] + for mode in mode_options: + if mode == "default": + continue + torch._dynamo.reset() + try: + if torch.cuda.is_available(): + _enable_tensor_cores() + compilation_time, running_time = benchmark_compile( + model, sample_input, num_iters, backend, mode, optimizer, loss_fn) + finally: + if torch.cuda.is_available(): + _disable_tensor_cores() + table.append([ + ("Training" if optimizer else "Inference"), + backend if backend else "-", + mode if mode is not None else "-", + f"{compilation_time} ms " if compilation_time else "-", + f"{running_time} ms " if running_time else "-", + ]) + + else: + torch._dynamo.reset() + compilation_time, running_time = benchmark_compile( + model, sample_input, num_iters, backend, None, optimizer, loss_fn) + + if running_time is not None: + table.append([ + ("Training" if optimizer else "Inference"), + backend, "-", + f"{compilation_time} ms " or "-", + f"{running_time} ms ", + ]) + + + # pyrefly: ignore [not-callable] + return tabulate(table, headers=field_names, tablefmt="github") diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/cpp_jit.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/cpp_jit.py new file mode 100644 index 0000000000000000000000000000000000000000..a298146ce17c7ff6f303b4d76c4c96ba786ae774 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/cpp_jit.py @@ -0,0 +1,175 @@ +"""JIT C++ strings into executables.""" +import atexit +import os +import re +import shutil +import textwrap +import threading +from typing import Any + +import torch +from torch.utils.benchmark.utils._stubs import CallgrindModuleType, TimeitModuleType +from torch.utils.benchmark.utils.common import _make_temp_dir +from torch.utils import cpp_extension + + +LOCK = threading.Lock() +SOURCE_ROOT = os.path.split(os.path.abspath(__file__))[0] + +# We calculate uuid once at import time so that separate processes will have +# separate build roots, but threads will share the same build root. +# `cpp_extension` uses build root as part of the cache key, so per-invocation +# uuid's (e.g. different build root per _compile_template call) would lead to +# a 0% cache hit rate and spurious recompilation. Consider the following: +# ``` +# setup = "auto x = torch::ones({1024, 1024});" +# stmt = "torch::mm(x, x);" +# for num_threads in [1, 2, 4, 8]: +# print(Timer(stmt, setup, num_threads=num_threads, language="c++").blocked_autorange()) +# ```` +# `setup` and `stmt` do not change, so we can reuse the executable from the +# first pass through the loop. +_BUILD_ROOT: str | None = None + +def _get_build_root() -> str: + global _BUILD_ROOT + if _BUILD_ROOT is None: + _BUILD_ROOT = _make_temp_dir(prefix="benchmark_utils_jit_build") + # pyrefly: ignore [missing-argument] + atexit.register(shutil.rmtree, _BUILD_ROOT) + return _BUILD_ROOT + + +# BACK_TESTING_NOTE: +# There are two workflows where this code could be used. One is the obvious +# case where someone simply builds or installs PyTorch and uses Timer. +# The other is that the entire `torch/utils/benchmark` folder from a CURRENT +# PyTorch checkout is copy-pasted into a much OLDER version of the PyTorch +# source code. This is what we refer to here as "back testing". The rationale +# is that we might want to use current tooling to study some aspect of an +# earlier version of PyTorch. (e.g. a regression.) +# +# The problem is that Timer relies on several aspects of core PyTorch, namely +# some binding functions for Valgrind symbols in `torch._C` and the +# `torch.__config__._cxx_flags()` method. If we were to naively copy code +# around this wouldn't work as the symbols of interest aren't present in +# earlier versions of PyTorch. In order to work around this, we must add back +# testing shims. These shims will never activate during normal use, but will +# allow Timer to function outside of the "correct" version of PyTorch by +# emulating functionality that was added later. +# +# These shims are temporary, and as Timer becomes more integrated with +# PyTorch the cost and complexity of such shims will increase. Once back +# testing is no longer required (which is to say we have done enough historic +# analysis and the shims no longer justify their maintenance and code +# complexity costs) back testing paths will be removed. + +CXX_FLAGS: list[str] | None +if hasattr(torch.__config__, "_cxx_flags"): + try: + CXX_FLAGS = torch.__config__._cxx_flags().strip().split() + if CXX_FLAGS is not None and "-g" not in CXX_FLAGS: + CXX_FLAGS.append("-g") + # remove "-W" flags to allow build benchmarks + # with a relaxed constraint of compiler versions + if CXX_FLAGS is not None: + CXX_FLAGS = list(filter(lambda x: not x.startswith("-W"), CXX_FLAGS)) + + except RuntimeError: + # We are in FBCode. + CXX_FLAGS = None +else: + # FIXME: Remove when back testing is no longer required. + CXX_FLAGS = ["-O2", "-fPIC", "-g"] + +EXTRA_INCLUDE_PATHS: list[str] = [os.path.join(SOURCE_ROOT, "valgrind_wrapper")] +CONDA_PREFIX = os.getenv("CONDA_PREFIX") +if CONDA_PREFIX is not None: + # Load will automatically search /usr/include, but not conda include. + EXTRA_INCLUDE_PATHS.append(os.path.join(CONDA_PREFIX, "include")) + + +COMPAT_CALLGRIND_BINDINGS: CallgrindModuleType | None = None +def get_compat_bindings() -> CallgrindModuleType: + with LOCK: + global COMPAT_CALLGRIND_BINDINGS + if COMPAT_CALLGRIND_BINDINGS is None: + COMPAT_CALLGRIND_BINDINGS = cpp_extension.load( + name="callgrind_bindings", + sources=[os.path.join( + SOURCE_ROOT, + "valgrind_wrapper", + "compat_bindings.cpp" + )], + extra_cflags=CXX_FLAGS, + extra_include_paths=EXTRA_INCLUDE_PATHS, + ) + return COMPAT_CALLGRIND_BINDINGS + + +def _compile_template( + *, + stmt: str, + setup: str, + global_setup: str, + src: str, + is_standalone: bool +) -> Any: + for before, after, indentation in ( + ("// GLOBAL_SETUP_TEMPLATE_LOCATION", global_setup, 0), + ("// SETUP_TEMPLATE_LOCATION", setup, 4), + ("// STMT_TEMPLATE_LOCATION", stmt, 8) + ): + # C++ doesn't care about indentation so this code isn't load + # bearing the way it is with Python, but this makes the source + # look nicer if a human has to look at it. + src = re.sub( + before, + textwrap.indent(after, " " * indentation)[indentation:], + src + ) + + # We want to isolate different Timers. However `cpp_extension` will + # cache builds which will significantly reduce the cost of repeated + # invocations. + with LOCK: + name = f"timer_cpp_{abs(hash(src))}" + build_dir = os.path.join(_get_build_root(), name) + os.makedirs(build_dir, exist_ok=True) + + src_path = os.path.join(build_dir, "timer_src.cpp") + with open(src_path, "w") as f: + f.write(src) + + # `cpp_extension` has its own locking scheme, so we don't need our lock. + return cpp_extension.load( + name=name, + sources=[src_path], + build_directory=build_dir, + extra_cflags=CXX_FLAGS, + extra_include_paths=EXTRA_INCLUDE_PATHS, + is_python_module=not is_standalone, + is_standalone=is_standalone, + ) + + +def compile_timeit_template(*, stmt: str, setup: str, global_setup: str) -> TimeitModuleType: + template_path: str = os.path.join(SOURCE_ROOT, "timeit_template.cpp") + with open(template_path) as f: + src: str = f.read() + + module = _compile_template(stmt=stmt, setup=setup, global_setup=global_setup, src=src, is_standalone=False) + if not isinstance(module, TimeitModuleType): + raise AssertionError("compiled module is not a TimeitModuleType") + return module + + +def compile_callgrind_template(*, stmt: str, setup: str, global_setup: str) -> str: + template_path: str = os.path.join(SOURCE_ROOT, "valgrind_wrapper", "timer_callgrind_template.cpp") + with open(template_path) as f: + src: str = f.read() + + target = _compile_template(stmt=stmt, setup=setup, global_setup=global_setup, src=src, is_standalone=True) + if not isinstance(target, str): + raise AssertionError("compiled target path is not a string") + return target diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/fuzzer.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/fuzzer.py new file mode 100644 index 0000000000000000000000000000000000000000..38f771d23632efd27239e460591d923be3ee59fc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/fuzzer.py @@ -0,0 +1,469 @@ +# mypy: allow-untyped-defs +import functools +import itertools as it +from typing import Any +from collections.abc import Callable + +import torch + + +__all__ = [ + "Fuzzer", + "FuzzedParameter", "ParameterAlias", + "FuzzedTensor", +] + + +_DISTRIBUTIONS = ( + "loguniform", + "uniform", +) + + +class FuzzedParameter: + """Specification for a parameter to be generated during fuzzing.""" + def __init__( + self, + name: str, + minval: int | float | None = None, + maxval: int | float | None = None, + distribution: str | dict[Any, float] | None = None, + strict: bool = False, + ) -> None: + """ + Args: + name: + A string name with which to identify the parameter. + FuzzedTensors can reference this string in their + specifications. + minval: + The lower bound for the generated value. See the description + of `distribution` for type behavior. + maxval: + The upper bound for the generated value. Type behavior is + identical to `minval`. + distribution: + Specifies the distribution from which this parameter should + be drawn. There are three possibilities: + - "loguniform" + Samples between `minval` and `maxval` (inclusive) such + that the probabilities are uniform in log space. As a + concrete example, if minval=1 and maxval=100, a sample + is as likely to fall in [1, 10) as it is [10, 100]. + - "uniform" + Samples are chosen with uniform probability between + `minval` and `maxval` (inclusive). If either `minval` + or `maxval` is a float then the distribution is the + continuous uniform distribution; otherwise samples + are constrained to the integers. + - dict: + If a dict is passed, the keys are taken to be choices + for the variables and the values are interpreted as + probabilities. (And must sum to one.) + If a dict is passed, `minval` and `maxval` must not be set. + Otherwise, they must be set. + strict: + If a parameter is strict, it will not be included in the + iterative resampling process which Fuzzer uses to find a + valid parameter configuration. This allows an author to + prevent skew from resampling for a given parameter (for + instance, a low size limit could inadvertently bias towards + Tensors with fewer dimensions) at the cost of more iterations + when generating parameters. + """ + self._name = name + self._minval = minval + self._maxval = maxval + self._distribution = self._check_distribution(distribution) + self.strict = strict + + @property + def name(self): + return self._name + + def sample(self, state): + if self._distribution == "loguniform": + return self._loguniform(state) + + if self._distribution == "uniform": + return self._uniform(state) + + if isinstance(self._distribution, dict): + return self._custom_distribution(state) + + def _check_distribution(self, distribution): + if not isinstance(distribution, dict): + if distribution not in _DISTRIBUTIONS: + raise AssertionError(f"Unknown distribution: {distribution}") + else: + if any(i < 0 for i in distribution.values()): + raise AssertionError("Probabilities cannot be negative") + if not abs(sum(distribution.values()) - 1) > 1e-5: + raise AssertionError("Distribution is not normalized") + if self._minval is not None: + raise AssertionError("When passing a custom distribution, 'minval' must be None") + if self._maxval is not None: + raise AssertionError("When passing a custom distribution, 'maxval' must be None") + + return distribution + + def _loguniform(self, state): + import numpy as np + output = int(2 ** state.uniform( + low=np.log2(self._minval) if self._minval is not None else None, + high=np.log2(self._maxval) if self._maxval is not None else None, + )) + if self._minval is not None and output < self._minval: + return self._minval + if self._maxval is not None and output > self._maxval: + return self._maxval + return output + + def _uniform(self, state): + if isinstance(self._minval, int) and isinstance(self._maxval, int): + return int(state.randint(low=self._minval, high=self._maxval + 1)) + return state.uniform(low=self._minval, high=self._maxval) + + def _custom_distribution(self, state): + import numpy as np + # If we directly pass the keys to `choice`, numpy will convert + # them to numpy dtypes. + index = state.choice( + np.arange(len(self._distribution)), + p=tuple(self._distribution.values())) + return list(self._distribution.keys())[index] + + +class ParameterAlias: + """Indicates that a parameter should alias the value of another parameter. + + When used in conjunction with a custom distribution, this allows fuzzed + tensors to represent a broader range of behaviors. For example, the + following sometimes produces Tensors which broadcast: + + Fuzzer( + parameters=[ + FuzzedParameter("x_len", 4, 1024, distribution="uniform"), + + # `y` will either be size one, or match the size of `x`. + FuzzedParameter("y_len", distribution={ + 0.5: 1, + 0.5: ParameterAlias("x_len") + }), + ], + tensors=[ + FuzzedTensor("x", size=("x_len",)), + FuzzedTensor("y", size=("y_len",)), + ], + ) + + Chains of alias' are allowed, but may not contain cycles. + """ + def __init__(self, alias_to) -> None: + self.alias_to = alias_to + + def __repr__(self) -> str: + return f"ParameterAlias[alias_to: {self.alias_to}]" + + +def dtype_size(dtype): + if dtype == torch.bool: + return 1 + if dtype.is_floating_point or dtype.is_complex: + return int(torch.finfo(dtype).bits / 8) + return int(torch.iinfo(dtype).bits / 8) + + +def prod(values, base=1): + """np.prod can overflow, so for sizes the product should be done in Python. + + Even though np.prod type promotes to int64, it can still overflow in which + case the negative value will pass the size check and OOM when attempting to + actually allocate the Tensor. + """ + return functools.reduce(lambda x, y: int(x) * int(y), values, base) + + +class FuzzedTensor: + def __init__( + self, + name: str, + size: tuple[str | int, ...], + steps: tuple[str | int, ...] | None = None, + probability_contiguous: float = 0.5, + min_elements: int | None = None, + max_elements: int | None = None, + max_allocation_bytes: int | None = None, + dim_parameter: str | None = None, + roll_parameter: str | None = None, + dtype=torch.float32, + cuda=False, + tensor_constructor: Callable | None = None + ) -> None: + """ + Args: + name: + A string identifier for the generated Tensor. + size: + A tuple of integers or strings specifying the size of the generated + Tensor. String values will replaced with a concrete int during the + generation process, while ints are simply passed as literals. + steps: + An optional tuple with the same length as `size`. This indicates + that a larger Tensor should be allocated, and then sliced to + produce the generated Tensor. For instance, if size is (4, 8) + and steps is (1, 4), then a tensor `t` of size (4, 32) will be + created and then `t[:, ::4]` will be used. (Allowing one to test + Tensors with strided memory.) + probability_contiguous: + A number between zero and one representing the chance that the + generated Tensor has a contiguous memory layout. This is achieved by + randomly permuting the shape of a Tensor, calling `.contiguous()`, + and then permuting back. This is applied before `steps`, which can + also cause a Tensor to be non-contiguous. + min_elements: + The minimum number of parameters that this Tensor must have for a + set of parameters to be valid. (Otherwise they are resampled.) + max_elements: + Like `min_elements`, but setting an upper bound. + max_allocation_bytes: + Like `max_elements`, but for the size of Tensor that must be + allocated prior to slicing for `steps` (if applicable). For + example, a FloatTensor with size (1024, 1024) and steps (4, 4) + would have 1M elements, but would require a 64 MB allocation. + dim_parameter: + The length of `size` and `steps` will be truncated to this value. + This allows Tensors of varying dimensions to be generated by the + Fuzzer. + dtype: + The PyTorch dtype of the generated Tensor. + cuda: + Whether to place the Tensor on a GPU. + tensor_constructor: + Callable which will be used instead of the default Tensor + construction method. This allows the author to enforce properties + of the Tensor (e.g. it can only have certain values). The dtype and + concrete shape of the Tensor to be created will be passed, and + concrete values of all parameters will be passed as kwargs. Note + that transformations to the result (permuting, slicing) will be + performed by the Fuzzer; the tensor_constructor is only responsible + for creating an appropriately sized Tensor. + """ + self._name = name + self._size = size + self._steps = steps + self._probability_contiguous = probability_contiguous + self._min_elements = min_elements + self._max_elements = max_elements + self._max_allocation_bytes = max_allocation_bytes + self._dim_parameter = dim_parameter + self._dtype = dtype + self._cuda = cuda + self._tensor_constructor = tensor_constructor + + @property + def name(self): + return self._name + + @staticmethod + def default_tensor_constructor(size, dtype, **kwargs): + if dtype.is_floating_point or dtype.is_complex: + return torch.rand(size=size, dtype=dtype, device="cpu") + else: + return torch.randint(1, 127, size=size, dtype=dtype, device="cpu") + + def _make_tensor(self, params, state): + import numpy as np + size, steps, allocation_size = self._get_size_and_steps(params) + constructor = ( + self._tensor_constructor or + self.default_tensor_constructor + ) + + raw_tensor = constructor(size=allocation_size, dtype=self._dtype, **params) + if self._cuda: + raw_tensor = raw_tensor.cuda() + + # Randomly permute the Tensor and call `.contiguous()` to force re-ordering + # of the memory, and then permute it back to the original shape. + dim = len(size) + order = np.arange(dim) + if state.rand() > self._probability_contiguous: + while dim > 1 and np.all(order == np.arange(dim)): + order = state.permutation(raw_tensor.dim()) + + raw_tensor = raw_tensor.permute(tuple(order)).contiguous() + raw_tensor = raw_tensor.permute(tuple(np.argsort(order))) + + slices = [slice(0, size * step, step) for size, step in zip(size, steps, strict=True)] + tensor = raw_tensor[tuple(slices)] + + properties = { + "numel": int(tensor.numel()), + "order": order, + "steps": steps, + "is_contiguous": tensor.is_contiguous(), + "dtype": str(self._dtype), + } + + return tensor, properties + + def _get_size_and_steps(self, params): + dim = ( + params[self._dim_parameter] + if self._dim_parameter is not None + else len(self._size) + ) + + def resolve(values, dim): + """Resolve values into concrete integers.""" + values = tuple(params.get(i, i) for i in values) + if len(values) > dim: + values = values[:dim] + if len(values) < dim: + values = values + tuple(1 for _ in range(dim - len(values))) + return values + + size = resolve(self._size, dim) + steps = resolve(self._steps or (), dim) + allocation_size = tuple(size_i * step_i for size_i, step_i in zip(size, steps, strict=True)) + return size, steps, allocation_size + + def satisfies_constraints(self, params) -> bool: + size, _, allocation_size = self._get_size_and_steps(params) + # Product is computed in Python to avoid integer overflow. + num_elements = prod(size) + if num_elements < 0: + raise AssertionError("Computed number of elements is negative") + + allocation_bytes = prod(allocation_size, base=dtype_size(self._dtype)) + + def nullable_greater(left, right): + if left is None or right is None: + return False + return left > right + + return not any(( + nullable_greater(num_elements, self._max_elements), + nullable_greater(self._min_elements, num_elements), + nullable_greater(allocation_bytes, self._max_allocation_bytes), + )) + + +class Fuzzer: + def __init__( + self, + parameters: list[FuzzedParameter | list[FuzzedParameter]], + tensors: list[FuzzedTensor | list[FuzzedTensor]], + constraints: list[Callable] | None = None, + seed: int | None = None + ) -> None: + """ + Args: + parameters: + List of FuzzedParameters which provide specifications + for generated parameters. Iterable elements will be + unpacked, though arbitrary nested structures will not. + tensors: + List of FuzzedTensors which define the Tensors which + will be created each step based on the parameters for + that step. Iterable elements will be unpacked, though + arbitrary nested structures will not. + constraints: + List of callables. They will be called with params + as kwargs, and if any of them return False the current + set of parameters will be rejected. + seed: + Seed for the RandomState used by the Fuzzer. This will + also be used to set the PyTorch random seed so that random + ops will create reproducible Tensors. + """ + import numpy as np + if seed is None: + seed = int(np.random.RandomState().randint(0, 2 ** 32 - 1, dtype=np.int64)) + self._seed = seed + self._parameters = Fuzzer._unpack(parameters, FuzzedParameter) + self._tensors = Fuzzer._unpack(tensors, FuzzedTensor) + self._constraints = constraints or () + + p_names = {p.name for p in self._parameters} + t_names = {t.name for t in self._tensors} + name_overlap = p_names.intersection(t_names) + if name_overlap: + raise ValueError(f"Duplicate names in parameters and tensors: {name_overlap}") + + self._rejections = 0 + self._total_generated = 0 + + @staticmethod + def _unpack(values, cls): + return tuple(it.chain.from_iterable( + [[i] if isinstance(i, cls) else i for i in values] + )) + + def take(self, n): + import numpy as np + state = np.random.RandomState(self._seed) + torch.manual_seed(state.randint(low=0, high=2 ** 63, dtype=np.int64)) + for _ in range(n): + params = self._generate(state) + tensors = {} + tensor_properties = {} + for t in self._tensors: + tensor, properties = t._make_tensor(params, state) + tensors[t.name] = tensor + tensor_properties[t.name] = properties + yield tensors, tensor_properties, params + + @property + def rejection_rate(self): + if not self._total_generated: + return 0. + return self._rejections / self._total_generated + + def _generate(self, state): + strict_params: dict[str, float | int | ParameterAlias] = {} + for _ in range(1000): + candidate_params: dict[str, float | int | ParameterAlias] = {} + for p in self._parameters: + if p.strict: + if p.name in strict_params: + candidate_params[p.name] = strict_params[p.name] + else: + candidate_params[p.name] = p.sample(state) + strict_params[p.name] = candidate_params[p.name] + else: + candidate_params[p.name] = p.sample(state) + + candidate_params = self._resolve_aliases(candidate_params) + + self._total_generated += 1 + if not all(f(candidate_params) for f in self._constraints): + self._rejections += 1 + continue + + if not all(t.satisfies_constraints(candidate_params) for t in self._tensors): + self._rejections += 1 + continue + + return candidate_params + raise ValueError("Failed to generate a set of valid parameters.") + + @staticmethod + def _resolve_aliases(params): + params = dict(params) + alias_count = sum(isinstance(v, ParameterAlias) for v in params.values()) + + keys = list(params.keys()) + while alias_count: + for k in keys: + v = params[k] + if isinstance(v, ParameterAlias): + params[k] = params[v.alias_to] + alias_count_new = sum(isinstance(v, ParameterAlias) for v in params.values()) + if alias_count == alias_count_new: + raise ValueError(f"ParameterAlias cycle detected\n{params}") + + alias_count = alias_count_new + + return params diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/sparse_fuzzer.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/sparse_fuzzer.py new file mode 100644 index 0000000000000000000000000000000000000000..cf38c11240b278e07e2b53e4e2306219c4f6a9fb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/sparse_fuzzer.py @@ -0,0 +1,122 @@ +# mypy: allow-untyped-defs +from numbers import Number +import torch +from torch.utils.benchmark import FuzzedTensor +import math + +class FuzzedSparseTensor(FuzzedTensor): + def __init__( + self, + name: str, + size: tuple[str | int, ...], + min_elements: int | None = None, + max_elements: int | None = None, + dim_parameter: str | None = None, + sparse_dim: str | None = None, + nnz: str | None = None, + density: str | None = None, + coalesced: str | None = None, + dtype=torch.float32, + cuda=False + ) -> None: + """ + Args: + name: + A string identifier for the generated Tensor. + size: + A tuple of integers or strings specifying the size of the generated + Tensor. String values will replaced with a concrete int during the + generation process, while ints are simply passed as literals. + min_elements: + The minimum number of parameters that this Tensor must have for a + set of parameters to be valid. (Otherwise they are resampled.) + max_elements: + Like `min_elements`, but setting an upper bound. + dim_parameter: + The length of `size` will be truncated to this value. + This allows Tensors of varying dimensions to be generated by the + Fuzzer. + sparse_dim: + The number of sparse dimensions in a sparse tensor. + density: + This value allows tensors of varying sparsities to be generated by the Fuzzer. + coalesced: + The sparse tensor format permits uncoalesced sparse tensors, + where there may be duplicate coordinates in the indices. + dtype: + The PyTorch dtype of the generated Tensor. + cuda: + Whether to place the Tensor on a GPU. + """ + super().__init__(name=name, size=size, min_elements=min_elements, + max_elements=max_elements, dim_parameter=dim_parameter, dtype=dtype, cuda=cuda) + self._density = density + self._coalesced = coalesced + self._sparse_dim = sparse_dim + + @staticmethod + def sparse_tensor_constructor(size, dtype, sparse_dim, nnz, is_coalesced): + """sparse_tensor_constructor creates a sparse tensor with coo format. + + Note that when `is_coalesced` is False, the number of elements is doubled but the number of indices + represents the same amount of number of non zeros `nnz`, i.e, this is virtually the same tensor + with the same sparsity pattern. Moreover, most of the sparse operation will use coalesce() method + and what we want here is to get a sparse tensor with the same `nnz` even if this is coalesced or not. + + In the other hand when `is_coalesced` is True the number of elements is reduced in the coalescing process + by an unclear amount however the probability to generate duplicates indices are low for most of the cases. + This decision was taken on purpose to maintain the construction cost as low as possible. + """ + if isinstance(size, Number): + size = [size] * sparse_dim + if all(size[d] <= 0 for d in range(sparse_dim)) and nnz != 0: + raise AssertionError('invalid arguments') + v_size = [nnz] + list(size[sparse_dim:]) + if dtype.is_floating_point: + v = torch.rand(size=v_size, dtype=dtype, device="cpu") + else: + v = torch.randint(1, 127, size=v_size, dtype=dtype, device="cpu") + + i = torch.rand(sparse_dim, nnz, device="cpu") + i.mul_(torch.tensor(size[:sparse_dim]).unsqueeze(1).to(i)) + i = i.to(torch.long) + + if not is_coalesced: + v = torch.cat([v, torch.randn_like(v)], 0) + i = torch.cat([i, i], 1) + + x = torch.sparse_coo_tensor(i, v, torch.Size(size)) + if is_coalesced: + x = x.coalesce() + return x + + def _make_tensor(self, params, state): + size, _, _ = self._get_size_and_steps(params) + density = params['density'] + nnz = math.ceil(sum(size) * density) + if nnz > sum(size): + raise AssertionError('nnz cannot exceed total number of elements') + + is_coalesced = params['coalesced'] + sparse_dim = params['sparse_dim'] if self._sparse_dim else len(size) + sparse_dim = min(sparse_dim, len(size)) + tensor = self.sparse_tensor_constructor(size, self._dtype, sparse_dim, nnz, is_coalesced) + + if self._cuda: + tensor = tensor.cuda() + sparse_dim = tensor.sparse_dim() + dense_dim = tensor.dense_dim() + is_hybrid = len(size[sparse_dim:]) > 0 + + properties = { + "numel": int(tensor.numel()), + "shape": tensor.size(), + "is_coalesced": tensor.is_coalesced(), + "density": density, + "sparsity": 1.0 - density, + "sparse_dim": sparse_dim, + "dense_dim": dense_dim, + "is_hybrid": is_hybrid, + "dtype": str(self._dtype), + } + return tensor, properties diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/timeit_template.cpp b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/timeit_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..30b6f79c0b5aebca676035ac0b7c08cfce639b23 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/timeit_template.cpp @@ -0,0 +1,43 @@ +/* C++ template for Timer.timeit + +This template will be consumed by `cpp_jit.py`, and will replace: + `GLOBAL_SETUP_TEMPLATE_LOCATION`, + `SETUP_TEMPLATE_LOCATION` + and + `STMT_TEMPLATE_LOCATION` +sections with user provided statements. +*/ +#include + +#include +#include +#include +#include + +// Global setup. (e.g. #includes) +// GLOBAL_SETUP_TEMPLATE_LOCATION + +double timeit(int n) { + pybind11::gil_scoped_release no_gil; + + // Setup + // SETUP_TEMPLATE_LOCATION + + { + // Warmup + // STMT_TEMPLATE_LOCATION + } + + // Main loop + auto start_time = std::chrono::high_resolution_clock::now(); + for (const auto loop_idx : c10::irange(n)) { + (void)loop_idx; + // STMT_TEMPLATE_LOCATION + } + auto end_time = std::chrono::high_resolution_clock::now(); + return std::chrono::duration(end_time - start_time).count(); +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("timeit", &timeit); +} diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/timer.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/timer.py new file mode 100644 index 0000000000000000000000000000000000000000..83fe22a591411200011b38c1b7cc443eede3c161 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/timer.py @@ -0,0 +1,531 @@ +"""Timer class based on the timeit.Timer class, but torch aware.""" +import enum +import timeit +import textwrap +from typing import overload, Any, NoReturn +from collections.abc import Callable + +import torch +from torch.utils.benchmark.utils import common, cpp_jit +from torch.utils.benchmark.utils._stubs import TimerClass, TimeitModuleType +from torch.utils.benchmark.utils.valgrind_wrapper import timer_interface as valgrind_timer_interface + + +__all__ = ["Timer", "timer", "Language"] + + +def timer() -> float: + if torch.accelerator.is_available(): + torch.accelerator.synchronize() + return timeit.default_timer() + + +class Language(enum.Enum): + PYTHON = 0 + CPP = 1 + + +class CPPTimer: + def __init__( + self, + stmt: str, + setup: str, + global_setup: str, + timer: Callable[[], float], + globals: dict[str, Any], + ) -> None: + if timer is not timeit.default_timer and torch.accelerator.is_available(): + raise NotImplementedError( + "PyTorch was built with accelerators and an accelerator is present; however " + "Timer does not yet support accelerator measurements. If your " + "code is CPU only, pass `timer=timeit.default_timer` to the " + "Timer's constructor to indicate this. (Note that this will " + "produce incorrect results if an accelerator is in fact used, as " + "Timer will not synchronize the accelerator.)" + ) + + if globals: + raise ValueError("C++ timing does not support globals.") + + self._stmt: str = textwrap.dedent(stmt) + self._setup: str = textwrap.dedent(setup) + self._global_setup: str = textwrap.dedent(global_setup) + self._timeit_module: TimeitModuleType | None = None + + def timeit(self, number: int) -> float: + if self._timeit_module is None: + self._timeit_module = cpp_jit.compile_timeit_template( + stmt=self._stmt, + setup=self._setup, + global_setup=self._global_setup, + ) + + return self._timeit_module.timeit(number) + + +class Timer: + """Helper class for measuring execution time of PyTorch statements. + + For a full tutorial on how to use this class, see: + https://pytorch.org/tutorials/recipes/recipes/benchmark.html + + The PyTorch Timer is based on `timeit.Timer` (and in fact uses + `timeit.Timer` internally), but with several key differences: + + 1) Runtime aware: + Timer will perform warmups (important as some elements of PyTorch are + lazily initialized), set threadpool size so that comparisons are + apples-to-apples, and synchronize asynchronous accelerator functions when + necessary. + + 2) Focus on replicates: + When measuring code, and particularly complex kernels / models, + run-to-run variation is a significant confounding factor. It is + expected that all measurements should include replicates to quantify + noise and allow median computation, which is more robust than mean. + To that effect, this class deviates from the `timeit` API by + conceptually merging `timeit.Timer.repeat` and `timeit.Timer.autorange`. + (Exact algorithms are discussed in method docstrings.) The `timeit` + method is replicated for cases where an adaptive strategy is not + desired. + + 3) Optional metadata: + When defining a Timer, one can optionally specify `label`, `sub_label`, + `description`, and `env`. (Defined later) These fields are included in + the representation of result object and by the `Compare` class to group + and display results for comparison. + + 4) Instruction counts + In addition to wall times, Timer can run a statement under Callgrind + and report instructions executed. + + Directly analogous to `timeit.Timer` constructor arguments: + + `stmt`, `setup`, `timer`, `globals` + + PyTorch Timer specific constructor arguments: + + `label`, `sub_label`, `description`, `env`, `num_threads` + + Args: + stmt: Code snippet to be run in a loop and timed. + + setup: Optional setup code. Used to define variables used in `stmt` + + global_setup: (C++ only) + Code which is placed at the top level of the file for things like + `#include` statements. + + timer: + Callable which returns the current time. If PyTorch was built + without accelerators or there is no accelerator present, this defaults to + `timeit.default_timer`; otherwise it will synchronize accelerators before + measuring the time. + + globals: + A dict which defines the global variables when `stmt` is being + executed. This is the other method for providing variables which + `stmt` needs. + + label: + String which summarizes `stmt`. For instance, if `stmt` is + "torch.nn.functional.relu(torch.add(x, 1, out=out))" + one might set label to "ReLU(x + 1)" to improve readability. + + sub_label: + Provide supplemental information to disambiguate measurements + with identical stmt or label. For instance, in our example + above sub_label might be "float" or "int", so that it is easy + to differentiate: + "ReLU(x + 1): (float)" + + "ReLU(x + 1): (int)" + when printing Measurements or summarizing using `Compare`. + + description: + String to distinguish measurements with identical label and + sub_label. The principal use of `description` is to signal to + `Compare` the columns of data. For instance one might set it + based on the input size to create a table of the form: :: + + | n=1 | n=4 | ... + ------------- ... + ReLU(x + 1): (float) | ... | ... | ... + ReLU(x + 1): (int) | ... | ... | ... + + + using `Compare`. It is also included when printing a Measurement. + + env: + This tag indicates that otherwise identical tasks were run in + different environments, and are therefore not equivalent, for + instance when A/B testing a change to a kernel. `Compare` will + treat Measurements with different `env` specification as distinct + when merging replicate runs. + + num_threads: + The size of the PyTorch threadpool when executing `stmt`. Single + threaded performance is important as both a key inference workload + and a good indicator of intrinsic algorithmic efficiency, so the + default is set to one. This is in contrast to the default PyTorch + threadpool size which tries to utilize all cores. + """ + + _timer_cls: type[TimerClass] = timeit.Timer + + def __init__( + self, + stmt: str = "pass", + setup: str = "pass", + global_setup: str = "", + timer: Callable[[], float] = timer, + globals: dict[str, Any] | None = None, + label: str | None = None, + sub_label: str | None = None, + description: str | None = None, + env: str | None = None, + num_threads: int = 1, + language: Language | str = Language.PYTHON, + ) -> None: + if not isinstance(stmt, str): + raise ValueError("Currently only a `str` stmt is supported.") + + # We copy `globals` to prevent mutations from leaking. + # (For instance, `eval` adds the `__builtins__` key) + self._globals = dict(globals or {}) + + timer_kwargs = {} + if language in (Language.PYTHON, "py", "python"): + # Include `torch` if not specified as a convenience feature. + self._globals.setdefault("torch", torch) + self._language: Language = Language.PYTHON + if global_setup: + raise ValueError( + f"global_setup is C++ only, got `{global_setup}`. Most " + "likely this code can simply be moved to `setup`." + ) + + elif language in (Language.CPP, "cpp", "c++"): + if self._timer_cls is not timeit.Timer: + raise AssertionError("_timer_cls has already been swapped.") + self._timer_cls = CPPTimer + setup = ("" if setup == "pass" else setup) + self._language = Language.CPP + timer_kwargs["global_setup"] = global_setup + + else: + raise ValueError(f"Invalid language `{language}`.") + + # Convenience adjustment so that multi-line code snippets defined in + # functions do not IndentationError (Python) or look odd (C++). The + # leading newline removal is for the initial newline that appears when + # defining block strings. For instance: + # textwrap.dedent(""" + # print("This is a stmt") + # """) + # produces '\nprint("This is a stmt")\n'. + # + # Stripping this down to 'print("This is a stmt")' doesn't change + # what gets executed, but it makes __repr__'s nicer. + stmt = textwrap.dedent(stmt) + stmt = (stmt[1:] if stmt and stmt[0] == "\n" else stmt).rstrip() + setup = textwrap.dedent(setup) + setup = (setup[1:] if setup and setup[0] == "\n" else setup).rstrip() + + + self._timer = self._timer_cls( + stmt=stmt, + setup=setup, + timer=timer, + globals=valgrind_timer_interface.CopyIfCallgrind.unwrap_all(self._globals), + **timer_kwargs, + ) + self._task_spec = common.TaskSpec( + stmt=stmt, + setup=setup, + global_setup=global_setup, + label=label, + sub_label=sub_label, + description=description, + env=env, + num_threads=num_threads, + ) + + def _timeit(self, number: int) -> float: + # Even calling a timer in C++ takes ~50 ns, so no real operation should + # take less than 1 ns. (And this prevents divide by zero errors.) + return max(self._timer.timeit(number), 1e-9) + + def timeit(self, number: int = 1000000) -> common.Measurement: + """Mirrors the semantics of timeit.Timer.timeit(). + + Execute the main statement (`stmt`) `number` times. + https://docs.python.org/3/library/timeit.html#timeit.Timer.timeit + """ + with common.set_torch_threads(self._task_spec.num_threads): + # Warmup + self._timeit(number=max(int(number // 100), 2)) + + return common.Measurement( + number_per_run=number, + raw_times=[self._timeit(number=number)], + task_spec=self._task_spec + ) + + def repeat(self, repeat: int = -1, number: int = -1) -> None: + raise NotImplementedError("See `Timer.blocked_autorange.`") + + def autorange(self, callback: Callable[[int, float], NoReturn] | None = None) -> None: + raise NotImplementedError("See `Timer.blocked_autorange.`") + + def _threaded_measurement_loop( + self, + number: int, + time_hook: Callable[[], float], + stop_hook: Callable[[list[float]], bool], + min_run_time: float, + max_run_time: float | None = None, + callback: Callable[[int, float], NoReturn] | None = None + ) -> list[float]: + total_time = 0.0 + can_stop = False + times: list[float] = [] + with common.set_torch_threads(self._task_spec.num_threads): + while (total_time < min_run_time) or (not can_stop): + time_spent = time_hook() + times.append(time_spent) + total_time += time_spent + if callback: + callback(number, time_spent) + can_stop = stop_hook(times) + if max_run_time and total_time > max_run_time: + break + return times + + def _estimate_block_size(self, min_run_time: float) -> int: + with common.set_torch_threads(self._task_spec.num_threads): + # Estimate the block size needed for measurement to be negligible + # compared to the inner loop. This also serves as a warmup. + overhead = torch.tensor([self._timeit(0) for _ in range(5)]).median().item() + number = 1 + while True: + time_taken = self._timeit(number) + relative_overhead = overhead / time_taken + if relative_overhead <= 1e-4 and time_taken >= min_run_time / 1000: + break + if time_taken > min_run_time: + break + # Avoid overflow in C++ pybind11 interface + if number * 10 > 2147483647: + break + number *= 10 + return number + + def blocked_autorange( + self, + callback: Callable[[int, float], NoReturn] | None = None, + min_run_time: float = 0.2, + ) -> common.Measurement: + """Measure many replicates while keeping timer overhead to a minimum. + + At a high level, blocked_autorange executes the following pseudo-code:: + + `setup` + + total_time = 0 + while total_time < min_run_time + start = timer() + for _ in range(block_size): + `stmt` + total_time += (timer() - start) + + Note the variable `block_size` in the inner loop. The choice of block + size is important to measurement quality, and must balance two + competing objectives: + + 1) A small block size results in more replicates and generally + better statistics. + + 2) A large block size better amortizes the cost of `timer` + invocation, and results in a less biased measurement. This is + important because accelerator synchronization time is non-trivial + (order single to low double digit microseconds) and would + otherwise bias the measurement. + + blocked_autorange sets block_size by running a warmup period, + increasing block size until timer overhead is less than 0.1% of + the overall computation. This value is then used for the main + measurement loop. + + Returns: + A `Measurement` object that contains measured runtimes and + repetition counts, and can be used to compute statistics. + (mean, median, etc.) + """ + number = self._estimate_block_size(min_run_time) + + def time_hook() -> float: + return self._timeit(number) + + def stop_hook(times: list[float]) -> bool: + return True + + times = self._threaded_measurement_loop( + number, time_hook, stop_hook, + min_run_time=min_run_time, + callback=callback) + + return common.Measurement( + number_per_run=number, + raw_times=times, + task_spec=self._task_spec + ) + + def adaptive_autorange( + self, + threshold: float = 0.1, + *, + min_run_time: float = 0.01, + max_run_time: float = 10.0, + callback: Callable[[int, float], NoReturn] | None = None, + ) -> common.Measurement: + """Similar to `blocked_autorange` but also checks for variability in measurements + and repeats until iqr/median is smaller than `threshold` or `max_run_time` is reached. + + + At a high level, adaptive_autorange executes the following pseudo-code:: + + `setup` + + times = [] + while times.sum < max_run_time + start = timer() + for _ in range(block_size): + `stmt` + times.append(timer() - start) + + enough_data = len(times)>3 and times.sum > min_run_time + small_iqr=times.iqr/times.mean float: + return self._timeit(number) + + def stop_hook(times: list[float]) -> bool: + if len(times) > 3: + return common.Measurement( + number_per_run=number, + raw_times=times, + task_spec=self._task_spec + ).meets_confidence(threshold=threshold) + return False + times = self._threaded_measurement_loop( + number, time_hook, stop_hook, min_run_time, max_run_time, callback=callback) + + return common.Measurement( + number_per_run=number, + raw_times=times, + task_spec=self._task_spec + ) + + @overload + def collect_callgrind( + self, + number: int, + *, + repeats: None, + collect_baseline: bool, + retain_out_file: bool, + ) -> valgrind_timer_interface.CallgrindStats: + ... + + @overload + def collect_callgrind( + self, + number: int, + *, + repeats: int, + collect_baseline: bool, + retain_out_file: bool, + ) -> tuple[valgrind_timer_interface.CallgrindStats, ...]: + ... + + def collect_callgrind( + self, + number: int = 100, + *, + repeats: int | None = None, + collect_baseline: bool = True, + retain_out_file: bool = False, + ) -> Any: + """Collect instruction counts using Callgrind. + + Unlike wall times, instruction counts are deterministic + (modulo non-determinism in the program itself and small amounts of + jitter from the Python interpreter.) This makes them ideal for detailed + performance analysis. This method runs `stmt` in a separate process + so that Valgrind can instrument the program. Performance is severely + degraded due to the instrumentation, however this is ameliorated by + the fact that a small number of iterations is generally sufficient to + obtain good measurements. + + In order to use this method `valgrind`, `callgrind_control`, and + `callgrind_annotate` must be installed. + + Because there is a process boundary between the caller (this process) + and the `stmt` execution, `globals` cannot contain arbitrary in-memory + data structures. (Unlike timing methods) Instead, globals are + restricted to builtins, `nn.Modules`'s, and TorchScripted functions/modules + to reduce the surprise factor from serialization and subsequent + deserialization. The `GlobalsBridge` class provides more detail on this + subject. Take particular care with nn.Modules: they rely on pickle and + you may need to add an import to `setup` for them to transfer properly. + + By default, a profile for an empty statement will be collected and + cached to indicate how many instructions are from the Python loop which + drives `stmt`. + + Returns: + A `CallgrindStats` object which provides instruction counts and + some basic facilities for analyzing and manipulating results. + """ + if not isinstance(self._task_spec.stmt, str): + raise ValueError("`collect_callgrind` currently only supports string `stmt`") + + if repeats is not None and repeats < 1: + raise ValueError("If specified, `repeats` must be >= 1") + + # Check that the statement is valid. It doesn't guarantee success, but it's much + # simpler and quicker to raise an exception for a faulty `stmt` or `setup` in + # the parent process rather than the valgrind subprocess. + self._timeit(1) + is_python = (self._language == Language.PYTHON) + if not is_python and self._globals: + raise AssertionError("_timer globals are only supported for Python timers") + result = valgrind_timer_interface.wrapper_singleton().collect_callgrind( + task_spec=self._task_spec, + globals=self._globals, + number=number, + repeats=repeats or 1, + collect_baseline=collect_baseline and is_python, + is_python=is_python, + retain_out_file=retain_out_file, + ) + + return (result[0] if repeats is None else result) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e86f3bed90c4ed0be4d2aa034ff6ffe8f2ff2ac6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/__pycache__/timer_interface.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/__pycache__/timer_interface.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04b03233d91a829f4feb6ccb9ef0fb40d1febca0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/__pycache__/timer_interface.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/callgrind.h b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/callgrind.h new file mode 100644 index 0000000000000000000000000000000000000000..f078cc82b95daf94d2bea51f1e1b1a8c12daea23 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/callgrind.h @@ -0,0 +1,129 @@ + +/* + ---------------------------------------------------------------- + + Notice that the following BSD-style license applies to this one + file (callgrind.h) only. The rest of Valgrind is licensed under the + terms of the GNU General Public License, version 2, unless + otherwise indicated. See the COPYING file in the source + distribution for details. + + ---------------------------------------------------------------- + + This file is part of callgrind, a valgrind tool for cache simulation + and call tree tracing. + + Copyright (C) 2003-2017 Josef Weidendorfer. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + + 3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + ---------------------------------------------------------------- + + Notice that the above BSD-style license applies to this one file + (callgrind.h) only. The entire rest of Valgrind is licensed under + the terms of the GNU General Public License, version 2. See the + COPYING file in the source distribution for details. + + ---------------------------------------------------------------- +*/ + +#ifndef __CALLGRIND_H +#define __CALLGRIND_H + +#include "valgrind.h" + +/* !! ABIWARNING !! ABIWARNING !! ABIWARNING !! ABIWARNING !! + This enum comprises an ABI exported by Valgrind to programs + which use client requests. DO NOT CHANGE THE ORDER OF THESE + ENTRIES, NOR DELETE ANY -- add new ones at the end. + + The identification ('C','T') for Callgrind has historical + reasons: it was called "Calltree" before. Besides, ('C','G') would + clash with cachegrind. + */ + +typedef + enum { + VG_USERREQ__DUMP_STATS = VG_USERREQ_TOOL_BASE('C','T'), + VG_USERREQ__ZERO_STATS, + VG_USERREQ__TOGGLE_COLLECT, + VG_USERREQ__DUMP_STATS_AT, + VG_USERREQ__START_INSTRUMENTATION, + VG_USERREQ__STOP_INSTRUMENTATION + } Vg_CallgrindClientRequest; + +/* Dump current state of cost centers, and zero them afterwards */ +#define CALLGRIND_DUMP_STATS \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DUMP_STATS, \ + 0, 0, 0, 0, 0) + +/* Dump current state of cost centers, and zero them afterwards. + The argument is appended to a string stating the reason which triggered + the dump. This string is written as a description field into the + profile data dump. */ +#define CALLGRIND_DUMP_STATS_AT(pos_str) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DUMP_STATS_AT, \ + pos_str, 0, 0, 0, 0) + +/* Zero cost centers */ +#define CALLGRIND_ZERO_STATS \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__ZERO_STATS, \ + 0, 0, 0, 0, 0) + +/* Toggles collection state. + The collection state specifies whether the happening of events + should be noted or if they are to be ignored. Events are noted + by increment of counters in a cost center */ +#define CALLGRIND_TOGGLE_COLLECT \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__TOGGLE_COLLECT, \ + 0, 0, 0, 0, 0) + +/* Start full callgrind instrumentation if not already switched on. + When cache simulation is done, it will flush the simulated cache; + this will lead to an artificial cache warmup phase afterwards with + cache misses which would not have happened in reality. */ +#define CALLGRIND_START_INSTRUMENTATION \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__START_INSTRUMENTATION, \ + 0, 0, 0, 0, 0) + +/* Stop full callgrind instrumentation if not already switched off. + This flushes Valgrinds translation cache, and does no additional + instrumentation afterwards, which effectivly will run at the same + speed as the "none" tool (ie. at minimal slowdown). + Use this to bypass Callgrind aggregation for uninteresting code parts. + To start Callgrind in this mode to ignore the setup phase, use + the option "--instr-atstart=no". */ +#define CALLGRIND_STOP_INSTRUMENTATION \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__STOP_INSTRUMENTATION, \ + 0, 0, 0, 0, 0) + +#endif /* __CALLGRIND_H */ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/compat_bindings.cpp b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/compat_bindings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd41f0de092f0b1488c8945edf2af80c6f9b596c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/compat_bindings.cpp @@ -0,0 +1,35 @@ +/* Used to collect profiles of old versions of PyTorch. */ +#include +#include + +bool _valgrind_supported_platform() { +#if defined(NVALGRIND) + return false; +#else + return true; +#endif +} + +void _valgrind_toggle() { +#if defined(NVALGRIND) + TORCH_CHECK(false, "Valgrind is not supported."); +#else + CALLGRIND_TOGGLE_COLLECT; +#endif +} + +void _valgrind_toggle_and_dump_stats() { +#if defined(NVALGRIND) + TORCH_CHECK(false, "Valgrind is not supported."); +#else + // NB: See note in Module.cpp + CALLGRIND_TOGGLE_COLLECT; + CALLGRIND_DUMP_STATS; +#endif +} + +PYBIND11_MODULE(callgrind_bindings, m) { + m.def("_valgrind_supported_platform", &_valgrind_supported_platform); + m.def("_valgrind_toggle", &_valgrind_toggle); + m.def("_valgrind_toggle_and_dump_stats", &_valgrind_dump_stats); +} diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/timer_callgrind_template.cpp b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/timer_callgrind_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..587685c7df7445b299c35462307f47cf6012a00d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/timer_callgrind_template.cpp @@ -0,0 +1,68 @@ +/* C++ template for Timer.collect_callgrind + +This template will be consumed by `cpp_jit.py`, and will replace: + `GLOBAL_SETUP_TEMPLATE_LOCATION`, + `SETUP_TEMPLATE_LOCATION` + and + `STMT_TEMPLATE_LOCATION` +sections with user provided statements. +*/ + +#include +#include +#include + +#include + +// Global setup. (e.g. #includes) +// GLOBAL_SETUP_TEMPLATE_LOCATION + +#if defined(NVALGRIND) +static_assert(false); +#endif + +int main(int argc, char* argv[]) { + // This file should only be called inside of `Timer`, so we can adopt a + // very simple and rigid argument parsing scheme. + TORCH_CHECK(argc == 9); + TORCH_CHECK(std::string(argv[1]) == "--number"); + auto number = std::stoi(argv[2]); + + TORCH_CHECK( + std::string(argv[3]) == "--number-warmup" || + std::string(argv[3]) == "--number_warmup"); + auto number_warmup = std::stoi(argv[4]); + + TORCH_CHECK(std::string(argv[5]) == "--repeats"); + auto repeats = std::stoi(argv[6]); + + TORCH_CHECK( + std::string(argv[7]) == "--number-threads" || + std::string(argv[7]) == "--number_threads"); + auto number_threads = std::stoi(argv[8]); + torch::set_num_threads(number_threads); + + // Setup + // SETUP_TEMPLATE_LOCATION + + // Warmup + for (const auto i : c10::irange(number_warmup)) { + (void)i; + // STMT_TEMPLATE_LOCATION + } + + // Main loop + for (const auto repeat : c10::irange(repeats)) { + (void)repeat; + CALLGRIND_TOGGLE_COLLECT; + + for (const auto i : c10::irange(number)) { + (void)i; + // STMT_TEMPLATE_LOCATION + } + + // NB: See note in Module.cpp + CALLGRIND_TOGGLE_COLLECT; + CALLGRIND_DUMP_STATS; + } +} diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/timer_interface.py b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/timer_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..7faf77910d7b192a04cf07a02b0caa72bf3194bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/timer_interface.py @@ -0,0 +1,919 @@ +"""Intermediate layer between `Timer` and `valgrind`.""" +from __future__ import annotations + +import collections +import enum +import dataclasses +import itertools as it +import os +import pickle +import re +import shutil +import subprocess +import sys +import textwrap +from typing import ( + cast, Any, NamedTuple, + TYPE_CHECKING) + +import torch +from torch.utils.benchmark.utils import common, cpp_jit +import operator + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + from torch.utils.benchmark.utils._stubs import CallgrindModuleType + + +__all__ = ["FunctionCount", "FunctionCounts", "CallgrindStats", "CopyIfCallgrind"] + + +if TYPE_CHECKING: + CompletedProcessType = subprocess.CompletedProcess[str] +else: + CompletedProcessType = subprocess.CompletedProcess + + +class FunctionCount(NamedTuple): + # TODO(#105471): Rename the count field + count: int # type: ignore[assignment] + function: str + + +@dataclasses.dataclass(repr=False, eq=False, frozen=True) +class FunctionCounts: + """Container for manipulating Callgrind results. + + It supports: + 1) Addition and subtraction to combine or diff results. + 2) Tuple-like indexing. + 3) A `denoise` function which strips CPython calls which are known to + be non-deterministic and quite noisy. + 4) Two higher order methods (`filter` and `transform`) for custom + manipulation. + """ + _data: tuple[FunctionCount, ...] + inclusive: bool + truncate_rows: bool = True + + # For normal use, torch._tensor_str.PRINT_OPTS.linewidth determines + # the print settings. This is simply to allow hermetic unit tests. + _linewidth: int | None = None + + def __iter__(self) -> Iterator[FunctionCount]: + yield from self._data + + def __len__(self) -> int: + return len(self._data) + + def __getitem__(self, item: Any) -> FunctionCount | FunctionCounts: + data: FunctionCount | tuple[FunctionCount, ...] = self._data[item] + return ( + FunctionCounts(cast(tuple[FunctionCount, ...], data), self.inclusive, truncate_rows=False) + if isinstance(data, tuple) else data + ) + + def __repr__(self) -> str: + count_len = 0 + for c, _ in self: + # Account for sign in string length. + count_len = max(count_len, len(str(c)) + int(c < 0)) + + lines = [] + linewidth = self._linewidth or torch._tensor_str.PRINT_OPTS.linewidth + fn_str_len = max(linewidth - count_len - 4, 40) + for c, fn in self: + if len(fn) > fn_str_len: + left_len = int((fn_str_len - 5) // 2) + fn = fn[:left_len] + " ... " + fn[-(fn_str_len - left_len - 5):] + lines.append(f" {c:>{count_len}} {fn}") + + if self.truncate_rows and len(lines) > 18: + lines = lines[:9] + ["...".rjust(count_len + 2)] + lines[-9:] + + if not self.inclusive: + lines.extend(["", f"Total: {self.sum()}"]) + + return "\n".join([super().__repr__()] + lines) + + def __add__( + self, + other: FunctionCounts, + ) -> FunctionCounts: + return self._merge(other, lambda c: c) + + def __sub__( + self, + other: FunctionCounts, + ) -> FunctionCounts: + return self._merge(other, operator.neg) + + def __mul__(self, other: int | float) -> FunctionCounts: + return self._from_dict({ + fn: int(c * other) for c, fn in self._data + }, self.inclusive) + + def transform(self, map_fn: Callable[[str], str]) -> FunctionCounts: + """Apply `map_fn` to all of the function names. + + This can be used to regularize function names (e.g. stripping irrelevant + parts of the file path), coalesce entries by mapping multiple functions + to the same name (in which case the counts are added together), etc. + """ + counts: collections.defaultdict[str, int] = collections.defaultdict(int) + for c, fn in self._data: + counts[map_fn(fn)] += c + + return self._from_dict(counts, self.inclusive) + + def filter(self, filter_fn: Callable[[str], bool]) -> FunctionCounts: + """Keep only the elements where `filter_fn` applied to function name returns True.""" + return FunctionCounts(tuple(i for i in self if filter_fn(i.function)), self.inclusive) + + def sum(self) -> int: + return sum(c for c, _ in self) + + def denoise(self) -> FunctionCounts: + """Remove known noisy instructions. + + Several instructions in the CPython interpreter are rather noisy. These + instructions involve unicode to dictionary lookups which Python uses to + map variable names. FunctionCounts is generally a content agnostic + container, however this is sufficiently important for obtaining + reliable results to warrant an exception.""" + return self.filter(lambda fn: "dictobject.c:lookdict_unicode" not in fn) + + def _merge( + self, + second: FunctionCounts, + merge_fn: Callable[[int], int] + ) -> FunctionCounts: + if self.inclusive != second.inclusive: + raise AssertionError("Cannot merge inclusive and exclusive counts.") + counts: collections.defaultdict[str, int] = collections.defaultdict(int) + for c, fn in self: + counts[fn] += c + + for c, fn in second: + counts[fn] += merge_fn(c) + + return self._from_dict(counts, self.inclusive) + + @staticmethod + def _from_dict(counts: dict[str, int], inclusive: bool) -> FunctionCounts: + flat_counts = (FunctionCount(c, fn) for fn, c in counts.items() if c) + return FunctionCounts(tuple(sorted(flat_counts, reverse=True)), inclusive) + + +@dataclasses.dataclass(repr=False, eq=False, frozen=True) +class CallgrindStats: + """Top level container for Callgrind results collected by Timer. + + Manipulation is generally done using the FunctionCounts class, which is + obtained by calling `CallgrindStats.stats(...)`. Several convenience + methods are provided as well; the most significant is + `CallgrindStats.as_standardized()`. + """ + task_spec: common.TaskSpec + number_per_run: int + built_with_debug_symbols: bool + baseline_inclusive_stats: FunctionCounts + baseline_exclusive_stats: FunctionCounts + stmt_inclusive_stats: FunctionCounts + stmt_exclusive_stats: FunctionCounts + stmt_callgrind_out: str | None + + def __repr__(self) -> str: + base_stats = self.baseline_exclusive_stats + output = f""" +{super().__repr__()} +{self.task_spec.summarize()} + {'':>25}All{'':>10}Noisy symbols removed + Instructions: {self.counts(denoise=False):>12}{'':>15}{self.counts(denoise=True):>12} + Baseline: {base_stats.sum():>12}{'':>15}{base_stats.denoise().sum():>12} +{self.number_per_run} runs per measurement, {self.task_spec.num_threads} thread{'s' if self.task_spec.num_threads > 1 else ''} +""".strip() + if not self.built_with_debug_symbols: + output += textwrap.dedent(""" + Warning: PyTorch was not built with debug symbols. + Source information may be limited. Rebuild with + REL_WITH_DEB_INFO=1 for more detailed results.""") + return output + + def stats(self, inclusive: bool = False) -> FunctionCounts: + """Returns detailed function counts. + + Conceptually, the FunctionCounts returned can be thought of as a tuple + of (count, path_and_function_name) tuples. + + `inclusive` matches the semantics of callgrind. If True, the counts + include instructions executed by children. `inclusive=True` is useful + for identifying hot spots in code; `inclusive=False` is useful for + reducing noise when diffing counts from two different runs. (See + CallgrindStats.delta(...) for more details) + """ + return self.stmt_inclusive_stats if inclusive else self.stmt_exclusive_stats + + def counts(self, *, denoise: bool = False) -> int: + """Returns the total number of instructions executed. + + See `FunctionCounts.denoise()` for an explanation of the `denoise` arg. + """ + stats = self.stmt_exclusive_stats + return (stats.denoise() if denoise else stats).sum() + + # FIXME: Once 3.7 is the minimum version, type annotate `other` per PEP 563 + def delta( + self, + other: CallgrindStats, + inclusive: bool = False, + ) -> FunctionCounts: + """Diff two sets of counts. + + One common reason to collect instruction counts is to determine the + effect that a particular change will have on the number of instructions + needed to perform some unit of work. If a change increases that number, the + next logical question is "why". This generally involves looking at what part + if the code increased in instruction count. This function automates that + process so that one can easily diff counts on both an inclusive and + exclusive basis. + """ + return self.stats(inclusive=inclusive) - other.stats(inclusive=inclusive) + + def as_standardized(self) -> CallgrindStats: + """Strip library names and some prefixes from function strings. + + When comparing two different sets of instruction counts, on stumbling + block can be path prefixes. Callgrind includes the full filepath + when reporting a function (as it should). However, this can cause + issues when diffing profiles. If a key component such as Python + or PyTorch was built in separate locations in the two profiles, which + can result in something resembling:: + + 23234231 /tmp/first_build_dir/thing.c:foo(...) + 9823794 /tmp/first_build_dir/thing.c:bar(...) + ... + 53453 .../aten/src/Aten/...:function_that_actually_changed(...) + ... + -9823794 /tmp/second_build_dir/thing.c:bar(...) + -23234231 /tmp/second_build_dir/thing.c:foo(...) + + Stripping prefixes can ameliorate this issue by regularizing the + strings and causing better cancellation of equivalent call sites + when diffing. + """ + def strip(stats: FunctionCounts) -> FunctionCounts: + transforms = ( + # PyTorch may have been built in different locations. + (r"^.+build/\.\./", "build/../"), + (r"^.+/" + re.escape("build/aten/"), "build/aten/"), + + # "Python" and "Objects" come from CPython. + (r"^.+/" + re.escape("Python/"), "Python/"), + (r"^.+/" + re.escape("Objects/"), "Objects/"), + + # Strip library name. e.g. `libtorch.so` + (r"\s\[.+\]$", ""), + ) + + for before, after in transforms: + stats = stats.transform(lambda fn: re.sub(before, after, fn)) + + return stats + + return CallgrindStats( + task_spec=self.task_spec, + number_per_run=self.number_per_run, + built_with_debug_symbols=self.built_with_debug_symbols, + baseline_inclusive_stats=strip(self.baseline_inclusive_stats), + baseline_exclusive_stats=strip(self.baseline_exclusive_stats), + stmt_inclusive_stats=strip(self.stmt_inclusive_stats), + stmt_exclusive_stats=strip(self.stmt_exclusive_stats), + + # `as_standardized` will change symbol names, so the contents will + # no longer map directly to `callgrind.out` + stmt_callgrind_out=None, + ) + + +class Serialization(enum.Enum): + PICKLE = 0 + TORCH = 1 + TORCH_JIT = 2 + + +_GLOBALS_ALLOWED_TYPES: dict[Serialization, tuple[Any, ...]] = { + Serialization.PICKLE: (str, bytes, bool, int, float, complex), + Serialization.TORCH_JIT: (torch.jit.ScriptFunction, torch.jit.ScriptModule), + Serialization.TORCH: (torch.nn.Module,), +} + + +class CopyIfCallgrind: + """Signal that a global may be replaced with a deserialized copy. + + See `GlobalsBridge` for why this matters. + """ + def __init__(self, value: Any, *, setup: str | None = None) -> None: + for method, supported_types in _GLOBALS_ALLOWED_TYPES.items(): + if any(isinstance(value, t) for t in supported_types): + self._value: Any = value + self._setup: str | None = setup + self._serialization: Serialization = method + break + else: + supported_str = "\n".join([ + getattr(t, "__name__", repr(t)) + for t in it.chain(_GLOBALS_ALLOWED_TYPES.values())]) + + raise ValueError( + f"Unsupported type: {type(value)}\n" + f"`collect_callgrind` restricts globals to the following types:\n" + f"{textwrap.indent(supported_str, ' ')}" + ) + + @property + def value(self) -> Any: + return self._value + + @property + def setup(self) -> str | None: + return self._setup + + @property + def serialization(self) -> Serialization: + return self._serialization + + @staticmethod + def unwrap_all(globals: dict[str, Any]) -> dict[str, Any]: + return { + k: (v.value if isinstance(v, CopyIfCallgrind) else v) + for k, v in globals.items() + } + + +class GlobalsBridge: + """Handle the transfer of (certain) globals when collecting Callgrind statistics. + + Key takeaway: Any globals passed must be wrapped in `CopyIfCallgrind` to + work with `Timer.collect_callgrind`. + + Consider the following code snippet: + ``` + import pickle + import timeit + + class Counter: + value = 0 + + def __call__(self): + self.value += 1 + + counter = Counter() + timeit.Timer("counter()", globals={"counter": counter}).timeit(10) + print(counter.value) # 10 + + timeit.Timer( + "counter()", + globals={"counter": pickle.loads(pickle.dumps(counter))} + ).timeit(20) + print(counter.value) # Still 10 + ``` + + In the first case, `stmt` is executed using the objects in `globals`; + however, the addition of serialization and deserialization changes the + semantics and may meaningfully change behavior. + + This is a practical consideration when collecting Callgrind statistics. + Unlike `exec` based execution (which `timeit` uses under the hood) which + can share in-memory data structures with the caller, Callgrind collection + requires an entirely new process in order to run under Valgrind. This means + that any data structures used for statement execution will have to be + serialized and deserialized in the subprocess. + + In order to avoid surprising semantics from (user invisible) process + boundaries, what can be passed through `globals` is severely restricted + for `Timer.collect_callgrind`. It is expected that most setup should be + achievable (albeit perhaps less ergonomically) by passing a `setup` + string. + + There are, however, exceptions. One such class are TorchScripted functions. + Because they require a concrete file with source code it is not possible + to define them using a `setup` string. Another group are torch.nn.Modules, + whose construction can be complex and prohibitively cumbersome to coerce + into a `setup` string. Finally, most builtin types are sufficiently well + behaved and sufficiently common to warrant allowing as well. (e.g. + `globals={"n": 1}` is very convenient.) + + Fortunately, all have well defined serialization semantics. This class + is responsible for enabling the Valgrind subprocess to use elements in + `globals` so long as they are an allowed type. + + Caveats: + The user is required to acknowledge this serialization by wrapping + elements in `globals` with `CopyIfCallgrind`. + + While ScriptFunction and ScriptModule are expected to save and load + quite robustly, it is up to the user to ensure that an nn.Module can + un-pickle successfully. + + `torch.Tensor` and `np.ndarray` are deliberately excluded. The + serialization/deserialization process perturbs the representation of a + tensor in ways that could result in incorrect measurements. For example, + if a tensor lives in pinned CPU memory, this fact would not be preserved + by a dump, and that will in turn change the performance of certain CUDA + operations. + """ + + def __init__(self, globals: dict[str, Any], data_dir: str) -> None: + self._globals: dict[str, CopyIfCallgrind] = {} + self._data_dir = data_dir + if not os.path.exists(data_dir): + os.mkdir(data_dir) + + if globals.get("torch", torch) is not torch: + raise ValueError("`collect_callgrind` does not support mocking out `torch`.") + + for name, value in globals.items(): + if name in ("torch", "__builtins__"): + # Torch will be imported by the collection script, and + # __builtins__ is added by Timer. + continue + + if not isinstance(value, CopyIfCallgrind): + raise ValueError( + "`collect_callgrind` requires that globals be wrapped in " + "`CopyIfCallgrind` so that serialization is explicit." + ) + + self._globals[name] = value + + def construct(self) -> str: + load_lines = [] + for name, wrapped_value in self._globals.items(): + if wrapped_value.setup is not None: + load_lines.append(textwrap.dedent(wrapped_value.setup)) + + if wrapped_value.serialization == Serialization.PICKLE: + path = os.path.join(self._data_dir, f"{name}.pkl") + load_lines.append( + f"with open({repr(path)}, 'rb') as f:\n {name} = pickle.load(f)") + with open(path, "wb") as f: + pickle.dump(wrapped_value.value, f) + + elif wrapped_value.serialization == Serialization.TORCH: + path = os.path.join(self._data_dir, f"{name}.pt") + # TODO: Figure out if we can use torch.serialization.add_safe_globals here + # Using weights_only=False after the change in + # https://dev-discuss.pytorch.org/t/bc-breaking-change-torch-load-is-being-flipped-to-use-weights-only-true-by-default-in-the-nightlies-after-137602/2573 + load_lines.append(f"{name} = torch.load({repr(path)}, weights_only=False)") + torch.save(wrapped_value.value, path) + + elif wrapped_value.serialization == Serialization.TORCH_JIT: + path = os.path.join(self._data_dir, f"{name}.pt") + load_lines.append(f"{name} = torch.jit.load({repr(path)})") + with open(path, "wb") as f: + torch.jit.save(wrapped_value.value, f) # type: ignore[no-untyped-call] + + else: + raise NotImplementedError( + f"Unknown serialization method: {wrapped_value.serialization}") + + return "\n".join(load_lines) + + +class _ValgrindWrapper: + def __init__(self) -> None: + self._bindings_module: CallgrindModuleType | None = None + valgrind_symbols = ( + "_valgrind_supported_platform", + "_valgrind_toggle", + "_valgrind_toggle_and_dump_stats", + ) + if all(hasattr(torch._C, symbol) for symbol in valgrind_symbols): + self._supported_platform: bool = torch._C._valgrind_supported_platform() + + else: + print("Callgrind bindings are not present in `torch._C`. JIT-ing bindings.") + self._bindings_module = cpp_jit.get_compat_bindings() + if not all(hasattr(self._bindings_module, symbol) for symbol in valgrind_symbols): + raise AssertionError("JIT-compiled callgrind bindings are missing required symbols") + self._supported_platform = self._bindings_module._valgrind_supported_platform() + + self._commands_available: dict[str, bool] = {} + if self._supported_platform: + # Only bother checking on supported platforms. + for cmd in ("valgrind", "callgrind_control", "callgrind_annotate"): + self._commands_available[cmd] = not subprocess.run( + ["which", cmd], + capture_output=True, + check=False, + ).returncode + + self._build_type: str | None = None + build_search = re.search("BUILD_TYPE=(.+),", torch.__config__.show()) # type: ignore[no-untyped-call] + if build_search is not None: + self._build_type = build_search.groups()[0].split(",")[0] + + def _validate(self) -> None: + if not self._supported_platform: + raise OSError("Valgrind is not supported on this platform.") + + missing_cmds = [cmd for cmd, available in self._commands_available.items() if not available] + if missing_cmds: + raise OSError("Missing: " + ", ".join(missing_cmds)) + + def collect_callgrind( + self, + task_spec: common.TaskSpec, + globals: dict[str, Any], + *, + number: int, + repeats: int, + collect_baseline: bool, + is_python: bool, + retain_out_file: bool, + ) -> tuple[CallgrindStats, ...]: + """Collect stats, and attach a reference run which can be used to filter interpreter overhead.""" + self._validate() + if not is_python and collect_baseline: + raise AssertionError("collect_baseline is only supported for Python timers") + + *task_stats, baseline_stats = self._invoke( + task_spec=task_spec, + globals=globals, + number=number, + repeats=repeats, + collect_baseline=collect_baseline, + is_python=is_python, + retain_out_file=retain_out_file, + ) + if len(task_stats) != repeats: + raise AssertionError("Unexpected number of task stats returned from _invoke") + + return tuple( + CallgrindStats( + task_spec=task_spec, + number_per_run=number, + built_with_debug_symbols=self._build_type == "RelWithDebInfo", + baseline_inclusive_stats=baseline_stats[0], + baseline_exclusive_stats=baseline_stats[1], + stmt_inclusive_stats=stmt_inclusive_stats, + stmt_exclusive_stats=stmt_exclusive_stats, + stmt_callgrind_out=out_contents, + ) + for stmt_inclusive_stats, stmt_exclusive_stats, out_contents in task_stats + ) + + def _invoke( + self, + *, + task_spec: common.TaskSpec, + globals: dict[str, Any], + number: int, + repeats: int, + collect_baseline: bool, + is_python: bool, + retain_out_file: bool, + ) -> tuple[tuple[FunctionCounts, FunctionCounts, str | None], ...]: + """Core invocation method for Callgrind collection. + + Valgrind operates by effectively replacing the CPU with an emulated + version which allows it to instrument any code at the cost of severe + performance degradation. This has the practical effect that in order + to collect Callgrind statistics, a new process has to be created + running under `valgrind`. The steps for this process are: + + 1) Create a scratch directory. + 2) Codegen a run script. (_ValgrindWrapper._construct_script) + Inside the run script: + * Validate that Python and torch match the parent process + * Validate that it is indeed running under valgrind + * Execute `setup` and warm up `stmt` + * Begin collecting stats + * Run the `stmt` loop + * Stop collecting stats + 3) Parse the run results. + 4) Cleanup the scratch directory. + """ + working_dir = common._make_temp_dir(prefix="callgrind") + data_dir = os.path.join(working_dir, "data") + script_file = os.path.join(working_dir, "timer_callgrind.py") + callgrind_out = os.path.join(working_dir, "callgrind.out") + error_log = os.path.join(working_dir, "error.txt") + stat_log = os.path.join(working_dir, "callgrind_stat.txt") + stdout_stderr_log = os.path.join(working_dir, "stdout_stderr.log") + + def run(args: list[str], **kwargs: Any) -> tuple[CompletedProcessType, str]: + # https://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/ + with open(stdout_stderr_log, "wb") as f_stdout_stderr: + invocation = subprocess.run( + args, + stdout=f_stdout_stderr, + stderr=subprocess.STDOUT, + **kwargs, + ) + with open(stdout_stderr_log) as f: + return invocation, f.read() + + try: + if is_python: + if self._bindings_module is not None: + shutil.copy( + self._bindings_module.__file__, + os.path.join(working_dir, os.path.split(self._bindings_module.__file__)[1]) + ) + + script_file = os.path.join(working_dir, "timer_callgrind.py") + with open(script_file, "w") as f: + f.write(self._construct_script( + task_spec, + globals=GlobalsBridge(globals, data_dir), + number=number, + repeats=repeats, + collect_baseline=collect_baseline, + error_log=error_log, + stat_log=stat_log, + bindings=self._bindings_module)) + + run_loop_cmd = ["python", script_file] + else: + if collect_baseline: + raise AssertionError("collect_baseline must be False for non-Python timers") + run_loop_exec = cpp_jit.compile_callgrind_template( + stmt=task_spec.stmt, + setup=task_spec.setup, + global_setup=task_spec.global_setup, + ) + run_loop_cmd = [ + run_loop_exec, + "--number", str(number), + "--number-warmup", str(min(number, 10)), + "--repeats", str(repeats), + "--number-threads", str(task_spec.num_threads), + ] + + valgrind_invocation, valgrind_invocation_output = run([ + "valgrind", + "--tool=callgrind", + f"--callgrind-out-file={callgrind_out}", + "--dump-line=yes", + "--dump-instr=yes", + "--instr-atstart=yes", + "--collect-atstart=no", + ] + run_loop_cmd) + + if valgrind_invocation.returncode: + error_report = "" + if os.path.exists(error_log): + with open(error_log) as f: + error_report = f.read() + if not error_report: + error_report = "Unknown error.\n" + valgrind_invocation_output + + raise OSError(f"Failed to collect callgrind profile:\n{error_report}") + + def parse_output(fpath: str, inclusive: bool) -> FunctionCounts: + _annotate_invocation, annotate_invocation_output = run([ + "callgrind_annotate", + f"--inclusive={'yes' if inclusive else 'no'}", + "--threshold=100", + "--show-percs=no", + fpath + ], check=True) + + total_pattern = re.compile(r"^([0-9,]+)\s+PROGRAM TOTALS") + begin_pattern = re.compile(r"Ir\s+file:function") + function_pattern = re.compile(r"^\s*([0-9,]+)\s+(.+:.+)$") + + class ScanState(enum.Enum): + SCANNING_FOR_TOTAL = 0 + SCANNING_FOR_START = 1 + PARSING = 2 + + scan_state = ScanState.SCANNING_FOR_TOTAL + fn_counts = [] + for l in annotate_invocation_output.splitlines(keepends=False): + if scan_state == ScanState.SCANNING_FOR_TOTAL: + total_match = total_pattern.match(l) + if total_match: + program_totals = int(total_match.groups()[0].replace(",", "")) + scan_state = ScanState.SCANNING_FOR_START + + elif scan_state == ScanState.SCANNING_FOR_START: + if begin_pattern.match(l): + scan_state = ScanState.PARSING + + else: + if scan_state != ScanState.PARSING: + raise AssertionError("Failed to enter PARSING state while parsing callgrind_annotate output") + fn_match = function_pattern.match(l) + if fn_match: + ir_str, file_function = fn_match.groups() + ir = int(ir_str.replace(",", "")) + if ir == program_totals: # type: ignore[possibly-undefined] + # Callgrind includes some top level red herring symbols when + # a program dumps multiple profiles. + continue + fn_counts.append(FunctionCount(ir, file_function)) + + elif re.match(r"-+", l): + # Ignore heading separator lines. + continue + + else: + break + + if scan_state != ScanState.PARSING: + raise AssertionError(f"Failed to parse {fpath}") + return FunctionCounts(tuple(sorted(fn_counts, reverse=True)), inclusive=inclusive) + + def read_results(i: int) -> tuple[FunctionCounts, FunctionCounts, str | None]: + if i == repeats and not collect_baseline: + # Null baseline. + return ( + FunctionCounts((), inclusive=True), + FunctionCounts((), inclusive=False), + None, + ) + + fpath = f"{callgrind_out}.{i + 1}" # Callgrind one-indexes files. + callgrind_out_contents: str | None = None + if retain_out_file: + with open(fpath) as f: + callgrind_out_contents = f.read() + + return ( + parse_output(fpath, inclusive=True), + parse_output(fpath, inclusive=False), + callgrind_out_contents + ) + + return tuple(read_results(i) for i in range(repeats + 1)) + finally: + shutil.rmtree(working_dir) + + @staticmethod + def _construct_script( + task_spec: common.TaskSpec, + globals: GlobalsBridge, + *, + number: int, + repeats: int, + collect_baseline: bool, + error_log: str, + stat_log: str, + bindings: CallgrindModuleType | None, + ) -> str: + def block_stmt(stmt: str, indent: int = 0) -> str: + """Partially unroll benchmark loop. + + The naive template looks something like: + "for _ in range({number}): {stmt}" + + However a loop in Python is surprisingly expensive, and significantly + increases the number of background Python instructions. So instead we + partially unroll the loops, with a block size of 100 chosen to keep + the instruction overhead from `range` low while also not ballooning + the size of the generated file. + """ + block_size = 100 + loop_count = number // block_size + if loop_count == 1: + # There is no point in having `for _ in range(1): ...` rather + # than just `...`, and this lets us save shave a few background + # instructions. + loop_count = 0 + remainder = number - block_size * loop_count + blocked_stmt = "" + + if loop_count: + unrolled_stmts = textwrap.indent("\n".join([stmt] * block_size), " " * 4) + blocked_stmt += f"for _ in range({loop_count}):\n{unrolled_stmts}\n" + + if remainder: + blocked_stmt += "\n".join([stmt] * remainder) + + return textwrap.indent(blocked_stmt, " " * indent) + + pass_baseline = ( + "callgrind_bindings._valgrind_toggle()\n" + f"{block_stmt('pass')}\n" + "callgrind_bindings._valgrind_toggle_and_dump_stats()" + ) + + return textwrap.dedent(r""" + import gc + import os + import pickle + import subprocess + import sys + import time + + # Mitigate https://github.com/pytorch/pytorch/issues/37377 + # which can sometimes cause the subprocess call to fail. + import numpy as np + + import torch + torch.set_num_threads({num_threads}) + + {bindings_import} + + PID = os.getpid() + + def log_failure(msg): + with open({error_log_repr}, "wt") as f: + f.write(msg) + sys.exit(1) + + def check_result(completed_process): + if completed_process.returncode: + log_failure(f"Command failed: {{' '.join(completed_process.args)}}") + return completed_process + + # ============================================================================= + # == Check that subprocess matches parent ===================================== + # ============================================================================= + if os.path.realpath(sys.executable) != "{parent_interpreter}": + log_failure( + "Interpreter mismatch:\n" + f" {{os.path.realpath(sys.executable)}}\n vs.\n {parent_interpreter}" + ) + + if torch.__file__ != "{torch_file}": + log_failure( + "PyTorch does not match expected file:\n" + f" {{torch.__file__}}\n vs.\n {torch_file}" + ) + + # ============================================================================= + # == User specified setup ===================================================== + # ============================================================================= + # Load serialized globals + {load_globals} + + # User setup str + {setup} + + for _ in range({warmup_number}): + {indented_stmt} + + # ============================================================================= + # == Callgrind management ===================================================== + # ============================================================================= + with open("{stat_log}", "wb") as stat_file: + # If many instances of callgrind are running at once, the output of + # `callgrind_control` may exceed 16kb which would cause `subprocess.PIPE` + # to deadlock. So instead we use a file. + callgrind_stat = check_result(subprocess.run( + ["callgrind_control", "--stat"], + stdout=stat_file, + stderr=subprocess.STDOUT, + )) + + with open("{stat_log}", "rt") as stat_file: + stat_lines = stat_file.read().splitlines() + + if f"PID {{PID}}: python {{__file__}}" not in stat_lines: + log_failure("Process does not appear to be running callgrind.") + + gc.collect() + time.sleep(0.01) + + # ============================================================================= + # == User code block ========================================================== + # ============================================================================= + for _ in range({repeats}): + callgrind_bindings._valgrind_toggle() + {blocked_stmt} + callgrind_bindings._valgrind_toggle_and_dump_stats() + gc.collect() + + {baseline} + """).strip().format( + indented_stmt=textwrap.indent(task_spec.stmt, " " * 4), + blocked_stmt=block_stmt(task_spec.stmt, indent=4), + baseline=(pass_baseline if collect_baseline else ""), + number=number, + repeats=repeats, + load_globals=globals.construct(), + setup=task_spec.setup, + warmup_number=min(number, 10), + num_threads=task_spec.num_threads, + error_log_repr=repr(error_log), + stat_log=stat_log, + parent_interpreter=os.path.realpath(sys.executable), + torch_file=torch.__file__, + bindings_import=( + "import torch._C as callgrind_bindings" if bindings is None + else f"import {bindings.__name__} as callgrind_bindings"), + ) + + +CALLGRIND_SINGLETON: _ValgrindWrapper | None = None +def wrapper_singleton() -> _ValgrindWrapper: + global CALLGRIND_SINGLETON + if CALLGRIND_SINGLETON is None: + CALLGRIND_SINGLETON = _ValgrindWrapper() + return CALLGRIND_SINGLETON diff --git a/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/valgrind.h b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/valgrind.h new file mode 100644 index 0000000000000000000000000000000000000000..d33dd30932aa86b8284cb93d0e29ec646e820197 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/benchmark/utils/valgrind_wrapper/valgrind.h @@ -0,0 +1,7157 @@ +/* -*- c -*- + ---------------------------------------------------------------- + + Notice that the following BSD-style license applies to this one + file (valgrind.h) only. The rest of Valgrind is licensed under the + terms of the GNU General Public License, version 2, unless + otherwise indicated. See the COPYING file in the source + distribution for details. + + ---------------------------------------------------------------- + + This file is part of Valgrind, a dynamic binary instrumentation + framework. + + Copyright (C) 2000-2017 Julian Seward. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + + 3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + + 4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + ---------------------------------------------------------------- + + Notice that the above BSD-style license applies to this one file + (valgrind.h) only. The entire rest of Valgrind is licensed under + the terms of the GNU General Public License, version 2. See the + COPYING file in the source distribution for details. + + ---------------------------------------------------------------- +*/ + + +/* This file is for inclusion into client (your!) code. + + You can use these macros to manipulate and query Valgrind's + execution inside your own programs. + + The resulting executables will still run without Valgrind, just a + little bit more slowly than they otherwise would, but otherwise + unchanged. When not running on valgrind, each client request + consumes very few (eg. 7) instructions, so the resulting performance + loss is negligible unless you plan to execute client requests + millions of times per second. Nevertheless, if that is still a + problem, you can compile with the NVALGRIND symbol defined (gcc + -DNVALGRIND) so that client requests are not even compiled in. */ + +#ifndef __VALGRIND_H +#define __VALGRIND_H + + +/* ------------------------------------------------------------------ */ +/* VERSION NUMBER OF VALGRIND */ +/* ------------------------------------------------------------------ */ + +/* Specify Valgrind's version number, so that user code can + conditionally compile based on our version number. Note that these + were introduced at version 3.6 and so do not exist in version 3.5 + or earlier. The recommended way to use them to check for "version + X.Y or later" is (eg) + +#if defined(__VALGRIND_MAJOR__) && defined(__VALGRIND_MINOR__) \ + && (__VALGRIND_MAJOR__ > 3 \ + || (__VALGRIND_MAJOR__ == 3 && __VALGRIND_MINOR__ >= 6)) +*/ +#define __VALGRIND_MAJOR__ 3 +#define __VALGRIND_MINOR__ 17 + + +#include + +/* Nb: this file might be included in a file compiled with -ansi. So + we can't use C++ style "//" comments nor the "asm" keyword (instead + use "__asm__"). */ + +/* Derive some tags indicating what the target platform is. Note + that in this file we're using the compiler's CPP symbols for + identifying architectures, which are different to the ones we use + within the rest of Valgrind. Note, __powerpc__ is active for both + 32 and 64-bit PPC, whereas __powerpc64__ is only active for the + latter (on Linux, that is). + + Misc note: how to find out what's predefined in gcc by default: + gcc -Wp,-dM somefile.c +*/ +#undef PLAT_x86_darwin +#undef PLAT_amd64_darwin +#undef PLAT_x86_win32 +#undef PLAT_amd64_win64 +#undef PLAT_x86_linux +#undef PLAT_amd64_linux +#undef PLAT_ppc32_linux +#undef PLAT_ppc64be_linux +#undef PLAT_ppc64le_linux +#undef PLAT_arm_linux +#undef PLAT_arm64_linux +#undef PLAT_s390x_linux +#undef PLAT_mips32_linux +#undef PLAT_mips64_linux +#undef PLAT_nanomips_linux +#undef PLAT_x86_solaris +#undef PLAT_amd64_solaris + + +#if defined(__APPLE__) && defined(__i386__) +# define PLAT_x86_darwin 1 +#elif defined(__APPLE__) && defined(__x86_64__) +# define PLAT_amd64_darwin 1 +#elif (defined(__MINGW32__) && defined(__i386__)) \ + || defined(__CYGWIN32__) \ + || (defined(_WIN32) && defined(_M_IX86)) +# define PLAT_x86_win32 1 +#elif (defined(__MINGW32__) && defined(__x86_64__)) \ + || (defined(_WIN32) && defined(_M_X64)) +/* __MINGW32__ and _WIN32 are defined in 64 bit mode as well. */ +# define PLAT_amd64_win64 1 +#elif defined(__linux__) && defined(__i386__) +# define PLAT_x86_linux 1 +#elif defined(__linux__) && defined(__x86_64__) && !defined(__ILP32__) +# define PLAT_amd64_linux 1 +#elif defined(__linux__) && defined(__powerpc__) && !defined(__powerpc64__) +# define PLAT_ppc32_linux 1 +#elif defined(__linux__) && defined(__powerpc__) && defined(__powerpc64__) && _CALL_ELF != 2 +/* Big Endian uses ELF version 1 */ +# define PLAT_ppc64be_linux 1 +#elif defined(__linux__) && defined(__powerpc__) && defined(__powerpc64__) && _CALL_ELF == 2 +/* Little Endian uses ELF version 2 */ +# define PLAT_ppc64le_linux 1 +#elif defined(__linux__) && defined(__arm__) && !defined(__aarch64__) +# define PLAT_arm_linux 1 +#elif defined(__linux__) && defined(__aarch64__) && !defined(__arm__) +# define PLAT_arm64_linux 1 +#elif defined(__linux__) && defined(__s390__) && defined(__s390x__) +# define PLAT_s390x_linux 1 +#elif defined(__linux__) && defined(__mips__) && (__mips==64) +# define PLAT_mips64_linux 1 +#elif defined(__linux__) && defined(__mips__) && (__mips==32) +# define PLAT_mips32_linux 1 +#elif defined(__linux__) && defined(__nanomips__) +# define PLAT_nanomips_linux 1 +#elif defined(__sun) && defined(__i386__) +# define PLAT_x86_solaris 1 +#elif defined(__sun) && defined(__x86_64__) +# define PLAT_amd64_solaris 1 +#else +/* If we're not compiling for our target platform, don't generate + any inline asms. */ +# if !defined(NVALGRIND) +# define NVALGRIND 1 +# endif +#endif + + +/* ------------------------------------------------------------------ */ +/* ARCHITECTURE SPECIFICS for SPECIAL INSTRUCTIONS. There is nothing */ +/* in here of use to end-users -- skip to the next section. */ +/* ------------------------------------------------------------------ */ + +/* + * VALGRIND_DO_CLIENT_REQUEST(): a statement that invokes a Valgrind client + * request. Accepts both pointers and integers as arguments. + * + * VALGRIND_DO_CLIENT_REQUEST_STMT(): a statement that invokes a Valgrind + * client request that does not return a value. + + * VALGRIND_DO_CLIENT_REQUEST_EXPR(): a C expression that invokes a Valgrind + * client request and whose value equals the client request result. Accepts + * both pointers and integers as arguments. Note that such calls are not + * necessarily pure functions -- they may have side effects. + */ + +#define VALGRIND_DO_CLIENT_REQUEST(_zzq_rlval, _zzq_default, \ + _zzq_request, _zzq_arg1, _zzq_arg2, \ + _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + do { (_zzq_rlval) = VALGRIND_DO_CLIENT_REQUEST_EXPR((_zzq_default), \ + (_zzq_request), (_zzq_arg1), (_zzq_arg2), \ + (_zzq_arg3), (_zzq_arg4), (_zzq_arg5)); } while (0) + +#define VALGRIND_DO_CLIENT_REQUEST_STMT(_zzq_request, _zzq_arg1, \ + _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + do { (void) VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \ + (_zzq_request), (_zzq_arg1), (_zzq_arg2), \ + (_zzq_arg3), (_zzq_arg4), (_zzq_arg5)); } while (0) + +#if defined(NVALGRIND) + +/* Define NVALGRIND to completely remove the Valgrind magic sequence + from the compiled code (analogous to NDEBUG's effects on + assert()) */ +#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \ + _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + (_zzq_default) + +#else /* ! NVALGRIND */ + +/* The following defines the magic code sequences which the JITter + spots and handles magically. Don't look too closely at them as + they will rot your brain. + + The assembly code sequences for all architectures is in this one + file. This is because this file must be stand-alone, and we don't + want to have multiple files. + + For VALGRIND_DO_CLIENT_REQUEST, we must ensure that the default + value gets put in the return slot, so that everything works when + this is executed not under Valgrind. Args are passed in a memory + block, and so there's no intrinsic limit to the number that could + be passed, but it's currently five. + + The macro args are: + _zzq_rlval result lvalue + _zzq_default default value (result returned when running on real CPU) + _zzq_request request code + _zzq_arg1..5 request params + + The other two macros are used to support function wrapping, and are + a lot simpler. VALGRIND_GET_NR_CONTEXT returns the value of the + guest's NRADDR pseudo-register and whatever other information is + needed to safely run the call original from the wrapper: on + ppc64-linux, the R2 value at the divert point is also needed. This + information is abstracted into a user-visible type, OrigFn. + + VALGRIND_CALL_NOREDIR_* behaves the same as the following on the + guest, but guarantees that the branch instruction will not be + redirected: x86: call *%eax, amd64: call *%rax, ppc32/ppc64: + branch-and-link-to-r11. VALGRIND_CALL_NOREDIR is just text, not a + complete inline asm, since it needs to be combined with more magic + inline asm stuff to be useful. +*/ + +/* ----------------- x86-{linux,darwin,solaris} ---------------- */ + +#if defined(PLAT_x86_linux) || defined(PLAT_x86_darwin) \ + || (defined(PLAT_x86_win32) && defined(__GNUC__)) \ + || defined(PLAT_x86_solaris) + +typedef + struct { + unsigned int nraddr; /* where's the code? */ + } + OrigFn; + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "roll $3, %%edi ; roll $13, %%edi\n\t" \ + "roll $29, %%edi ; roll $19, %%edi\n\t" + +#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \ + _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + __extension__ \ + ({volatile unsigned int _zzq_args[6]; \ + volatile unsigned int _zzq_result; \ + _zzq_args[0] = (unsigned int)(_zzq_request); \ + _zzq_args[1] = (unsigned int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned int)(_zzq_arg5); \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %EDX = client_request ( %EAX ) */ \ + "xchgl %%ebx,%%ebx" \ + : "=d" (_zzq_result) \ + : "a" (&_zzq_args[0]), "0" (_zzq_default) \ + : "cc", "memory" \ + ); \ + _zzq_result; \ + }) + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + volatile unsigned int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %EAX = guest_NRADDR */ \ + "xchgl %%ecx,%%ecx" \ + : "=a" (__addr) \ + : \ + : "cc", "memory" \ + ); \ + _zzq_orig->nraddr = __addr; \ + } + +#define VALGRIND_CALL_NOREDIR_EAX \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* call-noredir *%EAX */ \ + "xchgl %%edx,%%edx\n\t" + +#define VALGRIND_VEX_INJECT_IR() \ + do { \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + "xchgl %%edi,%%edi\n\t" \ + : : : "cc", "memory" \ + ); \ + } while (0) + +#endif /* PLAT_x86_linux || PLAT_x86_darwin || (PLAT_x86_win32 && __GNUC__) + || PLAT_x86_solaris */ + +/* ------------------------- x86-Win32 ------------------------- */ + +#if defined(PLAT_x86_win32) && !defined(__GNUC__) + +typedef + struct { + unsigned int nraddr; /* where's the code? */ + } + OrigFn; + +#if defined(_MSC_VER) + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + __asm rol edi, 3 __asm rol edi, 13 \ + __asm rol edi, 29 __asm rol edi, 19 + +#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \ + _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + valgrind_do_client_request_expr((uintptr_t)(_zzq_default), \ + (uintptr_t)(_zzq_request), (uintptr_t)(_zzq_arg1), \ + (uintptr_t)(_zzq_arg2), (uintptr_t)(_zzq_arg3), \ + (uintptr_t)(_zzq_arg4), (uintptr_t)(_zzq_arg5)) + +static __inline uintptr_t +valgrind_do_client_request_expr(uintptr_t _zzq_default, uintptr_t _zzq_request, + uintptr_t _zzq_arg1, uintptr_t _zzq_arg2, + uintptr_t _zzq_arg3, uintptr_t _zzq_arg4, + uintptr_t _zzq_arg5) +{ + volatile uintptr_t _zzq_args[6]; + volatile unsigned int _zzq_result; + _zzq_args[0] = (uintptr_t)(_zzq_request); + _zzq_args[1] = (uintptr_t)(_zzq_arg1); + _zzq_args[2] = (uintptr_t)(_zzq_arg2); + _zzq_args[3] = (uintptr_t)(_zzq_arg3); + _zzq_args[4] = (uintptr_t)(_zzq_arg4); + _zzq_args[5] = (uintptr_t)(_zzq_arg5); + __asm { __asm lea eax, _zzq_args __asm mov edx, _zzq_default + __SPECIAL_INSTRUCTION_PREAMBLE + /* %EDX = client_request ( %EAX ) */ + __asm xchg ebx,ebx + __asm mov _zzq_result, edx + } + return _zzq_result; +} + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + volatile unsigned int __addr; \ + __asm { __SPECIAL_INSTRUCTION_PREAMBLE \ + /* %EAX = guest_NRADDR */ \ + __asm xchg ecx,ecx \ + __asm mov __addr, eax \ + } \ + _zzq_orig->nraddr = __addr; \ + } + +#define VALGRIND_CALL_NOREDIR_EAX ERROR + +#define VALGRIND_VEX_INJECT_IR() \ + do { \ + __asm { __SPECIAL_INSTRUCTION_PREAMBLE \ + __asm xchg edi,edi \ + } \ + } while (0) + +#else +#error Unsupported compiler. +#endif + +#endif /* PLAT_x86_win32 */ + +/* ----------------- amd64-{linux,darwin,solaris} --------------- */ + +#if defined(PLAT_amd64_linux) || defined(PLAT_amd64_darwin) \ + || defined(PLAT_amd64_solaris) \ + || (defined(PLAT_amd64_win64) && defined(__GNUC__)) + +typedef + struct { + unsigned long int nraddr; /* where's the code? */ + } + OrigFn; + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "rolq $3, %%rdi ; rolq $13, %%rdi\n\t" \ + "rolq $61, %%rdi ; rolq $51, %%rdi\n\t" + +#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \ + _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + __extension__ \ + ({ volatile unsigned long int _zzq_args[6]; \ + volatile unsigned long int _zzq_result; \ + _zzq_args[0] = (unsigned long int)(_zzq_request); \ + _zzq_args[1] = (unsigned long int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned long int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned long int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned long int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned long int)(_zzq_arg5); \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %RDX = client_request ( %RAX ) */ \ + "xchgq %%rbx,%%rbx" \ + : "=d" (_zzq_result) \ + : "a" (&_zzq_args[0]), "0" (_zzq_default) \ + : "cc", "memory" \ + ); \ + _zzq_result; \ + }) + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + volatile unsigned long int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %RAX = guest_NRADDR */ \ + "xchgq %%rcx,%%rcx" \ + : "=a" (__addr) \ + : \ + : "cc", "memory" \ + ); \ + _zzq_orig->nraddr = __addr; \ + } + +#define VALGRIND_CALL_NOREDIR_RAX \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* call-noredir *%RAX */ \ + "xchgq %%rdx,%%rdx\n\t" + +#define VALGRIND_VEX_INJECT_IR() \ + do { \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + "xchgq %%rdi,%%rdi\n\t" \ + : : : "cc", "memory" \ + ); \ + } while (0) + +#endif /* PLAT_amd64_linux || PLAT_amd64_darwin || PLAT_amd64_solaris */ + +/* ------------------------- amd64-Win64 ------------------------- */ + +#if defined(PLAT_amd64_win64) && !defined(__GNUC__) + +#error Unsupported compiler. + +#endif /* PLAT_amd64_win64 */ + +/* ------------------------ ppc32-linux ------------------------ */ + +#if defined(PLAT_ppc32_linux) + +typedef + struct { + unsigned int nraddr; /* where's the code? */ + } + OrigFn; + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "rlwinm 0,0,3,0,31 ; rlwinm 0,0,13,0,31\n\t" \ + "rlwinm 0,0,29,0,31 ; rlwinm 0,0,19,0,31\n\t" + +#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \ + _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + \ + __extension__ \ + ({ unsigned int _zzq_args[6]; \ + unsigned int _zzq_result; \ + unsigned int* _zzq_ptr; \ + _zzq_args[0] = (unsigned int)(_zzq_request); \ + _zzq_args[1] = (unsigned int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned int)(_zzq_arg5); \ + _zzq_ptr = _zzq_args; \ + __asm__ volatile("mr 3,%1\n\t" /*default*/ \ + "mr 4,%2\n\t" /*ptr*/ \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = client_request ( %R4 ) */ \ + "or 1,1,1\n\t" \ + "mr %0,3" /*result*/ \ + : "=b" (_zzq_result) \ + : "b" (_zzq_default), "b" (_zzq_ptr) \ + : "cc", "memory", "r3", "r4"); \ + _zzq_result; \ + }) + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + unsigned int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = guest_NRADDR */ \ + "or 2,2,2\n\t" \ + "mr %0,3" \ + : "=b" (__addr) \ + : \ + : "cc", "memory", "r3" \ + ); \ + _zzq_orig->nraddr = __addr; \ + } + +#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* branch-and-link-to-noredir *%R11 */ \ + "or 3,3,3\n\t" + +#define VALGRIND_VEX_INJECT_IR() \ + do { \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + "or 5,5,5\n\t" \ + ); \ + } while (0) + +#endif /* PLAT_ppc32_linux */ + +/* ------------------------ ppc64-linux ------------------------ */ + +#if defined(PLAT_ppc64be_linux) + +typedef + struct { + unsigned long int nraddr; /* where's the code? */ + unsigned long int r2; /* what tocptr do we need? */ + } + OrigFn; + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "rotldi 0,0,3 ; rotldi 0,0,13\n\t" \ + "rotldi 0,0,61 ; rotldi 0,0,51\n\t" + +#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \ + _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + \ + __extension__ \ + ({ unsigned long int _zzq_args[6]; \ + unsigned long int _zzq_result; \ + unsigned long int* _zzq_ptr; \ + _zzq_args[0] = (unsigned long int)(_zzq_request); \ + _zzq_args[1] = (unsigned long int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned long int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned long int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned long int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned long int)(_zzq_arg5); \ + _zzq_ptr = _zzq_args; \ + __asm__ volatile("mr 3,%1\n\t" /*default*/ \ + "mr 4,%2\n\t" /*ptr*/ \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = client_request ( %R4 ) */ \ + "or 1,1,1\n\t" \ + "mr %0,3" /*result*/ \ + : "=b" (_zzq_result) \ + : "b" (_zzq_default), "b" (_zzq_ptr) \ + : "cc", "memory", "r3", "r4"); \ + _zzq_result; \ + }) + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + unsigned long int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = guest_NRADDR */ \ + "or 2,2,2\n\t" \ + "mr %0,3" \ + : "=b" (__addr) \ + : \ + : "cc", "memory", "r3" \ + ); \ + _zzq_orig->nraddr = __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = guest_NRADDR_GPR2 */ \ + "or 4,4,4\n\t" \ + "mr %0,3" \ + : "=b" (__addr) \ + : \ + : "cc", "memory", "r3" \ + ); \ + _zzq_orig->r2 = __addr; \ + } + +#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* branch-and-link-to-noredir *%R11 */ \ + "or 3,3,3\n\t" + +#define VALGRIND_VEX_INJECT_IR() \ + do { \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + "or 5,5,5\n\t" \ + ); \ + } while (0) + +#endif /* PLAT_ppc64be_linux */ + +#if defined(PLAT_ppc64le_linux) + +typedef + struct { + unsigned long int nraddr; /* where's the code? */ + unsigned long int r2; /* what tocptr do we need? */ + } + OrigFn; + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "rotldi 0,0,3 ; rotldi 0,0,13\n\t" \ + "rotldi 0,0,61 ; rotldi 0,0,51\n\t" + +#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \ + _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + \ + __extension__ \ + ({ unsigned long int _zzq_args[6]; \ + unsigned long int _zzq_result; \ + unsigned long int* _zzq_ptr; \ + _zzq_args[0] = (unsigned long int)(_zzq_request); \ + _zzq_args[1] = (unsigned long int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned long int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned long int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned long int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned long int)(_zzq_arg5); \ + _zzq_ptr = _zzq_args; \ + __asm__ volatile("mr 3,%1\n\t" /*default*/ \ + "mr 4,%2\n\t" /*ptr*/ \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = client_request ( %R4 ) */ \ + "or 1,1,1\n\t" \ + "mr %0,3" /*result*/ \ + : "=b" (_zzq_result) \ + : "b" (_zzq_default), "b" (_zzq_ptr) \ + : "cc", "memory", "r3", "r4"); \ + _zzq_result; \ + }) + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + unsigned long int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = guest_NRADDR */ \ + "or 2,2,2\n\t" \ + "mr %0,3" \ + : "=b" (__addr) \ + : \ + : "cc", "memory", "r3" \ + ); \ + _zzq_orig->nraddr = __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %R3 = guest_NRADDR_GPR2 */ \ + "or 4,4,4\n\t" \ + "mr %0,3" \ + : "=b" (__addr) \ + : \ + : "cc", "memory", "r3" \ + ); \ + _zzq_orig->r2 = __addr; \ + } + +#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R12 \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* branch-and-link-to-noredir *%R12 */ \ + "or 3,3,3\n\t" + +#define VALGRIND_VEX_INJECT_IR() \ + do { \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + "or 5,5,5\n\t" \ + ); \ + } while (0) + +#endif /* PLAT_ppc64le_linux */ + +/* ------------------------- arm-linux ------------------------- */ + +#if defined(PLAT_arm_linux) + +typedef + struct { + unsigned int nraddr; /* where's the code? */ + } + OrigFn; + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "mov r12, r12, ror #3 ; mov r12, r12, ror #13 \n\t" \ + "mov r12, r12, ror #29 ; mov r12, r12, ror #19 \n\t" + +#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \ + _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + \ + __extension__ \ + ({volatile unsigned int _zzq_args[6]; \ + volatile unsigned int _zzq_result; \ + _zzq_args[0] = (unsigned int)(_zzq_request); \ + _zzq_args[1] = (unsigned int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned int)(_zzq_arg5); \ + __asm__ volatile("mov r3, %1\n\t" /*default*/ \ + "mov r4, %2\n\t" /*ptr*/ \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* R3 = client_request ( R4 ) */ \ + "orr r10, r10, r10\n\t" \ + "mov %0, r3" /*result*/ \ + : "=r" (_zzq_result) \ + : "r" (_zzq_default), "r" (&_zzq_args[0]) \ + : "cc","memory", "r3", "r4"); \ + _zzq_result; \ + }) + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + unsigned int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* R3 = guest_NRADDR */ \ + "orr r11, r11, r11\n\t" \ + "mov %0, r3" \ + : "=r" (__addr) \ + : \ + : "cc", "memory", "r3" \ + ); \ + _zzq_orig->nraddr = __addr; \ + } + +#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* branch-and-link-to-noredir *%R4 */ \ + "orr r12, r12, r12\n\t" + +#define VALGRIND_VEX_INJECT_IR() \ + do { \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + "orr r9, r9, r9\n\t" \ + : : : "cc", "memory" \ + ); \ + } while (0) + +#endif /* PLAT_arm_linux */ + +/* ------------------------ arm64-linux ------------------------- */ + +#if defined(PLAT_arm64_linux) + +typedef + struct { + unsigned long int nraddr; /* where's the code? */ + } + OrigFn; + +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "ror x12, x12, #3 ; ror x12, x12, #13 \n\t" \ + "ror x12, x12, #51 ; ror x12, x12, #61 \n\t" + +#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \ + _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + \ + __extension__ \ + ({volatile unsigned long int _zzq_args[6]; \ + volatile unsigned long int _zzq_result; \ + _zzq_args[0] = (unsigned long int)(_zzq_request); \ + _zzq_args[1] = (unsigned long int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned long int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned long int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned long int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned long int)(_zzq_arg5); \ + __asm__ volatile("mov x3, %1\n\t" /*default*/ \ + "mov x4, %2\n\t" /*ptr*/ \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* X3 = client_request ( X4 ) */ \ + "orr x10, x10, x10\n\t" \ + "mov %0, x3" /*result*/ \ + : "=r" (_zzq_result) \ + : "r" ((unsigned long int)(_zzq_default)), \ + "r" (&_zzq_args[0]) \ + : "cc","memory", "x3", "x4"); \ + _zzq_result; \ + }) + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + unsigned long int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* X3 = guest_NRADDR */ \ + "orr x11, x11, x11\n\t" \ + "mov %0, x3" \ + : "=r" (__addr) \ + : \ + : "cc", "memory", "x3" \ + ); \ + _zzq_orig->nraddr = __addr; \ + } + +#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_X8 \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* branch-and-link-to-noredir X8 */ \ + "orr x12, x12, x12\n\t" + +#define VALGRIND_VEX_INJECT_IR() \ + do { \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + "orr x9, x9, x9\n\t" \ + : : : "cc", "memory" \ + ); \ + } while (0) + +#endif /* PLAT_arm64_linux */ + +/* ------------------------ s390x-linux ------------------------ */ + +#if defined(PLAT_s390x_linux) + +typedef + struct { + unsigned long int nraddr; /* where's the code? */ + } + OrigFn; + +/* __SPECIAL_INSTRUCTION_PREAMBLE will be used to identify Valgrind specific + * code. This detection is implemented in platform specific toIR.c + * (e.g. VEX/priv/guest_s390_decoder.c). + */ +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "lr 15,15\n\t" \ + "lr 1,1\n\t" \ + "lr 2,2\n\t" \ + "lr 3,3\n\t" + +#define __CLIENT_REQUEST_CODE "lr 2,2\n\t" +#define __GET_NR_CONTEXT_CODE "lr 3,3\n\t" +#define __CALL_NO_REDIR_CODE "lr 4,4\n\t" +#define __VEX_INJECT_IR_CODE "lr 5,5\n\t" + +#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \ + _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + __extension__ \ + ({volatile unsigned long int _zzq_args[6]; \ + volatile unsigned long int _zzq_result; \ + _zzq_args[0] = (unsigned long int)(_zzq_request); \ + _zzq_args[1] = (unsigned long int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned long int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned long int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned long int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned long int)(_zzq_arg5); \ + __asm__ volatile(/* r2 = args */ \ + "lgr 2,%1\n\t" \ + /* r3 = default */ \ + "lgr 3,%2\n\t" \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + __CLIENT_REQUEST_CODE \ + /* results = r3 */ \ + "lgr %0, 3\n\t" \ + : "=d" (_zzq_result) \ + : "a" (&_zzq_args[0]), "0" (_zzq_default) \ + : "cc", "2", "3", "memory" \ + ); \ + _zzq_result; \ + }) + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + volatile unsigned long int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + __GET_NR_CONTEXT_CODE \ + "lgr %0, 3\n\t" \ + : "=a" (__addr) \ + : \ + : "cc", "3", "memory" \ + ); \ + _zzq_orig->nraddr = __addr; \ + } + +#define VALGRIND_CALL_NOREDIR_R1 \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + __CALL_NO_REDIR_CODE + +#define VALGRIND_VEX_INJECT_IR() \ + do { \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + __VEX_INJECT_IR_CODE); \ + } while (0) + +#endif /* PLAT_s390x_linux */ + +/* ------------------------- mips32-linux ---------------- */ + +#if defined(PLAT_mips32_linux) + +typedef + struct { + unsigned int nraddr; /* where's the code? */ + } + OrigFn; + +/* .word 0x342 + * .word 0x742 + * .word 0xC2 + * .word 0x4C2*/ +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "srl $0, $0, 13\n\t" \ + "srl $0, $0, 29\n\t" \ + "srl $0, $0, 3\n\t" \ + "srl $0, $0, 19\n\t" + +#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \ + _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + __extension__ \ + ({ volatile unsigned int _zzq_args[6]; \ + volatile unsigned int _zzq_result; \ + _zzq_args[0] = (unsigned int)(_zzq_request); \ + _zzq_args[1] = (unsigned int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned int)(_zzq_arg5); \ + __asm__ volatile("move $11, %1\n\t" /*default*/ \ + "move $12, %2\n\t" /*ptr*/ \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* T3 = client_request ( T4 ) */ \ + "or $13, $13, $13\n\t" \ + "move %0, $11\n\t" /*result*/ \ + : "=r" (_zzq_result) \ + : "r" (_zzq_default), "r" (&_zzq_args[0]) \ + : "$11", "$12", "memory"); \ + _zzq_result; \ + }) + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + volatile unsigned int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* %t9 = guest_NRADDR */ \ + "or $14, $14, $14\n\t" \ + "move %0, $11" /*result*/ \ + : "=r" (__addr) \ + : \ + : "$11" \ + ); \ + _zzq_orig->nraddr = __addr; \ + } + +#define VALGRIND_CALL_NOREDIR_T9 \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* call-noredir *%t9 */ \ + "or $15, $15, $15\n\t" + +#define VALGRIND_VEX_INJECT_IR() \ + do { \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + "or $11, $11, $11\n\t" \ + ); \ + } while (0) + + +#endif /* PLAT_mips32_linux */ + +/* ------------------------- mips64-linux ---------------- */ + +#if defined(PLAT_mips64_linux) + +typedef + struct { + unsigned long nraddr; /* where's the code? */ + } + OrigFn; + +/* dsll $0,$0, 3 + * dsll $0,$0, 13 + * dsll $0,$0, 29 + * dsll $0,$0, 19*/ +#define __SPECIAL_INSTRUCTION_PREAMBLE \ + "dsll $0,$0, 3 ; dsll $0,$0,13\n\t" \ + "dsll $0,$0,29 ; dsll $0,$0,19\n\t" + +#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \ + _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + __extension__ \ + ({ volatile unsigned long int _zzq_args[6]; \ + volatile unsigned long int _zzq_result; \ + _zzq_args[0] = (unsigned long int)(_zzq_request); \ + _zzq_args[1] = (unsigned long int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned long int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned long int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned long int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned long int)(_zzq_arg5); \ + __asm__ volatile("move $11, %1\n\t" /*default*/ \ + "move $12, %2\n\t" /*ptr*/ \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* $11 = client_request ( $12 ) */ \ + "or $13, $13, $13\n\t" \ + "move %0, $11\n\t" /*result*/ \ + : "=r" (_zzq_result) \ + : "r" (_zzq_default), "r" (&_zzq_args[0]) \ + : "$11", "$12", "memory"); \ + _zzq_result; \ + }) + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + volatile unsigned long int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* $11 = guest_NRADDR */ \ + "or $14, $14, $14\n\t" \ + "move %0, $11" /*result*/ \ + : "=r" (__addr) \ + : \ + : "$11"); \ + _zzq_orig->nraddr = __addr; \ + } + +#define VALGRIND_CALL_NOREDIR_T9 \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* call-noredir $25 */ \ + "or $15, $15, $15\n\t" + +#define VALGRIND_VEX_INJECT_IR() \ + do { \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + "or $11, $11, $11\n\t" \ + ); \ + } while (0) + +#endif /* PLAT_mips64_linux */ + +#if defined(PLAT_nanomips_linux) + +typedef + struct { + unsigned int nraddr; /* where's the code? */ + } + OrigFn; +/* + 8000 c04d srl zero, zero, 13 + 8000 c05d srl zero, zero, 29 + 8000 c043 srl zero, zero, 3 + 8000 c053 srl zero, zero, 19 +*/ + +#define __SPECIAL_INSTRUCTION_PREAMBLE "srl[32] $zero, $zero, 13 \n\t" \ + "srl[32] $zero, $zero, 29 \n\t" \ + "srl[32] $zero, $zero, 3 \n\t" \ + "srl[32] $zero, $zero, 19 \n\t" + +#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \ + _zzq_default, _zzq_request, \ + _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \ + __extension__ \ + ({ volatile unsigned int _zzq_args[6]; \ + volatile unsigned int _zzq_result; \ + _zzq_args[0] = (unsigned int)(_zzq_request); \ + _zzq_args[1] = (unsigned int)(_zzq_arg1); \ + _zzq_args[2] = (unsigned int)(_zzq_arg2); \ + _zzq_args[3] = (unsigned int)(_zzq_arg3); \ + _zzq_args[4] = (unsigned int)(_zzq_arg4); \ + _zzq_args[5] = (unsigned int)(_zzq_arg5); \ + __asm__ volatile("move $a7, %1\n\t" /* default */ \ + "move $t0, %2\n\t" /* ptr */ \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* $a7 = client_request( $t0 ) */ \ + "or[32] $t0, $t0, $t0\n\t" \ + "move %0, $a7\n\t" /* result */ \ + : "=r" (_zzq_result) \ + : "r" (_zzq_default), "r" (&_zzq_args[0]) \ + : "$a7", "$t0", "memory"); \ + _zzq_result; \ + }) + +#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \ + { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \ + volatile unsigned long int __addr; \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + /* $a7 = guest_NRADDR */ \ + "or[32] $t1, $t1, $t1\n\t" \ + "move %0, $a7" /*result*/ \ + : "=r" (__addr) \ + : \ + : "$a7"); \ + _zzq_orig->nraddr = __addr; \ + } + +#define VALGRIND_CALL_NOREDIR_T9 \ + __SPECIAL_INSTRUCTION_PREAMBLE \ + /* call-noredir $25 */ \ + "or[32] $t2, $t2, $t2\n\t" + +#define VALGRIND_VEX_INJECT_IR() \ + do { \ + __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \ + "or[32] $t3, $t3, $t3\n\t" \ + ); \ + } while (0) + +#endif +/* Insert assembly code for other platforms here... */ + +#endif /* NVALGRIND */ + + +/* ------------------------------------------------------------------ */ +/* PLATFORM SPECIFICS for FUNCTION WRAPPING. This is all very */ +/* ugly. It's the least-worst tradeoff I can think of. */ +/* ------------------------------------------------------------------ */ + +/* This section defines magic (a.k.a appalling-hack) macros for doing + guaranteed-no-redirection macros, so as to get from function + wrappers to the functions they are wrapping. The whole point is to + construct standard call sequences, but to do the call itself with a + special no-redirect call pseudo-instruction that the JIT + understands and handles specially. This section is long and + repetitious, and I can't see a way to make it shorter. + + The naming scheme is as follows: + + CALL_FN_{W,v}_{v,W,WW,WWW,WWWW,5W,6W,7W,etc} + + 'W' stands for "word" and 'v' for "void". Hence there are + different macros for calling arity 0, 1, 2, 3, 4, etc, functions, + and for each, the possibility of returning a word-typed result, or + no result. +*/ + +/* Use these to write the name of your wrapper. NOTE: duplicates + VG_WRAP_FUNCTION_Z{U,Z} in pub_tool_redir.h. NOTE also: inserts + the default behaviour equivalance class tag "0000" into the name. + See pub_tool_redir.h for details -- normally you don't need to + think about this, though. */ + +/* Use an extra level of macroisation so as to ensure the soname/fnname + args are fully macro-expanded before pasting them together. */ +#define VG_CONCAT4(_aa,_bb,_cc,_dd) _aa##_bb##_cc##_dd + +#define I_WRAP_SONAME_FNNAME_ZU(soname,fnname) \ + VG_CONCAT4(_vgw00000ZU_,soname,_,fnname) + +#define I_WRAP_SONAME_FNNAME_ZZ(soname,fnname) \ + VG_CONCAT4(_vgw00000ZZ_,soname,_,fnname) + +/* Use this macro from within a wrapper function to collect the + context (address and possibly other info) of the original function. + Once you have that you can then use it in one of the CALL_FN_ + macros. The type of the argument _lval is OrigFn. */ +#define VALGRIND_GET_ORIG_FN(_lval) VALGRIND_GET_NR_CONTEXT(_lval) + +/* Also provide end-user facilities for function replacement, rather + than wrapping. A replacement function differs from a wrapper in + that it has no way to get hold of the original function being + called, and hence no way to call onwards to it. In a replacement + function, VALGRIND_GET_ORIG_FN always returns zero. */ + +#define I_REPLACE_SONAME_FNNAME_ZU(soname,fnname) \ + VG_CONCAT4(_vgr00000ZU_,soname,_,fnname) + +#define I_REPLACE_SONAME_FNNAME_ZZ(soname,fnname) \ + VG_CONCAT4(_vgr00000ZZ_,soname,_,fnname) + +/* Derivatives of the main macros below, for calling functions + returning void. */ + +#define CALL_FN_v_v(fnptr) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_v(_junk,fnptr); } while (0) + +#define CALL_FN_v_W(fnptr, arg1) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_W(_junk,fnptr,arg1); } while (0) + +#define CALL_FN_v_WW(fnptr, arg1,arg2) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_WW(_junk,fnptr,arg1,arg2); } while (0) + +#define CALL_FN_v_WWW(fnptr, arg1,arg2,arg3) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_WWW(_junk,fnptr,arg1,arg2,arg3); } while (0) + +#define CALL_FN_v_WWWW(fnptr, arg1,arg2,arg3,arg4) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_WWWW(_junk,fnptr,arg1,arg2,arg3,arg4); } while (0) + +#define CALL_FN_v_5W(fnptr, arg1,arg2,arg3,arg4,arg5) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_5W(_junk,fnptr,arg1,arg2,arg3,arg4,arg5); } while (0) + +#define CALL_FN_v_6W(fnptr, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_6W(_junk,fnptr,arg1,arg2,arg3,arg4,arg5,arg6); } while (0) + +#define CALL_FN_v_7W(fnptr, arg1,arg2,arg3,arg4,arg5,arg6,arg7) \ + do { volatile unsigned long _junk; \ + CALL_FN_W_7W(_junk,fnptr,arg1,arg2,arg3,arg4,arg5,arg6,arg7); } while (0) + +/* ----------------- x86-{linux,darwin,solaris} ---------------- */ + +#if defined(PLAT_x86_linux) || defined(PLAT_x86_darwin) \ + || defined(PLAT_x86_solaris) + +/* These regs are trashed by the hidden call. No need to mention eax + as gcc can already see that, plus causes gcc to bomb. */ +#define __CALLER_SAVED_REGS /*"eax"*/ "ecx", "edx" + +/* Macros to save and align the stack before making a function + call and restore it afterwards as gcc may not keep the stack + pointer aligned if it doesn't realise calls are being made + to other functions. */ + +#define VALGRIND_ALIGN_STACK \ + "movl %%esp,%%edi\n\t" \ + "andl $0xfffffff0,%%esp\n\t" +#define VALGRIND_RESTORE_STACK \ + "movl %%edi,%%esp\n\t" + +/* These CALL_FN_ macros assume that on x86-linux, sizeof(unsigned + long) == 4. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[1]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "edi" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[2]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "subl $12, %%esp\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "edi" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "subl $8, %%esp\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "edi" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[4]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "subl $4, %%esp\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "edi" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[5]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "edi" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[6]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "subl $12, %%esp\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "edi" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[7]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "subl $8, %%esp\n\t" \ + "pushl 24(%%eax)\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "edi" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[8]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "subl $4, %%esp\n\t" \ + "pushl 28(%%eax)\n\t" \ + "pushl 24(%%eax)\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "edi" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[9]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "pushl 32(%%eax)\n\t" \ + "pushl 28(%%eax)\n\t" \ + "pushl 24(%%eax)\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "edi" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[10]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "subl $12, %%esp\n\t" \ + "pushl 36(%%eax)\n\t" \ + "pushl 32(%%eax)\n\t" \ + "pushl 28(%%eax)\n\t" \ + "pushl 24(%%eax)\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "edi" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[11]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "subl $8, %%esp\n\t" \ + "pushl 40(%%eax)\n\t" \ + "pushl 36(%%eax)\n\t" \ + "pushl 32(%%eax)\n\t" \ + "pushl 28(%%eax)\n\t" \ + "pushl 24(%%eax)\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "edi" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ + arg6,arg7,arg8,arg9,arg10, \ + arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[12]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "subl $4, %%esp\n\t" \ + "pushl 44(%%eax)\n\t" \ + "pushl 40(%%eax)\n\t" \ + "pushl 36(%%eax)\n\t" \ + "pushl 32(%%eax)\n\t" \ + "pushl 28(%%eax)\n\t" \ + "pushl 24(%%eax)\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "edi" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ + arg6,arg7,arg8,arg9,arg10, \ + arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[13]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + _argvec[12] = (unsigned long)(arg12); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "pushl 48(%%eax)\n\t" \ + "pushl 44(%%eax)\n\t" \ + "pushl 40(%%eax)\n\t" \ + "pushl 36(%%eax)\n\t" \ + "pushl 32(%%eax)\n\t" \ + "pushl 28(%%eax)\n\t" \ + "pushl 24(%%eax)\n\t" \ + "pushl 20(%%eax)\n\t" \ + "pushl 16(%%eax)\n\t" \ + "pushl 12(%%eax)\n\t" \ + "pushl 8(%%eax)\n\t" \ + "pushl 4(%%eax)\n\t" \ + "movl (%%eax), %%eax\n\t" /* target->%eax */ \ + VALGRIND_CALL_NOREDIR_EAX \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "edi" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_x86_linux || PLAT_x86_darwin || PLAT_x86_solaris */ + +/* ---------------- amd64-{linux,darwin,solaris} --------------- */ + +#if defined(PLAT_amd64_linux) || defined(PLAT_amd64_darwin) \ + || defined(PLAT_amd64_solaris) + +/* ARGREGS: rdi rsi rdx rcx r8 r9 (the rest on stack in R-to-L order) */ + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS /*"rax",*/ "rcx", "rdx", "rsi", \ + "rdi", "r8", "r9", "r10", "r11" + +/* This is all pretty complex. It's so as to make stack unwinding + work reliably. See bug 243270. The basic problem is the sub and + add of 128 of %rsp in all of the following macros. If gcc believes + the CFA is in %rsp, then unwinding may fail, because what's at the + CFA is not what gcc "expected" when it constructs the CFIs for the + places where the macros are instantiated. + + But we can't just add a CFI annotation to increase the CFA offset + by 128, to match the sub of 128 from %rsp, because we don't know + whether gcc has chosen %rsp as the CFA at that point, or whether it + has chosen some other register (eg, %rbp). In the latter case, + adding a CFI annotation to change the CFA offset is simply wrong. + + So the solution is to get hold of the CFA using + __builtin_dwarf_cfa(), put it in a known register, and add a + CFI annotation to say what the register is. We choose %rbp for + this (perhaps perversely), because: + + (1) %rbp is already subject to unwinding. If a new register was + chosen then the unwinder would have to unwind it in all stack + traces, which is expensive, and + + (2) %rbp is already subject to precise exception updates in the + JIT. If a new register was chosen, we'd have to have precise + exceptions for it too, which reduces performance of the + generated code. + + However .. one extra complication. We can't just whack the result + of __builtin_dwarf_cfa() into %rbp and then add %rbp to the + list of trashed registers at the end of the inline assembly + fragments; gcc won't allow %rbp to appear in that list. Hence + instead we need to stash %rbp in %r15 for the duration of the asm, + and say that %r15 is trashed instead. gcc seems happy to go with + that. + + Oh .. and this all needs to be conditionalised so that it is + unchanged from before this commit, when compiled with older gccs + that don't support __builtin_dwarf_cfa. Furthermore, since + this header file is freestanding, it has to be independent of + config.h, and so the following conditionalisation cannot depend on + configure time checks. + + Although it's not clear from + 'defined(__GNUC__) && defined(__GCC_HAVE_DWARF2_CFI_ASM)', + this expression excludes Darwin. + .cfi directives in Darwin assembly appear to be completely + different and I haven't investigated how they work. + + For even more entertainment value, note we have to use the + completely undocumented __builtin_dwarf_cfa(), which appears to + really compute the CFA, whereas __builtin_frame_address(0) claims + to but actually doesn't. See + https://bugs.kde.org/show_bug.cgi?id=243270#c47 +*/ +#if defined(__GNUC__) && defined(__GCC_HAVE_DWARF2_CFI_ASM) +# define __FRAME_POINTER \ + ,"r"(__builtin_dwarf_cfa()) +# define VALGRIND_CFI_PROLOGUE \ + "movq %%rbp, %%r15\n\t" \ + "movq %2, %%rbp\n\t" \ + ".cfi_remember_state\n\t" \ + ".cfi_def_cfa rbp, 0\n\t" +# define VALGRIND_CFI_EPILOGUE \ + "movq %%r15, %%rbp\n\t" \ + ".cfi_restore_state\n\t" +#else +# define __FRAME_POINTER +# define VALGRIND_CFI_PROLOGUE +# define VALGRIND_CFI_EPILOGUE +#endif + +/* Macros to save and align the stack before making a function + call and restore it afterwards as gcc may not keep the stack + pointer aligned if it doesn't realise calls are being made + to other functions. */ + +#define VALGRIND_ALIGN_STACK \ + "movq %%rsp,%%r14\n\t" \ + "andq $0xfffffffffffffff0,%%rsp\n\t" +#define VALGRIND_RESTORE_STACK \ + "movq %%r14,%%rsp\n\t" + +/* These CALL_FN_ macros assume that on amd64-linux, sizeof(unsigned + long) == 8. */ + +/* NB 9 Sept 07. There is a nasty kludge here in all these CALL_FN_ + macros. In order not to trash the stack redzone, we need to drop + %rsp by 128 before the hidden call, and restore afterwards. The + nastyness is that it is only by luck that the stack still appears + to be unwindable during the hidden call - since then the behaviour + of any routine using this macro does not match what the CFI data + says. Sigh. + + Why is this important? Imagine that a wrapper has a stack + allocated local, and passes to the hidden call, a pointer to it. + Because gcc does not know about the hidden call, it may allocate + that local in the redzone. Unfortunately the hidden call may then + trash it before it comes to use it. So we must step clear of the + redzone, for the duration of the hidden call, to make it safe. + + Probably the same problem afflicts the other redzone-style ABIs too + (ppc64-linux); but for those, the stack is + self describing (none of this CFI nonsense) so at least messing + with the stack pointer doesn't give a danger of non-unwindable + stack. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[1]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + VALGRIND_ALIGN_STACK \ + "subq $128,%%rsp\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + VALGRIND_RESTORE_STACK \ + VALGRIND_CFI_EPILOGUE \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r14", "r15" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[2]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + VALGRIND_ALIGN_STACK \ + "subq $128,%%rsp\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + VALGRIND_RESTORE_STACK \ + VALGRIND_CFI_EPILOGUE \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r14", "r15" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + VALGRIND_ALIGN_STACK \ + "subq $128,%%rsp\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + VALGRIND_RESTORE_STACK \ + VALGRIND_CFI_EPILOGUE \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r14", "r15" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[4]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + VALGRIND_ALIGN_STACK \ + "subq $128,%%rsp\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + VALGRIND_RESTORE_STACK \ + VALGRIND_CFI_EPILOGUE \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r14", "r15" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[5]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + VALGRIND_ALIGN_STACK \ + "subq $128,%%rsp\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + VALGRIND_RESTORE_STACK \ + VALGRIND_CFI_EPILOGUE \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r14", "r15" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[6]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + VALGRIND_ALIGN_STACK \ + "subq $128,%%rsp\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + VALGRIND_RESTORE_STACK \ + VALGRIND_CFI_EPILOGUE \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r14", "r15" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[7]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + VALGRIND_ALIGN_STACK \ + "subq $128,%%rsp\n\t" \ + "movq 48(%%rax), %%r9\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + VALGRIND_RESTORE_STACK \ + VALGRIND_CFI_EPILOGUE \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r14", "r15" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[8]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + VALGRIND_ALIGN_STACK \ + "subq $136,%%rsp\n\t" \ + "pushq 56(%%rax)\n\t" \ + "movq 48(%%rax), %%r9\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + VALGRIND_RESTORE_STACK \ + VALGRIND_CFI_EPILOGUE \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r14", "r15" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[9]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + VALGRIND_ALIGN_STACK \ + "subq $128,%%rsp\n\t" \ + "pushq 64(%%rax)\n\t" \ + "pushq 56(%%rax)\n\t" \ + "movq 48(%%rax), %%r9\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + VALGRIND_RESTORE_STACK \ + VALGRIND_CFI_EPILOGUE \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r14", "r15" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[10]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + VALGRIND_ALIGN_STACK \ + "subq $136,%%rsp\n\t" \ + "pushq 72(%%rax)\n\t" \ + "pushq 64(%%rax)\n\t" \ + "pushq 56(%%rax)\n\t" \ + "movq 48(%%rax), %%r9\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + VALGRIND_RESTORE_STACK \ + VALGRIND_CFI_EPILOGUE \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r14", "r15" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[11]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + VALGRIND_ALIGN_STACK \ + "subq $128,%%rsp\n\t" \ + "pushq 80(%%rax)\n\t" \ + "pushq 72(%%rax)\n\t" \ + "pushq 64(%%rax)\n\t" \ + "pushq 56(%%rax)\n\t" \ + "movq 48(%%rax), %%r9\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + VALGRIND_RESTORE_STACK \ + VALGRIND_CFI_EPILOGUE \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r14", "r15" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[12]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + VALGRIND_ALIGN_STACK \ + "subq $136,%%rsp\n\t" \ + "pushq 88(%%rax)\n\t" \ + "pushq 80(%%rax)\n\t" \ + "pushq 72(%%rax)\n\t" \ + "pushq 64(%%rax)\n\t" \ + "pushq 56(%%rax)\n\t" \ + "movq 48(%%rax), %%r9\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + VALGRIND_RESTORE_STACK \ + VALGRIND_CFI_EPILOGUE \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r14", "r15" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[13]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + _argvec[12] = (unsigned long)(arg12); \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + VALGRIND_ALIGN_STACK \ + "subq $128,%%rsp\n\t" \ + "pushq 96(%%rax)\n\t" \ + "pushq 88(%%rax)\n\t" \ + "pushq 80(%%rax)\n\t" \ + "pushq 72(%%rax)\n\t" \ + "pushq 64(%%rax)\n\t" \ + "pushq 56(%%rax)\n\t" \ + "movq 48(%%rax), %%r9\n\t" \ + "movq 40(%%rax), %%r8\n\t" \ + "movq 32(%%rax), %%rcx\n\t" \ + "movq 24(%%rax), %%rdx\n\t" \ + "movq 16(%%rax), %%rsi\n\t" \ + "movq 8(%%rax), %%rdi\n\t" \ + "movq (%%rax), %%rax\n\t" /* target->%rax */ \ + VALGRIND_CALL_NOREDIR_RAX \ + VALGRIND_RESTORE_STACK \ + VALGRIND_CFI_EPILOGUE \ + : /*out*/ "=a" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r14", "r15" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_amd64_linux || PLAT_amd64_darwin || PLAT_amd64_solaris */ + +/* ------------------------ ppc32-linux ------------------------ */ + +#if defined(PLAT_ppc32_linux) + +/* This is useful for finding out about the on-stack stuff: + + extern int f9 ( int,int,int,int,int,int,int,int,int ); + extern int f10 ( int,int,int,int,int,int,int,int,int,int ); + extern int f11 ( int,int,int,int,int,int,int,int,int,int,int ); + extern int f12 ( int,int,int,int,int,int,int,int,int,int,int,int ); + + int g9 ( void ) { + return f9(11,22,33,44,55,66,77,88,99); + } + int g10 ( void ) { + return f10(11,22,33,44,55,66,77,88,99,110); + } + int g11 ( void ) { + return f11(11,22,33,44,55,66,77,88,99,110,121); + } + int g12 ( void ) { + return f12(11,22,33,44,55,66,77,88,99,110,121,132); + } +*/ + +/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */ + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS \ + "lr", "ctr", "xer", \ + "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \ + "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \ + "r11", "r12", "r13" + +/* Macros to save and align the stack before making a function + call and restore it afterwards as gcc may not keep the stack + pointer aligned if it doesn't realise calls are being made + to other functions. */ + +#define VALGRIND_ALIGN_STACK \ + "mr 28,1\n\t" \ + "rlwinm 1,1,0,0,27\n\t" +#define VALGRIND_RESTORE_STACK \ + "mr 1,28\n\t" + +/* These CALL_FN_ macros assume that on ppc32-linux, + sizeof(unsigned long) == 4. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[1]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + VALGRIND_RESTORE_STACK \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[2]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + VALGRIND_RESTORE_STACK \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + VALGRIND_RESTORE_STACK \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[4]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + VALGRIND_RESTORE_STACK \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[5]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + VALGRIND_RESTORE_STACK \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[6]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + VALGRIND_RESTORE_STACK \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[7]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 8,24(11)\n\t" \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + VALGRIND_RESTORE_STACK \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[8]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 8,24(11)\n\t" \ + "lwz 9,28(11)\n\t" \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + VALGRIND_RESTORE_STACK \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[9]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 8,24(11)\n\t" \ + "lwz 9,28(11)\n\t" \ + "lwz 10,32(11)\n\t" /* arg8->r10 */ \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + VALGRIND_RESTORE_STACK \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[10]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + _argvec[9] = (unsigned long)arg9; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "addi 1,1,-16\n\t" \ + /* arg9 */ \ + "lwz 3,36(11)\n\t" \ + "stw 3,8(1)\n\t" \ + /* args1-8 */ \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 8,24(11)\n\t" \ + "lwz 9,28(11)\n\t" \ + "lwz 10,32(11)\n\t" /* arg8->r10 */ \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + VALGRIND_RESTORE_STACK \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[11]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + _argvec[9] = (unsigned long)arg9; \ + _argvec[10] = (unsigned long)arg10; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "addi 1,1,-16\n\t" \ + /* arg10 */ \ + "lwz 3,40(11)\n\t" \ + "stw 3,12(1)\n\t" \ + /* arg9 */ \ + "lwz 3,36(11)\n\t" \ + "stw 3,8(1)\n\t" \ + /* args1-8 */ \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 8,24(11)\n\t" \ + "lwz 9,28(11)\n\t" \ + "lwz 10,32(11)\n\t" /* arg8->r10 */ \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + VALGRIND_RESTORE_STACK \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[12]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + _argvec[9] = (unsigned long)arg9; \ + _argvec[10] = (unsigned long)arg10; \ + _argvec[11] = (unsigned long)arg11; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "addi 1,1,-32\n\t" \ + /* arg11 */ \ + "lwz 3,44(11)\n\t" \ + "stw 3,16(1)\n\t" \ + /* arg10 */ \ + "lwz 3,40(11)\n\t" \ + "stw 3,12(1)\n\t" \ + /* arg9 */ \ + "lwz 3,36(11)\n\t" \ + "stw 3,8(1)\n\t" \ + /* args1-8 */ \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 8,24(11)\n\t" \ + "lwz 9,28(11)\n\t" \ + "lwz 10,32(11)\n\t" /* arg8->r10 */ \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + VALGRIND_RESTORE_STACK \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[13]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + _argvec[9] = (unsigned long)arg9; \ + _argvec[10] = (unsigned long)arg10; \ + _argvec[11] = (unsigned long)arg11; \ + _argvec[12] = (unsigned long)arg12; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "addi 1,1,-32\n\t" \ + /* arg12 */ \ + "lwz 3,48(11)\n\t" \ + "stw 3,20(1)\n\t" \ + /* arg11 */ \ + "lwz 3,44(11)\n\t" \ + "stw 3,16(1)\n\t" \ + /* arg10 */ \ + "lwz 3,40(11)\n\t" \ + "stw 3,12(1)\n\t" \ + /* arg9 */ \ + "lwz 3,36(11)\n\t" \ + "stw 3,8(1)\n\t" \ + /* args1-8 */ \ + "lwz 3,4(11)\n\t" /* arg1->r3 */ \ + "lwz 4,8(11)\n\t" \ + "lwz 5,12(11)\n\t" \ + "lwz 6,16(11)\n\t" /* arg4->r6 */ \ + "lwz 7,20(11)\n\t" \ + "lwz 8,24(11)\n\t" \ + "lwz 9,28(11)\n\t" \ + "lwz 10,32(11)\n\t" /* arg8->r10 */ \ + "lwz 11,0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + VALGRIND_RESTORE_STACK \ + "mr %0,3" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_ppc32_linux */ + +/* ------------------------ ppc64-linux ------------------------ */ + +#if defined(PLAT_ppc64be_linux) + +/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */ + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS \ + "lr", "ctr", "xer", \ + "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \ + "r0", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \ + "r11", "r12", "r13" + +/* Macros to save and align the stack before making a function + call and restore it afterwards as gcc may not keep the stack + pointer aligned if it doesn't realise calls are being made + to other functions. */ + +#define VALGRIND_ALIGN_STACK \ + "mr 28,1\n\t" \ + "rldicr 1,1,0,59\n\t" +#define VALGRIND_RESTORE_STACK \ + "mr 1,28\n\t" + +/* These CALL_FN_ macros assume that on ppc64-linux, sizeof(unsigned + long) == 8. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+0]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+1]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+2]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+3]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+4]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+5]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+6]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+7]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+8]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+9]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "addi 1,1,-128\n\t" /* expand stack frame */ \ + /* arg9 */ \ + "ld 3,72(11)\n\t" \ + "std 3,112(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+10]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "addi 1,1,-128\n\t" /* expand stack frame */ \ + /* arg10 */ \ + "ld 3,80(11)\n\t" \ + "std 3,120(1)\n\t" \ + /* arg9 */ \ + "ld 3,72(11)\n\t" \ + "std 3,112(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+11]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + _argvec[2+11] = (unsigned long)arg11; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "addi 1,1,-144\n\t" /* expand stack frame */ \ + /* arg11 */ \ + "ld 3,88(11)\n\t" \ + "std 3,128(1)\n\t" \ + /* arg10 */ \ + "ld 3,80(11)\n\t" \ + "std 3,120(1)\n\t" \ + /* arg9 */ \ + "ld 3,72(11)\n\t" \ + "std 3,112(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+12]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + _argvec[2+11] = (unsigned long)arg11; \ + _argvec[2+12] = (unsigned long)arg12; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 11,%1\n\t" \ + "std 2,-16(11)\n\t" /* save tocptr */ \ + "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \ + "addi 1,1,-144\n\t" /* expand stack frame */ \ + /* arg12 */ \ + "ld 3,96(11)\n\t" \ + "std 3,136(1)\n\t" \ + /* arg11 */ \ + "ld 3,88(11)\n\t" \ + "std 3,128(1)\n\t" \ + /* arg10 */ \ + "ld 3,80(11)\n\t" \ + "std 3,120(1)\n\t" \ + /* arg9 */ \ + "ld 3,72(11)\n\t" \ + "std 3,112(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(11)\n\t" /* arg1->r3 */ \ + "ld 4, 16(11)\n\t" /* arg2->r4 */ \ + "ld 5, 24(11)\n\t" /* arg3->r5 */ \ + "ld 6, 32(11)\n\t" /* arg4->r6 */ \ + "ld 7, 40(11)\n\t" /* arg5->r7 */ \ + "ld 8, 48(11)\n\t" /* arg6->r8 */ \ + "ld 9, 56(11)\n\t" /* arg7->r9 */ \ + "ld 10, 64(11)\n\t" /* arg8->r10 */ \ + "ld 11, 0(11)\n\t" /* target->r11 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \ + "mr 11,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(11)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_ppc64be_linux */ + +/* ------------------------- ppc64le-linux ----------------------- */ +#if defined(PLAT_ppc64le_linux) + +/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */ + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS \ + "lr", "ctr", "xer", \ + "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \ + "r0", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \ + "r11", "r12", "r13" + +/* Macros to save and align the stack before making a function + call and restore it afterwards as gcc may not keep the stack + pointer aligned if it doesn't realise calls are being made + to other functions. */ + +#define VALGRIND_ALIGN_STACK \ + "mr 28,1\n\t" \ + "rldicr 1,1,0,59\n\t" +#define VALGRIND_RESTORE_STACK \ + "mr 1,28\n\t" + +/* These CALL_FN_ macros assume that on ppc64-linux, sizeof(unsigned + long) == 8. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+0]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 12,%1\n\t" \ + "std 2,-16(12)\n\t" /* save tocptr */ \ + "ld 2,-8(12)\n\t" /* use nraddr's tocptr */ \ + "ld 12, 0(12)\n\t" /* target->r12 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R12 \ + "mr 12,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(12)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+1]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 12,%1\n\t" \ + "std 2,-16(12)\n\t" /* save tocptr */ \ + "ld 2,-8(12)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(12)\n\t" /* arg1->r3 */ \ + "ld 12, 0(12)\n\t" /* target->r12 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R12 \ + "mr 12,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(12)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+2]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 12,%1\n\t" \ + "std 2,-16(12)\n\t" /* save tocptr */ \ + "ld 2,-8(12)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(12)\n\t" /* arg1->r3 */ \ + "ld 4, 16(12)\n\t" /* arg2->r4 */ \ + "ld 12, 0(12)\n\t" /* target->r12 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R12 \ + "mr 12,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(12)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+3]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 12,%1\n\t" \ + "std 2,-16(12)\n\t" /* save tocptr */ \ + "ld 2,-8(12)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(12)\n\t" /* arg1->r3 */ \ + "ld 4, 16(12)\n\t" /* arg2->r4 */ \ + "ld 5, 24(12)\n\t" /* arg3->r5 */ \ + "ld 12, 0(12)\n\t" /* target->r12 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R12 \ + "mr 12,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(12)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+4]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 12,%1\n\t" \ + "std 2,-16(12)\n\t" /* save tocptr */ \ + "ld 2,-8(12)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(12)\n\t" /* arg1->r3 */ \ + "ld 4, 16(12)\n\t" /* arg2->r4 */ \ + "ld 5, 24(12)\n\t" /* arg3->r5 */ \ + "ld 6, 32(12)\n\t" /* arg4->r6 */ \ + "ld 12, 0(12)\n\t" /* target->r12 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R12 \ + "mr 12,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(12)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+5]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 12,%1\n\t" \ + "std 2,-16(12)\n\t" /* save tocptr */ \ + "ld 2,-8(12)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(12)\n\t" /* arg1->r3 */ \ + "ld 4, 16(12)\n\t" /* arg2->r4 */ \ + "ld 5, 24(12)\n\t" /* arg3->r5 */ \ + "ld 6, 32(12)\n\t" /* arg4->r6 */ \ + "ld 7, 40(12)\n\t" /* arg5->r7 */ \ + "ld 12, 0(12)\n\t" /* target->r12 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R12 \ + "mr 12,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(12)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+6]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 12,%1\n\t" \ + "std 2,-16(12)\n\t" /* save tocptr */ \ + "ld 2,-8(12)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(12)\n\t" /* arg1->r3 */ \ + "ld 4, 16(12)\n\t" /* arg2->r4 */ \ + "ld 5, 24(12)\n\t" /* arg3->r5 */ \ + "ld 6, 32(12)\n\t" /* arg4->r6 */ \ + "ld 7, 40(12)\n\t" /* arg5->r7 */ \ + "ld 8, 48(12)\n\t" /* arg6->r8 */ \ + "ld 12, 0(12)\n\t" /* target->r12 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R12 \ + "mr 12,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(12)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+7]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 12,%1\n\t" \ + "std 2,-16(12)\n\t" /* save tocptr */ \ + "ld 2,-8(12)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(12)\n\t" /* arg1->r3 */ \ + "ld 4, 16(12)\n\t" /* arg2->r4 */ \ + "ld 5, 24(12)\n\t" /* arg3->r5 */ \ + "ld 6, 32(12)\n\t" /* arg4->r6 */ \ + "ld 7, 40(12)\n\t" /* arg5->r7 */ \ + "ld 8, 48(12)\n\t" /* arg6->r8 */ \ + "ld 9, 56(12)\n\t" /* arg7->r9 */ \ + "ld 12, 0(12)\n\t" /* target->r12 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R12 \ + "mr 12,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(12)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+8]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 12,%1\n\t" \ + "std 2,-16(12)\n\t" /* save tocptr */ \ + "ld 2,-8(12)\n\t" /* use nraddr's tocptr */ \ + "ld 3, 8(12)\n\t" /* arg1->r3 */ \ + "ld 4, 16(12)\n\t" /* arg2->r4 */ \ + "ld 5, 24(12)\n\t" /* arg3->r5 */ \ + "ld 6, 32(12)\n\t" /* arg4->r6 */ \ + "ld 7, 40(12)\n\t" /* arg5->r7 */ \ + "ld 8, 48(12)\n\t" /* arg6->r8 */ \ + "ld 9, 56(12)\n\t" /* arg7->r9 */ \ + "ld 10, 64(12)\n\t" /* arg8->r10 */ \ + "ld 12, 0(12)\n\t" /* target->r12 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R12 \ + "mr 12,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(12)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+9]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 12,%1\n\t" \ + "std 2,-16(12)\n\t" /* save tocptr */ \ + "ld 2,-8(12)\n\t" /* use nraddr's tocptr */ \ + "addi 1,1,-128\n\t" /* expand stack frame */ \ + /* arg9 */ \ + "ld 3,72(12)\n\t" \ + "std 3,96(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(12)\n\t" /* arg1->r3 */ \ + "ld 4, 16(12)\n\t" /* arg2->r4 */ \ + "ld 5, 24(12)\n\t" /* arg3->r5 */ \ + "ld 6, 32(12)\n\t" /* arg4->r6 */ \ + "ld 7, 40(12)\n\t" /* arg5->r7 */ \ + "ld 8, 48(12)\n\t" /* arg6->r8 */ \ + "ld 9, 56(12)\n\t" /* arg7->r9 */ \ + "ld 10, 64(12)\n\t" /* arg8->r10 */ \ + "ld 12, 0(12)\n\t" /* target->r12 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R12 \ + "mr 12,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(12)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+10]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 12,%1\n\t" \ + "std 2,-16(12)\n\t" /* save tocptr */ \ + "ld 2,-8(12)\n\t" /* use nraddr's tocptr */ \ + "addi 1,1,-128\n\t" /* expand stack frame */ \ + /* arg10 */ \ + "ld 3,80(12)\n\t" \ + "std 3,104(1)\n\t" \ + /* arg9 */ \ + "ld 3,72(12)\n\t" \ + "std 3,96(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(12)\n\t" /* arg1->r3 */ \ + "ld 4, 16(12)\n\t" /* arg2->r4 */ \ + "ld 5, 24(12)\n\t" /* arg3->r5 */ \ + "ld 6, 32(12)\n\t" /* arg4->r6 */ \ + "ld 7, 40(12)\n\t" /* arg5->r7 */ \ + "ld 8, 48(12)\n\t" /* arg6->r8 */ \ + "ld 9, 56(12)\n\t" /* arg7->r9 */ \ + "ld 10, 64(12)\n\t" /* arg8->r10 */ \ + "ld 12, 0(12)\n\t" /* target->r12 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R12 \ + "mr 12,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(12)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+11]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + _argvec[2+11] = (unsigned long)arg11; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 12,%1\n\t" \ + "std 2,-16(12)\n\t" /* save tocptr */ \ + "ld 2,-8(12)\n\t" /* use nraddr's tocptr */ \ + "addi 1,1,-144\n\t" /* expand stack frame */ \ + /* arg11 */ \ + "ld 3,88(12)\n\t" \ + "std 3,112(1)\n\t" \ + /* arg10 */ \ + "ld 3,80(12)\n\t" \ + "std 3,104(1)\n\t" \ + /* arg9 */ \ + "ld 3,72(12)\n\t" \ + "std 3,96(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(12)\n\t" /* arg1->r3 */ \ + "ld 4, 16(12)\n\t" /* arg2->r4 */ \ + "ld 5, 24(12)\n\t" /* arg3->r5 */ \ + "ld 6, 32(12)\n\t" /* arg4->r6 */ \ + "ld 7, 40(12)\n\t" /* arg5->r7 */ \ + "ld 8, 48(12)\n\t" /* arg6->r8 */ \ + "ld 9, 56(12)\n\t" /* arg7->r9 */ \ + "ld 10, 64(12)\n\t" /* arg8->r10 */ \ + "ld 12, 0(12)\n\t" /* target->r12 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R12 \ + "mr 12,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(12)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3+12]; \ + volatile unsigned long _res; \ + /* _argvec[0] holds current r2 across the call */ \ + _argvec[1] = (unsigned long)_orig.r2; \ + _argvec[2] = (unsigned long)_orig.nraddr; \ + _argvec[2+1] = (unsigned long)arg1; \ + _argvec[2+2] = (unsigned long)arg2; \ + _argvec[2+3] = (unsigned long)arg3; \ + _argvec[2+4] = (unsigned long)arg4; \ + _argvec[2+5] = (unsigned long)arg5; \ + _argvec[2+6] = (unsigned long)arg6; \ + _argvec[2+7] = (unsigned long)arg7; \ + _argvec[2+8] = (unsigned long)arg8; \ + _argvec[2+9] = (unsigned long)arg9; \ + _argvec[2+10] = (unsigned long)arg10; \ + _argvec[2+11] = (unsigned long)arg11; \ + _argvec[2+12] = (unsigned long)arg12; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "mr 12,%1\n\t" \ + "std 2,-16(12)\n\t" /* save tocptr */ \ + "ld 2,-8(12)\n\t" /* use nraddr's tocptr */ \ + "addi 1,1,-144\n\t" /* expand stack frame */ \ + /* arg12 */ \ + "ld 3,96(12)\n\t" \ + "std 3,120(1)\n\t" \ + /* arg11 */ \ + "ld 3,88(12)\n\t" \ + "std 3,112(1)\n\t" \ + /* arg10 */ \ + "ld 3,80(12)\n\t" \ + "std 3,104(1)\n\t" \ + /* arg9 */ \ + "ld 3,72(12)\n\t" \ + "std 3,96(1)\n\t" \ + /* args1-8 */ \ + "ld 3, 8(12)\n\t" /* arg1->r3 */ \ + "ld 4, 16(12)\n\t" /* arg2->r4 */ \ + "ld 5, 24(12)\n\t" /* arg3->r5 */ \ + "ld 6, 32(12)\n\t" /* arg4->r6 */ \ + "ld 7, 40(12)\n\t" /* arg5->r7 */ \ + "ld 8, 48(12)\n\t" /* arg6->r8 */ \ + "ld 9, 56(12)\n\t" /* arg7->r9 */ \ + "ld 10, 64(12)\n\t" /* arg8->r10 */ \ + "ld 12, 0(12)\n\t" /* target->r12 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R12 \ + "mr 12,%1\n\t" \ + "mr %0,3\n\t" \ + "ld 2,-16(12)\n\t" /* restore tocptr */ \ + VALGRIND_RESTORE_STACK \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[2]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r28" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_ppc64le_linux */ + +/* ------------------------- arm-linux ------------------------- */ + +#if defined(PLAT_arm_linux) + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS "r0", "r1", "r2", "r3","r4", "r12", "r14" + +/* Macros to save and align the stack before making a function + call and restore it afterwards as gcc may not keep the stack + pointer aligned if it doesn't realise calls are being made + to other functions. */ + +/* This is a bit tricky. We store the original stack pointer in r10 + as it is callee-saves. gcc doesn't allow the use of r11 for some + reason. Also, we can't directly "bic" the stack pointer in thumb + mode since r13 isn't an allowed register number in that context. + So use r4 as a temporary, since that is about to get trashed + anyway, just after each use of this macro. Side effect is we need + to be very careful about any future changes, since + VALGRIND_ALIGN_STACK simply assumes r4 is usable. */ +#define VALGRIND_ALIGN_STACK \ + "mov r10, sp\n\t" \ + "mov r4, sp\n\t" \ + "bic r4, r4, #7\n\t" \ + "mov sp, r4\n\t" +#define VALGRIND_RESTORE_STACK \ + "mov sp, r10\n\t" + +/* These CALL_FN_ macros assume that on arm-linux, sizeof(unsigned + long) == 4. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[1]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + VALGRIND_RESTORE_STACK \ + "mov %0, r0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r10" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[2]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + VALGRIND_RESTORE_STACK \ + "mov %0, r0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r10" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + VALGRIND_RESTORE_STACK \ + "mov %0, r0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r10" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[4]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + VALGRIND_RESTORE_STACK \ + "mov %0, r0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r10" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[5]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + VALGRIND_RESTORE_STACK \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r10" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[6]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "sub sp, sp, #4 \n\t" \ + "ldr r0, [%1, #20] \n\t" \ + "push {r0} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + VALGRIND_RESTORE_STACK \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r10" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[7]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr r0, [%1, #20] \n\t" \ + "ldr r1, [%1, #24] \n\t" \ + "push {r0, r1} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + VALGRIND_RESTORE_STACK \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r10" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[8]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "sub sp, sp, #4 \n\t" \ + "ldr r0, [%1, #20] \n\t" \ + "ldr r1, [%1, #24] \n\t" \ + "ldr r2, [%1, #28] \n\t" \ + "push {r0, r1, r2} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + VALGRIND_RESTORE_STACK \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r10" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[9]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr r0, [%1, #20] \n\t" \ + "ldr r1, [%1, #24] \n\t" \ + "ldr r2, [%1, #28] \n\t" \ + "ldr r3, [%1, #32] \n\t" \ + "push {r0, r1, r2, r3} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + VALGRIND_RESTORE_STACK \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r10" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[10]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "sub sp, sp, #4 \n\t" \ + "ldr r0, [%1, #20] \n\t" \ + "ldr r1, [%1, #24] \n\t" \ + "ldr r2, [%1, #28] \n\t" \ + "ldr r3, [%1, #32] \n\t" \ + "ldr r4, [%1, #36] \n\t" \ + "push {r0, r1, r2, r3, r4} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + VALGRIND_RESTORE_STACK \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r10" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[11]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr r0, [%1, #40] \n\t" \ + "push {r0} \n\t" \ + "ldr r0, [%1, #20] \n\t" \ + "ldr r1, [%1, #24] \n\t" \ + "ldr r2, [%1, #28] \n\t" \ + "ldr r3, [%1, #32] \n\t" \ + "ldr r4, [%1, #36] \n\t" \ + "push {r0, r1, r2, r3, r4} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + VALGRIND_RESTORE_STACK \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r10" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ + arg6,arg7,arg8,arg9,arg10, \ + arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[12]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "sub sp, sp, #4 \n\t" \ + "ldr r0, [%1, #40] \n\t" \ + "ldr r1, [%1, #44] \n\t" \ + "push {r0, r1} \n\t" \ + "ldr r0, [%1, #20] \n\t" \ + "ldr r1, [%1, #24] \n\t" \ + "ldr r2, [%1, #28] \n\t" \ + "ldr r3, [%1, #32] \n\t" \ + "ldr r4, [%1, #36] \n\t" \ + "push {r0, r1, r2, r3, r4} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + VALGRIND_RESTORE_STACK \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r10" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ + arg6,arg7,arg8,arg9,arg10, \ + arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[13]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + _argvec[12] = (unsigned long)(arg12); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr r0, [%1, #40] \n\t" \ + "ldr r1, [%1, #44] \n\t" \ + "ldr r2, [%1, #48] \n\t" \ + "push {r0, r1, r2} \n\t" \ + "ldr r0, [%1, #20] \n\t" \ + "ldr r1, [%1, #24] \n\t" \ + "ldr r2, [%1, #28] \n\t" \ + "ldr r3, [%1, #32] \n\t" \ + "ldr r4, [%1, #36] \n\t" \ + "push {r0, r1, r2, r3, r4} \n\t" \ + "ldr r0, [%1, #4] \n\t" \ + "ldr r1, [%1, #8] \n\t" \ + "ldr r2, [%1, #12] \n\t" \ + "ldr r3, [%1, #16] \n\t" \ + "ldr r4, [%1] \n\t" /* target->r4 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \ + VALGRIND_RESTORE_STACK \ + "mov %0, r0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r10" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_arm_linux */ + +/* ------------------------ arm64-linux ------------------------ */ + +#if defined(PLAT_arm64_linux) + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS \ + "x0", "x1", "x2", "x3","x4", "x5", "x6", "x7", "x8", "x9", \ + "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17", \ + "x18", "x19", "x20", "x30", \ + "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", \ + "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", \ + "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", \ + "v26", "v27", "v28", "v29", "v30", "v31" + +/* x21 is callee-saved, so we can use it to save and restore SP around + the hidden call. */ +#define VALGRIND_ALIGN_STACK \ + "mov x21, sp\n\t" \ + "bic sp, x21, #15\n\t" +#define VALGRIND_RESTORE_STACK \ + "mov sp, x21\n\t" + +/* These CALL_FN_ macros assume that on arm64-linux, + sizeof(unsigned long) == 8. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[1]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr x8, [%1] \n\t" /* target->x8 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_X8 \ + VALGRIND_RESTORE_STACK \ + "mov %0, x0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "x21" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[2]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr x0, [%1, #8] \n\t" \ + "ldr x8, [%1] \n\t" /* target->x8 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_X8 \ + VALGRIND_RESTORE_STACK \ + "mov %0, x0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "x21" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr x0, [%1, #8] \n\t" \ + "ldr x1, [%1, #16] \n\t" \ + "ldr x8, [%1] \n\t" /* target->x8 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_X8 \ + VALGRIND_RESTORE_STACK \ + "mov %0, x0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "x21" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[4]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr x0, [%1, #8] \n\t" \ + "ldr x1, [%1, #16] \n\t" \ + "ldr x2, [%1, #24] \n\t" \ + "ldr x8, [%1] \n\t" /* target->x8 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_X8 \ + VALGRIND_RESTORE_STACK \ + "mov %0, x0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "x21" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[5]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr x0, [%1, #8] \n\t" \ + "ldr x1, [%1, #16] \n\t" \ + "ldr x2, [%1, #24] \n\t" \ + "ldr x3, [%1, #32] \n\t" \ + "ldr x8, [%1] \n\t" /* target->x8 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_X8 \ + VALGRIND_RESTORE_STACK \ + "mov %0, x0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "x21" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[6]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr x0, [%1, #8] \n\t" \ + "ldr x1, [%1, #16] \n\t" \ + "ldr x2, [%1, #24] \n\t" \ + "ldr x3, [%1, #32] \n\t" \ + "ldr x4, [%1, #40] \n\t" \ + "ldr x8, [%1] \n\t" /* target->x8 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_X8 \ + VALGRIND_RESTORE_STACK \ + "mov %0, x0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "x21" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[7]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr x0, [%1, #8] \n\t" \ + "ldr x1, [%1, #16] \n\t" \ + "ldr x2, [%1, #24] \n\t" \ + "ldr x3, [%1, #32] \n\t" \ + "ldr x4, [%1, #40] \n\t" \ + "ldr x5, [%1, #48] \n\t" \ + "ldr x8, [%1] \n\t" /* target->x8 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_X8 \ + VALGRIND_RESTORE_STACK \ + "mov %0, x0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "x21" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[8]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr x0, [%1, #8] \n\t" \ + "ldr x1, [%1, #16] \n\t" \ + "ldr x2, [%1, #24] \n\t" \ + "ldr x3, [%1, #32] \n\t" \ + "ldr x4, [%1, #40] \n\t" \ + "ldr x5, [%1, #48] \n\t" \ + "ldr x6, [%1, #56] \n\t" \ + "ldr x8, [%1] \n\t" /* target->x8 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_X8 \ + VALGRIND_RESTORE_STACK \ + "mov %0, x0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "x21" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[9]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "ldr x0, [%1, #8] \n\t" \ + "ldr x1, [%1, #16] \n\t" \ + "ldr x2, [%1, #24] \n\t" \ + "ldr x3, [%1, #32] \n\t" \ + "ldr x4, [%1, #40] \n\t" \ + "ldr x5, [%1, #48] \n\t" \ + "ldr x6, [%1, #56] \n\t" \ + "ldr x7, [%1, #64] \n\t" \ + "ldr x8, [%1] \n\t" /* target->x8 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_X8 \ + VALGRIND_RESTORE_STACK \ + "mov %0, x0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "x21" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[10]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "sub sp, sp, #0x20 \n\t" \ + "ldr x0, [%1, #8] \n\t" \ + "ldr x1, [%1, #16] \n\t" \ + "ldr x2, [%1, #24] \n\t" \ + "ldr x3, [%1, #32] \n\t" \ + "ldr x4, [%1, #40] \n\t" \ + "ldr x5, [%1, #48] \n\t" \ + "ldr x6, [%1, #56] \n\t" \ + "ldr x7, [%1, #64] \n\t" \ + "ldr x8, [%1, #72] \n\t" \ + "str x8, [sp, #0] \n\t" \ + "ldr x8, [%1] \n\t" /* target->x8 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_X8 \ + VALGRIND_RESTORE_STACK \ + "mov %0, x0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "x21" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[11]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "sub sp, sp, #0x20 \n\t" \ + "ldr x0, [%1, #8] \n\t" \ + "ldr x1, [%1, #16] \n\t" \ + "ldr x2, [%1, #24] \n\t" \ + "ldr x3, [%1, #32] \n\t" \ + "ldr x4, [%1, #40] \n\t" \ + "ldr x5, [%1, #48] \n\t" \ + "ldr x6, [%1, #56] \n\t" \ + "ldr x7, [%1, #64] \n\t" \ + "ldr x8, [%1, #72] \n\t" \ + "str x8, [sp, #0] \n\t" \ + "ldr x8, [%1, #80] \n\t" \ + "str x8, [sp, #8] \n\t" \ + "ldr x8, [%1] \n\t" /* target->x8 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_X8 \ + VALGRIND_RESTORE_STACK \ + "mov %0, x0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "x21" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[12]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "sub sp, sp, #0x30 \n\t" \ + "ldr x0, [%1, #8] \n\t" \ + "ldr x1, [%1, #16] \n\t" \ + "ldr x2, [%1, #24] \n\t" \ + "ldr x3, [%1, #32] \n\t" \ + "ldr x4, [%1, #40] \n\t" \ + "ldr x5, [%1, #48] \n\t" \ + "ldr x6, [%1, #56] \n\t" \ + "ldr x7, [%1, #64] \n\t" \ + "ldr x8, [%1, #72] \n\t" \ + "str x8, [sp, #0] \n\t" \ + "ldr x8, [%1, #80] \n\t" \ + "str x8, [sp, #8] \n\t" \ + "ldr x8, [%1, #88] \n\t" \ + "str x8, [sp, #16] \n\t" \ + "ldr x8, [%1] \n\t" /* target->x8 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_X8 \ + VALGRIND_RESTORE_STACK \ + "mov %0, x0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "x21" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10,arg11, \ + arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[13]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + _argvec[12] = (unsigned long)(arg12); \ + __asm__ volatile( \ + VALGRIND_ALIGN_STACK \ + "sub sp, sp, #0x30 \n\t" \ + "ldr x0, [%1, #8] \n\t" \ + "ldr x1, [%1, #16] \n\t" \ + "ldr x2, [%1, #24] \n\t" \ + "ldr x3, [%1, #32] \n\t" \ + "ldr x4, [%1, #40] \n\t" \ + "ldr x5, [%1, #48] \n\t" \ + "ldr x6, [%1, #56] \n\t" \ + "ldr x7, [%1, #64] \n\t" \ + "ldr x8, [%1, #72] \n\t" \ + "str x8, [sp, #0] \n\t" \ + "ldr x8, [%1, #80] \n\t" \ + "str x8, [sp, #8] \n\t" \ + "ldr x8, [%1, #88] \n\t" \ + "str x8, [sp, #16] \n\t" \ + "ldr x8, [%1, #96] \n\t" \ + "str x8, [sp, #24] \n\t" \ + "ldr x8, [%1] \n\t" /* target->x8 */ \ + VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_X8 \ + VALGRIND_RESTORE_STACK \ + "mov %0, x0" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "x21" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_arm64_linux */ + +/* ------------------------- s390x-linux ------------------------- */ + +#if defined(PLAT_s390x_linux) + +/* Similar workaround as amd64 (see above), but we use r11 as frame + pointer and save the old r11 in r7. r11 might be used for + argvec, therefore we copy argvec in r1 since r1 is clobbered + after the call anyway. */ +#if defined(__GNUC__) && defined(__GCC_HAVE_DWARF2_CFI_ASM) +# define __FRAME_POINTER \ + ,"d"(__builtin_dwarf_cfa()) +# define VALGRIND_CFI_PROLOGUE \ + ".cfi_remember_state\n\t" \ + "lgr 1,%1\n\t" /* copy the argvec pointer in r1 */ \ + "lgr 7,11\n\t" \ + "lgr 11,%2\n\t" \ + ".cfi_def_cfa r11, 0\n\t" +# define VALGRIND_CFI_EPILOGUE \ + "lgr 11, 7\n\t" \ + ".cfi_restore_state\n\t" +#else +# define __FRAME_POINTER +# define VALGRIND_CFI_PROLOGUE \ + "lgr 1,%1\n\t" +# define VALGRIND_CFI_EPILOGUE +#endif + +/* Nb: On s390 the stack pointer is properly aligned *at all times* + according to the s390 GCC maintainer. (The ABI specification is not + precise in this regard.) Therefore, VALGRIND_ALIGN_STACK and + VALGRIND_RESTORE_STACK are not defined here. */ + +/* These regs are trashed by the hidden call. Note that we overwrite + r14 in s390_irgen_noredir (VEX/priv/guest_s390_irgen.c) to give the + function a proper return address. All others are ABI defined call + clobbers. */ +#if defined(__VX__) || defined(__S390_VX__) +#define __CALLER_SAVED_REGS "0", "1", "2", "3", "4", "5", "14", \ + "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", \ + "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", \ + "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", \ + "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31" +#else +#define __CALLER_SAVED_REGS "0", "1", "2", "3", "4", "5", "14", \ + "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7" +#endif + +/* Nb: Although r11 is modified in the asm snippets below (inside + VALGRIND_CFI_PROLOGUE) it is not listed in the clobber section, for + two reasons: + (1) r11 is restored in VALGRIND_CFI_EPILOGUE, so effectively it is not + modified + (2) GCC will complain that r11 cannot appear inside a clobber section, + when compiled with -O -fno-omit-frame-pointer + */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[1]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + "aghi 15,-160\n\t" \ + "lg 1, 0(1)\n\t" /* target->r1 */ \ + VALGRIND_CALL_NOREDIR_R1 \ + "aghi 15,160\n\t" \ + VALGRIND_CFI_EPILOGUE \ + "lgr %0, 2\n\t" \ + : /*out*/ "=d" (_res) \ + : /*in*/ "d" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS,"7" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +/* The call abi has the arguments in r2-r6 and stack */ +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[2]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + "aghi 15,-160\n\t" \ + "lg 2, 8(1)\n\t" \ + "lg 1, 0(1)\n\t" \ + VALGRIND_CALL_NOREDIR_R1 \ + "aghi 15,160\n\t" \ + VALGRIND_CFI_EPILOGUE \ + "lgr %0, 2\n\t" \ + : /*out*/ "=d" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS,"7" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1, arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + "aghi 15,-160\n\t" \ + "lg 2, 8(1)\n\t" \ + "lg 3,16(1)\n\t" \ + "lg 1, 0(1)\n\t" \ + VALGRIND_CALL_NOREDIR_R1 \ + "aghi 15,160\n\t" \ + VALGRIND_CFI_EPILOGUE \ + "lgr %0, 2\n\t" \ + : /*out*/ "=d" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS,"7" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1, arg2, arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[4]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + "aghi 15,-160\n\t" \ + "lg 2, 8(1)\n\t" \ + "lg 3,16(1)\n\t" \ + "lg 4,24(1)\n\t" \ + "lg 1, 0(1)\n\t" \ + VALGRIND_CALL_NOREDIR_R1 \ + "aghi 15,160\n\t" \ + VALGRIND_CFI_EPILOGUE \ + "lgr %0, 2\n\t" \ + : /*out*/ "=d" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS,"7" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1, arg2, arg3, arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[5]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + "aghi 15,-160\n\t" \ + "lg 2, 8(1)\n\t" \ + "lg 3,16(1)\n\t" \ + "lg 4,24(1)\n\t" \ + "lg 5,32(1)\n\t" \ + "lg 1, 0(1)\n\t" \ + VALGRIND_CALL_NOREDIR_R1 \ + "aghi 15,160\n\t" \ + VALGRIND_CFI_EPILOGUE \ + "lgr %0, 2\n\t" \ + : /*out*/ "=d" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS,"7" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1, arg2, arg3, arg4, arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[6]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + "aghi 15,-160\n\t" \ + "lg 2, 8(1)\n\t" \ + "lg 3,16(1)\n\t" \ + "lg 4,24(1)\n\t" \ + "lg 5,32(1)\n\t" \ + "lg 6,40(1)\n\t" \ + "lg 1, 0(1)\n\t" \ + VALGRIND_CALL_NOREDIR_R1 \ + "aghi 15,160\n\t" \ + VALGRIND_CFI_EPILOGUE \ + "lgr %0, 2\n\t" \ + : /*out*/ "=d" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS,"6","7" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1, arg2, arg3, arg4, arg5, \ + arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[7]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + "aghi 15,-168\n\t" \ + "lg 2, 8(1)\n\t" \ + "lg 3,16(1)\n\t" \ + "lg 4,24(1)\n\t" \ + "lg 5,32(1)\n\t" \ + "lg 6,40(1)\n\t" \ + "mvc 160(8,15), 48(1)\n\t" \ + "lg 1, 0(1)\n\t" \ + VALGRIND_CALL_NOREDIR_R1 \ + "aghi 15,168\n\t" \ + VALGRIND_CFI_EPILOGUE \ + "lgr %0, 2\n\t" \ + : /*out*/ "=d" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS,"6","7" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1, arg2, arg3, arg4, arg5, \ + arg6, arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[8]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + "aghi 15,-176\n\t" \ + "lg 2, 8(1)\n\t" \ + "lg 3,16(1)\n\t" \ + "lg 4,24(1)\n\t" \ + "lg 5,32(1)\n\t" \ + "lg 6,40(1)\n\t" \ + "mvc 160(8,15), 48(1)\n\t" \ + "mvc 168(8,15), 56(1)\n\t" \ + "lg 1, 0(1)\n\t" \ + VALGRIND_CALL_NOREDIR_R1 \ + "aghi 15,176\n\t" \ + VALGRIND_CFI_EPILOGUE \ + "lgr %0, 2\n\t" \ + : /*out*/ "=d" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS,"6","7" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1, arg2, arg3, arg4, arg5, \ + arg6, arg7 ,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[9]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + "aghi 15,-184\n\t" \ + "lg 2, 8(1)\n\t" \ + "lg 3,16(1)\n\t" \ + "lg 4,24(1)\n\t" \ + "lg 5,32(1)\n\t" \ + "lg 6,40(1)\n\t" \ + "mvc 160(8,15), 48(1)\n\t" \ + "mvc 168(8,15), 56(1)\n\t" \ + "mvc 176(8,15), 64(1)\n\t" \ + "lg 1, 0(1)\n\t" \ + VALGRIND_CALL_NOREDIR_R1 \ + "aghi 15,184\n\t" \ + VALGRIND_CFI_EPILOGUE \ + "lgr %0, 2\n\t" \ + : /*out*/ "=d" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS,"6","7" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1, arg2, arg3, arg4, arg5, \ + arg6, arg7 ,arg8, arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[10]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + _argvec[9] = (unsigned long)arg9; \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + "aghi 15,-192\n\t" \ + "lg 2, 8(1)\n\t" \ + "lg 3,16(1)\n\t" \ + "lg 4,24(1)\n\t" \ + "lg 5,32(1)\n\t" \ + "lg 6,40(1)\n\t" \ + "mvc 160(8,15), 48(1)\n\t" \ + "mvc 168(8,15), 56(1)\n\t" \ + "mvc 176(8,15), 64(1)\n\t" \ + "mvc 184(8,15), 72(1)\n\t" \ + "lg 1, 0(1)\n\t" \ + VALGRIND_CALL_NOREDIR_R1 \ + "aghi 15,192\n\t" \ + VALGRIND_CFI_EPILOGUE \ + "lgr %0, 2\n\t" \ + : /*out*/ "=d" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS,"6","7" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1, arg2, arg3, arg4, arg5, \ + arg6, arg7 ,arg8, arg9, arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[11]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + _argvec[9] = (unsigned long)arg9; \ + _argvec[10] = (unsigned long)arg10; \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + "aghi 15,-200\n\t" \ + "lg 2, 8(1)\n\t" \ + "lg 3,16(1)\n\t" \ + "lg 4,24(1)\n\t" \ + "lg 5,32(1)\n\t" \ + "lg 6,40(1)\n\t" \ + "mvc 160(8,15), 48(1)\n\t" \ + "mvc 168(8,15), 56(1)\n\t" \ + "mvc 176(8,15), 64(1)\n\t" \ + "mvc 184(8,15), 72(1)\n\t" \ + "mvc 192(8,15), 80(1)\n\t" \ + "lg 1, 0(1)\n\t" \ + VALGRIND_CALL_NOREDIR_R1 \ + "aghi 15,200\n\t" \ + VALGRIND_CFI_EPILOGUE \ + "lgr %0, 2\n\t" \ + : /*out*/ "=d" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS,"6","7" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1, arg2, arg3, arg4, arg5, \ + arg6, arg7 ,arg8, arg9, arg10, arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[12]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + _argvec[9] = (unsigned long)arg9; \ + _argvec[10] = (unsigned long)arg10; \ + _argvec[11] = (unsigned long)arg11; \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + "aghi 15,-208\n\t" \ + "lg 2, 8(1)\n\t" \ + "lg 3,16(1)\n\t" \ + "lg 4,24(1)\n\t" \ + "lg 5,32(1)\n\t" \ + "lg 6,40(1)\n\t" \ + "mvc 160(8,15), 48(1)\n\t" \ + "mvc 168(8,15), 56(1)\n\t" \ + "mvc 176(8,15), 64(1)\n\t" \ + "mvc 184(8,15), 72(1)\n\t" \ + "mvc 192(8,15), 80(1)\n\t" \ + "mvc 200(8,15), 88(1)\n\t" \ + "lg 1, 0(1)\n\t" \ + VALGRIND_CALL_NOREDIR_R1 \ + "aghi 15,208\n\t" \ + VALGRIND_CFI_EPILOGUE \ + "lgr %0, 2\n\t" \ + : /*out*/ "=d" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS,"6","7" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1, arg2, arg3, arg4, arg5, \ + arg6, arg7 ,arg8, arg9, arg10, arg11, arg12)\ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[13]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)arg1; \ + _argvec[2] = (unsigned long)arg2; \ + _argvec[3] = (unsigned long)arg3; \ + _argvec[4] = (unsigned long)arg4; \ + _argvec[5] = (unsigned long)arg5; \ + _argvec[6] = (unsigned long)arg6; \ + _argvec[7] = (unsigned long)arg7; \ + _argvec[8] = (unsigned long)arg8; \ + _argvec[9] = (unsigned long)arg9; \ + _argvec[10] = (unsigned long)arg10; \ + _argvec[11] = (unsigned long)arg11; \ + _argvec[12] = (unsigned long)arg12; \ + __asm__ volatile( \ + VALGRIND_CFI_PROLOGUE \ + "aghi 15,-216\n\t" \ + "lg 2, 8(1)\n\t" \ + "lg 3,16(1)\n\t" \ + "lg 4,24(1)\n\t" \ + "lg 5,32(1)\n\t" \ + "lg 6,40(1)\n\t" \ + "mvc 160(8,15), 48(1)\n\t" \ + "mvc 168(8,15), 56(1)\n\t" \ + "mvc 176(8,15), 64(1)\n\t" \ + "mvc 184(8,15), 72(1)\n\t" \ + "mvc 192(8,15), 80(1)\n\t" \ + "mvc 200(8,15), 88(1)\n\t" \ + "mvc 208(8,15), 96(1)\n\t" \ + "lg 1, 0(1)\n\t" \ + VALGRIND_CALL_NOREDIR_R1 \ + "aghi 15,216\n\t" \ + VALGRIND_CFI_EPILOGUE \ + "lgr %0, 2\n\t" \ + : /*out*/ "=d" (_res) \ + : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \ + : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS,"6","7" \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + + +#endif /* PLAT_s390x_linux */ + +/* ------------------------- mips32-linux ----------------------- */ + +#if defined(PLAT_mips32_linux) + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS "$2", "$3", "$4", "$5", "$6", \ +"$7", "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$24", \ +"$25", "$31" + +/* These CALL_FN_ macros assume that on mips-linux, sizeof(unsigned + long) == 4. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[1]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + "subu $29, $29, 8 \n\t" \ + "sw $28, 0($29) \n\t" \ + "sw $31, 4($29) \n\t" \ + "subu $29, $29, 16 \n\t" \ + "lw $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "addu $29, $29, 16\n\t" \ + "lw $28, 0($29) \n\t" \ + "lw $31, 4($29) \n\t" \ + "addu $29, $29, 8 \n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[2]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + __asm__ volatile( \ + "subu $29, $29, 8 \n\t" \ + "sw $28, 0($29) \n\t" \ + "sw $31, 4($29) \n\t" \ + "subu $29, $29, 16 \n\t" \ + "lw $4, 4(%1) \n\t" /* arg1*/ \ + "lw $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "addu $29, $29, 16 \n\t" \ + "lw $28, 0($29) \n\t" \ + "lw $31, 4($29) \n\t" \ + "addu $29, $29, 8 \n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + __asm__ volatile( \ + "subu $29, $29, 8 \n\t" \ + "sw $28, 0($29) \n\t" \ + "sw $31, 4($29) \n\t" \ + "subu $29, $29, 16 \n\t" \ + "lw $4, 4(%1) \n\t" \ + "lw $5, 8(%1) \n\t" \ + "lw $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "addu $29, $29, 16 \n\t" \ + "lw $28, 0($29) \n\t" \ + "lw $31, 4($29) \n\t" \ + "addu $29, $29, 8 \n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[4]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + __asm__ volatile( \ + "subu $29, $29, 8 \n\t" \ + "sw $28, 0($29) \n\t" \ + "sw $31, 4($29) \n\t" \ + "subu $29, $29, 16 \n\t" \ + "lw $4, 4(%1) \n\t" \ + "lw $5, 8(%1) \n\t" \ + "lw $6, 12(%1) \n\t" \ + "lw $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "addu $29, $29, 16 \n\t" \ + "lw $28, 0($29) \n\t" \ + "lw $31, 4($29) \n\t" \ + "addu $29, $29, 8 \n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[5]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + __asm__ volatile( \ + "subu $29, $29, 8 \n\t" \ + "sw $28, 0($29) \n\t" \ + "sw $31, 4($29) \n\t" \ + "subu $29, $29, 16 \n\t" \ + "lw $4, 4(%1) \n\t" \ + "lw $5, 8(%1) \n\t" \ + "lw $6, 12(%1) \n\t" \ + "lw $7, 16(%1) \n\t" \ + "lw $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "addu $29, $29, 16 \n\t" \ + "lw $28, 0($29) \n\t" \ + "lw $31, 4($29) \n\t" \ + "addu $29, $29, 8 \n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[6]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + __asm__ volatile( \ + "subu $29, $29, 8 \n\t" \ + "sw $28, 0($29) \n\t" \ + "sw $31, 4($29) \n\t" \ + "lw $4, 20(%1) \n\t" \ + "subu $29, $29, 24\n\t" \ + "sw $4, 16($29) \n\t" \ + "lw $4, 4(%1) \n\t" \ + "lw $5, 8(%1) \n\t" \ + "lw $6, 12(%1) \n\t" \ + "lw $7, 16(%1) \n\t" \ + "lw $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "addu $29, $29, 24 \n\t" \ + "lw $28, 0($29) \n\t" \ + "lw $31, 4($29) \n\t" \ + "addu $29, $29, 8 \n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[7]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + __asm__ volatile( \ + "subu $29, $29, 8 \n\t" \ + "sw $28, 0($29) \n\t" \ + "sw $31, 4($29) \n\t" \ + "lw $4, 20(%1) \n\t" \ + "subu $29, $29, 32\n\t" \ + "sw $4, 16($29) \n\t" \ + "lw $4, 24(%1) \n\t" \ + "nop\n\t" \ + "sw $4, 20($29) \n\t" \ + "lw $4, 4(%1) \n\t" \ + "lw $5, 8(%1) \n\t" \ + "lw $6, 12(%1) \n\t" \ + "lw $7, 16(%1) \n\t" \ + "lw $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "addu $29, $29, 32 \n\t" \ + "lw $28, 0($29) \n\t" \ + "lw $31, 4($29) \n\t" \ + "addu $29, $29, 8 \n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[8]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + __asm__ volatile( \ + "subu $29, $29, 8 \n\t" \ + "sw $28, 0($29) \n\t" \ + "sw $31, 4($29) \n\t" \ + "lw $4, 20(%1) \n\t" \ + "subu $29, $29, 32\n\t" \ + "sw $4, 16($29) \n\t" \ + "lw $4, 24(%1) \n\t" \ + "sw $4, 20($29) \n\t" \ + "lw $4, 28(%1) \n\t" \ + "sw $4, 24($29) \n\t" \ + "lw $4, 4(%1) \n\t" \ + "lw $5, 8(%1) \n\t" \ + "lw $6, 12(%1) \n\t" \ + "lw $7, 16(%1) \n\t" \ + "lw $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "addu $29, $29, 32 \n\t" \ + "lw $28, 0($29) \n\t" \ + "lw $31, 4($29) \n\t" \ + "addu $29, $29, 8 \n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[9]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + __asm__ volatile( \ + "subu $29, $29, 8 \n\t" \ + "sw $28, 0($29) \n\t" \ + "sw $31, 4($29) \n\t" \ + "lw $4, 20(%1) \n\t" \ + "subu $29, $29, 40\n\t" \ + "sw $4, 16($29) \n\t" \ + "lw $4, 24(%1) \n\t" \ + "sw $4, 20($29) \n\t" \ + "lw $4, 28(%1) \n\t" \ + "sw $4, 24($29) \n\t" \ + "lw $4, 32(%1) \n\t" \ + "sw $4, 28($29) \n\t" \ + "lw $4, 4(%1) \n\t" \ + "lw $5, 8(%1) \n\t" \ + "lw $6, 12(%1) \n\t" \ + "lw $7, 16(%1) \n\t" \ + "lw $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "addu $29, $29, 40 \n\t" \ + "lw $28, 0($29) \n\t" \ + "lw $31, 4($29) \n\t" \ + "addu $29, $29, 8 \n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[10]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + __asm__ volatile( \ + "subu $29, $29, 8 \n\t" \ + "sw $28, 0($29) \n\t" \ + "sw $31, 4($29) \n\t" \ + "lw $4, 20(%1) \n\t" \ + "subu $29, $29, 40\n\t" \ + "sw $4, 16($29) \n\t" \ + "lw $4, 24(%1) \n\t" \ + "sw $4, 20($29) \n\t" \ + "lw $4, 28(%1) \n\t" \ + "sw $4, 24($29) \n\t" \ + "lw $4, 32(%1) \n\t" \ + "sw $4, 28($29) \n\t" \ + "lw $4, 36(%1) \n\t" \ + "sw $4, 32($29) \n\t" \ + "lw $4, 4(%1) \n\t" \ + "lw $5, 8(%1) \n\t" \ + "lw $6, 12(%1) \n\t" \ + "lw $7, 16(%1) \n\t" \ + "lw $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "addu $29, $29, 40 \n\t" \ + "lw $28, 0($29) \n\t" \ + "lw $31, 4($29) \n\t" \ + "addu $29, $29, 8 \n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[11]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + __asm__ volatile( \ + "subu $29, $29, 8 \n\t" \ + "sw $28, 0($29) \n\t" \ + "sw $31, 4($29) \n\t" \ + "lw $4, 20(%1) \n\t" \ + "subu $29, $29, 48\n\t" \ + "sw $4, 16($29) \n\t" \ + "lw $4, 24(%1) \n\t" \ + "sw $4, 20($29) \n\t" \ + "lw $4, 28(%1) \n\t" \ + "sw $4, 24($29) \n\t" \ + "lw $4, 32(%1) \n\t" \ + "sw $4, 28($29) \n\t" \ + "lw $4, 36(%1) \n\t" \ + "sw $4, 32($29) \n\t" \ + "lw $4, 40(%1) \n\t" \ + "sw $4, 36($29) \n\t" \ + "lw $4, 4(%1) \n\t" \ + "lw $5, 8(%1) \n\t" \ + "lw $6, 12(%1) \n\t" \ + "lw $7, 16(%1) \n\t" \ + "lw $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "addu $29, $29, 48 \n\t" \ + "lw $28, 0($29) \n\t" \ + "lw $31, 4($29) \n\t" \ + "addu $29, $29, 8 \n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ + arg6,arg7,arg8,arg9,arg10, \ + arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[12]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + __asm__ volatile( \ + "subu $29, $29, 8 \n\t" \ + "sw $28, 0($29) \n\t" \ + "sw $31, 4($29) \n\t" \ + "lw $4, 20(%1) \n\t" \ + "subu $29, $29, 48\n\t" \ + "sw $4, 16($29) \n\t" \ + "lw $4, 24(%1) \n\t" \ + "sw $4, 20($29) \n\t" \ + "lw $4, 28(%1) \n\t" \ + "sw $4, 24($29) \n\t" \ + "lw $4, 32(%1) \n\t" \ + "sw $4, 28($29) \n\t" \ + "lw $4, 36(%1) \n\t" \ + "sw $4, 32($29) \n\t" \ + "lw $4, 40(%1) \n\t" \ + "sw $4, 36($29) \n\t" \ + "lw $4, 44(%1) \n\t" \ + "sw $4, 40($29) \n\t" \ + "lw $4, 4(%1) \n\t" \ + "lw $5, 8(%1) \n\t" \ + "lw $6, 12(%1) \n\t" \ + "lw $7, 16(%1) \n\t" \ + "lw $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "addu $29, $29, 48 \n\t" \ + "lw $28, 0($29) \n\t" \ + "lw $31, 4($29) \n\t" \ + "addu $29, $29, 8 \n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ + arg6,arg7,arg8,arg9,arg10, \ + arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[13]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + _argvec[12] = (unsigned long)(arg12); \ + __asm__ volatile( \ + "subu $29, $29, 8 \n\t" \ + "sw $28, 0($29) \n\t" \ + "sw $31, 4($29) \n\t" \ + "lw $4, 20(%1) \n\t" \ + "subu $29, $29, 56\n\t" \ + "sw $4, 16($29) \n\t" \ + "lw $4, 24(%1) \n\t" \ + "sw $4, 20($29) \n\t" \ + "lw $4, 28(%1) \n\t" \ + "sw $4, 24($29) \n\t" \ + "lw $4, 32(%1) \n\t" \ + "sw $4, 28($29) \n\t" \ + "lw $4, 36(%1) \n\t" \ + "sw $4, 32($29) \n\t" \ + "lw $4, 40(%1) \n\t" \ + "sw $4, 36($29) \n\t" \ + "lw $4, 44(%1) \n\t" \ + "sw $4, 40($29) \n\t" \ + "lw $4, 48(%1) \n\t" \ + "sw $4, 44($29) \n\t" \ + "lw $4, 4(%1) \n\t" \ + "lw $5, 8(%1) \n\t" \ + "lw $6, 12(%1) \n\t" \ + "lw $7, 16(%1) \n\t" \ + "lw $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "addu $29, $29, 56 \n\t" \ + "lw $28, 0($29) \n\t" \ + "lw $31, 4($29) \n\t" \ + "addu $29, $29, 8 \n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_mips32_linux */ + +/* ------------------------- nanomips-linux -------------------- */ + +#if defined(PLAT_nanomips_linux) + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS "$t4", "$t5", "$a0", "$a1", "$a2", \ +"$a3", "$a4", "$a5", "$a6", "$a7", "$t0", "$t1", "$t2", "$t3", \ +"$t8","$t9", "$at" + +/* These CALL_FN_ macros assume that on mips-linux, sizeof(unsigned + long) == 4. */ + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[1]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + __asm__ volatile( \ + "lw $t9, 0(%1)\n\t" \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $a0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[2]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + __asm__ volatile( \ + "lw $t9, 0(%1)\n\t" \ + "lw $a0, 4(%1)\n\t" \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $a0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[3]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + __asm__ volatile( \ + "lw $t9, 0(%1)\n\t" \ + "lw $a0, 4(%1)\n\t" \ + "lw $a1, 8(%1)\n\t" \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $a0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[4]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + __asm__ volatile( \ + "lw $t9, 0(%1)\n\t" \ + "lw $a0, 4(%1)\n\t" \ + "lw $a1, 8(%1)\n\t" \ + "lw $a2,12(%1)\n\t" \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $a0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[5]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + __asm__ volatile( \ + "lw $t9, 0(%1)\n\t" \ + "lw $a0, 4(%1)\n\t" \ + "lw $a1, 8(%1)\n\t" \ + "lw $a2,12(%1)\n\t" \ + "lw $a3,16(%1)\n\t" \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $a0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[6]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + __asm__ volatile( \ + "lw $t9, 0(%1)\n\t" \ + "lw $a0, 4(%1)\n\t" \ + "lw $a1, 8(%1)\n\t" \ + "lw $a2,12(%1)\n\t" \ + "lw $a3,16(%1)\n\t" \ + "lw $a4,20(%1)\n\t" \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $a0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[7]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + __asm__ volatile( \ + "lw $t9, 0(%1)\n\t" \ + "lw $a0, 4(%1)\n\t" \ + "lw $a1, 8(%1)\n\t" \ + "lw $a2,12(%1)\n\t" \ + "lw $a3,16(%1)\n\t" \ + "lw $a4,20(%1)\n\t" \ + "lw $a5,24(%1)\n\t" \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $a0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[8]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + __asm__ volatile( \ + "lw $t9, 0(%1)\n\t" \ + "lw $a0, 4(%1)\n\t" \ + "lw $a1, 8(%1)\n\t" \ + "lw $a2,12(%1)\n\t" \ + "lw $a3,16(%1)\n\t" \ + "lw $a4,20(%1)\n\t" \ + "lw $a5,24(%1)\n\t" \ + "lw $a6,28(%1)\n\t" \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $a0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[9]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + __asm__ volatile( \ + "lw $t9, 0(%1)\n\t" \ + "lw $a0, 4(%1)\n\t" \ + "lw $a1, 8(%1)\n\t" \ + "lw $a2,12(%1)\n\t" \ + "lw $a3,16(%1)\n\t" \ + "lw $a4,20(%1)\n\t" \ + "lw $a5,24(%1)\n\t" \ + "lw $a6,28(%1)\n\t" \ + "lw $a7,32(%1)\n\t" \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $a0\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[10]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + __asm__ volatile( \ + "addiu $sp, $sp, -16 \n\t" \ + "lw $t9,36(%1) \n\t" \ + "sw $t9, 0($sp) \n\t" \ + "lw $t9, 0(%1) \n\t" \ + "lw $a0, 4(%1) \n\t" \ + "lw $a1, 8(%1) \n\t" \ + "lw $a2,12(%1) \n\t" \ + "lw $a3,16(%1) \n\t" \ + "lw $a4,20(%1) \n\t" \ + "lw $a5,24(%1) \n\t" \ + "lw $a6,28(%1) \n\t" \ + "lw $a7,32(%1) \n\t" \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $a0 \n\t" \ + "addiu $sp, $sp, 16 \n\t" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[11]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + __asm__ volatile( \ + "addiu $sp, $sp, -16 \n\t" \ + "lw $t9,36(%1) \n\t" \ + "sw $t9, 0($sp) \n\t" \ + "lw $t9,40(%1) \n\t" \ + "sw $t9, 4($sp) \n\t" \ + "lw $t9, 0(%1) \n\t" \ + "lw $a0, 4(%1) \n\t" \ + "lw $a1, 8(%1) \n\t" \ + "lw $a2,12(%1) \n\t" \ + "lw $a3,16(%1) \n\t" \ + "lw $a4,20(%1) \n\t" \ + "lw $a5,24(%1) \n\t" \ + "lw $a6,28(%1) \n\t" \ + "lw $a7,32(%1) \n\t" \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $a0 \n\t" \ + "addiu $sp, $sp, 16 \n\t" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ + arg6,arg7,arg8,arg9,arg10, \ + arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[12]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + __asm__ volatile( \ + "addiu $sp, $sp, -16 \n\t" \ + "lw $t9,36(%1) \n\t" \ + "sw $t9, 0($sp) \n\t" \ + "lw $t9,40(%1) \n\t" \ + "sw $t9, 4($sp) \n\t" \ + "lw $t9,44(%1) \n\t" \ + "sw $t9, 8($sp) \n\t" \ + "lw $t9, 0(%1) \n\t" \ + "lw $a0, 4(%1) \n\t" \ + "lw $a1, 8(%1) \n\t" \ + "lw $a2,12(%1) \n\t" \ + "lw $a3,16(%1) \n\t" \ + "lw $a4,20(%1) \n\t" \ + "lw $a5,24(%1) \n\t" \ + "lw $a6,28(%1) \n\t" \ + "lw $a7,32(%1) \n\t" \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $a0 \n\t" \ + "addiu $sp, $sp, 16 \n\t" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ + arg6,arg7,arg8,arg9,arg10, \ + arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long _argvec[13]; \ + volatile unsigned long _res; \ + _argvec[0] = (unsigned long)_orig.nraddr; \ + _argvec[1] = (unsigned long)(arg1); \ + _argvec[2] = (unsigned long)(arg2); \ + _argvec[3] = (unsigned long)(arg3); \ + _argvec[4] = (unsigned long)(arg4); \ + _argvec[5] = (unsigned long)(arg5); \ + _argvec[6] = (unsigned long)(arg6); \ + _argvec[7] = (unsigned long)(arg7); \ + _argvec[8] = (unsigned long)(arg8); \ + _argvec[9] = (unsigned long)(arg9); \ + _argvec[10] = (unsigned long)(arg10); \ + _argvec[11] = (unsigned long)(arg11); \ + _argvec[12] = (unsigned long)(arg12); \ + __asm__ volatile( \ + "addiu $sp, $sp, -16 \n\t" \ + "lw $t9,36(%1) \n\t" \ + "sw $t9, 0($sp) \n\t" \ + "lw $t9,40(%1) \n\t" \ + "sw $t9, 4($sp) \n\t" \ + "lw $t9,44(%1) \n\t" \ + "sw $t9, 8($sp) \n\t" \ + "lw $t9,48(%1) \n\t" \ + "sw $t9,12($sp) \n\t" \ + "lw $t9, 0(%1) \n\t" \ + "lw $a0, 4(%1) \n\t" \ + "lw $a1, 8(%1) \n\t" \ + "lw $a2,12(%1) \n\t" \ + "lw $a3,16(%1) \n\t" \ + "lw $a4,20(%1) \n\t" \ + "lw $a5,24(%1) \n\t" \ + "lw $a6,28(%1) \n\t" \ + "lw $a7,32(%1) \n\t" \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $a0 \n\t" \ + "addiu $sp, $sp, 16 \n\t" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) _res; \ + } while (0) + +#endif /* PLAT_nanomips_linux */ + +/* ------------------------- mips64-linux ------------------------- */ + +#if defined(PLAT_mips64_linux) + +/* These regs are trashed by the hidden call. */ +#define __CALLER_SAVED_REGS "$2", "$3", "$4", "$5", "$6", \ +"$7", "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$24", \ +"$25", "$31" + +/* These CALL_FN_ macros assume that on mips64-linux, + sizeof(long long) == 8. */ + +#define MIPS64_LONG2REG_CAST(x) ((long long)(long)x) + +#define CALL_FN_W_v(lval, orig) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long long _argvec[1]; \ + volatile unsigned long long _res; \ + _argvec[0] = MIPS64_LONG2REG_CAST(_orig.nraddr); \ + __asm__ volatile( \ + "ld $25, 0(%1)\n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "0" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) (long)_res; \ + } while (0) + +#define CALL_FN_W_W(lval, orig, arg1) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long long _argvec[2]; \ + volatile unsigned long long _res; \ + _argvec[0] = MIPS64_LONG2REG_CAST(_orig.nraddr); \ + _argvec[1] = MIPS64_LONG2REG_CAST(arg1); \ + __asm__ volatile( \ + "ld $4, 8(%1)\n\t" /* arg1*/ \ + "ld $25, 0(%1)\n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) (long)_res; \ + } while (0) + +#define CALL_FN_W_WW(lval, orig, arg1,arg2) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long long _argvec[3]; \ + volatile unsigned long long _res; \ + _argvec[0] = _orig.nraddr; \ + _argvec[1] = MIPS64_LONG2REG_CAST(arg1); \ + _argvec[2] = MIPS64_LONG2REG_CAST(arg2); \ + __asm__ volatile( \ + "ld $4, 8(%1)\n\t" \ + "ld $5, 16(%1)\n\t" \ + "ld $25, 0(%1)\n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) (long)_res; \ + } while (0) + + +#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long long _argvec[4]; \ + volatile unsigned long long _res; \ + _argvec[0] = _orig.nraddr; \ + _argvec[1] = MIPS64_LONG2REG_CAST(arg1); \ + _argvec[2] = MIPS64_LONG2REG_CAST(arg2); \ + _argvec[3] = MIPS64_LONG2REG_CAST(arg3); \ + __asm__ volatile( \ + "ld $4, 8(%1)\n\t" \ + "ld $5, 16(%1)\n\t" \ + "ld $6, 24(%1)\n\t" \ + "ld $25, 0(%1)\n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) (long)_res; \ + } while (0) + +#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long long _argvec[5]; \ + volatile unsigned long long _res; \ + _argvec[0] = MIPS64_LONG2REG_CAST(_orig.nraddr); \ + _argvec[1] = MIPS64_LONG2REG_CAST(arg1); \ + _argvec[2] = MIPS64_LONG2REG_CAST(arg2); \ + _argvec[3] = MIPS64_LONG2REG_CAST(arg3); \ + _argvec[4] = MIPS64_LONG2REG_CAST(arg4); \ + __asm__ volatile( \ + "ld $4, 8(%1)\n\t" \ + "ld $5, 16(%1)\n\t" \ + "ld $6, 24(%1)\n\t" \ + "ld $7, 32(%1)\n\t" \ + "ld $25, 0(%1)\n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) (long)_res; \ + } while (0) + +#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long long _argvec[6]; \ + volatile unsigned long long _res; \ + _argvec[0] = MIPS64_LONG2REG_CAST(_orig.nraddr); \ + _argvec[1] = MIPS64_LONG2REG_CAST(arg1); \ + _argvec[2] = MIPS64_LONG2REG_CAST(arg2); \ + _argvec[3] = MIPS64_LONG2REG_CAST(arg3); \ + _argvec[4] = MIPS64_LONG2REG_CAST(arg4); \ + _argvec[5] = MIPS64_LONG2REG_CAST(arg5); \ + __asm__ volatile( \ + "ld $4, 8(%1)\n\t" \ + "ld $5, 16(%1)\n\t" \ + "ld $6, 24(%1)\n\t" \ + "ld $7, 32(%1)\n\t" \ + "ld $8, 40(%1)\n\t" \ + "ld $25, 0(%1)\n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) (long)_res; \ + } while (0) + +#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long long _argvec[7]; \ + volatile unsigned long long _res; \ + _argvec[0] = MIPS64_LONG2REG_CAST(_orig.nraddr); \ + _argvec[1] = MIPS64_LONG2REG_CAST(arg1); \ + _argvec[2] = MIPS64_LONG2REG_CAST(arg2); \ + _argvec[3] = MIPS64_LONG2REG_CAST(arg3); \ + _argvec[4] = MIPS64_LONG2REG_CAST(arg4); \ + _argvec[5] = MIPS64_LONG2REG_CAST(arg5); \ + _argvec[6] = MIPS64_LONG2REG_CAST(arg6); \ + __asm__ volatile( \ + "ld $4, 8(%1)\n\t" \ + "ld $5, 16(%1)\n\t" \ + "ld $6, 24(%1)\n\t" \ + "ld $7, 32(%1)\n\t" \ + "ld $8, 40(%1)\n\t" \ + "ld $9, 48(%1)\n\t" \ + "ld $25, 0(%1)\n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) (long)_res; \ + } while (0) + +#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long long _argvec[8]; \ + volatile unsigned long long _res; \ + _argvec[0] = MIPS64_LONG2REG_CAST(_orig.nraddr); \ + _argvec[1] = MIPS64_LONG2REG_CAST(arg1); \ + _argvec[2] = MIPS64_LONG2REG_CAST(arg2); \ + _argvec[3] = MIPS64_LONG2REG_CAST(arg3); \ + _argvec[4] = MIPS64_LONG2REG_CAST(arg4); \ + _argvec[5] = MIPS64_LONG2REG_CAST(arg5); \ + _argvec[6] = MIPS64_LONG2REG_CAST(arg6); \ + _argvec[7] = MIPS64_LONG2REG_CAST(arg7); \ + __asm__ volatile( \ + "ld $4, 8(%1)\n\t" \ + "ld $5, 16(%1)\n\t" \ + "ld $6, 24(%1)\n\t" \ + "ld $7, 32(%1)\n\t" \ + "ld $8, 40(%1)\n\t" \ + "ld $9, 48(%1)\n\t" \ + "ld $10, 56(%1)\n\t" \ + "ld $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) (long)_res; \ + } while (0) + +#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long long _argvec[9]; \ + volatile unsigned long long _res; \ + _argvec[0] = MIPS64_LONG2REG_CAST(_orig.nraddr); \ + _argvec[1] = MIPS64_LONG2REG_CAST(arg1); \ + _argvec[2] = MIPS64_LONG2REG_CAST(arg2); \ + _argvec[3] = MIPS64_LONG2REG_CAST(arg3); \ + _argvec[4] = MIPS64_LONG2REG_CAST(arg4); \ + _argvec[5] = MIPS64_LONG2REG_CAST(arg5); \ + _argvec[6] = MIPS64_LONG2REG_CAST(arg6); \ + _argvec[7] = MIPS64_LONG2REG_CAST(arg7); \ + _argvec[8] = MIPS64_LONG2REG_CAST(arg8); \ + __asm__ volatile( \ + "ld $4, 8(%1)\n\t" \ + "ld $5, 16(%1)\n\t" \ + "ld $6, 24(%1)\n\t" \ + "ld $7, 32(%1)\n\t" \ + "ld $8, 40(%1)\n\t" \ + "ld $9, 48(%1)\n\t" \ + "ld $10, 56(%1)\n\t" \ + "ld $11, 64(%1)\n\t" \ + "ld $25, 0(%1) \n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) (long)_res; \ + } while (0) + +#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long long _argvec[10]; \ + volatile unsigned long long _res; \ + _argvec[0] = MIPS64_LONG2REG_CAST(_orig.nraddr); \ + _argvec[1] = MIPS64_LONG2REG_CAST(arg1); \ + _argvec[2] = MIPS64_LONG2REG_CAST(arg2); \ + _argvec[3] = MIPS64_LONG2REG_CAST(arg3); \ + _argvec[4] = MIPS64_LONG2REG_CAST(arg4); \ + _argvec[5] = MIPS64_LONG2REG_CAST(arg5); \ + _argvec[6] = MIPS64_LONG2REG_CAST(arg6); \ + _argvec[7] = MIPS64_LONG2REG_CAST(arg7); \ + _argvec[8] = MIPS64_LONG2REG_CAST(arg8); \ + _argvec[9] = MIPS64_LONG2REG_CAST(arg9); \ + __asm__ volatile( \ + "dsubu $29, $29, 8\n\t" \ + "ld $4, 72(%1)\n\t" \ + "sd $4, 0($29)\n\t" \ + "ld $4, 8(%1)\n\t" \ + "ld $5, 16(%1)\n\t" \ + "ld $6, 24(%1)\n\t" \ + "ld $7, 32(%1)\n\t" \ + "ld $8, 40(%1)\n\t" \ + "ld $9, 48(%1)\n\t" \ + "ld $10, 56(%1)\n\t" \ + "ld $11, 64(%1)\n\t" \ + "ld $25, 0(%1)\n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "daddu $29, $29, 8\n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) (long)_res; \ + } while (0) + +#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \ + arg7,arg8,arg9,arg10) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long long _argvec[11]; \ + volatile unsigned long long _res; \ + _argvec[0] = MIPS64_LONG2REG_CAST(_orig.nraddr); \ + _argvec[1] = MIPS64_LONG2REG_CAST(arg1); \ + _argvec[2] = MIPS64_LONG2REG_CAST(arg2); \ + _argvec[3] = MIPS64_LONG2REG_CAST(arg3); \ + _argvec[4] = MIPS64_LONG2REG_CAST(arg4); \ + _argvec[5] = MIPS64_LONG2REG_CAST(arg5); \ + _argvec[6] = MIPS64_LONG2REG_CAST(arg6); \ + _argvec[7] = MIPS64_LONG2REG_CAST(arg7); \ + _argvec[8] = MIPS64_LONG2REG_CAST(arg8); \ + _argvec[9] = MIPS64_LONG2REG_CAST(arg9); \ + _argvec[10] = MIPS64_LONG2REG_CAST(arg10); \ + __asm__ volatile( \ + "dsubu $29, $29, 16\n\t" \ + "ld $4, 72(%1)\n\t" \ + "sd $4, 0($29)\n\t" \ + "ld $4, 80(%1)\n\t" \ + "sd $4, 8($29)\n\t" \ + "ld $4, 8(%1)\n\t" \ + "ld $5, 16(%1)\n\t" \ + "ld $6, 24(%1)\n\t" \ + "ld $7, 32(%1)\n\t" \ + "ld $8, 40(%1)\n\t" \ + "ld $9, 48(%1)\n\t" \ + "ld $10, 56(%1)\n\t" \ + "ld $11, 64(%1)\n\t" \ + "ld $25, 0(%1)\n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "daddu $29, $29, 16\n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) (long)_res; \ + } while (0) + +#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ + arg6,arg7,arg8,arg9,arg10, \ + arg11) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long long _argvec[12]; \ + volatile unsigned long long _res; \ + _argvec[0] = MIPS64_LONG2REG_CAST(_orig.nraddr); \ + _argvec[1] = MIPS64_LONG2REG_CAST(arg1); \ + _argvec[2] = MIPS64_LONG2REG_CAST(arg2); \ + _argvec[3] = MIPS64_LONG2REG_CAST(arg3); \ + _argvec[4] = MIPS64_LONG2REG_CAST(arg4); \ + _argvec[5] = MIPS64_LONG2REG_CAST(arg5); \ + _argvec[6] = MIPS64_LONG2REG_CAST(arg6); \ + _argvec[7] = MIPS64_LONG2REG_CAST(arg7); \ + _argvec[8] = MIPS64_LONG2REG_CAST(arg8); \ + _argvec[9] = MIPS64_LONG2REG_CAST(arg9); \ + _argvec[10] = MIPS64_LONG2REG_CAST(arg10); \ + _argvec[11] = MIPS64_LONG2REG_CAST(arg11); \ + __asm__ volatile( \ + "dsubu $29, $29, 24\n\t" \ + "ld $4, 72(%1)\n\t" \ + "sd $4, 0($29)\n\t" \ + "ld $4, 80(%1)\n\t" \ + "sd $4, 8($29)\n\t" \ + "ld $4, 88(%1)\n\t" \ + "sd $4, 16($29)\n\t" \ + "ld $4, 8(%1)\n\t" \ + "ld $5, 16(%1)\n\t" \ + "ld $6, 24(%1)\n\t" \ + "ld $7, 32(%1)\n\t" \ + "ld $8, 40(%1)\n\t" \ + "ld $9, 48(%1)\n\t" \ + "ld $10, 56(%1)\n\t" \ + "ld $11, 64(%1)\n\t" \ + "ld $25, 0(%1)\n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "daddu $29, $29, 24\n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) (long)_res; \ + } while (0) + +#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5, \ + arg6,arg7,arg8,arg9,arg10, \ + arg11,arg12) \ + do { \ + volatile OrigFn _orig = (orig); \ + volatile unsigned long long _argvec[13]; \ + volatile unsigned long long _res; \ + _argvec[0] = MIPS64_LONG2REG_CAST(_orig.nraddr); \ + _argvec[1] = MIPS64_LONG2REG_CAST(arg1); \ + _argvec[2] = MIPS64_LONG2REG_CAST(arg2); \ + _argvec[3] = MIPS64_LONG2REG_CAST(arg3); \ + _argvec[4] = MIPS64_LONG2REG_CAST(arg4); \ + _argvec[5] = MIPS64_LONG2REG_CAST(arg5); \ + _argvec[6] = MIPS64_LONG2REG_CAST(arg6); \ + _argvec[7] = MIPS64_LONG2REG_CAST(arg7); \ + _argvec[8] = MIPS64_LONG2REG_CAST(arg8); \ + _argvec[9] = MIPS64_LONG2REG_CAST(arg9); \ + _argvec[10] = MIPS64_LONG2REG_CAST(arg10); \ + _argvec[11] = MIPS64_LONG2REG_CAST(arg11); \ + _argvec[12] = MIPS64_LONG2REG_CAST(arg12); \ + __asm__ volatile( \ + "dsubu $29, $29, 32\n\t" \ + "ld $4, 72(%1)\n\t" \ + "sd $4, 0($29)\n\t" \ + "ld $4, 80(%1)\n\t" \ + "sd $4, 8($29)\n\t" \ + "ld $4, 88(%1)\n\t" \ + "sd $4, 16($29)\n\t" \ + "ld $4, 96(%1)\n\t" \ + "sd $4, 24($29)\n\t" \ + "ld $4, 8(%1)\n\t" \ + "ld $5, 16(%1)\n\t" \ + "ld $6, 24(%1)\n\t" \ + "ld $7, 32(%1)\n\t" \ + "ld $8, 40(%1)\n\t" \ + "ld $9, 48(%1)\n\t" \ + "ld $10, 56(%1)\n\t" \ + "ld $11, 64(%1)\n\t" \ + "ld $25, 0(%1)\n\t" /* target->t9 */ \ + VALGRIND_CALL_NOREDIR_T9 \ + "daddu $29, $29, 32\n\t" \ + "move %0, $2\n" \ + : /*out*/ "=r" (_res) \ + : /*in*/ "r" (&_argvec[0]) \ + : /*trash*/ "memory", __CALLER_SAVED_REGS \ + ); \ + lval = (__typeof__(lval)) (long)_res; \ + } while (0) + +#endif /* PLAT_mips64_linux */ + +/* ------------------------------------------------------------------ */ +/* ARCHITECTURE INDEPENDENT MACROS for CLIENT REQUESTS. */ +/* */ +/* ------------------------------------------------------------------ */ + +/* Some request codes. There are many more of these, but most are not + exposed to end-user view. These are the public ones, all of the + form 0x1000 + small_number. + + Core ones are in the range 0x00000000--0x0000ffff. The non-public + ones start at 0x2000. +*/ + +/* These macros are used by tools -- they must be public, but don't + embed them into other programs. */ +#define VG_USERREQ_TOOL_BASE(a,b) \ + ((unsigned int)(((a)&0xff) << 24 | ((b)&0xff) << 16)) +#define VG_IS_TOOL_USERREQ(a, b, v) \ + (VG_USERREQ_TOOL_BASE(a,b) == ((v) & 0xffff0000)) + +/* !! ABIWARNING !! ABIWARNING !! ABIWARNING !! ABIWARNING !! + This enum comprises an ABI exported by Valgrind to programs + which use client requests. DO NOT CHANGE THE NUMERIC VALUES OF THESE + ENTRIES, NOR DELETE ANY -- add new ones at the end of the most + relevant group. */ +typedef + enum { VG_USERREQ__RUNNING_ON_VALGRIND = 0x1001, + VG_USERREQ__DISCARD_TRANSLATIONS = 0x1002, + + /* These allow any function to be called from the simulated + CPU but run on the real CPU. Nb: the first arg passed to + the function is always the ThreadId of the running + thread! So CLIENT_CALL0 actually requires a 1 arg + function, etc. */ + VG_USERREQ__CLIENT_CALL0 = 0x1101, + VG_USERREQ__CLIENT_CALL1 = 0x1102, + VG_USERREQ__CLIENT_CALL2 = 0x1103, + VG_USERREQ__CLIENT_CALL3 = 0x1104, + + /* Can be useful in regression testing suites -- eg. can + send Valgrind's output to /dev/null and still count + errors. */ + VG_USERREQ__COUNT_ERRORS = 0x1201, + + /* Allows the client program and/or gdbserver to execute a monitor + command. */ + VG_USERREQ__GDB_MONITOR_COMMAND = 0x1202, + + /* Allows the client program to change a dynamic command line + option. */ + VG_USERREQ__CLO_CHANGE = 0x1203, + + /* These are useful and can be interpreted by any tool that + tracks malloc() et al, by using vg_replace_malloc.c. */ + VG_USERREQ__MALLOCLIKE_BLOCK = 0x1301, + VG_USERREQ__RESIZEINPLACE_BLOCK = 0x130b, + VG_USERREQ__FREELIKE_BLOCK = 0x1302, + /* Memory pool support. */ + VG_USERREQ__CREATE_MEMPOOL = 0x1303, + VG_USERREQ__DESTROY_MEMPOOL = 0x1304, + VG_USERREQ__MEMPOOL_ALLOC = 0x1305, + VG_USERREQ__MEMPOOL_FREE = 0x1306, + VG_USERREQ__MEMPOOL_TRIM = 0x1307, + VG_USERREQ__MOVE_MEMPOOL = 0x1308, + VG_USERREQ__MEMPOOL_CHANGE = 0x1309, + VG_USERREQ__MEMPOOL_EXISTS = 0x130a, + + /* Allow printfs to valgrind log. */ + /* The first two pass the va_list argument by value, which + assumes it is the same size as or smaller than a UWord, + which generally isn't the case. Hence are deprecated. + The second two pass the vargs by reference and so are + immune to this problem. */ + /* both :: char* fmt, va_list vargs (DEPRECATED) */ + VG_USERREQ__PRINTF = 0x1401, + VG_USERREQ__PRINTF_BACKTRACE = 0x1402, + /* both :: char* fmt, va_list* vargs */ + VG_USERREQ__PRINTF_VALIST_BY_REF = 0x1403, + VG_USERREQ__PRINTF_BACKTRACE_VALIST_BY_REF = 0x1404, + + /* Stack support. */ + VG_USERREQ__STACK_REGISTER = 0x1501, + VG_USERREQ__STACK_DEREGISTER = 0x1502, + VG_USERREQ__STACK_CHANGE = 0x1503, + + /* Wine support */ + VG_USERREQ__LOAD_PDB_DEBUGINFO = 0x1601, + + /* Querying of debug info. */ + VG_USERREQ__MAP_IP_TO_SRCLOC = 0x1701, + + /* Disable/enable error reporting level. Takes a single + Word arg which is the delta to this thread's error + disablement indicator. Hence 1 disables or further + disables errors, and -1 moves back towards enablement. + Other values are not allowed. */ + VG_USERREQ__CHANGE_ERR_DISABLEMENT = 0x1801, + + /* Some requests used for Valgrind internal, such as + self-test or self-hosting. */ + /* Initialise IR injection */ + VG_USERREQ__VEX_INIT_FOR_IRI = 0x1901, + /* Used by Inner Valgrind to inform Outer Valgrind where to + find the list of inner guest threads */ + VG_USERREQ__INNER_THREADS = 0x1902 + } Vg_ClientRequest; + +#if !defined(__GNUC__) +# define __extension__ /* */ +#endif + + +/* Returns the number of Valgrinds this code is running under. That + is, 0 if running natively, 1 if running under Valgrind, 2 if + running under Valgrind which is running under another Valgrind, + etc. */ +#define RUNNING_ON_VALGRIND \ + (unsigned)VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* if not */, \ + VG_USERREQ__RUNNING_ON_VALGRIND, \ + 0, 0, 0, 0, 0) \ + + +/* Discard translation of code in the range [_qzz_addr .. _qzz_addr + + _qzz_len - 1]. Useful if you are debugging a JITter or some such, + since it provides a way to make sure valgrind will retranslate the + invalidated area. Returns no value. */ +#define VALGRIND_DISCARD_TRANSLATIONS(_qzz_addr,_qzz_len) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DISCARD_TRANSLATIONS, \ + _qzz_addr, _qzz_len, 0, 0, 0) + +#define VALGRIND_INNER_THREADS(_qzz_addr) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__INNER_THREADS, \ + _qzz_addr, 0, 0, 0, 0) + + +/* These requests are for getting Valgrind itself to print something. + Possibly with a backtrace. This is a really ugly hack. The return value + is the number of characters printed, excluding the "**** " part at the + start and the backtrace (if present). */ + +#if defined(__GNUC__) || defined(__INTEL_COMPILER) && !defined(_MSC_VER) +/* Modern GCC will optimize the static routine out if unused, + and unused attribute will shut down warnings about it. */ +static int VALGRIND_PRINTF(const char *format, ...) + __attribute__((format(__printf__, 1, 2), __unused__)); +#endif +static int +#if defined(_MSC_VER) +__inline +#endif +VALGRIND_PRINTF(const char *format, ...) +{ +#if defined(NVALGRIND) + (void)format; + return 0; +#else /* NVALGRIND */ +#if defined(_MSC_VER) || defined(__MINGW64__) + uintptr_t _qzz_res; +#else + unsigned long _qzz_res; +#endif + va_list vargs; + va_start(vargs, format); +#if defined(_MSC_VER) || defined(__MINGW64__) + _qzz_res = VALGRIND_DO_CLIENT_REQUEST_EXPR(0, + VG_USERREQ__PRINTF_VALIST_BY_REF, + (uintptr_t)format, + (uintptr_t)&vargs, + 0, 0, 0); +#else + _qzz_res = VALGRIND_DO_CLIENT_REQUEST_EXPR(0, + VG_USERREQ__PRINTF_VALIST_BY_REF, + (unsigned long)format, + (unsigned long)&vargs, + 0, 0, 0); +#endif + va_end(vargs); + return (int)_qzz_res; +#endif /* NVALGRIND */ +} + +#if defined(__GNUC__) || defined(__INTEL_COMPILER) && !defined(_MSC_VER) +static int VALGRIND_PRINTF_BACKTRACE(const char *format, ...) + __attribute__((format(__printf__, 1, 2), __unused__)); +#endif +static int +#if defined(_MSC_VER) +__inline +#endif +VALGRIND_PRINTF_BACKTRACE(const char *format, ...) +{ +#if defined(NVALGRIND) + (void)format; + return 0; +#else /* NVALGRIND */ +#if defined(_MSC_VER) || defined(__MINGW64__) + uintptr_t _qzz_res; +#else + unsigned long _qzz_res; +#endif + va_list vargs; + va_start(vargs, format); +#if defined(_MSC_VER) || defined(__MINGW64__) + _qzz_res = VALGRIND_DO_CLIENT_REQUEST_EXPR(0, + VG_USERREQ__PRINTF_BACKTRACE_VALIST_BY_REF, + (uintptr_t)format, + (uintptr_t)&vargs, + 0, 0, 0); +#else + _qzz_res = VALGRIND_DO_CLIENT_REQUEST_EXPR(0, + VG_USERREQ__PRINTF_BACKTRACE_VALIST_BY_REF, + (unsigned long)format, + (unsigned long)&vargs, + 0, 0, 0); +#endif + va_end(vargs); + return (int)_qzz_res; +#endif /* NVALGRIND */ +} + + +/* These requests allow control to move from the simulated CPU to the + real CPU, calling an arbitrary function. + + Note that the current ThreadId is inserted as the first argument. + So this call: + + VALGRIND_NON_SIMD_CALL2(f, arg1, arg2) + + requires f to have this signature: + + Word f(Word tid, Word arg1, Word arg2) + + where "Word" is a word-sized type. + + Note that these client requests are not entirely reliable. For example, + if you call a function with them that subsequently calls printf(), + there's a high chance Valgrind will crash. Generally, your prospects of + these working are made higher if the called function does not refer to + any global variables, and does not refer to any libc or other functions + (printf et al). Any kind of entanglement with libc or dynamic linking is + likely to have a bad outcome, for tricky reasons which we've grappled + with a lot in the past. +*/ +#define VALGRIND_NON_SIMD_CALL0(_qyy_fn) \ + VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ + VG_USERREQ__CLIENT_CALL0, \ + _qyy_fn, \ + 0, 0, 0, 0) + +#define VALGRIND_NON_SIMD_CALL1(_qyy_fn, _qyy_arg1) \ + VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ + VG_USERREQ__CLIENT_CALL1, \ + _qyy_fn, \ + _qyy_arg1, 0, 0, 0) + +#define VALGRIND_NON_SIMD_CALL2(_qyy_fn, _qyy_arg1, _qyy_arg2) \ + VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ + VG_USERREQ__CLIENT_CALL2, \ + _qyy_fn, \ + _qyy_arg1, _qyy_arg2, 0, 0) + +#define VALGRIND_NON_SIMD_CALL3(_qyy_fn, _qyy_arg1, _qyy_arg2, _qyy_arg3) \ + VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* default return */, \ + VG_USERREQ__CLIENT_CALL3, \ + _qyy_fn, \ + _qyy_arg1, _qyy_arg2, \ + _qyy_arg3, 0) + + +/* Counts the number of errors that have been recorded by a tool. Nb: + the tool must record the errors with VG_(maybe_record_error)() or + VG_(unique_error)() for them to be counted. */ +#define VALGRIND_COUNT_ERRORS \ + (unsigned)VALGRIND_DO_CLIENT_REQUEST_EXPR( \ + 0 /* default return */, \ + VG_USERREQ__COUNT_ERRORS, \ + 0, 0, 0, 0, 0) + +/* Several Valgrind tools (Memcheck, Massif, Helgrind, DRD) rely on knowing + when heap blocks are allocated in order to give accurate results. This + happens automatically for the standard allocator functions such as + malloc(), calloc(), realloc(), memalign(), new, new[], free(), delete, + delete[], etc. + + But if your program uses a custom allocator, this doesn't automatically + happen, and Valgrind will not do as well. For example, if you allocate + superblocks with mmap() and then allocates chunks of the superblocks, all + Valgrind's observations will be at the mmap() level and it won't know that + the chunks should be considered separate entities. In Memcheck's case, + that means you probably won't get heap block overrun detection (because + there won't be redzones marked as unaddressable) and you definitely won't + get any leak detection. + + The following client requests allow a custom allocator to be annotated so + that it can be handled accurately by Valgrind. + + VALGRIND_MALLOCLIKE_BLOCK marks a region of memory as having been allocated + by a malloc()-like function. For Memcheck (an illustrative case), this + does two things: + + - It records that the block has been allocated. This means any addresses + within the block mentioned in error messages will be + identified as belonging to the block. It also means that if the block + isn't freed it will be detected by the leak checker. + + - It marks the block as being addressable and undefined (if 'is_zeroed' is + not set), or addressable and defined (if 'is_zeroed' is set). This + controls how accesses to the block by the program are handled. + + 'addr' is the start of the usable block (ie. after any + redzone), 'sizeB' is its size. 'rzB' is the redzone size if the allocator + can apply redzones -- these are blocks of padding at the start and end of + each block. Adding redzones is recommended as it makes it much more likely + Valgrind will spot block overruns. `is_zeroed' indicates if the memory is + zeroed (or filled with another predictable value), as is the case for + calloc(). + + VALGRIND_MALLOCLIKE_BLOCK should be put immediately after the point where a + heap block -- that will be used by the client program -- is allocated. + It's best to put it at the outermost level of the allocator if possible; + for example, if you have a function my_alloc() which calls + internal_alloc(), and the client request is put inside internal_alloc(), + stack traces relating to the heap block will contain entries for both + my_alloc() and internal_alloc(), which is probably not what you want. + + For Memcheck users: if you use VALGRIND_MALLOCLIKE_BLOCK to carve out + custom blocks from within a heap block, B, that has been allocated with + malloc/calloc/new/etc, then block B will be *ignored* during leak-checking + -- the custom blocks will take precedence. + + VALGRIND_FREELIKE_BLOCK is the partner to VALGRIND_MALLOCLIKE_BLOCK. For + Memcheck, it does two things: + + - It records that the block has been deallocated. This assumes that the + block was annotated as having been allocated via + VALGRIND_MALLOCLIKE_BLOCK. Otherwise, an error will be issued. + + - It marks the block as being unaddressable. + + VALGRIND_FREELIKE_BLOCK should be put immediately after the point where a + heap block is deallocated. + + VALGRIND_RESIZEINPLACE_BLOCK informs a tool about reallocation. For + Memcheck, it does four things: + + - It records that the size of a block has been changed. This assumes that + the block was annotated as having been allocated via + VALGRIND_MALLOCLIKE_BLOCK. Otherwise, an error will be issued. + + - If the block shrunk, it marks the freed memory as being unaddressable. + + - If the block grew, it marks the new area as undefined and defines a red + zone past the end of the new block. + + - The V-bits of the overlap between the old and the new block are preserved. + + VALGRIND_RESIZEINPLACE_BLOCK should be put after allocation of the new block + and before deallocation of the old block. + + In many cases, these three client requests will not be enough to get your + allocator working well with Memcheck. More specifically, if your allocator + writes to freed blocks in any way then a VALGRIND_MAKE_MEM_UNDEFINED call + will be necessary to mark the memory as addressable just before the zeroing + occurs, otherwise you'll get a lot of invalid write errors. For example, + you'll need to do this if your allocator recycles freed blocks, but it + zeroes them before handing them back out (via VALGRIND_MALLOCLIKE_BLOCK). + Alternatively, if your allocator reuses freed blocks for allocator-internal + data structures, VALGRIND_MAKE_MEM_UNDEFINED calls will also be necessary. + + Really, what's happening is a blurring of the lines between the client + program and the allocator... after VALGRIND_FREELIKE_BLOCK is called, the + memory should be considered unaddressable to the client program, but the + allocator knows more than the rest of the client program and so may be able + to safely access it. Extra client requests are necessary for Valgrind to + understand the distinction between the allocator and the rest of the + program. + + Ignored if addr == 0. +*/ +#define VALGRIND_MALLOCLIKE_BLOCK(addr, sizeB, rzB, is_zeroed) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__MALLOCLIKE_BLOCK, \ + addr, sizeB, rzB, is_zeroed, 0) + +/* See the comment for VALGRIND_MALLOCLIKE_BLOCK for details. + Ignored if addr == 0. +*/ +#define VALGRIND_RESIZEINPLACE_BLOCK(addr, oldSizeB, newSizeB, rzB) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__RESIZEINPLACE_BLOCK, \ + addr, oldSizeB, newSizeB, rzB, 0) + +/* See the comment for VALGRIND_MALLOCLIKE_BLOCK for details. + Ignored if addr == 0. +*/ +#define VALGRIND_FREELIKE_BLOCK(addr, rzB) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__FREELIKE_BLOCK, \ + addr, rzB, 0, 0, 0) + +/* Create a memory pool. */ +#define VALGRIND_CREATE_MEMPOOL(pool, rzB, is_zeroed) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__CREATE_MEMPOOL, \ + pool, rzB, is_zeroed, 0, 0) + +/* Create a memory pool with some flags specifying extended behaviour. + When flags is zero, the behaviour is identical to VALGRIND_CREATE_MEMPOOL. + + The flag VALGRIND_MEMPOOL_METAPOOL specifies that the pieces of memory + associated with the pool using VALGRIND_MEMPOOL_ALLOC will be used + by the application as superblocks to dole out MALLOC_LIKE blocks using + VALGRIND_MALLOCLIKE_BLOCK. In other words, a meta pool is a "2 levels" + pool : first level is the blocks described by VALGRIND_MEMPOOL_ALLOC. + The second level blocks are described using VALGRIND_MALLOCLIKE_BLOCK. + Note that the association between the pool and the second level blocks + is implicit : second level blocks will be located inside first level + blocks. It is necessary to use the VALGRIND_MEMPOOL_METAPOOL flag + for such 2 levels pools, as otherwise valgrind will detect overlapping + memory blocks, and will abort execution (e.g. during leak search). + + Such a meta pool can also be marked as an 'auto free' pool using the flag + VALGRIND_MEMPOOL_AUTO_FREE, which must be OR-ed together with the + VALGRIND_MEMPOOL_METAPOOL. For an 'auto free' pool, VALGRIND_MEMPOOL_FREE + will automatically free the second level blocks that are contained + inside the first level block freed with VALGRIND_MEMPOOL_FREE. + In other words, calling VALGRIND_MEMPOOL_FREE will cause implicit calls + to VALGRIND_FREELIKE_BLOCK for all the second level blocks included + in the first level block. + Note: it is an error to use the VALGRIND_MEMPOOL_AUTO_FREE flag + without the VALGRIND_MEMPOOL_METAPOOL flag. +*/ +#define VALGRIND_MEMPOOL_AUTO_FREE 1 +#define VALGRIND_MEMPOOL_METAPOOL 2 +#define VALGRIND_CREATE_MEMPOOL_EXT(pool, rzB, is_zeroed, flags) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__CREATE_MEMPOOL, \ + pool, rzB, is_zeroed, flags, 0) + +/* Destroy a memory pool. */ +#define VALGRIND_DESTROY_MEMPOOL(pool) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DESTROY_MEMPOOL, \ + pool, 0, 0, 0, 0) + +/* Associate a piece of memory with a memory pool. */ +#define VALGRIND_MEMPOOL_ALLOC(pool, addr, size) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__MEMPOOL_ALLOC, \ + pool, addr, size, 0, 0) + +/* Disassociate a piece of memory from a memory pool. */ +#define VALGRIND_MEMPOOL_FREE(pool, addr) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__MEMPOOL_FREE, \ + pool, addr, 0, 0, 0) + +/* Disassociate any pieces outside a particular range. */ +#define VALGRIND_MEMPOOL_TRIM(pool, addr, size) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__MEMPOOL_TRIM, \ + pool, addr, size, 0, 0) + +/* Resize and/or move a piece associated with a memory pool. */ +#define VALGRIND_MOVE_MEMPOOL(poolA, poolB) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__MOVE_MEMPOOL, \ + poolA, poolB, 0, 0, 0) + +/* Resize and/or move a piece associated with a memory pool. */ +#define VALGRIND_MEMPOOL_CHANGE(pool, addrA, addrB, size) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__MEMPOOL_CHANGE, \ + pool, addrA, addrB, size, 0) + +/* Return 1 if a mempool exists, else 0. */ +#define VALGRIND_MEMPOOL_EXISTS(pool) \ + (unsigned)VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \ + VG_USERREQ__MEMPOOL_EXISTS, \ + pool, 0, 0, 0, 0) + +/* Mark a piece of memory as being a stack. Returns a stack id. + start is the lowest addressable stack byte, end is the highest + addressable stack byte. */ +#define VALGRIND_STACK_REGISTER(start, end) \ + (unsigned)VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \ + VG_USERREQ__STACK_REGISTER, \ + start, end, 0, 0, 0) + +/* Unmark the piece of memory associated with a stack id as being a + stack. */ +#define VALGRIND_STACK_DEREGISTER(id) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__STACK_DEREGISTER, \ + id, 0, 0, 0, 0) + +/* Change the start and end address of the stack id. + start is the new lowest addressable stack byte, end is the new highest + addressable stack byte. */ +#define VALGRIND_STACK_CHANGE(id, start, end) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__STACK_CHANGE, \ + id, start, end, 0, 0) + +/* Load PDB debug info for Wine PE image_map. */ +#define VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__LOAD_PDB_DEBUGINFO, \ + fd, ptr, total_size, delta, 0) + +/* Map a code address to a source file name and line number. buf64 + must point to a 64-byte buffer in the caller's address space. The + result will be dumped in there and is guaranteed to be zero + terminated. If no info is found, the first byte is set to zero. */ +#define VALGRIND_MAP_IP_TO_SRCLOC(addr, buf64) \ + (unsigned)VALGRIND_DO_CLIENT_REQUEST_EXPR(0, \ + VG_USERREQ__MAP_IP_TO_SRCLOC, \ + addr, buf64, 0, 0, 0) + +/* Disable error reporting for this thread. Behaves in a stack like + way, so you can safely call this multiple times provided that + VALGRIND_ENABLE_ERROR_REPORTING is called the same number of times + to re-enable reporting. The first call of this macro disables + reporting. Subsequent calls have no effect except to increase the + number of VALGRIND_ENABLE_ERROR_REPORTING calls needed to re-enable + reporting. Child threads do not inherit this setting from their + parents -- they are always created with reporting enabled. */ +#define VALGRIND_DISABLE_ERROR_REPORTING \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__CHANGE_ERR_DISABLEMENT, \ + 1, 0, 0, 0, 0) + +/* Re-enable error reporting, as per comments on + VALGRIND_DISABLE_ERROR_REPORTING. */ +#define VALGRIND_ENABLE_ERROR_REPORTING \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__CHANGE_ERR_DISABLEMENT, \ + -1, 0, 0, 0, 0) + +/* Execute a monitor command from the client program. + If a connection is opened with GDB, the output will be sent + according to the output mode set for vgdb. + If no connection is opened, output will go to the log output. + Returns 1 if command not recognised, 0 otherwise. */ +#define VALGRIND_MONITOR_COMMAND(command) \ + VALGRIND_DO_CLIENT_REQUEST_EXPR(0, VG_USERREQ__GDB_MONITOR_COMMAND, \ + command, 0, 0, 0, 0) + + +/* Change the value of a dynamic command line option. + Note that unknown or not dynamically changeable options + will cause a warning message to be output. */ +#define VALGRIND_CLO_CHANGE(option) \ + VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__CLO_CHANGE, \ + option, 0, 0, 0, 0) + + +#undef PLAT_x86_darwin +#undef PLAT_amd64_darwin +#undef PLAT_x86_win32 +#undef PLAT_amd64_win64 +#undef PLAT_x86_linux +#undef PLAT_amd64_linux +#undef PLAT_ppc32_linux +#undef PLAT_ppc64be_linux +#undef PLAT_ppc64le_linux +#undef PLAT_arm_linux +#undef PLAT_s390x_linux +#undef PLAT_mips32_linux +#undef PLAT_mips64_linux +#undef PLAT_nanomips_linux +#undef PLAT_x86_solaris +#undef PLAT_amd64_solaris + +#endif /* __VALGRIND_H */ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/bundled_inputs.py b/.venv/lib/python3.12/site-packages/torch/utils/bundled_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..03a407a1e849c549756583e1500ed5359366c289 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/bundled_inputs.py @@ -0,0 +1,472 @@ +#!/usr/bin/env python3 +# mypy: allow-untyped-defs +from typing import Any, TypeVar, NamedTuple +from collections.abc import Callable, Sequence +import textwrap +import torch +from torch._C import TupleType, ListType +from torch.jit._recursive import wrap_cpp_module + + +T = TypeVar("T") + +MAX_RAW_TENSOR_SIZE = 16 + +class InflatableArg(NamedTuple): + """Helper type for bundled inputs. + + 'value' is the compressed/deflated input that is stored in the model. Value + must be of the same type as the argument to the function that it is a deflated + input for. + + 'fmt' is a formattable code string that is executed to inflate the compressed data into + the appropriate input. It can use 'value' as an input to the format str. It must result + in a value of the same type as 'value'. + + 'fmt_fn' is a formattable function code string that is executed to inflate the compressed + data into the appropriate input. It must result in a value of the same type as 'value'. + The function name should be the formattable part of the string. + + Note: Only top level InflatableArgs can be inflated. i.e. you cannot place + an inflatable arg inside of some other structure. You should instead create + an inflatable arg such that the fmt code string returns the full structure + of your input. + """ + + value: Any + fmt: str = "{}" + fmt_fn: str = "" + + +def bundle_inputs( + model: torch.jit.ScriptModule, + inputs: Sequence[tuple[Any, ...]] | dict[Callable, Sequence[tuple[Any, ...]] | None] | None, + info: list[str] | dict[Callable, list[str]] | None = None, + *, + _receive_inflate_expr: list[str] | None = None, +) -> torch.jit.ScriptModule: + """Create and return a copy of the specified model with inputs attached. + + The original model is not mutated or changed in any way. + + Models with bundled inputs can be invoked in a uniform manner by + benchmarking and code coverage tools. + + If inputs is passed in as a list then the inputs will be bundled for 'forward'. + If inputs is instead passed in as a map then all the methods specified in the map + will have their corresponding inputs bundled. Info should match whatever type is + chosen for the inputs. + + The returned model will support the following methods: + + `get_all_bundled_inputs_for_() -> List[Tuple[Any, ...]]` + Returns a list of tuples suitable for passing to the model like + `for inp in model.get_all_bundled_inputs_for_foo(): model.foo(*inp)` + + `get_bundled_inputs_functions_and_info() -> Dict[str, Dict[str: List[str]]]` + Returns a dictionary mapping function names to a metadata dictionary. + This nested dictionary maps preset strings like: + 'get_inputs_function_name' -> the name of a function attribute in this model that can be + run to get back a list of inputs corresponding to that function. + 'info' -> the user provided extra information about the bundled inputs + + If forward has bundled inputs then these following functions will also be defined on the returned module: + + `get_all_bundled_inputs() -> List[Tuple[Any, ...]]` + Returns a list of tuples suitable for passing to the model like + `for inp in model.get_all_bundled_inputs(): model(*inp)` + + `get_num_bundled_inputs() -> int` + Equivalent to `len(model.get_all_bundled_inputs())`, + but slightly easier to call from C++. + + Inputs can be specified in one of two ways: + + - The model can define `_generate_bundled_inputs_for_`. + If the user chooses this method inputs[] should map to None + + - The `inputs` argument to this function can be a dictionary mapping functions to a + list of inputs, of the same form that will be returned by get_all_bundled_inputs_for_. + Alternatively if only bundling inputs for forward the map can be omitted and a singular list of inputs + can be provided instead. + + The type of the inputs is List[Tuple[Any, ...]]. The outer list corresponds with a + list of inputs, the inner tuple is the list of args that together make up one input. + For inputs of functions that take one arg, this will be a tuple of length one. The Any, ... + is the actual data that makes up the args, e.g. a tensor. + + Info is an optional parameter that maps functions to a list of strings providing extra information about that + function's bundled inputs. Alternatively if only bundling inputs for forward the map can be omitted and + a singular list of information can be provided instead. This could be descriptions, expected outputs, etc. + - Ex: info={model.forward : ['man eating icecream', 'an airplane', 'a dog']} + + This function will attempt to optimize arguments so that (e.g.) + arguments like `torch.zeros(1000)` will be represented compactly. + Only top-level arguments will be optimized. + Tensors in lists or tuples will not. + """ + if not isinstance(model, torch.jit.ScriptModule): + raise Exception("Only ScriptModule is supported.") # noqa: TRY002 + + ignored_methods, ignored_attrs = _get_bundled_inputs_attributes_and_methods(model) + clone = torch._C._hack_do_not_use_clone_module_with_class( # type: ignore[attr-defined] + model._c, + ignored_methods, + ignored_attrs, + ) + + # The above cloning function returns a torch._C.scriptmodule and we need a torch.jit.scriptmodule. + # Fortunately there is a function in _recursive that does exactly that conversion. + cloned_module = wrap_cpp_module(clone) + if isinstance(inputs, dict): + if not isinstance(info, dict) and info is not None: + raise AssertionError("If inputs is a dict, info must be a dict or None") + augment_many_model_functions_with_bundled_inputs(cloned_module, inputs, _receive_inflate_expr, info) + else: + if not isinstance(info, list) and info is not None: + raise AssertionError("If inputs is a list, info must be a list or None") + augment_model_with_bundled_inputs(cloned_module, inputs, _receive_inflate_expr, info) + return cloned_module + +def augment_model_with_bundled_inputs( + model: torch.jit.ScriptModule, + inputs: Sequence[tuple[Any, ...]] | None = None, + _receive_inflate_expr: list[str] | None = None, # For debugging. + info: list[str] | None = None, # Optional argument to provide info about forward or its inputs + skip_size_check=False, +) -> None: + """Add bundled sample inputs to a model for the forward function. + + Models with bundled inputs can be invoked in a uniform manner by + benchmarking and code coverage tools. + + Augmented models will support the following methods: + + `get_all_bundled_inputs() -> List[Tuple[Any, ...]]` + Returns a list of tuples suitable for passing to the model like + `for inp in model.get_all_bundled_inputs(): model(*inp)` + + `get_num_bundled_inputs() -> int` + Equivalent to `len(model.get_all_bundled_inputs())`, + but slightly easier to call from C++. + + `get_bundled_inputs_functions_and_info() -> Dict[str, Dict[str: List[str]]]` + Returns a dictionary mapping function names to a metadata dictionary. + This nested dictionary maps preset strings like: + 'get_inputs_function_name' -> the name of a function attribute in this model that can be + run to get back a list of inputs corresponding to that function. + 'info' -> the user provided extra information about the bundled inputs + + Inputs can be specified in one of two ways: + + - The model can define `_generate_bundled_inputs_for_forward`. + If the user chooses this method inputs should be None + + - `inputs` is a list of inputs of form List[Tuple[Any, ...]]. A list of tuples where the elements + of each tuple are the args that make up one input. + """ + if not isinstance(model, torch.jit.ScriptModule): + raise Exception("Only ScriptModule is supported.") # noqa: TRY002 + + forward: Callable = model.forward + + # Sometimes forward won't have a name attached so just in case + if not hasattr(forward, "__name__"): + forward.__name__ = 'forward' + augment_many_model_functions_with_bundled_inputs( + model, + inputs={forward : inputs}, + _receive_inflate_expr=_receive_inflate_expr, + info={forward : info} if info else None, + skip_size_check=skip_size_check, + ) + + +def augment_many_model_functions_with_bundled_inputs( + model: torch.jit.ScriptModule, + inputs: dict[Callable, Sequence[tuple[Any, ...]] | None], + _receive_inflate_expr: list[str] | None = None, # For debugging. + info: dict[Callable, list[str]] | None = None, # Optional argument to provide info about the function or its inputs + skip_size_check=False, +) -> None: + """Add bundled sample inputs to a model for an arbitrary list of public functions. + + Models with bundled inputs can be invoked in a uniform manner by + benchmarking and code coverage tools. + + Augmented models will support the following methods: + + `get_all_bundled_inputs_for_() -> List[Tuple[Any, ...]]` + Returns a list of tuples suitable for passing to the model like + `for inp in model.get_all_bundled_inputs_for_foo(): model.foo(*inp)` + + `get_bundled_inputs_functions_and_info() -> Dict[str, Dict[str: List[str]]]` + Returns a dictionary mapping function names to a metadata dictionary. + This nested dictionary maps preset strings like: + 'get_inputs_function_name' -> the name of a function attribute in this model that can be + run to get back a list of inputs corresponding to that function. + 'info' -> the user provided extra information about the bundled inputs + + If forward has bundled inputs then these following functions are also defined: + + `get_all_bundled_inputs() -> List[Tuple[Any, ...]]` + Returns a list of tuples suitable for passing to the model like + `for inp in model.get_all_bundled_inputs(): model(*inp)` + + `get_num_bundled_inputs() -> int` + Equivalent to `len(model.get_all_bundled_inputs())`, + but slightly easier to call from C++. + + Inputs can be specified in one of two ways: + + - The model can define `_generate_bundled_inputs_for_`. + If the user chooses this method inputs[] should map to None + + - The `inputs` argument to this function can be a dictionary mapping functions to a + list of inputs, of the same form that will be returned by get_all_bundled_inputs_for_. + The type of the inputs is List[Tuple[Any, ...]]. The outer list corresponds with a + list of inputs, the inner tuple is the list of args that together make up one input. + For inputs of functions that take one arg, this will be a tuple of length one. The Any, ... + is the actual data that makes up the args, e.g. a tensor. + + Info is an optional parameter that maps functions to a list of strings providing extra information about that + function's bundled inputs. This could be descriptions, expected outputs, etc. + - Ex: info={model.forward : ['man eating icecream', 'an airplane', 'a dog']} + + This function will attempt to optimize arguments so that (e.g.) + arguments like `torch.zeros(1000)` will be represented compactly. + Only top-level arguments will be optimized. + Tensors in lists or tuples will not. + """ + if not isinstance(model, torch.jit.ScriptModule): + raise Exception("Only ScriptModule is supported.") # noqa: TRY002 + + if not inputs: + raise Exception("Please provide inputs for at least 1 function") # noqa: TRY002 + + if hasattr(model, "get_all_bundled_inputs") or hasattr(model, "get_bundled_inputs_functions_and_info"): + raise Exception( # noqa: TRY002 + "Models can only be augmented with bundled inputs once. " + "This Model seems to have already been augmented with " + "bundled inputs. Please start afresh with one that " + "doesn't have bundled inputs.", + ) + + get_bundled_inputs_functions_and_info_template = "" + + for function, input_list in inputs.items(): + if hasattr(function, "__name__"): + function_name = function.__name__ + else: + if hasattr(function, "name"): + function_name = function.name # type: ignore[attr-defined] + else: + raise Exception( # noqa: TRY002 + 'At least one of your functions has no attribute name please ensure all have one. m.foo.name = "foo"') + + + if input_list is not None and not isinstance(input_list, Sequence): + raise TypeError(f"Error inputs for function {function_name} is not a Sequence") + + function_arg_types = [arg.type for arg in function.schema.arguments[1:]] # type: ignore[attr-defined] + deflated_inputs_type: ListType = ListType(TupleType(function_arg_types)) + model._c._register_attribute(f"_bundled_inputs_deflated_{function_name}", deflated_inputs_type, []) + + if hasattr(model, "_generate_bundled_inputs_for_" + function_name): + if input_list is not None: + raise Exception( # noqa: TRY002 + f"inputs[{function_name}] is not None, but _generate_bundled_inputs_for_{function_name} is already defined" + ) + # Model author already defined _generate_bundled_inputs_for_. + elif input_list is None or len(input_list) == 0: + raise Exception( # noqa: TRY002 + f"inputs for {function_name} must be specified if " + f"_generate_bundled_inputs_for_{function_name} is not already defined" + ) + else: + # Iterate over the inputs and args in each input. + # Accumulate `deflated_inputs` as (possibly) compressed values + # and `parts` to be joined into the expression that unpacks them. + deflated_inputs = [] + parts = [] + for inp_idx, args in enumerate(input_list): + if not isinstance(args, tuple) and not isinstance(args, list): # type: ignore[arg-type] + raise TypeError( + f"Error bundled input for function {function_name} idx: {inp_idx} is not a Tuple or a List" + ) + deflated_args = [] + parts.append("(") + for arg_idx, arg in enumerate(args): + inflate_helper_fn_name = _get_inflate_helper_fn_name(arg_idx, inp_idx, function_name) + deflated, inflater, helper_definition = _inflate_expr( + arg, + f"deflated[{inp_idx}][{arg_idx}]", + inflate_helper_fn_name, + skip_size_check=skip_size_check, + ) + deflated_args.append(deflated) + parts.append(f" {inflater},") + if helper_definition: + model.define(textwrap.dedent(helper_definition)) + deflated_inputs.append(tuple(deflated_args)) + parts.append("),") + parts.append("") + expr = "\n".join(parts) + + # Back-channel return this expr for debugging. + if _receive_inflate_expr is not None: + _receive_inflate_expr.append(expr) + setattr(model, f"_bundled_inputs_deflated_{function_name}", deflated_inputs) + definition = textwrap.dedent(""" + def _generate_bundled_inputs_for_{name}(self): + deflated = self._bundled_inputs_deflated_{name} + return [ + {expr} + ] + """).format(expr=expr, name=function_name) + model.define(definition) + + # Define get_all_bundled_inputs_for_ that caches the generated inputs. + model.define(textwrap.dedent(""" + def get_all_bundled_inputs_for_{name}(self): + all_inputs = self._generate_bundled_inputs_for_{name}() + assert all_inputs is not None + return all_inputs + """).format(name=function_name)) + + # Add to the high level helper methods + inputs_info = repr(info[function]) if info and function in info else '[]' + get_bundled_inputs_functions_and_info_template += f""" + temp_dict : Dict[str,List[str]] = {{}} + info: List[str] = {inputs_info} + + temp_dict['info'] = info + temp_dict['get_inputs_function_name'] = ['get_all_bundled_inputs_for_{function_name}'] + all_inputs['{function_name}'] = temp_dict + """ + + # To ensure backwards compatibility and a streamlined api for forward these wrappers are provided + if function_name == 'forward': + model.define(textwrap.dedent(""" + def get_all_bundled_inputs(self): + return self.get_all_bundled_inputs_for_forward() + """)) + model.define(textwrap.dedent(""" + def get_num_bundled_inputs(self): + return len(self.get_all_bundled_inputs_for_forward()) + """)) + + # Define some high level helper methods that act on all bundled inputs + model.define(textwrap.dedent(f""" + def get_bundled_inputs_functions_and_info(self): + all_inputs : Dict[str, Dict[str,List[str]]] = {{}} + {get_bundled_inputs_functions_and_info_template} + return all_inputs + """)) + +def _inflate_expr( + arg: T, ref: str, inflate_helper_fn_name: str, skip_size_check: bool = False +) -> tuple[T | torch.Tensor, str, str | None]: + # Allow custom inflation expressions any object. + # For example, calling custom image-decoding ops. + # Or just use "{}" as the format string to ignore size limits. + if isinstance(arg, InflatableArg): + if arg.fmt_fn: + if arg.fmt not in ["{}", ""]: + raise Exception( # noqa: TRY002 + f"Bundled input argument at position '{ref}' has " + f"both arg.fmt_fn => \n{arg.fmt_fn} " + f"\n and arg.fmt => {arg.fmt}. " + "Please choose `arg.fmt` if the deflater is straightforward or " + "`arg.fmt_fn` if you need a function." + ) + + helper_definition = arg.fmt_fn.format(inflate_helper_fn_name) + expr = f"self.{inflate_helper_fn_name}({ref})" + + return arg.value, expr, helper_definition + else: + return arg.value, arg.fmt.format(ref), None + + if isinstance(arg, torch.Tensor): + # Small-storage tensors can just be saved directly. + if arg._typed_storage().size() <= MAX_RAW_TENSOR_SIZE or skip_size_check: + return arg, ref, None + # Small contiguous tensors can be cloned to have small storage. + # TODO: Should we do this even for non-contiguous tensors? + if arg.is_contiguous() and arg.numel() <= MAX_RAW_TENSOR_SIZE: + return arg.clone(), ref, None + # Example inputs commonly come from torch.zeros, torch.ones, or torch.full. + # These can be represented compactly. + for fmt in [torch.contiguous_format, torch.channels_last]: + if arg.is_contiguous(memory_format=fmt) and (arg == arg.flatten()[0]).all().item(): + return (arg.flatten()[0].clone().expand(*arg.size()), + f"{ref}.contiguous(memory_format={fmt})", None) + # Prevent big tensors from being bundled by default. + # TODO: Provide more useful diagnostics. + raise Exception( # noqa: TRY002 + f"Bundled input argument at position '{ref}' is " + f"a tensor with storage size {arg._typed_storage().size()}. " + f"You probably don't want to bundle this as an input. " + ) + else: + return arg, ref, None + +def _get_bundled_inputs_attributes_and_methods(script_module: torch.jit.ScriptModule) -> tuple[list[str], list[str]]: + methods: list[str] = [] + attributes: list[str] = [] + + # Has bundled inputs for forward + if hasattr(script_module, 'get_all_bundled_inputs'): + methods.append('get_all_bundled_inputs') + methods.append('get_num_bundled_inputs') + methods.append('run_on_bundled_input') + + if hasattr(script_module, 'get_bundled_inputs_functions_and_info'): + methods.append('get_bundled_inputs_functions_and_info') + all_info = script_module.get_bundled_inputs_functions_and_info() + for function_name in all_info: + methods.append("get_all_bundled_inputs_for_" + function_name) + methods.append("_generate_bundled_inputs_for_" + function_name) + attributes.append("_bundled_inputs_deflated_" + function_name) + + bundled_inputs_fn = getattr( + script_module, + f"get_all_bundled_inputs_for_{function_name}" + ) + num_bundled_inputs: int = len(bundled_inputs_fn()) + + # Check inflate helper functions for each function, argument and bundled input + func = getattr(script_module, function_name) + for arg_idx in range(len(func.schema.arguments) - 1): + for input_idx in range(num_bundled_inputs): + helper_fn_name = _get_inflate_helper_fn_name( + arg_idx=arg_idx, + input_idx=input_idx, + function_name=function_name + ) + # if the arg has an InflatableArg with fmt_fn, add the helper function name + if hasattr(script_module, helper_fn_name): + methods.append(helper_fn_name) + + return (methods, attributes) + + +def _get_inflate_helper_fn_name( + arg_idx: int, + input_idx: int, + function_name: str, +) -> str: + return f"_inflate_helper_for_{function_name}_input_{input_idx}_arg_{arg_idx}" + + + +def bundle_randn(*size, dtype=None): + """Generate a tensor that will be inflated with torch.randn.""" + stub = torch.zeros(1, dtype=dtype).expand(*size) + return InflatableArg(value=stub, fmt="torch.randn_like({})") + + +def bundle_large_tensor(t): + """Wrap a tensor to allow bundling regardless of size.""" + return InflatableArg(value=t, fmt="{}") diff --git a/.venv/lib/python3.12/site-packages/torch/utils/checkpoint.py b/.venv/lib/python3.12/site-packages/torch/utils/checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..b7254e3cba6ba80ef037084a500d4e56e1bcc29f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/checkpoint.py @@ -0,0 +1,2059 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import contextlib +import functools +import itertools +import platform +import uuid +import warnings +import weakref +from collections import defaultdict +from typing import * # noqa: F403 +from typing_extensions import Self +import enum +from weakref import ReferenceType + +import torch +import torch.fx.traceback as fx_traceback +from torch.utils._pytree import tree_map +from torch.testing._internal.logging_tensor import capture_logs, LoggingTensorMode +from torch.utils._python_dispatch import TorchDispatchMode +from torch._C._autograd import _make_saved_tensor, SavedTensor +from typing import NoReturn, overload, ParamSpec, TypeVar + +__all__ = [ + "checkpoint", + "checkpoint_sequential", + "CheckpointError", + "CheckpointFunction", + "check_backward_validity", + "detach_variable", + "get_device_states", + "set_device_states", + "noop_context_fn", + "set_checkpoint_early_stop", + "DefaultDeviceType", + "set_checkpoint_debug_enabled", + "CheckpointPolicy", + "SelectiveCheckpointContext", + "create_selective_checkpoint_contexts", + "SAC_IGNORED_OPS", + "GraphExecGroup", +] + +_DEFAULT_DETERMINISM_MODE = "default" + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +_checkpoint_debug_enabled: bool | None = None + + +@contextlib.contextmanager +def set_checkpoint_debug_enabled(enabled: bool | None): + """ + Context manager that sets whether checkpoint should print additional debug + information when running. See the ``debug`` flag for + :func:`~torch.utils.checkpoint.checkpoint` for more information. Note that + when set, this context manager overrides the value of ``debug`` passed to + checkpoint. To defer to the local setting, pass ``None`` to this context. + + Args: + enabled (bool): Whether checkpoint should print debug information. + Default is 'None'. + """ + global _checkpoint_debug_enabled + try: + prev = _checkpoint_debug_enabled + _checkpoint_debug_enabled = enabled + yield + finally: + _checkpoint_debug_enabled = prev + + +def detach_variable(inputs: Tuple[Any, ...]) -> Tuple[torch.Tensor, ...]: + if isinstance(inputs, tuple): + out = [] + for inp in inputs: + if not isinstance(inp, torch.Tensor): + out.append(inp) + continue + + x = inp.detach() + x.requires_grad = inp.requires_grad + out.append(x) + return tuple(out) + else: + raise RuntimeError( + f"Only tuple of tensors is supported. Got Unsupported input type: {type(inputs).__name__}" + ) + + +def check_backward_validity(inputs: Iterable[Any]) -> None: + if not any(inp.requires_grad for inp in inputs if isinstance(inp, torch.Tensor)): + warnings.warn( + "None of the inputs have requires_grad=True. Gradients will be None", stacklevel=2 + ) + + +def _get_device_module(device="cuda"): + if device == "meta": + return torch.device("meta") + device_module = getattr(torch, device) + return device_module + + +class DefaultDeviceType: + r""" + A class that manages the default device type for checkpointing. + + If no non-CPU tensors are present, the default device type will + be used. The default value is 'cuda'. The device type is used in + the checkpointing process when determining which device states + to save and restore for recomputation. + """ + + _default_device_type: str | None = None + + @staticmethod + def set_device_type(device: str = "cuda") -> None: + """ + Set the default device type for checkpointing. + + Args: + device (str): The device type to be set as default. Default is 'cuda'. + """ + DefaultDeviceType._default_device_type = device + + @staticmethod + def get_device_type() -> str: + """ + Get the current default device type for checkpointing. + + Returns: + str: The current default device type. + """ + if not DefaultDeviceType._default_device_type: + DefaultDeviceType._default_device_type = acc.type if (acc := torch.accelerator.current_accelerator(True)) else "cpu" + + return DefaultDeviceType._default_device_type + + +def _infer_device_type(*args): + device_types = [] + + def add_device_types(arg): + nonlocal device_types + if isinstance(arg, torch.Tensor) and arg.device.type != "cpu": + device_types.append(arg.device.type) + return arg + tree_map(add_device_types, args) + + device_types_set = set(device_types) + if len(device_types_set) > 1: + warnings.warn( + "Tensor arguments, excluding CPU tensors, are detected on at least two types of devices. " + "Device state will only be saved for devices of a single device type, and the remaining " + "devices will be ignored. Consequently, if any checkpointed functions involve randomness, " + "this may result in incorrect gradients. (Note that if CUDA devices are among the devices " + "detected, it will be prioritized; otherwise, the first device encountered will be selected.)" + f"\nDevice types: {sorted(device_types_set)} first device type: {device_types[0]}", stacklevel=2 + ) + if len(device_types) == 0: + return DefaultDeviceType.get_device_type() + elif "cuda" in device_types_set: + return "cuda" + else: + return device_types[0] + + +# We can't know if the run_fn will internally move some args to different devices, +# which would require logic to preserve rng states for those devices as well. +# We could paranoically stash and restore ALL the rng states for all visible devices, +# but that seems very wasteful for most cases. Compromise: Stash the RNG state for +# the device of all Tensor args. +# +# To consider: maybe get_device_states and set_device_states should reside in torch/random.py? +def get_device_states(*args) -> Tuple[List[int], List[torch.Tensor]]: + # This will not error out if "arg" is a CPU tensor or a non-tensor type because + # the conditionals short-circuit. + fwd_device_ids = [] + + def add_device_ids(arg): + nonlocal fwd_device_ids + if isinstance(arg, torch.Tensor) and arg.device.type not in {"cpu", "meta"}: + fwd_device_ids.append(arg.get_device()) + return arg + tree_map(add_device_ids, args) + + fwd_device_states = [] + device_module = _get_device_module(_infer_device_type(*args)) + for device_id in fwd_device_ids: + with device_module.device(device_id): + fwd_device_states.append(device_module.get_rng_state()) + + return fwd_device_ids, fwd_device_states + + +def set_device_states(devices, states, *, device_type=None) -> None: + """Sets random number generator states for the specified devices. + + Args: + devices: Device ids to set states for. + states: States to set. + device_type: ``device_type`` of the devices to set states for. Default + is the device returned by a call to ``DefaultDeviceType.get_device_type()``, + which is ``cuda`` if not changed by calling ``DefaultDeviceType::set_device_type()``. + """ + if device_type is None: + device_type = DefaultDeviceType.get_device_type() + if device_type == "meta": + return + device_module = _get_device_module(device_type) + for device, state in zip(devices, states, strict=False): + with device_module.device(device): + device_module.set_rng_state(state) + + +def _get_autocast_kwargs(device_type="cuda"): + if torch.amp.is_autocast_available(device_type): + device_autocast_kwargs = { + "enabled": torch.is_autocast_enabled(device_type), + "dtype": torch.get_autocast_dtype(device_type), + "cache_enabled": torch.is_autocast_cache_enabled(), + } + else: + device_autocast_kwargs = None + + cpu_autocast_kwargs = { + "enabled": torch.is_autocast_enabled('cpu'), + "dtype": torch.get_autocast_dtype('cpu'), + "cache_enabled": torch.is_autocast_cache_enabled(), + } + + return device_autocast_kwargs, cpu_autocast_kwargs + + +class CheckpointFunction(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx, run_function, preserve_rng_state, *args): + check_backward_validity(args) + ctx.run_function = run_function + ctx.preserve_rng_state = preserve_rng_state + # Accommodates the (remote) possibility that autocast is enabled for cpu AND gpu. + ctx.device_type = _infer_device_type(*args) + ctx.device_autocast_kwargs, ctx.cpu_autocast_kwargs = _get_autocast_kwargs( + ctx.device_type + ) + if preserve_rng_state: + ctx.fwd_cpu_state = torch.get_rng_state() + # Don't eagerly initialize the cuda context by accident. + # (If the user intends that the context is initialized later, within their + # run_function, we SHOULD actually stash the cuda state here. Unfortunately, + # we have no way to anticipate this will happen before we run the function.) + ctx.had_device_in_fwd = False + device_module = _get_device_module(ctx.device_type) + if getattr(device_module, "_initialized", False): + ctx.had_device_in_fwd = True + ctx.fwd_devices, ctx.fwd_device_states = get_device_states(*args) + + # Save non-tensor inputs in ctx, keep a placeholder None for tensors + # to be filled out during the backward. + ctx.inputs = [] + ctx.tensor_indices = [] + tensor_inputs = [] + for i, arg in enumerate(args): + if torch.is_tensor(arg): + tensor_inputs.append(arg) + ctx.tensor_indices.append(i) + ctx.inputs.append(None) + else: + ctx.inputs.append(arg) + + ctx.save_for_backward(*tensor_inputs) + + with torch.no_grad(): + outputs = run_function(*args) + return outputs + + @staticmethod + def backward(ctx, *args): + if not torch.autograd._is_checkpoint_valid(): + raise RuntimeError( + "When use_reentrant=True, torch.utils.checkpoint is incompatible" + " with .grad() or passing an `inputs` parameter to .backward()." + " To resolve this error, you can either set use_reentrant=False," + " or call .backward() without passing the `inputs` argument." + ) + # Copy the list to avoid modifying original list. + inputs = list(ctx.inputs) + tensor_indices = ctx.tensor_indices + tensors = ctx.saved_tensors + + # Fill in inputs with appropriate saved tensors. + for i, idx in enumerate(tensor_indices): + inputs[idx] = tensors[i] + + # Stash the surrounding rng state, and mimic the state that was + # present at this time during forward. Restore the surrounding state + # when we're done. + rng_devices = [] + if ctx.preserve_rng_state and ctx.had_device_in_fwd: + rng_devices = ctx.fwd_devices + with torch.random.fork_rng( + devices=rng_devices, enabled=ctx.preserve_rng_state, device_type=ctx.device_type + ): + if ctx.preserve_rng_state: + torch.set_rng_state(ctx.fwd_cpu_state) + if ctx.had_device_in_fwd: + set_device_states(ctx.fwd_devices, ctx.fwd_device_states, device_type=ctx.device_type) + detached_inputs = detach_variable(tuple(inputs)) + + device_autocast_ctx = torch.amp.autocast( + device_type=ctx.device_type, **ctx.device_autocast_kwargs + ) if torch.amp.is_autocast_available(ctx.device_type) else contextlib.nullcontext() + with torch.enable_grad(), device_autocast_ctx, torch.amp.autocast("cpu", **ctx.cpu_autocast_kwargs): # type: ignore[attr-defined] + outputs = ctx.run_function(*detached_inputs) + + if isinstance(outputs, torch.Tensor): + outputs = (outputs,) + + # run backward() with only tensor that requires grad + outputs_with_grad = [] + args_with_grad = [] + for i in range(len(outputs)): + if torch.is_tensor(outputs[i]) and outputs[i].requires_grad: + outputs_with_grad.append(outputs[i]) + args_with_grad.append(args[i]) + if len(outputs_with_grad) == 0: + raise RuntimeError( + "none of output has requires_grad=True," + " this checkpoint() is not necessary" + ) + torch.autograd.backward(outputs_with_grad, args_with_grad) + grads = tuple( + inp.grad if isinstance(inp, torch.Tensor) else None + for inp in detached_inputs + ) + + return (None, None) + grads + + +def noop_context_fn(): + return contextlib.nullcontext(), contextlib.nullcontext() + + +class _CheckpointedFunction: + def __init__(self, function, **checkpoint_kwargs): + self.function = function + self.checkpoint_kwargs = dict(checkpoint_kwargs) + functools.update_wrapper(self, function, updated=()) + + def __call__(self, *args, **kwargs): + return _checkpoint_impl( + self.function, + args, + kwargs, + **self.checkpoint_kwargs, + ) + + def __get__(self, instance, owner=None): + # Supports using the curried form as a method decorator. When accessed + # off an instance, bind the wrapped function to that instance via its + # own descriptor protocol and re-wrap, so the checkpoint config carries + # over to the bound method. + if instance is None: + return self + descriptor_get = getattr(self.function, "__get__", None) + if descriptor_get is None: + return self + return type(self)( + descriptor_get(instance, owner), + **self.checkpoint_kwargs, + ) + + +def _make_checkpoint_wrapper(function, **checkpoint_kwargs): + return _CheckpointedFunction(function, **checkpoint_kwargs) + + +@overload +def checkpoint( + function: Callable[..., _T], + *args: Any, + use_reentrant: bool | None = None, + preserve_rng_state: bool = True, + context_fn: Callable[[], Tuple[ContextManager, ContextManager]] = noop_context_fn, + determinism_check: str = _DEFAULT_DETERMINISM_MODE, + debug: bool = False, + early_stop: bool = True, + respect_saved_tensors_hooks: bool | None = None, + **kwargs: Any, +) -> _T: ... + + +@overload +def checkpoint( + function: None = None, + *, + use_reentrant: bool | None = None, + preserve_rng_state: bool = True, + context_fn: Callable[[], Tuple[ContextManager, ContextManager]] = noop_context_fn, + determinism_check: str = _DEFAULT_DETERMINISM_MODE, + debug: bool = False, + early_stop: bool = True, + respect_saved_tensors_hooks: bool | None = None, +) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: ... + + +# Note: [torch.compile and checkpoint] +# TorchDynamo does not step inside utils.checkpoint function. The flow +# looks likes this +# 1) TorchDynamo tries to wrap utils.checkpoint in a HigherOrderOp by +# speculatively checking if the forward function is safe to trace. +# 2) If yes, then Dynamo-generated Fx graph has the wrapped higher +# order op. As a result, TorchDynamo does not look inside utils.checkpoint. +# 3) If not, then TorchDynamo falls back to eager by performing a graph +# break. And here, the following disable wrapper ensures that +# TorchDynamo does not trigger again on the frames created by +# utils.checkpoint innards. +@torch._disable_dynamo +def checkpoint( + function=None, + *args, + use_reentrant: bool | None = None, + preserve_rng_state: bool = True, + context_fn: Callable[[], Tuple[ContextManager, ContextManager]] = noop_context_fn, + determinism_check: str = _DEFAULT_DETERMINISM_MODE, + debug: bool = False, + early_stop: bool = True, + respect_saved_tensors_hooks: bool | None = None, + **kwargs +): + r"""Checkpoint a model or part of the model. + + Activation checkpointing is a technique that trades compute for memory. + By default, tensors computed during the forward pass are kept alive until + they are used in gradient computations in the backward pass. To reduce this + memory usage, tensors produced in the passed :attr:`function` are not kept + alive until the backward pass. Instead, any passed tensors in :attr:`args` + are kept alive, and the unsaved tensors are recomputed by re-invoking + :attr:`function` in the backward pass as needed for gradient computation. + Activation checkpointing can be applied to any part of a model -- this is + sometimes described as "checkpointing" that part of the model. + + There are currently two checkpointing implementations available, determined + by the :attr:`use_reentrant` parameter. It is recommended that you use + ``use_reentrant=False``. Please refer the note below for a discussion of + their differences. + + .. warning:: + + If the :attr:`function` invocation during the backward pass differs + from the forward pass, e.g., due to a global variable, the checkpointed + version may not be equivalent, potentially causing an + error being raised or leading to silently incorrect gradients. + + .. warning:: + + The ``use_reentrant`` parameter should be passed explicitly. In version + 2.9 we will raise an exception if ``use_reentrant`` is not passed. + If you are using the ``use_reentrant=True`` variant, please refer to the + note below for important considerations and potential limitations. + + .. note:: + + The reentrant variant of checkpoint (``use_reentrant=True``) and + the non-reentrant variant of checkpoint (``use_reentrant=False``) + differ in the following ways: + + * Non-reentrant checkpoint stops recomputation as soon as all needed + intermediate activations have been recomputed. This feature is enabled + by default, but can be disabled with :func:`set_checkpoint_early_stop`. + Reentrant checkpoint always recomputes :attr:`function` in its + entirety during the backward pass. + + * The reentrant variant does not record the autograd graph during the + forward pass, as it runs with the forward pass under + :func:`torch.no_grad`. The non-reentrant version does record the + autograd graph, allowing one to perform backward on the graph within + checkpointed regions. + + * The reentrant checkpoint only supports the + :func:`torch.autograd.backward` API for the backward pass without its + `inputs` argument, while the non-reentrant version supports all ways + of performing the backward pass. + + * At least one input and output must have ``requires_grad=True`` for the + reentrant variant. If this condition is unmet, the checkpointed part + of the model will not have gradients. The non-reentrant version does + not have this requirement. + + * The reentrant version does not consider tensors in nested structures + (e.g., custom objects, lists, dicts, etc) as participating in + autograd, while the non-reentrant version does. + + * The reentrant checkpoint does not support checkpointed regions with + detached tensors from the computational graph, whereas the + non-reentrant version does. For the reentrant variant, if the + checkpointed segment contains tensors detached using ``detach()`` or + with :func:`torch.no_grad`, the backward pass will raise an error. + This is because ``checkpoint`` makes all the outputs require gradients + and this causes issues when a tensor is defined to have no gradient in + the model. To avoid this, detach the tensors outside of the + ``checkpoint`` function. + + Args: + function: describes what to run in the forward pass of the model or + part of the model. It should also know how to handle the inputs + passed as the tuple. For example, in LSTM, if user passes + ``(activation, hidden)``, :attr:`function` should correctly use the + first input as ``activation`` and the second input as ``hidden``. + If omitted, ``checkpoint`` returns a decorator that can be used to + wrap a function before passing user arguments. + args: tuple containing inputs to the :attr:`function` + + Keyword args: + preserve_rng_state(bool, optional): Omit stashing and restoring + the RNG state during each checkpoint. Note that under torch.compile, + this flag doesn't take effect and we always preserve RNG state. + Default: ``True`` + use_reentrant(bool): + specify whether to use the activation checkpoint variant that + requires reentrant autograd. This parameter should be passed + explicitly. In version 2.9 we will raise an exception if + ``use_reentrant`` is not passed. If ``use_reentrant=False``, + ``checkpoint`` will use an implementation that does not require + reentrant autograd. This allows ``checkpoint`` to support additional + functionality, such as working as expected with + ``torch.autograd.grad`` and support for keyword arguments input into + the checkpointed function. + context_fn(Callable, optional): A callable returning a tuple of two + context managers. The function and its recomputation will be run + under the first and second context managers respectively. + This argument is only supported if ``use_reentrant=False``. + determinism_check(str, optional): A string specifying the determinism + check to perform. By default it is set to ``"default"`` which + compares the shapes, dtypes, and devices of the recomputed tensors + against those the saved tensors. To turn off this check, specify + ``"none"``. Currently these are the only two supported values. + Please open an issue if you would like to see more determinism + checks. This argument is only supported if ``use_reentrant=False``, + if ``use_reentrant=True``, the determinism check is always disabled. + debug(bool, optional): If ``True``, error messages will also include + a trace of the operators ran during the original forward computation + as well as the recomputation. This argument is only supported if + ``use_reentrant=False``. + early_stop(bool, optional): If ``True``, non-reentrant checkpoint stops + recomputation as soon as it has computed all needed Tensors. This + argument is ignored if ``use_reentrant=True``. Can be overridden + globally using :func:`set_checkpoint_early_stop` context manager. + Default: ``True``. + respect_saved_tensors_hooks(bool, optional): Whether tensors that + selective activation checkpointing (SAC) saves are routed through + the surrounding user + :func:`torch.autograd.graph.saved_tensors_hooks` (e.g. + :func:`torch.autograd.graph.save_on_cpu`). Such tensors are held + outside the autograd graph, so historically these hooks did not see + them; a future release will make checkpoint honor the hooks by + default. Until then the default (``None``) keeps the legacy behavior + and emits a ``FutureWarning`` when a user hook is in scope; pass + ``True`` to opt in or ``False`` to keep the legacy behavior without + the warning. Has no effect without SAC (plain checkpoint recomputes + rather than saves) or when ``use_reentrant=True``. This argument is + only supported if ``use_reentrant=False``. + + Returns: + Output of running :attr:`function` on :attr:`*args`, or a decorator + when :attr:`function` is omitted. + + Example: + >>> # xdoctest: +SKIP("stub") + >>> # Direct call: checkpoint the function immediately. + >>> out = torch.utils.checkpoint.checkpoint( + ... fn, *args, use_reentrant=False, **kwargs + ... ) + >>> # Decorator/curried form: configure once, then call. + >>> checkpointed_fn = torch.utils.checkpoint.checkpoint( + ... use_reentrant=False, + ... preserve_rng_state=False, + ... )(fn) + >>> out = checkpointed_fn(*args, **kwargs) + >>> # The same decorator can be applied directly to a function or method. + >>> @torch.utils.checkpoint.checkpoint(use_reentrant=False) + ... def fn(*args, **kwargs): + ... ... + >>> out = fn(*args, **kwargs) + """ + if function is None and not args: + if kwargs: + raise ValueError( + "Unexpected keyword arguments: " + ",".join(arg for arg in kwargs) + ) + return functools.partial( + _make_checkpoint_wrapper, + use_reentrant=use_reentrant, + preserve_rng_state=preserve_rng_state, + context_fn=context_fn, + determinism_check=determinism_check, + debug=debug, + early_stop=early_stop, + respect_saved_tensors_hooks=respect_saved_tensors_hooks, + ) + + return _checkpoint_impl( + function, + args, + kwargs, + use_reentrant=use_reentrant, + preserve_rng_state=preserve_rng_state, + context_fn=context_fn, + determinism_check=determinism_check, + debug=debug, + early_stop=early_stop, + respect_saved_tensors_hooks=respect_saved_tensors_hooks, + ) + + +def _checkpoint_impl( + function, + args, + kwargs, + *, + use_reentrant: bool | None = None, + preserve_rng_state: bool = True, + context_fn: Callable[[], Tuple[ContextManager, ContextManager]] = noop_context_fn, + determinism_check: str = _DEFAULT_DETERMINISM_MODE, + debug: bool = False, + early_stop: bool = True, + respect_saved_tensors_hooks: bool | None = None, +): + preserve = preserve_rng_state + + if use_reentrant is None: + warnings.warn( + "torch.utils.checkpoint: the use_reentrant parameter should be " + "passed explicitly. Starting in PyTorch 2.9, calling checkpoint " + "without use_reentrant will raise an exception. use_reentrant=False is " + "recommended, but if you need to preserve the current default " + "behavior, you can pass use_reentrant=True. Refer to docs for more " + "details on the differences between the two variants.", + stacklevel=3, + ) + use_reentrant = True + + if kwargs and use_reentrant: + raise ValueError( + "Unexpected keyword arguments: " + ",".join(arg for arg in kwargs) + ) + + if use_reentrant: + if ( + context_fn is not noop_context_fn + or debug is not False + or respect_saved_tensors_hooks is not None + ): + raise ValueError( + "Passing `context_fn`, `debug`, or `respect_saved_tensors_hooks` " + "is only supported when use_reentrant=False." + ) + return CheckpointFunction.apply(function, preserve, *args) + else: + gen = _checkpoint_without_reentrant_generator_impl( + function, + args, + kwargs, + preserve_rng_state=preserve, + context_fn=context_fn, + determinism_check=determinism_check, + debug=debug, + early_stop=early_stop, + respect_saved_tensors_hooks=respect_saved_tensors_hooks, + ) + # Runs pre-forward logic + next(gen) + try: + ret = function(*args, **kwargs) + except BaseException as e: + try: + gen.throw(e) + except StopIteration as stop: + raise RuntimeError( + "torch.utils.checkpoint: the forward context provided by " + "context_fn suppressed an exception raised during the " + "checkpointed forward. This is not supported because " + "checkpoint cannot return a value for a failed forward." + ) from stop + raise + # Runs post-forward logic + try: + next(gen) + except StopIteration: + return ret + raise AssertionError( + "torch.utils.checkpoint: expected context_fn generator to yield " + "exactly twice, but it yielded more than twice." + ) + + +def checkpoint_sequential(functions, segments, input, use_reentrant=None, **kwargs): + r"""Checkpoint a sequential model to save memory. + + Sequential models execute a list of modules/functions in order + (sequentially). Therefore, we can divide such a model in various segments + and checkpoint each segment. All segments except the last will not store + the intermediate activations. The inputs of each checkpointed segment will + be saved for re-running the segment in the backward pass. + + .. warning:: + The ``use_reentrant`` parameter should be passed explicitly. In version + 2.9 we will raise an exception if ``use_reentrant`` is not passed. + If you are using the ``use_reentrant=True` variant, please see + :func:`~torch.utils.checkpoint.checkpoint` for + the important considerations and limitations of this variant. It is + recommended that you use ``use_reentrant=False``. + + .. warning: + Since PyTorch 1.4, it allows only one Tensor as the input and + intermediate outputs, just like :class:`torch.nn.Sequential`. + + Args: + functions: A :class:`torch.nn.Sequential` or the list of modules or + functions (comprising the model) to run sequentially. + segments: Number of chunks to create in the model + input: A Tensor that is input to :attr:`functions` + preserve_rng_state(bool, optional): Omit stashing and restoring + the RNG state during each checkpoint. + Default: ``True`` + use_reentrant(bool): + specify whether to use the activation checkpoint variant that + requires reentrant autograd. This parameter should be passed + explicitly. In version 2.5 we will raise an exception if + ``use_reentrant`` is not passed. If ``use_reentrant=False``, + ``checkpoint`` will use an implementation that does not require + reentrant autograd. This allows ``checkpoint`` to support additional + functionality, such as working as expected with + ``torch.autograd.grad`` and support for keyword arguments input into + the checkpointed function. + + Returns: + Output of running :attr:`functions` sequentially on :attr:`*inputs` + + Example: + >>> # xdoctest: +SKIP("stub") + >>> model = nn.Sequential(...) + >>> input_var = checkpoint_sequential(model, chunks, input_var) + """ + if use_reentrant is None: + warnings.warn( + "torch.utils.checkpoint.checkpoint_sequential: the use_reentrant " + "parameter should be passed explicitly. " + "In version 2.9 we will raise an exception if use_reentrant " + "is not passed. use_reentrant=False is " + "recommended, but if you need to preserve the current default " + "behavior, you can pass use_reentrant=True. Refer to docs for more " + "details on the differences between the two variants.", stacklevel=2 + ) + use_reentrant = True + + # Hack for keyword-only parameter in a python 2.7-compliant way + preserve = kwargs.pop("preserve_rng_state", True) + if kwargs: + raise ValueError( + "Unexpected keyword arguments: " + ",".join(arg for arg in kwargs) + ) + + def run_function(start, end, functions): + def forward(input): + for j in range(start, end + 1): + input = functions[j](input) + return input + + return forward + + if isinstance(functions, torch.nn.Sequential): + functions = list(functions.children()) + + segment_size = len(functions) // segments + # the last chunk has to be non-volatile + end = -1 + for start in range(0, segment_size * (segments - 1), segment_size): + end = start + segment_size - 1 + input = checkpoint( + run_function(start, end, functions), + input, + use_reentrant=use_reentrant, + preserve_rng_state=preserve, + ) + return run_function(end + 1, len(functions) - 1, functions)(input) + + +def _internal_assert(cond) -> None: + if not cond: + raise AssertionError( + "Something went unexpectedly wrong in activation checkpoint. " + "Please report this bug by filing an issue to PyTorch." + ) + + +# NOTE [ Nestable Checkpoint ] +# +# The semantics of nested checkpoint can be defined by two basic rules. +# Following the two rules leads to an important implication that is central +# to motivating the design. +# +# Rule 1. Saved tensors are managed by inner-most checkpoint only and hidden +# from any outer layers of checkpoint. +# +# Rule 2. The inputs of inner checkpoints are treated as tensors saved to its +# parent checkpoint. +# +# Implication: To recompute any given saved tensor, we need to recompute all of +# the checkpoints wrapping it. +# +# Why is this implied? To unpack a saved tensor X during backward we need to +# recompute the inner-most checkpoint (#1), and in order to recompute that +# checkpoint I need to have its inputs, which are managed by that checkpoint's +# parent (#2), which thus also needs to be recomputed first. Continue this line +# of reasoning and we realize that in order to unpack X, all checkpoints that +# were active at the time X was saved need to be recomputed. (unless we have +# already done so in that backward for some other saved tensor). +# +# In practice, we use a noop autograd Function to save inputs as saved tensors. +# During unpack calling ctx.saved_tensor triggers the parent checkpoint to +# recompute. +# +# Rule 3. We should start recomputation as if there are no checkpoints currently +# active. Checkpoints encountered during recomputation are still +# respected. +# +# When we start recomputation, we push the saved variable hook meant for +# recomputation on the stack. See examples in Rule 6 for more context. +# +# * * * * +# +# Beyond the basic semantics specific to nested checkpoint, we impose several +# more constraints that may apply to checkpointing in general. +# +# Rule 4. Lifetime of recomputed tensors +# +# Recomputed tensors are considered specific to particular invocations +# of backward and are always cleared immediately as they are unpacked +# Particularly, we require this to happen even if retain_graph=True. +# +# [ Implementation details of Rule 4 ] +# +# If we were okay with recomputed tensors staying alive after backward is run +# with retain_graph=True, we would store recomputed variables as the values of a +# WeakKeyDictionary and pack strong references to the keys, so that as we +# backward, those packed keys would be cleared as long as retain_graph=False. +# Clearing the packed key clears the corresponding entry in the WKD. +# +# If we wish recomputed variables to be immediately cleared as we unpack them in +# the retain_graph=True case, we cannot rely on the packed keys to be cleared by +# backward automatically. Instead of packing the strong reference to the key +# directly, we pack a container object, which we manually clear as we unpack. +# +# An important detail is that if a second backward happens, the second +# recomputation needs to reset the container with a newly created key. +# +# Rule 5. Stop recomputation as soon as we've recomputed the saved tensors we +# know we need. +# +# [ Implementation details of Rule 5 ] +# +# During recomputation, raise an exception if the number of recomputed tensors +# matches the number of tensors that we expected to recompute. We wrap the +# recomputation call with a try-catch to catch this specific exception. See +# Rule #6 below for some examples. +# +# Rule 6. We support doing backward inside checkpoint context +# +# [ retain_graph is True] +# +# def fn(x): +# y = x.sin() +# z = y.cos() +# gx, = torch.autograd.grad(z, x, retains_grad=True) +# return gx, z +# +# out = checkpoint(fn)(inp) +# out.backward() +# +# Because z is saved by cos while checkpoint is enabled, it would not be +# actually saved, and so the .grad() call inside must trigger a recomputation. +# +# During recomputation the "inner pack hook" has two responsibilities: +# +# 1) As usual, populating the WeakKeyDictionary storing recomputed tensors +# 2) Pack the actual tensor (detached) so that one may perform backward on the +# recomputed graph. The tensors saved to this graph will live until the end +# of recomputation, or die earlier if someone performs backward with +# retain_graph=False. +# +# More generally performing backward on the recomputed graph occurs in the +# following cases: +# - If backward is performed inside forward, +# - During the original forward IF early-stop is disabled +# - During the original backward +# - If there are multiple .grad()/.backward() calls, we would perform backward +# on the recomputed graph even if early-stop is enabled (see the example below) +# +# [ retain_graph is False ] +# +# The example below shows what happens if during recomputation we find that some +# of the tensors we are trying to recompute have already been cleared. +# +# Spoiler: we don't do anything special, we just skip over them! +# +# def fn(x): +# y = x.sin() # (1) +# z = y.cos() # (2) +# gx, = torch.autograd.grad(z, x) # (3) +# return x.cos() * gx # (4) +# +# out = checkpoint(fn)(inp) +# out.backward() # (5) +# +# 1, 2. Don't save x and y since we are inside a checkpoint. +# 3. Trigger a recompute of fn since x and y weren't saved. +# And depending on whether early stop is enabled, either stop at (2) or +# continue running the function. +# Because we are running backward with retain_graph=False, we clear x and y's +# holders. +# 4. Don't save x since we are inside a checkpoint. +# 5. Calling backward triggers another recompute of fn. During recompute, we see +# that x and y have already been cleared in the original graph as indicated +# by holder=None. We skip over them. We still save x at (4) (since its holder +# is still alive.) + +_enable_checkpoint_early_stop: bool | None = None + + +@contextlib.contextmanager +def set_checkpoint_early_stop(enable: bool): + """Controls whether checkpoint should stop recomputation early. + + By default, non-reentrant checkpoint stops recomputation as soon as it + has computed all needed Tensors. This context manager can be used to disable + that feature if it is problematic for your specific application. + + This context manager only needs to be active when forward is run. It does + not need to be active during backward. + + Example:: + + >>> # xdoctest: +SKIP(failing) + >>> message = "saved tensors default hooks are disabled" + >>> with set_checkpoint_early_stop(False): + ... # Any checkpoint under this context manager will respect this + ... # context manager, even if its backward is performed outside. + ... out = checkpoint(fn, inputs) + ... + >>> out.backward() + """ + global _enable_checkpoint_early_stop + try: + prev = _enable_checkpoint_early_stop + _enable_checkpoint_early_stop = enable + yield + finally: + _enable_checkpoint_early_stop = prev + + +class _Handle: + pass + + +class _Holder: + def __init__(self) -> None: + self.handles: dict[int, _Handle | None] = {} + + +class _CheckpointFrame: + def __init__(self, recompute_fn, early_stop, unpack_error_cb, metadata_fn) -> None: + self.recompute_fn = recompute_fn + self.saved_args: List[Any] = [] + self.weak_holders: List[ReferenceType] = [] + # We store this as a weakkeydictionary so that in the case of a partial + # backward, the entries in the dict are cleared alongside the Holder + # which will be removed when the SavedVariable is cleared. + self.recomputed: DefaultDict[ + int, weakref.WeakKeyDictionary[_Handle, torch.Tensor] + ] = defaultdict(weakref.WeakKeyDictionary) + # We need both recomp_counter and recomputed since they can diverge + # https://github.com/pytorch/pytorch/pull/90105#discussion_r1135889885 + self.recomp_counter: DefaultDict[int, int] = defaultdict(int) + self.is_recomputed: DefaultDict[int, bool] = defaultdict(bool) + + # See Rule 5 + self.early_stop = early_stop + + # Debugging + self.metadata_fn = metadata_fn + self.unpack_error_cb = unpack_error_cb + self.x_metadatas = [] + self.forward_completed = False + self.ignore_saved_mismatch = False + + def save_inputs(self, *args): + self.saved_args = [ + _make_saved_tensor(arg, is_output=False) + if isinstance(arg, torch.Tensor) else arg + for arg in args + ] + + def get_inputs(self): + return [ + arg.unpack() if isinstance(arg, SavedTensor) else arg + for arg in self.saved_args + ] + + def check_recomputed_tensors_match(self, gid) -> None: + if self.ignore_saved_mismatch: + # TODO: we can probably make this check stricter by checking that + # the metadata of the first tensors still match. + return + # NOTE [ Error handling for checkpoint ] + # + # At a high level, we need to check that the tensors saved + # during original forward matches tensors saved during recompute + # This means handling 3 cases: + # + # 1. During recompute, more tensors were saved. + # + # Usually this is hidden due to the StopRecomputationError + # but if early stop is not enabled, or we would have errored + # anyway because there aren't enough weak_holders. But we + # do want to have a nice error. See the _recomputation_hook + # for details. + if not len(self.weak_holders) == self.recomp_counter[gid]: + # 2. During recompute, fewer tensors were saved + # + # We know that every time we save something during original forward + # we append to weak_holder, and every time we save a tensor + # during recompute we increment recompute_counter. + raise CheckpointError( + "torch.utils.checkpoint: A different number of tensors was saved " + "during the original forward and recomputation.\n" + f"Number of tensors saved during forward: {len(self.weak_holders)}\n" + f"Number of tensors saved during recomputation: {self.recomp_counter[gid]}.\n" + f"{_debug_tip_msg}" + ) + + # 3. During recompute, the same tensors were saved, but they + # have different metadata + nb_meta_different = [] + for idx, weak_holder in enumerate(self.weak_holders): + holder = weak_holder() + if holder is None: + continue + # We've seen all holders since we iterate over them in order + # For every holder that is still alive now, it must've been + # alive when we saw it during recompute, therefore, the + # gid must be set. + _internal_assert(gid in holder.handles) + # We know this is the first unpack, so it couldn't have been set + # to None yet. + _internal_assert(holder.handles[gid] is not None) + # We always set these together in the recomputation hook + _internal_assert(holder.handles[gid] in self.recomputed[gid]) + # see pack hook, x_metadata is 1:1 with weak_holders. + x_meta = self.x_metadatas[idx] + recomputed_x = self.recomputed[gid][holder.handles[gid]] + if x_meta != self.metadata_fn(recomputed_x): + nb_meta_different.append((idx, x_meta, self.metadata_fn(recomputed_x))) + + if len(nb_meta_different) > 0: + mismatched_tensors = "" + for idx, x_meta, recomputed_meta in nb_meta_different: + mismatched_tensors += ( + f"tensor at position {idx}:\n" + f"saved metadata: {x_meta}\n" + f"recomputed metadata: {recomputed_meta}\n" + ) + raise CheckpointError( + "torch.utils.checkpoint: Recomputed values for the following tensors " + "have different metadata than during the forward pass.\n" + f"{mismatched_tensors}.\n" + f"{_debug_tip_msg}" + ) + + +_debug_tip_msg = """ +Tip: To see a more detailed error message, either pass `debug=True` to +`torch.utils.checkpoint.checkpoint(...)` or wrap the code block +with `with torch.utils.checkpoint.set_checkpoint_debug_enabled(True):` to +enable checkpoint‑debug mode globally. + +If this error occurs under torch.compile with automatic_dynamic_shapes enabled, +it may be because the recomputation selected a different compiled graph than the +forward pass (e.g., a dynamic graph instead of the original static graph). +To fix this, either: + - Use torch._dynamo.mark_dynamic() to explicitly mark varying dimensions as + dynamic upfront, avoiding the static-to-dynamic transition. + - Call torch._C._dynamo.eval_frame._set_lru_cache(False) to disable LRU cache + reordering, which can change which graph is checked first between forward + and recompute. +See https://github.com/pytorch/pytorch/issues/166926 for more details and +workaround examples. +""" + + +_checkpoint_error_template = """ \ +An error happened while unpacking tensors; dumping logs of latest computation +because you passed `debug=True` to `torch.utils.checkpoint.checkpoint()`. +Scroll all the way down for guidance on how to navigate these logs. + ++~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ +| 1. Stack traces of the operators that ran in the original forward | ++------------------------------------------------------------------------------+ + +{forward_traces} ++~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ +| 2. Stack traces of the operators that ran during recomputation | ++------------------------------------------------------------------------------+ + +{recompute_traces} ++~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ +| 3. Log of operators in the original forward and recomputation | ++------------------------------------------------------------------------------+ +(Scroll up to correlate stack traces with each operation listed below. This + helps identify their source in the code.) + +IMPORTANT: Differences in "detach" calls between the original forward and the + recomputation are expected. They are introduced by the checkpointing + mechanism and can be ignored. + +Operations executed during the original forward: + +{forward_ops} + +Operations executed during recomputation: + +{recompute_ops} + ++------------------------------------------------------------------------------+ + ERROR: Detected non-determinism while running activation checkpointing + + You are seeing this error because you passed `debug=True` to checkpoint and + tensors to be saved during the original forward and differ between those saved + during recomputation. This can happen if different operators were ran in the + original forward and in the recomputation. + + To identify where the mismatch may be coming from, you can do the following: + + 1) Compare the operators ran during original forward and recomputation to + see where they differ. These operators are printed above in the order they + were executed. + + 2) Review the stack trace for each operator to locate its invocation source. + Each operator's stack trace is printed in their execution order. + + Note that the logs can be quite long. Here's how they are structured: + (Tip: you can Ctrl-f for these headers) + + 1. Stack traces of the operators that ran in the original forward + 2. Stack traces of the operators that ran during recomputation + 3. Log of operators in the original forward and recomputation + 4. Error message <--- You are here +-------------------------------------------------------------------------------- +""" + +class CheckpointError(RuntimeError): + pass + + +def _get_debug_context_and_cb() -> Tuple[Callable[[], Any], Callable[[CheckpointError], None]]: + # This function returns the context_fn and error_cb to be used by the + # checkpointing mechanism. error_cb is invoked when an error is detected + # during unpack. + + cpp_tb = platform.machine() in ('x86_64', 'aarch64', 'arm64') and platform.system() == 'Linux' + + class CaptureLogs: + def __init__(self) -> None: + self.logs = None + self.tbs = None + + def get_context_manager(self): + @contextlib.contextmanager + def logging_mode(): + with LoggingTensorMode(), \ + capture_logs(True, python_tb=True, script_tb=True, cpp_tb=cpp_tb) as logs_and_tb: + self.logs, self.tbs = logs_and_tb + yield logs_and_tb + return logging_mode() + + capture_logs_fwd = CaptureLogs() + capture_logs_recompute = CaptureLogs() + + def unpack_error_cb(e: CheckpointError) -> NoReturn: + def get_str_tb(label, capture_logs): + out = "" + total_len = len(capture_logs.logs) + for i, (log, tb) in enumerate(zip(capture_logs.logs, capture_logs.tbs, strict=False)): + out += f"{log} ({i + 1} of {total_len} in {label})\n\n" + found_torch_dispatch = False + for line in tb: + # Start printing stack trace only after __torch_dispatch__ is found + is_torch_dispatch = line['name'] == '__torch_dispatch__' + if not found_torch_dispatch and not is_torch_dispatch: + continue + elif is_torch_dispatch: + found_torch_dispatch = True + continue + out += f"{line['filename']}:{line['line']}:{line['name']}\n" + out += "\n\n" + return out + if capture_logs_fwd.logs is None: + raise AssertionError("capture_logs_fwd.logs is None") + if capture_logs_recompute.logs is None: + raise AssertionError("capture_logs_recompute.logs is None") + raise CheckpointError( + _checkpoint_error_template.format( + forward_traces=get_str_tb("original", capture_logs_fwd), + recompute_traces=get_str_tb("recompute", capture_logs_recompute), + forward_ops="\n".join(capture_logs_fwd.logs), + recompute_ops="\n".join(capture_logs_recompute.logs) + ) + ) from e + + def context_fn(): + return capture_logs_fwd.get_context_manager(), capture_logs_recompute.get_context_manager() + + return context_fn, unpack_error_cb + +def _default_meta_extractor(x: torch.Tensor) -> Dict[str, Any]: + # These properties are fast to check, easy to understand + return { + "shape": x.shape, + "dtype": x.dtype, + "device": x.device + } + +_allowed_determinism_checks_to_fns: Dict[str, Callable[[torch.Tensor], Any]] = { + _DEFAULT_DETERMINISM_MODE: _default_meta_extractor, + "none": lambda _: None, +} + +# See Rule 5 +class _StopRecomputationError(Exception): + pass + + +def _current_user_saved_tensors_hooks(): + # The (pack, unpack) pair a SavedVariable created right now would use, + # skipping checkpoint-internal hooks, or None. Checkpoint-internal hooks + # record the pair that was visible when they were pushed so that nested + # checkpoints resolve to the user's hooks, not each other's. + hooks = torch._C._autograd._top_saved_tensors_default_hooks(False) + while hooks is not None and getattr(hooks[0], "_checkpoint_internal", False): + hooks = hooks[0]._user_hooks # pyrefly: ignore[missing-attribute] + return hooks + + +class _checkpoint_internal_hook(torch.autograd.graph.saved_tensors_hooks): + # _user_hooks must only exist while we are on the hooks TLS stack (the + # only time _current_user_saved_tensors_hooks can reach it): the graph + # retains pack_hook via SavedVariable in a way gc cannot traverse, so a + # persistent attribute would give the graph a strong ref to user hooks, + # leaking uncollectably whenever those hooks reach back to the graph. + def __enter__(self): + self.pack_hook._user_hooks = _current_user_saved_tensors_hooks() # pyrefly: ignore[missing-attribute] + return super().__enter__() + + def __exit__(self, *args): + del self.pack_hook._user_hooks # pyrefly: ignore[missing-attribute] + return super().__exit__(*args) + + +class _recomputation_hook(_checkpoint_internal_hook): + def __init__(self, target_frame_ref: ReferenceType, gid: GraphExecGroup | int) -> None: + # Dynamo guards on WeakKeyDictionary internals are unstable here + # (dict length/keys change every call), causing recompilation storms. + # with `.compile()` so we disable + @torch._dynamo.disable + def pack_hook(x): + x = x.detach() if x.requires_grad else x + target_frame = target_frame_ref() + if target_frame is None: + raise AssertionError("Internal error: target_frame reference is None") + recomp_idx = target_frame.recomp_counter[gid] + target_frame.recomp_counter[gid] += 1 + + if recomp_idx >= len(target_frame.weak_holders): + if target_frame.early_stop: + raise AssertionError("Unexpected state: target_frame.early_stop is set") + if not target_frame.forward_completed: + # We run into this case when early stop is not enabled and do + # grad within checkpoint. + # We need to set this flag, so we don't error out later when + # we check if the number of tensors saved during forward and + # recomputation match. + target_frame.ignore_saved_mismatch = True + return x + raise CheckpointError( + "torch.utils.checkpoint: trying to save more tensors during " + "recomputation than during the original forward pass.\n" + f"{_debug_tip_msg}" + ) + + holder = target_frame.weak_holders[recomp_idx]() + + # This holder may have been cleared because someone may have called + # backward within forward. If so, we don't need to save. + if holder is not None: + _internal_assert(holder.handles.get(gid, None) is None) + holder.handles[gid] = _Handle() + target_frame.recomputed[gid][holder.handles[gid]] = x + + if target_frame.early_stop and target_frame.recomp_counter[gid] == len( + target_frame.weak_holders + ): + raise _StopRecomputationError + # See Rule 6: [ retain_graph is True ] above + return x + + def unpack_hook(x): + # See Rule 6: [ retain_graph is True ] above for an example of when + # the graph created during recomputation could be backwarded. + return x + + pack_hook._checkpoint_internal = True # type: ignore[attr-defined] + super().__init__(pack_hook, unpack_hook) + + +# torch._disable_dynamo creates a reference cycle with decorated function +# This function is used to ensure that the decorated function does not have +# a closure, so that other objects aren't also kept alive. +# https://github.com/pytorch/pytorch/issues/154642 +# Note: does not work when fn is compiled +@torch._disable_dynamo +def _run_fn_with_dynamo_disabled(fn, *args, **kwargs): + return fn(*args, **kwargs) + + +class _checkpoint_hook(_checkpoint_internal_hook): + def __init__(self, frame) -> None: + def pack_hook(x): + # See Rule 4 above + holder = _Holder() + frame.weak_holders.append(weakref.ref(holder)) + # Save metadata to detect non-determinism + if frame.metadata_fn is not None: + with torch.no_grad(): + frame.x_metadatas.append(frame.metadata_fn(x)) + return holder + + def unpack_hook(holder): + # First check if we're inside a GraphExecGroup context + gid: GraphExecGroup | None | int = GraphExecGroup._get_current_group() + if gid is None: + # Fallback to using the current graph task id + gid = torch._C._current_graph_task_id() + if gid == -1: + # generate a temporary id if we trigger unpack outside of a backward call + gid = int(uuid.uuid4()) + + if not frame.is_recomputed[gid]: + args = frame.get_inputs() + + try: + with _recomputation_hook( + weakref.ref(frame), gid + ), torch.autograd.enable_grad(): + # See Note: [compiled autograd and checkpoint unpack hook] + _run_fn_with_dynamo_disabled(frame.recompute_fn, *args) + except _StopRecomputationError: + pass + frame.is_recomputed[gid] = True + frame.check_recomputed_tensors_match(gid) + + _internal_assert(gid in holder.handles) + + if holder.handles[gid] is None: + extra = "" + if torch._C._get_graph_exec_group() is not None: + extra = ( + "Performing two backward calls that overlap (i.e. require the same " + "saved activation in order to compute gradients) is not allowed while " + "under the torch.utils.checkpoint.GraphExecGroup context. " + ) + raise CheckpointError( + "torch.utils.checkpoint: Unpack is being triggered for a tensor that was already " + f"unpacked once. {extra}If you are calling ctx.saved_tensors in backward, make sure " + "to do so only once. Otherwise please open an issue with details on your use case." + ) + _internal_assert(holder.handles[gid] in frame.recomputed[gid]) + ret = frame.recomputed[gid][holder.handles[gid]] + holder.handles[gid] = None + return ret + + pack_hook._checkpoint_internal = True # type: ignore[attr-defined] + if frame.unpack_error_cb is not None: + def unpack_hook_with_error_cb(holder): + try: + return unpack_hook(holder) + except CheckpointError as e: + frame.unpack_error_cb(e) + super().__init__(pack_hook, unpack_hook_with_error_cb) + else: + super().__init__(pack_hook, unpack_hook) + + +def _is_compiling(func, args, kwargs): + # Check if we are under AOTAutograd tracing or export tracing + # Checking that a proxy mode is active should always do what we want + if torch.compiler._is_non_strict_tracing(): + return False + return torch._C._get_dispatch_mode(torch._C._TorchDispatchModeKey.PROXY) is not None + + +class _VersionWrapper: + # Check that cached tensors are not mutated. + def __init__(self, val, unpack_hook=None) -> None: + self.val: torch.Tensor | Any = val + self.version: int | None = val._version if isinstance(val, torch.Tensor) else None + # Set when val was produced by a user saved-tensors pack hook; applied + # on retrieval so SAC-cached tensors honor hooks like save_on_cpu. + self.unpack_hook = unpack_hook + + def get_val(self, allow_cache_entry_mutation): + if self.version is not None and not allow_cache_entry_mutation: + if self.val._version != self.version: + # Can we give user a stack trace of where the mutation happened? + raise RuntimeError( + "Tensor cached during selective activation checkpoint has been mutated" + ) + return self.val if self.unpack_hook is None else self.unpack_hook(self.val) + + +def _detach_helper(x): + # We detach for two separate reasons: + # - For view ops, we need to ensure that when the tensor is returned from + # CachedDispatchMode, as_view sees that the AutogradMeta is nullptr + # - Avoid reference cycles + if isinstance(x, torch.Tensor): + with torch._C._SetExcludeDispatchKeyGuard(torch._C.DispatchKey.ADInplaceOrView, False): + # Ensure that view performed beneath autograd properly propagates + # version counter. TODO: Use reentrant_dispatch instead of + # manually manipulating dispatch keys. Using reentrant_dispatch + # would respect inference_mode, though that is not relevant for + # this case. + x = x.detach() + return x + + +class SelectiveCheckpointContext: + """ + Context passed to policy function during selective checkpointing. + + This class is used to pass relevant metadata to the policy function during + selective checkpointing. + + The policy function is only called during the forward pass. During + recomputation, cached values are retrieved by index, so ``is_recompute`` + is deprecated and always ``False``. + + Example: + >>> # xdoctest: +SKIP(stub) + >>> + >>> def policy_fn(ctx, op, *args, **kwargs): + >>> print(ctx.op_output) + >>> + >>> context_fn = functools.partial(create_selective_checkpoint_contexts, policy_fn) + >>> + >>> out = torch.utils.checkpoint.checkpoint( + >>> fn, x, y, + >>> use_reentrant=False, + >>> context_fn=context_fn, + >>> ) + """ + def __init__(self, *, is_recompute, op_output=None) -> None: + self.is_recompute = is_recompute + self.op_output = op_output + + +class CheckpointPolicy(enum.Enum): + """ + Enum for specifying the policy for checkpointing during backpropagation. + + The following policies are supported: + + - ``{MUST,PREFER}_SAVE``: The operation's output will be saved during the forward + pass and will not be recomputed during the backward pass + - ``{MUST,PREFER}_RECOMPUTE``: The operation's output will not be saved during the + forward pass and will be recomputed during the backward pass + - ``{MUST,PREFER}_CPU_OFFLOAD``: The operation's output will be saved during the + forward pass, offloaded to CPU, and reloaded to GPU during the backward pass + + Use ``MUST_*`` over ``PREFER_*`` to indicate that the policy should not be overridden + by other subsystems like `torch.compile`. + + .. note:: + A policy function that always returns ``PREFER_RECOMPUTE`` is + equivalent to vanilla checkpointing. + + A policy function that returns ``PREFER_SAVE`` every op is + NOT equivalent to not using checkpointing. Using such a policy would + save additional tensors not limited to ones that are actually needed for + gradient computation. + """ + MUST_SAVE = 0 + PREFER_SAVE = 1 + MUST_RECOMPUTE = 2 + PREFER_RECOMPUTE = 3 + MUST_CPU_OFFLOAD = 4 + PREFER_CPU_OFFLOAD = 5 + + +def _policy_from_bool(b): + # For backward compatibility + return CheckpointPolicy.MUST_SAVE if b else CheckpointPolicy.PREFER_RECOMPUTE + + +SAC_IGNORED_OPS = { + # AC inserts different number of detach during forward and recompute. + torch.ops.aten.detach.default, + # AC's determinism check invokes additional metadata ops during forward. + # With subclasses involved, these metadata ops become dispatchable, this + # can result in incorrectness if these ops are selected cached. + torch.ops.prim.device.default, +} | set(torch._subclasses.functional_tensor.FunctionalTensor.metadata_fns) # type: ignore[has-type] + + +def _sac_storage_key(func, args): + """Compute the SAC storage key for a given op. + + For inductor_compiled_code, each compiled region gets its own FIFO queue + keyed by the callable's unique idx. Without this, all compiled regions + share one queue and a cache-hit that skips a region during recompute + causes the queue to return the wrong entry (see gh-175258). + """ + from torch._higher_order_ops.wrap import ( + _resolve_inductor_callable, + inductor_compiled_code as _inductor_compiled_code, + ) + if func is _inductor_compiled_code and args: + return (func, _resolve_inductor_callable(args[0]).idx) + return func + + +class _CachingTorchDispatchMode(TorchDispatchMode): + @classmethod + def ignore_compile_internals(cls): + return True + + # Used together with _CachedTorchDispatchMode to implement SAC. + def __init__(self, policy_fn, storage, ac_graph_id=None) -> None: + self.policy_fn = policy_fn + self.storage = storage + self.ac_graph_id = ac_graph_id + # Tri-state opt-in for routing SAC-cached tensors through the + # surrounding user saved_tensors_hooks, set by checkpoint() after this + # mode is constructed (like ac_graph_id). None: legacy behavior (hooks + # bypassed) plus a FutureWarning if user hooks are in scope; True/False: + # opt into the new/old behavior explicitly and silence the warning. + self.respect_saved_tensors_hooks: bool | None = None + self.func_counter: Dict[Any, int] = defaultdict(int) + + def __torch_dispatch__(self, func, types, args=(), kwargs=None): + kwargs = {} if kwargs is None else kwargs + is_compiling = _is_compiling(func, args, kwargs) + + if is_compiling: + fx_traceback.current_meta["ac_graph_id"] = self.ac_graph_id + fx_traceback.current_meta["recompute"] = CheckpointPolicy.PREFER_RECOMPUTE + + if func in SAC_IGNORED_OPS: + return func(*args, **kwargs) + + proxy_mode = None + graph_len_before = 0 + if is_compiling: + from torch.fx.experimental.proxy_tensor import get_proxy_mode + proxy_mode = get_proxy_mode() + if proxy_mode is not None: + graph_len_before = len(proxy_mode.tracer.graph.nodes) + + out = func(*args, **kwargs) + + key = _sac_storage_key(func, args) + idx = self.func_counter[key] + self.func_counter[key] += 1 + + policy = self.policy_fn(SelectiveCheckpointContext(is_recompute=False, op_output=out), + func, *args, **kwargs) + if isinstance(policy, bool): + policy = _policy_from_bool(policy) + + if is_compiling: + if proxy_mode is not None: + graph = proxy_mode.tracer.graph + num_new = len(graph.nodes) - graph_len_before + for node in itertools.islice(reversed(graph.nodes), num_new): + node.meta["recompute"] = policy + + if policy in (CheckpointPolicy.MUST_SAVE, CheckpointPolicy.PREFER_SAVE) or is_compiling: + # SAC caches these tensors outside the autograd graph, bypassing + # SavedVariable, so simulate pack/unpack with the user's + # saved-tensors hooks (if any): hooks like save_on_cpu must see + # every tensor retained until backward, whether autograd or SAC + # holds it. Skipped under compile, where storage is a tracing + # artifact rather than a real cache. + # + # Honoring the hooks is a BC break, so it is gated behind the + # respect_saved_tensors_hooks opt-in on checkpoint(), which defaults + # to the legacy behavior (hooks bypassed). When a user hook is + # actually in scope we warn, since the default will flip. + user_hooks = None if is_compiling else _current_user_saved_tensors_hooks() + if user_hooks is not None: + respects = self.respect_saved_tensors_hooks + if respects is None: + warnings.warn( + "A saved_tensors_hooks context (e.g. save_on_cpu) is " + "active around a selective activation checkpoint region. " + "Tensors that SAC saves currently bypass these hooks, but " + "a future release will route them through the hooks like " + "any other saved tensor. Silence this warning and choose " + "the behavior explicitly by passing " + "respect_saved_tensors_hooks=True|False to " + "torch.utils.checkpoint.checkpoint.", + FutureWarning, + stacklevel=2, + ) + if not respects: + user_hooks = None + + def wrap(x): + x = _detach_helper(x) + if user_hooks is not None and isinstance(x, torch.Tensor): + return _VersionWrapper(user_hooks[0](x), unpack_hook=user_hooks[1]) + return _VersionWrapper(x) + + self.storage[key][idx] = tree_map(wrap, out) + else: + self.storage[key][idx] = _RECOMPUTE + return out + +_RECOMPUTE = object() +_CONSUMED = object() + +_SAC_MISMATCH_MSG = ( + "This can happen if the operations in the checkpointed region are " + "nondeterministic or depend on global state that changed between " + "forward and backward." +) + + +class _CachedTorchDispatchMode(TorchDispatchMode): + @classmethod + def ignore_compile_internals(cls): + return True + + # Used together with _CachingTorchDispatchMode to implement SAC. + # policy_fn is accepted but ignored for BC (xformers subclasses this). + def __init__(self, policy_fn, storage, allow_cache_entry_mutation=False) -> None: + self.storage = storage + self.allow_cache_entry_mutation = allow_cache_entry_mutation + self.func_counter: Dict[Any, int] = defaultdict(int) + + def __enter__(self): + # Reset so retain_graph=True hits "backward an extra time" not "index not found". + self.func_counter.clear() + return super().__enter__() + + def __torch_dispatch__(self, func, types, args=(), kwargs=None): + if func in SAC_IGNORED_OPS: + return func(*args, **kwargs) + + key = _sac_storage_key(func, args) + idx = self.func_counter[key] + self.func_counter[key] += 1 + + func_storage = self.storage.get(key) + if func_storage is None: + raise RuntimeError( + f"{func} encountered during backward but not found in " + f"storage. {_SAC_MISMATCH_MSG}" + ) + entry = func_storage.get(idx) + if entry is None: + raise RuntimeError( + f"{func} invocation index {idx} encountered during backward " + f"but not found in storage. {_SAC_MISMATCH_MSG}" + ) + elif entry is _CONSUMED: + raise RuntimeError( + "Trying to backward an extra time. You are only allowed to backward once " + "on any region computed under selective activation checkpoint." + ) + elif entry is _RECOMPUTE: + kwargs = {} if kwargs is None else kwargs + return func(*args, **kwargs) + else: + func_storage[idx] = _CONSUMED + return tree_map(lambda x: x.get_val(self.allow_cache_entry_mutation), entry) + + +def create_selective_checkpoint_contexts(policy_fn_or_list, allow_cache_entry_mutation=False): + """ + Helper to avoid recomputing certain ops during activation checkpointing. + + Use this with `torch.utils.checkpoint.checkpoint` to control which + operations are recomputed during the backward pass. + + Args: + policy_fn_or_list (Callable or List): + - If a policy function is provided, it should accept a + :class:`SelectiveCheckpointContext`, the :class:`OpOverload`, args and + kwargs to the op, and return a :class:`CheckpointPolicy` enum value + indicating whether the execution of the op should be recomputed or not. + - If a list of operations is provided, it is equivalent to a policy + returning `CheckpointPolicy.MUST_SAVE` for the specified + operations and `CheckpointPolicy.PREFER_RECOMPUTE` for all other + operations. + allow_cache_entry_mutation (bool, optional): By default, an error is + raised if any tensors cached by selective activation checkpoint are + mutated in order to ensure correctness. If set to `True`, this check + is disabled. + Returns: + A tuple of two context managers. + + Example: + >>> # xdoctest: +REQUIRES(LINUX) + >>> import functools + >>> + >>> x = torch.rand(10, 10, requires_grad=True) + >>> y = torch.rand(10, 10, requires_grad=True) + >>> + >>> ops_to_save = [ + >>> torch.ops.aten.mm.default, + >>> ] + >>> + >>> def policy_fn(ctx, op, *args, **kwargs): + >>> if op in ops_to_save: + >>> return CheckpointPolicy.MUST_SAVE + >>> else: + >>> return CheckpointPolicy.PREFER_RECOMPUTE + >>> + >>> context_fn = functools.partial(create_selective_checkpoint_contexts, policy_fn) + >>> + >>> # or equivalently + >>> context_fn = functools.partial(create_selective_checkpoint_contexts, ops_to_save) + >>> + >>> def fn(x, y): + >>> return torch.sigmoid(torch.matmul(torch.matmul(x, y), y)) * y + >>> + >>> out = torch.utils.checkpoint.checkpoint( + >>> fn, x, y, + >>> use_reentrant=False, + >>> context_fn=context_fn, + >>> ) + """ + # NB: If grad_mode is disabled, checkpoint would not run forward under + # context_fn anyway, so proceed as usual. + if isinstance(policy_fn_or_list, list): + for op in policy_fn_or_list: + if not isinstance(op, (torch._ops.OpOverload, torch._ops.HigherOrderOperator)): + _extra_msg = ( + "Please update the OpOverloadPacket to a specific OpOverload." + "For example, if you have `torch.ops.aten.mm`, change it to `torch.ops.aten.mm.default`." + ) if isinstance(op, torch._ops.OpOverloadPacket) else "" + raise ValueError( + f"Expected op in `op_list` to be an OpOverload but got: {op} " + f"of type {type(op)}. {_extra_msg}" + ) + + def policy_fn(ctx, op, *args, **kwargs): + if op in policy_fn_or_list: + return CheckpointPolicy.MUST_SAVE + else: + return CheckpointPolicy.PREFER_RECOMPUTE + elif callable(policy_fn_or_list): + policy_fn = policy_fn_or_list + else: + raise TypeError("policy_fn_or_list must be either a function or a list of ops.") + + storage: Dict[Any, Dict[int, Any]] = defaultdict(dict) + return ( + _CachingTorchDispatchMode(policy_fn, storage), + _CachedTorchDispatchMode(None, storage, allow_cache_entry_mutation), + ) + +# NB: this helper wraps fn before calling checkpoint_impl. kwargs and +# saving/restoring of global state is handled here. + +def _checkpoint_without_reentrant_generator( + fn, + preserve_rng_state=True, + context_fn: Callable[[], Tuple[ContextManager, ContextManager]] = noop_context_fn, + determinism_check: str = _DEFAULT_DETERMINISM_MODE, + debug: bool = False, + early_stop: bool = True, + *args, + respect_saved_tensors_hooks: bool | None = None, + **kwargs, +): + # BC shim: this retains the original positional-args signature (args/kwargs + # trailing the config) for out-of-tree callers that invoke it positionally. + # New in-tree callers should use _checkpoint_without_reentrant_generator_impl, + # which takes args/kwargs as explicit tuple/dict parameters. + return _checkpoint_without_reentrant_generator_impl( + fn, + args, + kwargs, + preserve_rng_state=preserve_rng_state, + context_fn=context_fn, + determinism_check=determinism_check, + debug=debug, + early_stop=early_stop, + respect_saved_tensors_hooks=respect_saved_tensors_hooks, + ) + + +def _checkpoint_without_reentrant_generator_impl( + fn, + args, + kwargs, + *, + preserve_rng_state=True, + context_fn: Callable[[], Tuple[ContextManager, ContextManager]] = noop_context_fn, + determinism_check: str = _DEFAULT_DETERMINISM_MODE, + debug: bool = False, + early_stop: bool = True, + respect_saved_tensors_hooks: bool | None = None, +): + """Checkpointing without reentrant autograd. + + Args: + fn: describes what to run in the forward pass of the model or + part of the model. It should also know how to handle the inputs + passed as the tuple. For example, in LSTM, if user passes + ``(activation, hidden)``, :attr:`function` should correctly use the + first input as ``activation`` and the second input as ``hidden`` + args: Tuple of arguments to pass in to the given ``function``. + kwargs: Dict of keyword arguments to pass into the given ``function``. + preserve_rng_state(bool, optional): Omit stashing and restoring + the RNG state during each checkpoint. + Default: ``True`` + context_fn(Callable, optional): A callable returning a tuple of two + context managers. The function and its recomputation will be run + under the first and second context managers respectively. + determinism_check(str, optional): A string specifying the determinism + check to perform. By default it is set to ``"default"`` which + compares the shapes, dtypes, and devices of the recomputed tensors + against those the saved tensors. To turn off this check, specify + ``"none"``. Currently these are the only two supported values. + Please open an issue if you would like to see more determinism + checks. + debug(bool, optional): If ``True``, error messages will also include + a trace of the operators ran during the original forward computation + as well as the recomputation. + early_stop(bool, optional): If ``True``, non-reentrant checkpoint stops + recomputation as soon as it has computed all needed Tensors. Can be + overridden globally using :func:`set_checkpoint_early_stop` context + manager. Default: ``True``. + """ + unpack_error_cb = None + + if _checkpoint_debug_enabled if _checkpoint_debug_enabled is not None else debug: + if context_fn is not noop_context_fn: + raise ValueError( + "debug=True is incompatible with non-default context_fn" + ) + context_fn, unpack_error_cb = _get_debug_context_and_cb() + + if determinism_check in _allowed_determinism_checks_to_fns: + metadata_fn = _allowed_determinism_checks_to_fns[determinism_check] + else: + raise ValueError( + f"determinism_check should be one of {list(_allowed_determinism_checks_to_fns.keys())}, " + f"but got {determinism_check}" + ) + + device_type = _infer_device_type(*args) + device_module = _get_device_module(device_type) + forward_context, recompute_context = context_fn() + # SAC caches some tensors outside the autograd graph; this tells its caching + # mode whether to route them through the user's saved_tensors_hooks. Set by + # attribute after construction, like ac_graph_id in the compile path. No-op + # for context_fns that are not SAC (e.g. the default), which cache nothing. + if isinstance(forward_context, _CachingTorchDispatchMode): + forward_context.respect_saved_tensors_hooks = respect_saved_tensors_hooks + if _is_compiling(fn, args, kwargs) and context_fn is not noop_context_fn: + if ( + not isinstance(forward_context, TorchDispatchMode) + or not isinstance(recompute_context, TorchDispatchMode) + ): + raise AssertionError( + "In torch.compile mode, `context_fn` arg passed to `torch.utils.checkpoint` " + "must generate a tuple of two `TorchDispatchMode`s." + ) + # Accommodates the (remote) possibility that autocast is enabled for cpu AND gpu. + device_autocast_kwargs, cpu_autocast_kwargs = _get_autocast_kwargs(device_type=device_type) + + if preserve_rng_state: + fwd_cpu_state = torch.get_rng_state() + # Don't eagerly initialize the cuda context by accident. + # (If the user intends that the context is initialized later, within their + # run_function, we SHOULD actually stash the cuda state here. Unfortunately, + # we have no way to anticipate this will happen before we run the function. + # If they do so, we raise an error.) + had_device_in_fwd = False + if getattr(device_module, "_initialized", False): + had_device_in_fwd = True + fwd_devices, fwd_device_states = get_device_states(*args) + + from torch.overrides import _get_current_function_mode_stack + from torch.utils._device import DeviceContext + + # recompute_fn should respect the device context of the original forward. + # Capture the device, not the mode instance: re-entering the captured + # DeviceContext during recompute (possibly on the backward thread) corrupts + # its exit state and leaks it. A fresh context avoids that. + device_ctx = next( + ( + DeviceContext(mode.device) + for mode in reversed(_get_current_function_mode_stack()) + if isinstance(mode, DeviceContext) + ), + contextlib.nullcontext(), + ) + error_on_nested_fx_trace = torch._dynamo.config.error_on_nested_fx_trace + is_non_strict_tracing = torch.compiler._is_non_strict_tracing() + is_fx_tracing = torch.fx._symbolic_trace._get_is_fx_tracing() + + def recompute_fn(*args) -> None: + # This will be called later during recomputation. This wrapping enables + # the necessary global state to be captured. + rng_devices = [] + if preserve_rng_state and had_device_in_fwd: + rng_devices = fwd_devices + with torch.random.fork_rng( + devices=rng_devices, enabled=preserve_rng_state, device_type=device_type + ): + if preserve_rng_state: + torch.set_rng_state(fwd_cpu_state) + if had_device_in_fwd: + set_device_states(fwd_devices, fwd_device_states, device_type=device_type) + + device_autocast_ctx = torch.amp.autocast( + device_type=device_type, **device_autocast_kwargs + ) if torch.amp.is_autocast_available(device_type) else contextlib.nullcontext() + nested_fx_trace_ctx = ( + torch._dynamo.config.patch( + error_on_nested_fx_trace=error_on_nested_fx_trace + ) + if is_non_strict_tracing + else contextlib.nullcontext() + ) + with ( + device_autocast_ctx, + torch.amp.autocast("cpu", **cpu_autocast_kwargs), + recompute_context, + device_ctx, + nested_fx_trace_ctx, + torch.fx._symbolic_trace._is_fx_tracing_context(is_fx_tracing), + ): # type: ignore[attr-defined] + fn(*args, **kwargs) + + new_frame = _CheckpointFrame( + recompute_fn, + _enable_checkpoint_early_stop if _enable_checkpoint_early_stop is not None else early_stop, + unpack_error_cb, + metadata_fn + ) + + if not torch.is_grad_enabled(): + yield + return + + if ( + isinstance(forward_context, _CachingTorchDispatchMode) + and torch._C._autograd._top_saved_tensors_default_hooks(False) is not None + ): + torch._C._log_api_usage_once( + "torch.utils.checkpoint.sac_with_saved_tensors_hooks" + ) + + new_frame.save_inputs(*args) + + forward_context_suppressed_exc = False + with _checkpoint_hook(new_frame), forward_context: + try: + yield + except BaseException: + forward_context_suppressed_exc = True + raise + if forward_context_suppressed_exc: + raise RuntimeError( + "torch.utils.checkpoint: the forward context provided by " + "context_fn suppressed an exception raised during the " + "checkpointed forward. This is not supported because checkpoint " + "cannot return a value for a failed forward." + ) + new_frame.forward_completed = True + + if getattr(device_module, "_initialized", False) and \ + preserve_rng_state and not had_device_in_fwd: # type: ignore[possibly-undefined] + # Device was not initialized before running the forward, so we didn't + # stash the device state. + raise RuntimeError( + "PyTorch's device state was initialized in the forward pass " + "of a Checkpoint, which is not allowed. Please open an issue " + "if you need this feature." + ) + + return + + +class GraphExecGroup: + """Any checkpointed regions encountered by backward under the same instance + of this context manager will trigger recompute at most once, even if + there are multiple calls to backward. + + Backward calls under the same instance of this context manager must execute + over non-overlapping regions of the backward graph even if retain_graph=True. + In particular, any two backward call cannot use the same saved activation for + gradient computation. + + .. note:: + This context manager only affects checkpoint with use_reentrant=False, and + is a no-op otherwise. + """ + + def __enter__(self) -> Self: + if torch._C._get_graph_exec_group() is not None: + raise RuntimeError( + "GraphExecGroup contexts cannot be nested. " + f"Already inside group {torch._C._get_graph_exec_group()}" + ) + torch._C._set_graph_exec_group(self) + return self + + def __exit__(self, *args: object) -> None: + torch._C._set_graph_exec_group(None) + + @classmethod + def _get_current_group(cls) -> GraphExecGroup | None: + # Private API to be used by utils like AC + return torch._C._get_graph_exec_group() + + +# Note: [compiled autograd and checkpoint unpack hook] +# When tracing via compiled autograd, this hook will be visible to the +# compiler if the forward of this checkpointed region ran in eager. +# If the forward had ran under compile, it would have been wrapped in a +# higher order op. See Note: [torch.compile and checkpoint]. +# +# Since we run the recomputation hook under a enable_grad context, +# AOTDispatch will trace a joint graph for this hook, and may +# save different activations than in eager. This conflicts with the +# strict activation count checks in `frame.check_recomputed_tensors_match`. +# So, we disable this hook to force it to recompute eager checkpointed regions +# in eager. This could be removed if we can disable the partitioner for this +# graph segment. diff --git a/.venv/lib/python3.12/site-packages/torch/utils/collect_env.py b/.venv/lib/python3.12/site-packages/torch/utils/collect_env.py new file mode 100644 index 0000000000000000000000000000000000000000..b566cd94e5d0314afc50150b24e2af7cb984a390 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/collect_env.py @@ -0,0 +1,944 @@ +# mypy: allow-untyped-defs + +# Unlike the rest of the PyTorch this file must be python2 compliant. +# This script outputs relevant system environment info +# Run it with `python collect_env.py` or `python -m torch.utils.collect_env` +import datetime +import json +import locale +import os +import re +import subprocess +import sys +from collections import namedtuple +from typing import cast as _cast, Dict as _Dict + + +try: + import torch + + TORCH_AVAILABLE = True +except (ImportError, NameError, AttributeError, OSError): + TORCH_AVAILABLE = False + +# System Environment Information +SystemEnv = namedtuple( + "SystemEnv", + [ + "torch_version", + "is_debug_build", + "cuda_compiled_version", + "gcc_version", + "clang_version", + "cmake_version", + "os", + "libc_version", + "python_version", + "python_platform", + "is_cuda_available", + "cuda_runtime_version", + "cuda_module_loading", + "nvidia_driver_version", + "nvidia_gpu_models", + "cudnn_version", + "is_xpu_available", + "pip_version", # 'pip' or 'pip3' + "pip_packages", + "conda_packages", + "hip_compiled_version", + "hip_runtime_version", + "miopen_runtime_version", + "caching_allocator_config", + "is_xnnpack_available", + "cpu_info", + ], +) + +COMMON_PATTERNS = [ + "torch", + "numpy", + "triton", + "optree", +] + +NVIDIA_PATTERNS = [ + "cuda-cudart", + "cuda-cupti", + "cuda-libraries", + "cuda-opencl", + "cuda-nvrtc", + "cuda-runtime", + "cublas", + "cudnn", + "cufft", + "curand", + "cusolver", + "cusparse", + "nccl", + "nvjitlink", + "nvtx", +] + +ONEAPI_PATTERNS = [ + "dpcpp-cpp-rt", + "intel-cmplr-lib-rt", + "intel-cmplr-lib-ur", + "intel-cmplr-lic-rt", + "intel-opencl-rt", + "intel-sycl-rt", + "mkl", + "onemkl-sycl-blas", + "onemkl-sycl-dft", + "onemkl-sycl-lapack", + "onemkl-sycl-rng", + "onemkl-sycl-sparse", + "intel-openmp", + "tbb", + "impi-rt", + "impi-devel", + "oneccl", + "oneccl-devel", + "intel-pti", + "umf", + "tcmlib", +] + +CONDA_PATTERNS = [ + "cudatoolkit", + "soumith", + "mkl", + "magma", +] + +PIP_PATTERNS = [ + "mypy", + "flake8", + "onnx", +] + + +def run(command): + """Return (return-code, stdout, stderr).""" + shell = type(command) is str + p = subprocess.Popen( + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell + ) + raw_output, raw_err = p.communicate() + rc = p.returncode + if get_platform() == "win32": + enc = "oem" + else: + enc = locale.getpreferredencoding() + output = raw_output.decode(enc) + err = raw_err.decode(enc) + return rc, output.strip(), err.strip() + + +def run_and_read_all(run_lambda, command): + """Run command using run_lambda; reads and returns entire output if rc is 0.""" + rc, out, _ = run_lambda(command) + if rc != 0: + return None + return out + + +def run_and_parse_first_match(run_lambda, command, regex): + """Run command using run_lambda, returns the first regex match if it exists.""" + rc, out, _ = run_lambda(command) + if rc != 0: + return None + match = re.search(regex, out) + if match is None: + return None + return match.group(1) + + +def run_and_return_first_line(run_lambda, command): + """Run command using run_lambda and returns first line if output is not empty.""" + rc, out, _ = run_lambda(command) + if rc != 0: + return None + return out.split("\n")[0] + + +def get_conda_packages(run_lambda, patterns=None): + if patterns is None: + patterns = CONDA_PATTERNS + COMMON_PATTERNS + NVIDIA_PATTERNS + ONEAPI_PATTERNS + conda = os.environ.get("CONDA_EXE", "conda") + out = run_and_read_all(run_lambda, "{} list".format(conda)) + if out is None: + return out + + return "\n".join( + line + for line in out.splitlines() + if not line.startswith("#") and any(name in line for name in patterns) + ) + + +def get_gcc_version(run_lambda): + return run_and_parse_first_match(run_lambda, "gcc --version", r"gcc (.*)") + + +def get_clang_version(run_lambda): + return run_and_parse_first_match( + run_lambda, "clang --version", r"clang version (.*)" + ) + + +def get_cmake_version(run_lambda): + return run_and_parse_first_match(run_lambda, "cmake --version", r"cmake (.*)") + + +def get_nvidia_driver_version(run_lambda): + if get_platform() == "darwin": + cmd = "kextstat | grep -i cuda" + return run_and_parse_first_match( + run_lambda, cmd, r"com[.]nvidia[.]CUDA [(](.*?)[)]" + ) + smi = get_nvidia_smi() + return run_and_parse_first_match(run_lambda, smi, r"Driver Version: (.*?) ") + + +def get_gpu_info(run_lambda): + if get_platform() == "darwin" or ( + TORCH_AVAILABLE + and hasattr(torch.version, "hip") + and torch.version.hip is not None + ): + if TORCH_AVAILABLE and torch.cuda.is_available(): + if torch.version.hip is not None: + prop = torch.cuda.get_device_properties(0) + if hasattr(prop, "gcnArchName"): + gcnArch = " ({})".format(prop.gcnArchName) + else: + gcnArch = "NoGCNArchNameOnOldPyTorch" + else: + gcnArch = "" + return torch.cuda.get_device_name(None) + gcnArch + return None + smi = get_nvidia_smi() + uuid_regex = re.compile(r" \(UUID: .+?\)") + rc, out, _ = run_lambda(smi + " -L") + if rc != 0: + return None + # Anonymize GPUs by removing their UUID + return re.sub(uuid_regex, "", out) + + +def get_running_cuda_version(run_lambda): + return run_and_parse_first_match(run_lambda, "nvcc --version", r"release .+ V(.*)") + + +def get_cudnn_version(run_lambda): + """Return a list of libcudnn.so; it's hard to tell which one is being used.""" + if get_platform() == "win32": + system_root = os.environ.get("SYSTEMROOT", "C:\\Windows") + cuda_path = os.environ.get("CUDA_PATH", "%CUDA_PATH%") + where_cmd = os.path.join(system_root, "System32", "where") + cudnn_cmd = '{} /R "{}\\bin" cudnn*.dll'.format(where_cmd, cuda_path) + elif get_platform() == "darwin": + # CUDA libraries and drivers can be found in /usr/local/cuda/. See + # https://docs.nvidia.com/cuda/archive/9.0/cuda-installation-guide-mac-os-x/index.html#installation + # https://docs.nvidia.com/deeplearning/cudnn/installation/latest/ + # Use CUDNN_LIBRARY when cudnn library is installed elsewhere. + cudnn_cmd = "ls /usr/local/cuda/lib/libcudnn*" + else: + cudnn_cmd = 'ldconfig -p | grep libcudnn | rev | cut -d" " -f1 | rev' + rc, out, _ = run_lambda(cudnn_cmd) + # find will return 1 if there are permission errors or if not found + if len(out) == 0 or (rc != 1 and rc != 0): + l = os.environ.get("CUDNN_LIBRARY") + if l is not None and os.path.isfile(l): + return os.path.realpath(l) + return None + files_set = set() + for fn in out.split("\n"): + fn = os.path.realpath(fn) # eliminate symbolic links + if os.path.isfile(fn): + files_set.add(fn) + if not files_set: + return None + # Alphabetize the result because the order is non-deterministic otherwise + files = sorted(files_set) + if len(files) == 1: + return files[0] + result = "\n".join(files) + return "Probably one of the following:\n{}".format(result) + + +def get_nvidia_smi(): + # Note: nvidia-smi is currently available only on Windows and Linux + smi = "nvidia-smi" + if get_platform() == "win32": + system_root = os.environ.get("SYSTEMROOT", "C:\\Windows") + program_files_root = os.environ.get("PROGRAMFILES", "C:\\Program Files") + legacy_path = os.path.join( + program_files_root, "NVIDIA Corporation", "NVSMI", smi + ) + new_path = os.path.join(system_root, "System32", smi) + smis = [new_path, legacy_path] + for candidate_smi in smis: + if os.path.exists(candidate_smi): + smi = '"{}"'.format(candidate_smi) + break + return smi + + +def _detect_linux_pkg_manager(): + if get_platform() != "linux": + return "N/A" + for mgr_name in ["dpkg", "dnf", "yum", "zypper"]: + rc, _, _ = run(f"which {mgr_name}") + if rc == 0: + return mgr_name + return "N/A" + + +def get_linux_pkg_version(run_lambda, pkg_name): + pkg_mgr = _detect_linux_pkg_manager() + if pkg_mgr == "N/A": + return "N/A" + + grep_version = { + "dpkg": { + "field_index": 2, + "command": "dpkg -l | grep {}", + }, + "dnf": { + "field_index": 1, + "command": "dnf list | grep {}", + }, + "yum": { + "field_index": 1, + "command": "yum list | grep {}", + }, + "zypper": { + "field_index": 2, + "command": "zypper info {} | grep Version", + }, + } + + field_index: int = int(_cast(int, grep_version[pkg_mgr]["field_index"])) + cmd: str = str(grep_version[pkg_mgr]["command"]) + cmd = cmd.format(pkg_name) + ret = run_and_read_all(run_lambda, cmd) + if ret is None or ret == "": + return "N/A" + lst = re.sub(" +", " ", ret).split(" ") + if len(lst) <= field_index: + return "N/A" + return lst[field_index] + + +def get_intel_gpu_driver_version(run_lambda): + lst = [] + platform = get_platform() + if platform == "linux": + pkgs = { # type: ignore[var-annotated] + "dpkg": { + "intel-opencl-icd", + "libze1", + "level-zero", + }, + "dnf": { + "intel-opencl", + "level-zero", + }, + "yum": { + "intel-opencl", + "level-zero", + }, + "zypper": { + "intel-opencl", + "level-zero", + }, + }.get(_detect_linux_pkg_manager(), {}) + for pkg in pkgs: + ver = get_linux_pkg_version(run_lambda, pkg) + if ver != "N/A": + lst.append(f"* {pkg}:\t{ver}") + if platform in ["win32", "cygwin"]: + txt = run_and_read_all( + run_lambda, + 'powershell.exe "gwmi -Class Win32_PnpSignedDriver | where{$_.DeviceClass -eq \\"DISPLAY\\"\ + -and $_.Manufacturer -match \\"Intel\\"} | Select-Object -Property DeviceName,DriverVersion,DriverDate\ + | ConvertTo-Json"', + ) + try: + obj = json.loads(txt) + if type(obj) is list: + for o in obj: + lst.append( + f'* {o["DeviceName"]}: {o["DriverVersion"]} ({o["DriverDate"]})' + ) + else: + lst.append(f'* {obj["DriverVersion"]} ({obj["DriverDate"]})') + except ValueError as e: + lst.append(txt) + lst.append(str(e)) + return "\n".join(lst) + + +def get_intel_gpu_onboard(run_lambda): + lst: list[str] = [] + platform = get_platform() + if platform == "linux": + txt = run_and_read_all(run_lambda, "xpu-smi discovery -j") + if txt: + try: + obj = json.loads(txt) + device_list = obj.get("device_list", []) + if isinstance(device_list, list) and device_list: + lst.extend(f'* {device["device_name"]}' for device in device_list) + else: + lst.append("N/A") + except (ValueError, TypeError) as e: + lst.append(txt) + lst.append(str(e)) + else: + lst.append("N/A") + if platform in ["win32", "cygwin"]: + txt = run_and_read_all( + run_lambda, + 'powershell.exe "gwmi -Class Win32_PnpSignedDriver | where{$_.DeviceClass -eq \\"DISPLAY\\"\ + -and $_.Manufacturer -match \\"Intel\\"} | Select-Object -Property DeviceName | ConvertTo-Json"', + ) + if txt: + try: + obj = json.loads(txt) + if isinstance(obj, list) and obj: + lst.extend(f'* {device["DeviceName"]}' for device in obj) + else: + lst.append(f'* {obj.get("DeviceName", "N/A")}') + except ValueError as e: + lst.append(txt) + lst.append(str(e)) + else: + lst.append("N/A") + return "\n".join(lst) + + +def get_intel_gpu_detected(run_lambda): + if not TORCH_AVAILABLE or not hasattr(torch, "xpu"): + return "N/A" + + device_count = torch.xpu.device_count() + if device_count == 0: + return "N/A" + + devices = [ + f"* [{i}] {torch.xpu.get_device_properties(i)}" for i in range(device_count) + ] + return "\n".join(devices) + + +# example outputs of CPU infos +# * linux +# Architecture: x86_64 +# CPU op-mode(s): 32-bit, 64-bit +# Address sizes: 46 bits physical, 48 bits virtual +# Byte Order: Little Endian +# CPU(s): 128 +# On-line CPU(s) list: 0-127 +# Vendor ID: GenuineIntel +# Model name: Intel(R) Xeon(R) Platinum 8375C CPU @ 2.90GHz +# CPU family: 6 +# Model: 106 +# Thread(s) per core: 2 +# Core(s) per socket: 32 +# Socket(s): 2 +# Stepping: 6 +# BogoMIPS: 5799.78 +# Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr +# sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl +# xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq monitor ssse3 fma cx16 +# pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand +# hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced +# fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid avx512f avx512dq rdseed adx smap +# avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 +# xsaves wbnoinvd ida arat avx512vbmi pku ospke avx512_vbmi2 gfni vaes vpclmulqdq +# avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid md_clear flush_l1d arch_capabilities +# Virtualization features: +# Hypervisor vendor: KVM +# Virtualization type: full +# Caches (sum of all): +# L1d: 3 MiB (64 instances) +# L1i: 2 MiB (64 instances) +# L2: 80 MiB (64 instances) +# L3: 108 MiB (2 instances) +# NUMA: +# NUMA node(s): 2 +# NUMA node0 CPU(s): 0-31,64-95 +# NUMA node1 CPU(s): 32-63,96-127 +# Vulnerabilities: +# Itlb multihit: Not affected +# L1tf: Not affected +# Mds: Not affected +# Meltdown: Not affected +# Mmio stale data: Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown +# Retbleed: Not affected +# Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp +# Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization +# Spectre v2: Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence +# Srbds: Not affected +# Tsx async abort: Not affected +# * win32 +# Architecture=9 +# CurrentClockSpeed=2900 +# DeviceID=CPU0 +# Family=179 +# L2CacheSize=40960 +# L2CacheSpeed= +# Manufacturer=GenuineIntel +# MaxClockSpeed=2900 +# Name=Intel(R) Xeon(R) Platinum 8375C CPU @ 2.90GHz +# ProcessorType=3 +# Revision=27142 +# +# Architecture=9 +# CurrentClockSpeed=2900 +# DeviceID=CPU1 +# Family=179 +# L2CacheSize=40960 +# L2CacheSpeed= +# Manufacturer=GenuineIntel +# MaxClockSpeed=2900 +# Name=Intel(R) Xeon(R) Platinum 8375C CPU @ 2.90GHz +# ProcessorType=3 +# Revision=27142 + + +def get_cpu_info(run_lambda): + rc, out, err = 0, "", "" + if get_platform() == "linux": + rc, out, err = run_lambda("lscpu") + elif get_platform() == "win32": + rc, out, err = run_lambda( + 'powershell.exe "gwmi -Class Win32_Processor | Select-Object -Property Name,Manufacturer,Family,\ + Architecture,ProcessorType,DeviceID,CurrentClockSpeed,MaxClockSpeed,L2CacheSize,L2CacheSpeed,Revision\ + | ConvertTo-Json"' + ) + if rc == 0: + lst = [] + try: + obj = json.loads(out) + if type(obj) is list: + for o in obj: + lst.append("----------------------") + lst.extend([f"{k}: {v}" for (k, v) in o.items()]) + else: + lst.extend([f"{k}: {v}" for (k, v) in obj.items()]) + except ValueError as e: + lst.append(out) + lst.append(str(e)) + out = "\n".join(lst) + elif get_platform() == "darwin": + rc, out, err = run_lambda("sysctl -n machdep.cpu.brand_string") + cpu_info = "None" + if rc == 0: + cpu_info = out + else: + cpu_info = err + return cpu_info + + +def get_platform(): + if sys.platform.startswith("linux"): + return "linux" + elif sys.platform.startswith("win32"): + return "win32" + elif sys.platform.startswith("cygwin"): + return "cygwin" + elif sys.platform.startswith("darwin"): + return "darwin" + else: + return sys.platform + + +def get_mac_version(run_lambda): + return run_and_parse_first_match(run_lambda, "sw_vers -productVersion", r"(.*)") + + +def get_windows_version(run_lambda): + ret = run_and_read_all( + run_lambda, + 'powershell.exe "gwmi -Class Win32_OperatingSystem | Select-Object -Property Caption,\ + OSArchitecture,Version | ConvertTo-Json"', + ) + try: + obj = json.loads(ret) + ret = f'{obj["Caption"]} ({obj["Version"]} {obj["OSArchitecture"]})' + except ValueError as e: + ret += f"\n{str(e)}" + return ret + + +def get_lsb_version(run_lambda): + return run_and_parse_first_match( + run_lambda, "lsb_release -a", r"Description:\t(.*)" + ) + + +def check_release_file(run_lambda): + return run_and_parse_first_match( + run_lambda, "cat /etc/*-release", r'PRETTY_NAME="(.*)"' + ) + + +def get_os(run_lambda): + from platform import machine + + platform = get_platform() + + if platform in ["win32", "cygwin"]: + return get_windows_version(run_lambda) + + if platform == "darwin": + version = get_mac_version(run_lambda) + if version is None: + return None + return "macOS {} ({})".format(version, machine()) + + if platform == "linux": + # Ubuntu/Debian based + desc = get_lsb_version(run_lambda) + if desc is not None: + return "{} ({})".format(desc, machine()) + + # Try reading /etc/*-release + desc = check_release_file(run_lambda) + if desc is not None: + return "{} ({})".format(desc, machine()) + + return "{} ({})".format(platform, machine()) + + # Unknown platform + return platform + + +def get_python_platform(): + import platform + + return platform.platform() + + +def get_libc_version(): + import platform + + if get_platform() != "linux": + return "N/A" + return "-".join(platform.libc_ver()) + + +def get_pip_packages(run_lambda, patterns=None): + """Return `pip list` output. Note: will also find conda-installed pytorch and numpy packages.""" + if patterns is None: + patterns = PIP_PATTERNS + COMMON_PATTERNS + NVIDIA_PATTERNS + ONEAPI_PATTERNS + + pip_version = "pip3" if sys.version_info.major == 3 else "pip" + + os.environ["PIP_DISABLE_PIP_VERSION_CHECK"] = "1" + # People generally have pip as `pip` or `pip3` + # But here it is invoked as `python -mpip` + out = run_and_read_all( + run_lambda, [sys.executable, "-mpip", "list", "--format=freeze"] + ) + if out is None: + return pip_version, out + + filtered_out = "\n".join( + line for line in out.splitlines() if any(name in line for name in patterns) + ) + + return pip_version, filtered_out + + +def get_cachingallocator_config() -> _Dict[str, str]: + """Return the caching allocator configuration from environment variables. + """ + # pyrefly: ignore [bad-return] + return { + var: os.environ.get(var) + for var in ( + "PYTORCH_CUDA_ALLOC_CONF", + "PYTORCH_HIP_ALLOC_CONF", + "PYTORCH_ALLOC_CONF", + ) + if os.environ.get(var) + } + + +def get_cuda_module_loading_config(): + if TORCH_AVAILABLE and torch.cuda.is_available(): + torch.cuda.init() + config = os.environ.get("CUDA_MODULE_LOADING", "") + return config + else: + return "N/A" + + +def is_xnnpack_available(): + if TORCH_AVAILABLE: + import torch.backends.xnnpack + + return str(torch.backends.xnnpack.enabled) # type: ignore[attr-defined] + else: + return "N/A" + + +def get_env_info(): + """ + Collects environment information to aid in debugging. + + The returned environment information contains details on torch version, is debug build + or not, cuda compiled version, gcc version, clang version, cmake version, operating + system, libc version, python version, python platform, CUDA availability, CUDA + runtime version, CUDA module loading config, GPU model and configuration, Nvidia + driver version, cuDNN version, pip version and versions of relevant pip and + conda packages, HIP runtime version, MIOpen runtime version, + Caching allocator config, XNNPACK availability and CPU information. + + Returns: + SystemEnv (namedtuple): A tuple containing various environment details + and system information. + """ + run_lambda = run + pip_version, pip_list_output = get_pip_packages(run_lambda) + + if TORCH_AVAILABLE: + version_str = torch.__version__ + debug_mode_str = str(torch.version.debug) + cuda_available_str = str(torch.cuda.is_available()) + cuda_version_str = torch.version.cuda + xpu_available_str = str(torch.xpu.is_available()) + if torch.xpu.is_available(): + xpu_available_str = ( + f"{xpu_available_str}\n" + + f"XPU used to build PyTorch: {torch.version.xpu}\n" + + f"Intel GPU driver version:\n{get_intel_gpu_driver_version(run_lambda)}\n" + + f"Intel GPU models onboard:\n{get_intel_gpu_onboard(run_lambda)}\n" + + f"Intel GPU models detected:\n{get_intel_gpu_detected(run_lambda)}" + ) + if ( + not hasattr(torch.version, "hip") or torch.version.hip is None + ): # cuda version + hip_compiled_version = hip_runtime_version = miopen_runtime_version = "N/A" + else: # HIP version + + def get_version_or_na(cfg, prefix): + _lst = [s.rsplit(None, 1)[-1] for s in cfg if prefix in s] + return _lst[0] if _lst else "N/A" + + cfg = torch._C._show_config().split("\n") + hip_runtime_version = get_version_or_na(cfg, "HIP Runtime") + miopen_runtime_version = get_version_or_na(cfg, "MIOpen") + cuda_version_str = "N/A" + hip_compiled_version = torch.version.hip + else: + version_str = debug_mode_str = cuda_available_str = cuda_version_str = xpu_available_str = "N/A" # type: ignore[assignment] + hip_compiled_version = hip_runtime_version = miopen_runtime_version = "N/A" + + sys_version = sys.version.replace("\n", " ") + + conda_packages = get_conda_packages(run_lambda) + + return SystemEnv( + torch_version=version_str, + is_debug_build=debug_mode_str, + python_version="{} ({}-bit runtime)".format( + sys_version, sys.maxsize.bit_length() + 1 + ), + python_platform=get_python_platform(), + is_cuda_available=cuda_available_str, + cuda_compiled_version=cuda_version_str, + cuda_runtime_version=get_running_cuda_version(run_lambda), + cuda_module_loading=get_cuda_module_loading_config(), + nvidia_gpu_models=get_gpu_info(run_lambda), + nvidia_driver_version=get_nvidia_driver_version(run_lambda), + cudnn_version=get_cudnn_version(run_lambda), + is_xpu_available=xpu_available_str, + hip_compiled_version=hip_compiled_version, + hip_runtime_version=hip_runtime_version, + miopen_runtime_version=miopen_runtime_version, + pip_version=pip_version, + pip_packages=pip_list_output, + conda_packages=conda_packages, + os=get_os(run_lambda), + libc_version=get_libc_version(), + gcc_version=get_gcc_version(run_lambda), + clang_version=get_clang_version(run_lambda), + cmake_version=get_cmake_version(run_lambda), + caching_allocator_config=get_cachingallocator_config(), + is_xnnpack_available=is_xnnpack_available(), + cpu_info=get_cpu_info(run_lambda), + ) + + +env_info_fmt = """ +PyTorch version: {torch_version} +Is debug build: {is_debug_build} +CUDA used to build PyTorch: {cuda_compiled_version} +ROCM used to build PyTorch: {hip_compiled_version} + +OS: {os} +GCC version: {gcc_version} +Clang version: {clang_version} +CMake version: {cmake_version} +Libc version: {libc_version} + +Python version: {python_version} +Python platform: {python_platform} +Is CUDA available: {is_cuda_available} +CUDA runtime version: {cuda_runtime_version} +CUDA_MODULE_LOADING set to: {cuda_module_loading} +GPU models and configuration: {nvidia_gpu_models} +Nvidia driver version: {nvidia_driver_version} +cuDNN version: {cudnn_version} +Is XPU available: {is_xpu_available} +HIP runtime version: {hip_runtime_version} +MIOpen runtime version: {miopen_runtime_version} +Is XNNPACK available: {is_xnnpack_available} +Caching allocator config: {caching_allocator_config} + +CPU: +{cpu_info} + +Versions of relevant libraries: +{pip_packages} +{conda_packages} +""".strip() + + +def pretty_str(envinfo): + def replace_nones(dct, replacement="Could not collect"): + for key in dct: + if dct[key] is not None: + continue + dct[key] = replacement + return dct + + def replace_bools(dct, true="Yes", false="No"): + for key in dct: + if dct[key] is True: + dct[key] = true + elif dct[key] is False: + dct[key] = false + return dct + + def prepend(text, tag="[prepend]"): + lines = text.split("\n") + updated_lines = [tag + line for line in lines] + return "\n".join(updated_lines) + + def replace_if_empty(text, replacement="No relevant packages"): + if text is not None and len(text) == 0: + return replacement + return text + + def maybe_start_on_next_line(string): + # If `string` is multiline, prepend a \n to it. + if string is not None and len(string.split("\n")) > 1: + return "\n{}\n".format(string) + return string + + mutable_dict = envinfo._asdict() + + # If nvidia_gpu_models is multiline, start on the next line + mutable_dict["nvidia_gpu_models"] = maybe_start_on_next_line( + envinfo.nvidia_gpu_models + ) + + # If the machine doesn't have CUDA, report some fields as 'No CUDA' + dynamic_cuda_fields = [ + "cuda_runtime_version", + "nvidia_gpu_models", + "nvidia_driver_version", + ] + all_cuda_fields = dynamic_cuda_fields + ["cudnn_version"] + all_dynamic_cuda_fields_missing = all( + mutable_dict[field] is None for field in dynamic_cuda_fields + ) + if ( + TORCH_AVAILABLE + and not torch.cuda.is_available() + and all_dynamic_cuda_fields_missing + ): + for field in all_cuda_fields: + mutable_dict[field] = "No CUDA" + if envinfo.cuda_compiled_version is None: + mutable_dict["cuda_compiled_version"] = "None" + + # Replace True with Yes, False with No + mutable_dict = replace_bools(mutable_dict) + + # Replace all None objects with 'Could not collect' + mutable_dict = replace_nones(mutable_dict) + + # If either of these are '', replace with 'No relevant packages' + mutable_dict["pip_packages"] = replace_if_empty(mutable_dict["pip_packages"]) + mutable_dict["conda_packages"] = replace_if_empty(mutable_dict["conda_packages"]) + + # Tag conda and pip packages with a prefix + # If they were previously None, they'll show up as ie '[conda] Could not collect' + if mutable_dict["pip_packages"]: + mutable_dict["pip_packages"] = prepend( + mutable_dict["pip_packages"], "[{}] ".format(envinfo.pip_version) + ) + if mutable_dict["conda_packages"]: + mutable_dict["conda_packages"] = prepend( + mutable_dict["conda_packages"], "[conda] " + ) + mutable_dict["cpu_info"] = envinfo.cpu_info + mutable_dict["caching_allocator_config"] = envinfo.caching_allocator_config + if not envinfo.caching_allocator_config: + mutable_dict["caching_allocator_config"] = "N/A" + return env_info_fmt.format(**mutable_dict) + + +def get_pretty_env_info(): + """ + Returns a pretty string of environment information. + + This function retrieves environment information by calling the `get_env_info` function + and then formats the information into a human-readable string. The retrieved environment + information is listed in the document of `get_env_info`. + This function is used in `python collect_env.py` that should be executed when reporting a bug. + + Returns: + str: A pretty string of the environment information. + """ + return pretty_str(get_env_info()) + + +def main() -> None: + print("Collecting environment information...") + output = get_pretty_env_info() + print(output) + + if ( + TORCH_AVAILABLE + and hasattr(torch, "utils") + and hasattr(torch.utils, "_crash_handler") + ): + minidump_dir = torch.utils._crash_handler.DEFAULT_MINIDUMP_DIR + if sys.platform == "linux" and os.path.exists(minidump_dir): + dumps = [ + os.path.join(minidump_dir, dump) for dump in os.listdir(minidump_dir) + ] + latest = max(dumps, key=os.path.getctime) + ctime = os.path.getctime(latest) + creation_time = datetime.datetime.fromtimestamp(ctime).strftime( + "%Y-%m-%d %H:%M:%S" + ) + msg = ( + "\n*** Detected a minidump at {} created on {}, ".format( + latest, creation_time + ) + + "if this is related to your bug please include it when you file a report ***" + ) + print(msg, file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/cpp_backtrace.py b/.venv/lib/python3.12/site-packages/torch/utils/cpp_backtrace.py new file mode 100644 index 0000000000000000000000000000000000000000..af4a7fcb63e263038255359c946a6a0d4a21dbd0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/cpp_backtrace.py @@ -0,0 +1,12 @@ +# mypy: allow-untyped-defs +from torch._C import _get_cpp_backtrace + +def get_cpp_backtrace(frames_to_skip=0, maximum_number_of_frames=64) -> str: + r""" + Return a string containing the C++ stack trace of the current thread. + + Args: + frames_to_skip (int): the number of frames to skip from the top of the stack + maximum_number_of_frames (int): the maximum number of frames to return + """ + return _get_cpp_backtrace(frames_to_skip, maximum_number_of_frames) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/cpp_extension.py b/.venv/lib/python3.12/site-packages/torch/utils/cpp_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..98eeda7290218fab7d021886f6f6a7e1024fb15e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/cpp_extension.py @@ -0,0 +1,3328 @@ +# mypy: allow-untyped-defs +import copy +import glob +import importlib +import importlib.abc +import importlib.util +import os +import re +import shlex +import shutil +import setuptools +import subprocess +import sys +import sysconfig +import threading +import types +import collections +from pathlib import Path +import errno +import logging +from typing import TYPE_CHECKING + +logger = logging.getLogger(__name__) + +import torch +import torch._appdirs +from ._filelock import FileLock +from ._cpp_extension_versioner import ExtensionVersioner +from typing_extensions import deprecated +from torch.torch_version import TorchVersion, Version +from torch._utils_internal import get_file_path + + +IS_WINDOWS = sys.platform == 'win32' +IS_MACOS = sys.platform.startswith('darwin') +IS_LINUX = sys.platform.startswith('linux') +LIB_EXT = '.pyd' if IS_WINDOWS else '.so' +EXEC_EXT = '.exe' if IS_WINDOWS else '' +CLIB_PREFIX = '' if IS_WINDOWS else 'lib' +CLIB_EXT = '.dll' if IS_WINDOWS else '.so' +SHARED_FLAG = '/DLL' if IS_WINDOWS else '-shared' + +# Torch root used below to locate compiled artifacts (lib/, include/, bin/). +# Editable installs using scikit-build-core redirect mode place these in the +# installed package directory rather than the source tree this file loads +# from, so resolve it the same way torch._utils_internal does instead of from +# this file's location. +_TORCH_PATH = get_file_path("torch") +TORCH_LIB_PATH = os.path.join(_TORCH_PATH, 'lib') + + +SUBPROCESS_DECODE_ARGS = ('oem',) if IS_WINDOWS else () +MINIMUM_GCC_VERSION = (5, 0, 0) +MINIMUM_MSVC_VERSION = (19, 20, 0) + +VersionRange = tuple[tuple[int, ...], tuple[int, ...]] +VersionMap = dict[str, VersionRange] +# The following values were taken from the following GitHub gist that +# summarizes the minimum valid major versions of g++/clang++ for each supported +# CUDA version: https://gist.github.com/ax3l/9489132 +# Or from include/crt/host_config.h in the CUDA SDK +# The second value is the exclusive(!) upper bound, i.e. min <= version < max +CUDA_GCC_VERSIONS: VersionMap = { + '11.0': (MINIMUM_GCC_VERSION, (10, 0)), + '11.1': (MINIMUM_GCC_VERSION, (11, 0)), + '11.2': (MINIMUM_GCC_VERSION, (11, 0)), + '11.3': (MINIMUM_GCC_VERSION, (11, 0)), + '11.4': ((6, 0, 0), (12, 0)), + '11.5': ((6, 0, 0), (12, 0)), + '11.6': ((6, 0, 0), (12, 0)), + '11.7': ((6, 0, 0), (12, 0)), + '12.0': ((6, 0, 0), (13, 0)), + '12.1': ((6, 0, 0), (13, 0)), + '12.2': ((6, 0, 0), (13, 0)), + '12.3': ((6, 0, 0), (14, 0)), + '12.4': ((6, 0, 0), (14, 0)), + '12.5': ((6, 0, 0), (14, 0)), + '12.6': ((6, 0, 0), (14, 0)), + '12.7': ((6, 0, 0), (14, 0)), + '12.8': ((6, 0, 0), (15, 0)), + '12.9': ((6, 0, 0), (15, 0)), + '13.0': ((6, 0, 0), (16, 0)), +} + +MINIMUM_CLANG_VERSION = (3, 3, 0) +CUDA_CLANG_VERSIONS: VersionMap = { + '11.1': (MINIMUM_CLANG_VERSION, (11, 0)), + '11.2': (MINIMUM_CLANG_VERSION, (12, 0)), + '11.3': (MINIMUM_CLANG_VERSION, (12, 0)), + '11.4': (MINIMUM_CLANG_VERSION, (13, 0)), + '11.5': (MINIMUM_CLANG_VERSION, (13, 0)), + '11.6': (MINIMUM_CLANG_VERSION, (14, 0)), + '11.7': (MINIMUM_CLANG_VERSION, (14, 0)), + '12.0': ((7, 0), (15, 0)), + '12.1': ((7, 0), (15, 0)), + '12.2': ((7, 0), (16, 0)), + '12.3': ((7, 0), (16, 0)), + '12.4': ((7, 0), (17, 0)), + '12.5': ((7, 0), (18, 0)), + '12.6': ((7, 0), (18, 0)), + '12.7': ((7, 0), (19, 0)), + '12.8': ((7, 0), (19, 0)), + '12.9': ((7, 0), (19, 0)), + '13.0': ((7, 0), (21, 0)), +} + +__all__ = ["get_default_build_root", "check_compiler_ok_for_platform", "get_compiler_abi_compatibility_and_version", "BuildExtension", # noqa: F822, RUF100 + "CppExtension", "CUDAExtension", "SyclExtension", "include_paths", "library_paths", "load", "load_inline", "is_ninja_available", + "verify_ninja_availability", "remove_extension_h_precompiler_headers", "get_cxx_compiler", "check_compiler_is_gcc"] + +# setuptools.command.build_ext imports Cython when available, so keep it off the +# cpp_extension import path until BuildExtension is explicitly requested. +_BUILD_EXTENSION_CLASS = None +_BUILD_EXTENSION_BASE_INITIALIZED = False +_BUILD_EXTENSION_LOCK = threading.Lock() + + +if TYPE_CHECKING: + from setuptools.command.build_ext import build_ext as _LazyBuildExt +else: + class _LazyBuildExt(setuptools.Command): + pass + + +def _get_build_extension(): + global _BUILD_EXTENSION_BASE_INITIALIZED + build_extension = _BUILD_EXTENSION_CLASS + if build_extension is None: + raise RuntimeError("BuildExtension class is not initialized") + if not _BUILD_EXTENSION_BASE_INITIALIZED: + with _BUILD_EXTENSION_LOCK: + if not _BUILD_EXTENSION_BASE_INITIALIZED: + from setuptools.command.build_ext import build_ext + + build_extension.__bases__ = (build_ext,) + globals()["BuildExtension"] = build_extension + _BUILD_EXTENSION_BASE_INITIALIZED = True + return build_extension + + +def __getattr__(name): + if name == "BuildExtension": + return _get_build_extension() + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +# Taken directly from python stdlib < 3.9 +# See https://github.com/pytorch/pytorch/issues/48617 +def _nt_quote_args(args: list[str] | None) -> list[str]: + """Quote command-line arguments for DOS/Windows conventions. + + Just wraps every argument which contains blanks in double quotes, and + returns a new argument list. + """ + # Cover None-type + if not args: + return [] + return [f'"{arg}"' if ' ' in arg else arg for arg in args] + +def _find_cuda_home() -> str | None: + """Find the CUDA install path.""" + # Guess #1 + cuda_home = os.environ.get('CUDA_HOME') or os.environ.get('CUDA_PATH') + if cuda_home is None: + # Guess #2 + nvcc_path = shutil.which("nvcc") + if nvcc_path is not None: + cuda_home = os.path.dirname(os.path.dirname(nvcc_path)) + else: + # Guess #3 + if IS_WINDOWS: + cuda_homes = glob.glob( + 'C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v*.*') + if len(cuda_homes) == 0: + cuda_home = '' + else: + cuda_home = cuda_homes[0] + else: + cuda_home = '/usr/local/cuda' + if not os.path.exists(cuda_home): + cuda_home = None + if cuda_home and not torch.cuda.is_available(): + logger.warning("No CUDA runtime is found, using CUDA_HOME='%s'", cuda_home) + return cuda_home + +def _find_rocm_home() -> str | None: + """Find the ROCm install path.""" + # Guess #1 + rocm_home = os.environ.get('ROCM_HOME') or os.environ.get('ROCM_PATH') + if rocm_home is None: + # Guess #2: Support for ROCm distribution from TheRock + # rocm-sdk-core installs everything under /_rocm_sdk_core + # (include/, lib/, bin/, ...), so the module's own location is the + # ROCM_HOME we want. Use find_spec to locate it without importing. + spec = importlib.util.find_spec('_rocm_sdk_core') + if spec is not None and spec.origin is not None: + rocm_home = str(Path(spec.origin).parent.resolve()) + if rocm_home is None: + # Guess #3 + hipcc_path = shutil.which('hipcc') + if hipcc_path is not None: + rocm_home = os.path.dirname(os.path.dirname( + os.path.realpath(hipcc_path))) + # can be either /hip/bin/hipcc or /bin/hipcc + if os.path.basename(rocm_home) == 'hip': + rocm_home = os.path.dirname(rocm_home) + else: + # Guess #4 + fallback_path = '/opt/rocm' + if os.path.exists(fallback_path): + rocm_home = fallback_path + if rocm_home and torch.version.hip is None: + logger.warning("No ROCm runtime is found, using ROCM_HOME='%s'", rocm_home) + return rocm_home + +def _find_sycl_home() -> str | None: + sycl_home = None + icpx_path = shutil.which('icpx') + # Guess 1: for source code build developer/user, we'll have icpx in PATH, + # which will tell us the SYCL_HOME location. + if icpx_path is not None: + sycl_home = os.path.dirname(os.path.dirname( + os.path.realpath(icpx_path))) + + # Guess 2: for users install Pytorch with XPU support, the sycl runtime is + # inside intel-sycl-rt, which is automatically installed via pip dependency. + else: + try: + files = importlib.metadata.files('intel-sycl-rt') or [] + for f in files: + if f.name == "libsycl.so": + sycl_home = os.path.dirname(Path(f.locate()).parent.resolve()) + break + except importlib.metadata.PackageNotFoundError: + logger.warning("Trying to find SYCL_HOME from intel-sycl-rt package, but it is not installed.") + return sycl_home + +def _join_rocm_home(*paths) -> str: + """ + Join paths with ROCM_HOME, or raises an error if it ROCM_HOME is not set. + + This is basically a lazy way of raising an error for missing $ROCM_HOME + only once we need to get any ROCm-specific path. + """ + if ROCM_HOME is None: + raise OSError('ROCM_HOME environment variable is not set. ' + 'Please set it to your ROCm install root.') + return os.path.join(ROCM_HOME, *paths) + +def _join_sycl_home(*paths) -> str: + """ + Join paths with SYCL_HOME, or raises an error if it SYCL_HOME is not found. + + This is basically a lazy way of raising an error for missing SYCL_HOME + only once we need to get any SYCL-specific path. + """ + if SYCL_HOME is None: + raise OSError('SYCL runtime is not detected. Please setup the pytorch ' + 'prerequisites for Intel GPU following the instruction in ' + 'https://github.com/pytorch/pytorch?tab=readme-ov-file#intel-gpu-support ' + 'or install intel-sycl-rt via pip.') + + return os.path.join(SYCL_HOME, *paths) + + + +def _wrap_compiler(compiler: str | list[str]) -> list[str]: + """Prepend a compiler wrapper (ccache/sccache) if available. + + Accepts a compiler as a string or list. Always returns a list with the + wrapper prepended, or the original value as a list if no wrapper is found. + Disabled when TORCH_NO_COMPILER_WRAPPER is set. + """ + if isinstance(compiler, str): + compiler = [compiler] + # hipcc with ccache/sccache is currently broken + # I.e. compilation fails with + # sccache: caused by: Compiler not supported: "sh: 1: /usr/local/cuda/bin/nvcc: not found\n + # sh: 1: nvcc: not found\nDevice not supported - Defaulting to AMD\n + # failed to execute:/opt/rocm/lib/llvm/bin/clang++ -O3 -E -x c /tmp/sccachei1cosZ/testfile.c\n" + if os.environ.get('TORCH_NO_COMPILER_WRAPPER') or IS_WINDOWS or torch.version.hip is not None: + return compiler + for wrapper in ('ccache', 'sccache'): + if shutil.which(wrapper): + return [wrapper] + compiler + return compiler + + +def _windows_quote(arg: str) -> str: + """Quote a single argument per the MSVC ``CommandLineToArgvW`` rules.""" + if arg and not any(c in arg for c in ' \t\n\v"'): + return arg + out = ['"'] + backslashes = 0 + for c in arg: + if c == '\\': + backslashes += 1 + continue + if c == '"': + out.append('\\' * (2 * backslashes + 1)) + out.append('"') + else: + out.append('\\' * backslashes) + out.append(c) + backslashes = 0 + out.append('\\' * (2 * backslashes)) + out.append('"') + return ''.join(out) + + +def _shell_join(cmd: list[str]) -> str: + """Quote and join ``cmd`` for the current platform's shell. + + ``shlex.join`` produces POSIX-style quoting which ninja does not parse + correctly on Windows for paths like ``C:\\Program Files\\...``. + """ + if IS_WINDOWS: + return ' '.join(_windows_quote(a) for a in cmd) + return shlex.join(cmd) + + +ABI_INCOMPATIBILITY_WARNING = ( + " !! WARNING !!" + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" + "Your compiler (%s) may be ABI-incompatible with PyTorch!" + "Please use a compiler that is ABI-compatible with GCC 5.0 and above." + "See https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html." + "See https://gist.github.com/goldsborough/d466f43e8ffc948ff92de7486c5216d6" + "for instructions on how to install GCC 5 or higher." + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" + " !! WARNING !!" +) +WRONG_COMPILER_WARNING = ( + " !! WARNING !!" + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" + "Your compiler (%s) is not compatible with the compiler Pytorch was" + "built with for this platform, which is %s on %s. Please" + "use %s to compile your extension. Alternatively, you may" + "compile PyTorch from source using %s, and then you can also use" + "%s to compile your extension." + "See https://github.com/pytorch/pytorch/blob/master/CONTRIBUTING.md for help" + "with compiling PyTorch from source." + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" + " !! WARNING !!" +) +CUDA_MISMATCH_MESSAGE = ( + "The detected CUDA version (%s) mismatches the version that was used to compile" + "PyTorch (%s). Please make sure to use the same CUDA versions." +) +CUDA_MISMATCH_WARN = ( + "The detected CUDA version (%s) has a minor version mismatch with the version that was used to compile PyTorch (%s). Most likely this shouldn't be a problem." +) +CUDA_NOT_FOUND_MESSAGE = ( + "CUDA was not found on the system, please set the CUDA_HOME or the CUDA_PATH" + "environment variable or add NVCC to your system PATH. The extension compilation will fail." +) +ROCM_HOME = _find_rocm_home() if (torch.cuda._is_compiled() and torch.version.hip) else None +HIP_HOME = _join_rocm_home('hip') if ROCM_HOME else None +IS_HIP_EXTENSION = bool(ROCM_HOME is not None and torch.version.hip is not None) +ROCM_VERSION = None +if torch.version.hip is not None: + ROCM_VERSION = tuple(int(v) for v in torch.version.hip.split('.')[:2]) + +CUDA_HOME = _find_cuda_home() if (torch.cuda._is_compiled() and torch.version.cuda) else None +CUDNN_HOME = os.environ.get('CUDNN_HOME') or os.environ.get('CUDNN_PATH') +SYCL_HOME = _find_sycl_home() if torch.xpu._is_compiled() else None +WINDOWS_CUDA_HOME = os.environ.get('WINDOWS_CUDA_HOME') # used for AOTI cross-compilation + +# PyTorch releases have the version pattern major.minor.patch, whereas when +# PyTorch is built from source, we append the git commit hash, which gives +# it the below pattern. +BUILT_FROM_SOURCE_VERSION_PATTERN = re.compile(r'\d+\.\d+\.\d+\w+\+\w+') + +COMMON_MSVC_FLAGS = ['/MD', '/wd4819', '/wd4251', '/wd4244', '/wd4267', '/wd4275', '/wd4018', '/wd4190', '/wd4624', '/wd4067', '/wd4068', '/EHsc'] + +MSVC_IGNORE_CUDAFE_WARNINGS = [ + 'base_class_has_different_dll_interface', + 'field_without_dll_interface', + 'dll_interface_conflict_none_assumed', + 'dll_interface_conflict_dllexport_assumed' +] + +COMMON_NVCC_FLAGS = [ + '-D__CUDA_NO_HALF_OPERATORS__', + '-D__CUDA_NO_HALF_CONVERSIONS__', + '-D__CUDA_NO_BFLOAT16_CONVERSIONS__', + '-D__CUDA_NO_HALF2_OPERATORS__', + '--expt-relaxed-constexpr' +] + +COMMON_HIP_FLAGS = [ + '-D__HIP_PLATFORM_AMD__=1', + '-DUSE_ROCM=1', + '-DHIPBLAS_V2', +] + +if not IS_WINDOWS: + COMMON_HIP_FLAGS.append('-fPIC') + +COMMON_HIPCC_FLAGS = [ + '-DCUDA_HAS_FP16=1', + '-D__HIP_NO_HALF_OPERATORS__=1', + '-D__HIP_NO_HALF_CONVERSIONS__=1', + '-DHIP_ENABLE_WARP_SYNC_BUILTINS=1' +] + +if IS_WINDOWS: + # Compatibility flags, similar to those set in cmake/Dependencies.cmake. + COMMON_HIPCC_FLAGS.append('-fms-extensions') + # Suppress warnings about dllexport. + COMMON_HIPCC_FLAGS.append('-Wno-ignored-attributes') + + +def _get_icpx_version() -> str: + icpx = 'icx' if IS_WINDOWS else 'icpx' + compiler_info = subprocess.check_output([icpx, '--version']) + match = re.search(r'(\d+)\.(\d+)\.(\d+)', compiler_info.decode().strip()) + version = ['0', '0', '0'] if match is None else list(match.groups()) + version = list(map(int, version)) + if len(version) != 3: + raise AssertionError("Failed to parse DPC++ compiler version") + # Aligning version format with what torch.version.xpu() returns + return f"{version[0]}{version[1]:02}{version[2]:02}" + + +def _get_sycl_arch_list(): + if 'TORCH_XPU_ARCH_LIST' in os.environ: + return os.environ.get('TORCH_XPU_ARCH_LIST') + arch_list = torch.xpu.get_arch_list() + # Dropping dg2* archs since they lack hardware support for fp64 and require + # special consideration from the user. If needed these platforms can + # be requested thru TORCH_XPU_ARCH_LIST environment variable. + arch_list = [x for x in arch_list if not x.startswith('dg2')] + return ','.join(arch_list) + + +# If arch list returned by _get_sycl_arch_list() is empty, then sycl kernels will be compiled +# for default spir64 target and avoid device specific compilations entirely. Further, kernels +# will be JIT compiled at runtime. +def _append_sycl_targets_if_missing(cflags) -> None: + if any(flag.startswith('-fsycl-targets=') for flag in cflags): + # do nothing: user has manually specified sycl targets + return + if _get_sycl_arch_list() != '': + # AOT (spir64_gen) + JIT (spir64) + cflags.append('-fsycl-targets=spir64_gen,spir64') + else: + # JIT (spir64) + cflags.append('-fsycl-targets=spir64') + +def _get_sycl_device_flags(cflags): + # We need last occurrence of -fsycl-targets as it will be the one taking effect. + # So searching in reversed list. + flags = [f for f in reversed(cflags) if f.startswith('-fsycl-targets=')] + if not flags: + raise AssertionError("bug: -fsycl-targets should have been amended to cflags") + + arch_list = _get_sycl_arch_list() + if arch_list != '': + flags += [f'-Xs "-device {arch_list}"'] + return flags + +_COMMON_SYCL_FLAGS = [ + '-fsycl', +] + +_SYCL_DLINK_FLAGS = [ + *_COMMON_SYCL_FLAGS, + '-fsycl-link', + '--offload-compress', +] + +JIT_EXTENSION_VERSIONER = ExtensionVersioner() + +PLAT_TO_VCVARS = { + 'win32' : 'x86', + 'win-amd64' : 'x86_amd64', +} + +min_supported_cpython = "0x030A0000" # Python 3.10 hexcode + +def get_cxx_compiler(): + if IS_WINDOWS: + compiler = os.environ.get('CXX', 'cl') + else: + compiler = os.environ.get('CXX', 'c++') + return compiler + +def _is_binary_build() -> bool: + return not BUILT_FROM_SOURCE_VERSION_PATTERN.match(torch.version.__version__) + + +def _accepted_compilers_for_platform() -> list[str]: + # gnu-c++ and gnu-cc are the conda gcc compilers + return ['clang++', 'clang'] if IS_MACOS else ['g++', 'gcc', 'gnu-c++', 'gnu-cc', 'clang++', 'clang'] + +def _maybe_write(filename, new_content) -> None: + r''' + Equivalent to writing the content into the file but will not touch the file + if it already had the right content (to avoid triggering recompile). + ''' + if os.path.exists(filename): + with open(filename) as f: + content = f.read() + + if content == new_content: + # The file already contains the right thing! + return + + with open(filename, 'w') as source_file: + source_file.write(new_content) + +def get_default_build_root() -> str: + """ + Return the path to the root folder under which extensions will built. + + For each extension module built, there will be one folder underneath the + folder returned by this function. For example, if ``p`` is the path + returned by this function and ``ext`` the name of an extension, the build + folder for the extension will be ``p/ext``. + + This directory is **user-specific** so that multiple users on the same + machine won't meet permission issues. + """ + return os.path.realpath(torch._appdirs.user_cache_dir(appname='torch_extensions')) + + +def check_compiler_ok_for_platform(compiler: str) -> bool: + """ + Verify that the compiler is the expected one for the current platform. + + Args: + compiler (str): The compiler executable to check. + + Returns: + True if the compiler is gcc/g++ on Linux or clang/clang++ on macOS, + and always True for Windows. + """ + if IS_WINDOWS: + return True + compiler_path = shutil.which(compiler) + if compiler_path is None: + return False + # Use os.path.realpath to resolve any symlinks, in particular from 'c++' to e.g. 'g++'. + compiler_path = os.path.realpath(compiler_path) + # Check the compiler name + if any(name in compiler_path for name in _accepted_compilers_for_platform()): + return True + # If compiler wrapper is used try to infer the actual compiler by invoking it with -v flag + env = os.environ.copy() + env['LC_ALL'] = 'C' # Don't localize output + try: + version_string = subprocess.check_output([compiler, '-v'], stderr=subprocess.STDOUT, env=env).decode(*SUBPROCESS_DECODE_ARGS) + except subprocess.CalledProcessError: + # If '-v' fails, try '--version' + version_string = subprocess.check_output([compiler, '--version'], stderr=subprocess.STDOUT, env=env).decode(*SUBPROCESS_DECODE_ARGS) + if IS_LINUX: + # Check for 'gcc' or 'g++' for sccache wrapper + pattern = re.compile("^COLLECT_GCC=(.*)$", re.MULTILINE) + results = re.findall(pattern, version_string) + if len(results) != 1: + # Clang is also a supported compiler on Linux + # Though on Ubuntu it's sometimes called "Ubuntu clang version" + return 'clang version' in version_string + compiler_path = os.path.realpath(results[0].strip()) + # On RHEL/CentOS c++ is a gcc compiler wrapper + if os.path.basename(compiler_path) == 'c++' and 'gcc version' in version_string: + return True + return any(name in compiler_path for name in _accepted_compilers_for_platform()) + if IS_MACOS: + # Check for 'clang' or 'clang++' + return version_string.startswith("Apple clang") + return False + + +def get_compiler_abi_compatibility_and_version(compiler) -> tuple[bool, TorchVersion]: + """ + Determine if the given compiler is ABI-compatible with PyTorch alongside its version. + + Args: + compiler (str): The compiler executable name to check (e.g. ``g++``). + Must be executable in a shell process. + + Returns: + A tuple that contains a boolean that defines if the compiler is (likely) ABI-incompatible with PyTorch, + followed by a `TorchVersion` string that contains the compiler version separated by dots. + """ + if not _is_binary_build(): + return (True, TorchVersion('0.0.0')) + if os.environ.get('TORCH_DONT_CHECK_COMPILER_ABI') in ['ON', '1', 'YES', 'TRUE', 'Y']: + return (True, TorchVersion('0.0.0')) + + # First check if the compiler is one of the expected ones for the particular platform. + if not check_compiler_ok_for_platform(compiler): + logger.warning(WRONG_COMPILER_WARNING, compiler, _accepted_compilers_for_platform()[0], sys.platform, _accepted_compilers_for_platform()[0], compiler, compiler) + return (False, TorchVersion('0.0.0')) + + if IS_MACOS: + # There is no particular minimum version we need for clang, so we're good here. + return (True, TorchVersion('0.0.0')) + try: + if IS_LINUX: + minimum_required_version = MINIMUM_GCC_VERSION + compiler_info = subprocess.check_output([compiler, '-dumpfullversion', '-dumpversion']) + else: + minimum_required_version = MINIMUM_MSVC_VERSION + compiler_info = subprocess.check_output(compiler, stderr=subprocess.STDOUT) + match = re.search(r'(\d+)\.(\d+)\.(\d+)', compiler_info.decode(*SUBPROCESS_DECODE_ARGS).strip()) + version = ['0', '0', '0'] if match is None else list(match.groups()) + except (subprocess.CalledProcessError, OSError): + logger.warning('Error checking compiler version for %s', compiler, exc_info=True) + return (False, TorchVersion('0.0.0')) + + # convert alphanumeric string to numeric string + # amdclang++ returns str like 0.0.0git, others return 0.0.0 + numeric_version = [re.sub(r'\D', '', v) for v in version] + + if tuple(map(int, numeric_version)) >= minimum_required_version: + return (True, TorchVersion('.'.join(numeric_version))) + + compiler = f'{compiler} {".".join(numeric_version)}' + logger.warning(ABI_INCOMPATIBILITY_WARNING, compiler) + + return (False, TorchVersion('.'.join(numeric_version))) + + +def _check_cuda_version(compiler_name: str, compiler_version: TorchVersion) -> None: + if not CUDA_HOME: + raise RuntimeError(CUDA_NOT_FOUND_MESSAGE) + + nvcc = os.path.join(CUDA_HOME, 'bin', 'nvcc.exe' if IS_WINDOWS else 'nvcc') + if not os.path.exists(nvcc): + raise FileNotFoundError(f"nvcc not found at '{nvcc}'. Ensure CUDA path '{CUDA_HOME}' is correct.") + + cuda_version_str = subprocess.check_output([nvcc, '--version']).strip().decode(*SUBPROCESS_DECODE_ARGS) + cuda_version = re.search(r'release (\d+[.]\d+)', cuda_version_str) + if cuda_version is None: + return + + cuda_str_version = cuda_version.group(1) + cuda_ver = Version(cuda_str_version) + if torch.version.cuda is None: + return + + torch_cuda_version = Version(torch.version.cuda) + if cuda_ver != torch_cuda_version: + # major/minor attributes are only available in setuptools>=49.4.0 + if getattr(cuda_ver, "major", None) is None: + raise ValueError("setuptools>=49.4.0 is required") + if cuda_ver.major != torch_cuda_version.major: + raise RuntimeError(CUDA_MISMATCH_MESSAGE, cuda_str_version, torch.version.cuda) + logger.warning(CUDA_MISMATCH_WARN, cuda_str_version, torch.version.cuda) + + if not (sys.platform.startswith('linux') and + os.environ.get('TORCH_DONT_CHECK_COMPILER_ABI') not in ['ON', '1', 'YES', 'TRUE', 'Y'] and + _is_binary_build()): + return + + cuda_compiler_bounds: VersionMap = CUDA_CLANG_VERSIONS if compiler_name.startswith('clang') else CUDA_GCC_VERSIONS + + if cuda_str_version not in cuda_compiler_bounds: + logger.warning('There are no %s version bounds defined for CUDA version %s', compiler_name, cuda_str_version) + else: + min_compiler_version, max_excl_compiler_version = cuda_compiler_bounds[cuda_str_version] + # Special case for 11.4.0, which has lower compiler bounds than 11.4.1 + if "V11.4.48" in cuda_version_str and cuda_compiler_bounds == CUDA_GCC_VERSIONS: + max_excl_compiler_version = (11, 0) + min_compiler_version_str = '.'.join(map(str, min_compiler_version)) + max_excl_compiler_version_str = '.'.join(map(str, max_excl_compiler_version)) + + version_bound_str = f'>={min_compiler_version_str}, <{max_excl_compiler_version_str}' + + if compiler_version < TorchVersion(min_compiler_version_str): + raise RuntimeError( + f'The current installed version of {compiler_name} ({compiler_version}) is less ' + f'than the minimum required version by CUDA {cuda_str_version} ({min_compiler_version_str}). ' + f'Please make sure to use an adequate version of {compiler_name} ({version_bound_str}).' + ) + if compiler_version >= TorchVersion(max_excl_compiler_version_str): + raise RuntimeError( + f'The current installed version of {compiler_name} ({compiler_version}) is greater ' + f'than the maximum required version by CUDA {cuda_str_version}. ' + f'Please make sure to use an adequate version of {compiler_name} ({version_bound_str}).' + ) + + +# Specify Visual Studio C runtime library for hipcc +def _set_hipcc_runtime_lib(is_standalone, debug) -> None: + if is_standalone: + if debug: + COMMON_HIP_FLAGS.append('-fms-runtime-lib=static_dbg') + else: + COMMON_HIP_FLAGS.append('-fms-runtime-lib=static') + else: + if debug: + COMMON_HIP_FLAGS.append('-fms-runtime-lib=dll_dbg') + else: + COMMON_HIP_FLAGS.append('-fms-runtime-lib=dll') + +def _append_sycl_std_if_no_std_present(cflags) -> None: + if not any(flag.startswith('-sycl-std=') for flag in cflags): + cflags.append('-sycl-std=2020') + + +def _wrap_sycl_host_flags(cflags): + host_cflags = [] + host_cxx = get_cxx_compiler() + if IS_WINDOWS: + for flag in cflags: + if flag.startswith("-I"): + flag = flag.replace("\\", "\\\\").replace("-I", "/I") + else: + flag = flag.replace("-D", "/D") + flag = flag.replace('"', '\\"') + host_cflags.append(flag) + joined_host_cflags = ' '.join(host_cflags) + + external_include = _join_sycl_home("include").replace("\\", "\\\\") + + # Some versions of DPC++ compiler pass paths to SYCL headers as user include paths (`-I`) rather + # than system paths (`-isystem`). This makes host compiler to report warnings encountered in the + # SYCL headers, such as deprecated warnings, even if warned API is not actually used in the program. + # We expect that this issue will be addressed in the later version of DPC++ compiler. To workaround the + # issue now we wrap paths to SYCL headers in `/external:I`. Warning free compilation is especially important + # for Windows build as `/sdl` compilation flag assumes that and we will fail compilation otherwise. + wrapped_host_cflags = [ + f"-fsycl-host-compiler={host_cxx}", + f'-fsycl-host-compiler-options="\\"/external:I{external_include}\\" /external:W0 {joined_host_cflags}"', + ] + else: + joined_host_cflags = ' '.join(cflags) + wrapped_host_cflags = [ + f"-fsycl-host-compiler={host_cxx}", + shlex.quote(f"-fsycl-host-compiler-options={joined_host_cflags}"), + ] + return wrapped_host_cflags + + +class BuildExtension(_LazyBuildExt): + """ + A custom :mod:`setuptools` build extension . + + This :class:`setuptools.build_ext` subclass takes care of passing the + minimum required compiler flags (e.g. ``-std=c++20``) as well as mixed + C++/CUDA/SYCL compilation (and support for CUDA/SYCL files in general). + + When using :class:`BuildExtension`, it is allowed to supply a dictionary + for ``extra_compile_args`` (rather than the usual list) that maps from + languages/compilers (the only expected values are ``cxx``, ``nvcc`` or + ``sycl``) to a list of additional compiler flags to supply to the compiler. + This makes it possible to supply different flags to the C++, CUDA and SYCL + compiler during mixed compilation. + + ``use_ninja`` (bool): If ``use_ninja`` is ``True`` (default), then we + attempt to build using the Ninja backend. Ninja greatly speeds up + compilation compared to the standard ``setuptools.build_ext``. + Fallbacks to the standard distutils backend if Ninja is not available. + + .. note:: + By default, the Ninja backend uses #CPUS + 2 workers to build the + extension. This may use up too many resources on some systems. One + can control the number of workers by setting the `MAX_JOBS` environment + variable to a non-negative number. + """ + + @classmethod + def with_options(cls, **options): + """Return a subclass with alternative constructor that extends any original keyword arguments to the original constructor with the given options.""" + class cls_with_options(cls): # type: ignore[misc, valid-type] + def __init__(self, *args, **kwargs) -> None: + kwargs.update(options) + super().__init__(*args, **kwargs) + + return cls_with_options + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + self.no_python_abi_suffix = kwargs.get("no_python_abi_suffix", False) + + self.use_ninja = kwargs.get('use_ninja', True) + if self.use_ninja: + # Test if we can use ninja. Fallback otherwise. + msg = ('Attempted to use ninja as the BuildExtension backend but ' + '%s. Falling back to using the slow distutils backend.') + if not is_ninja_available(): + logger.warning(msg, 'we could not find ninja.') + self.use_ninja = False + + def finalize_options(self) -> None: + super().finalize_options() + if self.use_ninja: + self.force = True + + def build_extensions(self) -> None: + compiler_name, compiler_version = self._check_abi() + + cuda_ext = False + sycl_ext = False + extension_iter = iter(self.extensions) + extension = next(extension_iter, None) + while not (cuda_ext and sycl_ext) and extension: + for source in extension.sources: + _, ext = os.path.splitext(source) + if ext == '.cu': + cuda_ext = True + elif ext == '.sycl': + sycl_ext = True + + # This check accounts on a case when cuda and sycl sources + # are mixed in the same extension. We can stop checking + # sources if both are found or there is no more sources. + if cuda_ext and sycl_ext: + break + + extension = next(extension_iter, None) + + if sycl_ext: + if not self.use_ninja: + raise AssertionError("ninja is required to build sycl extensions.") + + if cuda_ext and not IS_HIP_EXTENSION: + _check_cuda_version(compiler_name, compiler_version) + + for extension in self.extensions: + # Ensure at least an empty list of flags for 'cxx', 'nvcc' and 'sycl' when + # extra_compile_args is a dict. Otherwise, default torch flags do + # not get passed. Necessary when only one of 'cxx', 'nvcc' or 'sycl' is + # passed to extra_compile_args in CUDAExtension or SyclExtension, i.e. + # CUDAExtension(..., extra_compile_args={'cxx': [...]}) + # or + # CUDAExtension(..., extra_compile_args={'nvcc': [...]}) + if isinstance(extension.extra_compile_args, dict): + for ext in ['cxx', 'nvcc', 'sycl']: + if ext not in extension.extra_compile_args: + extension.extra_compile_args[ext] = [] + + self._add_compile_flag(extension, '-DTORCH_API_INCLUDE_EXTENSION_H') + + if IS_HIP_EXTENSION: + self._hipify_compile_flags(extension) + + if extension.py_limited_api: + # compile any extension that has passed in py_limited_api to the + # Extension constructor with the Py_LIMITED_API flag set to our + # min supported CPython version. + # See https://docs.python.org/3/c-api/stable.html#c.Py_LIMITED_API + self._add_compile_flag(extension, f'-DPy_LIMITED_API={min_supported_cpython}') + self._define_torch_extension_name(extension) + + if 'nvcc_dlink' in extension.extra_compile_args: + if not self.use_ninja: + raise AssertionError( + f"With dlink=True, ninja is required to build cuda extension {extension.name}." + ) + + # Register .cu, .cuh, .hip, .mm and .sycl as valid source extensions. + # NOTE: At the moment .sycl is not a standard extension for SYCL supported + # by compiler. Here we introduce a torch level convention that SYCL sources + # should have .sycl file extension. + self.compiler.src_extensions += ['.cu', '.cuh', '.hip', '.sycl'] + if torch.backends.mps.is_built(): + self.compiler.src_extensions += ['.mm'] + # Save the original _compile method for later. + if self.compiler.compiler_type == 'msvc': + self.compiler._cpp_extensions += ['.cu', '.cuh', '.hip'] + original_compile = self.compiler.compile + original_spawn = self.compiler.spawn + else: + original_compile = self.compiler._compile + + def append_std17_if_no_std_present(cflags) -> None: + # NVCC does not allow multiple -std to be passed, so we avoid + # overriding the option if the user explicitly passed it. + cpp_format_prefix = '/{}:' if self.compiler.compiler_type == 'msvc' else '-{}=' + cpp_flag_prefix = cpp_format_prefix.format('std') + cpp_flag = cpp_flag_prefix + 'c++20' + if not any(flag.startswith(cpp_flag_prefix) for flag in cflags): + cflags.append(cpp_flag) + + def unix_cuda_flags(cflags): + cflags = (COMMON_NVCC_FLAGS + + ['--compiler-options', "'-fPIC'"] + + cflags + _get_cuda_arch_flags(cflags)) + + # NVCC does not allow multiple -ccbin/--compiler-bindir to be passed, so we avoid + # overriding the option if the user explicitly passed it. + _ccbin = os.getenv("CC") + if ( + _ccbin is not None + and not any(flag.startswith(('-ccbin', '--compiler-bindir')) for flag in cflags) + ): + cflags.extend(['-ccbin', _ccbin]) + + return cflags + + def convert_to_absolute_paths_inplace(paths) -> None: + # Helper function. See Note [Absolute include_dirs] + if paths is not None: + for i in range(len(paths)): + if not os.path.isabs(paths[i]): + paths[i] = os.path.abspath(paths[i]) + + def unix_wrap_single_compile(obj, src, ext, cc_args, extra_postargs, pp_opts) -> None: + # Copy before we make any modifications. + cflags = copy.deepcopy(extra_postargs) + try: + original_compiler = self.compiler.compiler_so + if _is_cuda_file(src): + nvcc = [_join_rocm_home('bin', 'hipcc') if IS_HIP_EXTENSION else _join_cuda_home('bin', 'nvcc')] + self.compiler.set_executable('compiler_so', _wrap_compiler(nvcc)) + if isinstance(cflags, dict): + cflags = cflags['nvcc'] + if IS_HIP_EXTENSION: + cflags = COMMON_HIPCC_FLAGS + cflags + _get_rocm_arch_flags(cflags) + else: + cflags = unix_cuda_flags(cflags) + else: + self.compiler.set_executable('compiler_so', _wrap_compiler(list(original_compiler))) + if isinstance(cflags, dict): + cflags = cflags['cxx'] + if IS_HIP_EXTENSION: + cflags = COMMON_HIP_FLAGS + cflags + append_std17_if_no_std_present(cflags) + + original_compile(obj, src, ext, cc_args, cflags, pp_opts) + finally: + # Put the original compiler back in place. + self.compiler.set_executable('compiler_so', original_compiler) + + def unix_wrap_ninja_compile(sources, + output_dir=None, + macros=None, + include_dirs=None, + debug=0, + extra_preargs=None, + extra_postargs=None, + depends=None): + r"""Compiles sources by outputting a ninja file and running it.""" + # NB: I copied some lines from self.compiler (which is an instance + # of distutils.UnixCCompiler). See the following link. + # https://github.com/python/cpython/blob/f03a8f8d5001963ad5b5b28dbd95497e9cc15596/Lib/distutils/ccompiler.py#L564-L567 # codespell:ignore + # This can be fragile, but a lot of other repos also do this + # (see https://github.com/search?q=_setup_compile&type=Code) + # so it is probably OK; we'll also get CI signal if/when + # we update our python version (which is when distutils can be + # upgraded) + + # Use absolute path for output_dir so that the object file paths + # (`objects`) get generated with absolute paths. + # pyrefly: ignore [no-matching-overload] + output_dir = os.path.abspath(output_dir) + + # See Note [Absolute include_dirs] + convert_to_absolute_paths_inplace(self.compiler.include_dirs) + + _, objects, extra_postargs, pp_opts, _ = \ + self.compiler._setup_compile(output_dir, macros, + include_dirs, sources, + depends, extra_postargs) + common_cflags = self.compiler._get_cc_args(pp_opts, debug, extra_preargs) + extra_cc_cflags = self.compiler.compiler_so[1:] + with_cuda = any(map(_is_cuda_file, sources)) + with_sycl = any(map(_is_sycl_file, sources)) + if with_sycl and with_cuda: + raise AssertionError( + "cannot have both SYCL and CUDA files in the same extension" + ) + + # extra_postargs can be either: + # - a dict mapping cxx/nvcc/sycl to extra flags + # - a list of extra flags. + if isinstance(extra_postargs, dict): + post_cflags = extra_postargs['cxx'] + else: + post_cflags = list(extra_postargs) + if IS_HIP_EXTENSION: + post_cflags = COMMON_HIP_FLAGS + post_cflags + append_std17_if_no_std_present(post_cflags) + + cuda_post_cflags = None + cuda_cflags = None + if with_cuda: + cuda_cflags = common_cflags + if isinstance(extra_postargs, dict): + cuda_post_cflags = extra_postargs['nvcc'] + else: + cuda_post_cflags = list(extra_postargs) + if IS_HIP_EXTENSION: + cuda_post_cflags = cuda_post_cflags + _get_rocm_arch_flags(cuda_post_cflags) + cuda_post_cflags = COMMON_HIP_FLAGS + COMMON_HIPCC_FLAGS + cuda_post_cflags + else: + cuda_post_cflags = unix_cuda_flags(cuda_post_cflags) + append_std17_if_no_std_present(cuda_post_cflags) + cuda_cflags = [shlex.quote(f) for f in cuda_cflags] + cuda_post_cflags = [shlex.quote(f) for f in cuda_post_cflags] + + if isinstance(extra_postargs, dict) and 'nvcc_dlink' in extra_postargs: + cuda_dlink_post_cflags = unix_cuda_flags(extra_postargs['nvcc_dlink']) + cuda_dlink_post_cflags = [shlex.quote(f) for f in cuda_dlink_post_cflags] + else: + cuda_dlink_post_cflags = None + + sycl_post_cflags = None + sycl_cflags = None + sycl_dlink_post_cflags = None + if with_sycl: + sycl_cflags = extra_cc_cflags + common_cflags + _COMMON_SYCL_FLAGS + if isinstance(extra_postargs, dict): + sycl_post_cflags = extra_postargs['sycl'] + else: + sycl_post_cflags = list(extra_postargs) + _append_sycl_targets_if_missing(sycl_post_cflags) + append_std17_if_no_std_present(sycl_cflags) + _append_sycl_std_if_no_std_present(sycl_cflags) + host_cflags = extra_cc_cflags + common_cflags + post_cflags + append_std17_if_no_std_present(host_cflags) + # escaping quoted arguments to pass them thru SYCL compiler + icpx_version = _get_icpx_version() + if int(icpx_version) >= 20250200: + host_cflags = [item.replace('"', '\\"') for item in host_cflags] + else: + host_cflags = [item.replace('"', '\\\\"') for item in host_cflags] + # Note the order: shlex.quote sycl_flags first, _wrap_sycl_host_flags + # second. Reason is that sycl host flags are quoted, space containing + # strings passed to SYCL compiler. + sycl_cflags = [shlex.quote(f) for f in sycl_cflags] + sycl_cflags += _wrap_sycl_host_flags(host_cflags) + sycl_dlink_post_cflags = _SYCL_DLINK_FLAGS.copy() + sycl_dlink_post_cflags += _get_sycl_device_flags(sycl_post_cflags) + sycl_post_cflags = [shlex.quote(f) for f in sycl_post_cflags] + + _write_ninja_file_and_compile_objects( + sources=sources, + objects=objects, + cflags=[shlex.quote(f) for f in extra_cc_cflags + common_cflags], + post_cflags=[shlex.quote(f) for f in post_cflags], + cuda_cflags=cuda_cflags, + cuda_post_cflags=cuda_post_cflags, + cuda_dlink_post_cflags=cuda_dlink_post_cflags, + sycl_cflags=sycl_cflags, + sycl_post_cflags=sycl_post_cflags, + sycl_dlink_post_cflags=sycl_dlink_post_cflags, + build_directory=output_dir, + verbose=True, + with_cuda=with_cuda, + with_sycl=with_sycl) + + # Return *all* object filenames, not just the ones we just built. + return objects + + def win_cuda_flags(cflags): + return (COMMON_NVCC_FLAGS + + cflags + _get_cuda_arch_flags(cflags)) + + def win_hip_flags(cflags): + return (COMMON_HIPCC_FLAGS + COMMON_HIP_FLAGS + cflags + _get_rocm_arch_flags(cflags)) + + def win_filter_msvc_include_dirs(pp_opts) -> list[str]: + """Filter out MSVC include dirs from pp_opts for oneAPI 2025.3+.""" + # oneAPI 2025.3+ changed include path ordering to match MSVC behavior. + # Filter out MSVC headers to avoid conflicting declarations with oneAPI's std headers. + icpx_version = int(_get_icpx_version()) + if icpx_version >= 20250300: + vc_tools_dir = os.path.normcase(os.environ.get('VCToolsInstallDir', '')) + if vc_tools_dir: + pp_opts = [ + path for path in pp_opts + if vc_tools_dir not in os.path.normcase(path) + ] + return pp_opts + + def win_wrap_single_compile(sources, + output_dir=None, + macros=None, + include_dirs=None, + debug=0, + extra_preargs=None, + extra_postargs=None, + depends=None): + + self.cflags = copy.deepcopy(extra_postargs) + extra_postargs = None + + def spawn(cmd): + # Using regex to match src, obj and include files + src_regex = re.compile('/T(p|c)(.*)') + src_list = [ + m.group(2) for m in (src_regex.match(elem) for elem in cmd) + if m + ] + + obj_regex = re.compile('/Fo(.*)') # codespell:ignore + obj_list = [ + m.group(1) for m in (obj_regex.match(elem) for elem in cmd) + if m + ] + + include_regex = re.compile(r'((\-|\/)I.*)') + include_list = [ + m.group(1) + for m in (include_regex.match(elem) for elem in cmd) if m + ] + + if len(src_list) >= 1 and len(obj_list) >= 1: + src = src_list[0] + obj = obj_list[0] + if _is_cuda_file(src): + if IS_HIP_EXTENSION: + nvcc = _get_hipcc_path() + else: + nvcc = _join_cuda_home('bin', 'nvcc') + if isinstance(self.cflags, dict): + cflags = self.cflags['nvcc'] + elif isinstance(self.cflags, list): + cflags = self.cflags + else: + cflags = [] + + if IS_HIP_EXTENSION: + cflags = win_hip_flags(cflags) + else: + cflags = win_cuda_flags(cflags) + ['-std=c++20', '--use-local-env'] + for ignore_warning in MSVC_IGNORE_CUDAFE_WARNINGS: + cflags = ['-Xcudafe', '--diag_suppress=' + ignore_warning] + cflags + for flag in COMMON_MSVC_FLAGS: + cflags = ['-Xcompiler', flag] + cflags + cmd = _wrap_compiler([nvcc, '-c', src, '-o', obj] + include_list + cflags) + else: + if isinstance(self.cflags, dict): + cflags = COMMON_MSVC_FLAGS + self.cflags['cxx'] + append_std17_if_no_std_present(cflags) + cmd += cflags + elif isinstance(self.cflags, list): + cflags = COMMON_MSVC_FLAGS + self.cflags + append_std17_if_no_std_present(cflags) + cmd += cflags + cmd = _wrap_compiler(cmd) + + return original_spawn(cmd) + + try: + self.compiler.spawn = spawn + return original_compile(sources, output_dir, macros, + include_dirs, debug, extra_preargs, + extra_postargs, depends) + finally: + self.compiler.spawn = original_spawn + + def win_wrap_ninja_compile(sources, + output_dir=None, + macros=None, + include_dirs=None, + debug=0, + extra_preargs=None, + extra_postargs=None, + depends=None, + is_standalone=False): + if not self.compiler.initialized: + self.compiler.initialize() + # pyrefly: ignore [no-matching-overload] + output_dir = os.path.abspath(output_dir) + + # Note [Absolute include_dirs] + # Convert relative path in self.compiler.include_dirs to absolute path if any. + # For ninja build, the build location is not local, but instead, the build happens + # in a script-created build folder. Thus, relative paths lose their correctness. + # To be consistent with jit extension, we allow user to enter relative include_dirs + # in setuptools.setup, and we convert the relative path to absolute path here. + convert_to_absolute_paths_inplace(self.compiler.include_dirs) + + _, objects, extra_postargs, pp_opts, _ = \ + self.compiler._setup_compile(output_dir, macros, + include_dirs, sources, + depends, extra_postargs) + # Replace space with \ when using hipcc (hipcc passes includes to clang without ""s so clang sees space in include paths as new argument) + if IS_HIP_EXTENSION: + pp_opts = ["-I{}".format(s[2:].replace(" ", "\\")) if s.startswith('-I') else s for s in pp_opts] + common_cflags = extra_preargs or [] + cflags = [] + if debug: + cflags.extend(self.compiler.compile_options_debug) + else: + cflags.extend(self.compiler.compile_options) + cflags = cflags + common_cflags + pp_opts + COMMON_MSVC_FLAGS + if IS_HIP_EXTENSION: + _set_hipcc_runtime_lib(is_standalone, debug) + common_cflags.extend(COMMON_HIP_FLAGS) + else: + common_cflags.extend(COMMON_MSVC_FLAGS) + with_cuda = any(map(_is_cuda_file, sources)) + with_sycl = any(map(_is_sycl_file, sources)) + if with_sycl and with_cuda: + raise AssertionError( + "cannot have both SYCL and CUDA files in the same extension" + ) + + # extra_postargs can be either: + # - a dict mapping cxx/nvcc to extra flags + # - a list of extra flags. + if isinstance(extra_postargs, dict): + post_cflags = extra_postargs['cxx'] + else: + post_cflags = list(extra_postargs) + if IS_HIP_EXTENSION: + post_cflags = COMMON_HIP_FLAGS + post_cflags + append_std17_if_no_std_present(post_cflags) + + cuda_post_cflags = None + cuda_cflags = None + if with_cuda: + cuda_cflags = ['-std=c++20'] + for common_cflag in common_cflags: + cuda_cflags.append('-Xcompiler') + cuda_cflags.append(common_cflag) + if not IS_HIP_EXTENSION: + cuda_cflags.append('--use-local-env') + for ignore_warning in MSVC_IGNORE_CUDAFE_WARNINGS: + cuda_cflags.append('-Xcudafe') + cuda_cflags.append('--diag_suppress=' + ignore_warning) + cuda_cflags.extend(pp_opts) + if isinstance(extra_postargs, dict): + cuda_post_cflags = extra_postargs['nvcc'] + else: + cuda_post_cflags = list(extra_postargs) + if IS_HIP_EXTENSION: + cuda_post_cflags = win_hip_flags(cuda_post_cflags) + else: + cuda_post_cflags = win_cuda_flags(cuda_post_cflags) + cflags = _nt_quote_args(cflags) + post_cflags = _nt_quote_args(post_cflags) + if with_cuda: + cuda_cflags = _nt_quote_args(cuda_cflags) + cuda_post_cflags = _nt_quote_args(cuda_post_cflags) + if isinstance(extra_postargs, dict) and 'nvcc_dlink' in extra_postargs: + cuda_dlink_post_cflags = win_cuda_flags(extra_postargs['nvcc_dlink']) + else: + cuda_dlink_post_cflags = None + + sycl_cflags = None + sycl_post_cflags = None + sycl_dlink_post_cflags = None + if with_sycl: + sycl_cflags = common_cflags + win_filter_msvc_include_dirs(pp_opts) + _COMMON_SYCL_FLAGS + if isinstance(extra_postargs, dict): + sycl_post_cflags = extra_postargs['sycl'] + else: + sycl_post_cflags = list(extra_postargs) + _append_sycl_targets_if_missing(sycl_post_cflags) + append_std17_if_no_std_present(sycl_cflags) + _append_sycl_std_if_no_std_present(sycl_cflags) + host_cflags = common_cflags + pp_opts + post_cflags + append_std17_if_no_std_present(host_cflags) + + sycl_cflags = _nt_quote_args(sycl_cflags) + host_cflags = _nt_quote_args(host_cflags) + + sycl_cflags += _wrap_sycl_host_flags(host_cflags) + sycl_dlink_post_cflags = _SYCL_DLINK_FLAGS.copy() + sycl_dlink_post_cflags += _get_sycl_device_flags(sycl_post_cflags) + sycl_post_cflags = _nt_quote_args(sycl_post_cflags) + + + _write_ninja_file_and_compile_objects( + sources=sources, + objects=objects, + cflags=cflags, + post_cflags=post_cflags, + cuda_cflags=cuda_cflags, + cuda_post_cflags=cuda_post_cflags, + cuda_dlink_post_cflags=cuda_dlink_post_cflags, + sycl_cflags=sycl_cflags, + sycl_post_cflags=sycl_post_cflags, + sycl_dlink_post_cflags=sycl_dlink_post_cflags, + build_directory=output_dir, + verbose=True, + with_cuda=with_cuda, + with_sycl=with_sycl) + + # Return *all* object filenames, not just the ones we just built. + return objects + # Monkey-patch the _compile or compile method. + # https://github.com/python/cpython/blob/dc0284ee8f7a270b6005467f26d8e5773d76e959/Lib/distutils/ccompiler.py#L511 # codespell:ignore + if self.compiler.compiler_type == 'msvc': + if self.use_ninja: + self.compiler.compile = win_wrap_ninja_compile + else: + self.compiler.compile = win_wrap_single_compile + else: + if self.use_ninja: + self.compiler.compile = unix_wrap_ninja_compile + else: + self.compiler._compile = unix_wrap_single_compile + + super().build_extensions() + + def get_ext_filename(self, ext_name): + # Get the original shared library name. For Python 3, this name will be + # suffixed with ".so", where will be something like + # cpython-37m-x86_64-linux-gnu. + ext_filename = super().get_ext_filename(ext_name) + # If `no_python_abi_suffix` is `True`, we omit the Python 3 ABI + # component. This makes building shared libraries with setuptools that + # aren't Python modules nicer. + if self.no_python_abi_suffix: + # The parts will be e.g. ["my_extension", "cpython-37m-x86_64-linux-gnu", "so"]. + ext_filename_parts = ext_filename.split('.') + # Remove ABI component only if it actually exists in a file name, see gh-170542. + if len(ext_filename_parts) > 2: + # Omit the second to last element. + without_abi = ext_filename_parts[:-2] + ext_filename_parts[-1:] + ext_filename = '.'.join(without_abi) + return ext_filename + + def get_export_symbols(self, ext): + if IS_WINDOWS: + # Skips exporting the module "PyInit_" function that the + # distutils Extension.get_export_symbols would add to + # ext.export_symbols. Only relevant for Windows builds. + return ext.export_symbols + return super().get_export_symbols(ext) + + def _check_abi(self) -> tuple[str, TorchVersion]: + # On some platforms, like Windows, compiler_cxx is not available. + if hasattr(self.compiler, 'compiler_cxx'): + compiler = self.compiler.compiler_cxx[0] + else: + compiler = get_cxx_compiler() + _, version = get_compiler_abi_compatibility_and_version(compiler) + # Warn user if VC env is activated but `DISTUILS_USE_SDK` is not set. + if IS_WINDOWS and 'VSCMD_ARG_TGT_ARCH' in os.environ and 'DISTUTILS_USE_SDK' not in os.environ: + msg = ('It seems that the VC environment is activated but DISTUTILS_USE_SDK is not set.' + 'This may lead to multiple activations of the VC env.' + 'Please set `DISTUTILS_USE_SDK=1` and try again.') + raise UserWarning(msg) + return compiler, version + + def _add_compile_flag(self, extension, flag) -> None: + extension.extra_compile_args = copy.deepcopy(extension.extra_compile_args) + if isinstance(extension.extra_compile_args, dict): + for args in extension.extra_compile_args.values(): + args.append(flag) + else: + extension.extra_compile_args.append(flag) + + # Simple hipify, replace the first occurrence of CUDA with HIP + # in flags starting with "-" and containing "CUDA", but exclude -I flags + def _hipify_compile_flags(self, extension) -> None: + if isinstance(extension.extra_compile_args, dict) and 'nvcc' in extension.extra_compile_args: + modified_flags = [] + for flag in extension.extra_compile_args['nvcc']: + if flag.startswith("-") and "CUDA" in flag and not flag.startswith("-I"): + # check/split flag into flag and value + parts = flag.split("=", 1) + if len(parts) == 2: + flag_part, value_part = parts + # replace first instance of "CUDA" with "HIP" only in the flag and not flag value + modified_flag_part = flag_part.replace("CUDA", "HIP", 1) + modified_flag = f"{modified_flag_part}={value_part}" + else: + # replace first instance of "CUDA" with "HIP" in flag + modified_flag = flag.replace("CUDA", "HIP", 1) + modified_flags.append(modified_flag) + logger.info('Modified flag: %s -> %s', flag, modified_flag) + else: + modified_flags.append(flag) + extension.extra_compile_args['nvcc'] = modified_flags + + def _define_torch_extension_name(self, extension) -> None: + # pybind11 doesn't support dots in the names + # so in order to support extensions in the packages + # like torch._C, we take the last part of the string + # as the library name + names = extension.name.split('.') + name = names[-1] + define = f'-DTORCH_EXTENSION_NAME={name}' + self._add_compile_flag(extension, define) + + +_BUILD_EXTENSION_CLASS = BuildExtension +del BuildExtension + + +def CppExtension(name, sources, *args, **kwargs): + """ + Create a :class:`setuptools.Extension` for C++. + + Convenience method that creates a :class:`setuptools.Extension` with the + bare minimum (but often sufficient) arguments to build a C++ extension. + + All arguments are forwarded to the :class:`setuptools.Extension` + constructor. Full list arguments can be found at + https://setuptools.pypa.io/en/latest/userguide/ext_modules.html#extension-api-reference + + .. warning:: + The PyTorch python API (as provided in libtorch_python) cannot be built + with the flag ``py_limited_api=True``. When this flag is passed, it is + the user's responsibility in their library to not use APIs from + libtorch_python (in particular pytorch/python bindings) and to only use + APIs from libtorch (aten objects, operators and the dispatcher). For + example, to give access to custom ops from python, the library should + register the ops through the dispatcher. + + Contrary to CPython setuptools, who does not define -DPy_LIMITED_API + as a compile flag when py_limited_api is specified as an option for + the "bdist_wheel" command in ``setup``, PyTorch does! We will specify + -DPy_LIMITED_API=min_supported_cpython to best enforce consistency, + safety, and sanity in order to encourage best practices. To target a + different version, set min_supported_cpython to the hexcode of the + CPython version of choice. + + Example: + >>> # xdoctest: +SKIP + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CPP_EXT) + >>> from setuptools import setup + >>> from torch.utils.cpp_extension import BuildExtension, CppExtension + >>> setup( + ... name='extension', + ... ext_modules=[ + ... CppExtension( + ... name='extension', + ... sources=['extension.cpp'], + ... extra_compile_args=['-g'], + ... extra_link_args=['-Wl,--no-as-needed', '-lm']) + ... ], + ... cmdclass={ + ... 'build_ext': BuildExtension + ... }) + """ + include_dirs = kwargs.get('include_dirs', []) + include_dirs += include_paths() + kwargs['include_dirs'] = include_dirs + + library_dirs = kwargs.get('library_dirs', []) + library_dirs += library_paths() + kwargs['library_dirs'] = library_dirs + + libraries = kwargs.get('libraries', []) + libraries.append('c10') + libraries.append('torch') + libraries.append('torch_cpu') + if not kwargs.get('py_limited_api', False): + # torch_python uses more than the python limited api + libraries.append('torch_python') + if IS_WINDOWS: + libraries.append("sleef") + + kwargs['libraries'] = libraries + + kwargs['language'] = 'c++' + return setuptools.Extension(name, sources, *args, **kwargs) + + +def CUDAExtension(name, sources, *args, **kwargs): + """ + Create a :class:`setuptools.Extension` for CUDA/C++. + + Convenience method that creates a :class:`setuptools.Extension` with the + bare minimum (but often sufficient) arguments to build a CUDA/C++ + extension. This includes the CUDA include path, library path and runtime + library. + + All arguments are forwarded to the :class:`setuptools.Extension` + constructor. Full list arguments can be found at + https://setuptools.pypa.io/en/latest/userguide/ext_modules.html#extension-api-reference + + .. warning:: + The PyTorch python API (as provided in libtorch_python) cannot be built + with the flag ``py_limited_api=True``. When this flag is passed, it is + the user's responsibility in their library to not use APIs from + libtorch_python (in particular pytorch/python bindings) and to only use + APIs from libtorch (aten objects, operators and the dispatcher). For + example, to give access to custom ops from python, the library should + register the ops through the dispatcher. + + Contrary to CPython setuptools, who does not define -DPy_LIMITED_API + as a compile flag when py_limited_api is specified as an option for + the "bdist_wheel" command in ``setup``, PyTorch does! We will specify + -DPy_LIMITED_API=min_supported_cpython to best enforce consistency, + safety, and sanity in order to encourage best practices. To target a + different version, set min_supported_cpython to the hexcode of the + CPython version of choice. + + Example: + >>> # xdoctest: +SKIP + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CPP_EXT) + >>> from setuptools import setup + >>> from torch.utils.cpp_extension import BuildExtension, CUDAExtension + >>> setup( + ... name='cuda_extension', + ... ext_modules=[ + ... CUDAExtension( + ... name='cuda_extension', + ... sources=['extension.cpp', 'extension_kernel.cu'], + ... extra_compile_args={'cxx': ['-g'], + ... 'nvcc': ['-O2']}, + ... extra_link_args=['-Wl,--no-as-needed', '-lcuda']) + ... ], + ... cmdclass={ + ... 'build_ext': BuildExtension + ... }) + + Compute capabilities: + + By default the extension will be compiled to run on all archs of the cards visible during the + building process of the extension, plus PTX. If down the road a new card is installed the + extension may need to be recompiled. If a visible card has a compute capability (CC) that's + newer than the newest version for which your nvcc can build fully-compiled binaries, PyTorch + will make nvcc fall back to building kernels with the newest version of PTX your nvcc does + support (see below for details on PTX). + + You can override the default behavior using `TORCH_CUDA_ARCH_LIST` to explicitly specify which + CCs you want the extension to support: + + ``TORCH_CUDA_ARCH_LIST="6.1 8.6" python build_my_extension.py`` + ``TORCH_CUDA_ARCH_LIST="5.2 6.0 6.1 7.0 7.5 8.0 8.6+PTX" python build_my_extension.py`` + + The +PTX option causes extension kernel binaries to include PTX instructions for the specified + CC. PTX is an intermediate representation that allows kernels to runtime-compile for any CC >= + the specified CC (for example, 8.6+PTX generates PTX that can runtime-compile for any GPU with + CC >= 8.6). This improves your binary's forward compatibility. However, relying on older PTX to + provide forward compat by runtime-compiling for newer CCs can modestly reduce performance on + those newer CCs. If you know exact CC(s) of the GPUs you want to target, you're always better + off specifying them individually. For example, if you want your extension to run on 8.0 and 8.6, + "8.0+PTX" would work functionally because it includes PTX that can runtime-compile for 8.6, but + "8.0 8.6" would be better. + + Note that while it's possible to include all supported archs, the more archs get included the + slower the building process will be, as it will build a separate kernel image for each arch. + + Note that CUDA-11.5 nvcc will hit internal compiler error while parsing torch/extension.h on Windows. + To workaround the issue, move python binding logic to pure C++ file. + + Example use: + #include + at::Tensor SigmoidAlphaBlendForwardCuda(....) + + Instead of: + #include + torch::Tensor SigmoidAlphaBlendForwardCuda(...) + + Currently open issue for nvcc bug: https://github.com/pytorch/pytorch/issues/69460 + Complete workaround code example: https://github.com/facebookresearch/pytorch3d/commit/cb170ac024a949f1f9614ffe6af1c38d972f7d48 + + Relocatable device code linking: + + If you want to reference device symbols across compilation units (across object files), + the object files need to be built with `relocatable device code` (-rdc=true or -dc). + An exception to this rule is "dynamic parallelism" (nested kernel launches) which is not used a lot anymore. + `Relocatable device code` is less optimized so it needs to be used only on object files that need it. + Using `-dlto` (Device Link Time Optimization) at the device code compilation step and `dlink` step + helps reduce the potential perf degradation of `-rdc`. + Note that it needs to be used at both steps to be useful. + + If you have `rdc` objects you need to have an extra `-dlink` (device linking) step before the CPU symbol linking step. + There is also a case where `-dlink` is used without `-rdc`: + when an extension is linked against a static lib containing rdc-compiled objects + like the [NVSHMEM library](https://developer.nvidia.com/nvshmem). + + Note: Ninja is required to build a CUDA Extension with RDC linking. + + Example: + >>> # xdoctest: +SKIP + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CPP_EXT) + >>> CUDAExtension( + ... name='cuda_extension', + ... sources=['extension.cpp', 'extension_kernel.cu'], + ... dlink=True, + ... dlink_libraries=["dlink_lib"], + ... extra_compile_args={'cxx': ['-g'], + ... 'nvcc': ['-O2', '-rdc=true']}) + """ + library_dirs = kwargs.get('library_dirs', []) + library_dirs += library_paths(device_type="cuda") + kwargs['library_dirs'] = library_dirs + + libraries = kwargs.get('libraries', []) + libraries.append('c10') + libraries.append('torch') + libraries.append('torch_cpu') + if not kwargs.get('py_limited_api', False): + # torch_python uses more than the python limited api + libraries.append('torch_python') + if IS_HIP_EXTENSION: + libraries.append('amdhip64') + libraries.append('c10_hip') + libraries.append('torch_hip') + else: + libraries.append('cudart') + libraries.append('c10_cuda') + libraries.append('torch_cuda') + kwargs['libraries'] = libraries + + include_dirs = kwargs.get('include_dirs', []) + + if IS_HIP_EXTENSION: + from .hipify import hipify_python + build_dir = os.getcwd() + hipify_result = hipify_python.hipify( + project_directory=build_dir, + output_directory=build_dir, + header_include_dirs=include_dirs, + includes=[os.path.join(build_dir, '*')], # limit scope to build_dir only + extra_files=[os.path.abspath(s) for s in sources], + show_detailed=True, + is_pytorch_extension=True, + hipify_extra_files_only=True, # don't hipify everything in includes path + ) + + hipified_sources = set() + for source in sources: + s_abs = os.path.abspath(source) + hipified_s_abs = (hipify_result[s_abs].hipified_path if (s_abs in hipify_result and + hipify_result[s_abs].hipified_path is not None) else s_abs) + # setup() arguments must *always* be /-separated paths relative to the setup.py directory, + # *never* absolute paths + try: + hip_path = os.path.relpath(hipified_s_abs, build_dir) + except ValueError: + # Cross-drive on Windows: no relative path exists; fall back to absolute (#91797). + hip_path = hipified_s_abs + hipified_sources.add(hip_path) + + sources = list(hipified_sources) + + include_dirs += include_paths(device_type="cuda") + kwargs['include_dirs'] = include_dirs + + kwargs['language'] = 'c++' + + dlink_libraries = kwargs.get('dlink_libraries', []) + dlink = kwargs.get('dlink', False) or dlink_libraries + if dlink: + extra_compile_args = kwargs.get('extra_compile_args', {}) + + extra_compile_args_dlink = extra_compile_args.get('nvcc_dlink', []) + extra_compile_args_dlink += ['-dlink'] + extra_compile_args_dlink += [f'-L{x}' for x in library_dirs] + extra_compile_args_dlink += [f'-l{x}' for x in dlink_libraries] + + if (torch.version.cuda is not None) and TorchVersion(torch.version.cuda) >= '11.2': + extra_compile_args_dlink += ['-dlto'] # Device Link Time Optimization started from cuda 11.2 + + extra_compile_args['nvcc_dlink'] = extra_compile_args_dlink + + kwargs['extra_compile_args'] = extra_compile_args + + return setuptools.Extension(name, sources, *args, **kwargs) + + +def SyclExtension(name, sources, *args, **kwargs): + r""" + Creates a :class:`setuptools.Extension` for SYCL/C++. + + Convenience method that creates a :class:`setuptools.Extension` with the + bare minimum (but often sufficient) arguments to build a SYCL/C++ + extension. + + All arguments are forwarded to the :class:`setuptools.Extension` + constructor. + + .. warning:: + The PyTorch python API (as provided in libtorch_python) cannot be built + with the flag ``py_limited_api=True``. When this flag is passed, it is + the user's responsibility in their library to not use APIs from + libtorch_python (in particular pytorch/python bindings) and to only use + APIs from libtorch (aten objects, operators and the dispatcher). For + example, to give access to custom ops from python, the library should + register the ops through the dispatcher. + + Contrary to CPython setuptools, who does not define -DPy_LIMITED_API + as a compile flag when py_limited_api is specified as an option for + the "bdist_wheel" command in ``setup``, PyTorch does! We will specify + -DPy_LIMITED_API=min_supported_cpython to best enforce consistency, + safety, and sanity in order to encourage best practices. To target a + different version, set min_supported_cpython to the hexcode of the + CPython version of choice. + + Example: + >>> # xdoctest: +SKIP + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CPP_EXT) + >>> from torch.utils.cpp_extension import BuildExtension, SyclExtension + >>> setup( + ... name='xpu_extension', + ... ext_modules=[ + ... SyclExtension( + ... name='xpu_extension', + ... sources=['extension.cpp', 'extension_kernel.cpp'], + ... extra_compile_args={'cxx': ['-g', '-std=c++20', '-fPIC']}) + ... ], + ... cmdclass={ + ... 'build_ext': BuildExtension + ... }) + + By default the extension will be compiled to run on all archs of the cards visible during the + building process of the extension. If down the road a new card is installed the + extension may need to be recompiled. You can override the default behavior using + `TORCH_XPU_ARCH_LIST` to explicitly specify which device architectures you want the extension + to support: + + ``TORCH_XPU_ARCH_LIST="pvc,xe-lpg" python build_my_extension.py`` + + Note that while it's possible to include all supported archs, the more archs get included the + slower the building process will be, as it will build a separate kernel image for each arch. + + Note: Ninja is required to build SyclExtension. + """ + library_dirs = kwargs.get("library_dirs", []) + library_dirs += library_paths() + kwargs["library_dirs"] = library_dirs + + libraries = kwargs.get("libraries", []) + libraries.append("c10") + libraries.append("c10_xpu") + libraries.append("torch") + libraries.append("torch_cpu") + libraries.append("sycl") + if not kwargs.get('py_limited_api', False): + # torch_python uses more than the python limited api + libraries.append("torch_python") + libraries.append("torch_xpu") + kwargs["libraries"] = libraries + + include_dirs = kwargs.get("include_dirs", []) + include_dirs += include_paths(device_type="xpu") + kwargs["include_dirs"] = include_dirs + + kwargs["language"] = "c++" + + return setuptools.Extension(name, sources, *args, **kwargs) + +def include_paths(device_type: str = "cpu", torch_include_dirs=True) -> list[str]: + """ + Get the include paths required to build a C++ or CUDA or SYCL extension. + + Args: + device_type: Defaults to "cpu". + Returns: + A list of include path strings. + """ + paths = [] + lib_include = os.path.join(_TORCH_PATH, 'include') + if torch_include_dirs: + paths.extend([ + lib_include, + # Remove this once torch/torch.h is officially no longer supported for C++ extensions. + os.path.join(lib_include, 'torch', 'csrc', 'api', 'include'), + ]) + if device_type == "cuda" and IS_HIP_EXTENSION: + paths.append(os.path.join(lib_include, 'THH')) + paths.append(_join_rocm_home('include')) + elif device_type == "cuda": + cuda_home_include = _join_cuda_home('include') + # if we have the Debian/Ubuntu packages for cuda, we get /usr as cuda home. + # but gcc doesn't like having /usr/include passed explicitly + if cuda_home_include != '/usr/include': + paths.append(cuda_home_include) + + # Support CUDA_INC_PATH env variable supported by CMake files + if (cuda_inc_path := os.environ.get("CUDA_INC_PATH", None)) and \ + cuda_inc_path != '/usr/include': + + paths.append(cuda_inc_path) + if CUDNN_HOME is not None: + paths.append(os.path.join(CUDNN_HOME, 'include')) + elif device_type == "xpu": + paths.append(_join_sycl_home('include')) + paths.append(_join_sycl_home('include', 'sycl')) + return paths + + +def library_paths(device_type: str = "cpu", torch_include_dirs: bool = True, cross_target_platform: str | None = None) -> list[str]: + """ + Get the library paths required to build a C++ or CUDA extension. + + Args: + device_type: Defaults to "cpu". + + Returns: + A list of library path strings. + """ + + paths = [] + + if torch_include_dirs: + # We need to link against libtorch.so + paths.extend([TORCH_LIB_PATH]) + + if device_type == "cuda" and IS_HIP_EXTENSION: + lib_dir = 'lib' + paths.append(_join_rocm_home(lib_dir)) + if HIP_HOME is not None: + paths.append(os.path.join(HIP_HOME, 'lib')) + elif device_type == "cuda": + if cross_target_platform == "windows": + lib_dir = os.path.join('lib', 'x64') + if WINDOWS_CUDA_HOME is None: + raise RuntimeError("Need to set WINDOWS_CUDA_HOME for windows cross-compilation") + paths.append(os.path.join(WINDOWS_CUDA_HOME, lib_dir)) + else: + if IS_WINDOWS: + lib_dir = os.path.join('lib', 'x64') + else: + lib_dir = 'lib64' + if (not os.path.exists(_join_cuda_home(lib_dir)) and + os.path.exists(_join_cuda_home('lib'))): + # 64-bit CUDA may be installed in 'lib' (see e.g. gh-16955) + # Note that it's also possible both don't exist (see + # _find_cuda_home) - in that case we stay with 'lib64'. + lib_dir = 'lib' + + paths.append(_join_cuda_home(lib_dir)) + if CUDNN_HOME is not None: + paths.append(os.path.join(CUDNN_HOME, lib_dir)) + elif device_type == "xpu": + if IS_WINDOWS: + lib_dir = os.path.join('lib', 'x64') + else: + lib_dir = 'lib64' + if (not os.path.exists(_join_sycl_home(lib_dir)) and + os.path.exists(_join_sycl_home('lib'))): + lib_dir = 'lib' + + paths.append(_join_sycl_home(lib_dir)) + + return paths + + +def load(name, + sources: str | list[str], + extra_cflags=None, + extra_cuda_cflags=None, + extra_sycl_cflags=None, + extra_ldflags=None, + extra_include_paths=None, + build_directory=None, + verbose=False, + with_cuda: bool | None = None, + with_sycl: bool | None = None, + is_python_module=True, + is_standalone=False, + keep_intermediates=True): + """ + Load a PyTorch C++ extension just-in-time (JIT). + + To load an extension, a Ninja build file is emitted, which is used to + compile the given sources into a dynamic library. This library is + subsequently loaded into the current Python process as a module and + returned from this function, ready for use. + + By default, the directory to which the build file is emitted and the + resulting library compiled to is ``/torch_extensions/``, where + ```` is the temporary folder on the current platform and ```` + the name of the extension. This location can be overridden in two ways. + First, if the ``TORCH_EXTENSIONS_DIR`` environment variable is set, it + replaces ``/torch_extensions`` and all extensions will be compiled + into subfolders of this directory. Second, if the ``build_directory`` + argument to this function is supplied, it overrides the entire path, i.e. + the library will be compiled into that folder directly. + + To compile the sources, the default system compiler (``c++``) is used, + which can be overridden by setting the ``CXX`` environment variable. To pass + additional arguments to the compilation process, ``extra_cflags`` or + ``extra_ldflags`` can be provided. For example, to compile your extension + with optimizations, pass ``extra_cflags=['-O3']``. You can also use + ``extra_cflags`` to pass further include directories. + + CUDA support with mixed compilation is provided. Simply pass CUDA source + files (``.cu`` or ``.cuh``) along with other sources. Such files will be + detected and compiled with nvcc rather than the C++ compiler. This includes + passing the CUDA lib64 directory as a library directory, and linking + ``cudart``. You can pass additional flags to nvcc via + ``extra_cuda_cflags``, just like with ``extra_cflags`` for C++. Various + heuristics for finding the CUDA install directory are used, which usually + work fine. If not, setting the ``CUDA_HOME`` environment variable is the + safest option. + + SYCL support with mixed compilation is provided. Simply pass SYCL source + files (``.sycl``) along with other sources. Such files will be detected + and compiled with SYCL compiler (such as Intel DPC++ Compiler) rather + than the C++ compiler. You can pass additional flags to SYCL compiler + via ``extra_sycl_cflags``, just like with ``extra_cflags`` for C++. + SYCL compiler is expected to be found via system PATH environment + variable. + + Args: + name: The name of the extension to build. This MUST be the same as the + name of the pybind11 module! + sources: A list of relative or absolute paths to C++ source files. + extra_cflags: optional list of compiler flags to forward to the build. + extra_cuda_cflags: optional list of compiler flags to forward to nvcc + when building CUDA sources. + extra_sycl_cflags: optional list of compiler flags to forward to SYCL + compiler when building SYCL sources. + extra_ldflags: optional list of linker flags to forward to the build. + extra_include_paths: optional list of include directories to forward + to the build. + build_directory: optional path to use as build workspace. + verbose: If ``True``, turns on verbose logging of load steps. + with_cuda: Determines whether CUDA headers and libraries are added to + the build. If set to ``None`` (default), this value is + automatically determined based on the existence of ``.cu`` or + ``.cuh`` in ``sources``. Set it to `True`` to force CUDA headers + and libraries to be included. + with_sycl: Determines whether SYCL headers and libraries are added to + the build. If set to ``None`` (default), this value is + automatically determined based on the existence of ``.sycl`` in + ``sources``. Set it to `True`` to force SYCL headers and + libraries to be included. + is_python_module: If ``True`` (default), imports the produced shared + library as a Python module. If ``False``, behavior depends on + ``is_standalone``. + is_standalone: If ``False`` (default) loads the constructed extension + into the process as a plain dynamic library. If ``True``, build a + standalone executable. + + Returns: + If ``is_python_module`` is ``True``: + Returns the loaded PyTorch extension as a Python module. + + If ``is_python_module`` is ``False`` and ``is_standalone`` is ``False``: + Returns nothing. (The shared library is loaded into the process as + a side effect.) + + If ``is_standalone`` is ``True``. + Return the path to the executable. (On Windows, TORCH_LIB_PATH is + added to the PATH environment variable as a side effect.) + + Example: + >>> # xdoctest: +SKIP + >>> from torch.utils.cpp_extension import load + >>> module = load( + ... name='extension', + ... sources=['extension.cpp', 'extension_kernel.cu'], + ... extra_cflags=['-O2'], + ... verbose=True) + """ + return _jit_compile( + name, + [sources] if isinstance(sources, str) else sources, + extra_cflags, + extra_cuda_cflags, + extra_sycl_cflags, + extra_ldflags, + extra_include_paths, + build_directory or _get_build_directory(name, verbose), + verbose, + with_cuda, + with_sycl, + is_python_module, + is_standalone, + keep_intermediates=keep_intermediates) + +@deprecated("PyBind11 ABI handling is internal to PyBind11; this will be removed after PyTorch 2.9.0") +def _get_pybind11_abi_build_flags() -> list[str]: + return [] + +def check_compiler_is_gcc(compiler) -> bool: + if not IS_LINUX: + return False + + env = os.environ.copy() + env['LC_ALL'] = 'C' # Don't localize output + try: + version_string = subprocess.check_output([compiler, '-v'], stderr=subprocess.STDOUT, env=env).decode(*SUBPROCESS_DECODE_ARGS) + except (subprocess.CalledProcessError, OSError): + try: + version_string = subprocess.check_output([compiler, '--version'], stderr=subprocess.STDOUT, env=env).decode(*SUBPROCESS_DECODE_ARGS) + except (subprocess.CalledProcessError, OSError): + return False + # Check for GCC by verifying both COLLECT_GCC and gcc version string are present + # This works for c++, g++, gcc, and versioned variants like g++-13 + pattern = re.compile("^COLLECT_GCC=(.*)$", re.MULTILINE) + has_collect_gcc = pattern.search(version_string) is not None + if has_collect_gcc and 'gcc version' in version_string: + return True + return False + +def _check_and_build_extension_h_precompiler_headers( + extra_cflags, + extra_include_paths, + is_standalone=False) -> None: + r''' + Precompiled Headers(PCH) can pre-build the same headers and reduce build time for pytorch load_inline modules. + GCC official manual: https://gcc.gnu.org/onlinedocs/gcc-4.0.4/gcc/Precompiled-Headers.html + PCH only works when built pch file(header.h.gch) and build target have the same build parameters. So, We need + add a signature file to record PCH file parameters. If the build parameters(signature) changed, it should rebuild + PCH file. + + Note: + 1. Windows and MacOS have different PCH mechanism. We only support Linux currently. + 2. It only works on GCC/G++. + ''' + if not IS_LINUX: + return + + compiler = get_cxx_compiler() + + b_is_gcc = check_compiler_is_gcc(compiler) + if b_is_gcc is False: + return + + compiler = _shell_join(_wrap_compiler(compiler)) + + head_file = os.path.join(_TORCH_PATH, 'include', 'torch', 'extension.h') + head_file_pch = os.path.join(_TORCH_PATH, 'include', 'torch', 'extension.h.gch') + head_file_signature = os.path.join(_TORCH_PATH, 'include', 'torch', 'extension.h.sign') + + def listToString(s): + # initialize an empty string + string = "" + if s is None: + return string + + # traverse in the string + for element in s: + string += (element + ' ') + # return string + return string + + def format_precompiler_header_cmd(compiler, head_file, head_file_pch, common_cflags, torch_include_dirs, extra_cflags, extra_include_paths): + return re.sub( + r"[ \n]+", + " ", + f""" + {compiler} -x c++-header {head_file} -o {head_file_pch} {torch_include_dirs} {extra_include_paths} {extra_cflags} {common_cflags} + """, + ).strip() + + def command_to_signature(cmd): + signature = cmd.replace(' ', '_') + return signature + + def check_pch_signature_in_file(file_path, signature): + b_exist = os.path.isfile(file_path) + if b_exist is False: + return False + + with open(file_path) as file: + # read all content of a file + content = file.read() + # check if string present in a file + return signature == content + + def _create_if_not_exist(path_dir) -> None: + if not os.path.exists(path_dir): + try: + Path(path_dir).mkdir(parents=True, exist_ok=True) + except OSError as exc: # Guard against race condition + if exc.errno != errno.EEXIST: + raise RuntimeError(f"Fail to create path {path_dir}") from exc + + def write_pch_signature_to_file(file_path, pch_sign) -> None: + _create_if_not_exist(os.path.dirname(file_path)) + with open(file_path, "w") as f: + f.write(pch_sign) + f.close() + + def build_precompile_header(pch_cmd) -> None: + try: + subprocess.check_output(shlex.split(pch_cmd), stderr=subprocess.STDOUT) + except subprocess.CalledProcessError as e: + raise RuntimeError(f"Compile PreCompile Header fail, command: {pch_cmd}") from e + + extra_cflags_str = listToString(extra_cflags) + extra_include_paths_str = " ".join( + [f"-I{include}" for include in extra_include_paths] if extra_include_paths else [] + ) + + lib_include = os.path.join(_TORCH_PATH, 'include') + torch_include_dirs = [ + f"-I {lib_include}", + # Python.h + "-I {}".format(sysconfig.get_path("include")), + # torch/all.h + "-I {}".format(os.path.join(lib_include, 'torch', 'csrc', 'api', 'include')), + ] + + torch_include_dirs_str = listToString(torch_include_dirs) + + common_cflags = [] + if not is_standalone: + common_cflags += ['-DTORCH_API_INCLUDE_EXTENSION_H'] + + common_cflags += ['-std=c++20', '-fPIC'] + common_cflags_str = listToString(common_cflags) + + pch_cmd = format_precompiler_header_cmd(compiler, head_file, head_file_pch, common_cflags_str, torch_include_dirs_str, extra_cflags_str, extra_include_paths_str) + pch_sign = command_to_signature(pch_cmd) + + if os.path.isfile(head_file_pch) is not True: + build_precompile_header(pch_cmd) + write_pch_signature_to_file(head_file_signature, pch_sign) + else: + b_same_sign = check_pch_signature_in_file(head_file_signature, pch_sign) + if b_same_sign is False: + build_precompile_header(pch_cmd) + write_pch_signature_to_file(head_file_signature, pch_sign) + +def remove_extension_h_precompiler_headers() -> None: + def _remove_if_file_exists(path_file) -> None: + if os.path.exists(path_file): + os.remove(path_file) + + head_file_pch = os.path.join(_TORCH_PATH, 'include', 'torch', 'extension.h.gch') + head_file_signature = os.path.join(_TORCH_PATH, 'include', 'torch', 'extension.h.sign') + + _remove_if_file_exists(head_file_pch) + _remove_if_file_exists(head_file_signature) + +def load_inline(name, + cpp_sources, + cuda_sources=None, + sycl_sources=None, + functions=None, + extra_cflags=None, + extra_cuda_cflags=None, + extra_sycl_cflags=None, + extra_ldflags=None, + extra_include_paths=None, + build_directory=None, + verbose=False, + with_cuda=None, + with_sycl=None, + is_python_module=True, + with_pytorch_error_handling=True, + keep_intermediates=True, + use_pch=False, + no_implicit_headers=False): + r''' + Load a PyTorch C++ extension just-in-time (JIT) from string sources. + + This function behaves exactly like :func:`load`, but takes its sources as + strings rather than filenames. These strings are stored to files in the + build directory, after which the behavior of :func:`load_inline` is + identical to :func:`load`. + + See `the + tests `_ + for good examples of using this function. + + Sources may omit two required parts of a typical non-inline C++ extension: + the necessary header includes, as well as the (pybind11) binding code. More + precisely, strings passed to ``cpp_sources`` are first concatenated into a + single ``.cpp`` file. This file is then prepended with ``#include + `` + + Furthermore, if the ``functions`` argument is supplied, bindings will be + automatically generated for each function specified. ``functions`` can + either be a list of function names, or a dictionary mapping from function + names to docstrings. If a list is given, the name of each function is used + as its docstring. + + The sources in ``cuda_sources`` are concatenated into a separate ``.cu`` + file and prepended with ``torch/types.h``, ``cuda.h`` and + ``cuda_runtime.h`` includes. The ``.cpp`` and ``.cu`` files are compiled + separately, but ultimately linked into a single library. Note that no + bindings are generated for functions in ``cuda_sources`` per se. To bind + to a CUDA kernel, you must create a C++ function that calls it, and either + declare or define this C++ function in one of the ``cpp_sources`` (and + include its name in ``functions``). + + The sources in ``sycl_sources`` are concatenated into a separate ``.sycl`` + file and prepended with ``torch/types.h``, ``sycl/sycl.hpp`` includes. + The ``.cpp`` and ``.sycl`` files are compiled separately, but ultimately + linked into a single library. Note that no bindings are generated for + functions in ``sycl_sources`` per se. To bind to a SYCL kernel, you must + create a C++ function that calls it, and either declare or define this + C++ function in one of the ``cpp_sources`` (and include its name + in ``functions``). + + + + See :func:`load` for a description of arguments omitted below. + + Args: + cpp_sources: A string, or list of strings, containing C++ source code. + cuda_sources: A string, or list of strings, containing CUDA source code. + sycl_sources: A string, or list of strings, containing SYCL source code. + functions: A list of function names for which to generate function + bindings. If a dictionary is given, it should map function names to + docstrings (which are otherwise just the function names). + with_cuda: Determines whether CUDA headers and libraries are added to + the build. If set to ``None`` (default), this value is + automatically determined based on whether ``cuda_sources`` is + provided. Set it to ``True`` to force CUDA headers + and libraries to be included. + with_sycl: Determines whether SYCL headers and libraries are added to + the build. If set to ``None`` (default), this value is + automatically determined based on whether ``sycl_sources`` is + provided. Set it to ``True`` to force SYCL headers + and libraries to be included. + with_pytorch_error_handling: Determines whether pytorch error and + warning macros are handled by pytorch instead of pybind. To do + this, each function ``foo`` is called via an intermediary ``_safe_foo`` + function. This redirection might cause issues in obscure cases + of cpp. This flag should be set to ``False`` when this redirect + causes issues. + no_implicit_headers: If ``True``, skips automatically adding headers, most notably + ``#include `` and ``#include `` lines. + Use this option to improve cold start times when you + already include the necessary headers in your source code. Default: ``False``. + + Example: + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CPP_EXT) + >>> from torch.utils.cpp_extension import load_inline + >>> source = """ + at::Tensor sin_add(at::Tensor x, at::Tensor y) { + return x.sin() + y.sin(); + } + """ + >>> module = load_inline(name='inline_extension', + ... cpp_sources=[source], + ... functions=['sin_add']) + + .. note:: + Since load_inline will just-in-time compile the source code, please ensure + that you have the right toolchains installed in the runtime. For example, + when loading C++, make sure a C++ compiler is available. If you're loading + a CUDA extension, you will need to additionally install the corresponding CUDA + toolkit (nvcc and any other dependencies your code has). Compiling toolchains + are not included when you install torch and must be additionally installed. + + During compiling, by default, the Ninja backend uses #CPUS + 2 workers to build + the extension. This may use up too many resources on some systems. One + can control the number of workers by setting the `MAX_JOBS` environment + variable to a non-negative number. + ''' + build_directory = build_directory or _get_build_directory(name, verbose) + + if isinstance(cpp_sources, str): + cpp_sources = [cpp_sources] + cuda_sources = cuda_sources or [] + if isinstance(cuda_sources, str): + cuda_sources = [cuda_sources] + sycl_sources = sycl_sources or [] + if isinstance(sycl_sources, str): + sycl_sources = [sycl_sources] + + if not no_implicit_headers: + cpp_sources.insert(0, '#include ') + + if use_pch is True: + # Using PreCompile Header('torch/extension.h') to reduce compile time. + _check_and_build_extension_h_precompiler_headers(extra_cflags, extra_include_paths) + else: + remove_extension_h_precompiler_headers() + + # If `functions` is supplied, we create the pybind11 bindings for the user. + # Here, `functions` is (or becomes, after some processing) a map from + # function names to function docstrings. + if functions is not None: + module_def = [] + module_def.append('PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {') + if isinstance(functions, str): + functions = [functions] + if isinstance(functions, list): + # Make the function docstring the same as the function name. + functions = {f: f for f in functions} + elif not isinstance(functions, dict): + raise ValueError(f"Expected 'functions' to be a list or dict, but was {type(functions)}") + for function_name, docstring in functions.items(): + if with_pytorch_error_handling: + module_def.append(f'm.def("{function_name}", torch::wrap_pybind_function({function_name}), "{docstring}");') + else: + module_def.append(f'm.def("{function_name}", {function_name}, "{docstring}");') + module_def.append('}') + cpp_sources += module_def + + cpp_source_path = os.path.join(build_directory, 'main.cpp') + _maybe_write(cpp_source_path, "\n".join(cpp_sources)) + + sources = [cpp_source_path] + + if cuda_sources: + if not no_implicit_headers: + cuda_sources.insert(0, '#include ') + cuda_sources.insert(1, '#include ') + cuda_sources.insert(2, '#include ') + + cuda_source_path = os.path.join(build_directory, 'cuda.cu') + _maybe_write(cuda_source_path, "\n".join(cuda_sources)) + + sources.append(cuda_source_path) + + if sycl_sources: + if not no_implicit_headers: + sycl_sources.insert(0, '#include ') + sycl_sources.insert(1, '#include ') + + sycl_source_path = os.path.join(build_directory, 'sycl.sycl') + _maybe_write(sycl_source_path, "\n".join(sycl_sources)) + + sources.append(sycl_source_path) + + return _jit_compile( + name, + sources, + extra_cflags, + extra_cuda_cflags, + extra_sycl_cflags, + extra_ldflags, + extra_include_paths, + build_directory, + verbose, + with_cuda, + with_sycl, + is_python_module, + is_standalone=False, + keep_intermediates=keep_intermediates) + + +def _jit_compile(name, + sources, + extra_cflags, + extra_cuda_cflags, + extra_sycl_cflags, + extra_ldflags, + extra_include_paths, + build_directory: str, + verbose: bool, + with_cuda: bool | None, + with_sycl: bool | None, + is_python_module, + is_standalone, + keep_intermediates=True) -> types.ModuleType | str: + if is_python_module and is_standalone: + raise ValueError("`is_python_module` and `is_standalone` are mutually exclusive.") + + if with_cuda is None: + with_cuda = any(map(_is_cuda_file, sources)) + with_cudnn = any('cudnn' in f for f in extra_ldflags or []) + if with_sycl is None: + with_sycl = any(map(_is_sycl_file, sources)) + if with_sycl and with_cuda: + raise AssertionError( + "cannot have both SYCL and CUDA files in the same extension" + ) + old_version = JIT_EXTENSION_VERSIONER.get_version(name) + version = JIT_EXTENSION_VERSIONER.bump_version_if_changed( + name, + sources, + build_arguments=[extra_cflags, extra_cuda_cflags, extra_ldflags, extra_include_paths], + build_directory=build_directory, + with_cuda=with_cuda, + with_sycl=with_sycl, + is_python_module=is_python_module, + is_standalone=is_standalone, + ) + if version > 0: + if version != old_version and verbose: + logger.info('The input conditions for extension module %s have changed.', name) + logger.info('Bumping to version %s and re-building as %s_v%s...', version, name, version) + name = f'{name}_v{version}' + + # Hold an OS-level advisory lock (via filelock) rather than a lock file + # whose mere existence blocks: the kernel releases the lock if the holder + # is killed, so a builder terminated by SIGKILL/OOM/Slurm no longer leaves + # a stale lock that deadlocks every later run + # (https://github.com/pytorch/pytorch/issues/189245). Whoever acquires the + # lock rechecks the version and (re)builds, so a crashed build is retried + # by the next process instead of leaving waiters to load a partial module. + with FileLock(os.path.join(build_directory, 'lock')): + if version != old_version: + if IS_HIP_EXTENSION and (with_cuda or with_cudnn): + from .hipify import hipify_python + from .hipify.hipify_python import GeneratedFileCleaner + clean_ctx_mgr = GeneratedFileCleaner(keep_intermediates=keep_intermediates) + else: + import contextlib + hipify_python = None # type: ignore[assignment] + clean_ctx_mgr = contextlib.nullcontext() + with clean_ctx_mgr as clean_ctx: + if IS_HIP_EXTENSION and (with_cuda or with_cudnn): + if hipify_python is None: + raise AssertionError("expected hipify_python to be not None") + hipify_result = hipify_python.hipify( + project_directory=build_directory, + output_directory=build_directory, + header_include_dirs=(extra_include_paths if extra_include_paths is not None else []), + extra_files=[os.path.abspath(s) for s in sources], + ignores=[_join_rocm_home('*'), os.path.join(_TORCH_PATH, '*')], # no need to hipify ROCm or PyTorch headers + show_detailed=verbose, + show_progress=verbose, + is_pytorch_extension=True, + clean_ctx=clean_ctx + ) + + hipified_sources = set() + for source in sources: + s_abs = os.path.abspath(source) + if s_abs in hipify_result and hipify_result[s_abs].hipified_path is not None: + hipified_s_abs = hipify_result[s_abs].hipified_path + else: + hipified_s_abs = s_abs + hipified_sources.add(hipified_s_abs) + sources = list(hipified_sources) + + _write_ninja_file_and_build_library( + name=name, + sources=sources, + extra_cflags=extra_cflags or [], + extra_cuda_cflags=extra_cuda_cflags or [], + extra_sycl_cflags=extra_sycl_cflags or [], + extra_ldflags=extra_ldflags or [], + extra_include_paths=extra_include_paths or [], + build_directory=build_directory, + verbose=verbose, + with_cuda=with_cuda, + with_sycl=with_sycl, + is_standalone=is_standalone) + elif verbose: + logger.debug('No modifications detected for re-loaded extension module %s, skipping build step...', name) + + if verbose: + logger.info('Loading extension module %s...', name) + + if is_standalone: + return _get_exec_path(name, build_directory) + + return _import_module_from_library(name, build_directory, is_python_module) + +def _get_hipcc_path(): + if IS_WINDOWS: + # mypy thinks ROCM_VERSION is None but it will never be None here + hipcc_exe = 'hipcc.exe' if ROCM_VERSION >= (6, 4) else 'hipcc.bat' # type: ignore[operator] + return _join_rocm_home('bin', hipcc_exe) + else: + return _join_rocm_home('bin', 'hipcc') + +def _write_ninja_file_and_compile_objects( + sources: list[str], + objects, + cflags, + post_cflags, + cuda_cflags, + cuda_post_cflags, + cuda_dlink_post_cflags, + sycl_cflags, + sycl_post_cflags, + sycl_dlink_post_cflags, + build_directory: str, + verbose: bool, + with_cuda: bool | None, + with_sycl: bool | None) -> None: + verify_ninja_availability() + + compiler = get_cxx_compiler() + + get_compiler_abi_compatibility_and_version(compiler) + if with_cuda is None: + with_cuda = any(map(_is_cuda_file, sources)) + if with_sycl is None: + with_sycl = any(map(_is_sycl_file, sources)) + if with_sycl and with_cuda: + raise AssertionError( + "cannot have both SYCL and CUDA files in the same extension" + ) + build_file_path = os.path.join(build_directory, 'build.ninja') + if verbose: + logger.debug('Emitting ninja build file %s...', build_file_path) + + # Create build_directory if it does not exist + if not os.path.exists(build_directory): + if verbose: + logger.debug('Creating directory %s...', build_directory) + # This is like mkdir -p, i.e. will also create parent directories. + os.makedirs(build_directory, exist_ok=True) + + _write_ninja_file( + path=build_file_path, + cflags=cflags, + post_cflags=post_cflags, + cuda_cflags=cuda_cflags, + cuda_post_cflags=cuda_post_cflags, + cuda_dlink_post_cflags=cuda_dlink_post_cflags, + sycl_cflags=sycl_cflags, + sycl_post_cflags=sycl_post_cflags, + sycl_dlink_post_cflags=sycl_dlink_post_cflags, + sources=sources, + objects=objects, + ldflags=None, + library_target=None, + with_cuda=with_cuda, + with_sycl=with_sycl) + if verbose: + logger.info('Compiling objects...') + _run_ninja_build( + build_directory, + verbose, + # It would be better if we could tell users the name of the extension + # that failed to build but there isn't a good way to get it here. + error_prefix='Error compiling objects for extension') + + +def _write_ninja_file_and_build_library( + name, + sources: list[str], + extra_cflags, + extra_cuda_cflags, + extra_sycl_cflags, + extra_ldflags, + extra_include_paths, + build_directory: str, + verbose: bool, + with_cuda: bool | None, + with_sycl: bool | None, + is_standalone: bool = False) -> None: + verify_ninja_availability() + + compiler = get_cxx_compiler() + + get_compiler_abi_compatibility_and_version(compiler) + if with_cuda is None: + with_cuda = any(map(_is_cuda_file, sources)) + if with_sycl is None: + with_sycl = any(map(_is_sycl_file, sources)) + if with_sycl and with_cuda: + raise AssertionError( + "cannot have both SYCL and CUDA files in the same extension" + ) + extra_ldflags = _prepare_ldflags( + extra_ldflags or [], + with_cuda, + with_sycl, + verbose, + is_standalone) + build_file_path = os.path.join(build_directory, 'build.ninja') + if verbose: + logger.debug('Emitting ninja build file %s...', build_file_path) + + # Create build_directory if it does not exist + if not os.path.exists(build_directory): + if verbose: + logger.debug('Creating directory %s...', build_directory) + # This is like mkdir -p, i.e. will also create parent directories. + os.makedirs(build_directory, exist_ok=True) + + # NOTE: Emitting a new ninja build file does not cause re-compilation if + # the sources did not change, so it's ok to re-emit (and it's fast). + _write_ninja_file_to_build_library( + path=build_file_path, + name=name, + sources=sources, + extra_cflags=extra_cflags or [], + extra_cuda_cflags=extra_cuda_cflags or [], + extra_sycl_cflags=extra_sycl_cflags or [], + extra_ldflags=extra_ldflags or [], + extra_include_paths=extra_include_paths or [], + with_cuda=with_cuda, + with_sycl=with_sycl, + is_standalone=is_standalone) + + if verbose: + logger.info('Building extension module %s...', name) + _run_ninja_build( + build_directory, + verbose, + error_prefix=f"Error building extension '{name}'") + + +def is_ninja_available() -> bool: + """Return ``True`` if the `ninja `_ build system is available on the system, ``False`` otherwise.""" + try: + subprocess.check_output(['ninja', '--version']) + except Exception: + return False + else: + return True + + +def verify_ninja_availability() -> None: + """Raise ``RuntimeError`` if `ninja `_ build system is not available on the system, does nothing otherwise.""" + if not is_ninja_available(): + raise RuntimeError("Ninja is required to load C++ extensions (pip install ninja to get it)") + + +def _prepare_ldflags(extra_ldflags, with_cuda, with_sycl, verbose, is_standalone): + if IS_WINDOWS: + python_lib_path = os.path.join(sys.base_exec_prefix, 'libs') + + extra_ldflags.append('c10.lib') + if with_cuda: + extra_ldflags.append('c10_hip.lib' if IS_HIP_EXTENSION else 'c10_cuda.lib') + if with_sycl: + extra_ldflags.append('c10_xpu.lib') + extra_ldflags.append('torch_cpu.lib') + if with_cuda: + extra_ldflags.append('torch_hip.lib' if IS_HIP_EXTENSION else 'torch_cuda.lib') + # /INCLUDE is used to ensure torch_cuda is linked against in a project that relies on it. + # Related issue: https://github.com/pytorch/pytorch/issues/31611 + extra_ldflags.append('-INCLUDE:?warp_size@cuda@at@@YAHXZ') + if with_sycl: + extra_ldflags.append('torch_xpu.lib') + extra_ldflags.append('torch.lib') + extra_ldflags.append(f'/LIBPATH:{TORCH_LIB_PATH}') + if not is_standalone: + extra_ldflags.append('torch_python.lib') + extra_ldflags.append(f'/LIBPATH:{python_lib_path}') + + else: + extra_ldflags.append(f'-L{TORCH_LIB_PATH}') + extra_ldflags.append('-lc10') + if with_cuda: + extra_ldflags.append('-lc10_hip' if IS_HIP_EXTENSION else '-lc10_cuda') + if with_sycl: + extra_ldflags.append('-lc10_xpu') + extra_ldflags.append('-ltorch_cpu') + if with_cuda: + extra_ldflags.append('-ltorch_hip' if IS_HIP_EXTENSION else '-ltorch_cuda') + if with_sycl: + extra_ldflags.append('-ltorch_xpu') + extra_ldflags.append('-ltorch') + if not is_standalone: + extra_ldflags.append('-ltorch_python') + + if is_standalone: + extra_ldflags.append(f"-Wl,-rpath,{TORCH_LIB_PATH}") + + if with_cuda: + if verbose: + logger.info('Detected CUDA files, patching ldflags') + if IS_WINDOWS and not IS_HIP_EXTENSION: + extra_ldflags.append(f'/LIBPATH:{_join_cuda_home("lib", "x64")}') + extra_ldflags.append('cudart.lib') + if CUDNN_HOME is not None: + extra_ldflags.append(f'/LIBPATH:{os.path.join(CUDNN_HOME, "lib", "x64")}') + elif not IS_HIP_EXTENSION: + extra_lib_dir = "lib64" + if (not os.path.exists(_join_cuda_home(extra_lib_dir)) and + os.path.exists(_join_cuda_home("lib"))): + # 64-bit CUDA may be installed in "lib" + # Note that it's also possible both don't exist (see _find_cuda_home) - in that case we stay with "lib64" + extra_lib_dir = "lib" + extra_ldflags.append(f'-L{_join_cuda_home(extra_lib_dir)}') + extra_ldflags.append('-lcudart') + if CUDNN_HOME is not None: + extra_ldflags.append(f'-L{os.path.join(CUDNN_HOME, "lib64")}') + elif IS_HIP_EXTENSION: + if IS_WINDOWS: + extra_ldflags.append(f'/LIBPATH:{_join_rocm_home("lib")}') + extra_ldflags.append('amdhip64.lib') + else: + extra_ldflags.append(f'-L{_join_rocm_home("lib")}') + extra_ldflags.append('-lamdhip64') + if with_sycl: + if IS_WINDOWS: + extra_ldflags.append(f'/LIBPATH:{_join_sycl_home("lib")}') + extra_ldflags.append('sycl.lib') + else: + extra_ldflags.append(f'-L{_join_sycl_home("lib")}') + extra_ldflags.append('-lsycl') + return extra_ldflags + + +def _get_cuda_arch_flags(cflags: list[str] | None = None) -> list[str]: + """ + Determine CUDA arch flags to use. + + For an arch, say "6.1", the added compile flag will be + ``-gencode=arch=compute_61,code=sm_61``. + For an added "+PTX", an additional + ``-gencode=arch=compute_xx,code=compute_xx`` is added. + + See select_compute_arch.cmake for corresponding named and supported arches + when building with CMake. + """ + # If cflags is given, there may already be user-provided arch flags in it + # (from `extra_compile_args`) + if cflags is not None: + for flag in cflags: + if 'TORCH_EXTENSION_NAME' in flag: + continue + if 'arch' in flag: + return [] + + # Note: keep combined names ("arch1+arch2") above single names, otherwise + # string replacement may not do the right thing + named_arches = collections.OrderedDict([ + ('Kepler+Tesla', '3.7'), + ('Kepler', '3.5+PTX'), + ('Maxwell+Tegra', '5.3'), + ('Maxwell', '5.0;5.2+PTX'), + ('Pascal', '6.0;6.1+PTX'), + ('Volta+Tegra', '7.2'), + ('Volta', '7.0+PTX'), + ('Turing', '7.5+PTX'), + ('Ampere+Tegra', '8.7'), + ('Ampere', '8.0;8.6+PTX'), + ('Ada', '8.9+PTX'), + ('Hopper', '9.0+PTX'), + ('Blackwell+Tegra', '11.0'), + ('Blackwell', '10.0;10.3;12.0;12.1+PTX'), + ('Rubin', '10.7+PTX'), + ]) + + supported_arches = ['3.5', '3.7', '5.0', '5.2', '5.3', '6.0', '6.1', '6.2', + '7.0', '7.2', '7.5', '8.0', '8.6', '8.7', '8.9', '9.0', '9.0a', + '10.0', '10.0a', '11.0', '11.0a', '10.3', '10.3a', '10.7', '10.7a', + '12.0', '12.0a', '12.1', '12.1a'] + valid_arch_strings = supported_arches + [s + "+PTX" for s in supported_arches] + + # The default is sm_30 for CUDA 9.x and 10.x + # First check for an env var (same as used by the main setup.py) + # Can be one or more architectures, e.g. "6.1" or "3.5;5.2;6.0;6.1;7.0+PTX" + # See cmake/Modules_CUDA_fix/upstream/FindCUDA/select_compute_arch.cmake + _arch_list = os.environ.get('TORCH_CUDA_ARCH_LIST', None) + + # If not given or set as native, determine what's best for the GPU / CUDA version that can be found + if not _arch_list or _arch_list == "native": + arch_list = [] + # the assumption is that the extension should run on any of the currently visible cards, + # which could be of different types - therefore all archs for visible cards should be included + for i in range(torch.cuda.device_count()): + capability = torch.cuda.get_device_capability(i) + supported_sm = [int("".join(re.findall(r"\d+", arch.split('_')[1]))) + for arch in torch.cuda.get_arch_list() if 'sm_' in arch] + max_supported_sm = max((sm // 10, sm % 10) for sm in supported_sm) + # Capability of the device may be higher than what's supported by the user's + # NVCC, causing compilation error. User's NVCC is expected to match the one + # used to build pytorch, so we use the maximum supported capability of pytorch + # to clamp the capability. + capability = min(max_supported_sm, capability) + arch = f'{capability[0]}.{capability[1]}' + if arch not in arch_list: + arch_list.append(arch) + arch_list = sorted(arch_list) + arch_list[-1] += '+PTX' + + if not _arch_list: + # Only log on rank 0 in distributed settings to avoid spam + if not torch.distributed.is_available() or not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0: + arch_list_str = ';'.join(arch_list) + logger.debug( + "TORCH_CUDA_ARCH_LIST is not set, using TORCH_CUDA_ARCH_LIST='%s' " + "for visible GPU architectures. Set os.environ['TORCH_CUDA_ARCH_LIST'] to override.", + arch_list_str) + else: + # Deal with lists that are ' ' separated (only deal with ';' after) + _arch_list = _arch_list.replace(' ', ';') + # Expand named arches + for named_arch, archival in named_arches.items(): + _arch_list = _arch_list.replace(named_arch, archival) + + arch_list = _arch_list.split(';') + + flags = [] + for arch in arch_list: + if arch not in valid_arch_strings: + raise ValueError(f"Unknown CUDA arch ({arch}) or GPU not supported") + else: + # Handle both single and double-digit architecture versions + version = arch.split('+')[0] # Remove "+PTX" if present + major, minor = version.split('.') + num = f"{major}{minor}" + flags.append(f'-gencode=arch=compute_{num},code=sm_{num}') + if arch.endswith('+PTX'): + flags.append(f'-gencode=arch=compute_{num},code=compute_{num}') + + return sorted(set(flags)) + + +def _get_rocm_arch_flags(cflags: list[str] | None = None) -> list[str]: + # If cflags is given, there may already be user-provided arch flags in it + # (from `extra_compile_args`). If user also specified -fgpu-rdc or -fno-gpu-rdc, we + # assume they know what they're doing. Otherwise, we force -fno-gpu-rdc default. + has_gpu_rdc_flag = False + if cflags is not None: + has_custom_flags = False + for flag in cflags: + if 'amdgpu-target' in flag or 'offload-arch' in flag: + has_custom_flags = True + elif 'gpu-rdc' in flag: + has_gpu_rdc_flag = True + if has_custom_flags: + return [] if has_gpu_rdc_flag else ['-fno-gpu-rdc'] + # Use same defaults as used for building PyTorch + # Allow env var to override, just like during initial cmake build. + _archs = os.environ.get('PYTORCH_ROCM_ARCH', None) + if not _archs: + arch_set = set() + # the assumption is that the extension should run on any of the currently visible cards, + # which could be of different types - therefore all archs for visible cards should be included + for i in range(torch.cuda.device_count()): + device_properties = torch.cuda.get_device_properties(i) + if hasattr(device_properties, "gcnArchName"): + device_arch = (device_properties.gcnArchName).split(":", 1)[0] + arch_set.add(device_arch) + + archs = ";".join(arch_set) + + logger.warning( + "The environment variable `PYTORCH_ROCM_ARCH` is not set, all archs for visible cards are included for compilation (%s).\n" + "If this is not desired, please set the environment variable `PYTORCH_ROCM_ARCH` to specific architectures.", archs) + else: + archs = _archs.replace(' ', ';') + + archs = archs.split(';') + flags = [f'--offload-arch={arch}' for arch in archs] + flags += [] if has_gpu_rdc_flag else ['-fno-gpu-rdc'] + return flags + +def _get_build_directory(name: str, verbose: bool) -> str: + """ + Get the build directory for an extension. + + Args: + name: The name of the extension + verbose: Whether to print verbose information + + Returns: + The path to the build directory + """ + root_extensions_directory = os.environ.get('TORCH_EXTENSIONS_DIR') + if root_extensions_directory is None: + root_extensions_directory = get_default_build_root() + # Determine GPU accelerator prefix based on available accelerators. Fallback to CPU. + # Priority: ROCm/HIP > CUDA > CPU + # Note: torch.backends.cuda.is_built() returns True for both CUDA and ROCm, + # so we need to check torch.version.hip to distinguish them + if torch.version.hip is not None: + accelerator_str = f'rocm{torch.version.hip.replace(".", "")}' + elif torch.version.cuda is not None: + accelerator_str = f'cu{torch.version.cuda.replace(".", "")}' + else: + accelerator_str = 'cpu' + python_version = f'py{sys.version_info.major}{sys.version_info.minor}{getattr(sys, "abiflags", "")}' + build_folder = f'{python_version}_{accelerator_str}' + + root_extensions_directory = os.path.join( + root_extensions_directory, build_folder) + + if verbose: + logger.info('Using %s as PyTorch extensions root...', root_extensions_directory) + + build_directory = os.path.join(root_extensions_directory, name) + if not os.path.exists(build_directory): + if verbose: + logger.debug('Creating extension directory %s...', build_directory) + # This is like mkdir -p, i.e. will also create parent directories. + os.makedirs(build_directory, exist_ok=True) + + return build_directory + + +def _get_num_workers(verbose: bool) -> int | None: + max_jobs = os.environ.get('MAX_JOBS') + if max_jobs is not None and max_jobs.isdigit(): + if verbose: + logger.debug('Using envvar MAX_JOBS (%s) as the number of workers...', max_jobs) + return int(max_jobs) + if verbose: + logger.info( + 'Allowing ninja to set a default number of workers... ' + '(overridable by setting the environment variable MAX_JOBS=N)' + ) + return None + + +def _get_vc_env(vc_arch: str) -> dict[str, str]: + try: + from setuptools import distutils # type: ignore[attr-defined] + + return distutils._msvccompiler._get_vc_env(vc_arch) + except AttributeError: + try: + from setuptools._distutils import _msvccompiler + return _msvccompiler._get_vc_env(vc_arch) # type: ignore[attr-defined] + except AttributeError: + from setuptools._distutils.compilers.C import msvc + return msvc._get_vc_env(vc_arch) # type: ignore[attr-defined] + +def _run_ninja_build(build_directory: str, verbose: bool, error_prefix: str) -> None: + command = ['ninja', '-v'] + num_workers = _get_num_workers(verbose) + if num_workers is not None: + command.extend(['-j', str(num_workers)]) + env = os.environ.copy() + # Try to activate the vc env for the users + if IS_WINDOWS and 'VSCMD_ARG_TGT_ARCH' not in env: + from setuptools import distutils # type: ignore[attr-defined] + + plat_name = distutils.util.get_platform() + plat_spec = PLAT_TO_VCVARS[plat_name] + vc_env = {k.upper(): v for k, v in _get_vc_env(plat_spec).items()} + for k, v in env.items(): + uk = k.upper() + if uk not in vc_env: + vc_env[uk] = v + env = vc_env + try: + sys.stdout.flush() + sys.stderr.flush() + # Warning: don't pass stdout=None to subprocess.run to get output. + # subprocess.run assumes that sys.__stdout__ has not been modified and + # attempts to write to it by default. However, when we call _run_ninja_build + # from ahead-of-time cpp extensions, the following happens: + # 1) If the stdout encoding is not utf-8, setuptools detaches __stdout__. + # https://github.com/pypa/setuptools/blob/7e97def47723303fafabe48b22168bbc11bb4821/setuptools/dist.py#L1110 + # (it probably shouldn't do this) + # 2) subprocess.run (on POSIX, with no stdout override) relies on + # __stdout__ not being detached: + # https://github.com/python/cpython/blob/c352e6c7446c894b13643f538db312092b351789/Lib/subprocess.py#L1214 + # To work around this, we pass in the fileno directly and hope that + # it is valid. + stdout_fileno = 1 + subprocess.run( + command, + shell=IS_WINDOWS and IS_HIP_EXTENSION, + stdout=stdout_fileno if verbose else subprocess.PIPE, + stderr=subprocess.STDOUT, + cwd=build_directory, + check=True, + env=env) + except subprocess.CalledProcessError as e: + # Python 2 and 3 compatible way of getting the error object. + _, error, _ = sys.exc_info() + # error.output contains the stdout and stderr of the build attempt. + message = error_prefix + # `error` is a CalledProcessError (which has an `output`) attribute, but + # mypy thinks it's Optional[BaseException] and doesn't narrow + if hasattr(error, 'output') and error.output: # type: ignore[union-attr] + message += f": {error.output.decode(*SUBPROCESS_DECODE_ARGS)}" # type: ignore[union-attr] + raise RuntimeError(message) from e + + +def _get_exec_path(module_name, path): + if IS_WINDOWS and TORCH_LIB_PATH not in os.getenv('PATH', '').split(';'): + torch_lib_in_path = any( + os.path.exists(p) and os.path.samefile(p, TORCH_LIB_PATH) + for p in os.getenv('PATH', '').split(';') + ) + if not torch_lib_in_path: + os.environ['PATH'] = f"{TORCH_LIB_PATH};{os.getenv('PATH', '')}" + return os.path.join(path, f'{module_name}{EXEC_EXT}') + + +def _import_module_from_library(module_name, path, is_python_module): + filepath = os.path.join(path, f"{module_name}{LIB_EXT}") + if is_python_module: + # https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path + spec = importlib.util.spec_from_file_location(module_name, filepath) + if spec is None: + raise AssertionError(f"Failed to create spec for module {module_name} at {filepath}") + module = importlib.util.module_from_spec(spec) + if not isinstance(spec.loader, importlib.abc.Loader): + raise AssertionError("spec.loader is not a valid importlib Loader") + spec.loader.exec_module(module) + return module + else: + torch.ops.load_library(filepath) + return filepath + + +def _write_ninja_file_to_build_library(path, + name, + sources, + extra_cflags, + extra_cuda_cflags, + extra_sycl_cflags, + extra_ldflags, + extra_include_paths, + with_cuda, + with_sycl, + is_standalone) -> None: + extra_cflags = [flag.strip() for flag in extra_cflags] + extra_cuda_cflags = [flag.strip() for flag in extra_cuda_cflags] + extra_sycl_cflags = [flag.strip() for flag in extra_sycl_cflags] + extra_ldflags = [flag.strip() for flag in extra_ldflags] + extra_include_paths = [flag.strip() for flag in extra_include_paths] + + # Turn into absolute paths so we can emit them into the ninja build + # file wherever it is. + user_includes = [os.path.abspath(file) for file in extra_include_paths] + + # include_paths() gives us the location of torch/extension.h + # TODO generalize with_cuda as specific device type. + if with_cuda: + system_includes = include_paths("cuda") + elif with_sycl: + system_includes = include_paths("xpu") + else: + system_includes = include_paths("cpu") + # sysconfig.get_path('include') gives us the location of Python.h + # Explicitly specify 'posix_prefix' scheme on non-Windows platforms to workaround error on some MacOS + # installations where default `get_path` points to non-existing `/Library/Python/M.m/include` folder + python_include_path = sysconfig.get_path('include', scheme='nt' if IS_WINDOWS else 'posix_prefix') + if python_include_path is not None: + system_includes.append(python_include_path) + + common_cflags = [] + if not is_standalone: + common_cflags.append(f'-DTORCH_EXTENSION_NAME={name}') + common_cflags.append('-DTORCH_API_INCLUDE_EXTENSION_H') + + # Windows does not understand `-isystem` and quotes flags later. + if IS_WINDOWS: + common_cflags += [f'-I{include}' for include in user_includes + system_includes] + else: + common_cflags += [f'-I{shlex.quote(include)}' for include in user_includes] + common_cflags += [f'-isystem {shlex.quote(include)}' for include in system_includes] + + if IS_WINDOWS: + COMMON_HIP_FLAGS.extend(['-fms-runtime-lib=dll']) + cflags = common_cflags + ['/std:c++20'] + extra_cflags + cflags += COMMON_MSVC_FLAGS + (COMMON_HIP_FLAGS if IS_HIP_EXTENSION else []) + cflags = _nt_quote_args(cflags) + else: + cflags = common_cflags + ['-fPIC', '-std=c++20'] + extra_cflags + + if with_cuda and IS_HIP_EXTENSION: + cuda_flags = ['-DWITH_HIP'] + common_cflags + extra_cflags + COMMON_HIP_FLAGS + COMMON_HIPCC_FLAGS + cuda_flags = cuda_flags + ['-std=c++20'] + cuda_flags += _get_rocm_arch_flags(cuda_flags) + cuda_flags += extra_cuda_cflags + if IS_WINDOWS: + cuda_flags = _nt_quote_args(cuda_flags) + elif with_cuda: + cuda_flags = common_cflags + COMMON_NVCC_FLAGS + _get_cuda_arch_flags(extra_cuda_cflags) + if IS_WINDOWS: + for flag in COMMON_MSVC_FLAGS: + cuda_flags = ['-Xcompiler', flag] + cuda_flags + for ignore_warning in MSVC_IGNORE_CUDAFE_WARNINGS: + cuda_flags = ['-Xcudafe', '--diag_suppress=' + ignore_warning] + cuda_flags + cuda_flags = cuda_flags + ['-std=c++20'] + cuda_flags = _nt_quote_args(cuda_flags) + cuda_flags += _nt_quote_args(extra_cuda_cflags) + else: + cuda_flags += ['--compiler-options', "'-fPIC'"] + cuda_flags += extra_cuda_cflags + if not any(flag.startswith('-std=') for flag in cuda_flags): + cuda_flags.append('-std=c++20') + cc_env = os.getenv("CC") + if cc_env is not None: + cuda_flags = ['-ccbin', cc_env] + cuda_flags + else: + cuda_flags = None + + if with_sycl: + sycl_cflags = cflags + _COMMON_SYCL_FLAGS + sycl_cflags += extra_sycl_cflags + _append_sycl_targets_if_missing(sycl_cflags) + _append_sycl_std_if_no_std_present(sycl_cflags) + host_cflags = cflags + # escaping quoted arguments to pass them thru SYCL compiler + icpx_version = _get_icpx_version() + if int(icpx_version) < 20250200: + host_cflags = [item.replace('\\"', '\\\\"') for item in host_cflags] + + sycl_cflags += _wrap_sycl_host_flags(host_cflags) + sycl_dlink_post_cflags = _SYCL_DLINK_FLAGS.copy() + sycl_dlink_post_cflags += _get_sycl_device_flags(sycl_cflags) + else: + sycl_cflags = None + sycl_dlink_post_cflags = None + + def object_file_path(source_file: str) -> str: + # '/path/to/file.cpp' -> 'file' + file_name = os.path.splitext(os.path.basename(source_file))[0] + if _is_cuda_file(source_file) and with_cuda: + # Use a different object filename in case a C++ and CUDA file have + # the same filename but different extension (.cpp vs. .cu). + target = f'{file_name}.cuda.o' + elif _is_sycl_file(source_file) and with_sycl: + target = f'{file_name}.sycl.o' + else: + target = f'{file_name}.o' + return target + + objects = [object_file_path(src) for src in sources] + ldflags = ([] if is_standalone else [SHARED_FLAG]) + extra_ldflags + + # The darwin linker needs explicit consent to ignore unresolved symbols. + if IS_MACOS: + ldflags.append('-undefined dynamic_lookup') + elif IS_WINDOWS: + ldflags = _nt_quote_args(ldflags) + + ext = EXEC_EXT if is_standalone else LIB_EXT + library_target = f'{name}{ext}' + + _write_ninja_file( + path=path, + cflags=cflags, + post_cflags=None, + cuda_cflags=cuda_flags, + cuda_post_cflags=None, + cuda_dlink_post_cflags=None, + sycl_cflags=sycl_cflags, + sycl_post_cflags=[], + sycl_dlink_post_cflags=sycl_dlink_post_cflags, + sources=sources, + objects=objects, + ldflags=ldflags, + library_target=library_target, + with_cuda=with_cuda, + with_sycl=with_sycl) + + +def _write_ninja_file(path, + cflags, + post_cflags, + cuda_cflags, + cuda_post_cflags, + cuda_dlink_post_cflags, + sycl_cflags, + sycl_post_cflags, + sycl_dlink_post_cflags, + sources, + objects, + ldflags, + library_target, + with_cuda, + with_sycl) -> None: + r"""Write a ninja file that does the desired compiling and linking. + + `path`: Where to write this file + `cflags`: list of flags to pass to $cxx. Can be None. + `post_cflags`: list of flags to append to the $cxx invocation. Can be None. + `cuda_cflags`: list of flags to pass to $nvcc. Can be None. + `cuda_post_cflags`: list of flags to append to the $nvcc invocation. Can be None. + `cuda_dlink_post_cflags`: list of flags to append to the $nvcc device code link invocation. Can be None. + `sycl_cflags`: list of flags to pass to SYCL compiler. Can be None. + `sycl_post_cflags`: list of flags to append to the SYCL compiler invocation. Can be None. + `sycl_dlink_post_cflags`: list of flags to append to the SYCL compiler device code link invocation. Can be None. +e. + `sources`: list of paths to source files + `objects`: list of desired paths to objects, one per source. + `ldflags`: list of flags to pass to linker. Can be None. + `library_target`: Name of the output library. Can be None; in that case, + we do no linking. + `with_cuda`: If we should be compiling with CUDA. + """ + def sanitize_flags(flags): + if flags is None: + return [] + else: + return [flag.strip() for flag in flags] + + cflags = sanitize_flags(cflags) + post_cflags = sanitize_flags(post_cflags) + cuda_cflags = sanitize_flags(cuda_cflags) + cuda_post_cflags = sanitize_flags(cuda_post_cflags) + cuda_dlink_post_cflags = sanitize_flags(cuda_dlink_post_cflags) + sycl_cflags = sanitize_flags(sycl_cflags) + sycl_post_cflags = sanitize_flags(sycl_post_cflags) + sycl_dlink_post_cflags = sanitize_flags(sycl_dlink_post_cflags) + ldflags = sanitize_flags(ldflags) + + # Sanity checks... + if len(sources) != len(objects): + raise AssertionError("sources and objects lists must be the same length") + if len(sources) == 0: + raise AssertionError("At least one source is required to build a library") + + compiler = get_cxx_compiler() + + # Version 1.3 is required for the `deps` directive. + config = ['ninja_required_version = 1.3'] + config.append(f'cxx = {_shell_join(_wrap_compiler(compiler))}') + if with_cuda or cuda_dlink_post_cflags: + if "PYTORCH_NVCC" in os.environ: + nvcc = os.getenv("PYTORCH_NVCC") # user can set nvcc compiler with ccache using the environment variable here + else: + if IS_HIP_EXTENSION: + nvcc = _get_hipcc_path() + else: + nvcc = _join_cuda_home('bin', 'nvcc') + nvcc = _shell_join(_wrap_compiler(nvcc)) + config.append(f'nvcc = {nvcc}') + if with_sycl or sycl_dlink_post_cflags: + sycl = 'icx' if IS_WINDOWS else 'icpx' + config.append(f'sycl = {sycl}') + + if IS_HIP_EXTENSION: + post_cflags = COMMON_HIP_FLAGS + post_cflags + flags = [f'cflags = {" ".join(cflags)}'] + flags.append(f'post_cflags = {" ".join(post_cflags)}') + if with_cuda: + flags.append(f'cuda_cflags = {" ".join(cuda_cflags)}') + flags.append(f'cuda_post_cflags = {" ".join(cuda_post_cflags)}') + flags.append(f'cuda_dlink_post_cflags = {" ".join(cuda_dlink_post_cflags)}') + if with_sycl: + flags.append(f'sycl_cflags = {" ".join(sycl_cflags)}') + flags.append(f'sycl_post_cflags = {" ".join(sycl_post_cflags)}') + flags.append(f'sycl_dlink_post_cflags = {" ".join(sycl_dlink_post_cflags)}') + flags.append(f'ldflags = {" ".join(ldflags)}') + + # Turn into absolute paths so we can emit them into the ninja build + # file wherever it is. + sources = [os.path.abspath(file) for file in sources] + + # See https://ninja-build.org/build.ninja.html for reference. + compile_rule = ['rule compile'] + if IS_WINDOWS: + compiler_name = "$cxx" if IS_HIP_EXTENSION else "cl" + compile_rule.append( + f' command = {compiler_name} ' + '/showIncludes $cflags -c $in /Fo$out $post_cflags' # codespell:ignore + ) + if not IS_HIP_EXTENSION: + compile_rule.append(' deps = msvc') + else: + compile_rule.append( + ' command = $cxx -MMD -MF $out.d $cflags -c $in -o $out $post_cflags') + compile_rule.append(' depfile = $out.d') + compile_rule.append(' deps = gcc') + + if with_cuda: + cuda_compile_rule = ['rule cuda_compile'] + nvcc_gendeps = '' + # -MD is not supported by ROCm + # Nvcc flag `-MD` is not supported by sccache, which may increase build time. + if torch.version.cuda is not None and os.getenv('TORCH_EXTENSION_SKIP_NVCC_GEN_DEPENDENCIES', '0') != '1': + cuda_compile_rule.append(' depfile = $out.d') + cuda_compile_rule.append(' deps = gcc') + # Note: non-system deps with nvcc are only supported + # on Linux so use -MD to make this work on Windows too. + nvcc_gendeps = '-MD -MF $out.d' + cuda_compile_rule.append( + f' command = $nvcc {nvcc_gendeps} $cuda_cflags -c $in -o $out $cuda_post_cflags') + + if with_sycl: + sycl_compile_rule = ['rule sycl_compile'] + # SYCL compiler does not recognize .sycl extension automatically, + # so we pass '-x c++' explicitly notifying compiler of file format + sycl_compile_rule.append( + ' command = $sycl $sycl_cflags -c -x c++ $in -o $out $sycl_post_cflags') + + + # Emit one build rule per source to enable incremental build. + build = [] + for source_file, object_file in zip(sources, objects, strict=True): + is_cuda_source = _is_cuda_file(source_file) and with_cuda + is_sycl_source = _is_sycl_file(source_file) and with_sycl + if is_cuda_source: + rule = 'cuda_compile' + elif is_sycl_source: + rule = 'sycl_compile' + else: + rule = 'compile' + if IS_WINDOWS: + source_file = source_file.replace(':', '$:') + object_file = object_file.replace(':', '$:') + source_file = source_file.replace(" ", "$ ") + object_file = object_file.replace(" ", "$ ") + build.append(f'build {object_file}: {rule} {source_file}') + + if cuda_dlink_post_cflags: + cuda_devlink_out = os.path.join(os.path.dirname(objects[0]), 'dlink.o') + cuda_devlink_rule = ['rule cuda_devlink'] + cuda_devlink_rule.append(' command = $nvcc $in -o $out $cuda_dlink_post_cflags') + cuda_devlink = [f'build {cuda_devlink_out}: cuda_devlink {" ".join(objects)}'] + objects += [cuda_devlink_out] + else: + cuda_devlink_rule, cuda_devlink = [], [] + + if sycl_dlink_post_cflags: + sycl_devlink_out = os.path.join(os.path.dirname(objects[0]), "sycl_dlink.o") + if IS_WINDOWS: + sycl_devlink_objects = [obj.replace(":", "$:") for obj in objects] + objects += [sycl_devlink_out] + sycl_devlink_out = sycl_devlink_out.replace(":", "$:") + else: + sycl_devlink_objects = list(objects) + objects += [sycl_devlink_out] + sycl_devlink_rule = ["rule sycl_devlink"] + sycl_devlink_rule.append( + " command = $sycl $in -o $out $sycl_dlink_post_cflags" + ) + sycl_devlink = [ + f"build {sycl_devlink_out}: sycl_devlink {' '.join(sycl_devlink_objects)}" + ] + else: + sycl_devlink_rule, sycl_devlink = [], [] + + if library_target is not None: + link_rule = ['rule link'] + if IS_WINDOWS: + cl_paths = subprocess.check_output(['where', + 'cl']).decode(*SUBPROCESS_DECODE_ARGS).split('\r\n') + if len(cl_paths) >= 1: + cl_path = os.path.dirname(cl_paths[0]).replace(':', '$:') + else: + raise RuntimeError("MSVC is required to load C++ extensions") + link_rule.append(f' command = "{cl_path}/link.exe" $in /nologo $ldflags /out:$out') + else: + link_rule.append(' command = $cxx $in $ldflags -o $out') + + link = [f'build {library_target}: link {" ".join(objects)}'] + + default = [f'default {library_target}'] + else: + link_rule, link, default = [], [], [] + + # 'Blocks' should be separated by newlines, for visual benefit. + blocks = [config, flags, compile_rule] + if with_cuda: + blocks.append(cuda_compile_rule) # type: ignore[possibly-undefined] + if with_sycl: + blocks.append(sycl_compile_rule) # type: ignore[possibly-undefined] + blocks += [cuda_devlink_rule, sycl_devlink_rule, link_rule, build, cuda_devlink, sycl_devlink, link, default] + content = "\n\n".join("\n".join(b) for b in blocks) + # Ninja requires a new lines at the end of the .ninja file + content += "\n" + _maybe_write(path, content) + +def _join_cuda_home(*paths) -> str: + """ + Join paths with CUDA_HOME, or raises an error if it CUDA_HOME is not set. + + This is basically a lazy way of raising an error for missing $CUDA_HOME + only once we need to get any CUDA-specific path. + """ + if CUDA_HOME is None: + raise OSError('CUDA_HOME environment variable is not set. ' + 'Please set it to your CUDA install root.') + return os.path.join(CUDA_HOME, *paths) + + +def _is_cuda_file(path: str) -> bool: + valid_ext = ['.cu', '.cuh'] + if IS_HIP_EXTENSION: + valid_ext.append('.hip') + return os.path.splitext(path)[1] in valid_ext + +def _is_sycl_file(path: str) -> bool: + valid_ext = ['.sycl'] + return os.path.splitext(path)[1] in valid_ext diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab5e7ce7f1c55a7b8bfff0bda646a4635231871 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/__init__.py @@ -0,0 +1,78 @@ +from torch.utils.data.dataloader import ( + _DatasetKind, + DataLoader, + default_collate, + default_convert, + get_worker_info, +) +from torch.utils.data.datapipes._decorator import ( + argument_validation, + functional_datapipe, + guaranteed_datapipes_determinism, + non_deterministic, + runtime_validation, + runtime_validation_disabled, +) +from torch.utils.data.datapipes.datapipe import ( + DataChunk, + DFIterDataPipe, + IterDataPipe, + MapDataPipe, +) +from torch.utils.data.dataset import ( + ChainDataset, + ConcatDataset, + Dataset, + IterableDataset, + random_split, + StackDataset, + Subset, + TensorDataset, +) +from torch.utils.data.distributed import DistributedSampler +from torch.utils.data.sampler import ( + BatchSampler, + RandomSampler, + Sampler, + SequentialSampler, + SubsetRandomSampler, + WeightedRandomSampler, +) + + +__all__ = [ + "BatchSampler", + "ChainDataset", + "ConcatDataset", + "DFIterDataPipe", + "DataChunk", + "DataLoader", + "Dataset", + "DistributedSampler", + "IterDataPipe", + "IterableDataset", + "MapDataPipe", + "RandomSampler", + "Sampler", + "SequentialSampler", + "StackDataset", + "Subset", + "SubsetRandomSampler", + "TensorDataset", + "WeightedRandomSampler", + "_DatasetKind", + "argument_validation", + "default_collate", + "default_convert", + "functional_datapipe", + "get_worker_info", + "guaranteed_datapipes_determinism", + "non_deterministic", + "random_split", + "runtime_validation", + "runtime_validation_disabled", +] + +# Please keep this list sorted +if __all__ != sorted(__all__): + raise AssertionError("__all__ is not sorted") diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9feb6082c6beb40a17f08f82950677db8abe3f4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/backward_compatibility.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/backward_compatibility.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba179220d22ff9c86da9376a719b14b1f8ed286e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/backward_compatibility.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/dataloader.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/dataloader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89ed012d18cc5b1621698636e3e1590299c007ea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/dataloader.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/dataset.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/dataset.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f146240d4528650188318325942f96a0c7cb632c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/dataset.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/distributed.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/distributed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b5d1097e111f5256b01e4c2d8db891ab80ed332 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/distributed.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/graph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3eacc0f71f3a26c0d05ea12419c5c0b6396e9c56 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/graph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/graph_settings.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/graph_settings.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..582155455dad507dd873e5e1eb148b91dec78ad7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/graph_settings.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/sampler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/sampler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abb6d71ea59335ec5b1ad53ee19a8d39110bf522 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/__pycache__/sampler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c3b16852820cb0afd8cdd6c5310584a809fec5e3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__init__.py @@ -0,0 +1,53 @@ +r"""Utility classes & functions for data loading. Code in this folder is mostly used by ../dataloader.py. + +A lot of multiprocessing is used in data loading, which only supports running +functions defined in global environment (py2 can't serialize static methods). +Therefore, for code tidiness we put these functions into different files in this +folder. +""" + +import atexit +import sys + +# old private location of the ExceptionWrapper that some users rely on: +from torch._utils import ExceptionWrapper + + +IS_WINDOWS = sys.platform == "win32" + + +MP_STATUS_CHECK_INTERVAL = 5.0 +r"""Interval (in seconds) to check status of processes to avoid hanging in + multiprocessing data loading. This is mainly used in getting data from + another process, in which case we need to periodically check whether the + sender is alive to prevent hanging.""" + + +python_exit_status = False +r"""Whether Python is shutting down. This flag is guaranteed to be set before +the Python core library resources are freed, but Python may already be exiting +for some time when this is set. + +Hook to set this flag is `_set_python_exit_flag`, and is inspired by a similar +hook in Python 3.7 multiprocessing library: +https://github.com/python/cpython/blob/d4d60134b29290049e28df54f23493de4f1824b6/Lib/multiprocessing/util.py#L277-L327 +""" + + +try: + import numpy + + HAS_NUMPY = True +except ModuleNotFoundError: + HAS_NUMPY = False + + +def _set_python_exit_flag() -> None: + global python_exit_status + python_exit_status = True + + +atexit.register(_set_python_exit_flag) + + +from . import collate, fetch, pin_memory, signal_handling, worker diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d0d5159de75ad135e17b3f50163825fc4367245 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/collate.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/collate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d921a9ef8114fc1adac67ca014975495c6ee5147 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/collate.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/fetch.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/fetch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c12a68cafee550d1b88cbd2c9a9b38e867d04ce Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/fetch.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/pin_memory.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/pin_memory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa753279998f3fb1db9b2d28936423effd015be6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/pin_memory.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/signal_handling.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/signal_handling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed9c683be7304c8d4e25648da8c7324a226d96a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/signal_handling.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/worker.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/worker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38e20e88ab266dee88bd7eb939394a8f8c1f48fb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/__pycache__/worker.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/collate.py b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/collate.py new file mode 100644 index 0000000000000000000000000000000000000000..f420eb57fe1114f1151c001d6097a344242997d7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/collate.py @@ -0,0 +1,401 @@ +# mypy: allow-untyped-defs +r"""Contains definitions of the methods used by the _BaseDataLoaderIter workers. + +These methods are used to collate samples fetched from dataset into Tensor(s). +These **need** to be in global scope since Py2 doesn't support serializing +static methods. + +`default_collate` and `default_convert` are exposed to users via 'dataloader.py'. +""" + +import collections +import contextlib +import copy +import re +from collections.abc import Callable + +import torch + + +np_str_obj_array_pattern = re.compile(r"[SaUO]") + + +def default_convert(data): + r""" + Convert each NumPy array element into a :class:`torch.Tensor`. + + If the input is a `Sequence`, `Collection`, or `Mapping`, it tries to convert each element inside to a :class:`torch.Tensor`. + If the input is not a NumPy array, it is left unchanged. + This is used as the default function for collation when both `batch_sampler` and `batch_size` + are NOT defined in :class:`~torch.utils.data.DataLoader`. + + The general input type to output type mapping is similar to that + of :func:`~torch.utils.data.default_collate`. See the description there for more details. + + Args: + data: a single data point to be converted + + Examples: + >>> # xdoctest: +SKIP + >>> # Example with `int` + >>> default_convert(0) + 0 + >>> # Example with NumPy array + >>> default_convert(np.array([0, 1])) + tensor([0, 1]) + >>> # Example with NamedTuple + >>> Point = namedtuple("Point", ["x", "y"]) + >>> default_convert(Point(0, 0)) + Point(x=0, y=0) + >>> default_convert(Point(np.array(0), np.array(0))) + Point(x=tensor(0), y=tensor(0)) + >>> # Example with List + >>> default_convert([np.array([0, 1]), np.array([2, 3])]) + [tensor([0, 1]), tensor([2, 3])] + """ + elem_type = type(data) + if isinstance(data, torch.Tensor): + return data + elif ( + elem_type.__module__ == "numpy" + and elem_type.__name__ != "str_" + and elem_type.__name__ != "string_" + ): + # array of string classes and object + if ( + elem_type.__name__ == "ndarray" + and np_str_obj_array_pattern.search(data.dtype.str) is not None + ): + return data + return torch.as_tensor(data) + elif isinstance(data, collections.abc.Mapping): + try: + if isinstance(data, collections.abc.MutableMapping): + # The mapping type may have extra properties, so we can't just + # use `type(data)(...)` to create the new mapping. + # Create a clone and update it if the mapping type is mutable. + clone = copy.copy(data) + clone.update({key: default_convert(data[key]) for key in data}) + return clone + else: + return elem_type({key: default_convert(data[key]) for key in data}) + except TypeError: + # The mapping type may not support `copy()` / `update(mapping)` + # or `__init__(iterable)`. + return {key: default_convert(data[key]) for key in data} + elif isinstance(data, tuple) and hasattr(data, "_fields"): # namedtuple + return elem_type(*(default_convert(d) for d in data)) + elif isinstance(data, tuple): + return [default_convert(d) for d in data] # Backwards compatibility. + elif isinstance(data, collections.abc.Sequence) and not isinstance( + data, (str, bytes) + ): + try: + if isinstance(data, collections.abc.MutableSequence): + # The sequence type may have extra properties, so we can't just + # use `type(data)(...)` to create the new sequence. + # Create a clone and update it if the sequence type is mutable. + clone = copy.copy(data) # type: ignore[arg-type] + for i, d in enumerate(data): + clone[i] = default_convert(d) + return clone + else: + return elem_type([default_convert(d) for d in data]) + except TypeError: + # The sequence type may not support `copy()` / `__setitem__(index, item)` + # or `__init__(iterable)` (e.g., `range`). + return [default_convert(d) for d in data] + else: + return data + + +default_collate_err_msg_format = ( + "default_collate: batch must contain tensors, numpy arrays, numbers, " + "dicts or lists; found {}" +) + + +def collate( + batch, + *, + collate_fn_map: dict[type | tuple[type, ...], Callable] | None = None, +): + r""" + General collate function that handles collection type of element within each batch. + + The function also opens function registry to deal with specific element types. `default_collate_fn_map` + provides default collate functions for tensors, numpy arrays, numbers and strings. + + Args: + batch: a single batch to be collated + collate_fn_map: Optional dictionary mapping from element type to the corresponding collate function. + If the element type isn't present in this dictionary, + this function will go through each key of the dictionary in the insertion order to + invoke the corresponding collate function if the element type is a subclass of the key. + + Examples: + >>> def collate_tensor_fn(batch, *, collate_fn_map): + ... # Extend this function to handle batch of tensors + ... return torch.stack(batch, 0) + >>> def custom_collate(batch): + ... collate_map = {torch.Tensor: collate_tensor_fn} + ... return collate(batch, collate_fn_map=collate_map) + >>> # Extend `default_collate` by in-place modifying `default_collate_fn_map` + >>> default_collate_fn_map.update({torch.Tensor: collate_tensor_fn}) + + Note: + Each collate function requires a positional argument for batch and a keyword argument + for the dictionary of collate functions as `collate_fn_map`. + """ + elem = batch[0] + elem_type = type(elem) + + if collate_fn_map is not None: + if elem_type in collate_fn_map: + return collate_fn_map[elem_type](batch, collate_fn_map=collate_fn_map) + + for collate_type in collate_fn_map: + if isinstance(elem, collate_type): + return collate_fn_map[collate_type]( + batch, collate_fn_map=collate_fn_map + ) + + if isinstance(elem, collections.abc.Mapping): + try: + if isinstance(elem, collections.abc.MutableMapping): + # The mapping type may have extra properties, so we can't just + # use `type(data)(...)` to create the new mapping. + # Create a clone and update it if the mapping type is mutable. + clone = copy.copy(elem) + clone.update( + { + key: collate( + [d[key] for d in batch], collate_fn_map=collate_fn_map + ) + for key in elem + } + ) + return clone + else: + return elem_type( + { + key: collate( + [d[key] for d in batch], collate_fn_map=collate_fn_map + ) + for key in elem + } + ) + except TypeError: + # The mapping type may not support `copy()` / `update(mapping)` + # or `__init__(iterable)`. + return { + key: collate([d[key] for d in batch], collate_fn_map=collate_fn_map) + for key in elem + } + elif isinstance(elem, tuple) and hasattr(elem, "_fields"): # namedtuple + return elem_type( + *( + collate(samples, collate_fn_map=collate_fn_map) + for samples in zip(*batch, strict=False) + ) + ) + elif isinstance(elem, collections.abc.Sequence): + # check to make sure that the elements in batch have consistent size + it = iter(batch) + elem_size = len(next(it)) + + if not all(len(elem) == elem_size for elem in it): + raise RuntimeError("each element in list of batch should be of equal size") + transposed = list( + zip(*batch, strict=False) + ) # It may be accessed twice, so we use a list. + + if isinstance(elem, tuple): + return [ + collate(samples, collate_fn_map=collate_fn_map) + for samples in transposed + ] # Backwards compatibility. + else: + try: + if isinstance(elem, collections.abc.MutableSequence): + # The sequence type may have extra properties, so we can't just + # use `type(data)(...)` to create the new sequence. + # Create a clone and update it if the sequence type is mutable. + clone = copy.copy(elem) # type: ignore[arg-type] + for i, samples in enumerate(transposed): + clone[i] = collate(samples, collate_fn_map=collate_fn_map) + return clone + else: + return elem_type( + [ + collate(samples, collate_fn_map=collate_fn_map) + for samples in transposed + ] + ) + except TypeError: + # The sequence type may not support `copy()` / `__setitem__(index, item)` + # or `__init__(iterable)` (e.g., `range`). + return [ + collate(samples, collate_fn_map=collate_fn_map) + for samples in transposed + ] + + raise TypeError(default_collate_err_msg_format.format(elem_type)) + + +def collate_tensor_fn( + batch, + *, + collate_fn_map: dict[type | tuple[type, ...], Callable] | None = None, +): + elem = batch[0] + out = None + if elem.is_nested: + raise RuntimeError( + "Batches of nested tensors are not currently supported by the default collate_fn; " + "please provide a custom collate_fn to handle them appropriately." + ) + if elem.layout in { + torch.sparse_coo, + torch.sparse_csr, + torch.sparse_bsr, + torch.sparse_csc, + torch.sparse_bsc, + }: + raise RuntimeError( + "Batches of sparse tensors are not currently supported by the default collate_fn; " + "please provide a custom collate_fn to handle them appropriately." + ) + if torch.utils.data.get_worker_info() is not None: + # If we're in a background process, concatenate directly into a + # shared memory tensor to avoid an extra copy + numel = sum(x.numel() for x in batch) + storage = elem._typed_storage()._new_shared(numel, device=elem.device) + out = elem.new(storage).resize_(len(batch), *list(elem.size())) + return torch.stack(batch, 0, out=out) + + +def collate_numpy_array_fn( + batch, + *, + collate_fn_map: dict[type | tuple[type, ...], Callable] | None = None, +): + elem = batch[0] + # array of string classes and object + if np_str_obj_array_pattern.search(elem.dtype.str) is not None: + raise TypeError(default_collate_err_msg_format.format(elem.dtype)) + + return collate([torch.as_tensor(b) for b in batch], collate_fn_map=collate_fn_map) + + +def collate_numpy_scalar_fn( + batch, + *, + collate_fn_map: dict[type | tuple[type, ...], Callable] | None = None, +): + return torch.as_tensor(batch) + + +def collate_float_fn( + batch, + *, + collate_fn_map: dict[type | tuple[type, ...], Callable] | None = None, +): + return torch.tensor(batch, dtype=torch.float64) + + +def collate_int_fn( + batch, + *, + collate_fn_map: dict[type | tuple[type, ...], Callable] | None = None, +): + return torch.tensor(batch) + + +def collate_str_fn( + batch, + *, + collate_fn_map: dict[type | tuple[type, ...], Callable] | None = None, +): + return batch + + +default_collate_fn_map: dict[type | tuple[type, ...], Callable] = { + torch.Tensor: collate_tensor_fn +} +with contextlib.suppress(ImportError): + import numpy as np + + # For both ndarray and memmap (subclass of ndarray) + default_collate_fn_map[np.ndarray] = collate_numpy_array_fn + # See scalars hierarchy: https://numpy.org/doc/stable/reference/arrays.scalars.html + # Skip string scalars + default_collate_fn_map[(np.bool_, np.number, np.object_)] = collate_numpy_scalar_fn +default_collate_fn_map[float] = collate_float_fn +default_collate_fn_map[int] = collate_int_fn +default_collate_fn_map[str] = collate_str_fn +default_collate_fn_map[bytes] = collate_str_fn + + +def default_collate(batch): + r""" + Take in a batch of data and put the elements within the batch into a tensor with an additional outer dimension - batch size. + + The exact output type can be a :class:`torch.Tensor`, a `Sequence` of :class:`torch.Tensor`, a + Collection of :class:`torch.Tensor`, or left unchanged, depending on the input type. + This is used as the default function for collation when + `batch_size` or `batch_sampler` is defined in :class:`~torch.utils.data.DataLoader`. + + Here is the general input type (based on the type of the element within the batch) to output type mapping: + + * :class:`torch.Tensor` -> :class:`torch.Tensor` (with an added outer dimension batch size) + * NumPy Arrays -> :class:`torch.Tensor` + * `float` -> :class:`torch.Tensor` + * `int` -> :class:`torch.Tensor` + * `str` -> `str` (unchanged) + * `bytes` -> `bytes` (unchanged) + * `Mapping[K, V_i]` -> `Mapping[K, default_collate([V_1, V_2, ...])]` + * `NamedTuple[V1_i, V2_i, ...]` -> `NamedTuple[default_collate([V1_1, V1_2, ...]), + default_collate([V2_1, V2_2, ...]), ...]` + * `Sequence[V1_i, V2_i, ...]` -> `Sequence[default_collate([V1_1, V1_2, ...]), + default_collate([V2_1, V2_2, ...]), ...]` + + Args: + batch: a single batch to be collated + + Examples: + >>> # xdoctest: +SKIP + >>> # Example with a batch of `int`s: + >>> default_collate([0, 1, 2, 3]) + tensor([0, 1, 2, 3]) + >>> # Example with a batch of `str`s: + >>> default_collate(["a", "b", "c"]) + ['a', 'b', 'c'] + >>> # Example with `Map` inside the batch: + >>> default_collate([{"A": 0, "B": 1}, {"A": 100, "B": 100}]) + {'A': tensor([ 0, 100]), 'B': tensor([ 1, 100])} + >>> # Example with `NamedTuple` inside the batch: + >>> Point = namedtuple("Point", ["x", "y"]) + >>> default_collate([Point(0, 0), Point(1, 1)]) + Point(x=tensor([0, 1]), y=tensor([0, 1])) + >>> # Example with `Tuple` inside the batch: + >>> default_collate([(0, 1), (2, 3)]) + [tensor([0, 2]), tensor([1, 3])] + >>> # Example with `List` inside the batch: + >>> default_collate([[0, 1], [2, 3]]) + [tensor([0, 2]), tensor([1, 3])] + >>> # Two options to extend `default_collate` to handle specific type + >>> # Option 1: Write custom collate function and invoke `default_collate` + >>> def custom_collate(batch): + ... elem = batch[0] + ... if isinstance(elem, CustomType): # Some custom condition + ... return ... + ... else: # Fall back to `default_collate` + ... return default_collate(batch) + >>> # Option 2: In-place modify `default_collate_fn_map` + >>> def collate_customtype_fn(batch, *, collate_fn_map=None): + ... return ... + >>> default_collate_fn_map.update(CustomType, collate_customtype_fn) + >>> default_collate(batch) # Handle `CustomType` automatically + """ + return collate(batch, collate_fn_map=default_collate_fn_map) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/fetch.py b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/fetch.py new file mode 100644 index 0000000000000000000000000000000000000000..9bcd0ec5b30731269fc304b5ef2e087d94dc3211 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/fetch.py @@ -0,0 +1,57 @@ +# mypy: allow-untyped-defs +r"""Contains definitions of the methods used by the _BaseDataLoaderIter to fetch data from an iterable-style or map-style dataset. + +This logic is shared in both single- and multi-processing data loading. +""" + +from typing import NoReturn + + +class _BaseDatasetFetcher: + def __init__(self, dataset, auto_collation, collate_fn, drop_last) -> None: + self.dataset = dataset + self.auto_collation = auto_collation + self.collate_fn = collate_fn + self.drop_last = drop_last + + def fetch(self, possibly_batched_index) -> NoReturn: + raise NotImplementedError + + +class _IterableDatasetFetcher(_BaseDatasetFetcher): + def __init__(self, dataset, auto_collation, collate_fn, drop_last) -> None: + super().__init__(dataset, auto_collation, collate_fn, drop_last) + self.dataset_iter = iter(dataset) + self.ended = False + + def fetch(self, possibly_batched_index): + if self.ended: + raise StopIteration + + if self.auto_collation: + data = [] + for _ in possibly_batched_index: + try: + data.append(next(self.dataset_iter)) + except StopIteration: + self.ended = True + break + if len(data) == 0 or ( + self.drop_last and len(data) < len(possibly_batched_index) + ): + raise StopIteration + else: + data = next(self.dataset_iter) + return self.collate_fn(data) + + +class _MapDatasetFetcher(_BaseDatasetFetcher): + def fetch(self, possibly_batched_index): + if self.auto_collation: + if hasattr(self.dataset, "__getitems__") and self.dataset.__getitems__: + data = self.dataset.__getitems__(possibly_batched_index) + else: + data = [self.dataset[idx] for idx in possibly_batched_index] + else: + data = self.dataset[possibly_batched_index] + return self.collate_fn(data) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/pin_memory.py b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/pin_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..69aacf272142e03fda640496a951baadd6180ead --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/pin_memory.py @@ -0,0 +1,108 @@ +# mypy: allow-untyped-defs +r"""Contains definitions of the methods used by the _BaseDataLoaderIter to put fetched tensors into pinned memory. + +These **need** to be in global scope since Py2 doesn't support serializing +static methods. +""" + +import collections +import copy +import queue + +import torch +from torch._utils import ExceptionWrapper + +from . import MP_STATUS_CHECK_INTERVAL + + +def _pin_memory_loop(in_queue, out_queue, device_id, done_event, device) -> None: + # This setting is thread local, and prevents the copy in pin_memory from + # consuming all CPU cores. + torch.set_num_threads(1) + + torch.multiprocessing._set_thread_name("pt_data_pin") + torch.accelerator.set_device_index(device_id) + + def do_one_step() -> None: + try: + r = in_queue.get(timeout=MP_STATUS_CHECK_INTERVAL) + except queue.Empty: + return + idx, data = r + if not done_event.is_set() and not isinstance(data, ExceptionWrapper): + try: + data = pin_memory(data, device) + except Exception: + data = ExceptionWrapper( + where=f"in pin memory thread for device {device_id}" + ) + r = (idx, data) + while not done_event.is_set(): + try: + out_queue.put(r, timeout=MP_STATUS_CHECK_INTERVAL) + break + except queue.Full: + continue + + # See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on the + # logic of this function. + while not done_event.is_set(): + # Make sure that we don't preserve any object from one iteration + # to the next + do_one_step() + + +def pin_memory(data, device=None): + if isinstance(data, torch.Tensor): + return data.pin_memory() + + if hasattr(data, "pin_memory"): + return data.pin_memory() + + if isinstance(data, (str, bytes)): + return data + + if isinstance(data, collections.abc.Mapping): + try: + if isinstance(data, collections.abc.MutableMapping): + # The mapping type may have extra properties, so we can't just + # use `type(data)(...)` to create the new mapping. + # Create a clone and update it if the mapping type is mutable. + clone = copy.copy(data) + clone.update( + {k: pin_memory(sample, device) for k, sample in data.items()} + ) + return clone + else: + # pyrefly: ignore [bad-instantiation] + return type(data)( + # pyrefly: ignore [bad-argument-count] + {k: pin_memory(sample, device) for k, sample in data.items()} + ) # type: ignore[call-arg] + except TypeError: + # The mapping type may not support `copy()` / `update(mapping)` + # or `__init__(iterable)`. + return {k: pin_memory(sample, device) for k, sample in data.items()} + + if isinstance(data, tuple): + if hasattr(data, "_fields"): # namedtuple + return type(data)(*(pin_memory(sample, device) for sample in data)) + return type(data)(pin_memory(sample, device) for sample in data) + + if isinstance(data, collections.abc.Sequence): + try: + if isinstance(data, collections.abc.MutableSequence): + # The sequence type may have extra properties, so we can't just + # use `type(data)(...)` to create the new sequence. + # Create a clone and update it if the sequence type is mutable. + clone = copy.copy(data) # type: ignore[arg-type] + for i, item in enumerate(data): + clone[i] = pin_memory(item, device) + return clone + return type(data)([pin_memory(sample, device) for sample in data]) # type: ignore[call-arg] + except TypeError: + # The sequence type may not support `copy()` / `__setitem__(index, item)` + # or `__init__(iterable)` (e.g., `range`). + return [pin_memory(sample, device) for sample in data] + + return data diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/signal_handling.py b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/signal_handling.py new file mode 100644 index 0000000000000000000000000000000000000000..77970be83c2fffb254aa960e376e76dc7a0429a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/signal_handling.py @@ -0,0 +1,80 @@ +# mypy: allow-untyped-defs +r"""Signal handling for multiprocessing data loading. + +NOTE [ Signal handling in multiprocessing data loading ] + +In cases like DataLoader, if a worker process dies due to bus error/segfault +or just hang, the main process will hang waiting for data. This is difficult +to avoid on PyTorch side as it can be caused by limited shm, or other +libraries users call in the workers. In this file and `DataLoader.cpp`, we make +our best effort to provide some error message to users when such unfortunate +events happen. + +When a _BaseDataLoaderIter starts worker processes, their pids are registered in a +defined in `DataLoader.cpp`: id(_BaseDataLoaderIter) => Collection[ Worker pids ] +via `_set_worker_pids`. + +When an error happens in a worker process, the main process receives a SIGCHLD, +and Python will eventually call the handler registered below +(in `_set_SIGCHLD_handler`). In the handler, the `_error_if_any_worker_fails` +call checks all registered worker pids and raises a proper error message to +prevent main process from hanging waiting for data from worker. + +Additionally, at the beginning of each worker's `_utils.worker._worker_loop`, +`_set_worker_signal_handlers` is called to register critical signal handlers +(e.g., for SIGSEGV, SIGBUS, SIGFPE, SIGTERM) in C, which just prints an error +message to stderr before triggering the default handler. So a message will also +be printed from the worker process when it is killed by such signals. + +See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for the reasoning of +this signal handling design and other mechanism we implement to make our +multiprocessing data loading robust to errors. +""" + +import signal +import threading + +# Some of the following imported functions are not used in this file, but are to +# be used `_utils.signal_handling.XXXXX`. +from torch._C import ( # noqa: F401 + _error_if_any_worker_fails, + _remove_worker_pids, + _set_worker_pids, + _set_worker_signal_handlers, +) + +from . import IS_WINDOWS + + +_SIGCHLD_handler_set = False +r"""Whether SIGCHLD handler is set for DataLoader worker failures. Only one +handler needs to be set for all DataLoaders in a process.""" + + +def _set_SIGCHLD_handler() -> None: + # Windows doesn't support SIGCHLD handler + if IS_WINDOWS: + return + # can't set signal in child threads + if not isinstance(threading.current_thread(), threading._MainThread): # type: ignore[attr-defined] + return + global _SIGCHLD_handler_set + if _SIGCHLD_handler_set: + return + previous_handler = signal.getsignal(signal.SIGCHLD) + if not callable(previous_handler): + # This doesn't catch default handler, but SIGCHLD default handler is a + # no-op. + previous_handler = None + + def handler(signum, frame) -> None: + # This following call uses `waitid` with WNOHANG from C side. Therefore, + # Python can still get and update the process status successfully. + _error_if_any_worker_fails() + if previous_handler is not None: + if not callable(previous_handler): + raise AssertionError("previous_handler is not callable") + previous_handler(signum, frame) + + signal.signal(signal.SIGCHLD, handler) + _SIGCHLD_handler_set = True diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/worker.py b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..d19d1a7715375520163bc23d31ee74788828a08f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/_utils/worker.py @@ -0,0 +1,402 @@ +# mypy: allow-untyped-defs +r"""Contains definitions of the methods used by the _BaseDataLoaderIter workers. + +These **need** to be in global scope since Py2 doesn't support serializing +static methods. +""" + +from __future__ import annotations + +import os +import queue +import random +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import torch +from torch._utils import ExceptionWrapper + +from . import HAS_NUMPY, IS_WINDOWS, MP_STATUS_CHECK_INTERVAL, signal_handling + + +if TYPE_CHECKING: + from torch.utils.data import Dataset + +if IS_WINDOWS: + import ctypes + from ctypes.wintypes import BOOL, DWORD, HANDLE + + # On Windows, the parent ID of the worker process remains unchanged when the manager process + # is gone, and the only way to check it through OS is to let the worker have a process handle + # of the manager and ask if the process status has changed. + class ManagerWatchdog: + def __init__(self) -> None: + self.manager_pid = os.getppid() + + # mypy cannot detect this code is windows only + self.kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) # type: ignore[attr-defined] + self.kernel32.OpenProcess.argtypes = (DWORD, BOOL, DWORD) + self.kernel32.OpenProcess.restype = HANDLE + self.kernel32.WaitForSingleObject.argtypes = (HANDLE, DWORD) + self.kernel32.WaitForSingleObject.restype = DWORD + + # Value obtained from https://msdn.microsoft.com/en-us/library/ms684880.aspx + SYNCHRONIZE = 0x00100000 + self.manager_handle = self.kernel32.OpenProcess( + SYNCHRONIZE, 0, self.manager_pid + ) + + if not self.manager_handle: + raise ctypes.WinError(ctypes.get_last_error()) # type: ignore[attr-defined] + + self.manager_dead = False + + def is_alive(self) -> bool: + if not self.manager_dead: + # Value obtained from https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032.aspx + self.manager_dead = ( + self.kernel32.WaitForSingleObject(self.manager_handle, 0) == 0 + ) + return not self.manager_dead + +else: + + class ManagerWatchdog: # type: ignore[no-redef] + def __init__(self) -> None: + self.manager_pid = os.getppid() + self.manager_dead = False + + def is_alive(self) -> bool: + if not self.manager_dead: + self.manager_dead = os.getppid() != self.manager_pid + return not self.manager_dead + + +_worker_info: WorkerInfo | None = None + + +@dataclass(frozen=True, slots=True) +class WorkerInfo: + """Information about the current DataLoader worker process or thread. + + Attributes: + id: The current worker id (0 to num_workers - 1) + num_workers: Total number of workers + seed: Random seed set for this worker + dataset: Copy of the dataset object in this worker + rng: Optional RNG state container. Defaults to None. + worker_method: Optional worker method ("multiprocessing" or "thread"). Defaults to "multiprocessing". + """ + + id: int + num_workers: int + seed: int + dataset: Dataset + rng: _RNG | None = None + worker_method: str | None = "multiprocessing" + + +def get_worker_info() -> WorkerInfo | None: + r"""Returns the information about the current + :class:`~torch.utils.data.DataLoader` iterator worker process. + + When called in a worker, this returns an object guaranteed to have the + following attributes: + + * :attr:`id`: the current worker id. + * :attr:`num_workers`: the total number of workers. + * :attr:`seed`: the random seed set for the current worker. This value is + determined by main process RNG and the worker id. See + :class:`~torch.utils.data.DataLoader`'s documentation for more details. + * :attr:`dataset`: the copy of the dataset object in **this** process. Note + that this will be a different object in a different process than the one + in the main process. + + When called in the main process, this returns ``None``. + + .. note:: + When used in a :attr:`worker_init_fn` passed over to + :class:`~torch.utils.data.DataLoader`, this method can be useful to + set up each worker process differently, for instance, using ``worker_id`` + to configure the ``dataset`` object to only read a specific fraction of a + sharded dataset, or use ``seed`` to seed other libraries used in dataset + code. + """ + return _worker_info + + +r"""Dummy class used to signal the end of an IterableDataset""" + + +@dataclass(frozen=True) +class _IterableDatasetStopIteration: + worker_id: int + + +r"""Dummy class used to resume the fetching when worker reuse is enabled""" + + +@dataclass(frozen=True) +class _ResumeIteration: + seed: int | None = None + + +@dataclass(frozen=True, slots=True) +class _RNG: + """Container for thread-local random number generator state. + + Used by thread workers to maintain separate RNG state per worker thread + to avoid race conditions. + + Attributes: + random_generator: Python random.Random generator for this thread + torch_generator: PyTorch Generator for this thread + numpy_generator: NumPy Generator for this thread (None if numpy not available) + """ + + random_generator: random.Random + torch_generator: torch.Generator + numpy_generator: object | None = None + + +# The function `_generate_state` is adapted from `numpy.random.SeedSequence` +# from https://github.com/numpy/numpy/blob/main/numpy/random/bit_generator.pyx +# It's MIT licensed, here is the copyright: + +# Copyright (c) 2015 Melissa E. O'Neill +# Copyright (c) 2019 NumPy Developers +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + + +# This function generates an array of int32 as the seed for +# `numpy.random`, in order to prevent state collision due to same +# seed and algorithm for `numpy.random` and `random` modules. +# TODO: Implement `SeedSequence` like object for `torch.random` +def _generate_state(base_seed, worker_id): + INIT_A = 0x43B0D7E5 + MULT_A = 0x931E8875 + INIT_B = 0x8B51F9DD + MULT_B = 0x58F38DED + MIX_MULT_L = 0xCA01F9DD + MIX_MULT_R = 0x4973F715 + XSHIFT = 4 * 8 // 2 + MASK32 = 0xFFFFFFFF + + entropy = [worker_id, base_seed & MASK32, base_seed >> 32, 0] + pool = [0] * 4 + + hash_const_A = INIT_A + + def hash(value): + nonlocal hash_const_A + value = (value ^ hash_const_A) & MASK32 + hash_const_A = (hash_const_A * MULT_A) & MASK32 + value = (value * hash_const_A) & MASK32 + value = (value ^ (value >> XSHIFT)) & MASK32 + return value + + def mix(x, y): + result_x = (MIX_MULT_L * x) & MASK32 + result_y = (MIX_MULT_R * y) & MASK32 + result = (result_x - result_y) & MASK32 + result = (result ^ (result >> XSHIFT)) & MASK32 + return result + + # Add in the entropy to the pool. + for i in range(len(pool)): + pool[i] = hash(entropy[i]) + + # Mix all bits together so late bits can affect earlier bits. + for i_src in range(len(pool)): + for i_dst in range(len(pool)): + if i_src != i_dst: + pool[i_dst] = mix(pool[i_dst], hash(pool[i_src])) + + hash_const_B = INIT_B + state = [] + for i_dst in range(4): + data_val = pool[i_dst] + data_val = (data_val ^ hash_const_B) & MASK32 + hash_const_B = (hash_const_B * MULT_B) & MASK32 + data_val = (data_val * hash_const_B) & MASK32 + data_val = (data_val ^ (data_val >> XSHIFT)) & MASK32 + state.append(data_val) + return state + + +def _worker_loop( + dataset_kind, + dataset_holder, + index_queue, + data_queue, + done_event, + auto_collation, + collate_fn, + drop_last, + base_seed, + init_fn, + worker_id, + num_workers, + persistent_workers, + shared_seed, +) -> None: + # See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on the + # logic of this function. + dataset = dataset_holder.pop() + + try: + # Initialize C side signal handlers for SIGBUS and SIGSEGV. Python signal + # module's handlers are executed after Python returns from C low-level + # handlers, likely when the same fatal signal had already happened + # again. + # https://docs.python.org/3/library/signal.html#execution-of-python-signal-handlers + signal_handling._set_worker_signal_handlers() + + torch.multiprocessing._set_thread_name("pt_data_worker") + + torch.set_num_threads(1) + seed = base_seed + worker_id + random.seed(seed) + torch.manual_seed(seed) + if HAS_NUMPY: + np_seed = _generate_state(base_seed, worker_id) + import numpy as np + + np.random.seed(np_seed) + + from torch.utils.data import IterDataPipe + from torch.utils.data.graph_settings import apply_random_seed + + shared_rng = torch.Generator() + if isinstance(dataset, IterDataPipe): + if shared_seed is None: + raise AssertionError( + "shared_seed must be provided for IterDataPipe workers" + ) + shared_rng.manual_seed(shared_seed) + dataset = apply_random_seed(dataset, shared_rng) + + global _worker_info + _worker_info = WorkerInfo( + id=worker_id, num_workers=num_workers, seed=seed, dataset=dataset + ) + + from torch.utils.data import _DatasetKind + + init_exception = None + + try: + if init_fn is not None: + init_fn(worker_id) + + fetcher = _DatasetKind.create_fetcher( + dataset_kind, dataset, auto_collation, collate_fn, drop_last + ) + except Exception: + init_exception = ExceptionWrapper( + where=f"in DataLoader worker process {worker_id}" + ) + + # When using Iterable mode, some worker can exit earlier than others due + # to the IterableDataset behaving differently for different workers. + # When such things happen, an `_IterableDatasetStopIteration` object is + # sent over to the main process with the ID of this worker, so that the + # main process won't send more tasks to this worker, and will send + # `None` to this worker to properly exit it. + # + # Note that we cannot set `done_event` from a worker as it is shared + # among all processes. Instead, we set the `iteration_end` flag to + # signify that the iterator is exhausted. When either `done_event` or + # `iteration_end` is set, we skip all processing step and just wait for + # `None`. + iteration_end = False + + watchdog = ManagerWatchdog() + + while watchdog.is_alive(): + try: + r = index_queue.get(timeout=MP_STATUS_CHECK_INTERVAL) + except queue.Empty: + continue + if isinstance(r, _ResumeIteration): + # Acknowledge the main process + data_queue.put((r, None)) + iteration_end = False + + if isinstance(dataset, IterDataPipe): + if r.seed is None: + raise AssertionError( + "resume iteration seed is None for IterDataPipe" + ) + shared_rng.manual_seed(r.seed) + dataset = apply_random_seed(dataset, shared_rng) + + # Recreate the fetcher for worker-reuse policy + fetcher = _DatasetKind.create_fetcher( + dataset_kind, dataset, auto_collation, collate_fn, drop_last + ) + continue + elif r is None: + # Received the final signal + if not done_event.is_set() and not iteration_end: + raise AssertionError( + "Received final signal but neither done_event nor iteration_end is set" + ) + break + elif done_event.is_set() or iteration_end: + # `done_event` is set. But I haven't received the final signal + # (None) yet. I will keep continuing until get it, and skip the + # processing steps. + continue + idx, index = r + data: _IterableDatasetStopIteration | ExceptionWrapper + if init_exception is not None: + data = init_exception + init_exception = None + else: + try: + data = fetcher.fetch(index) # type: ignore[possibly-undefined] + except Exception as e: + if ( + isinstance(e, StopIteration) + and dataset_kind == _DatasetKind.Iterable + ): + data = _IterableDatasetStopIteration(worker_id) + # Set `iteration_end` + # (1) to save future `next(...)` calls, and + # (2) to avoid sending multiple `_IterableDatasetStopIteration`s. + iteration_end = True + else: + # It is important that we don't store exc_info in a variable. + # `ExceptionWrapper` does the correct thing. + # See NOTE [ Python Traceback Reference Cycle Problem ] + data = ExceptionWrapper( + where=f"in DataLoader worker process {worker_id}" + ) + data_queue.put((idx, data)) + del data, idx, index, r # save memory + except KeyboardInterrupt: + # Main process will raise KeyboardInterrupt anyways. + pass + finally: + _worker_info = None + if done_event.is_set(): + data_queue.cancel_join_thread() + data_queue.close() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/backward_compatibility.py b/.venv/lib/python3.12/site-packages/torch/utils/data/backward_compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..5b928aea69fa7a7033a82021c5f41e053ff962fa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/backward_compatibility.py @@ -0,0 +1,11 @@ +# mypy: allow-untyped-defs +from typing_extensions import deprecated as _deprecated + + +@_deprecated( + "Usage of `backward_compatibility.worker_init_fn` is deprecated " + "as `DataLoader` automatically applies sharding in every worker", + category=FutureWarning, +) +def worker_init_fn(worker_id) -> None: + pass diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py b/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..068c57e9fdf1f0087b76bd7bb67a062e6f75bc6a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/dataloader.py @@ -0,0 +1,1706 @@ +# mypy: allow-untyped-defs +r"""Definition of the DataLoader and associated iterators that subclass _BaseDataLoaderIter. + +To support these two classes, in `./_utils` we define many utility methods and +functions to be run in multiprocessing. E.g., the data loading worker loop is +in `./_utils/worker.py`. +""" + +from __future__ import annotations + +import contextlib +import functools +import itertools +import logging +import multiprocessing as python_multiprocessing +import os +import queue +import threading +import warnings +import weakref +from collections.abc import Callable +from typing import Any, Generic, NoReturn, TYPE_CHECKING, TypeVar +from typing_extensions import Self + +import torch +import torch.distributed as dist +import torch.utils.data.graph_settings +from torch._utils import ExceptionWrapper +from torch.utils.data import _utils +from torch.utils.data.datapipes.datapipe import ( + _IterDataPipeSerializationWrapper, + _MapDataPipeSerializationWrapper, + IterDataPipe, + MapDataPipe, +) +from torch.utils.data.dataset import Dataset, IterableDataset +from torch.utils.data.sampler import ( + BatchSampler, + RandomSampler, + Sampler, + SequentialSampler, +) + + +if TYPE_CHECKING: + from collections.abc import Iterable + +__all__ = [ + "DataLoader", + "get_worker_info", + "default_collate", + "default_convert", +] + + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_worker_init_fn_t = Callable[[int], None] + +# Ideally we would parameterize `DataLoader` by the return type of `collate_fn`, but there is currently no way to have that +# type parameter set to a default value if the user doesn't pass in a custom 'collate_fn'. +# See https://github.com/python/mypy/issues/3737. +_collate_fn_t = Callable[[list[_T]], Any] + + +# These functions used to be defined in this file. However, it was moved to +# _utils/collate.py. Although it is rather hard to access this from user land +# (one has to explicitly directly `import torch.utils.data.dataloader`), there +# probably is user code out there using it. This aliasing maintains BC in this +# aspect. +default_collate: _collate_fn_t = _utils.collate.default_collate +default_convert = _utils.collate.default_convert + +get_worker_info = _utils.worker.get_worker_info + +logger = logging.getLogger(__name__) + +_persistent_workers_atexit_lock = threading.Lock() +_persistent_workers_atexit_registered = False +_persistent_workers_atexit: weakref.WeakSet[_MultiProcessingDataLoaderIter] = ( + weakref.WeakSet() +) + + +class _DatasetKind: + Map = 0 + Iterable = 1 + + @staticmethod + def create_fetcher(kind, dataset, auto_collation, collate_fn, drop_last): + if kind == _DatasetKind.Map: + return _utils.fetch._MapDatasetFetcher( + dataset, auto_collation, collate_fn, drop_last + ) + else: + return _utils.fetch._IterableDatasetFetcher( + dataset, auto_collation, collate_fn, drop_last + ) + + +class _InfiniteConstantSampler(Sampler): + r"""Analogous to ``itertools.repeat(None, None)``. + + Used as sampler for :class:`~torch.utils.data.IterableDataset`. + """ + + def __iter__(self): + while True: + yield None + + +def _get_distributed_settings(): + if dist.is_available() and dist.is_initialized(): + return dist.get_world_size(), dist.get_rank() + else: + return 1, 0 + + +def _sharding_worker_init_fn(worker_init_fn, world_size, rank_id, worker_id) -> None: + global_worker_id = worker_id + info = torch.utils.data.get_worker_info() + if info is None: + raise AssertionError("Worker info is None in sharding worker init function") + total_workers = info.num_workers + datapipe = info.dataset + if not isinstance(datapipe, (IterDataPipe, MapDataPipe)): + raise AssertionError( + "datapipe must be an instance of IterDataPipe or MapDataPipe" + ) + # To distribute elements across distributed process evenly, we should shard data on distributed + # processes first then shard on worker processes + total_workers *= world_size + global_worker_id = global_worker_id * world_size + rank_id + # For BC, use default SHARDING_PRIORITIES + torch.utils.data.graph_settings.apply_sharding( + datapipe, total_workers, global_worker_id + ) + if worker_init_fn is not None: + worker_init_fn(worker_id) + + +def _share_dist_seed(generator, pg): + _shared_seed = torch.empty((), dtype=torch.int64).random_(generator=generator) + if isinstance(pg, dist.ProcessGroup): + dist.broadcast(_shared_seed, src=0, group=pg) + return _shared_seed.item() + + +class DataLoader(Generic[_T_co]): + r""" + Data loader combines a dataset and a sampler, and provides an iterable over the given dataset. + + The :class:`~torch.utils.data.DataLoader` supports both map-style and + iterable-style datasets with single- or multi-process loading, customizing + loading order and optional automatic batching (collation) and memory pinning. + + See :py:mod:`torch.utils.data` documentation page for more details. + + Args: + dataset (Dataset): dataset from which to load the data. + batch_size (int, optional): how many samples per batch to load + (default: ``1``). + shuffle (bool, optional): set to ``True`` to have the data reshuffled + at every epoch (default: ``False``). + sampler (Sampler or Iterable, optional): defines the strategy to draw + samples from the dataset. Can be any ``Iterable`` with ``__len__`` + implemented. If specified, :attr:`shuffle` must not be specified. + batch_sampler (Sampler or Iterable, optional): like :attr:`sampler`, but + returns a batch of indices at a time. Mutually exclusive with + :attr:`batch_size`, :attr:`shuffle`, :attr:`sampler`, + and :attr:`drop_last`. + num_workers (int, optional): how many subprocesses to use for data + loading. ``0`` means that the data will be loaded in the main process. + (default: ``0``) + collate_fn (Callable, optional): merges a list of samples to form a + mini-batch of Tensor(s). Used when using batched loading from a + map-style dataset. + pin_memory (bool, optional): If ``True``, the data loader will copy Tensors + into device/CUDA pinned memory before returning them. If your data elements + are a custom type, or your :attr:`collate_fn` returns a batch that is a custom type, + see the example below. + drop_last (bool, optional): set to ``True`` to drop the last incomplete batch, + if the dataset size is not divisible by the batch size. If ``False`` and + the size of dataset is not divisible by the batch size, then the last batch + will be smaller. (default: ``False``) + timeout (numeric, optional): if positive, the timeout value for collecting a batch + from workers. Should always be non-negative. (default: ``0``) + worker_init_fn (Callable, optional): If not ``None``, this will be called on each + worker subprocess with the worker id (an int in ``[0, num_workers - 1]``) as + input, after seeding and before data loading. (default: ``None``) + multiprocessing_context (str or multiprocessing.context.BaseContext, optional): If + ``None``, the default + `multiprocessing context `_ # noqa: D401 + of your operating system will + be used. (default: ``None``) + generator (torch.Generator, optional): If not ``None``, this RNG will be used + by RandomSampler to generate random indexes and multiprocessing to generate + ``base_seed`` for workers. (default: ``None``) + prefetch_factor (int, optional, keyword-only arg): Number of batches loaded + in advance by each worker. ``2`` means there will be a total of + 2 * num_workers batches prefetched across all workers. (default value depends + on the set value for num_workers. If value of num_workers=0 default is ``None``. + Otherwise, if value of ``num_workers > 0`` default is ``2``). + persistent_workers (bool, optional): If ``True``, the data loader will not shut down + the worker processes after a dataset has been consumed once. This allows to + maintain the workers `Dataset` instances alive. (default: ``False``) + pin_memory_device (str, optional): Deprecated, the current :ref:`accelerator` + will be used as the device if ``pin_memory=True``. + in_order (bool, optional): If ``False``, the data loader will not enforce that batches + are returned in a first-in, first-out order. Only applies when ``num_workers > 0``. (default: ``True``) + + + .. warning:: If the ``spawn`` start method is used, :attr:`worker_init_fn` + cannot be an unpicklable object, e.g., a lambda function. See + :ref:`multiprocessing-best-practices` on more details related + to multiprocessing in PyTorch. + + .. warning:: ``len(dataloader)`` heuristic is based on the length of the sampler used. + When :attr:`dataset` is an :class:`~torch.utils.data.IterableDataset`, + it instead returns an estimate based on ``len(dataset) / batch_size``, with proper + rounding depending on :attr:`drop_last`, regardless of multi-process loading + configurations. This represents the best guess PyTorch can make because PyTorch + trusts user :attr:`dataset` code in correctly handling multi-process + loading to avoid duplicate data. + + However, if sharding results in multiple workers having incomplete last batches, + this estimate can still be inaccurate, because (1) an otherwise complete batch can + be broken into multiple ones and (2) more than one batch worth of samples can be + dropped when :attr:`drop_last` is set. Unfortunately, PyTorch can not detect such + cases in general. + + See `Dataset Types`_ for more details on these two types of datasets and how + :class:`~torch.utils.data.IterableDataset` interacts with + `Multi-process data loading`_. + + .. warning:: See :ref:`reproducibility`, and :ref:`dataloader-workers-random-seed`, and + :ref:`data-loading-randomness` notes for random seed related questions. + + .. warning:: Setting `in_order` to `False` can harm reproducibility and may lead to a skewed data + distribution being fed to the trainer in cases with imbalanced data. + """ + + dataset: Dataset[_T_co] + batch_size: int | None + num_workers: int + pin_memory: bool + drop_last: bool + timeout: float + sampler: Sampler | Iterable + pin_memory_device: str + prefetch_factor: int | None + _iterator: _BaseDataLoaderIter | None + __initialized = False + + def __init__( + self, + dataset: Dataset[_T_co], + batch_size: int | None = 1, + shuffle: bool | None = None, + sampler: Sampler | Iterable | None = None, + batch_sampler: Sampler[list] | Iterable[list] | None = None, + num_workers: int = 0, + collate_fn: _collate_fn_t | None = None, + pin_memory: bool = False, + drop_last: bool = False, + timeout: float = 0, + worker_init_fn: _worker_init_fn_t | None = None, + multiprocessing_context=None, + generator=None, + *, + prefetch_factor: int | None = None, + persistent_workers: bool = False, + pin_memory_device: str = "", + in_order: bool = True, + ) -> None: + torch._C._log_api_usage_once("python.data_loader") + + if num_workers < 0: + raise ValueError( + "num_workers option should be non-negative; " + "use num_workers=0 to disable multiprocessing." + ) + + if timeout < 0: + raise ValueError("timeout option should be non-negative") + + if num_workers == 0 and prefetch_factor is not None: + raise ValueError( + "prefetch_factor option could only be specified in multiprocessing." + "let num_workers > 0 to enable multiprocessing, otherwise set prefetch_factor to None." + ) + elif num_workers > 0 and prefetch_factor is None: + prefetch_factor = 2 + elif prefetch_factor is not None and prefetch_factor < 0: + raise ValueError("prefetch_factor option should be non-negative") + + if persistent_workers and num_workers == 0: + raise ValueError("persistent_workers option needs num_workers > 0") + + self.dataset = dataset + self.num_workers = num_workers + self.prefetch_factor = prefetch_factor + self.pin_memory = pin_memory + self.pin_memory_device = pin_memory_device + self.timeout = timeout + self.worker_init_fn = worker_init_fn + self.multiprocessing_context = multiprocessing_context + self.in_order = in_order + + # Adds forward compatibilities so classic DataLoader can work with DataPipes: + # _DataPipeSerializationWrapper container makes it easier to serialize without redefining pickler + if isinstance(self.dataset, IterDataPipe): + self.dataset = _IterDataPipeSerializationWrapper(self.dataset) + elif isinstance(self.dataset, MapDataPipe): + self.dataset = _MapDataPipeSerializationWrapper(self.dataset) + + # Arg-check dataset related before checking samplers because we want to + # tell users that iterable-style datasets are incompatible with custom + # samplers first, so that they don't learn that this combo doesn't work + # after spending time fixing the custom sampler errors. + if isinstance(dataset, IterableDataset): + self._dataset_kind = _DatasetKind.Iterable + # NOTE [ Custom Samplers and IterableDataset ] + # + # `IterableDataset` does not support custom `batch_sampler` or + # `sampler` since the key is irrelevant (unless we support + # generator-style dataset one day...). + # + # For `sampler`, we always create a dummy sampler. This is an + # infinite sampler even when the dataset may have an implemented + # finite `__len__` because in multi-process data loading, naive + # settings will return duplicated data (which may be desired), and + # thus using a sampler with length matching that of dataset will + # cause data loss (you may have duplicates of the first couple + # batches, but never see anything afterwards). Therefore, + # `IterableDataset` always uses an infinite sampler, an instance of + # `_InfiniteConstantSampler` defined above. + # + # A custom `batch_sampler` essentially only controls the batch size. + # However, it is unclear how useful it would be since an iterable-style + # dataset can handle that within itself. Moreover, it is pointless + # in multi-process data loading as the assignment order of batches + # to workers is an implementation detail so users can not control + # how to batchify each worker's iterable. Thus, we disable this + # option. If this turns out to be useful in future, we can re-enable + # this, and support custom samplers that specify the assignments to + # specific workers. + if isinstance(dataset, IterDataPipe): + if shuffle is not None: + dataset = torch.utils.data.graph_settings.apply_shuffle_settings( + dataset, shuffle=shuffle + ) + # We cannot check `shuffle is not None` here, since previously `shuffle=False` was the default. + elif shuffle not in {False, None}: + raise ValueError( + f"DataLoader with IterableDataset: expected unspecified shuffle option, but got shuffle={shuffle}" + ) + + if sampler is not None: + # See NOTE [ Custom Samplers and IterableDataset ] + raise ValueError( + f"DataLoader with IterableDataset: expected unspecified sampler option, but got sampler={sampler}" + ) + elif batch_sampler is not None: + # See NOTE [ Custom Samplers and IterableDataset ] + raise ValueError( + "DataLoader with IterableDataset: expected unspecified " + f"batch_sampler option, but got batch_sampler={batch_sampler}" + ) + else: + shuffle = bool(shuffle) + self._dataset_kind = _DatasetKind.Map + + if sampler is not None and shuffle: + raise ValueError("sampler option is mutually exclusive with shuffle") + + if batch_sampler is not None: + # auto_collation with custom batch_sampler + if batch_size != 1 or shuffle or sampler is not None or drop_last: + raise ValueError( + "batch_sampler option is mutually exclusive " + "with batch_size, shuffle, sampler, and " + "drop_last" + ) + batch_size = None + drop_last = False + elif batch_size is None: + # no auto_collation + if drop_last: + raise ValueError( + "batch_size=None option disables auto-batching " + "and is mutually exclusive with drop_last" + ) + + if sampler is None: # give default samplers + if self._dataset_kind == _DatasetKind.Iterable: + # See NOTE [ Custom Samplers and IterableDataset ] + sampler = _InfiniteConstantSampler() + else: # map-style + if shuffle: + sampler = RandomSampler(dataset, generator=generator) # type: ignore[arg-type] + else: + sampler = SequentialSampler(dataset) # type: ignore[arg-type] + + if batch_size is not None and batch_sampler is None: + # auto_collation without custom batch_sampler + batch_sampler = BatchSampler(sampler, batch_size, drop_last) + + self.batch_size = batch_size + self.drop_last = drop_last + self.sampler = sampler + self.batch_sampler = batch_sampler + self.generator = generator + + if collate_fn is None: + if self._auto_collation: + collate_fn = _utils.collate.default_collate + else: + collate_fn = _utils.collate.default_convert + + self.collate_fn = collate_fn + self.persistent_workers = persistent_workers + + self.__initialized = True + self._IterableDataset_len_called = ( + None # See NOTE [ IterableDataset and __len__ ] + ) + + self._iterator = None + + self.check_worker_number_rationality() + + def _get_iterator(self) -> _BaseDataLoaderIter: + if self.num_workers == 0: + return _SingleProcessDataLoaderIter(self) + else: + self.check_worker_number_rationality() + return _MultiProcessingDataLoaderIter(self) + + @property + def multiprocessing_context(self): + return self.__multiprocessing_context + + @multiprocessing_context.setter + def multiprocessing_context(self, multiprocessing_context) -> None: + if multiprocessing_context is not None: + if self.num_workers > 0: + if isinstance(multiprocessing_context, str): + valid_start_methods = torch.multiprocessing.get_all_start_methods() + if multiprocessing_context not in valid_start_methods: + raise ValueError( + "multiprocessing_context option " + f"should specify a valid start method in {valid_start_methods!r}, but got " + f"multiprocessing_context={multiprocessing_context!r}" + ) + multiprocessing_context = torch.multiprocessing.get_context( + multiprocessing_context + ) + + if not isinstance( + multiprocessing_context, python_multiprocessing.context.BaseContext + ): + raise TypeError( + "multiprocessing_context option should be a valid context " + "object or a string specifying the start method, but got " + f"multiprocessing_context={multiprocessing_context}" + ) + else: + raise ValueError( + "multiprocessing_context can only be used with " + "multi-process loading (num_workers > 0), but got " + f"num_workers={self.num_workers}" + ) + + self.__multiprocessing_context = multiprocessing_context + + def __setattr__(self, attr, val) -> None: + if self.__initialized and attr in ( + "batch_size", + "batch_sampler", + "sampler", + "drop_last", + "dataset", + "persistent_workers", + ): + raise ValueError( + f"{attr} attribute should not be set after {self.__class__.__name__} is initialized" + ) + + super().__setattr__(attr, val) + + def __iter__(self) -> _BaseDataLoaderIter: + # When using a single worker the returned iterator should be + # created every time to avoid resetting its state + # However, in the case of a multiple workers iterator + # the iterator is only created once in the lifetime of the + # DataLoader object so that workers can be reused + if self.persistent_workers and self.num_workers > 0: + if self._iterator is None: + self._iterator = self._get_iterator() + else: + self._iterator._reset(self) + return self._iterator + else: + return self._get_iterator() + + @property + def _auto_collation(self): + return self.batch_sampler is not None + + @property + def _index_sampler(self): + # The actual sampler used for generating indices for `_DatasetFetcher` + # (see _utils/fetch.py) to read data at each time. This would be + # `.batch_sampler` if in auto-collation mode, and `.sampler` otherwise. + # We can't change `.sampler` and `.batch_sampler` attributes for BC + # reasons. + if self._auto_collation: + return self.batch_sampler + else: + return self.sampler + + def __len__(self) -> int: + if self._dataset_kind == _DatasetKind.Iterable: + # NOTE [ IterableDataset and __len__ ] + # + # For `IterableDataset`, `__len__` could be inaccurate when one naively + # does multi-processing data loading, since the samples will be duplicated. + # However, no real use case should be actually using that behavior, so + # it should count as a user error. We should generally trust user + # code to do the proper thing (e.g., configure each replica differently + # in `__iter__`), and give us the correct `__len__` if they choose to + # implement it (this will still throw if the dataset does not implement + # a `__len__`). + # + # To provide a further warning, we track if `__len__` was called on the + # `DataLoader`, save the returned value in `self._len_called`, and warn + # if the iterator ends up yielding more than this number of samples. + + # Cannot statically verify that dataset is Sized + length = self._IterableDataset_len_called = len(self.dataset) # type: ignore[assignment, arg-type] + if ( + self.batch_size is not None + ): # IterableDataset doesn't allow custom sampler or batch_sampler + from math import ceil + + if self.drop_last: + length = length // self.batch_size + else: + length = ceil(length / self.batch_size) + return length + else: + return len(self._index_sampler) + + def check_worker_number_rationality(self) -> None: + # This function check whether the dataloader's worker number is rational based on + # current system's resource. Current rule is that if the number of workers this + # Dataloader will create is bigger than the number of logical cpus that is allowed to + # use, then we will pop up a warning to let user pay attention. + # + # eg. If current system has 2 physical CPUs with 16 cores each. And each core support 2 + # threads, then the total logical cpus here is 2 * 16 * 2 = 64. Let's say current + # DataLoader process can use half of them which is 32, then the rational max number of + # worker that initiated from this process is 32. + # Now, let's say the created DataLoader has num_works = 40, which is bigger than 32. + # So the warning message is triggered to notify the user to lower the worker number if + # necessary. + # + # + # [Note] Please note that this function respects `cpuset` only when os.sched_getaffinity is + # available (available in most of Linux system, but not OSX and Windows). + # When os.sched_getaffinity is not available, os.cpu_count() is called instead, but + # it doesn't respect cpuset. + # We don't take threading into account since each worker process is single threaded + # at this time. + # + # We don't set any threading flags (eg. OMP_NUM_THREADS, MKL_NUM_THREADS, etc) + # other than `torch.set_num_threads` to 1 in the worker process, if the passing + # in functions use 3rd party modules that rely on those threading flags to determine + # how many thread to create (eg. numpy, etc), then it is caller's responsibility to + # set those flags correctly. + def _create_warning_msg(num_worker_suggest, num_worker_created, cpuset_checked): + suggested_max_worker_msg = ( + ( + ( + "Our suggested max number of worker in current system is {}{}, which is smaller " + "than what this DataLoader is going to create." + ).format( + num_worker_suggest, + ( + "" + if cpuset_checked + else " (`cpuset` is not taken into account)" + ), + ) + ) + if num_worker_suggest is not None + else ( + "DataLoader is not able to compute a suggested max number of worker in current system." + ) + ) + + warn_msg = ( + f"This DataLoader will create {num_worker_created} worker processes in total. {suggested_max_worker_msg} " + "Please be aware that excessive worker creation might get DataLoader running slow or even freeze, " + "lower the worker number to avoid potential slowness/freeze if necessary." + ) + return warn_msg + + if not self.num_workers or self.num_workers == 0: + return + + # try to compute a suggested max number of worker based on system's resource + max_num_worker_suggest = torch._utils.cpu_count() + cpuset_checked = hasattr(os, "sched_getaffinity") + + if max_num_worker_suggest is None or self.num_workers > max_num_worker_suggest: + warnings.warn( + _create_warning_msg( + max_num_worker_suggest, self.num_workers, cpuset_checked + ), + stacklevel=2, + ) + + +class _BaseDataLoaderIter: + def __init__(self, loader: DataLoader) -> None: + self._dataset = loader.dataset + self._shared_seed = None + self._pg = None + if isinstance(self._dataset, IterDataPipe): + if dist.is_available() and dist.is_initialized(): + self._pg = dist.new_group(backend="gloo") + self._shared_seed = _share_dist_seed(loader.generator, self._pg) + shared_rng = torch.Generator() + shared_rng.manual_seed(self._shared_seed) + self._dataset = torch.utils.data.graph_settings.apply_random_seed( + self._dataset, shared_rng + ) + self._dataset_kind = loader._dataset_kind + self._IterableDataset_len_called = loader._IterableDataset_len_called + self._auto_collation = loader._auto_collation + self._drop_last = loader.drop_last + self._index_sampler = loader._index_sampler + self._num_workers = loader.num_workers + ws, rank = _get_distributed_settings() + self._world_size = ws + self._rank = rank + + if loader.pin_memory and loader.pin_memory_device: + warnings.warn( + "pin_memory_device is deprecated, the current accelerator will be used as the device," + f"ignore pin_memory_device='{loader.pin_memory_device}'.", + stacklevel=2, + ) + if loader.pin_memory and not torch.accelerator.is_available(): + warn_msg = ( + "'pin_memory' argument is set as true but no accelerator is found, " + "then device pinned memory won't be used." + ) + warnings.warn(warn_msg, stacklevel=2) + + # Enabling pin_memory in _BaseDataLoaderIter to support identical + # behavior in forked implementations using _BaseDataLoaderIter. + self._pin_memory = loader.pin_memory and torch.accelerator.is_available() + + # Set pin memory device based on the current accelerator. + self._pin_memory_device = ( + acc.type + if self._pin_memory + and (acc := torch.accelerator.current_accelerator()) is not None + else None + ) + + # Currently, pin_memory would raise error on the MPS backend (see + # https://github.com/pytorch/pytorch/issues/86060), so forcibly + # disable pin_memory on MPS. Remove this restriction once pinned + # memory allocation for MPS is fixed. + if self._pin_memory_device == "mps": + self._pin_memory = False + warn_msg = ( + "'pin_memory' argument is set as true but not supported on MPS now, " + "device pinned memory won't be used." + ) + warnings.warn(warn_msg, stacklevel=2) + + self._timeout = loader.timeout + self._collate_fn = loader.collate_fn + self._sampler_iter = iter(self._index_sampler) + self._base_seed = ( + torch.empty((), dtype=torch.int64) + .random_(generator=loader.generator) + .item() + ) + self._persistent_workers = loader.persistent_workers + self._num_yielded = 0 + self._profile_name = f"enumerate(DataLoader)#{self.__class__.__name__}.__next__" + + def __iter__(self) -> Self: + return self + + def _reset(self, loader, first_iter=False) -> None: + self._sampler_iter = iter(self._index_sampler) + self._num_yielded = 0 + self._IterableDataset_len_called = loader._IterableDataset_len_called + if isinstance(self._dataset, IterDataPipe): + self._shared_seed = _share_dist_seed(loader.generator, self._pg) + shared_rng = torch.Generator() + shared_rng.manual_seed(self._shared_seed) + self._dataset = torch.utils.data.graph_settings.apply_random_seed( + self._dataset, shared_rng + ) + + def _next_index(self): + return next(self._sampler_iter) # may raise StopIteration + + def _next_data(self) -> NoReturn: + raise NotImplementedError + + def __next__(self) -> Any: + with torch.autograd.profiler.record_function(self._profile_name): + if self._sampler_iter is None: + # TODO(https://github.com/pytorch/pytorch/issues/76750) + self._reset() # type: ignore[call-arg] + data = self._next_data() + self._num_yielded += 1 + if ( + self._dataset_kind == _DatasetKind.Iterable + and self._IterableDataset_len_called is not None + and self._num_yielded > self._IterableDataset_len_called + ): + warn_msg = ( + f"Length of IterableDataset {self._dataset} was reported to be {self._IterableDataset_len_called}" + f"(when accessing len(dataloader)), but {self._num_yielded} samples have been fetched. " + ) + if self._num_workers > 0: + warn_msg += ( + "For multiprocessing data-loading, this could be caused by not properly configuring the " + "IterableDataset replica at each worker. Please see " + "https://pytorch.org/docs/stable/data.html#torch.utils.data.IterableDataset for examples." + ) + warnings.warn(warn_msg, stacklevel=2) + return data + + def __len__(self) -> int: + return len(self._index_sampler) + + def __getstate__(self): + # TODO: add limited pickling support for sharing an iterator + # across multiple threads for HOGWILD. + # Probably the best way to do this is by moving the sample pushing + # to a separate thread and then just sharing the data queue + # but signalling the end is tricky without a non-blocking API + raise NotImplementedError("{} cannot be pickled", self.__class__.__name__) + + +class _SingleProcessDataLoaderIter(_BaseDataLoaderIter): + def __init__(self, loader) -> None: + super().__init__(loader) + if self._timeout != 0: + raise AssertionError("_SingleProcessDataLoaderIter requires timeout == 0") + if self._num_workers != 0: + raise AssertionError( + "_SingleProcessDataLoaderIter requires num_workers == 0" + ) + + # Adds forward compatibilities so classic DataLoader can work with DataPipes: + # Taking care of distributed sharding + if isinstance(self._dataset, (IterDataPipe, MapDataPipe)): + # For BC, use default SHARDING_PRIORITIES + torch.utils.data.graph_settings.apply_sharding( + self._dataset, self._world_size, self._rank + ) + + self._dataset_fetcher = _DatasetKind.create_fetcher( + self._dataset_kind, + self._dataset, + self._auto_collation, + self._collate_fn, + self._drop_last, + ) + + def _next_data(self): + index = self._next_index() # may raise StopIteration + data = self._dataset_fetcher.fetch(index) # may raise StopIteration + if self._pin_memory: + data = _utils.pin_memory.pin_memory(data, self._pin_memory_device) + return data + + +class _MultiProcessingDataLoaderIter(_BaseDataLoaderIter): + r"""Iterates once over the DataLoader's dataset, as specified by the sampler.""" + + # NOTE [ Data Loader Multiprocessing Shutdown Logic ] + # + # Preliminary: + # + # Our data model looks like this (queues are indicated with curly brackets): + # + # main process || + # | || + # {index_queue} || + # | || + # worker processes || DATA + # | || + # {worker_result_queue} || FLOW + # | || + # pin_memory_thread of main process || DIRECTION + # | || + # {data_queue} || + # | || + # data output \/ + # + # P.S. `worker_result_queue` and `pin_memory_thread` part may be omitted if + # `pin_memory=False`. + # + # + # Terminating multiprocessing logic requires very careful design. In + # particular, we need to make sure that + # + # 1. The iterator gracefully exits the workers when its last reference is + # gone or it is depleted. + # + # In this case, the workers should be gracefully exited because the + # main process may still need to continue to run, and we want cleaning + # up code in the workers to be executed (e.g., releasing GPU memory). + # Naturally, we implement the shutdown logic in `__del__` of + # DataLoaderIterator. + # + # We delay the discussion on the logic in this case until later. + # + # 2. The iterator exits the workers when the loader process and/or worker + # processes exits normally or with error. + # + # We set all workers and `pin_memory_thread` to have `daemon=True`. + # + # You may ask, why can't we make the workers non-daemonic, and + # gracefully exit using the same logic as we have in `__del__` when the + # iterator gets deleted (see 1 above)? + # + # First of all, `__del__` is **not** guaranteed to be called when + # interpreter exits. Even if it is called, by the time it executes, + # many Python core library resources may already be freed, and even + # simple things like acquiring an internal lock of a queue may hang. + # Therefore, in this case, we actually need to prevent `__del__` from + # being executed, and rely on the automatic termination of daemonic + # children. + # + # Thus, we register an `atexit` hook that sets a global flag + # `_utils.python_exit_status`. Since `atexit` hooks are executed in the + # reverse order of registration, we are guaranteed that this flag is + # set before library resources we use are freed (which, at least in + # CPython, is done via an `atexit` handler defined in + # `multiprocessing/util.py` + # https://github.com/python/cpython/blob/c606624af8d4cb3b4a052fb263bb983b3f87585b/Lib/multiprocessing/util.py#L320-L362 + # registered when an object requiring this mechanism is first + # created, e.g., `mp.Queue` + # https://github.com/python/cpython/blob/c606624af8d4cb3b4a052fb263bb983b3f87585b/Lib/multiprocessing/context.py#L100-L103 + # https://github.com/python/cpython/blob/c606624af8d4cb3b4a052fb263bb983b3f87585b/Lib/multiprocessing/queues.py#L29 + # ) + # + # So in `__del__`, we check if `_utils.python_exit_status` is set or + # `None` (freed), and perform no-op if so. + # + # However, simply letting library clean-up codes run can also be bad, + # because such codes (i.e., `multiprocessing.util._exit_function()`) + # include join putting threads for `mp.Queue`, which can be blocking. + # Hence, the main process putting threads are called with + # `cancel_join_thread` at creation. See later section + # [ 3b. A process won't hang when putting into a queue; ] + # for more details. + # + # Here are two example cases where library clean-up codes can run + # before `__del__` is called: + # + # 1. If we hold onto a reference to the iterator, it more often + # than not tries to do `multiprocessing` library cleaning before + # clearing the alive referenced objects (https://github.com/pytorch/pytorch/issues/48666) + # and thus prevents our cleaning-up code to run first. + # + # 2. A similar issue araises when a `DataLoader` is used in a subprocess. + # When a process ends, it shuts the all its daemonic children + # down with a SIGTERM (instead of joining them without a timeout). + # Similarly for threads, but by a different mechanism. This fact, + # together with a few implementation details of multiprocessing, forces + # us to make workers daemonic. All of our problems arise when a + # DataLoader is used in a subprocess, and are caused by multiprocessing + # code which looks more or less like this: + # + # try: + # your_function_using_a_dataloader() + # finally: + # multiprocessing.util._exit_function() + # + # The joining/termination mentioned above happens inside + # `_exit_function()`. Now, if `your_function_using_a_dataloader()` + # throws, the stack trace stored in the exception will prevent the + # frame which uses `DataLoaderIter` to be freed. If the frame has any + # reference to the `DataLoaderIter` (e.g., in a method of the iter), + # its `__del__`, which starts the shutdown procedure, will not be + # called. That, in turn, means that workers aren't notified. Attempting + # to join in `_exit_function` will then result in a hang. + # + # For context, `_exit_function` is also registered as an `atexit` call. + # So it is unclear to me (@ssnl) why this is needed in a finally block. + # The code dates back to 2008 and there is no comment on the original + # PEP 371 or patch https://bugs.python.org/issue3050 (containing both + # the finally block and the `atexit` registration) that explains this. + # + # + # Finally, another choice is to just shutdown workers with logic in 1 + # above whenever we see an error in `next`. This isn't ideal because + # a. It prevents users from using try-catch to resume data loading. + # b. It doesn't prevent hanging if users have references to the + # iterator. + # + # 3. All processes exit if any of them die unexpectedly by fatal signals. + # + # As shown above, the workers are set as daemonic children of the main + # process. However, automatic cleaning-up of such child processes only + # happens if the parent process exits gracefully (e.g., not via fatal + # signals like SIGKILL). So we must ensure that each process will exit + # even the process that should send/receive data to/from it were + # killed, i.e., + # + # a. A process won't hang when getting from a queue. + # + # Even with carefully designed data dependencies (i.e., a `put()` + # always corresponding to a `get()`), hanging on `get()` can still + # happen when data in queue is corrupted (e.g., due to + # `cancel_join_thread` or unexpected exit). + # + # For child exit, we set a timeout whenever we try to get data + # from `data_queue`, and check the workers' status on each timeout + # and error. + # See `_DataLoaderiter._get_batch()` and + # `_DataLoaderiter._try_get_data()` for details. + # + # Additionally, for child exit on non-Windows platforms, we also + # register a SIGCHLD handler (which is supported on Windows) on + # the main process, which checks if any of the workers fail in the + # (Python) handler. This is more efficient and faster in detecting + # worker failures, compared to only using the above mechanism. + # See `DataLoader.cpp` and `_utils/signal_handling.py` for details. + # + # For `.get()` calls where the sender(s) is not the workers, we + # guard them with timeouts, and check the status of the sender + # when timeout happens: + # + in the workers, the `_utils.worker.ManagerWatchdog` class + # checks the status of the main process. + # + if `pin_memory=True`, when getting from `pin_memory_thread`, + # check `pin_memory_thread` status periodically until `.get()` + # returns or see that `pin_memory_thread` died. + # + # b. A process won't hang when putting into a queue; + # + # We use `mp.Queue` which has a separate background thread to put + # objects from an unbounded buffer array. The background thread is + # daemonic and usually automatically joined when the process + # *exits*. + # + # In case that the receiver has ended abruptly while + # reading from the pipe, the join will hang forever. The usual + # solution for this in Python is calling `q.cancel_join_thread`, + # which prevents automatically joining it when finalizing + # (exiting). + # + # Nonetheless, `cancel_join_thread` must only be called when the + # queue is **not** going to be read from or write into by another + # process, because it may hold onto a lock or leave corrupted data + # in the queue, leading other readers/writers to hang. + # + # Hence, + # + For worker processes, we only do so (for their output + # queues, i.e., `worker_result_queue`) before exiting. + # + For `pin_memory_thread`, its output queue `data_queue` is a + # `queue.Queue` that does blocking `put` if the queue is full. + # So there is no above problem, but as a result, in + # `_pin_memory_loop`, we do need to wrap the `put` in a loop + # that breaks not only upon success, but also when the main + # process stops reading, i.e., is shutting down. + # + For loader process, we `cancel_join_thread()` for all + # `_index_queues` because the whole purpose of workers and + # `pin_memory_thread` is to serve the loader process. If + # loader process is already exiting, we don't really care if + # the queues are corrupted. + # + # + # Now let's get back to 1: + # how we gracefully exit the workers when the last reference to the + # iterator is gone. + # + # To achieve this, we implement the following logic along with the design + # choices mentioned above: + # + # `workers_done_event`: + # A `multiprocessing.Event` shared among the main process and all worker + # processes. This is used to signal the workers that the iterator is + # shutting down. After it is set, they will not send processed data to + # queues anymore, and only wait for the final `None` before exiting. + # `done_event` isn't strictly needed. I.e., we can just check for `None` + # from the input queue, but it allows us to skip wasting resources + # processing data if we are already shutting down. + # + # `pin_memory_thread_done_event`: + # A `threading.Event` for a similar purpose to that of + # `workers_done_event`, but is for the `pin_memory_thread`. The reason + # that separate events are needed is that `pin_memory_thread` reads from + # the output queue of the workers. But the workers, upon seeing that + # `workers_done_event` is set, only wants to see the final `None`, and is + # not required to flush all data in the output queue (e.g., it may call + # `cancel_join_thread` on that queue if its `IterableDataset` iterator + # happens to exhaust coincidentally, which is out of the control of the + # main process). Thus, since we will exit `pin_memory_thread` before the + # workers (see below), two separate events are used. + # + # NOTE: In short, the protocol is that the main process will set these + # `done_event`s and then the corresponding processes/threads a `None`, + # and that they may exit at any time after receiving the `None`. + # + # NOTE: Using `None` as the final signal is valid, since normal data will + # always be a 2-tuple with the 1st element being the index of the data + # transferred (different from dataset index/key), and the 2nd being + # either the dataset key or the data sample (depending on which part + # of the data model the queue is at). + # + # [ worker processes ] + # While loader process is alive: + # Get from `index_queue`. + # If get anything else, + # Check `workers_done_event`. + # If set, continue to next iteration + # i.e., keep getting until see the `None`, then exit. + # Otherwise, process data: + # If is fetching from an `IterableDataset` and the iterator + # is exhausted, send an `_IterableDatasetStopIteration` + # object to signal iteration end. The main process, upon + # receiving such an object, will send `None` to this + # worker and not use the corresponding `index_queue` + # anymore. + # If timed out, + # No matter `workers_done_event` is set (still need to see `None`) + # or not, must continue to next iteration. + # (outside loop) + # If `workers_done_event` is set, (this can be False with `IterableDataset`) + # `data_queue.cancel_join_thread()`. (Everything is ending here: + # main process won't read from it; + # other workers will also call + # `cancel_join_thread`.) + # + # [ pin_memory_thread ] + # # No need to check main thread. If this thread is alive, the main loader + # # thread must be alive, because this thread is set as daemonic. + # While `pin_memory_thread_done_event` is not set: + # Get from `worker_result_queue`. + # If timed out, continue to get in the next iteration. + # Otherwise, process data. + # While `pin_memory_thread_done_event` is not set: + # Put processed data to `data_queue` (a `queue.Queue` with blocking put) + # If timed out, continue to put in the next iteration. + # Otherwise, break, i.e., continuing to the out loop. + # + # NOTE: we don't check the status of the main thread because + # 1. if the process is killed by fatal signal, `pin_memory_thread` + # ends. + # 2. in other cases, either the cleaning-up in __del__ or the + # automatic exit of daemonic thread will take care of it. + # This won't busy-wait either because `.get(timeout)` does not + # busy-wait. + # + # [ main process ] + # In the DataLoader Iter's `__del__` + # b. Exit `pin_memory_thread` + # i. Set `pin_memory_thread_done_event`. + # ii Put `None` in `worker_result_queue`. + # iii. Join the `pin_memory_thread`. + # iv. `worker_result_queue.cancel_join_thread()`. + # + # c. Exit the workers. + # i. Set `workers_done_event`. + # ii. Put `None` in each worker's `index_queue`. + # iii. Join the workers. + # iv. Call `.cancel_join_thread()` on each worker's `index_queue`. + # + # NOTE: (c) is better placed after (b) because it may leave corrupted + # data in `worker_result_queue`, which `pin_memory_thread` + # reads from, in which case the `pin_memory_thread` can only + # happen at timing out, which is slow. Nonetheless, same thing + # happens if a worker is killed by signal at unfortunate times, + # but in other cases, we are better off having a non-corrupted + # `worker_result_queue` for `pin_memory_thread`. + # + # NOTE: If `pin_memory=False`, there is no `pin_memory_thread` and (b) + # can be omitted + # + # NB: `done_event`s isn't strictly needed. E.g., we can just check for + # `None` from `index_queue`, but it allows us to skip wasting resources + # processing indices already in `index_queue` if we are already shutting + # down. + + def __init__(self, loader) -> None: + super().__init__(loader) + + self._prefetch_factor = loader.prefetch_factor + self._in_order = loader.in_order + + if self._num_workers <= 0: + raise AssertionError( + "num_workers must be greater than 0 for MultiProcessingDataLoaderIter" + ) + if self._prefetch_factor <= 0: + raise AssertionError( + "prefetch_factor must be greater than 0 for MultiProcessingDataLoaderIter" + ) + + if loader.multiprocessing_context is None: + multiprocessing_context = torch.multiprocessing + else: + multiprocessing_context = loader.multiprocessing_context + + self._worker_init_fn = loader.worker_init_fn + + # Adds forward compatibilities so classic DataLoader can work with DataPipes: + # Additional worker init function will take care of sharding in MP and Distributed + if isinstance(self._dataset, (IterDataPipe, MapDataPipe)): + self._worker_init_fn = functools.partial( + _sharding_worker_init_fn, + self._worker_init_fn, + self._world_size, + self._rank, + ) + + # No certainty which module multiprocessing_context is + self._worker_result_queue = multiprocessing_context.Queue() # type: ignore[var-annotated] + self._worker_pids_set = False + self._shutdown = False + self._workers_done_event = multiprocessing_context.Event() + + self._index_queues = [] + self._workers = [] + for i in range(self._num_workers): + # No certainty which module multiprocessing_context is + index_queue = multiprocessing_context.Queue() # type: ignore[var-annotated] + # Need to `cancel_join_thread` here! + # See sections (2) and (3b) above. + index_queue.cancel_join_thread() + # The worker consumes the holder so its Process does not retain the dataset. + dataset_holder = [self._dataset] + w = multiprocessing_context.Process( + target=_utils.worker._worker_loop, + args=( + self._dataset_kind, + dataset_holder, + index_queue, + self._worker_result_queue, + self._workers_done_event, + self._auto_collation, + self._collate_fn, + self._drop_last, + self._base_seed, + self._worker_init_fn, + i, + self._num_workers, + self._persistent_workers, + self._shared_seed, + ), + ) + w.daemon = True + # NB: Process.start() actually take some time as it needs to + # start a process and pass the arguments over via a pipe. + # Therefore, we only add a worker to self._workers list after + # it started, so that we do not call .join() if program dies + # before it starts, and __del__ tries to join but will get: + # AssertionError: can only join a started process. + from pickle import PicklingError + + try: + w.start() + except (TypeError, AttributeError, PicklingError): + warnings.warn( + "Got pickle error when attempting to start a worker Process. " + "This might be because the worker Process arguments are not picklable. " + "Python 3.14+ changed the multiprocessing start method in non-Mac POSIX platforms " + "to 'forkserver', which requires the worker Process arguments to be picklable. " + "You can also try multiprocessing.set_start_method('fork').", + stacklevel=2, + ) + raise + self._index_queues.append(index_queue) + self._workers.append(w) + + if self._pin_memory: + self._pin_memory_thread_done_event = threading.Event() + + # Queue is not type-annotated + self._data_queue = queue.Queue() # type: ignore[var-annotated] + current_device_id = torch.accelerator.current_device_index() + pin_memory_thread = threading.Thread( + target=_utils.pin_memory._pin_memory_loop, + args=( + self._worker_result_queue, + self._data_queue, + current_device_id, + self._pin_memory_thread_done_event, + self._pin_memory_device, + ), + ) + pin_memory_thread.daemon = True + pin_memory_thread.start() + # Similar to workers (see comment above), we only register + # pin_memory_thread once it is started. + self._pin_memory_thread = pin_memory_thread + else: + self._data_queue = self._worker_result_queue # type: ignore[assignment] + + # In some rare cases, persistent workers (daemonic processes) + # would be terminated before `__del__` of iterator is invoked + # when main process exits + # It would cause failure when pin_memory_thread tries to read + # corrupted data from worker_result_queue + # atexit is used to shutdown thread and child processes in the + # right sequence before main process exits + if self._persistent_workers and self._pin_memory: + self._register_persistent_workers_atexit() + + # .pid can be None only before process is spawned (not the case, so ignore) + _utils.signal_handling._set_worker_pids( + id(self), + tuple(w.pid for w in self._workers), # type: ignore[misc] + ) + _utils.signal_handling._set_SIGCHLD_handler() + self._worker_pids_set = True + self._reset(loader, first_iter=True) + + def _reset(self, loader, first_iter=False) -> None: + super()._reset(loader, first_iter) + self._send_idx = 0 # idx of the next task to be sent to workers + self._rcvd_idx = 0 # idx of the next task to be returned in __next__ + # information about data not yet yielded, i.e., tasks w/ indices in range [rcvd_idx, send_idx). + # map: task idx => - (worker_id,) if data isn't fetched (outstanding) + # \ (worker_id, data) if data is already fetched (out-of-order) + self._task_info = {} + self._tasks_outstanding = ( + 0 # always equal to count(v for v in task_info.values() if len(v) == 1) + ) + # A list of booleans representing whether each worker still has work to + # do, i.e., not having exhausted its iterable dataset object. It always + # contains all `True`s if not using an iterable-style dataset + # (i.e., if kind != Iterable). + # Not that this indicates that a worker still has work to do *for this epoch*. + # It does not mean that a worker is dead. In case of `_persistent_workers`, + # the worker will be reset to available in the next epoch. + self._workers_status = [True for i in range(self._num_workers)] + # A list of integers representing how many tasks are outstanding for each worker + # Incremented when a task is dispatched to the worker + # Decremented when that data has been given to the main thread + # Each worker should have at most self._prefetch_factor tasks outstanding + self._workers_num_tasks = [0 for i in range(self._num_workers)] + # Reset the worker queue cycle so it resumes next epoch at worker 0 + self._worker_queue_idx_cycle = itertools.cycle(range(self._num_workers)) + # We resume the prefetching in case it was enabled + if not first_iter: + for idx in range(self._num_workers): + self._index_queues[idx].put( + _utils.worker._ResumeIteration(self._shared_seed) + ) + resume_iteration_cnt = self._num_workers + while resume_iteration_cnt > 0: + return_idx, return_data = self._get_data() + if isinstance(return_idx, _utils.worker._ResumeIteration): + if return_data is not None: + raise AssertionError( + "Expected return_data to be None when resuming iteration" + ) + resume_iteration_cnt -= 1 + # prime the prefetch loop + for _ in range(self._prefetch_factor * self._num_workers): + self._try_put_index() + + def _try_get_data(self, timeout=_utils.MP_STATUS_CHECK_INTERVAL): + # Tries to fetch data from `self._data_queue` once for a given timeout. + # This can also be used as inner loop of fetching without timeout, with + # the sender status as the loop condition. + # + # This raises a `RuntimeError` if any worker died expectedly. This error + # can come from either the SIGCHLD handler in `_utils/signal_handling.py` + # (only for non-Windows platforms), or the manual check below on errors + # and timeouts. + # + # Returns a 2-tuple: + # (bool: whether successfully get data, any: data if successful else None) + try: + data = self._data_queue.get(timeout=timeout) + return (True, data) + except Exception as e: + # At timeout and error, we manually check whether any worker has + # failed. Note that this is the only mechanism for Windows to detect + # worker failures. + failed_workers = [] + for worker_id, w in enumerate(self._workers): + if self._workers_status[worker_id] and not w.is_alive(): + failed_workers.append(w) + self._mark_worker_as_unavailable(worker_id) + if len(failed_workers) > 0: + pids_str = ", ".join(str(w.pid) for w in failed_workers) + raise RuntimeError( + f"DataLoader worker (pid(s) {pids_str}) exited unexpectedly" + ) from e + if isinstance(e, queue.Empty): + return (False, None) + + import errno + import tempfile + + try: + # Raise an exception if we are this close to the FDs limit. + # Apparently, trying to open only one file is not a sufficient + # test. + # See NOTE [ DataLoader on Linux and open files limit ] + fds_limit_margin = 10 + with contextlib.ExitStack() as stack: + for _ in range(fds_limit_margin): + stack.enter_context( + tempfile.NamedTemporaryFile() # pyrefly: ignore [bad-argument-type] + ) + except OSError as e: + if e.errno == errno.EMFILE: + raise RuntimeError( + "Too many open files. Communication with the" + " workers is no longer possible. Please increase the" + " limit using `ulimit -n` in the shell or change the" + " sharing strategy by calling" + " `torch.multiprocessing.set_sharing_strategy('file_system')`" + " at the beginning of your code" + ) from None + raise + + # NOTE [ DataLoader on Linux and open files limit ] + # + # On Linux when DataLoader is used with multiprocessing we pass the data between + # the root process and the workers through SHM files. We remove those files from + # the filesystem as soon as they are created and keep them alive by + # passing around their file descriptors through AF_UNIX sockets. (See + # docs/source/multiprocessing.rst and 'Multiprocessing Technical Notes` in + # the wiki (https://github.com/pytorch/pytorch/wiki).) + # + # This sometimes leads us to exceeding the open files limit. When that happens, + # and the offending file descriptor is coming over a socket, the `socket` Python + # package silently strips the file descriptor from the message, setting only the + # `MSG_CTRUNC` flag (which might be a bit misleading since the manpage says that + # it _indicates that some control data were discarded due to lack of space in + # the buffer for ancillary data_). This might reflect the C implementation of + # AF_UNIX sockets. + # + # This behaviour can be reproduced with the script and instructions at the + # bottom of this note. + # + # When that happens, the standard Python `multiprocessing` (and not + # `torch.multiprocessing`) raises a `RuntimeError: received 0 items of ancdata` + # + # Sometimes, instead of the FD being stripped, you may get an `OSError: + # Too many open files`, both in the script below and in DataLoader. However, + # this is rare and seems to be nondeterministic. + # + # + # #!/usr/bin/env python3 + # import sys + # import socket + # import os + # import array + # import shutil + # import socket + # + # + # if len(sys.argv) != 4: + # print("Usage: ", sys.argv[0], " tmp_dirname iteration (send|recv)") + # sys.exit(1) + # + # if __name__ == '__main__': + # dirname = sys.argv[1] + # sock_path = dirname + "/sock" + # iterations = int(sys.argv[2]) + # def dummy_path(i): + # return dirname + "/" + str(i) + ".dummy" + # + # + # if sys.argv[3] == 'send': + # while not os.path.exists(sock_path): + # pass + # client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) + # client.connect(sock_path) + # for i in range(iterations): + # fd = os.open(dummy_path(i), os.O_WRONLY | os.O_CREAT) + # ancdata = array.array('i', [fd]) + # msg = bytes([i % 256]) + # print("Sending fd ", fd, " (iteration #", i, ")") + # client.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, ancdata)]) + # + # + # else: + # assert sys.argv[3] == 'recv' + # + # if os.path.exists(dirname): + # raise Exception("Directory exists") + # + # os.mkdir(dirname) + # + # print("Opening socket...") + # server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) + # server.bind(sock_path) + # + # print("Listening...") + # for i in range(iterations): + # a = array.array('i') + # msg, ancdata, flags, addr = server.recvmsg(1, socket.CMSG_SPACE(a.itemsize)) + # assert(len(ancdata) == 1) + # cmsg_level, cmsg_type, cmsg_data = ancdata[0] + # a.frombytes(cmsg_data) + # print("Received fd ", a[0], " (iteration #", i, ")") + # + # shutil.rmtree(dirname) + # + # Steps to reproduce: + # + # 1. Run two shells and set lower file descriptor limit in the receiving one: + # (shell1) ulimit -n 1020 + # (shell2) ulimit -n 1022 + # + # 2. Run the script above with the `recv` option in the first shell + # (shell1) ./test_socket.py sock_tmp 1017 recv + # + # 3. Run the script with the `send` option in the second shell: + # (shell2) ./test_socket.py sock_tmp 1017 send + + def _get_data(self): + # Fetches data from `self._data_queue`. + # + # We check workers' status every `MP_STATUS_CHECK_INTERVAL` seconds, + # which we achieve by running `self._try_get_data(timeout=MP_STATUS_CHECK_INTERVAL)` + # in a loop. This is the only mechanism to detect worker failures for + # Windows. For other platforms, a SIGCHLD handler is also used for + # worker failure detection. + # + # If `pin_memory=True`, we also need check if `pin_memory_thread` had + # died at timeouts. + if self._timeout > 0: + success, data = self._try_get_data(self._timeout) + if success: + return data + else: + raise RuntimeError( + f"DataLoader timed out after {self._timeout} seconds" + ) + elif self._pin_memory: + while self._pin_memory_thread.is_alive(): + success, data = self._try_get_data() + if success: + return data + else: + # while condition is false, i.e., pin_memory_thread died. + raise RuntimeError("Pin memory thread exited unexpectedly") + # In this case, `self._data_queue` is a `queue.Queue`,. But we don't + # need to call `.task_done()` because we don't use `.join()`. + else: + while True: + success, data = self._try_get_data() + if success: + return data + + def _next_data(self): + while True: + # If the worker responsible for `self._rcvd_idx` has already ended + # and was unable to fulfill this task (due to exhausting an `IterableDataset`), + # we try to advance `self._rcvd_idx` to find the next valid index. + # + # This part needs to run in the loop because both the `self._get_data()` + # call and `_IterableDatasetStopIteration` check below can mark + # extra worker(s) as dead. + while self._rcvd_idx < self._send_idx: + info = self._task_info.get(self._rcvd_idx, None) + if info: + worker_id = info[0] + if ( + len(info) == 2 or self._workers_status[worker_id] + ): # has data or is still active + break + del self._task_info[self._rcvd_idx] + self._rcvd_idx += 1 + else: + # no valid `self._rcvd_idx` is found (i.e., didn't break) + if not self._persistent_workers: + self._shutdown_workers() + raise StopIteration + + # Now `self._rcvd_idx` is the batch index we want to fetch + + # Check if the next sample has already been generated + if len(self._task_info[self._rcvd_idx]) == 2: + worker_id, data = self._task_info.pop(self._rcvd_idx) + self._rcvd_idx += 1 + return self._process_data(data, worker_id) + + if self._shutdown or self._tasks_outstanding <= 0: + raise AssertionError( + "Invalid iterator state: shutdown or no outstanding tasks when fetching next data" + ) + idx, data = self._get_data() + self._tasks_outstanding -= 1 + if self._dataset_kind == _DatasetKind.Iterable: + # Check for _IterableDatasetStopIteration + if isinstance(data, _utils.worker._IterableDatasetStopIteration): + if self._persistent_workers: + self._workers_status[data.worker_id] = False + else: + self._mark_worker_as_unavailable(data.worker_id) + self._try_put_index() + continue + + if idx != self._rcvd_idx: + if not self._in_order: + # don't store it for later, process now + # delete from self._task_info immediately + # this keeps the object size manageable + worker_id = self._task_info.pop(idx)[0] + return self._process_data(data, worker_id) + # store out-of-order samples + self._task_info[idx] += (data,) + else: + worker_id = self._task_info.pop(idx)[0] + self._rcvd_idx += 1 + return self._process_data(data, worker_id) + + def _try_put_index(self) -> None: + max_tasks = self._prefetch_factor * self._num_workers + if self._tasks_outstanding >= max_tasks: + raise AssertionError( + "Number of outstanding tasks exceeded maximum allowed tasks" + ) + + try: + index = self._next_index() + except StopIteration: + return + for _ in range(self._num_workers): # find the next active worker, if any + worker_queue_idx = next(self._worker_queue_idx_cycle) + if self._workers_status[worker_queue_idx]: + if self._in_order: + break + elif self._workers_num_tasks[worker_queue_idx] < max_tasks // sum( + self._workers_status + ): + # when self._in_order is False, distribute work to a worker if it has capacity + # _workers_status is updated only in this thread, so the sum is guaranteed > 0 + break + else: + # not found (i.e., didn't break) + return + + self._index_queues[worker_queue_idx].put((self._send_idx, index)) # type: ignore[possibly-undefined] + self._task_info[self._send_idx] = (worker_queue_idx,) + self._workers_num_tasks[worker_queue_idx] += 1 + self._tasks_outstanding += 1 + self._send_idx += 1 + + def _process_data(self, data, worker_idx): + self._workers_num_tasks[worker_idx] -= 1 + self._try_put_index() + if isinstance(data, ExceptionWrapper): + data.reraise() + return data + + def _mark_worker_as_unavailable(self, worker_id, shutdown=False) -> None: + # Mark a worker as having finished its work e.g., due to + # exhausting an `IterableDataset`. This should be used only when this + # `_MultiProcessingDataLoaderIter` is going to continue running. + + if ( + not self._workers_status[worker_id] + and not self._persistent_workers + and not shutdown + ): + raise AssertionError( + "Worker status inconsistent when marking worker as unavailable" + ) + + # Signal termination to that specific worker. + q = self._index_queues[worker_id] + # Indicate that no more data will be put on this queue by the current + # process. + q.put(None) + + # Note that we don't actually join the worker here, nor do we remove the + # worker's pid from C side struct because (1) joining may be slow, and + # (2) since we don't join, the worker may still raise error, and we + # prefer capturing those, rather than ignoring them, even though they + # are raised after the worker has finished its job. + # Joining is deferred to `_shutdown_workers`, which it is called when + # all workers finish their jobs (e.g., `IterableDataset` replicas) or + # when this iterator is garbage collected. + + self._workers_status[worker_id] = False + + if self._workers_done_event.is_set() != shutdown: + raise AssertionError( + "_workers_done_event state does not match shutdown flag" + ) + + def _shutdown_workers(self) -> None: + # Called when shutting down this `_MultiProcessingDataLoaderIter`. + # See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on + # the logic of this function. + if ( + _utils is None + # pyrefly: ignore [unnecessary-comparison] + or _utils.python_exit_status is True + # pyrefly: ignore [unnecessary-comparison] + or _utils.python_exit_status is None + ): + # See (2) of the note. If Python is shutting down, do no-op. + return + # Normal exit when last reference is gone / iterator is depleted. + # See (1) and the second half of the note. + if not self._shutdown: + self._shutdown = True + try: + # Normal exit when last reference is gone / iterator is depleted. + # See (1) and the second half of the note. + + # Exit `pin_memory_thread` first because exiting workers may leave + # corrupted data in `worker_result_queue` which `pin_memory_thread` + # reads from. + if hasattr(self, "_pin_memory_thread"): + # Use hasattr in case error happens before we set the attribute. + self._pin_memory_thread_done_event.set() + # Send something to pin_memory_thread in case it is waiting + # so that it can wake up and check `pin_memory_thread_done_event` + self._worker_result_queue.put((None, None)) + self._pin_memory_thread.join() + self._worker_result_queue.cancel_join_thread() + self._worker_result_queue.close() + + # Exit workers now. + self._workers_done_event.set() + for worker_id in range(len(self._workers)): + # Get number of workers from `len(self._workers)` instead of + # `self._num_workers` in case we error before starting all + # workers. + # If we are using workers_status with persistent_workers + # we have to shut it down because the worker is paused + if self._persistent_workers or self._workers_status[worker_id]: + self._mark_worker_as_unavailable(worker_id, shutdown=True) + for w in self._workers: + # We should be able to join here, but in case anything went + # wrong, we set a timeout and if the workers fail to join, + # they are killed in the `finally` block. + w.join(timeout=_utils.MP_STATUS_CHECK_INTERVAL) + for q in self._index_queues: + q.cancel_join_thread() + q.close() + finally: + # Even though all this function does is putting into queues that + # we have called `cancel_join_thread` on, weird things can + # happen when a worker is killed by a signal, e.g., hanging in + # `Event.set()`. So we need to guard this with SIGCHLD handler, + # and remove pids from the C side data structure only at the + # end. + # + # FIXME: Unfortunately, for Windows, we are missing a worker + # error detection mechanism here in this function, as it + # doesn't provide a SIGCHLD handler. + if self._worker_pids_set: + _utils.signal_handling._remove_worker_pids(id(self)) + self._worker_pids_set = False + for w in self._workers: + if w.is_alive(): + # Existing mechanisms try to make the workers exit + # peacefully, but in case that we unfortunately reach + # here, which we shouldn't, (e.g., pytorch/pytorch#39570), + # we kill the worker. + w.terminate() + w.join(timeout=_utils.MP_STATUS_CHECK_INTERVAL) + + @staticmethod + def _clean_up_persistent_workers_atexit() -> None: + # This callback is registered after `_utils._set_python_exit_flag`, + # so it runs while `_shutdown_workers()` can still use multiprocessing. + with _persistent_workers_atexit_lock: + iterators = tuple(_persistent_workers_atexit) + for iterator in iterators: + iterator._shutdown_workers() + + def _register_persistent_workers_atexit(self) -> None: + import atexit + + global _persistent_workers_atexit_registered + with _persistent_workers_atexit_lock: + _persistent_workers_atexit.add(self) + if _persistent_workers_atexit_registered: + return + atexit.register( + _MultiProcessingDataLoaderIter._clean_up_persistent_workers_atexit + ) + _persistent_workers_atexit_registered = True + + def __del__(self) -> None: + self._shutdown_workers() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ac93de335b2d7379246de9cee658dd9eafe1d303 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__init__.py @@ -0,0 +1 @@ +from torch.utils.data.datapipes import dataframe as dataframe, iter as iter, map as map diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c036c361ee29251303f1826a8a63939faa0cff3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/_decorator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/_decorator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cb2c1462e2f0e543b9daafd898cc90193388c10 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/_decorator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/_hook_iterator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/_hook_iterator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f4394ad2d14ebf244131cb1acad778e438456d4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/_hook_iterator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/_typing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/_typing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49fe612c39217529c330ac7fa248cc0c5907ebde Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/_typing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/datapipe.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/datapipe.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6734ab181dd0ceb68b216dbe8b378d94b1f11d92 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/datapipe.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/gen_pyi.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/gen_pyi.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85bcc13de7d42cd35290b0b622371bc17ce2436d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/__pycache__/gen_pyi.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/_decorator.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/_decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..41211baef8a2125c09032de4b4420185e87ae529 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/_decorator.py @@ -0,0 +1,213 @@ +# mypy: allow-untyped-defs +import inspect +from collections.abc import Callable +from functools import wraps +from typing import Any, get_type_hints + +from torch.utils.data.datapipes._typing import _DataPipeMeta +from torch.utils.data.datapipes.datapipe import IterDataPipe, MapDataPipe + + +###################################################### +# Functional API +###################################################### +class functional_datapipe: + name: str + + def __init__(self, name: str, enable_df_api_tracing=False) -> None: + """ + Define a functional datapipe. + + Args: + enable_df_api_tracing - if set, any returned DataPipe would accept + DataFrames API in tracing mode. + """ + self.name = name + self.enable_df_api_tracing = enable_df_api_tracing + + def __call__(self, cls): + if issubclass(cls, IterDataPipe): + if isinstance(cls, type): # type: ignore[arg-type] + if not isinstance(cls, _DataPipeMeta): + raise TypeError( + "`functional_datapipe` can only decorate IterDataPipe" + ) + # with non_deterministic decorator + else: + if not isinstance(cls, non_deterministic) and not ( + hasattr(cls, "__self__") + and isinstance(cls.__self__, non_deterministic) + ): + raise TypeError( + "`functional_datapipe` can only decorate IterDataPipe" + ) + IterDataPipe.register_datapipe_as_function( + self.name, cls, enable_df_api_tracing=self.enable_df_api_tracing + ) + elif issubclass(cls, MapDataPipe): + MapDataPipe.register_datapipe_as_function(self.name, cls) + + return cls + + +###################################################### +# Determinism +###################################################### +_determinism: bool = False + + +class guaranteed_datapipes_determinism: + prev: bool + + def __init__(self) -> None: + global _determinism + self.prev = _determinism + _determinism = True + + def __enter__(self) -> None: + pass + + def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: + global _determinism + _determinism = self.prev + + +class non_deterministic: + cls: type[IterDataPipe] | None = None + # TODO: Lambda for picking + deterministic_fn: Callable[..., bool] + + def __init__(self, arg: type[IterDataPipe] | Callable[..., bool]) -> None: + # 1. Decorator doesn't have any argument + if isinstance(arg, type): # type: ignore[arg-type] + if not issubclass(arg, IterDataPipe): # type: ignore[arg-type] + raise TypeError( + "Only `IterDataPipe` can be decorated with `non_deterministic`" + f", but {arg.__name__} is found" + ) + self.cls = arg # type: ignore[assignment] + # 2. Decorator has an argument of a function + # This class should behave differently given different inputs. Use this + # function to verify the determinism for each instance. + # When the function returns True, the instance is non-deterministic. Otherwise, + # the instance is a deterministic DataPipe. + elif isinstance(arg, Callable): # type:ignore[arg-type] + self.deterministic_fn = arg + else: + raise TypeError(f"{arg} can not be decorated by non_deterministic") + + def __call__(self, *args, **kwargs): + global _determinism + # Decorate IterDataPipe + if self.cls is not None: + if _determinism: + raise TypeError( + f"{self.cls.__name__} is non-deterministic, but you set 'guaranteed_datapipes_determinism'. " + "You can turn off determinism for this DataPipe if that is acceptable " + "for your application" + ) + return self.cls(*args, **kwargs) # type: ignore[call-arg] + + # Decorate with a functional argument + if not ( + isinstance(args[0], type) and issubclass(args[0], IterDataPipe) # type: ignore[arg-type] + ): + raise TypeError( + f"Only `IterDataPipe` can be decorated, but {args[0].__name__} is found" + ) + self.cls = args[0] + return self.deterministic_wrapper_fn + + def deterministic_wrapper_fn(self, *args, **kwargs) -> IterDataPipe: + res = self.deterministic_fn(*args, **kwargs) + if not isinstance(res, bool): + raise TypeError( + "deterministic_fn of `non_deterministic` decorator is required " + f"to return a boolean value, but {type(res)} is found" + ) + global _determinism + if _determinism and res: + raise TypeError( + f"{self.cls.__name__} is non-deterministic with the inputs, but you set " # type: ignore[union-attr] + "'guaranteed_datapipes_determinism'. You can turn off determinism " + "for this DataPipe if that is acceptable for your application" + ) + return self.cls(*args, **kwargs) # type: ignore[call-arg, misc] + + +###################################################### +# Type validation +###################################################### +# Validate each argument of DataPipe with hint as a subtype of the hint. +def argument_validation(f): + signature = inspect.signature(f) + hints = get_type_hints(f) + + @wraps(f) + def wrapper(*args, **kwargs): + bound = signature.bind(*args, **kwargs) + for argument_name, value in bound.arguments.items(): + if argument_name in hints and isinstance( + hints[argument_name], _DataPipeMeta + ): + hint = hints[argument_name] + if not isinstance(value, IterDataPipe): + raise TypeError( + f"Expected argument '{argument_name}' as an IterDataPipe, but found {type(value)}" + ) + if not value.type.issubtype(hint.type): + raise TypeError( + f"Expected type of argument '{argument_name}' as a subtype of " + f"hint {hint.type}, but found {value.type}" + ) + + return f(*args, **kwargs) + + return wrapper + + +# Default value is True +_runtime_validation_enabled: bool = True + + +class runtime_validation_disabled: + prev: bool + + def __init__(self) -> None: + global _runtime_validation_enabled + self.prev = _runtime_validation_enabled + _runtime_validation_enabled = False + + def __enter__(self) -> None: + pass + + def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: + global _runtime_validation_enabled + _runtime_validation_enabled = self.prev + + +# Runtime checking +# Validate output data is subtype of return hint +def runtime_validation(f): + # TODO: + # Can be extended to validate '__getitem__' and nonblocking + if f.__name__ != "__iter__": + raise TypeError( + f"Can not decorate function {f.__name__} with 'runtime_validation'" + ) + + @wraps(f) + def wrapper(self): + global _runtime_validation_enabled + if not _runtime_validation_enabled: + yield from f(self) + else: + it = f(self) + for d in it: + if not self.type.issubtype_of_instance(d): + raise RuntimeError( + f"Expected an instance as subtype of {self.type}, but found {d}({type(d)})" + ) + yield d + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/_hook_iterator.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/_hook_iterator.py new file mode 100644 index 0000000000000000000000000000000000000000..ddbaec48531974e76da8b92c8f9d13c0e0794b34 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/_hook_iterator.py @@ -0,0 +1,279 @@ +# mypy: allow-untyped-defs +import functools +import inspect +from enum import Enum + +import torch + + +class _SnapshotState(Enum): + r""" + These are the snapshotting-related states that IterDataPipes can be in. + + `NotStarted` - allows you to restore a snapshot and create an iterator with reset + `Restored` - cannot restore again, allows you to create an iterator without resetting the DataPipe + `Iterating` - can restore, will reset if you create a new iterator + """ + + NotStarted = 0 + Restored = 1 + Iterating = 2 + + +def _simplify_obj_name(obj) -> str: + """Simplify the display strings of objects for the purpose of rendering within DataPipe error messages.""" + if inspect.isfunction(obj): + return obj.__name__ + else: + return repr(obj) + + +def _strip_datapipe_from_name(name: str) -> str: + return name.replace("IterDataPipe", "").replace("MapDataPipe", "") + + +def _generate_input_args_string(obj): + """Generate a string for the input arguments of an object.""" + signature = inspect.signature(obj.__class__) + input_param_names = set(signature.parameters.keys()) + result = [] + for name, value in inspect.getmembers(obj): + if name in input_param_names: + result.append((name, _simplify_obj_name(value))) + return ", ".join([f"{name}={value}" for name, value in result]) + + +def _generate_iterdatapipe_msg(datapipe, simplify_dp_name: bool = False): + output_string = ( + f"{datapipe.__class__.__name__}({_generate_input_args_string(datapipe)})" + ) + if simplify_dp_name: + output_string = _strip_datapipe_from_name(output_string) + return output_string + + +def _gen_invalid_iterdatapipe_msg(datapipe) -> str: + return ( + "This iterator has been invalidated because another iterator has been created " + f"from the same IterDataPipe: {_generate_iterdatapipe_msg(datapipe)}\n" + "This may be caused by multiple references to the same IterDataPipe. We recommend " + "using `.fork()` if that is necessary." + ) + + +_feedback_msg = ( + "\nFor feedback regarding this single iterator per IterDataPipe constraint, feel free " + "to comment on this issue: https://github.com/pytorch/data/issues/45." +) + + +def _check_iterator_valid(datapipe, iterator_id, next_method_exists=False) -> None: + r""" + Given an instance of a DataPipe and an iterator ID, check if the IDs match, and if not, raises an exception. + + In the case of ChildDataPipe, the ID gets compared to the one stored in `main_datapipe` as well. + """ + if next_method_exists: + # This is the case where `IterDataPipe` has both `__iter__` and `__next__`. + # The `_valid_iterator_id` should either be never set (`None`), or set by at most one + # iterator (`0`). Otherwise, it means there are multiple iterators. + if datapipe._valid_iterator_id is not None and datapipe._valid_iterator_id != 0: + extra_msg = "\nNote that this exception is raised inside your IterDataPipe's `__next__` method" + raise RuntimeError( + _gen_invalid_iterdatapipe_msg(datapipe) + extra_msg + _feedback_msg + ) + elif ( + hasattr(datapipe, "_is_child_datapipe") and datapipe._is_child_datapipe is True + ): + if hasattr(datapipe, "_check_valid_iterator_id"): + if not datapipe._check_valid_iterator_id(iterator_id): + raise RuntimeError( + "This iterator has been invalidated, because a new iterator has been created " + f"from one of the ChildDataPipes of " + f"{_generate_iterdatapipe_msg(datapipe.main_datapipe)}." + + _feedback_msg + ) + else: + raise RuntimeError( + "ChildDataPipe must have method `_check_valid_iterator_id`." + ) + elif datapipe._valid_iterator_id != iterator_id: + raise RuntimeError(_gen_invalid_iterdatapipe_msg(datapipe) + _feedback_msg) + + +def _set_datapipe_valid_iterator_id(datapipe): + """Given a DataPipe, updates its valid iterator ID and reset the DataPipe.""" + if hasattr(datapipe, "_is_child_datapipe") and datapipe._is_child_datapipe is True: + if hasattr(datapipe, "_set_main_datapipe_valid_iterator_id"): + datapipe._set_main_datapipe_valid_iterator_id() # reset() is called within this method when appropriate + else: + raise RuntimeError( + "ChildDataPipe must have method `_set_main_datapipe_valid_iterator_id`." + ) + else: + if datapipe._valid_iterator_id is None: + datapipe._valid_iterator_id = 0 + else: + datapipe._valid_iterator_id += 1 + datapipe.reset() + return datapipe._valid_iterator_id + + +def hook_iterator(namespace) -> None: + r""" + Define a hook that is applied to all `__iter__` of metaclass `_DataPipeMeta`. + + This is done for the purpose of profiling and checking if an iterator is still valid. + """ + + def profiler_record_fn_context(datapipe): + if not hasattr(datapipe, "_profile_name"): + datapipe._profile_name = _generate_iterdatapipe_msg( + datapipe, simplify_dp_name=True + ) + return torch.autograd.profiler.record_function(datapipe._profile_name) + + class IteratorDecorator: + r""" + Wrap the iterator and modifying its `__next__` method. + + This decorator is applied to DataPipes of which `__iter__` method is NOT a generator function. + Those `__iter__` method commonly returns `self` but not necessarily. + """ + + def __init__(self, iterator, datapipe, iterator_id, has_next_method) -> None: + self.iterator = iterator + self.datapipe = datapipe + self.iterator_id = iterator_id + self._profiler_enabled = torch.autograd._profiler_enabled() + # Check if `__iter__` returns `self` and `DataPipe` has `__next__` + self.self_and_has_next_method = ( + self.iterator is self.datapipe and has_next_method + ) + + def __iter__(self): + return self + + def _get_next(self): + """Return next with logic related to iterator validity, profiler, and incrementation of samples yielded.""" + _check_iterator_valid(self.datapipe, self.iterator_id) + result = next(self.iterator) + if not self.self_and_has_next_method: + self.datapipe._number_of_samples_yielded += 1 + return result + + def __next__(self): + # TODO: Add try-except to in-place reduce traceback from the Exception + # See: https://github.com/pytorch/data/issues/284 + if self._profiler_enabled: + with profiler_record_fn_context(self.datapipe): + return self._get_next() + else: # Decided against using `contextlib.nullcontext` for performance reasons + return self._get_next() + + def __getattr__(self, name): + return getattr(self.iterator, name) + + func = namespace["__iter__"] + + # ``__iter__`` of IterDataPipe is a generator function + if inspect.isgeneratorfunction(func): + + @functools.wraps(func) + def wrap_generator(*args, **kwargs): + gen = func(*args, **kwargs) + datapipe = args[0] + if datapipe._fast_forward_iterator: + it = datapipe._fast_forward_iterator + datapipe._fast_forward_iterator = None + datapipe._snapshot_state = _SnapshotState.Iterating + while True: + try: + yield next(it) + except StopIteration: + return + iterator_id = _set_datapipe_valid_iterator_id( + datapipe + ) # This ID is tied to each created iterator + _profiler_enabled = torch.autograd._profiler_enabled() + try: + if _profiler_enabled: + with profiler_record_fn_context(datapipe): + response = gen.send(None) + else: + response = gen.send(None) + + while True: + datapipe._number_of_samples_yielded += 1 + request = yield response + # Pass through here every time `__next__` is called + if _profiler_enabled: + with profiler_record_fn_context(datapipe): + _check_iterator_valid(datapipe, iterator_id) + response = gen.send(request) + else: # Decided against using `contextlib.nullcontext` for performance reasons + _check_iterator_valid(datapipe, iterator_id) + response = gen.send(request) + except StopIteration: + return + except Exception as e: + # TODO: Simplify the traceback message to skip over `response = gen.send(None)` + # Part of https://github.com/pytorch/data/issues/284 + datapipe = args[0] + msg = "thrown by __iter__ of" + single_iterator_msg = "single iterator per IterDataPipe constraint" + if hasattr(e.args, "__len__"): + full_msg = f"{msg} {datapipe.__class__.__name__}({_generate_input_args_string(datapipe)})" + if len(e.args) == 0 or not isinstance( + e.args[0], str + ): # If an exception message doesn't exist + e.args = (f"\nThis exception is {full_msg}",) + elif msg not in e.args[0] and single_iterator_msg not in e.args[0]: + e.args = ( + e.args[0] + f"\nThis exception is {full_msg}", + ) + e.args[1:] + raise + + namespace["__iter__"] = wrap_generator + else: # ``__iter__`` of IterDataPipe is NOT a generator function + # IterDataPipe is an iterator with both ``__iter__`` and ``__next__`` + # And ``__iter__`` may or may not return `self` + if "__next__" in namespace: # If `__next__` exists, put a wrapper around it + next_func = namespace["__next__"] + + @functools.wraps(next_func) + def wrap_next(*args, **kwargs): + datapipe = args[0] + if torch.autograd._profiler_enabled(): + with profiler_record_fn_context(datapipe): + result = next_func(*args, **kwargs) + else: + result = next_func(*args, **kwargs) + datapipe._number_of_samples_yielded += 1 + return result + + namespace["__next__"] = wrap_next + + # Note that if the `__next__` and `__iter__` do something completely unrelated. It may cause issue but + # the user will be violating the iterator protocol. Potential issue: + # 1. Valid iterator ID may not update or checked properly + # 2. The number of samples yielded will be miscounted + + # Regardless if `__next__` exists or not, `__iter__` needs a wrapper to track the number of valid iterators + @functools.wraps(func) + def wrap_iter(*args, **kwargs): + iter_ret = func(*args, **kwargs) + datapipe = args[0] + datapipe._snapshot_state = _SnapshotState.Iterating + if datapipe._fast_forward_iterator: + iter_ret = datapipe._fast_forward_iterator + datapipe._fast_forward_iterator = None + return iter_ret + iterator_id = _set_datapipe_valid_iterator_id( + datapipe + ) # This ID is tied to each created iterator + return IteratorDecorator( + iter_ret, datapipe, iterator_id, "__next__" in namespace + ) + + namespace["__iter__"] = wrap_iter diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/_typing.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..2784bbc49ec6451744fb7a90ef749ad680ddc4cc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/_typing.py @@ -0,0 +1,481 @@ +# mypy: allow-untyped-defs +# Taking reference from official Python typing +# https://github.com/python/cpython/blob/master/Lib/typing.py + +import collections +import functools +import numbers +import sys + +# Please check [Note: TypeMeta and TypeAlias] +# In case of metaclass conflict due to ABCMeta or _ProtocolMeta +# For Python 3.9, only Protocol in typing uses metaclass +from abc import ABCMeta +from collections.abc import Iterator + +# TODO: Use TypeAlias when Python 3.6 is deprecated +from typing import ( + _eval_type, # pyrefly: ignore [missing-module-attribute] + _GenericAlias, # pyrefly: ignore [missing-module-attribute] + _tp_cache, # pyrefly: ignore [missing-module-attribute] + _type_check, # pyrefly: ignore [missing-module-attribute] + _type_repr, + Any, + ForwardRef, + Generic, + get_args, + get_type_hints, + TypeVar, + Union, +) + +from torch.utils.data.datapipes._hook_iterator import _SnapshotState, hook_iterator + + +class GenericMeta(ABCMeta): # type: ignore[no-redef] + pass + + +class Integer(numbers.Integral): + pass + + +class Boolean(numbers.Integral): + pass + + +# Python 'type' object is not subscriptable +# Tuple[int, List, dict] -> valid +# tuple[int, list, dict] -> invalid +# Map Python 'type' to abstract base class +TYPE2ABC = { + bool: Boolean, + int: Integer, + float: numbers.Real, + complex: numbers.Complex, + dict: dict, + list: list, + set: set, + tuple: tuple, + None: type(None), +} + + +def issubtype(left, right, recursive=True): + r""" + Check if the left-side type is a subtype of the right-side type. + + If any of type is a composite type like `Union` and `TypeVar` with + bounds, it would be expanded into a list of types and check all + of left-side types are subtypes of either one from right-side types. + """ + left = TYPE2ABC.get(left, left) + right = TYPE2ABC.get(right, right) + + if right is Any or left == right: + return True + + if isinstance(right, _GenericAlias): + if getattr(right, "__origin__", None) is Generic: + return True + + if right is type(None): + return False + + # Right-side type + constraints = _decompose_type(right) + + if len(constraints) == 0 or Any in constraints: + return True + + if left is Any: + return False + + # Left-side type + variants = _decompose_type(left) + + # all() will return True for empty variants + if len(variants) == 0: + return False + + return all( + _issubtype_with_constraints(variant, constraints, recursive) + for variant in variants + ) + + +def _decompose_type(t, to_list=True): + if isinstance(t, TypeVar): + if t.__bound__ is not None: + ts = [t.__bound__] + else: + # For T_co, __constraints__ is () + ts = list(t.__constraints__) + elif hasattr(t, "__origin__") and t.__origin__ == Union: + ts = get_args(t) + else: + if not to_list: + return None + ts = [t] + # Ignored: Generator has incompatible item type "object"; expected "Type[Any]" + ts = [TYPE2ABC.get(_t, _t) for _t in ts] # type: ignore[misc] + return ts + + +def _issubtype_with_constraints(variant, constraints, recursive=True): + r""" + Check if the variant is a subtype of either one from constraints. + + For composite types like `Union` and `TypeVar` with bounds, they + would be expanded for testing. + """ + if variant in constraints: + return True + + # [Note: Subtype for Union and TypeVar] + # Python typing is able to flatten Union[Union[...]] or Union[TypeVar]. + # But it couldn't flatten the following scenarios: + # - Union[int, TypeVar[Union[...]]] + # - TypeVar[TypeVar[...]] + # So, variant and each constraint may be a TypeVar or a Union. + # In these cases, all of inner types from the variant are required to be + # extracted and verified as a subtype of any constraint. And, all of + # inner types from any constraint being a TypeVar or a Union are + # also required to be extracted and verified if the variant belongs to + # any of them. + + # Variant + vs = _decompose_type(variant, to_list=False) + + # Variant is TypeVar or Union + if vs is not None: + return all(_issubtype_with_constraints(v, constraints, recursive) for v in vs) + + # Variant is not TypeVar or Union + if hasattr(variant, "__origin__") and variant.__origin__ is not None: + v_origin = variant.__origin__ + v_args = get_args(variant) or None + else: + v_origin = variant + v_args = None + + # Constraints + for constraint in constraints: + cs = _decompose_type(constraint, to_list=False) + + # Constraint is TypeVar or Union + if cs is not None: + if _issubtype_with_constraints(variant, cs, recursive): + return True + # Constraint is not TypeVar or Union + else: + # __origin__ can be None for plain list, tuple, ... in Python 3.6 + if hasattr(constraint, "__origin__") and constraint.__origin__ is not None: + c_origin = constraint.__origin__ + if v_origin == c_origin: + if not recursive: + return True + c_args = get_args(constraint) or None + if c_args is None or len(c_args) == 0: + return True + if ( + v_args is not None + and len(v_args) == len(c_args) + and all( + issubtype(v_arg, c_arg) + for v_arg, c_arg in zip(v_args, c_args, strict=True) + ) + ): + return True + # Tuple[int] -> Tuple + else: + if v_origin == constraint: + return True + + return False + + +def issubinstance(data, data_type): + if not issubtype(type(data), data_type, recursive=False): + return False + + dt_args = get_args(data_type) or None + if isinstance(data, tuple): + if dt_args is None or len(dt_args) == 0: + return True + if len(dt_args) != len(data): + return False + return all(issubinstance(d, t) for d, t in zip(data, dt_args, strict=True)) + elif isinstance(data, (list, set)): + if dt_args is None or len(dt_args) == 0: + return True + t = dt_args[0] + return all(issubinstance(d, t) for d in data) + elif isinstance(data, dict): + if dt_args is None or len(dt_args) == 0: + return True + kt, vt = dt_args + return all( + issubinstance(k, kt) and issubinstance(v, vt) for k, v in data.items() + ) + + return True + + +# [Note: TypeMeta and TypeAlias] +# In order to keep compatibility for Python 3.6, use Meta for the typing. +# TODO: When PyTorch drops the support for Python 3.6, it can be converted +# into the Alias system and using `__class_getitem__` for DataPipe. The +# typing system will gain benefit of performance and resolving metaclass +# conflicts as elaborated in https://www.python.org/dev/peps/pep-0560/ + + +class _DataPipeType: + r"""Save type annotation in `param`.""" + + def __init__(self, param) -> None: + self.param = param + + def __repr__(self) -> str: + return _type_repr(self.param) + + def __eq__(self, other): + if isinstance(other, _DataPipeType): + return self.param == other.param + return NotImplemented + + def __hash__(self): + return hash(self.param) + + def issubtype(self, other): + if isinstance(other.param, _GenericAlias): + if getattr(other.param, "__origin__", None) is Generic: + return True + if isinstance(other, _DataPipeType): + return issubtype(self.param, other.param) + if isinstance(other, type): + return issubtype(self.param, other) + raise TypeError(f"Expected '_DataPipeType' or 'type', but found {type(other)}") + + def issubtype_of_instance(self, other): + return issubinstance(other, self.param) + + +# Default type for DataPipe without annotation +_T_co = TypeVar("_T_co", covariant=True) +# pyrefly: ignore [invalid-annotation] +_DEFAULT_TYPE = _DataPipeType(Generic[_T_co]) + + +class _DataPipeMeta(GenericMeta): + r""" + Metaclass for `DataPipe`. + + Add `type` attribute and `__init_subclass__` based on the type, and validate the return hint of `__iter__`. + + Note that there is subclass `_IterDataPipeMeta` specifically for `IterDataPipe`. + """ + + type: _DataPipeType + + def __new__(cls, name, bases, namespace, **kwargs): + return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload] + + # TODO: the statements below are not reachable by design as there is a bug and typing is low priority for now. + cls.__origin__ = None + if "type" in namespace: + return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload] + + namespace["__type_class__"] = False + # For plain derived class without annotation + for base in bases: + if isinstance(base, _DataPipeMeta): + return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload] + + namespace.update( + {"type": _DEFAULT_TYPE, "__init_subclass__": _dp_init_subclass} + ) + return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload] + + def __init__(self, name, bases, namespace, **kwargs) -> None: + super().__init__(name, bases, namespace, **kwargs) # type: ignore[call-overload] + + # TODO: Fix isinstance bug + @_tp_cache + def _getitem_(self, params): + if params is None: + raise TypeError(f"{self.__name__}[t]: t can not be None") + if isinstance(params, str): + params = ForwardRef(params) + if not isinstance(params, tuple): + params = (params,) + + msg = f"{self.__name__}[t]: t must be a type" + params = tuple(_type_check(p, msg) for p in params) + + if isinstance(self.type.param, _GenericAlias): + orig = getattr(self.type.param, "__origin__", None) + if isinstance(orig, type) and orig is not Generic: + p = self.type.param[params] # type: ignore[index] + t = _DataPipeType(p) + l = len(str(self.type)) + 2 + name = self.__name__[:-l] + name = name + "[" + str(t) + "]" + bases = (self,) + self.__bases__ + return self.__class__( + name, + bases, + { + "__init_subclass__": _dp_init_subclass, + "type": t, + "__type_class__": True, + }, + ) + + if len(params) > 1: + raise TypeError( + f"Too many parameters for {self} actual {len(params)}, expected 1" + ) + + t = _DataPipeType(params[0]) + + if not t.issubtype(self.type): + raise TypeError( + f"Can not subclass a DataPipe[{t}] from DataPipe[{self.type}]" + ) + + # Types are equal, fast path for inheritance + if self.type == t: + return self + + name = self.__name__ + "[" + str(t) + "]" + bases = (self,) + self.__bases__ + + return self.__class__( + name, + bases, + {"__init_subclass__": _dp_init_subclass, "__type_class__": True, "type": t}, + ) + + # TODO: Fix isinstance bug + def _eq_(self, other): + if not isinstance(other, _DataPipeMeta): + return NotImplemented + if self.__origin__ is None or other.__origin__ is None: # type: ignore[has-type] + return self is other + return ( + self.__origin__ == other.__origin__ # type: ignore[has-type] + and self.type == other.type + ) + + # TODO: Fix isinstance bug + def _hash_(self): + return hash((self.__name__, self.type)) + + +class _IterDataPipeMeta(_DataPipeMeta): + r""" + Metaclass for `IterDataPipe` and inherits from `_DataPipeMeta`. + + Add various functions for behaviors specific to `IterDataPipe`. + """ + + def __new__(cls, name, bases, namespace, **kwargs): + if "reset" in namespace: + reset_func = namespace["reset"] + + @functools.wraps(reset_func) + def conditional_reset(*args, **kwargs) -> None: + r""" + Only execute DataPipe's `reset()` method if `_SnapshotState` is `Iterating` or `NotStarted`. + + This allows recently restored DataPipe to preserve its restored state during the initial `__iter__` call. + """ + datapipe = args[0] + if datapipe._snapshot_state in ( + _SnapshotState.Iterating, + _SnapshotState.NotStarted, + ): + # Reset `NotStarted` is necessary because the `source_datapipe` of a DataPipe might have + # already begun iterating. + datapipe._number_of_samples_yielded = 0 + datapipe._fast_forward_iterator = None + reset_func(*args, **kwargs) + datapipe._snapshot_state = _SnapshotState.Iterating + + namespace["reset"] = conditional_reset + + if "__iter__" in namespace: + hook_iterator(namespace) + return super().__new__(cls, name, bases, namespace, **kwargs) # type: ignore[call-overload] + + +def _dp_init_subclass(sub_cls, *args, **kwargs) -> None: + # Add function for datapipe instance to reinforce the type + sub_cls.reinforce_type = reinforce_type + + # TODO: + # - add global switch for type checking at compile-time + + # Ignore internal type class + if getattr(sub_cls, "__type_class__", False): + return + + # Check if the string type is valid + if isinstance(sub_cls.type.param, ForwardRef): + base_globals = sys.modules[sub_cls.__module__].__dict__ + try: + param = _eval_type(sub_cls.type.param, base_globals, locals()) + sub_cls.type.param = param + except TypeError as e: + raise TypeError( + f"{sub_cls.type.param.__forward_arg__} is not supported by Python typing" + ) from e + + if "__iter__" in sub_cls.__dict__: + iter_fn = sub_cls.__dict__["__iter__"] + hints = get_type_hints(iter_fn) + if "return" in hints: + return_hint = hints["return"] + # Plain Return Hint for Python 3.6 + if return_hint == Iterator: + return + if not ( + hasattr(return_hint, "__origin__") + and ( + return_hint.__origin__ == Iterator + or return_hint.__origin__ == collections.abc.Iterator + ) + ): + raise TypeError( + "Expected 'Iterator' as the return annotation for `__iter__` of {}" + ", but found {}".format( + sub_cls.__name__, _type_repr(hints["return"]) + ) + ) + data_type = get_args(return_hint)[0] + if not issubtype(data_type, sub_cls.type.param): + raise TypeError( + f"Expected return type of '__iter__' as a subtype of {sub_cls.type}," + f" but found {_type_repr(data_type)} for {sub_cls.__name__}" + ) + + +def reinforce_type(self, expected_type): + r""" + Reinforce the type for DataPipe instance. + + And the 'expected_type' is required to be a subtype of the original type + hint to restrict the type requirement of DataPipe instance. + """ + if isinstance(expected_type, tuple): + expected_type = tuple[expected_type] # type: ignore[valid-type] + _type_check(expected_type, msg="'expected_type' must be a type") + + if not issubtype(expected_type, self.type.param): + raise TypeError( + f"Expected 'expected_type' as subtype of {self.type}, but found {_type_repr(expected_type)}" + ) + + self.type = _DataPipeType(expected_type) + return self diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f7f4b7dcb414c205614a694ccaa02961e45e9b3e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__init__.py @@ -0,0 +1,12 @@ +from torch.utils.data.datapipes.dataframe.dataframes import ( + CaptureDataFrame, + DFIterDataPipe, +) +from torch.utils.data.datapipes.dataframe.datapipes import DataFramesAsTuplesPipe + + +__all__ = ["CaptureDataFrame", "DFIterDataPipe", "DataFramesAsTuplesPipe"] + +# Please keep this list sorted +if __all__ != sorted(__all__): + raise AssertionError("__all__ is not sorted") diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..833863f2e89363cbdaff4ba88aa1e22b0b1dbcde Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/dataframe_wrapper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/dataframe_wrapper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bc406b663d37c6e2d940e6564d04f5576d97b8f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/dataframe_wrapper.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/dataframes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/dataframes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..787cd9b27c63ec89aa46e458074e870b5123d733 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/dataframes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/datapipes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/datapipes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c65407cfab57df5225c8831aecd0f4e5177cbee3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/datapipes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/structures.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/structures.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4581847c15dfc6a866b0d1a253ec4e3c0b6439e9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/__pycache__/structures.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/dataframe_wrapper.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/dataframe_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..9cfc5c268a17455cb30d981036996a716d0cc668 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/dataframe_wrapper.py @@ -0,0 +1,128 @@ +# mypy: allow-untyped-defs +from typing import Any + + +_pandas: Any = None +_WITH_PANDAS: bool | None = None + + +def _try_import_pandas() -> bool: + try: + import pandas # type: ignore[import] + + global _pandas + _pandas = pandas + return True + except ImportError: + return False + + +# pandas used only for prototyping, will be shortly replaced with TorchArrow +def _with_pandas() -> bool: + global _WITH_PANDAS + if _WITH_PANDAS is None: + _WITH_PANDAS = _try_import_pandas() + return _WITH_PANDAS + + +class PandasWrapper: + @classmethod + def create_dataframe(cls, data, columns): + if not _with_pandas(): + raise RuntimeError("DataFrames prototype requires pandas to function") + return _pandas.DataFrame(data, columns=columns) # type: ignore[union-attr] + + @classmethod + def is_dataframe(cls, data): + if not _with_pandas(): + return False + return isinstance(data, _pandas.core.frame.DataFrame) # type: ignore[union-attr] + + @classmethod + def is_column(cls, data): + if not _with_pandas(): + return False + return isinstance(data, _pandas.core.series.Series) # type: ignore[union-attr] + + @classmethod + def iterate(cls, data): + if not _with_pandas(): + raise RuntimeError("DataFrames prototype requires pandas to function") + yield from data.itertuples(index=False) + + @classmethod + def concat(cls, buffer): + if not _with_pandas(): + raise RuntimeError("DataFrames prototype requires pandas to function") + return _pandas.concat(buffer) # type: ignore[union-attr] + + @classmethod + def get_item(cls, data, idx): + if not _with_pandas(): + raise RuntimeError("DataFrames prototype requires pandas to function") + return data[idx : idx + 1] + + @classmethod + def get_len(cls, df): + if not _with_pandas(): + raise RuntimeError("DataFrames prototype requires pandas to function") + return len(df.index) + + @classmethod + def get_columns(cls, df): + if not _with_pandas(): + raise RuntimeError("DataFrames prototype requires pandas to function") + return list(df.columns.values.tolist()) + + +# When you build own implementation just override it with dataframe_wrapper.set_df_wrapper(new_wrapper_class) +default_wrapper = PandasWrapper + + +def get_df_wrapper(): + return default_wrapper + + +def set_df_wrapper(wrapper) -> None: + global default_wrapper + default_wrapper = wrapper + + +def create_dataframe(data, columns=None): + wrapper = get_df_wrapper() + return wrapper.create_dataframe(data, columns) + + +def is_dataframe(data): + wrapper = get_df_wrapper() + return wrapper.is_dataframe(data) + + +def get_columns(data): + wrapper = get_df_wrapper() + return wrapper.get_columns(data) + + +def is_column(data): + wrapper = get_df_wrapper() + return wrapper.is_column(data) + + +def concat(buffer): + wrapper = get_df_wrapper() + return wrapper.concat(buffer) + + +def iterate(data): + wrapper = get_df_wrapper() + return wrapper.iterate(data) + + +def get_item(data, idx): + wrapper = get_df_wrapper() + return wrapper.get_item(data, idx) + + +def get_len(df): + wrapper = get_df_wrapper() + return wrapper.get_len(df) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/dataframes.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/dataframes.py new file mode 100644 index 0000000000000000000000000000000000000000..d2608796dc75e2ae2c441b77de5bcbc760919459 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/dataframes.py @@ -0,0 +1,468 @@ +# mypy: allow-untyped-defs +from typing import Any, NoReturn + +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.dataframe.structures import DataChunkDF +from torch.utils.data.datapipes.datapipe import DFIterDataPipe, IterDataPipe + + +# TODO(VitalyFedyunin): Add error when two different traces get combined + +__all__ = [ + "Capture", + "CaptureA", + "CaptureAdd", + "CaptureCall", + "CaptureControl", + "CaptureDataFrame", + "CaptureDataFrameWithDataPipeOps", + "CaptureF", + "CaptureGetAttr", + "CaptureGetItem", + "CaptureInitial", + "CaptureLikeMock", + "CaptureMul", + "CaptureSetItem", + "CaptureSub", + "CaptureVariable", + "CaptureVariableAssign", + "DataFrameTracer", + "DataFrameTracedOps", + "disable_capture", + "get_val", +] + + +def disable_capture() -> None: + CaptureControl.disabled = True + + +class CaptureControl: + disabled = False + + +class DataFrameTracedOps(DFIterDataPipe): + def __init__(self, source_datapipe, output_var) -> None: + super().__init__() + self.source_datapipe = source_datapipe + self.output_var = output_var + + def __iter__(self): + for item in self.source_datapipe: + yield self.output_var.apply_ops(item) + + +# TODO(VitalyFedyunin): Extract this list from the DFIterDataPipe registered functions +DATAPIPES_OPS = [ + "_dataframes_as_tuples", + "groupby", + "_dataframes_filter", + "map", + "to_datapipe", + "shuffle", + "concat", + "batch", + "_dataframes_per_row", + "_dataframes_concat", + "_dataframes_shuffle", +] + +UNIMPLEMENTED_ATTR = ["__deepcopy__", "__setstate__", "is_shardable", "apply_sharding"] + + +class Capture: + # TODO: All operations are shared across entire InitialCapture, need to figure out what if we join two captures + + def __init__(self, schema_df=None) -> None: + self.ctx = {"operations": [], "variables": [], "schema_df": schema_df} + + def __str__(self) -> str: + return self._ops_str() + + def _ops_str(self): + res = "" + for op in self.ctx["operations"]: + if len(res) > 0: + res += "\n" + res += str(op) + return res + + def __getstate__(self): + # TODO(VitalyFedyunin): Currently can't pickle (why?) + self.ctx["schema_df"] = None + for var in self.ctx["variables"]: + var.calculated_value = None + state = {} + for item in self.__dict__: + state[item] = getattr(self, item) + return state + + def __setstate__(self, state): + for k, v in state.items(): + setattr(self, k, v) + + def __getattr__(self, attrname): + if attrname == "kwarg" or attrname == "kwargs": + raise RuntimeError("no kwargs!") + if attrname == "__deepcopy__": + raise AttributeError + result = CaptureGetAttr(self, attrname, ctx=self.ctx) + return result + + def __getitem__(self, key): + return CaptureGetItem(self, key, ctx=self.ctx) + + def __setitem__(self, key, value) -> None: + self.ctx["operations"].append(CaptureSetItem(self, key, value, ctx=self.ctx)) + + def __add__(self, add_val): + res = CaptureAdd(self, add_val, ctx=self.ctx) + var = CaptureVariable(res, ctx=self.ctx) + self.ctx["operations"].append( + CaptureVariableAssign(variable=var, value=res, ctx=self.ctx) + ) + return var + + def __sub__(self, add_val): + res = CaptureSub(self, add_val, ctx=self.ctx) + var = CaptureVariable(res, ctx=self.ctx) + self.ctx["operations"].append( + CaptureVariableAssign(variable=var, value=res, ctx=self.ctx) + ) + return var + + def __mul__(self, add_val): + res = CaptureMul(self, add_val, ctx=self.ctx) + var = CaptureVariable(res, ctx=self.ctx) + t = CaptureVariableAssign(variable=var, value=res, ctx=self.ctx) + self.ctx["operations"].append(t) + return var + + def _is_context_empty(self): + return len(self.ctx["operations"]) == 0 and len(self.ctx["variables"]) == 0 + + def apply_ops_2(self, dataframe) -> None: + # TODO(VitalyFedyunin): Make this calculation thread safe (as currently it updates pointer) + self.ctx["variables"][0].calculated_value = dataframe + for op in self.ctx["operations"]: + op.execute() + + @property + def columns(self): + self.apply_ops_2(self.ctx["schema_df"]) + value = self.execute() + return value.columns + + # TODO(VitalyFedyunin): Add tests + # TODO(VitalyFedyunin): Need to join context if one of them are empty because we used capture + + def __call__(self, *args, **kwargs): + # TODO: Check if args or kwargs have more than one different context + if self._is_context_empty(): + # TODO: Allow CaptureA to take context from mock + for arg in args: + if isinstance(arg, Capture) and not arg._is_context_empty(): + self.ctx = arg.ctx + break + if self._is_context_empty(): + for k, v in kwargs.items(): + if isinstance(k, Capture) and not k._is_context_empty(): + self.ctx = k.ctx + break + if isinstance(v, Capture) and not v._is_context_empty(): + self.ctx = v.ctx + break + + res = CaptureCall(self, ctx=self.ctx, args=args, kwargs=kwargs) + var = CaptureVariable(None, ctx=self.ctx) + t = CaptureVariableAssign(ctx=self.ctx, variable=var, value=res) + self.ctx["operations"].append(t) + return var + + +class CaptureF(Capture): + def __init__(self, ctx=None, **kwargs) -> None: + super().__init__() + if ctx is None: + self.ctx = {"operations": [], "variables": []} + else: + self.ctx = ctx + self.kwargs = kwargs + + +class CaptureA(CaptureF): + def __str__(self) -> str: + return f"{self.kwargs['name']}" + + def execute(self): + value = self.kwargs["real_attribute"] + return value + + +class CaptureLikeMock: + def __init__(self, name) -> None: + import unittest.mock as mock + + # TODO(VitalyFedyunin): Do not use private function here, copy own implementation instead. + get_target, attribute = mock._get_target(name) # type: ignore[attr-defined] + self.get_target = get_target + self.attribute = attribute + self.name = name + + def __enter__(self): + self.save = getattr(self.get_target(), self.attribute) + capt = CaptureA(name=self.name, real_attribute=self.save) + setattr(self.get_target(), self.attribute, capt) + + def __exit__(self, *exc_info): + setattr(self.get_target(), self.attribute, self.save) + + +class CaptureCall(Capture): + def __init__(self, callable, ctx=None, **kwargs) -> None: + super().__init__() + if ctx is None: + self.ctx = {"operations": [], "variables": []} + else: + self.ctx = ctx + self.kwargs = kwargs + self.callable = callable + + def __str__(self) -> str: + return "{callable}({args},{kwargs})".format( + callable=self.callable, **self.kwargs + ) + + def execute(self): + # TODO: VitalyFedyunin execute kwargs and maybe nested structures + executed_args = [] + for arg in self.kwargs["args"]: + if isinstance(arg, Capture): + executed_args.append(arg.execute()) + else: + executed_args.append(arg) + left = get_val(self.callable) + return left(*executed_args, **self.kwargs["kwargs"]) + + +class CaptureVariableAssign(CaptureF): + def __str__(self) -> str: + variable = self.kwargs["variable"] + value = self.kwargs["value"] + return f"{variable} = {value}" + + def execute(self) -> None: + self.kwargs["variable"].calculated_value = self.kwargs["value"].execute() + + +class CaptureVariable(Capture): + # TODO(VitalyFedyunin): This should be atomic and thread safe + names_idx = 0 + + def __init__(self, value, ctx) -> None: + super().__init__() + if CaptureControl.disabled: + raise RuntimeError("Attempting to create capture variable with capture off") + self.ctx = ctx + self.value = value + self.name = f"var_{CaptureVariable.names_idx}" + CaptureVariable.names_idx += 1 + self.ctx["variables"].append(self) + + def __str__(self) -> str: + return self.name + + def execute(self): + return self.calculated_value + + def apply_ops(self, dataframe): + # TODO(VitalyFedyunin): Make this calculation thread safe (as currently it updates pointer) + self.ctx["variables"][0].calculated_value = dataframe + for op in self.ctx["operations"]: + op.execute() + return self.calculated_value + + +class CaptureGetItem(Capture): + def __init__(self, left, key, ctx) -> None: + super().__init__() + self.ctx = ctx + self.left = left + self.key = key + + def __str__(self) -> str: + return f"{self.left}[{get_val(self.key)}]" + + def execute(self): + left = self.left.execute() + return left[self.key] + + +class CaptureSetItem(Capture): + def __init__(self, left, key, value, ctx) -> None: + super().__init__() + self.ctx = ctx + self.left = left + self.key = key + self.value = value + + def __str__(self) -> str: + return f"{self.left}[{get_val(self.key)}] = {self.value}" + + def execute(self) -> None: + left = self.left.execute() + value = self.value.execute() + left[self.key] = value + + +class CaptureAdd(Capture): + def __init__(self, left, right, ctx) -> None: + super().__init__() + self.ctx = ctx + self.left = left + self.right = right + + def __str__(self) -> str: + return f"{self.left} + {self.right}" + + def execute(self): + return get_val(self.left) + get_val(self.right) + + +class CaptureMul(Capture): + def __init__(self, left, right, ctx) -> None: + super().__init__() + self.ctx = ctx + self.left = left + self.right = right + + def __str__(self) -> str: + return f"{self.left} * {self.right}" + + def execute(self): + return get_val(self.left) * get_val(self.right) + + +class CaptureSub(Capture): + def __init__(self, left, right, ctx) -> None: + super().__init__() + self.ctx = ctx + self.left = left + self.right = right + + def __str__(self) -> str: + return f"{self.left} - {self.right}" + + def execute(self): + return get_val(self.left) - get_val(self.right) + + +class CaptureGetAttr(Capture): + def __init__(self, src, name, ctx) -> None: + super().__init__() + self.ctx = ctx + self.src = src + self.name = name + + def __str__(self) -> str: + return f"{self.src}.{self.name}" + + def execute(self): + val = get_val(self.src) + return getattr(val, self.name) + + +def get_val(capture): + if isinstance(capture, Capture): + return capture.execute() + elif isinstance(capture, str): + return f'"{capture}"' + else: + return capture + + +class CaptureInitial(CaptureVariable): + def __init__(self, schema_df=None) -> None: + # pyrefly: ignore [bad-assignment] + new_ctx: dict[str, list[Any]] = { + "operations": [], + "variables": [], + "schema_df": schema_df, + } + super().__init__(None, new_ctx) + self.name = f"input_{self.name}" + + +class CaptureDataFrame(CaptureInitial): + pass + + +class CaptureDataFrameWithDataPipeOps(CaptureDataFrame): + def as_datapipe(self): + return DataFrameTracedOps(self.ctx["variables"][0].source_datapipe, self) + + def raw_iterator(self): + return self.as_datapipe().__iter__() + + def __iter__(self): + return iter(self._dataframes_as_tuples()) + + def batch(self, batch_size=10, drop_last: bool = False, wrapper_class=DataChunkDF): + dp = self._dataframes_per_row()._dataframes_concat(batch_size) + dp = dp.as_datapipe().batch(1, drop_last=drop_last, wrapper_class=wrapper_class) + dp._dp_contains_dataframe = True + return dp + + def groupby( + self, + group_key_fn, + *, + buffer_size=10000, + group_size=None, + guaranteed_group_size=None, + drop_remaining=False, + ): + dp = self._dataframes_per_row() + dp = dp.as_datapipe().groupby( + group_key_fn, + buffer_size=buffer_size, + group_size=group_size, + guaranteed_group_size=guaranteed_group_size, + drop_remaining=drop_remaining, + ) + return dp + + def shuffle(self, *args, **kwargs): + return self._dataframes_shuffle(*args, **kwargs) + + def filter(self, *args, **kwargs): + return self._dataframes_filter(*args, **kwargs) + + def collate(self, *args, **kwargs) -> NoReturn: + raise RuntimeError("Can't collate unbatched DataFrames stream") + + def __getattr__(self, attrname): # ? + if attrname in UNIMPLEMENTED_ATTR: + raise AttributeError("Attempting to get ", attrname) + if attrname in DATAPIPES_OPS: + return (self.as_datapipe()).__getattr__(attrname) + return super().__getattr__(attrname) + + +@functional_datapipe("trace_as_dataframe") +class DataFrameTracer(CaptureDataFrameWithDataPipeOps, IterDataPipe): # type: ignore[misc] + source_datapipe: Any | None = None + + # TODO(VitalyFedyunin): Must implement all special functions of datapipes + + def set_shuffle_settings(self, *args, **kwargs) -> None: + pass + + def is_shardable(self) -> bool: + return False + + def __init__(self, source_datapipe, schema_df=None) -> None: + self.source_datapipe = source_datapipe + if schema_df is None: + schema_df = next(iter(self.source_datapipe)) + super().__init__(schema_df=schema_df) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/datapipes.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/datapipes.py new file mode 100644 index 0000000000000000000000000000000000000000..2ea8b6fe7b836e8fe8ac6d543e4598b72a3ebb02 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/datapipes.py @@ -0,0 +1,138 @@ +# mypy: allow-untyped-defs +import random +from typing import Any + +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.dataframe import dataframe_wrapper as df_wrapper +from torch.utils.data.datapipes.datapipe import DFIterDataPipe, IterDataPipe + + +__all__ = [ + "ConcatDataFramesPipe", + "DataFramesAsTuplesPipe", + "ExampleAggregateAsDataFrames", + "FilterDataFramesPipe", + "PerRowDataFramesPipe", + "ShuffleDataFramesPipe", +] + + +@functional_datapipe("_dataframes_as_tuples") +class DataFramesAsTuplesPipe(IterDataPipe): + def __init__(self, source_datapipe) -> None: + super().__init__() + self.source_datapipe = source_datapipe + + def __iter__(self): + for df in self.source_datapipe: + # for record in df.to_records(index=False): + yield from df_wrapper.iterate(df) + + +@functional_datapipe("_dataframes_per_row", enable_df_api_tracing=True) +class PerRowDataFramesPipe(DFIterDataPipe): + def __init__(self, source_datapipe) -> None: + self.source_datapipe = source_datapipe + + def __iter__(self): + for df in self.source_datapipe: + # TODO(VitalyFedyunin): Replacing with TorchArrow only API, as we are dropping pandas as followup + for i in range(len(df)): + yield df[i : i + 1] + + +@functional_datapipe("_dataframes_concat", enable_df_api_tracing=True) +class ConcatDataFramesPipe(DFIterDataPipe): + def __init__(self, source_datapipe, batch=3) -> None: + self.source_datapipe = source_datapipe + self.n_batch = batch + + def __iter__(self): + buffer = [] + for df in self.source_datapipe: + buffer.append(df) + if len(buffer) == self.n_batch: + yield df_wrapper.concat(buffer) + buffer = [] + if buffer: + yield df_wrapper.concat(buffer) + + +@functional_datapipe("_dataframes_shuffle", enable_df_api_tracing=True) +class ShuffleDataFramesPipe(DFIterDataPipe): + def __init__(self, source_datapipe) -> None: + self.source_datapipe = source_datapipe + + def __iter__(self): + size = None + all_buffer: list[Any] = [] + for df in self.source_datapipe: + if size is None: + size = df_wrapper.get_len(df) + all_buffer.extend( + df_wrapper.get_item(df, i) for i in range(df_wrapper.get_len(df)) + ) + random.shuffle(all_buffer) + buffer = [] + for df in all_buffer: + buffer.append(df) + if len(buffer) == size: + yield df_wrapper.concat(buffer) + buffer = [] + if buffer: + yield df_wrapper.concat(buffer) + + +@functional_datapipe("_dataframes_filter", enable_df_api_tracing=True) +class FilterDataFramesPipe(DFIterDataPipe): + def __init__(self, source_datapipe, filter_fn) -> None: + self.source_datapipe = source_datapipe + self.filter_fn = filter_fn + + def __iter__(self): + size = None + all_buffer = [] + filter_res = [] + # pyrefly: ignore [bad-assignment] + for df in self.source_datapipe: + if size is None: + size = len(df.index) + for i in range(len(df.index)): + all_buffer.append(df[i : i + 1]) + filter_res.append(self.filter_fn(df.iloc[i])) + + buffer = [] + for df, res in zip(all_buffer, filter_res, strict=True): + if res: + buffer.append(df) + if len(buffer) == size: + yield df_wrapper.concat(buffer) + buffer = [] + if buffer: + yield df_wrapper.concat(buffer) + + +@functional_datapipe("_to_dataframes_pipe", enable_df_api_tracing=True) +class ExampleAggregateAsDataFrames(DFIterDataPipe): + def __init__(self, source_datapipe, dataframe_size=10, columns=None) -> None: + self.source_datapipe = source_datapipe + self.columns = columns + self.dataframe_size = dataframe_size + + def _as_list(self, item): + try: + return list(item) + except ( + Exception + ): # TODO(VitalyFedyunin): Replace with better iterable exception + return [item] + + def __iter__(self): + aggregate = [] + for item in self.source_datapipe: + aggregate.append(self._as_list(item)) + if len(aggregate) == self.dataframe_size: + yield df_wrapper.create_dataframe(aggregate, columns=self.columns) + aggregate = [] + if len(aggregate) > 0: + yield df_wrapper.create_dataframe(aggregate, columns=self.columns) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/structures.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/structures.py new file mode 100644 index 0000000000000000000000000000000000000000..26b4c33db03cc584f223444c07730ef67f4495e7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/dataframe/structures.py @@ -0,0 +1,22 @@ +from collections.abc import Iterator +from typing import Any + +from torch.utils.data.datapipes.dataframe import dataframe_wrapper as df_wrapper +from torch.utils.data.datapipes.datapipe import DataChunk + + +__all__ = ["DataChunkDF"] + + +class DataChunkDF(DataChunk): + """DataChunkDF iterating over individual items inside of DataFrame containers, to access DataFrames user `raw_iterator`.""" + + def __iter__(self) -> Iterator[Any]: + for df in self.items: + yield from df_wrapper.iterate(df) + + def __len__(self) -> int: + total_len = 0 + for df in self.items: + total_len += df_wrapper.get_len(df) + return total_len diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/datapipe.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/datapipe.py new file mode 100644 index 0000000000000000000000000000000000000000..51c1689008530b1ec4e78c9c921fd9aa6629ecfb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/datapipe.py @@ -0,0 +1,427 @@ +import functools +import pickle +from collections.abc import Callable, Iterable, Iterator +from typing import TypeVar + +from torch.utils._import_utils import import_dill +from torch.utils.data.datapipes._hook_iterator import _SnapshotState +from torch.utils.data.datapipes._typing import _DataPipeMeta, _IterDataPipeMeta +from torch.utils.data.datapipes.utils.common import ( + _deprecation_warning, + _iter_deprecated_functional_names, + _map_deprecated_functional_names, +) +from torch.utils.data.dataset import Dataset, IterableDataset + + +dill = import_dill() +HAS_DILL = dill is not None + +__all__ = [ + "DataChunk", + "DFIterDataPipe", + "IterDataPipe", + "MapDataPipe", +] + + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) + +UNTRACABLE_DATAFRAME_PIPES = [ + "batch", # As it returns DataChunks + "groupby", # As it returns DataChunks + "_dataframes_as_tuples", # As it unpacks DF + "trace_as_dataframe", # As it used to mark DF for tracing +] + + +class DataChunk(list[_T]): + def __init__(self, items: Iterable[_T]) -> None: + items = list(items) + super().__init__(items) + self.items = items + + def as_str(self, indent: str = "") -> str: + return indent + "[" + ", ".join(str(i) for i in iter(self)) + "]" + + def __iter__(self) -> Iterator[_T]: + yield from super().__iter__() + + def raw_iterator(self) -> Iterator[_T]: + yield from self.items + + +class IterDataPipe(IterableDataset[_T_co], metaclass=_IterDataPipeMeta): + r""" + Iterable-style DataPipe. + + All DataPipes that represent an iterable of data samples should subclass this. + This style of DataPipes is particularly useful when data come from a stream, or + when the number of samples is too large to fit them all in memory. ``IterDataPipe`` is lazily initialized and its + elements are computed only when ``next()`` is called on the iterator of an ``IterDataPipe``. + + All subclasses should overwrite :meth:`__iter__`, which would return an + iterator of samples in this DataPipe. Calling ``__iter__`` of an ``IterDataPipe`` automatically invokes its + method ``reset()``, which by default performs no operation. When writing a custom ``IterDataPipe``, users should + override ``reset()`` if necessary. The common usages include resetting buffers, pointers, + and various state variables within the custom ``IterDataPipe``. + + Note: + Only `one` iterator can be valid for each ``IterDataPipe`` at a time, + and the creation a second iterator will invalidate the first one. This constraint is necessary because + some ``IterDataPipe`` have internal buffers, whose states can become invalid if there are multiple iterators. + The code example below presents details on how this constraint looks in practice. + If you have any feedback related to this constraint, please see `GitHub IterDataPipe Single Iterator Issue`_. + + These DataPipes can be invoked in two ways, using the class constructor or applying their + functional form onto an existing ``IterDataPipe`` (recommended, available to most but not all DataPipes). + You can chain multiple `IterDataPipe` together to form a pipeline that will perform multiple + operations in succession. + + .. _GitHub IterDataPipe Single Iterator Issue: + https://github.com/pytorch/data/issues/45 + + Note: + When a subclass is used with :class:`~torch.utils.data.DataLoader`, each + item in the DataPipe will be yielded from the :class:`~torch.utils.data.DataLoader` + iterator. When :attr:`num_workers > 0`, each worker process will have a + different copy of the DataPipe object, so it is often desired to configure + each copy independently to avoid having duplicate data returned from the + workers. :func:`~torch.utils.data.get_worker_info`, when called in a worker + process, returns information about the worker. It can be used in either the + dataset's :meth:`__iter__` method or the :class:`~torch.utils.data.DataLoader` 's + :attr:`worker_init_fn` option to modify each copy's behavior. + + Examples: + General Usage: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper, Mapper + >>> dp = IterableWrapper(range(10)) + >>> map_dp_1 = Mapper(dp, lambda x: x + 1) # Using class constructor + >>> map_dp_2 = dp.map( + ... lambda x: x + 1 + ... ) # Using functional form (recommended) + >>> list(map_dp_1) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + >>> list(map_dp_2) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + >>> filter_dp = map_dp_1.filter(lambda x: x % 2 == 0) + >>> list(filter_dp) + [2, 4, 6, 8, 10] + Single Iterator Constraint Example: + >>> from torchdata.datapipes.iter import IterableWrapper, Mapper + >>> source_dp = IterableWrapper(range(10)) + >>> it1 = iter(source_dp) + >>> list(it1) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + >>> it1 = iter(source_dp) + >>> it2 = iter( + ... source_dp + ... ) # The creation of a new iterator invalidates `it1` + >>> next(it2) + 0 + >>> next(it1) # Further usage of `it1` will raise a `RunTimeError` + """ + + functions: dict[str, Callable] = {} + reduce_ex_hook: Callable | None = None + getstate_hook: Callable | None = None + str_hook: Callable | None = None + repr_hook: Callable | None = None + _valid_iterator_id: int | None = None + _number_of_samples_yielded: int = 0 + _snapshot_state: _SnapshotState = _SnapshotState.NotStarted + _fast_forward_iterator: Iterator | None = None + + def __iter__(self) -> Iterator[_T_co]: + # pyrefly: ignore [bad-return] + return self + + def __getattr__(self, attribute_name): + if attribute_name in IterDataPipe.functions: + if attribute_name in _iter_deprecated_functional_names: + kwargs = _iter_deprecated_functional_names[attribute_name] + _deprecation_warning(**kwargs) + f = IterDataPipe.functions[attribute_name] + function = functools.partial(f, self) + functools.update_wrapper(wrapper=function, wrapped=f, assigned=("__doc__",)) + return function + else: + raise AttributeError( + f"'{self.__class__.__name__}' object has no attribute '{attribute_name}" + ) + + @classmethod + def register_function(cls, function_name, function) -> None: + cls.functions[function_name] = function + + @classmethod + def register_datapipe_as_function( + cls, function_name, cls_to_register, enable_df_api_tracing=False + ) -> None: + if function_name in cls.functions: + raise Exception( # noqa: TRY002 + f"Unable to add DataPipe function name {function_name} as it is already taken" + ) + + def class_function(cls, enable_df_api_tracing, source_dp, *args, **kwargs): + result_pipe = cls(source_dp, *args, **kwargs) + if isinstance(result_pipe, IterDataPipe): + if enable_df_api_tracing or isinstance(source_dp, DFIterDataPipe): + if function_name not in UNTRACABLE_DATAFRAME_PIPES: + result_pipe = result_pipe.trace_as_dataframe() + + return result_pipe + + function = functools.partial( + class_function, cls_to_register, enable_df_api_tracing + ) + functools.update_wrapper( + wrapper=function, wrapped=cls_to_register, assigned=("__doc__",) + ) + cls.functions[function_name] = function + + def __getstate__(self): + """ + Serialize `lambda` functions when `dill` is available. + + If this doesn't cover your custom DataPipe's use case, consider writing custom methods for + `__getstate__` and `__setstate__`, or use `pickle.dumps` for serialization. + """ + state = self.__dict__ + if IterDataPipe.getstate_hook is not None: + return IterDataPipe.getstate_hook(state) + return state + + def __reduce_ex__(self, *args, **kwargs): + if IterDataPipe.reduce_ex_hook is not None: + try: + return IterDataPipe.reduce_ex_hook(self) + except NotImplementedError: + pass + return super().__reduce_ex__(*args, **kwargs) + + @classmethod + def set_getstate_hook(cls, hook_fn) -> None: + if IterDataPipe.getstate_hook is not None and hook_fn is not None: + raise RuntimeError("Attempt to override existing getstate_hook") + IterDataPipe.getstate_hook = hook_fn + + @classmethod + def set_reduce_ex_hook(cls, hook_fn) -> None: + if IterDataPipe.reduce_ex_hook is not None and hook_fn is not None: + raise RuntimeError("Attempt to override existing reduce_ex_hook") + IterDataPipe.reduce_ex_hook = hook_fn + + def __repr__(self) -> str: + if self.repr_hook is not None: + return self.repr_hook(self) + # Instead of showing , return the class name + return str(self.__class__.__qualname__) + + def __str__(self) -> str: + if self.str_hook is not None: + return self.str_hook(self) + # Instead of showing , return the class name + return str(self.__class__.__qualname__) + + def __dir__(self): + # for auto-completion in a REPL (e.g. Jupyter notebook) + return list(super().__dir__()) + list(self.functions.keys()) + + def reset(self) -> None: + r""" + Reset the `IterDataPipe` to the initial state. + + By default, no-op. For subclasses of `IterDataPipe`, depending on their functionalities, + they may want to override this method with implementations that + may clear the buffers and reset pointers of the DataPipe. + The `reset` method is always called when `__iter__` is called as part of `hook_iterator`. + """ + + +class DFIterDataPipe(IterDataPipe): + def _is_dfpipe(self) -> bool: + return True + + +class MapDataPipe(Dataset[_T_co], metaclass=_DataPipeMeta): + r""" + Map-style DataPipe. + + All datasets that represent a map from keys to data samples should subclass this. + Subclasses should overwrite :meth:`__getitem__`, supporting fetching a + data sample for a given, unique key. Subclasses can also optionally overwrite + :meth:`__len__`, which is expected to return the size of the dataset by many + :class:`~torch.utils.data.Sampler` implementations and the default options + of :class:`~torch.utils.data.DataLoader`. + + These DataPipes can be invoked in two ways, using the class constructor or applying their + functional form onto an existing `MapDataPipe` (recommend, available to most but not all DataPipes). + + Note: + :class:`~torch.utils.data.DataLoader` by default constructs an index + sampler that yields integral indices. To make it work with a map-style + DataPipe with non-integral indices/keys, a custom sampler must be provided. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper, Mapper + >>> dp = SequenceWrapper(range(10)) + >>> map_dp_1 = dp.map(lambda x: x + 1) # Using functional form (recommended) + >>> list(map_dp_1) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + >>> map_dp_2 = Mapper(dp, lambda x: x + 1) # Using class constructor + >>> list(map_dp_2) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + >>> batch_dp = map_dp_1.batch(batch_size=2) + >>> list(batch_dp) + [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] + """ + + functions: dict[str, Callable] = {} + reduce_ex_hook: Callable | None = None + getstate_hook: Callable | None = None + str_hook: Callable | None = None + repr_hook: Callable | None = None + + def __getattr__(self, attribute_name): + if attribute_name in MapDataPipe.functions: + if attribute_name in _map_deprecated_functional_names: + kwargs = _map_deprecated_functional_names[attribute_name] + _deprecation_warning(**kwargs) + f = MapDataPipe.functions[attribute_name] + function = functools.partial(f, self) + functools.update_wrapper(wrapper=function, wrapped=f, assigned=("__doc__",)) + return function + else: + raise AttributeError( + f"'{self.__class__.__name__}' object has no attribute '{attribute_name}" + ) + + @classmethod + def register_function(cls, function_name, function) -> None: + cls.functions[function_name] = function + + @classmethod + def register_datapipe_as_function(cls, function_name, cls_to_register) -> None: + if function_name in cls.functions: + raise Exception( # noqa: TRY002 + f"Unable to add DataPipe function name {function_name} as it is already taken" + ) + + def class_function(cls, source_dp, *args, **kwargs): + result_pipe = cls(source_dp, *args, **kwargs) + return result_pipe + + function = functools.partial(class_function, cls_to_register) + functools.update_wrapper( + wrapper=function, wrapped=cls_to_register, assigned=("__doc__",) + ) + cls.functions[function_name] = function + + def __getstate__(self): + """ + Serialize `lambda` functions when `dill` is available. + + If this doesn't cover your custom DataPipe's use case, consider writing custom methods for + `__getstate__` and `__setstate__`, or use `pickle.dumps` for serialization. + """ + state = self.__dict__ + if MapDataPipe.getstate_hook is not None: + return MapDataPipe.getstate_hook(state) + return state + + def __reduce_ex__(self, *args, **kwargs): + if MapDataPipe.reduce_ex_hook is not None: + try: + return MapDataPipe.reduce_ex_hook(self) + except NotImplementedError: + pass + return super().__reduce_ex__(*args, **kwargs) + + @classmethod + def set_getstate_hook(cls, hook_fn) -> None: + if MapDataPipe.getstate_hook is not None and hook_fn is not None: + raise RuntimeError("Attempt to override existing getstate_hook") + MapDataPipe.getstate_hook = hook_fn + + @classmethod + def set_reduce_ex_hook(cls, hook_fn) -> None: + if MapDataPipe.reduce_ex_hook is not None and hook_fn is not None: + raise RuntimeError("Attempt to override existing reduce_ex_hook") + MapDataPipe.reduce_ex_hook = hook_fn + + def __repr__(self) -> str: + if self.repr_hook is not None: + return self.repr_hook(self) + # Instead of showing , return the class name + return str(self.__class__.__qualname__) + + def __str__(self) -> str: + if self.str_hook is not None: + return self.str_hook(self) + # Instead of showing , return the class name + return str(self.__class__.__qualname__) + + def __dir__(self): + # for auto-completion in a REPL (e.g. Jupyter notebook) + return list(super().__dir__()) + list(self.functions.keys()) + + +class _DataPipeSerializationWrapper: + def __init__(self, datapipe) -> None: + self._datapipe = datapipe + + def __getstate__(self): + use_dill = False + try: + value = pickle.dumps(self._datapipe) + except Exception: + if HAS_DILL: + # pyrefly: ignore [missing-attribute] + value = dill.dumps(self._datapipe) + use_dill = True + else: + raise + return (value, use_dill) + + def __setstate__(self, state): + value, use_dill = state + if use_dill: + # pyrefly: ignore [missing-attribute] + self._datapipe = dill.loads(value) + else: + self._datapipe = pickle.loads(value) + + def __len__(self) -> int: + try: + return len(self._datapipe) + except Exception as e: + raise TypeError( + f"{type(self).__name__} instance doesn't have valid length" + ) from e + + +class _IterDataPipeSerializationWrapper(_DataPipeSerializationWrapper, IterDataPipe): + def __init__(self, datapipe: IterDataPipe[_T_co]) -> None: + super().__init__(datapipe) + # pyrefly: ignore [invalid-type-var] + self._datapipe_iter: Iterator[_T_co] | None = None + + def __iter__(self) -> "_IterDataPipeSerializationWrapper": + self._datapipe_iter = iter(self._datapipe) + return self + + def __next__(self) -> _T_co: # type: ignore[type-var] + if self._datapipe_iter is None: + raise AssertionError( + "Iterator has not been initialized; call __iter__() before __next__()" + ) + return next(self._datapipe_iter) + + +class _MapDataPipeSerializationWrapper(_DataPipeSerializationWrapper, MapDataPipe): + def __getitem__(self, idx): + return self._datapipe[idx] diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/datapipe.pyi b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/datapipe.pyi new file mode 100644 index 0000000000000000000000000000000000000000..222c5d3535f228faf77cbceeadae2a7bc6899dbd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/datapipe.pyi @@ -0,0 +1,746 @@ +# @generated by torch/utils/data/datapipes/gen_pyi.py from datapipe.pyi.in +# mypy: allow-untyped-defs +# This base template ("datapipe.pyi.in") is generated from mypy stubgen with minimal editing for code injection +# The output file will be "datapipe.pyi". This is executed as part of torch/CMakeLists.txt +# Note that, for mypy, .pyi file takes precedent over .py file, such that we must define the interface for other +# classes/objects here, even though we are not injecting extra code into them at the moment. + +from collections.abc import Callable, Iterable, Iterator +from typing import Any, Literal, TypeVar + +from torch.utils.data import Dataset, default_collate, IterableDataset +from torch.utils.data.datapipes._hook_iterator import _SnapshotState +from torch.utils.data.datapipes._typing import _DataPipeMeta, _IterDataPipeMeta + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +UNTRACABLE_DATAFRAME_PIPES: Any + +class DataChunk(list[_T]): + items: list[_T] + def __init__(self, items: Iterable[_T]) -> None: ... + def as_str(self, indent: str = "") -> str: ... + def __iter__(self) -> Iterator[_T]: ... + def raw_iterator(self) -> Iterator[_T]: ... + +class MapDataPipe(Dataset[_T_co], metaclass=_DataPipeMeta): + functions: dict[str, Callable] = ... + reduce_ex_hook: Callable | None = ... + getstate_hook: Callable | None = ... + str_hook: Callable | None = ... + repr_hook: Callable | None = ... + def __getattr__(self, attribute_name: Any): ... + @classmethod + def register_function(cls, function_name: Any, function: Any) -> None: ... + @classmethod + def register_datapipe_as_function( + cls, + function_name: Any, + cls_to_register: Any, + ): ... + def __getstate__(self): ... + def __reduce_ex__(self, *args: Any, **kwargs: Any): ... + @classmethod + def set_getstate_hook(cls, hook_fn: Any) -> None: ... + @classmethod + def set_reduce_ex_hook(cls, hook_fn: Any) -> None: ... + # Functional form of 'BatcherMapDataPipe' + def batch( + self, + batch_size: int, + drop_last: bool = False, + wrapper_class: type[DataChunk] = DataChunk, + ) -> MapDataPipe: + r""" + Create mini-batches of data (functional name: ``batch``). + + An outer dimension will be added as ``batch_size`` if ``drop_last`` is set to ``True``, + or ``length % batch_size`` for the last batch if ``drop_last`` is set to ``False``. + + Args: + datapipe: Iterable DataPipe being batched + batch_size: The size of each batch + drop_last: Option to drop the last batch if it's not full + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper + >>> dp = SequenceWrapper(range(10)) + >>> batch_dp = dp.batch(batch_size=2) + >>> list(batch_dp) + [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]] + """ + # Functional form of 'ConcaterMapDataPipe' + def concat(self, *datapipes: MapDataPipe) -> MapDataPipe: + r""" + Concatenate multiple Map DataPipes (functional name: ``concat``). + + The new index is the cumulative sum of source DataPipes. + For example, if there are 2 source DataPipes both with length 5, + index 0 to 4 of the resulting `ConcatMapDataPipe` would refer to + elements of the first DataPipe, and 5 to 9 would refer to elements + of the second DataPipe. + + Args: + datapipes: Map DataPipes being concatenated + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper + >>> dp1 = SequenceWrapper(range(3)) + >>> dp2 = SequenceWrapper(range(3)) + >>> concat_dp = dp1.concat(dp2) + >>> list(concat_dp) + [0, 1, 2, 0, 1, 2] + """ + # Functional form of 'MapperMapDataPipe' + def map(self, fn: Callable = ...) -> MapDataPipe: + r""" + Apply the input function over each item from the source DataPipe (functional name: ``map``). + + The function can be any regular Python function or partial object. Lambda + function is not recommended as it is not supported by pickle. + + Args: + datapipe: Source MapDataPipe + fn: Function being applied to each item + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper, Mapper + >>> def add_one(x): + ... return x + 1 + >>> dp = SequenceWrapper(range(10)) + >>> map_dp_1 = dp.map(add_one) + >>> list(map_dp_1) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + >>> map_dp_2 = Mapper(dp, lambda x: x + 1) + >>> list(map_dp_2) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + """ + # Functional form of 'ShufflerIterDataPipe' + def shuffle(self, *, indices: list | None = None) -> IterDataPipe: + r""" + Shuffle the input MapDataPipe via its indices (functional name: ``shuffle``). + + When it is used with :class:`~torch.utils.data.DataLoader`, the methods to + set up random seed are different based on :attr:`num_workers`. + + For single-process mode (:attr:`num_workers == 0`), the random seed is set before + the :class:`~torch.utils.data.DataLoader` in the main process. For multi-process + mode (:attr:`num_worker > 0`), ``worker_init_fn`` is used to set up a random seed + for each worker process. + + Args: + datapipe: MapDataPipe being shuffled + indices: a list of indices of the MapDataPipe. If not provided, we assume it uses 0-based indexing + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper + >>> dp = SequenceWrapper(range(10)) + >>> shuffle_dp = dp.shuffle().set_seed(0) + >>> list(shuffle_dp) + [7, 8, 1, 5, 3, 4, 2, 0, 9, 6] + >>> list(shuffle_dp) + [6, 1, 9, 5, 2, 4, 7, 3, 8, 0] + >>> # Reset seed for Shuffler + >>> shuffle_dp = shuffle_dp.set_seed(0) + >>> list(shuffle_dp) + [7, 8, 1, 5, 3, 4, 2, 0, 9, 6] + + Note: + Even though this ``shuffle`` operation takes a ``MapDataPipe`` as the input, it would return an + ``IterDataPipe`` rather than a ``MapDataPipe``, because ``MapDataPipe`` should be non-sensitive to + the order of data order for the sake of random reads, but ``IterDataPipe`` depends on the order + of data during data-processing. + """ + # Functional form of 'ZipperMapDataPipe' + def zip(self, *datapipes: MapDataPipe[_T_co]) -> MapDataPipe: + r""" + Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``). + + This MapDataPipe is out of bounds as soon as the shortest input DataPipe is exhausted. + + Args: + *datapipes: Map DataPipes being aggregated + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper + >>> dp1 = SequenceWrapper(range(3)) + >>> dp2 = SequenceWrapper(range(10, 13)) + >>> zip_dp = dp1.zip(dp2) + >>> list(zip_dp) + [(0, 10), (1, 11), (2, 12)] + """ + +class IterDataPipe(IterableDataset[_T_co], metaclass=_IterDataPipeMeta): + functions: dict[str, Callable] = ... + reduce_ex_hook: Callable | None = ... + getstate_hook: Callable | None = ... + str_hook: Callable | None = ... + repr_hook: Callable | None = ... + _number_of_samples_yielded: int = ... + _snapshot_state: _SnapshotState = _SnapshotState.Iterating # noqa: PYI015 + _fast_forward_iterator: Iterator | None = ... + def __getattr__(self, attribute_name: Any): ... + @classmethod + def register_function(cls, function_name: Any, function: Any) -> None: ... + @classmethod + def register_datapipe_as_function( + cls, + function_name: Any, + cls_to_register: Any, + enable_df_api_tracing: bool = ..., + ): ... + def __getstate__(self): ... + def __reduce_ex__(self, *args: Any, **kwargs: Any): ... + @classmethod + def set_getstate_hook(cls, hook_fn: Any) -> None: ... + @classmethod + def set_reduce_ex_hook(cls, hook_fn: Any) -> None: ... + # Functional form of 'BatcherIterDataPipe' + def batch( + self, + batch_size: int, + drop_last: bool = False, + wrapper_class: type[DataChunk] = DataChunk, + ) -> IterDataPipe: + r""" + Creates mini-batches of data (functional name: ``batch``). + + An outer dimension will be added as ``batch_size`` if ``drop_last`` is set to ``True``, or ``length % batch_size`` for the + last batch if ``drop_last`` is set to ``False``. + + Args: + datapipe: Iterable DataPipe being batched + batch_size: The size of each batch + drop_last: Option to drop the last batch if it's not full + wrapper_class: wrapper to apply onto each batch (type ``List``) before yielding, + defaults to ``DataChunk`` + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp = IterableWrapper(range(10)) + >>> dp = dp.batch(batch_size=3, drop_last=True) + >>> list(dp) + [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + """ + # Functional form of 'CollatorIterDataPipe' + def collate( + self, + conversion: Callable[..., Any]| dict[str | Any, Callable | Any]| None = default_collate, + collate_fn: Callable | None = None, + ) -> IterDataPipe: # fmt: skip + r""" + Collates samples from DataPipe to Tensor(s) by a custom collate function (functional name: ``collate``). + + By default, it uses :func:`torch.utils.data.default_collate`. + + .. note:: + While writing a custom collate function, you can import :func:`torch.utils.data.default_collate` for the + default behavior and `functools.partial` to specify any additional arguments. + + Args: + datapipe: Iterable DataPipe being collated + collate_fn: Customized collate function to collect and combine data or a batch of data. + Default function collates to Tensor(s) based on data type. + + Example: + >>> # xdoctest: +SKIP + >>> # Convert integer data to float Tensor + >>> class MyIterDataPipe(torch.utils.data.IterDataPipe): + ... def __init__(self, start, end): + ... super(MyIterDataPipe).__init__() + ... assert end > start, "this example only works with end >= start" + ... self.start = start + ... self.end = end + ... + ... def __iter__(self): + ... return iter(range(self.start, self.end)) + ... + ... def __len__(self): + ... return self.end - self.start + >>> ds = MyIterDataPipe(start=3, end=7) + >>> print(list(ds)) + [3, 4, 5, 6] + >>> def collate_fn(batch): + ... return torch.tensor(batch, dtype=torch.float) + >>> collated_ds = CollateIterDataPipe(ds, collate_fn=collate_fn) + >>> print(list(collated_ds)) + [tensor(3.), tensor(4.), tensor(5.), tensor(6.)] + """ + # Functional form of 'ConcaterIterDataPipe' + def concat(self, *datapipes: IterDataPipe) -> IterDataPipe: + r""" + Concatenates multiple Iterable DataPipes (functional name: ``concat``). + + The resulting DataPipe will yield all the elements from the first input DataPipe, before yielding from the subsequent ones. + + Args: + datapipes: Iterable DataPipes being concatenated + + Example: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> import random + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp1 = IterableWrapper(range(3)) + >>> dp2 = IterableWrapper(range(5)) + >>> list(dp1.concat(dp2)) + [0, 1, 2, 0, 1, 2, 3, 4] + """ + # Functional form of 'DemultiplexerIterDataPipe' + def demux( + self, + num_instances: int, + classifier_fn: Callable[[_T_co], int | None], + drop_none: bool = False, + buffer_size: int = 1000, + ) -> list[IterDataPipe]: + r""" + Splits the input DataPipe into multiple child DataPipes, using the given classification function (functional name: ``demux``). + + A list of the child DataPipes is returned from this operation. + + Args: + datapipe: Iterable DataPipe being filtered + num_instances: number of instances of the DataPipe to create + classifier_fn: a function that maps values to an integer within the range ``[0, num_instances - 1]`` or ``None`` + drop_none: defaults to ``False``, if ``True``, the function will skip over elements classified as ``None`` + buffer_size: this defines the maximum number of inputs that the buffer can hold across all child + DataPipes while waiting for their values to be yielded. + Defaults to ``1000``. Use ``-1`` for the unlimited buffer. + + Examples: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> from torchdata.datapipes.iter import IterableWrapper + >>> def odd_or_even(n): + ... return n % 2 + >>> source_dp = IterableWrapper(range(5)) + >>> dp1, dp2 = source_dp.demux(num_instances=2, classifier_fn=odd_or_even) + >>> list(dp1) + [0, 2, 4] + >>> list(dp2) + [1, 3] + >>> # It can also filter out any element that gets `None` from the `classifier_fn` + >>> def odd_or_even_no_zero(n): + ... return n % 2 if n != 0 else None + >>> dp1, dp2 = source_dp.demux( + ... num_instances=2, classifier_fn=odd_or_even_no_zero, drop_none=True + ... ) + >>> list(dp1) + [2, 4] + >>> list(dp2) + [1, 3] + """ + # Functional form of 'FilterIterDataPipe' + def filter(self, filter_fn: Callable, input_col=None) -> IterDataPipe: + r""" + Filters out elements from the source datapipe according to input ``filter_fn`` (functional name: ``filter``). + + Args: + datapipe: Iterable DataPipe being filtered + filter_fn: Customized function mapping an element to a boolean. + input_col: Index or indices of data which ``filter_fn`` is applied, such as: + + - ``None`` as default to apply ``filter_fn`` to the data directly. + - Integer(s) is used for list/tuple. + - Key(s) is used for dict. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> def is_even(n): + ... return n % 2 == 0 + >>> dp = IterableWrapper(range(5)) + >>> filter_dp = dp.filter(filter_fn=is_even) + >>> list(filter_dp) + [0, 2, 4] + """ + # Functional form of 'ForkerIterDataPipe' + def fork( + self, + num_instances: int, + buffer_size: int = 1000, + copy: Literal["shallow", "deep"] | None = None, + ) -> list[IterDataPipe]: + r""" + Creates multiple instances of the same Iterable DataPipe (functional name: ``fork``). + + Args: + datapipe: Iterable DataPipe being copied + num_instances: number of instances of the datapipe to create + buffer_size: this restricts how far ahead the leading child DataPipe + can read relative to the slowest child DataPipe. + Defaults to ``1000``. Use ``-1`` for the unlimited buffer. + copy: copy strategy to use for items yielded by each branch. Supported + options are ``None`` for no copying, ``"shallow"`` for shallow object + copies, and ``"deep"`` for deep object copies. Defaults to ``None``. + + Note: + All branches of the forked pipeline return the identical object unless + the copy parameter is supplied. If the object is mutable or contains + mutable objects, changing them in one branch will affect all others. + + Example: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> from torchdata.datapipes.iter import IterableWrapper + >>> source_dp = IterableWrapper(range(5)) + >>> dp1, dp2 = source_dp.fork(num_instances=2) + >>> list(dp1) + [0, 1, 2, 3, 4] + >>> list(dp2) + [0, 1, 2, 3, 4] + """ + # Functional form of 'GrouperIterDataPipe' + def groupby( + self, + group_key_fn: Callable[[_T_co], Any], + *, + keep_key: bool = False, + buffer_size: int = 10000, + group_size: int | None = None, + guaranteed_group_size: int | None = None, + drop_remaining: bool = False, + ) -> IterDataPipe: + r""" + Groups data from IterDataPipe by keys from ``group_key_fn``, yielding a ``DataChunk`` with batch size up to ``group_size``. + + (functional name: ``groupby``). + + The samples are read sequentially from the source ``datapipe``, and a batch of samples belonging to the same group + will be yielded as soon as the size of the batch reaches ``group_size``. When the buffer is full, + the DataPipe will yield the largest batch with the same key, provided that its size is larger + than ``guaranteed_group_size``. If its size is smaller, it will be dropped if ``drop_remaining=True``. + + After iterating through the entirety of source ``datapipe``, everything not dropped due to the buffer capacity + will be yielded from the buffer, even if the group sizes are smaller than ``guaranteed_group_size``. + + Args: + datapipe: Iterable datapipe to be grouped + group_key_fn: Function used to generate group key from the data of the source datapipe + keep_key: Option to yield the matching key along with the items in a tuple, + resulting in `(key, [items])` otherwise returning [items] + buffer_size: The size of buffer for ungrouped data + group_size: The max size of each group, a batch is yielded as soon as it reaches this size + guaranteed_group_size: The guaranteed minimum group size to be yielded in case the buffer is full + drop_remaining: Specifies if the group smaller than ``guaranteed_group_size`` will be dropped from buffer + when the buffer is full + + Example: + >>> import os + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> def group_fn(file): + ... return os.path.basename(file).split(".")[0] + >>> source_dp = IterableWrapper( + ... ["a.png", "b.png", "a.json", "b.json", "a.jpg", "c.json"] + ... ) + >>> dp0 = source_dp.groupby(group_key_fn=group_fn) + >>> list(dp0) + [['a.png', 'a.json', 'a.jpg'], ['b.png', 'b.json'], ['c.json']] + >>> # A group is yielded as soon as its size equals to `group_size` + >>> dp1 = source_dp.groupby(group_key_fn=group_fn, group_size=2) + >>> list(dp1) + [['a.png', 'a.json'], ['b.png', 'b.json'], ['a.jpg'], ['c.json']] + >>> # Scenario where `buffer` is full, and group 'a' needs to be yielded since its size > `guaranteed_group_size` + >>> dp2 = source_dp.groupby( + ... group_key_fn=group_fn, + ... buffer_size=3, + ... group_size=3, + ... guaranteed_group_size=2, + ... ) + >>> list(dp2) + [['a.png', 'a.json'], ['b.png', 'b.json'], ['a.jpg'], ['c.json']] + """ + # Functional form of 'FileListerIterDataPipe' + def list_files( + self, + masks: str | list[str] = "", + *, + recursive: bool = False, + abspath: bool = False, + non_deterministic: bool = False, + length: int = -1, + ) -> IterDataPipe: + r""" + Given path(s) to the root directory, yields file pathname(s) (path + filename) of files within the root directory. + + Multiple root directories can be provided (functional name: ``list_files``). + + Args: + root: Root directory or a sequence of root directories + masks: Unix style filter string or string list for filtering file name(s) + recursive: Whether to return pathname from nested directories or not + abspath: Whether to return relative pathname or absolute pathname + non_deterministic: Whether to return pathname in sorted order or not. + If ``False``, the results yielded from each root directory will be sorted + length: Nominal length of the datapipe + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import FileLister + >>> dp = FileLister(root=".", recursive=True) + >>> list(dp) + ['example.py', './data/data.tar'] + """ + # Functional form of 'MapperIterDataPipe' + def map( + self, + fn: Callable, + input_col=None, + output_col=None, + ) -> IterDataPipe: + r""" + Applies a function over each item from the source DataPipe (functional name: ``map``). + + The function can be any regular Python function or partial object. Lambda + function is not recommended as it is not supported by pickle. + + Args: + datapipe: Source Iterable DataPipe + fn: Function being applied over each item + input_col: Index or indices of data which ``fn`` is applied, such as: + + - ``None`` as default to apply ``fn`` to the data directly. + - Integer(s) is used for list/tuple. + - Key(s) is used for dict. + + output_col: Index of data where result of ``fn`` is placed. ``output_col`` can be specified + only when ``input_col`` is not ``None`` + + - ``None`` as default to replace the index that ``input_col`` specified; For ``input_col`` with + multiple indices, the left-most one is used, and other indices will be removed. + - Integer is used for list/tuple. ``-1`` represents to append result at the end. + - Key is used for dict. New key is acceptable. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper, Mapper + >>> def add_one(x): + ... return x + 1 + >>> dp = IterableWrapper(range(10)) + >>> # Invocation via functional form is preferred + ... map_dp_1 = dp.map(add_one) + >>> list(map_dp_1) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + >>> # We discourage the usage of `lambda` functions as they are not serializable with `pickle` + >>> # Use `functools.partial` or explicitly define the function instead + >>> map_dp_2 = Mapper(dp, lambda x: x + 1) + >>> list(map_dp_2) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + """ + # Functional form of 'MultiplexerIterDataPipe' + def mux(self, *datapipes) -> IterDataPipe: + r""" + Yields one element at a time from each of the input Iterable DataPipes (functional name: ``mux``). + + As in, one element from the 1st input DataPipe, then one element from the 2nd DataPipe in the next iteration, + and so on. It ends when the shortest input DataPipe is exhausted. + + Args: + datapipes: Iterable DataPipes that will take turn to yield their elements, until the shortest DataPipe is exhausted + + Example: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp1, dp2, dp3 = ( + ... IterableWrapper(range(3)), + ... IterableWrapper(range(10, 15)), + ... IterableWrapper(range(20, 25)), + ... ) + >>> list(dp1.mux(dp2, dp3)) + [0, 10, 20, 1, 11, 21, 2, 12, 22] + """ + # Functional form of 'FileOpenerIterDataPipe' + def open_files( + self, + mode: str = "r", + encoding: str | None = None, + length: int = -1, + ) -> IterDataPipe: + r""" + Given pathnames, opens files and yield pathname and file stream in a tuple (functional name: ``open_files``). + + Args: + datapipe: Iterable datapipe that provides pathnames + mode: An optional string that specifies the mode in which + the file is opened by ``open()``. It defaults to ``r``, other options are + ``b`` for reading in binary mode and ``t`` for text mode. + encoding: An optional string that specifies the encoding of the + underlying file. It defaults to ``None`` to match the default encoding of ``open``. + length: Nominal length of the datapipe + + Note: + The opened file handles will be closed by Python's GC periodically. Users can choose + to close them explicitly. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import ( + ... FileLister, + ... FileOpener, + ... StreamReader, + ... ) + >>> dp = FileLister(root=".").filter(lambda fname: fname.endswith(".txt")) + >>> dp = FileOpener(dp) + >>> dp = StreamReader(dp) + >>> list(dp) + [('./abc.txt', 'abc')] + """ + # Functional form of 'StreamReaderIterDataPipe' + def read_from_stream(self, chunk: int | None = None) -> IterDataPipe: + r""" + Given IO streams and their label names, yield bytes with label name as tuple. + + (functional name: ``read_from_stream``). + + Args: + datapipe: Iterable DataPipe provides label/URL and byte stream + chunk: Number of bytes to be read from stream per iteration. + If ``None``, all bytes will be read until the EOF. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper, StreamReader + >>> from io import StringIO + >>> dp = IterableWrapper([("alphabet", StringIO("abcde"))]) + >>> list(StreamReader(dp, chunk=1)) + [('alphabet', 'a'), ('alphabet', 'b'), ('alphabet', 'c'), ('alphabet', 'd'), ('alphabet', 'e')] + """ + # Functional form of 'RoutedDecoderIterDataPipe' + def routed_decode( + self, + *handlers: Callable, + key_fn: Callable = ..., + ) -> IterDataPipe: + r""" + Decodes binary streams from input DataPipe, yields pathname and decoded data in a tuple. + + (functional name: ``routed_decode``) + + Args: + datapipe: Iterable datapipe that provides pathname and binary stream in tuples + handlers: Optional user defined decoder handlers. If ``None``, basic and image decoder + handlers will be set as default. If multiple handlers are provided, the priority + order follows the order of handlers (the first handler has the top priority) + key_fn: Function for decoder to extract key from pathname to dispatch handlers. + Default is set to extract file extension from pathname + + Note: + When ``key_fn`` is specified returning anything other than extension, the default + handler will not work and users need to specify custom handler. Custom handler + could use regex to determine the eligibility to handle data. + """ + # Functional form of 'ShardingFilterIterDataPipe' + def sharding_filter(self, sharding_group_filter=None) -> IterDataPipe: + r""" + Wrapper that allows DataPipe to be sharded (functional name: ``sharding_filter``). + + After ``apply_sharding`` is called, each instance of the DataPipe (on different workers) will have every `n`-th element of the + original DataPipe, where `n` equals to the number of instances. + + Args: + source_datapipe: Iterable DataPipe that will be sharded + """ + # Functional form of 'ShufflerIterDataPipe' + def shuffle( + self, + *, + buffer_size: int = 10000, + unbatch_level: int = 0, + ) -> IterDataPipe: + r""" + Shuffle the input DataPipe with a buffer (functional name: ``shuffle``). + + The buffer with ``buffer_size`` is filled with elements from the datapipe first. Then, + each item will be yielded from the buffer by reservoir sampling via iterator. + + ``buffer_size`` is required to be larger than ``0``. For ``buffer_size == 1``, the + datapipe is not shuffled. In order to fully shuffle all elements from datapipe, + ``buffer_size`` is required to be greater than or equal to the size of datapipe. + + When it is used with :class:`torch.utils.data.DataLoader`, the methods to + set up random seed are different based on :attr:`num_workers`. + + For single-process mode (:attr:`num_workers == 0`), the random seed is set before + the :class:`~torch.utils.data.DataLoader` in the main process. For multi-process + mode (:attr:`num_worker > 0`), `worker_init_fn` is used to set up a random seed + for each worker process. + + Args: + datapipe: The IterDataPipe being shuffled + buffer_size: The buffer size for shuffling (default to ``10000``) + unbatch_level: Specifies if it is necessary to unbatch source data before + applying the shuffle + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp = IterableWrapper(range(10)) + >>> shuffle_dp = dp.shuffle() + >>> list(shuffle_dp) + [0, 4, 1, 6, 3, 2, 9, 5, 7, 8] + """ + # Functional form of 'UnBatcherIterDataPipe' + def unbatch(self, unbatch_level: int = 1) -> IterDataPipe: + r""" + Undoes batching of data (functional name: ``unbatch``). + + In other words, it flattens the data up to the specified level within a batched DataPipe. + + Args: + datapipe: Iterable DataPipe being un-batched + unbatch_level: Defaults to ``1`` (only flattening the top level). If set to ``2``, + it will flatten the top two levels, and ``-1`` will flatten the entire DataPipe. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> source_dp = IterableWrapper([[[0, 1], [2]], [[3, 4], [5]], [[6]]]) + >>> dp1 = source_dp.unbatch() + >>> list(dp1) + [[0, 1], [2], [3, 4], [5], [6]] + >>> dp2 = source_dp.unbatch(unbatch_level=2) + >>> list(dp2) + [0, 1, 2, 3, 4, 5, 6] + """ + # Functional form of 'ZipperIterDataPipe' + def zip(self, *datapipes: IterDataPipe) -> IterDataPipe: + r""" + Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``). + + The output is stopped as soon as the shortest input DataPipe is exhausted. + + Args: + *datapipes: Iterable DataPipes being aggregated + + Example: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp1, dp2, dp3 = ( + ... IterableWrapper(range(5)), + ... IterableWrapper(range(10, 15)), + ... IterableWrapper(range(20, 25)), + ... ) + >>> list(dp1.zip(dp2, dp3)) + [(0, 10, 20), (1, 11, 21), (2, 12, 22), (3, 13, 23), (4, 14, 24)] + """ + +class DFIterDataPipe(IterDataPipe): + def _is_dfpipe(self): ... + def __iter__(self): ... + +class _DataPipeSerializationWrapper: + def __init__(self, datapipe): ... + def __getstate__(self): ... + def __setstate__(self, state): ... + def __len__(self): ... + +class _IterDataPipeSerializationWrapper(_DataPipeSerializationWrapper, IterDataPipe): + def __iter__(self): ... + +class _MapDataPipeSerializationWrapper(_DataPipeSerializationWrapper, MapDataPipe): + def __getitem__(self, idx): ... diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/gen_pyi.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/gen_pyi.py new file mode 100644 index 0000000000000000000000000000000000000000..90f9d80a2e7fef61459d525d32486211415ad3ed --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/gen_pyi.py @@ -0,0 +1,336 @@ +# mypy: allow-untyped-defs +import os +from collections import defaultdict +from pathlib import Path +from typing import Any +from typing_extensions import deprecated + + +try: + from torchgen.api.python import format_function_signature + from torchgen.utils import FileManager +except ImportError: + import sys + + REPO_ROOT = Path(__file__).absolute().parents[4] + sys.path.insert(0, str(REPO_ROOT)) + + from torchgen.api.python import format_function_signature + from torchgen.utils import FileManager + + if len(sys.path) > 0 and sys.path[0] == str(REPO_ROOT): + del sys.path[0] + + +__all__: list[str] = [] # not intended to expose any symbols + + +def __dir__() -> list[str]: + return [] # appease public API test + + +@deprecated( + "`torch.utils.data.datapipes.gen_pyi.materialize_lines` is deprecated and will be removed in the future.", + category=FutureWarning, +) +def materialize_lines(lines: list[str], indentation: int) -> str: + output = "" + new_line_with_indent = "\n" + " " * indentation + for i, line in enumerate(lines): + if i != 0: + output += new_line_with_indent + output += line.replace("\n", new_line_with_indent) + return output + + +@deprecated( + "`torch.utils.data.datapipes.gen_pyi.gen_from_template` is deprecated and will be removed in the future.", + category=FutureWarning, +) +def gen_from_template( + dir: str, + template_name: str, + output_name: str, + replacements: list[tuple[str, Any, int]], +) -> None: + template_path = os.path.join(dir, template_name) + output_path = os.path.join(dir, output_name) + + with open(template_path, encoding="utf-8") as f: + content = f.read() + for placeholder, lines, indentation in replacements: + with open(output_path, "w", encoding="utf-8") as f: + content = content.replace( + placeholder, materialize_lines(lines, indentation) + ) + f.write(content) + + +def find_file_paths(dir_paths: list[str], files_to_exclude: set[str]) -> set[str]: + """ + When given a path to a directory, returns the paths to the relevant files within it. + + This function does NOT recursive traverse to subdirectories. + """ + paths: set[str] = set() + for dir_path in dir_paths: + all_files = os.listdir(dir_path) + python_files = {fname for fname in all_files if ".py" == fname[-3:]} + filter_files = { + fname for fname in python_files if fname not in files_to_exclude + } + paths.update({os.path.join(dir_path, fname) for fname in filter_files}) + return paths + + +def extract_method_name(line: str) -> str: + """Extract method name from decorator in the form of "@functional_datapipe({method_name})".""" + if '("' in line: + start_token, end_token = '("', '")' + elif "('" in line: + start_token, end_token = "('", "')" + else: + raise RuntimeError( + f"Unable to find appropriate method name within line:\n{line}" + ) + start, end = line.find(start_token) + len(start_token), line.find(end_token) + return line[start:end] + + +def extract_class_name(line: str) -> str: + """Extract class name from class definition in the form of "class {CLASS_NAME}({Type}):".""" + start_token = "class " + end_token = "(" + start, end = line.find(start_token) + len(start_token), line.find(end_token) + return line[start:end] + + +def parse_datapipe_file( + file_path: str, +) -> tuple[dict[str, list[str]], dict[str, str], set[str], dict[str, list[str]]]: + """Given a path to file, parses the file and returns a dictionary of method names to function signatures.""" + method_to_signature, method_to_class_name, special_output_type = {}, {}, set() + doc_string_dict = defaultdict(list) + with open(file_path, encoding="utf-8") as f: + open_paren_count = 0 + method_name, class_name, signature = "", "", "" + skip = False + for line in f: + if line.count('"""') % 2 == 1: + skip = not skip + if skip or '"""' in line: # Saving docstrings + doc_string_dict[method_name].append(line) + continue + if "@functional_datapipe" in line: + method_name = extract_method_name(line) + doc_string_dict[method_name] = [] + continue + if method_name and "class " in line: + class_name = extract_class_name(line) + continue + if method_name and ("def __init__(" in line or "def __new__(" in line): + if "def __new__(" in line: + special_output_type.add(method_name) + open_paren_count += 1 + start = line.find("(") + len("(") + line = line[start:] + if open_paren_count > 0: + open_paren_count += line.count("(") + open_paren_count -= line.count(")") + if open_paren_count == 0: + end = line.rfind(")") + signature += line[:end] + method_to_signature[method_name] = process_signature(signature) + method_to_class_name[method_name] = class_name + method_name, class_name, signature = "", "", "" + elif open_paren_count < 0: + raise RuntimeError( + "open parenthesis count < 0. This shouldn't be possible." + ) + else: + signature += line.strip() + return ( + method_to_signature, + method_to_class_name, + special_output_type, + doc_string_dict, + ) + + +def parse_datapipe_files( + file_paths: set[str], +) -> tuple[dict[str, list[str]], dict[str, str], set[str], dict[str, list[str]]]: + methods_and_signatures = {} + methods_and_class_names = {} + methods_with_special_output_types = set() + methods_and_doc_strings = {} + for path in file_paths: + ( + method_to_signature, + method_to_class_name, + methods_needing_special_output_types, + doc_string_dict, + ) = parse_datapipe_file(path) + methods_and_signatures.update(method_to_signature) + methods_and_class_names.update(method_to_class_name) + methods_with_special_output_types.update(methods_needing_special_output_types) + methods_and_doc_strings.update(doc_string_dict) + return ( + methods_and_signatures, + methods_and_class_names, + methods_with_special_output_types, + methods_and_doc_strings, + ) + + +def split_outside_bracket(line: str, delimiter: str = ",") -> list[str]: + """Given a line of text, split it on comma unless the comma is within a bracket '[]'.""" + bracket_count = 0 + curr_token = "" + res = [] + for char in line: + if char == "[": + bracket_count += 1 + elif char == "]": + bracket_count -= 1 + elif char == delimiter and bracket_count == 0: + res.append(curr_token) + curr_token = "" + continue + curr_token += char + res.append(curr_token) + return res + + +def process_signature(line: str) -> list[str]: + """ + Clean up a given raw function signature. + + This includes removing the self-referential datapipe argument, default + arguments of input functions, newlines, and spaces. + """ + tokens: list[str] = split_outside_bracket(line) + for i, token in enumerate(tokens): + tokens[i] = token.strip(" ") + if token == "cls": + tokens[i] = "self" + elif i > 0 and ("self" == tokens[i - 1]) and (tokens[i][0] != "*"): + # Remove the datapipe after 'self' or 'cls' unless it has '*' + tokens[i] = "" + elif "Callable =" in token: # Remove default argument if it is a function + head = token.rpartition("=")[0] + tokens[i] = head.strip(" ") + " = ..." + tokens = [t for t in tokens if t != ""] + return tokens + + +def get_method_definitions( + file_path: str | list[str], + files_to_exclude: set[str], + deprecated_files: set[str], + default_output_type: str, + method_to_special_output_type: dict[str, str], + root: str = "", +) -> list[str]: + """ + #.pyi generation for functional DataPipes Process. + + # 1. Find files that we want to process (exclude the ones who don't) + # 2. Parse method name and signature + # 3. Remove first argument after self (unless it is "*datapipes"), default args, and spaces + """ + if root == "": + root = str(Path(__file__).parent.resolve()) + file_path = [file_path] if isinstance(file_path, str) else file_path + file_path = [os.path.join(root, path) for path in file_path] + file_paths = find_file_paths( + file_path, files_to_exclude=files_to_exclude.union(deprecated_files) + ) + ( + methods_and_signatures, + methods_and_class_names, + methods_w_special_output_types, + methods_and_doc_strings, + ) = parse_datapipe_files(file_paths) + + for fn_name in method_to_special_output_type: + if fn_name not in methods_w_special_output_types: + methods_w_special_output_types.add(fn_name) + + method_definitions = [] + for method_name, arguments in methods_and_signatures.items(): + class_name = methods_and_class_names[method_name] + if method_name in methods_w_special_output_types: + output_type = method_to_special_output_type[method_name] + else: + output_type = default_output_type + doc_string = "".join(methods_and_doc_strings[method_name]) + if doc_string == "": + doc_string = " ..." + else: + doc_string = "\n" + doc_string + definition = format_function_signature(method_name, arguments, output_type) + method_definitions.append( + f"# Functional form of '{class_name}'\n" + + definition.removesuffix("...").rstrip() # remove "..." + + doc_string, + ) + method_definitions.sort( + key=lambda s: s.split("\n")[1] + ) # sorting based on method_name + + return method_definitions + + +# Defined outside of main() so they can be imported by TorchData +iterDP_file_path: str = "iter" +iterDP_files_to_exclude: set[str] = {"__init__.py", "utils.py"} +iterDP_deprecated_files: set[str] = set() +iterDP_method_to_special_output_type: dict[str, str] = { + "demux": "list[IterDataPipe]", + "fork": "list[IterDataPipe]", +} + +mapDP_file_path: str = "map" +mapDP_files_to_exclude: set[str] = {"__init__.py", "utils.py"} +mapDP_deprecated_files: set[str] = set() +mapDP_method_to_special_output_type: dict[str, str] = {"shuffle": "IterDataPipe"} + + +def main() -> None: + """ + # Inject file into template datapipe.pyi.in. + + TODO: The current implementation of this script only generates interfaces for built-in methods. To generate + interface for user-defined DataPipes, consider changing `IterDataPipe.register_datapipe_as_function`. + """ + iter_method_definitions = get_method_definitions( + iterDP_file_path, + iterDP_files_to_exclude, + iterDP_deprecated_files, + "IterDataPipe", + iterDP_method_to_special_output_type, + ) + + map_method_definitions = get_method_definitions( + mapDP_file_path, + mapDP_files_to_exclude, + mapDP_deprecated_files, + "MapDataPipe", + mapDP_method_to_special_output_type, + ) + + path = Path(__file__).absolute().parent + fm = FileManager(install_dir=path, template_dir=path, dry_run=False) + fm.write_with_template( + "datapipe.pyi", + "datapipe.pyi.in", + lambda: { + "IterDataPipeMethods": iter_method_definitions, + "MapDataPipeMethods": map_method_definitions, + }, + ) + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..05831250da468cc76e8c2cc8e4018373e8191951 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__init__.py @@ -0,0 +1,66 @@ +from torch.utils.data.datapipes.iter.callable import ( + CollatorIterDataPipe as Collator, + MapperIterDataPipe as Mapper, +) +from torch.utils.data.datapipes.iter.combinatorics import ( + SamplerIterDataPipe as Sampler, + ShufflerIterDataPipe as Shuffler, +) +from torch.utils.data.datapipes.iter.combining import ( + ConcaterIterDataPipe as Concater, + DemultiplexerIterDataPipe as Demultiplexer, + ForkerIterDataPipe as Forker, + MultiplexerIterDataPipe as Multiplexer, + ZipperIterDataPipe as Zipper, +) +from torch.utils.data.datapipes.iter.filelister import ( + FileListerIterDataPipe as FileLister, +) +from torch.utils.data.datapipes.iter.fileopener import ( + FileOpenerIterDataPipe as FileOpener, +) +from torch.utils.data.datapipes.iter.grouping import ( + BatcherIterDataPipe as Batcher, + GrouperIterDataPipe as Grouper, + UnBatcherIterDataPipe as UnBatcher, +) +from torch.utils.data.datapipes.iter.routeddecoder import ( + RoutedDecoderIterDataPipe as RoutedDecoder, +) +from torch.utils.data.datapipes.iter.selecting import FilterIterDataPipe as Filter +from torch.utils.data.datapipes.iter.sharding import ( + ShardingFilterIterDataPipe as ShardingFilter, +) +from torch.utils.data.datapipes.iter.streamreader import ( + StreamReaderIterDataPipe as StreamReader, +) +from torch.utils.data.datapipes.iter.utils import ( + IterableWrapperIterDataPipe as IterableWrapper, +) + + +__all__ = [ + "Batcher", + "Collator", + "Concater", + "Demultiplexer", + "FileLister", + "FileOpener", + "Filter", + "Forker", + "Grouper", + "IterableWrapper", + "Mapper", + "Multiplexer", + "RoutedDecoder", + "Sampler", + "ShardingFilter", + "Shuffler", + "StreamReader", + "UnBatcher", + "Zipper", +] + +# Please keep this list sorted +if __all__ != sorted(__all__): + raise AssertionError("__all__ is not sorted") diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35891e61994d42b61d92a8b4e36fbb23318ef660 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/callable.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/callable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..333759f7ef1b7777f82a9544bcd15a3bb2e463f4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/callable.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/combinatorics.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/combinatorics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5088e4adb7b2211f5b416e9a6159f88df0149a1f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/combinatorics.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/combining.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/combining.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45a047433419c2c2452c785853f734e24323fc54 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/combining.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/filelister.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/filelister.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c74ac9fadbef2e5068a54a47827feba6ec6c9a1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/filelister.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/fileopener.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/fileopener.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..365e178ad703da1e5a6fb403ee14ce18d99490c9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/fileopener.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/grouping.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/grouping.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b4a15720de2944599bccf31a4a0fb4cbd2c5a55 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/grouping.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/routeddecoder.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/routeddecoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1ab61c2fd1c8bdd63f0ca992216b8913a093819 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/routeddecoder.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/selecting.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/selecting.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35d842bac7d25153fa00662d4a5cd3dddfe07339 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/selecting.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/sharding.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/sharding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8df526d0326a1aa524d434e73b33ad625a425577 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/sharding.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/streamreader.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/streamreader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d00ea5e9bac405b74f47b73e9ff0346d4399741 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/streamreader.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ed4534aaae4c2b69dac21a500114b5cfdd2e70b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/callable.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/callable.py new file mode 100644 index 0000000000000000000000000000000000000000..aecaf775929ee846b3508f58be1c0355426b02cd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/callable.py @@ -0,0 +1,244 @@ +# mypy: allow-untyped-defs +import functools +from collections import namedtuple +from collections.abc import Callable, Iterator, Sized +from typing import Any, TypeVar + +import torch +from torch.utils.data._utils.collate import default_collate +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.dataframe import dataframe_wrapper as df_wrapper +from torch.utils.data.datapipes.datapipe import IterDataPipe +from torch.utils.data.datapipes.utils.common import ( + _check_unpickable_fn, + validate_input_col, +) + + +__all__ = [ + "CollatorIterDataPipe", + "MapperIterDataPipe", +] + + +_T_co = TypeVar("_T_co", covariant=True) + + +@functional_datapipe("map") +class MapperIterDataPipe(IterDataPipe[_T_co]): + r""" + Applies a function over each item from the source DataPipe (functional name: ``map``). + + The function can be any regular Python function or partial object. Lambda + function is not recommended as it is not supported by pickle. + + Args: + datapipe: Source Iterable DataPipe + fn: Function being applied over each item + input_col: Index or indices of data which ``fn`` is applied, such as: + + - ``None`` as default to apply ``fn`` to the data directly. + - Integer(s) is used for list/tuple. + - Key(s) is used for dict. + + output_col: Index of data where result of ``fn`` is placed. ``output_col`` can be specified + only when ``input_col`` is not ``None`` + + - ``None`` as default to replace the index that ``input_col`` specified; For ``input_col`` with + multiple indices, the left-most one is used, and other indices will be removed. + - Integer is used for list/tuple. ``-1`` represents to append result at the end. + - Key is used for dict. New key is acceptable. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper, Mapper + >>> def add_one(x): + ... return x + 1 + >>> dp = IterableWrapper(range(10)) + >>> # Invocation via functional form is preferred + ... map_dp_1 = dp.map(add_one) + >>> list(map_dp_1) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + >>> # We discourage the usage of `lambda` functions as they are not serializable with `pickle` + >>> # Use `functools.partial` or explicitly define the function instead + >>> map_dp_2 = Mapper(dp, lambda x: x + 1) + >>> list(map_dp_2) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + """ + + datapipe: IterDataPipe + fn: Callable + + def __init__( + self, + datapipe: IterDataPipe, + fn: Callable, + input_col=None, + output_col=None, + ) -> None: + torch._C._log_api_usage_once("python.data_pipes.map") + super().__init__() + self.datapipe = datapipe + + _check_unpickable_fn(fn) + self.fn = fn # type: ignore[assignment] + + self.input_col = input_col + if input_col is None and output_col is not None: + raise ValueError("`output_col` must be None when `input_col` is None.") + if isinstance(output_col, (list, tuple)): + if len(output_col) > 1: + raise ValueError("`output_col` must be a single-element list or tuple") + output_col = output_col[0] + self.output_col = output_col + validate_input_col(fn, input_col) + + def _apply_fn(self, data): + if self.input_col is None and self.output_col is None: + return self.fn(data) + + if self.input_col is None: + res = self.fn(data) + elif isinstance(self.input_col, (list, tuple)): + args = tuple(data[col] for col in self.input_col) + res = self.fn(*args) + else: + res = self.fn(data[self.input_col]) + + # Copy tuple to list and run in-place modification because tuple is immutable. + if isinstance(data, tuple): + t_flag = True + data = list(data) + else: + t_flag = False + + if self.output_col is None: + if isinstance(self.input_col, (list, tuple)): + data[self.input_col[0]] = res + for idx in sorted(self.input_col[1:], reverse=True): + del data[idx] + else: + data[self.input_col] = res + else: + if self.output_col == -1: + data.append(res) + else: + data[self.output_col] = res + + # Convert list back to tuple + return tuple(data) if t_flag else data + + def __iter__(self) -> Iterator[_T_co]: + for data in self.datapipe: + yield self._apply_fn(data) + + def __len__(self) -> int: + # pyrefly: ignore [unsafe-overlap] + if isinstance(self.datapipe, Sized): + return len(self.datapipe) + raise TypeError(f"{type(self).__name__} instance doesn't have valid length") + + +def _collate_helper(conversion, item): + # TODO(VitalyFedyunin): Verify that item is any sort of batch + if len(item.items) > 1: + # TODO(VitalyFedyunin): Compact all batch dataframes into one + raise RuntimeError("Only supports one DataFrame per batch") + df = item[0] + columns_name = df_wrapper.get_columns(df) + tuple_names: list = [] + tuple_values: list = [] + + for name in conversion: + if name not in columns_name: + raise RuntimeError("Conversion keys mismatch") + + for name in columns_name: + if name in conversion: + if not callable(conversion[name]): + raise RuntimeError( + "Collate (DF)DataPipe requires callable as dict values" + ) + collation_fn = conversion[name] + else: + # TODO(VitalyFedyunin): Add default collation into df_wrapper + try: + import torcharrow.pytorch as tap # type: ignore[import] + + collation_fn = tap.rec.Default() + except Exception as e: + raise RuntimeError( + "unable to import default collation function from the TorchArrow" + ) from e + + tuple_names.append(str(name)) + value = collation_fn(df[name]) + tuple_values.append(value) + + # TODO(VitalyFedyunin): We can dynamically extract types from the tuple_values here + # TODO(VitalyFedyunin): Instead of ignoring mypy error, make sure tuple_names is not empty + tpl_cls = namedtuple("CollateResult", tuple_names) # type: ignore[misc] + tuple = tpl_cls(*tuple_values) + return tuple + + +@functional_datapipe("collate") +class CollatorIterDataPipe(MapperIterDataPipe): + r""" + Collates samples from DataPipe to Tensor(s) by a custom collate function (functional name: ``collate``). + + By default, it uses :func:`torch.utils.data.default_collate`. + + .. note:: + While writing a custom collate function, you can import :func:`torch.utils.data.default_collate` for the + default behavior and `functools.partial` to specify any additional arguments. + + Args: + datapipe: Iterable DataPipe being collated + collate_fn: Customized collate function to collect and combine data or a batch of data. + Default function collates to Tensor(s) based on data type. + + Example: + >>> # xdoctest: +SKIP + >>> # Convert integer data to float Tensor + >>> class MyIterDataPipe(torch.utils.data.IterDataPipe): + ... def __init__(self, start, end): + ... super(MyIterDataPipe).__init__() + ... assert end > start, "this example only works with end >= start" + ... self.start = start + ... self.end = end + ... + ... def __iter__(self): + ... return iter(range(self.start, self.end)) + ... + ... def __len__(self): + ... return self.end - self.start + >>> ds = MyIterDataPipe(start=3, end=7) + >>> print(list(ds)) + [3, 4, 5, 6] + >>> def collate_fn(batch): + ... return torch.tensor(batch, dtype=torch.float) + >>> collated_ds = CollateIterDataPipe(ds, collate_fn=collate_fn) + >>> print(list(collated_ds)) + [tensor(3.), tensor(4.), tensor(5.), tensor(6.)] + """ + + def __init__( + self, + datapipe: IterDataPipe, + conversion: Callable[..., Any] + | dict[str | Any, Callable | Any] + | None = default_collate, + collate_fn: Callable | None = None, + ) -> None: + # TODO(VitalyFedyunin): Replace `Callable[..., Any]` with `Callable[[IColumn], Any]` + # TODO(VitalyFedyunin): Replace with `Dict[Union[str, IColumn], Union[Callable, Enum]]` + if collate_fn is not None: + super().__init__(datapipe, fn=collate_fn) + else: + if callable(conversion): + super().__init__(datapipe, fn=conversion) + else: + # TODO(VitalyFedyunin): Validate passed dictionary + collate_fn = functools.partial(_collate_helper, conversion) + super().__init__(datapipe, fn=collate_fn) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/combinatorics.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/combinatorics.py new file mode 100644 index 0000000000000000000000000000000000000000..f9221e63f12c27f8552c55bafa1ab841beba06af --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/combinatorics.py @@ -0,0 +1,195 @@ +# mypy: allow-untyped-defs +import random +from collections.abc import Iterator, Sized +from typing import TypeVar + +import torch +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.datapipe import IterDataPipe +from torch.utils.data.sampler import Sampler, SequentialSampler + + +__all__ = [ + "SamplerIterDataPipe", + "ShufflerIterDataPipe", +] + + +_T_co = TypeVar("_T_co", covariant=True) + + +class SamplerIterDataPipe(IterDataPipe[_T_co]): + r""" + Generate sample elements using the provided ``Sampler`` (defaults to :class:`SequentialSampler`). + + Args: + datapipe: IterDataPipe to sample from + sampler: Sampler class to generate sample elements from input DataPipe. + Default is :class:`SequentialSampler` for IterDataPipe + """ + + datapipe: IterDataPipe + sampler: Sampler + + def __init__( + self, + datapipe: IterDataPipe, + sampler: type[Sampler] = SequentialSampler, + sampler_args: tuple | None = None, + sampler_kwargs: dict | None = None, + ) -> None: + # pyrefly: ignore [unsafe-overlap] + if not isinstance(datapipe, Sized): + raise AssertionError( + "Sampler class requires input datapipe implemented `__len__`" + ) + super().__init__() + + self.datapipe = datapipe + self.sampler_args = () if sampler_args is None else sampler_args + self.sampler_kwargs = {} if sampler_kwargs is None else sampler_kwargs + self.sampler_kwargs["data_source"] = self.datapipe + self.sampler = sampler(*self.sampler_args, **self.sampler_kwargs) + + def __iter__(self) -> Iterator[_T_co]: + return iter(self.sampler) + + def __len__(self) -> int: + # Dataset has been tested as `Sized` + if isinstance(self.sampler, Sized): + return len(self.sampler) + raise TypeError(f"{type(self).__name__} instance doesn't have valid length") + + +@functional_datapipe("shuffle") +class ShufflerIterDataPipe(IterDataPipe[_T_co]): + r""" + Shuffle the input DataPipe with a buffer (functional name: ``shuffle``). + + The buffer with ``buffer_size`` is filled with elements from the datapipe first. Then, + each item will be yielded from the buffer by reservoir sampling via iterator. + + ``buffer_size`` is required to be larger than ``0``. For ``buffer_size == 1``, the + datapipe is not shuffled. In order to fully shuffle all elements from datapipe, + ``buffer_size`` is required to be greater than or equal to the size of datapipe. + + When it is used with :class:`torch.utils.data.DataLoader`, the methods to + set up random seed are different based on :attr:`num_workers`. + + For single-process mode (:attr:`num_workers == 0`), the random seed is set before + the :class:`~torch.utils.data.DataLoader` in the main process. For multi-process + mode (:attr:`num_worker > 0`), `worker_init_fn` is used to set up a random seed + for each worker process. + + Args: + datapipe: The IterDataPipe being shuffled + buffer_size: The buffer size for shuffling (default to ``10000``) + unbatch_level: Specifies if it is necessary to unbatch source data before + applying the shuffle + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp = IterableWrapper(range(10)) + >>> shuffle_dp = dp.shuffle() + >>> list(shuffle_dp) + [0, 4, 1, 6, 3, 2, 9, 5, 7, 8] + """ + + datapipe: IterDataPipe[_T_co] + buffer_size: int + _buffer: list[_T_co] + _enabled: bool + _seed: int | None + _rng: random.Random + + def __init__( + self, + datapipe: IterDataPipe[_T_co], + *, + buffer_size: int = 10000, + unbatch_level: int = 0, + ) -> None: + super().__init__() + # TODO: Performance optimization + # buffer can be a fixed size and remove expensive `append()` and `len()` operations + self._buffer: list[_T_co] = [] + if buffer_size <= 0: + raise AssertionError("buffer_size should be larger than 0") + if unbatch_level == 0: + self.datapipe = datapipe + else: + self.datapipe = datapipe.unbatch(unbatch_level=unbatch_level) + self.buffer_size = buffer_size + self._enabled = True + self._seed = None + self._rng = random.Random() + + def set_shuffle(self, shuffle=True): + self._enabled = shuffle + return self + + def set_seed(self, seed: int): + self._seed = seed + return self + + def __iter__(self) -> Iterator[_T_co]: + if not self._enabled: + yield from self.datapipe + else: + for x in self.datapipe: + if len(self._buffer) == self.buffer_size: + idx = self._rng.randint(0, len(self._buffer) - 1) + val, self._buffer[idx] = self._buffer[idx], x + yield val + else: + self._buffer.append(x) + while self._buffer: + idx = self._rng.randint(0, len(self._buffer) - 1) + yield self._buffer.pop(idx) + + def __len__(self) -> int: + # pyrefly: ignore [unsafe-overlap] + if isinstance(self.datapipe, Sized): + return len(self.datapipe) + raise TypeError(f"{type(self).__name__} instance doesn't have valid length") + + def reset(self) -> None: + self._buffer = [] + if self._enabled: + if self._seed is None: + self._seed = int(torch.empty((), dtype=torch.int64).random_().item()) + self._rng.seed(self._seed) + self._seed = None + + def __getstate__(self): + state = ( + self.datapipe, + self.buffer_size, + self._enabled, + self._seed, + self._buffer, + self._rng.getstate(), + self._valid_iterator_id, + self._number_of_samples_yielded, + ) + if IterDataPipe.getstate_hook is not None: + return IterDataPipe.getstate_hook(state) + return state + + def __setstate__(self, state): + ( + self.datapipe, + self.buffer_size, + self._enabled, + self._seed, + self._buffer, + rng_state, + self._valid_iterator_id, + self._number_of_samples_yielded, + ) = state + self._rng = random.Random() + self._rng.setstate(rng_state) + + def __del__(self) -> None: + self._buffer.clear() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/combining.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/combining.py new file mode 100644 index 0000000000000000000000000000000000000000..00ac91fba5940227a730d4bcb932b0b96946f780 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/combining.py @@ -0,0 +1,716 @@ +# mypy: allow-untyped-defs +import copy as copymodule +import warnings +from abc import ABC, abstractmethod +from collections import deque +from collections.abc import Callable, Iterator, Sized +from typing import Any, Literal, TypeVar + +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes._hook_iterator import _SnapshotState +from torch.utils.data.datapipes.datapipe import IterDataPipe +from torch.utils.data.datapipes.utils.common import _check_unpickable_fn, StreamWrapper + + +__all__ = [ + "ConcaterIterDataPipe", + "DemultiplexerIterDataPipe", + "ForkerIterDataPipe", + "MultiplexerIterDataPipe", + "ZipperIterDataPipe", +] + + +_T_co = TypeVar("_T_co", covariant=True) + + +@functional_datapipe("concat") +class ConcaterIterDataPipe(IterDataPipe): + r""" + Concatenates multiple Iterable DataPipes (functional name: ``concat``). + + The resulting DataPipe will yield all the elements from the first input DataPipe, before yielding from the subsequent ones. + + Args: + datapipes: Iterable DataPipes being concatenated + + Example: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> import random + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp1 = IterableWrapper(range(3)) + >>> dp2 = IterableWrapper(range(5)) + >>> list(dp1.concat(dp2)) + [0, 1, 2, 0, 1, 2, 3, 4] + """ + + datapipes: tuple[IterDataPipe] + + def __init__(self, *datapipes: IterDataPipe) -> None: + if len(datapipes) == 0: + raise ValueError("Expected at least one DataPipe, but got nothing") + if not all(isinstance(dp, IterDataPipe) for dp in datapipes): + raise TypeError("Expected all inputs to be `IterDataPipe`") + self.datapipes = datapipes # type: ignore[assignment] + + def __iter__(self) -> Iterator: + for dp in self.datapipes: + yield from dp + + def __len__(self) -> int: + # pyrefly: ignore [unsafe-overlap] + if all(isinstance(dp, Sized) for dp in self.datapipes): + # pyrefly: ignore [bad-argument-type] + return sum(len(dp) for dp in self.datapipes) + else: + raise TypeError(f"{type(self).__name__} instance doesn't have valid length") + + +@functional_datapipe("fork") +class ForkerIterDataPipe(IterDataPipe): + r""" + Creates multiple instances of the same Iterable DataPipe (functional name: ``fork``). + + Args: + datapipe: Iterable DataPipe being copied + num_instances: number of instances of the datapipe to create + buffer_size: this restricts how far ahead the leading child DataPipe + can read relative to the slowest child DataPipe. + Defaults to ``1000``. Use ``-1`` for the unlimited buffer. + copy: copy strategy to use for items yielded by each branch. Supported + options are ``None`` for no copying, ``"shallow"`` for shallow object + copies, and ``"deep"`` for deep object copies. Defaults to ``None``. + + Note: + All branches of the forked pipeline return the identical object unless + the copy parameter is supplied. If the object is mutable or contains + mutable objects, changing them in one branch will affect all others. + + Example: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> from torchdata.datapipes.iter import IterableWrapper + >>> source_dp = IterableWrapper(range(5)) + >>> dp1, dp2 = source_dp.fork(num_instances=2) + >>> list(dp1) + [0, 1, 2, 3, 4] + >>> list(dp2) + [0, 1, 2, 3, 4] + """ + + def __new__( + cls, + datapipe: IterDataPipe, + num_instances: int, + buffer_size: int = 1000, + copy: Literal["shallow", "deep"] | None = None, + ): + if num_instances < 1: + raise ValueError( + f"Expected `num_instances` larger than 0, but {num_instances} is found" + ) + if num_instances == 1: + return datapipe + container = _ForkerIterDataPipe(datapipe, num_instances, buffer_size, copy) # type: ignore[abstract] + return [_ChildDataPipe(container, i) for i in range(num_instances)] + + +class _ContainerTemplate(ABC): + r"""Abstract class for container ``DataPipes``. The following are three required methods.""" + + @abstractmethod + def get_next_element_by_instance(self, instance_id: int): ... + + @abstractmethod + def is_every_instance_exhausted(self) -> bool: ... + + @abstractmethod + def reset(self) -> None: ... + + @abstractmethod + def get_length_by_instance(self, instance_id: int): + r"""Raise TypeError if it's not supposed to be implemented to support `list(datapipe)`.""" + + +def _no_op(x): + return x + + +class _ForkerIterDataPipe(IterDataPipe, _ContainerTemplate): + r""" + Container to hold instance-specific information on behalf of ForkerIterDataPipe. + + It tracks the state of its child DataPipes, maintains the buffer, and yields the next value + as requested by the child DataPipes. + """ + + def __init__( + self, + datapipe: IterDataPipe, + num_instances: int, + buffer_size: int = 1000, + copy: Literal["shallow", "deep"] | None = None, + ) -> None: + self.main_datapipe = datapipe + self._datapipe_iterator: Iterator[Any] | None = None + self.num_instances = num_instances + self.buffer: deque = deque() + self.buffer_size = buffer_size + if self.buffer_size < 0: + warnings.warn( + "Unlimited buffer size is set for `fork`, " + "please be aware of OOM at random places", + UserWarning, + stacklevel=2, + ) + if copy is None: + self.copy_fn = _no_op + elif copy == "shallow": + self.copy_fn = copymodule.copy + elif copy == "deep": + self.copy_fn = copymodule.deepcopy + else: + raise ValueError( + f"Unknown copy method `{copy}` requested, choose one of None, `shallow` or `deep`." + ) + + self.child_pointers: list[int] = [ + 0 + ] * num_instances # Indicate the indices of the next element to get + self.slowest_ptr = 0 # The index to read by the slowest child + self.leading_ptr = 0 # The index to read by the fastest child + self.end_ptr: int | None = None # The index to stop child + self._child_stop: list[bool] = [True for _ in range(num_instances)] + + def __len__(self) -> int: + # pyrefly: ignore [bad-argument-type] + return len(self.main_datapipe) + + def get_next_element_by_instance(self, instance_id: int): + if self._datapipe_iterator is None and self._child_stop[instance_id]: + self._datapipe_iterator = iter(self.main_datapipe) + self._snapshot_state = _SnapshotState.Iterating + for i in range(self.num_instances): + self._child_stop[i] = False + try: + while not self._child_stop[instance_id]: + self.child_pointers[instance_id] += 1 + if ( + self.end_ptr is not None + and self.child_pointers[instance_id] == self.end_ptr + ): + self._child_stop[instance_id] = True + break + # Use buffer + if self.buffer and self.child_pointers[instance_id] <= self.leading_ptr: + idx = self.child_pointers[instance_id] - self.slowest_ptr - 1 + return_val = self.buffer[idx] + else: # Retrieve one element from main datapipe + self.leading_ptr = self.child_pointers[instance_id] + try: + return_val = next(self._datapipe_iterator) # type: ignore[arg-type] + self.buffer.append(return_val) + except StopIteration: + self._child_stop[instance_id] = True + self._datapipe_iterator = None + self.end_ptr = self.leading_ptr + continue + if self.child_pointers[instance_id] == self.slowest_ptr + 1: + new_min = min( + self.child_pointers + ) # Can optimize by avoiding the call to min() + if self.slowest_ptr < new_min: + self.slowest_ptr = new_min + self.buffer.popleft() + if ( + self.buffer_size >= 0 + and self.leading_ptr > self.buffer_size + self.slowest_ptr + ): + raise BufferError( + "ForkerIterDataPipe buffer overflow," + + f"buffer size {self.buffer_size} is insufficient." + ) + + yield self.copy_fn(return_val) # type: ignore[possibly-undefined] + finally: + self._child_stop[instance_id] = True + # Cleanup _datapipe_iterator for the case that fork exits earlier + if all(self._child_stop): + self._datapipe_iterator = None + self._cleanup() + + def is_every_instance_exhausted(self) -> bool: + return self.end_ptr is not None and all(self._child_stop) + + def get_length_by_instance(self, instance_id: int) -> int: + # pyrefly: ignore [bad-argument-type] + return len(self.main_datapipe) + + def reset(self) -> None: + self._datapipe_iterator = None + self.buffer = deque() + self.child_pointers = [0] * self.num_instances + self.slowest_ptr = 0 + self.leading_ptr = 0 + self.end_ptr = None + self._child_stop = [True for _ in range(self.num_instances)] + + def __getstate__(self): + state = ( + self.main_datapipe, + self.num_instances, + self.buffer_size, + self.copy_fn, + self._valid_iterator_id, + self._number_of_samples_yielded, + ) + if IterDataPipe.getstate_hook is not None: + return IterDataPipe.getstate_hook(state) + return state + + def __setstate__(self, state): + ( + self.main_datapipe, + self.num_instances, + self.buffer_size, + self.copy_fn, + self._valid_iterator_id, + self._number_of_samples_yielded, + ) = state + self._datapipe_iterator = None + self.buffer = deque() + self.child_pointers = [0] * self.num_instances + self.slowest_ptr = 0 + self.leading_ptr = 0 + self.end_ptr = None + self._child_stop = [True for _ in range(self.num_instances)] + + def _cleanup(self) -> None: + while self.buffer: + d = self.buffer.popleft() + StreamWrapper.close_streams(d) + + def __del__(self) -> None: + self._cleanup() + + +class _ChildDataPipe(IterDataPipe): + r""" + Iterable Datapipe that is a child of a main DataPipe. + + The instance of this class will pass its instance_id to get the next value from its main DataPipe. + + Note: + ChildDataPipe, like all other IterDataPipe, follows the single iterator per IterDataPipe constraint. + Since ChildDataPipes share a common buffer, when an iterator is created for one of the ChildDataPipes, + the previous iterators for all ChildDataPipes must be invalidated, with the exception when a ChildDataPipe + hasn't had an iterator created from it since the last invalidation. See the example below. + + Example: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> # Single Iterator per IterDataPipe Invalidation + >>> from torchdata.datapipes.iter import IterableWrapper + >>> source_dp = IterableWrapper(range(10)) + >>> cdp1, cdp2 = source_dp.fork(num_instances=2) + >>> it1, it2 = iter(cdp1), iter(cdp2) + >>> it3 = iter(cdp1) + >>> # The line above invalidates `it1` and `it2`, and resets `ForkerIterDataPipe`. + >>> it4 = iter(cdp2) + >>> # The line above doesn't invalidate `it3`, because an iterator for `cdp2` hasn't been created since + >>> # the last invalidation. + + Args: + main_datapipe: Main DataPipe with a method 'get_next_element_by_instance(instance_id)' + instance_id: integer identifier of this instance + """ + + _is_child_datapipe: bool = True + + def __init__(self, main_datapipe: IterDataPipe, instance_id: int) -> None: + if not isinstance(main_datapipe, _ContainerTemplate): + raise AssertionError("main_datapipe must implement _ContainerTemplate") + + self.main_datapipe: IterDataPipe = main_datapipe + self.instance_id = instance_id + + def __iter__(self): + # Note that the logic behind setting iterator ID and `reset` are handled within `hook_iterator` + # We want to separate the code for reset and yield, so that 'reset' executes before __next__ is called + return self.main_datapipe.get_next_element_by_instance(self.instance_id) + + def __len__(self) -> int: + return self.main_datapipe.get_length_by_instance(self.instance_id) + + # This method is called by `hook_iterator` in `_typing.py`. + def _set_main_datapipe_valid_iterator_id(self) -> int: + r""" + Update the valid iterator ID for both this DataPipe object and `main_datapipe`. + + `main_datapipe.reset()` is called when the ID is incremented to a new generation. + """ + # 1. First time any child iterator is created + if self.main_datapipe._valid_iterator_id is None: + self.main_datapipe._valid_iterator_id = 0 # type: ignore[attr-defined] + # 2. This instance was already in the same generation as `main_datapipe`, + # we need to increment the ID further by 1 + elif self.main_datapipe._valid_iterator_id == self._valid_iterator_id: # type: ignore[has-type] + self.main_datapipe._valid_iterator_id += 1 # type: ignore[attr-defined] + # Whenever a new generation of iterator is created, the `main_datapipe` must reset + if not self.main_datapipe.is_every_instance_exhausted(): + warnings.warn( + "Some child DataPipes are not exhausted when __iter__ is called. We are resetting " + "the buffer and each child DataPipe will read from the start again.", + UserWarning, + stacklevel=2, + ) + self.main_datapipe.reset() + # 3. Otherwise, the iterator is behind the others, so it will just need to catch up by setting + # the instance's iterator to match that of `main_datapipe` + self._valid_iterator_id = self.main_datapipe._valid_iterator_id + return self._valid_iterator_id + + # This method is called by `hook_iterator` in `_typing.py`. + def _check_valid_iterator_id(self, iterator_id) -> bool: + r"""Check the valid iterator ID against that of DataPipe object and that of `main_datapipe`.""" + return ( + iterator_id == self._valid_iterator_id + and iterator_id == self.main_datapipe._valid_iterator_id + ) + + +@functional_datapipe("demux") +class DemultiplexerIterDataPipe(IterDataPipe): + r""" + Splits the input DataPipe into multiple child DataPipes, using the given classification function (functional name: ``demux``). + + A list of the child DataPipes is returned from this operation. + + Args: + datapipe: Iterable DataPipe being filtered + num_instances: number of instances of the DataPipe to create + classifier_fn: a function that maps values to an integer within the range ``[0, num_instances - 1]`` or ``None`` + drop_none: defaults to ``False``, if ``True``, the function will skip over elements classified as ``None`` + buffer_size: this defines the maximum number of inputs that the buffer can hold across all child + DataPipes while waiting for their values to be yielded. + Defaults to ``1000``. Use ``-1`` for the unlimited buffer. + + Examples: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> from torchdata.datapipes.iter import IterableWrapper + >>> def odd_or_even(n): + ... return n % 2 + >>> source_dp = IterableWrapper(range(5)) + >>> dp1, dp2 = source_dp.demux(num_instances=2, classifier_fn=odd_or_even) + >>> list(dp1) + [0, 2, 4] + >>> list(dp2) + [1, 3] + >>> # It can also filter out any element that gets `None` from the `classifier_fn` + >>> def odd_or_even_no_zero(n): + ... return n % 2 if n != 0 else None + >>> dp1, dp2 = source_dp.demux( + ... num_instances=2, classifier_fn=odd_or_even_no_zero, drop_none=True + ... ) + >>> list(dp1) + [2, 4] + >>> list(dp2) + [1, 3] + """ + + def __new__( + cls, + datapipe: IterDataPipe, + num_instances: int, + classifier_fn: Callable[[_T_co], int | None], + drop_none: bool = False, + buffer_size: int = 1000, + ): + if num_instances < 1: + raise ValueError( + f"Expected `num_instances` larger than 0, but {num_instances} is found" + ) + + _check_unpickable_fn(classifier_fn) + + # When num_instances == 1, demux can be replaced by filter, + # but keep it as Demultiplexer for the sake of consistency + # like throwing Error when classification result is out of range + container = _DemultiplexerIterDataPipe( + datapipe, num_instances, classifier_fn, drop_none, buffer_size + ) # type: ignore[abstract] + return [_ChildDataPipe(container, i) for i in range(num_instances)] + + +class _DemultiplexerIterDataPipe(IterDataPipe, _ContainerTemplate): + r""" + Container to hold instance-specific information on behalf of DemultiplexerIterDataPipe. + + It tracks the state of its child DataPipes, maintains the buffer, classifies and yields the next correct value + as requested by the child DataPipes. + """ + + def __init__( + self, + datapipe: IterDataPipe[_T_co], + num_instances: int, + classifier_fn: Callable[[_T_co], int | None], + drop_none: bool, + buffer_size: int, + ) -> None: + # pyrefly: ignore [invalid-type-var] + self.main_datapipe = datapipe + self._datapipe_iterator: Iterator[Any] | None = None + self.num_instances = num_instances + self.buffer_size = buffer_size + if self.buffer_size < 0: + warnings.warn( + "Unlimited buffer size is set for `demux`, " + "please be aware of OOM at random places", + UserWarning, + stacklevel=2, + ) + self.current_buffer_usage = 0 + # pyrefly: ignore [invalid-type-var] + self.child_buffers: list[deque[_T_co]] = [deque() for _ in range(num_instances)] + # pyrefly: ignore [invalid-type-var] + self.classifier_fn = classifier_fn + self.drop_none = drop_none + self.main_datapipe_exhausted = False + self._child_stop: list[bool] = [True for _ in range(num_instances)] + + def _find_next(self, instance_id: int) -> _T_co: # type: ignore[type-var] + while True: + if self.main_datapipe_exhausted or self._child_stop[instance_id]: + raise StopIteration + if self._datapipe_iterator is None: + raise ValueError( + "_datapipe_iterator has not been set, likely because this private method is called directly " + "without invoking get_next_element_by_instance() first." + ) + value = next(self._datapipe_iterator) + classification = self.classifier_fn(value) + if classification is None and self.drop_none: + StreamWrapper.close_streams(value) + continue + if ( + classification is None + or classification >= self.num_instances + or classification < 0 + ): + raise ValueError( + f"Output of the classification fn should be between 0 and {self.num_instances - 1}. " + + f"{classification} is returned." + ) + if classification == instance_id: + return value + self.child_buffers[classification].append(value) + self.current_buffer_usage += 1 + if self.buffer_size >= 0 and self.current_buffer_usage > self.buffer_size: + raise BufferError( + f"DemultiplexerIterDataPipe buffer overflow, buffer size {self.buffer_size} is insufficient." + ) + + def get_next_element_by_instance(self, instance_id: int): + if self._datapipe_iterator is None and self._child_stop[instance_id]: + self._datapipe_iterator = iter(self.main_datapipe) + self._snapshot_state = ( + _SnapshotState.Iterating + ) # This is necessary for the DataPipe to reset properly. + self.main_datapipe_exhausted = False + for i in range(self.num_instances): + self._child_stop[i] = False + + try: + while not self._child_stop[instance_id]: + if self.child_buffers[instance_id]: + self.current_buffer_usage -= 1 + yield self.child_buffers[instance_id].popleft() + else: + try: + yield self._find_next(instance_id) + except StopIteration: + self._child_stop[instance_id] = True + self.main_datapipe_exhausted = True + self._datapipe_iterator = None + finally: + self._child_stop[instance_id] = True + # Cleanup _datapipe_iterator for the case that demux exits earlier + if all(self._child_stop): + self._datapipe_iterator = None + if self.child_buffers[instance_id]: + self._cleanup(instance_id) + + def is_every_instance_exhausted(self) -> bool: + return self.main_datapipe_exhausted and all(self._child_stop) + + def get_length_by_instance(self, instance_id: int) -> int: + raise TypeError + + def reset(self) -> None: + self._datapipe_iterator = None + self.current_buffer_usage = 0 + self.child_buffers = [deque() for _ in range(self.num_instances)] + self._child_stop = [True for _ in range(self.num_instances)] + self.main_datapipe_exhausted = False + + def __getstate__(self): + state = ( + self.main_datapipe, + self.num_instances, + self.buffer_size, + self.classifier_fn, + self.drop_none, + self._valid_iterator_id, + self._number_of_samples_yielded, + ) + if IterDataPipe.getstate_hook is not None: + return IterDataPipe.getstate_hook(state) + return state + + def __setstate__(self, state): + ( + self.main_datapipe, + self.num_instances, + self.buffer_size, + self.classifier_fn, + self.drop_none, + self._valid_iterator_id, + self._number_of_samples_yielded, + ) = state + self._datapipe_iterator = None + self.current_buffer_usage = 0 + self.child_buffers = [deque() for _ in range(self.num_instances)] + self._child_stop = [True for _ in range(self.num_instances)] + self.main_datapipe_exhausted = False + + def _cleanup(self, instance_id: int | None = None) -> None: + ids = ( + range(self.num_instances) + if instance_id is None + else [ + instance_id, + ] + ) + for i in ids: + q = self.child_buffers[i] + while q: + d = q.popleft() + StreamWrapper.close_streams(d) + + def __del__(self) -> None: + self._cleanup() + + +@functional_datapipe("mux") +class MultiplexerIterDataPipe(IterDataPipe): + r""" + Yields one element at a time from each of the input Iterable DataPipes (functional name: ``mux``). + + As in, one element from the 1st input DataPipe, then one element from the 2nd DataPipe in the next iteration, + and so on. It ends when the shortest input DataPipe is exhausted. + + Args: + datapipes: Iterable DataPipes that will take turn to yield their elements, until the shortest DataPipe is exhausted + + Example: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp1, dp2, dp3 = ( + ... IterableWrapper(range(3)), + ... IterableWrapper(range(10, 15)), + ... IterableWrapper(range(20, 25)), + ... ) + >>> list(dp1.mux(dp2, dp3)) + [0, 10, 20, 1, 11, 21, 2, 12, 22] + """ + + def __init__(self, *datapipes) -> None: + self.datapipes = datapipes + self.buffer: list = [] # Store values to be yielded only when every iterator provides one + + def __iter__(self): + iterators = [iter(x) for x in self.datapipes] + while iterators: + for it in iterators: + try: + value = next(it) + self.buffer.append(value) + except StopIteration: + self.buffer.clear() + return + yield from self.buffer + self.buffer.clear() + + def __len__(self) -> int: + if all(isinstance(dp, Sized) for dp in self.datapipes): + return min(len(dp) for dp in self.datapipes) * len(self.datapipes) + else: + raise TypeError(f"{type(self).__name__} instance doesn't have valid length") + + def reset(self) -> None: + self.buffer = [] + + def __getstate__(self): + state = ( + self.datapipes, + self._valid_iterator_id, + self._number_of_samples_yielded, + ) + if IterDataPipe.getstate_hook is not None: + return IterDataPipe.getstate_hook(state) + return state + + def __setstate__(self, state): + ( + self.datapipes, + self._valid_iterator_id, + self._number_of_samples_yielded, + ) = state + self.buffer = [] + + def __del__(self) -> None: + self.buffer.clear() + + +@functional_datapipe("zip") +class ZipperIterDataPipe(IterDataPipe[tuple[_T_co]]): + r""" + Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``). + + The output is stopped as soon as the shortest input DataPipe is exhausted. + + Args: + *datapipes: Iterable DataPipes being aggregated + + Example: + >>> # xdoctest: +REQUIRES(module:torchdata) + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp1, dp2, dp3 = ( + ... IterableWrapper(range(5)), + ... IterableWrapper(range(10, 15)), + ... IterableWrapper(range(20, 25)), + ... ) + >>> list(dp1.zip(dp2, dp3)) + [(0, 10, 20), (1, 11, 21), (2, 12, 22), (3, 13, 23), (4, 14, 24)] + """ + + datapipes: tuple[IterDataPipe] + + def __init__(self, *datapipes: IterDataPipe) -> None: + if not all(isinstance(dp, IterDataPipe) for dp in datapipes): + raise TypeError( + "All inputs are required to be `IterDataPipe` for `ZipIterDataPipe`." + ) + super().__init__() + self.datapipes = datapipes # type: ignore[assignment] + + def __iter__(self) -> Iterator[tuple[_T_co]]: + iterators = [iter(datapipe) for datapipe in self.datapipes] + yield from zip(*iterators, strict=False) + + def __len__(self) -> int: + # pyrefly: ignore [unsafe-overlap] + if all(isinstance(dp, Sized) for dp in self.datapipes): + # pyrefly: ignore [bad-argument-type] + return min(len(dp) for dp in self.datapipes) + else: + raise TypeError(f"{type(self).__name__} instance doesn't have valid length") diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/filelister.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/filelister.py new file mode 100644 index 0000000000000000000000000000000000000000..352d3c01e12d278cb8e1308ee78feff0610808bc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/filelister.py @@ -0,0 +1,67 @@ +from collections.abc import Iterator, Sequence + +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.datapipe import IterDataPipe +from torch.utils.data.datapipes.iter.utils import IterableWrapperIterDataPipe +from torch.utils.data.datapipes.utils.common import get_file_pathnames_from_root + + +__all__ = ["FileListerIterDataPipe"] + + +@functional_datapipe("list_files") +class FileListerIterDataPipe(IterDataPipe[str]): + r""" + Given path(s) to the root directory, yields file pathname(s) (path + filename) of files within the root directory. + + Multiple root directories can be provided (functional name: ``list_files``). + + Args: + root: Root directory or a sequence of root directories + masks: Unix style filter string or string list for filtering file name(s) + recursive: Whether to return pathname from nested directories or not + abspath: Whether to return relative pathname or absolute pathname + non_deterministic: Whether to return pathname in sorted order or not. + If ``False``, the results yielded from each root directory will be sorted + length: Nominal length of the datapipe + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import FileLister + >>> dp = FileLister(root=".", recursive=True) + >>> list(dp) + ['example.py', './data/data.tar'] + """ + + def __init__( + self, + root: str | Sequence[str] | IterDataPipe = ".", + masks: str | list[str] = "", + *, + recursive: bool = False, + abspath: bool = False, + non_deterministic: bool = False, + length: int = -1, + ) -> None: + super().__init__() + if isinstance(root, str): + root = [root] + if not isinstance(root, IterDataPipe): + root = IterableWrapperIterDataPipe(root) + self.datapipe: IterDataPipe = root + self.masks: str | list[str] = masks + self.recursive: bool = recursive + self.abspath: bool = abspath + self.non_deterministic: bool = non_deterministic + self.length: int = length + + def __iter__(self) -> Iterator[str]: + for path in self.datapipe: + yield from get_file_pathnames_from_root( + path, self.masks, self.recursive, self.abspath, self.non_deterministic + ) + + def __len__(self) -> int: + if self.length == -1: + raise TypeError(f"{type(self).__name__} instance doesn't have valid length") + return self.length diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/fileopener.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/fileopener.py new file mode 100644 index 0000000000000000000000000000000000000000..e77f7a4c8e660ec0e2ff5374fcdc8a30c474ea03 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/fileopener.py @@ -0,0 +1,79 @@ +from collections.abc import Iterable, Iterator +from io import IOBase + +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.datapipe import IterDataPipe +from torch.utils.data.datapipes.utils.common import get_file_binaries_from_pathnames + + +__all__ = [ + "FileOpenerIterDataPipe", +] + + +@functional_datapipe("open_files") +class FileOpenerIterDataPipe(IterDataPipe[tuple[str, IOBase]]): + r""" + Given pathnames, opens files and yield pathname and file stream in a tuple (functional name: ``open_files``). + + Args: + datapipe: Iterable datapipe that provides pathnames + mode: An optional string that specifies the mode in which + the file is opened by ``open()``. It defaults to ``r``, other options are + ``b`` for reading in binary mode and ``t`` for text mode. + encoding: An optional string that specifies the encoding of the + underlying file. It defaults to ``None`` to match the default encoding of ``open``. + length: Nominal length of the datapipe + + Note: + The opened file handles will be closed by Python's GC periodically. Users can choose + to close them explicitly. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import ( + ... FileLister, + ... FileOpener, + ... StreamReader, + ... ) + >>> dp = FileLister(root=".").filter(lambda fname: fname.endswith(".txt")) + >>> dp = FileOpener(dp) + >>> dp = StreamReader(dp) + >>> list(dp) + [('./abc.txt', 'abc')] + """ + + def __init__( + self, + datapipe: Iterable[str], + mode: str = "r", + encoding: str | None = None, + length: int = -1, + ) -> None: + super().__init__() + self.datapipe: Iterable[str] = datapipe + self.mode: str = mode + self.encoding: str | None = encoding + + if self.mode not in ("b", "t", "rb", "rt", "r"): + raise ValueError(f"Invalid mode {mode}") + # TODO: enforce typing for each instance based on mode, otherwise + # `argument_validation` with this DataPipe may be potentially broken + + if "b" in mode and encoding is not None: + raise ValueError("binary mode doesn't take an encoding argument") + + self.length: int = length + + # Remove annotation due to 'IOBase' is a general type and true type + # is determined at runtime based on mode. Some `DataPipe` requiring + # a subtype would cause mypy error. + def __iter__(self) -> Iterator[tuple[str, IOBase]]: + yield from get_file_binaries_from_pathnames( + self.datapipe, self.mode, self.encoding + ) + + def __len__(self) -> int: + if self.length == -1: + raise TypeError(f"{type(self).__name__} instance doesn't have valid length") + return self.length diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/grouping.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..c82948b583a938c3effd6a6d618271f1beea3d72 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/grouping.py @@ -0,0 +1,325 @@ +# mypy: allow-untyped-defs +from collections import defaultdict +from collections.abc import Callable, Iterator, Sized +from typing import Any, NoReturn, TypeVar + +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.datapipe import DataChunk, IterDataPipe +from torch.utils.data.datapipes.utils.common import _check_unpickable_fn + + +__all__ = [ + "BatcherIterDataPipe", + "GrouperIterDataPipe", + "UnBatcherIterDataPipe", +] + + +_T_co = TypeVar("_T_co", covariant=True) + + +def __getattr__(name: str) -> NoReturn: + raise AttributeError(f"module {__name__} has no attribute {name}") + + +@functional_datapipe("batch") +class BatcherIterDataPipe(IterDataPipe[DataChunk]): + r""" + Creates mini-batches of data (functional name: ``batch``). + + An outer dimension will be added as ``batch_size`` if ``drop_last`` is set to ``True``, or ``length % batch_size`` for the + last batch if ``drop_last`` is set to ``False``. + + Args: + datapipe: Iterable DataPipe being batched + batch_size: The size of each batch + drop_last: Option to drop the last batch if it's not full + wrapper_class: wrapper to apply onto each batch (type ``List``) before yielding, + defaults to ``DataChunk`` + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp = IterableWrapper(range(10)) + >>> dp = dp.batch(batch_size=3, drop_last=True) + >>> list(dp) + [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + """ + + datapipe: IterDataPipe + batch_size: int + drop_last: bool + + def __init__( + self, + datapipe: IterDataPipe, + batch_size: int, + drop_last: bool = False, + wrapper_class: type[DataChunk] = DataChunk, + ) -> None: + if batch_size <= 0: + raise AssertionError("Batch size is required to be larger than 0!") + super().__init__() + self.datapipe = datapipe + self.batch_size = batch_size + self.drop_last = drop_last + self.wrapper_class = wrapper_class + + def __iter__(self) -> Iterator[DataChunk]: + batch: list = [] + for x in self.datapipe: + batch.append(x) + if len(batch) == self.batch_size: + yield self.wrapper_class(batch) + batch = [] + if len(batch) > 0: + if not self.drop_last: + yield self.wrapper_class(batch) + + def __len__(self) -> int: + # pyrefly: ignore [unsafe-overlap] + if isinstance(self.datapipe, Sized): + if self.drop_last: + return len(self.datapipe) // self.batch_size + else: + return (len(self.datapipe) + self.batch_size - 1) // self.batch_size + else: + raise TypeError(f"{type(self).__name__} instance doesn't have valid length") + + +@functional_datapipe("unbatch") +class UnBatcherIterDataPipe(IterDataPipe): + r""" + Undoes batching of data (functional name: ``unbatch``). + + In other words, it flattens the data up to the specified level within a batched DataPipe. + + Args: + datapipe: Iterable DataPipe being un-batched + unbatch_level: Defaults to ``1`` (only flattening the top level). If set to ``2``, + it will flatten the top two levels, and ``-1`` will flatten the entire DataPipe. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> source_dp = IterableWrapper([[[0, 1], [2]], [[3, 4], [5]], [[6]]]) + >>> dp1 = source_dp.unbatch() + >>> list(dp1) + [[0, 1], [2], [3, 4], [5], [6]] + >>> dp2 = source_dp.unbatch(unbatch_level=2) + >>> list(dp2) + [0, 1, 2, 3, 4, 5, 6] + """ + + def __init__(self, datapipe: IterDataPipe, unbatch_level: int = 1) -> None: + self.datapipe = datapipe + self.unbatch_level = unbatch_level + + def __iter__(self): + for element in self.datapipe: + yield from self._dive(element, unbatch_level=self.unbatch_level) + + def _dive(self, element, unbatch_level): + if unbatch_level < -1: + raise ValueError("unbatch_level must be -1 or >= 0") + if unbatch_level == -1: + if isinstance(element, (list, DataChunk)): + for item in element: + yield from self._dive(item, unbatch_level=-1) + else: + yield element + elif unbatch_level == 0: + yield element + else: + if isinstance(element, (list, DataChunk)): + for item in element: + yield from self._dive(item, unbatch_level=unbatch_level - 1) + else: + raise IndexError( + f"unbatch_level {self.unbatch_level} exceeds the depth of the DataPipe" + ) + + +@functional_datapipe("groupby") +class GrouperIterDataPipe(IterDataPipe[DataChunk]): + r""" + Groups data from IterDataPipe by keys from ``group_key_fn``, yielding a ``DataChunk`` with batch size up to ``group_size``. + + (functional name: ``groupby``). + + The samples are read sequentially from the source ``datapipe``, and a batch of samples belonging to the same group + will be yielded as soon as the size of the batch reaches ``group_size``. When the buffer is full, + the DataPipe will yield the largest batch with the same key, provided that its size is larger + than ``guaranteed_group_size``. If its size is smaller, it will be dropped if ``drop_remaining=True``. + + After iterating through the entirety of source ``datapipe``, everything not dropped due to the buffer capacity + will be yielded from the buffer, even if the group sizes are smaller than ``guaranteed_group_size``. + + Args: + datapipe: Iterable datapipe to be grouped + group_key_fn: Function used to generate group key from the data of the source datapipe + keep_key: Option to yield the matching key along with the items in a tuple, + resulting in `(key, [items])` otherwise returning [items] + buffer_size: The size of buffer for ungrouped data + group_size: The max size of each group, a batch is yielded as soon as it reaches this size + guaranteed_group_size: The guaranteed minimum group size to be yielded in case the buffer is full + drop_remaining: Specifies if the group smaller than ``guaranteed_group_size`` will be dropped from buffer + when the buffer is full + + Example: + >>> import os + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> def group_fn(file): + ... return os.path.basename(file).split(".")[0] + >>> source_dp = IterableWrapper( + ... ["a.png", "b.png", "a.json", "b.json", "a.jpg", "c.json"] + ... ) + >>> dp0 = source_dp.groupby(group_key_fn=group_fn) + >>> list(dp0) + [['a.png', 'a.json', 'a.jpg'], ['b.png', 'b.json'], ['c.json']] + >>> # A group is yielded as soon as its size equals to `group_size` + >>> dp1 = source_dp.groupby(group_key_fn=group_fn, group_size=2) + >>> list(dp1) + [['a.png', 'a.json'], ['b.png', 'b.json'], ['a.jpg'], ['c.json']] + >>> # Scenario where `buffer` is full, and group 'a' needs to be yielded since its size > `guaranteed_group_size` + >>> dp2 = source_dp.groupby( + ... group_key_fn=group_fn, + ... buffer_size=3, + ... group_size=3, + ... guaranteed_group_size=2, + ... ) + >>> list(dp2) + [['a.png', 'a.json'], ['b.png', 'b.json'], ['a.jpg'], ['c.json']] + """ + + def __init__( + self, + datapipe: IterDataPipe[_T_co], + group_key_fn: Callable[[_T_co], Any], + *, + keep_key: bool = False, + buffer_size: int = 10000, + group_size: int | None = None, + guaranteed_group_size: int | None = None, + drop_remaining: bool = False, + ) -> None: + _check_unpickable_fn(group_key_fn) + # pyrefly: ignore [invalid-type-var] + self.datapipe = datapipe + # pyrefly: ignore [invalid-type-var] + self.group_key_fn = group_key_fn + + self.keep_key = keep_key + self.max_buffer_size = buffer_size + self.buffer_elements: defaultdict[Any, list] = defaultdict(list) + self.curr_buffer_size = 0 + self.group_size = group_size + self.guaranteed_group_size = None + if group_size is not None and buffer_size is not None: + if not (0 < group_size <= buffer_size): + raise AssertionError("group_size must be > 0 and <= buffer_size") + self.guaranteed_group_size = group_size + if guaranteed_group_size is not None: + if group_size is None or not (0 < guaranteed_group_size <= group_size): + raise AssertionError( + "guaranteed_group_size must be > 0 and <= group_size and group_size must be set" + ) + self.guaranteed_group_size = guaranteed_group_size + self.drop_remaining = drop_remaining + self.wrapper_class = DataChunk + + def _remove_biggest_key(self): + biggest_key = None + biggest_size = 0 + result_to_yield = None + for findkey in self.buffer_elements: + if len(self.buffer_elements[findkey]) > biggest_size: + biggest_size = len(self.buffer_elements[findkey]) + biggest_key = findkey + + if ( + self.guaranteed_group_size is not None + and biggest_size < self.guaranteed_group_size + and not self.drop_remaining + ): + raise RuntimeError( + "Failed to group items", str(self.buffer_elements[biggest_key]) + ) + + if ( + self.guaranteed_group_size is None + or biggest_size >= self.guaranteed_group_size + ): + result_to_yield = self.buffer_elements[biggest_key] + + self.curr_buffer_size -= biggest_size + del self.buffer_elements[biggest_key] + + return result_to_yield + + def __iter__(self): + for x in self.datapipe: + key = self.group_key_fn(x) + + self.buffer_elements[key].append(x) + self.curr_buffer_size += 1 + + if self.group_size is not None and self.group_size == len( + self.buffer_elements[key] + ): + result: DataChunk[Any] = self.wrapper_class(self.buffer_elements[key]) + yield (key, result) if self.keep_key else result + self.curr_buffer_size -= len(self.buffer_elements[key]) + del self.buffer_elements[key] + + if self.curr_buffer_size == self.max_buffer_size: + result_to_yield = self._remove_biggest_key() + if result_to_yield is not None: + result = self.wrapper_class(result_to_yield) + yield (key, result) if self.keep_key else result + + for key in tuple(self.buffer_elements.keys()): + result = self.wrapper_class(self.buffer_elements.pop(key)) + self.curr_buffer_size -= len(result) + yield (key, result) if self.keep_key else result + + def reset(self) -> None: + self.curr_buffer_size = 0 + self.buffer_elements = defaultdict(list) + + def __getstate__(self): + state = ( + self.datapipe, + self.group_key_fn, + self.keep_key, + self.max_buffer_size, + self.group_size, + self.guaranteed_group_size, + self.drop_remaining, + self.wrapper_class, + self._valid_iterator_id, + self._number_of_samples_yielded, + ) + if IterDataPipe.getstate_hook is not None: + return IterDataPipe.getstate_hook(state) + return state + + def __setstate__(self, state): + ( + self.datapipe, + self.group_key_fn, + self.keep_key, + self.max_buffer_size, + self.group_size, + self.guaranteed_group_size, + self.drop_remaining, + self.wrapper_class, + self._valid_iterator_id, + self._number_of_samples_yielded, + ) = state + self.curr_buffer_size = 0 + self.buffer_elements = defaultdict(list) + + def __del__(self) -> None: + self.buffer_elements.clear() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/routeddecoder.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/routeddecoder.py new file mode 100644 index 0000000000000000000000000000000000000000..70c86ab835dd4999ee4d5d502c64c566a3849fb5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/routeddecoder.py @@ -0,0 +1,70 @@ +from collections.abc import Callable, Iterable, Iterator, Sized +from io import BufferedIOBase +from typing import Any + +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.datapipe import IterDataPipe +from torch.utils.data.datapipes.utils.common import _deprecation_warning +from torch.utils.data.datapipes.utils.decoder import ( + basichandlers as decoder_basichandlers, + Decoder, + extension_extract_fn, + imagehandler as decoder_imagehandler, +) + + +__all__ = ["RoutedDecoderIterDataPipe"] + + +@functional_datapipe("routed_decode") +class RoutedDecoderIterDataPipe(IterDataPipe[tuple[str, Any]]): + r""" + Decodes binary streams from input DataPipe, yields pathname and decoded data in a tuple. + + (functional name: ``routed_decode``) + + Args: + datapipe: Iterable datapipe that provides pathname and binary stream in tuples + handlers: Optional user defined decoder handlers. If ``None``, basic and image decoder + handlers will be set as default. If multiple handlers are provided, the priority + order follows the order of handlers (the first handler has the top priority) + key_fn: Function for decoder to extract key from pathname to dispatch handlers. + Default is set to extract file extension from pathname + + Note: + When ``key_fn`` is specified returning anything other than extension, the default + handler will not work and users need to specify custom handler. Custom handler + could use regex to determine the eligibility to handle data. + """ + + def __init__( + self, + datapipe: Iterable[tuple[str, BufferedIOBase]], + *handlers: Callable, + key_fn: Callable = extension_extract_fn, + ) -> None: + super().__init__() + self.datapipe: Iterable[tuple[str, BufferedIOBase]] = datapipe + if not handlers: + handlers = (decoder_basichandlers, decoder_imagehandler("torch")) + self.decoder = Decoder(*handlers, key_fn=key_fn) + _deprecation_warning( + type(self).__name__, + deprecation_version="1.12", + removal_version="1.13", + old_functional_name="routed_decode", + ) + + def add_handler(self, *handler: Callable) -> None: + self.decoder.add_handler(*handler) + + def __iter__(self) -> Iterator[tuple[str, Any]]: + for data in self.datapipe: + pathname = data[0] + result = self.decoder(data) + yield (pathname, result[pathname]) + + def __len__(self) -> int: + if isinstance(self.datapipe, Sized): + return len(self.datapipe) + raise TypeError(f"{type(self).__name__} instance doesn't have valid length") diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/selecting.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/selecting.py new file mode 100644 index 0000000000000000000000000000000000000000..afb0e91d8557911aae6f20d830667c79f7764cc5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/selecting.py @@ -0,0 +1,102 @@ +# mypy: allow-untyped-defs +from collections.abc import Callable, Iterator +from typing import TypeVar + +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.dataframe import dataframe_wrapper as df_wrapper +from torch.utils.data.datapipes.datapipe import IterDataPipe +from torch.utils.data.datapipes.utils.common import ( + _check_unpickable_fn, + StreamWrapper, + validate_input_col, +) + + +__all__ = ["FilterIterDataPipe"] + + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) + + +@functional_datapipe("filter") +class FilterIterDataPipe(IterDataPipe[_T_co]): + r""" + Filters out elements from the source datapipe according to input ``filter_fn`` (functional name: ``filter``). + + Args: + datapipe: Iterable DataPipe being filtered + filter_fn: Customized function mapping an element to a boolean. + input_col: Index or indices of data which ``filter_fn`` is applied, such as: + + - ``None`` as default to apply ``filter_fn`` to the data directly. + - Integer(s) is used for list/tuple. + - Key(s) is used for dict. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> def is_even(n): + ... return n % 2 == 0 + >>> dp = IterableWrapper(range(5)) + >>> filter_dp = dp.filter(filter_fn=is_even) + >>> list(filter_dp) + [0, 2, 4] + """ + + datapipe: IterDataPipe[_T_co] + filter_fn: Callable + + def __init__( + self, + datapipe: IterDataPipe[_T_co], + filter_fn: Callable, + input_col=None, + ) -> None: + super().__init__() + self.datapipe = datapipe + + _check_unpickable_fn(filter_fn) + self.filter_fn = filter_fn # type: ignore[assignment] + + self.input_col = input_col + validate_input_col(filter_fn, input_col) + + def _apply_filter_fn(self, data) -> bool: + if self.input_col is None: + return self.filter_fn(data) + elif isinstance(self.input_col, (list, tuple)): + args = tuple(data[col] for col in self.input_col) + return self.filter_fn(*args) + else: + return self.filter_fn(data[self.input_col]) + + def __iter__(self) -> Iterator[_T_co]: + for data in self.datapipe: + condition, filtered = self._returnIfTrue(data) + if condition: + yield filtered + else: + StreamWrapper.close_streams(data) + + def _returnIfTrue(self, data: _T) -> tuple[bool, _T]: + condition = self._apply_filter_fn(data) + + if df_wrapper.is_column(condition): + # We are operating on DataFrames filter here + result = [] + for idx, mask in enumerate(df_wrapper.iterate(condition)): + if mask: + result.append(df_wrapper.get_item(data, idx)) + if result: + return True, df_wrapper.concat(result) + else: + return False, None # type: ignore[return-value] + + if not isinstance(condition, bool): + raise ValueError( + "Boolean output is required for `filter_fn` of FilterIterDataPipe, got", + type(condition), + ) + + return condition, data diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/sharding.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/sharding.py new file mode 100644 index 0000000000000000000000000000000000000000..dd3378016e915fb58c3a6e5d66e1ba7187b267c2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/sharding.py @@ -0,0 +1,106 @@ +# mypy: allow-untyped-defs +from collections.abc import Sized +from enum import IntEnum +from typing import NoReturn + +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.datapipe import IterDataPipe + + +__all__ = [ + "SHARDING_PRIORITIES", + "ShardingFilterIterDataPipe", +] + + +class SHARDING_PRIORITIES(IntEnum): + DEFAULT = 1 + DISTRIBUTED = 2 + MULTIPROCESSING = 3 + + +class _ShardingIterDataPipe(IterDataPipe): + def apply_sharding( + self, + num_of_instances: int, + instance_id: int, + sharding_group: SHARDING_PRIORITIES, + ) -> NoReturn: + raise NotImplementedError + + +@functional_datapipe("sharding_filter") +class ShardingFilterIterDataPipe(_ShardingIterDataPipe): + r""" + Wrapper that allows DataPipe to be sharded (functional name: ``sharding_filter``). + + After ``apply_sharding`` is called, each instance of the DataPipe (on different workers) will have every `n`-th element of the + original DataPipe, where `n` equals to the number of instances. + + Args: + source_datapipe: Iterable DataPipe that will be sharded + """ + + def __init__( + self, source_datapipe: IterDataPipe, sharding_group_filter=None + ) -> None: + super().__init__() + self.source_datapipe = source_datapipe + self.sharding_group_filter = sharding_group_filter + self.groups: dict[int, tuple[int, int]] = {} + self.num_of_instances = 1 + self.instance_id = 0 + self._update_num_of_instances() + + def apply_sharding( + self, num_of_instances, instance_id, sharding_group=SHARDING_PRIORITIES.DEFAULT + ): + if instance_id >= num_of_instances: + raise ValueError( + f"instance_id({instance_id}) should be smaller than num_of_instances({num_of_instances})" + ) + if sharding_group == SHARDING_PRIORITIES.DEFAULT: + if len(self.groups) and SHARDING_PRIORITIES.DEFAULT not in self.groups: + raise RuntimeError( + "ShardingFilter cannot mix DEFAULT and non DEFAULT groups" + ) + else: + if SHARDING_PRIORITIES.DEFAULT in self.groups: + raise RuntimeError( + "ShardingFilter cannot mix DEFAULT and non DEFAULT groups" + ) + self.groups[sharding_group] = (num_of_instances, instance_id) + self._update_num_of_instances() + + def _update_num_of_instances(self) -> None: + sorted_sharding_groups = [ + self.groups[key] + for key in sorted(self.groups.keys()) + if self.sharding_group_filter is None or key == self.sharding_group_filter + ] + + sorted_sharding_groups.reverse() + + self.num_of_instances = 1 + self.instance_id = 0 + + for group_num_of_instances, group_instance_id in sorted_sharding_groups: + self.instance_id += self.num_of_instances * group_instance_id + self.num_of_instances *= group_num_of_instances + + def __iter__(self): + for i, item in enumerate(self.source_datapipe): + if i % self.num_of_instances == self.instance_id: + yield item + + def __len__(self) -> int: + # pyrefly: ignore [unsafe-overlap] + if isinstance(self.source_datapipe, Sized): + return len(self.source_datapipe) // self.num_of_instances + ( + 1 + if ( + self.instance_id < len(self.source_datapipe) % self.num_of_instances + ) + else 0 + ) + raise TypeError(f"{type(self).__name__} instance doesn't have valid length") diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/streamreader.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/streamreader.py new file mode 100644 index 0000000000000000000000000000000000000000..1129c06548e1f406629e25a5a2f558dea3a1475e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/streamreader.py @@ -0,0 +1,45 @@ +from collections.abc import Iterator +from io import IOBase + +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.datapipe import IterDataPipe + + +__all__ = ["StreamReaderIterDataPipe"] + + +@functional_datapipe("read_from_stream") +class StreamReaderIterDataPipe(IterDataPipe[tuple[str, bytes]]): + r""" + Given IO streams and their label names, yield bytes with label name as tuple. + + (functional name: ``read_from_stream``). + + Args: + datapipe: Iterable DataPipe provides label/URL and byte stream + chunk: Number of bytes to be read from stream per iteration. + If ``None``, all bytes will be read until the EOF. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper, StreamReader + >>> from io import StringIO + >>> dp = IterableWrapper([("alphabet", StringIO("abcde"))]) + >>> list(StreamReader(dp, chunk=1)) + [('alphabet', 'a'), ('alphabet', 'b'), ('alphabet', 'c'), ('alphabet', 'd'), ('alphabet', 'e')] + """ + + def __init__( + self, datapipe: IterDataPipe[tuple[str, IOBase]], chunk: int | None = None + ) -> None: + self.datapipe = datapipe + self.chunk = chunk + + def __iter__(self) -> Iterator[tuple[str, bytes]]: + for furl, stream in self.datapipe: + while True: + d = stream.read(self.chunk) + if not d: + stream.close() + break + yield (furl, d) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/utils.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e45ddab282f7b975732b28ab88339f979792646a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/iter/utils.py @@ -0,0 +1,60 @@ +import copy +import warnings +from collections.abc import Iterable, Iterator, Sized +from typing import TypeVar + +from torch.utils.data.datapipes.datapipe import IterDataPipe + + +_T = TypeVar("_T") + +__all__ = ["IterableWrapperIterDataPipe"] + + +class IterableWrapperIterDataPipe(IterDataPipe[_T]): + r""" + Wraps an iterable object to create an IterDataPipe. + + Args: + iterable: Iterable object to be wrapped into an IterDataPipe + deepcopy: Option to deepcopy input iterable object for each + iterator. The copy is made when the first element is read in ``iter()``. + + .. note:: + If ``deepcopy`` is explicitly set to ``False``, users should ensure + that the data pipeline doesn't contain any in-place operations over + the iterable instance to prevent data inconsistency across iterations. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.iter import IterableWrapper + >>> dp = IterableWrapper(range(10)) + >>> list(dp) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + """ + + def __init__(self, iterable: Iterable[_T], deepcopy: bool = True) -> None: + self.iterable = iterable + self.deepcopy = deepcopy + + def __iter__(self) -> Iterator[_T]: + source_data = self.iterable + if self.deepcopy: + try: + source_data = copy.deepcopy(self.iterable) + # For the case that data cannot be deep-copied, + # all in-place operations will affect iterable variable. + # When this DataPipe is iterated second time, it will + # yield modified items. + except TypeError: + warnings.warn( + "The input iterable can not be deepcopied, " + "please be aware of in-place modification would affect source data.", + stacklevel=2, + ) + yield from source_data + + def __len__(self) -> int: + if isinstance(self.iterable, Sized): + return len(self.iterable) + raise TypeError(f"{type(self).__name__} instance doesn't have valid length") diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bc555e8fdac26039d36c4c1e1ba8309bfa8b4e5a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__init__.py @@ -0,0 +1,20 @@ +# Functional DataPipe +from torch.utils.data.datapipes.map.callable import MapperMapDataPipe as Mapper +from torch.utils.data.datapipes.map.combinatorics import ( + ShufflerIterDataPipe as Shuffler, +) +from torch.utils.data.datapipes.map.combining import ( + ConcaterMapDataPipe as Concater, + ZipperMapDataPipe as Zipper, +) +from torch.utils.data.datapipes.map.grouping import BatcherMapDataPipe as Batcher +from torch.utils.data.datapipes.map.utils import ( + SequenceWrapperMapDataPipe as SequenceWrapper, +) + + +__all__ = ["Batcher", "Concater", "Mapper", "SequenceWrapper", "Shuffler", "Zipper"] + +# Please keep this list sorted +if __all__ != sorted(__all__): + raise AssertionError("__all__ is not sorted") diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83a57c44a9640e9525a1cce8c81a1d3f1113fa53 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/callable.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/callable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edc459780ca100b4c480d902e77dd8aa97030bf0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/callable.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/combinatorics.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/combinatorics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6763e0e50c8972f558a86db03136351ddc1a0ea1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/combinatorics.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/combining.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/combining.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e91ffadb06a94923e8ae510ded9eb5ebdbf0544c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/combining.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/grouping.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/grouping.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eda375e57e968e3c82199260de71fe61336b6aaf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/grouping.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78eb34fd2893528c3d2ed5155f1d2afde78e7409 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/callable.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/callable.py new file mode 100644 index 0000000000000000000000000000000000000000..3696d34b2a815599709bb09d9b0dfcaca988a6eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/callable.py @@ -0,0 +1,67 @@ +# mypy: allow-untyped-defs +from collections.abc import Callable +from typing import TypeVar + +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.datapipe import MapDataPipe +from torch.utils.data.datapipes.utils.common import _check_unpickable_fn + + +__all__ = ["MapperMapDataPipe", "default_fn"] + + +_T_co = TypeVar("_T_co", covariant=True) + + +# Default function to return each item directly +# In order to keep datapipe picklable, eliminates the usage +# of python lambda function +def default_fn(data): + return data + + +@functional_datapipe("map") +class MapperMapDataPipe(MapDataPipe[_T_co]): + r""" + Apply the input function over each item from the source DataPipe (functional name: ``map``). + + The function can be any regular Python function or partial object. Lambda + function is not recommended as it is not supported by pickle. + + Args: + datapipe: Source MapDataPipe + fn: Function being applied to each item + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper, Mapper + >>> def add_one(x): + ... return x + 1 + >>> dp = SequenceWrapper(range(10)) + >>> map_dp_1 = dp.map(add_one) + >>> list(map_dp_1) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + >>> map_dp_2 = Mapper(dp, lambda x: x + 1) + >>> list(map_dp_2) + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + """ + + datapipe: MapDataPipe + fn: Callable + + def __init__( + self, + datapipe: MapDataPipe, + fn: Callable = default_fn, + ) -> None: + super().__init__() + self.datapipe = datapipe + _check_unpickable_fn(fn) + self.fn = fn # type: ignore[assignment] + + def __len__(self) -> int: + # pyrefly: ignore [bad-argument-type] + return len(self.datapipe) + + def __getitem__(self, index) -> _T_co: + return self.fn(self.datapipe[index]) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/combinatorics.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/combinatorics.py new file mode 100644 index 0000000000000000000000000000000000000000..858964ccd2f5866d4f137038ecb004a512a5fc3b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/combinatorics.py @@ -0,0 +1,132 @@ +# mypy: allow-untyped-defs +import random +from collections.abc import Iterator +from typing import TypeVar + +import torch +from torch.utils.data.datapipes.datapipe import IterDataPipe, MapDataPipe + + +__all__ = ["ShufflerIterDataPipe"] + + +_T_co = TypeVar("_T_co", covariant=True) + + +# @functional_datapipe('shuffle') +class ShufflerIterDataPipe(IterDataPipe[_T_co]): + r""" + Shuffle the input MapDataPipe via its indices (functional name: ``shuffle``). + + When it is used with :class:`~torch.utils.data.DataLoader`, the methods to + set up random seed are different based on :attr:`num_workers`. + + For single-process mode (:attr:`num_workers == 0`), the random seed is set before + the :class:`~torch.utils.data.DataLoader` in the main process. For multi-process + mode (:attr:`num_worker > 0`), ``worker_init_fn`` is used to set up a random seed + for each worker process. + + Args: + datapipe: MapDataPipe being shuffled + indices: a list of indices of the MapDataPipe. If not provided, we assume it uses 0-based indexing + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper + >>> dp = SequenceWrapper(range(10)) + >>> shuffle_dp = dp.shuffle().set_seed(0) + >>> list(shuffle_dp) + [7, 8, 1, 5, 3, 4, 2, 0, 9, 6] + >>> list(shuffle_dp) + [6, 1, 9, 5, 2, 4, 7, 3, 8, 0] + >>> # Reset seed for Shuffler + >>> shuffle_dp = shuffle_dp.set_seed(0) + >>> list(shuffle_dp) + [7, 8, 1, 5, 3, 4, 2, 0, 9, 6] + + Note: + Even though this ``shuffle`` operation takes a ``MapDataPipe`` as the input, it would return an + ``IterDataPipe`` rather than a ``MapDataPipe``, because ``MapDataPipe`` should be non-sensitive to + the order of data order for the sake of random reads, but ``IterDataPipe`` depends on the order + of data during data-processing. + """ + + datapipe: MapDataPipe[_T_co] + _enabled: bool + _seed: int | None + _rng: random.Random + + def __init__( + self, + datapipe: MapDataPipe[_T_co], + *, + indices: list | None = None, + ) -> None: + super().__init__() + self.datapipe = datapipe + # pyrefly: ignore [bad-argument-type] + self.indices = list(range(len(datapipe))) if indices is None else indices + self._enabled = True + self._seed = None + self._rng = random.Random() + self._shuffled_indices: list = self.indices + + def set_shuffle(self, shuffle=True): + self._enabled = shuffle + return self + + def set_seed(self, seed: int): + self._seed = seed + return self + + def __iter__(self) -> Iterator[_T_co]: + if not self._enabled: + for idx in self.indices: + yield self.datapipe[idx] + else: + while self._shuffled_indices: + idx = self._shuffled_indices.pop() + yield self.datapipe[idx] + + def reset(self) -> None: + if self._enabled and self._seed is None: + self._seed = int(torch.empty((), dtype=torch.int64).random_().item()) + self._rng.seed(self._seed) + self._seed = None + self._shuffled_indices = self._rng.sample(self.indices, len(self.indices)) + + def __len__(self) -> int: + # pyrefly: ignore [bad-argument-type] + return len(self.datapipe) + + def __getstate__(self): + state = ( + self.datapipe, + self.indices, + self._enabled, + self._seed, + self._rng.getstate(), + self._shuffled_indices, + self._valid_iterator_id, + self._number_of_samples_yielded, + ) + if IterDataPipe.getstate_hook is not None: + return IterDataPipe.getstate_hook(state) + return state + + def __setstate__(self, state): + ( + self.datapipe, + self.indices, + self._enabled, + self._seed, + rng_state, + self._shuffled_indices, + self._valid_iterator_id, + self._number_of_samples_yielded, + ) = state + self._rng = random.Random() + self._rng.setstate(rng_state) + + +MapDataPipe.register_datapipe_as_function("shuffle", ShufflerIterDataPipe) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/combining.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/combining.py new file mode 100644 index 0000000000000000000000000000000000000000..479b9f635a73ed90602c0fe498ae86be690a6dfd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/combining.py @@ -0,0 +1,111 @@ +# mypy: allow-untyped-defs +from collections.abc import Sized +from typing import TypeVar + +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.datapipe import MapDataPipe + + +__all__ = ["ConcaterMapDataPipe", "ZipperMapDataPipe"] + +_T_co = TypeVar("_T_co", covariant=True) + + +@functional_datapipe("concat") +class ConcaterMapDataPipe(MapDataPipe): + r""" + Concatenate multiple Map DataPipes (functional name: ``concat``). + + The new index is the cumulative sum of source DataPipes. + For example, if there are 2 source DataPipes both with length 5, + index 0 to 4 of the resulting `ConcatMapDataPipe` would refer to + elements of the first DataPipe, and 5 to 9 would refer to elements + of the second DataPipe. + + Args: + datapipes: Map DataPipes being concatenated + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper + >>> dp1 = SequenceWrapper(range(3)) + >>> dp2 = SequenceWrapper(range(3)) + >>> concat_dp = dp1.concat(dp2) + >>> list(concat_dp) + [0, 1, 2, 0, 1, 2] + """ + + datapipes: tuple[MapDataPipe] + + def __init__(self, *datapipes: MapDataPipe) -> None: + if len(datapipes) == 0: + raise ValueError("Expected at least one DataPipe, but got nothing") + if not all(isinstance(dp, MapDataPipe) for dp in datapipes): + raise TypeError("Expected all inputs to be `MapDataPipe`") + # pyrefly: ignore [unsafe-overlap] + if not all(isinstance(dp, Sized) for dp in datapipes): + raise TypeError("Expected all inputs to be `Sized`") + self.datapipes = datapipes # type: ignore[assignment] + + def __getitem__(self, index) -> _T_co: # type: ignore[type-var] + offset = 0 + for dp in self.datapipes: + # pyrefly: ignore [bad-argument-type] + if index - offset < len(dp): + return dp[index - offset] + else: + # pyrefly: ignore [bad-argument-type] + offset += len(dp) + raise IndexError(f"Index {index} is out of range.") + + def __len__(self) -> int: + # pyrefly: ignore [bad-argument-type] + return sum(len(dp) for dp in self.datapipes) + + +@functional_datapipe("zip") +class ZipperMapDataPipe(MapDataPipe[tuple[_T_co, ...]]): + r""" + Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``). + + This MapDataPipe is out of bounds as soon as the shortest input DataPipe is exhausted. + + Args: + *datapipes: Map DataPipes being aggregated + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper + >>> dp1 = SequenceWrapper(range(3)) + >>> dp2 = SequenceWrapper(range(10, 13)) + >>> zip_dp = dp1.zip(dp2) + >>> list(zip_dp) + [(0, 10), (1, 11), (2, 12)] + """ + + datapipes: tuple[MapDataPipe[_T_co], ...] + + def __init__(self, *datapipes: MapDataPipe[_T_co]) -> None: + if len(datapipes) == 0: + raise ValueError("Expected at least one DataPipe, but got nothing") + if not all(isinstance(dp, MapDataPipe) for dp in datapipes): + raise TypeError("Expected all inputs to be `MapDataPipe`") + # pyrefly: ignore [unsafe-overlap] + if not all(isinstance(dp, Sized) for dp in datapipes): + raise TypeError("Expected all inputs to be `Sized`") + self.datapipes = datapipes + + def __getitem__(self, index) -> tuple[_T_co, ...]: + res = [] + for dp in self.datapipes: + try: + res.append(dp[index]) + except IndexError as e: + raise IndexError( + f"Index {index} is out of range for one of the input MapDataPipes {dp}." + ) from e + return tuple(res) + + def __len__(self) -> int: + # pyrefly: ignore [bad-argument-type] + return min(len(dp) for dp in self.datapipes) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/grouping.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..fdc34d9dc4fdb0d6ce4d973c667bbfc774bd9bcb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/grouping.py @@ -0,0 +1,76 @@ +# mypy: allow-untyped-defs +from collections.abc import Sized +from typing import TypeVar + +from torch.utils.data.datapipes._decorator import functional_datapipe +from torch.utils.data.datapipes.datapipe import DataChunk, MapDataPipe + + +__all__ = ["BatcherMapDataPipe"] + + +_T = TypeVar("_T") + + +@functional_datapipe("batch") +class BatcherMapDataPipe(MapDataPipe[DataChunk]): + r""" + Create mini-batches of data (functional name: ``batch``). + + An outer dimension will be added as ``batch_size`` if ``drop_last`` is set to ``True``, + or ``length % batch_size`` for the last batch if ``drop_last`` is set to ``False``. + + Args: + datapipe: Iterable DataPipe being batched + batch_size: The size of each batch + drop_last: Option to drop the last batch if it's not full + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper + >>> dp = SequenceWrapper(range(10)) + >>> batch_dp = dp.batch(batch_size=2) + >>> list(batch_dp) + [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]] + """ + + datapipe: MapDataPipe + batch_size: int + drop_last: bool + + def __init__( + self, + datapipe: MapDataPipe[_T], + batch_size: int, + drop_last: bool = False, + wrapper_class: type[DataChunk] = DataChunk, + ) -> None: + if batch_size <= 0: + raise AssertionError("Batch size is required to be larger than 0!") + super().__init__() + self.datapipe = datapipe + self.batch_size = batch_size + self.drop_last = drop_last + self.wrapper_class = wrapper_class + + def __getitem__(self, index) -> DataChunk: + batch: list = [] + indices = range(index * self.batch_size, (index + 1) * self.batch_size) + try: + batch.extend(self.datapipe[i] for i in indices) + return self.wrapper_class(batch) + except IndexError as e: + if not self.drop_last and len(batch) > 0: + return self.wrapper_class(batch) + else: + raise IndexError(f"Index {index} is out of bound.") from e + + def __len__(self) -> int: + # pyrefly: ignore [unsafe-overlap] + if isinstance(self.datapipe, Sized): + if self.drop_last: + return len(self.datapipe) // self.batch_size + else: + return (len(self.datapipe) + self.batch_size - 1) // self.batch_size + else: + raise TypeError(f"{type(self).__name__} instance doesn't have valid length") diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/utils.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b9075f1dbbc66a84dfd14d0778cc96ca604da0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/map/utils.py @@ -0,0 +1,61 @@ +import copy +import warnings +from collections.abc import Mapping, Sequence +from typing import Any, TypeVar + +from torch.utils.data.datapipes.datapipe import MapDataPipe + + +_T = TypeVar("_T") + +__all__ = ["SequenceWrapperMapDataPipe"] + + +class SequenceWrapperMapDataPipe(MapDataPipe[_T]): + r""" + Wraps a sequence object into a MapDataPipe. + + Args: + sequence: Sequence object to be wrapped into an MapDataPipe + deepcopy: Option to deepcopy input sequence object + + .. note:: + If ``deepcopy`` is set to False explicitly, users should ensure + that data pipeline doesn't contain any in-place operations over + the iterable instance, in order to prevent data inconsistency + across iterations. + + Example: + >>> # xdoctest: +SKIP + >>> from torchdata.datapipes.map import SequenceWrapper + >>> dp = SequenceWrapper(range(10)) + >>> list(dp) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + >>> dp = SequenceWrapper({"a": 100, "b": 200, "c": 300, "d": 400}) + >>> dp["a"] + 100 + """ + + sequence: Sequence[_T] | Mapping[Any, _T] + + def __init__( + self, sequence: Sequence[_T] | Mapping[Any, _T], deepcopy: bool = True + ) -> None: + if deepcopy: + try: + self.sequence = copy.deepcopy(sequence) + except TypeError: + warnings.warn( + "The input sequence can not be deepcopied, " + "please be aware of in-place modification would affect source data", + stacklevel=2, + ) + self.sequence = sequence + else: + self.sequence = sequence + + def __getitem__(self, index: int) -> _T: + return self.sequence[index] + + def __len__(self) -> int: + return len(self.sequence) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db5f8d833b824f0275606c6ddabdf787ad06b2e7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/__pycache__/common.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..977517db616530eff529249ece4a637178218e16 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/__pycache__/common.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/__pycache__/decoder.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/__pycache__/decoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08482751e152305dfb864b58639ef928abf85ce6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/__pycache__/decoder.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/__pycache__/snapshot.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/__pycache__/snapshot.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e6b5977d827b9a3956e6f210ae77912be6fe5fd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/__pycache__/snapshot.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/common.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/common.py new file mode 100644 index 0000000000000000000000000000000000000000..e32cde2ee1fbb800f589e0059030e267135551a7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/common.py @@ -0,0 +1,414 @@ +# mypy: allow-untyped-defs +import fnmatch +import functools +import inspect +import os +import warnings +from collections.abc import Callable, Iterable +from io import IOBase +from typing import Any, NoReturn + +from torch.utils._import_utils import dill_available + + +__all__ = [ + "validate_input_col", + "StreamWrapper", + "get_file_binaries_from_pathnames", + "get_file_pathnames_from_root", + "match_masks", + "validate_pathname_binary_tuple", +] + + +# BC for torchdata +DILL_AVAILABLE = dill_available() + + +def validate_input_col(fn: Callable, input_col: int | tuple | list | None) -> None: + """ + Check that function used in a callable datapipe works with the input column. + + This simply ensures that the number of positional arguments matches the size + of the input column. The function must not contain any non-default + keyword-only arguments. + + Examples: + >>> # xdoctest: +SKIP("Failing on some CI machines") + >>> def f(a, b, *, c=1): + >>> return a + b + c + >>> def f_def(a, b=1, *, c=1): + >>> return a + b + c + >>> assert validate_input_col(f, [1, 2]) + >>> assert validate_input_col(f_def, 1) + >>> assert validate_input_col(f_def, [1, 2]) + + Notes: + If the function contains variable positional (``inspect.VAR_POSITIONAL``) arguments, + for example, ``f(a, *args)``, the validator will accept any size of input column + greater than or equal to the number of positional arguments. + (in this case, 1). + + Args: + fn: The function to check. + input_col: The input column to check. + + Raises: + ValueError: If the function is not compatible with the input column. + """ + try: + sig = inspect.signature(fn) + except ( + ValueError + ): # Signature cannot be inspected, likely it is a built-in fn or written in C + return + if isinstance(input_col, (list, tuple)): + input_col_size = len(input_col) + else: + input_col_size = 1 + + pos = [] + var_positional = False + non_default_kw_only = [] + + for p in sig.parameters.values(): + if p.kind in ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + ): + pos.append(p) + elif p.kind is inspect.Parameter.VAR_POSITIONAL: + var_positional = True + elif p.kind is inspect.Parameter.KEYWORD_ONLY: + if p.default is p.empty: + non_default_kw_only.append(p) + else: + continue + + if isinstance(fn, functools.partial): + fn_name = getattr(fn.func, "__name__", repr(fn.func)) + else: + fn_name = getattr(fn, "__name__", repr(fn)) + + if len(non_default_kw_only) > 0: + raise ValueError( + f"The function {fn_name} takes {len(non_default_kw_only)} " + f"non-default keyword-only parameters, which is not allowed." + ) + + if len(sig.parameters) < input_col_size: + if not var_positional: + raise ValueError( + f"The function {fn_name} takes {len(sig.parameters)} " + f"parameters, but {input_col_size} are required." + ) + else: + if len(pos) > input_col_size: + if any(p.default is p.empty for p in pos[input_col_size:]): + raise ValueError( + f"The function {fn_name} takes {len(pos)} " + f"positional parameters, but {input_col_size} are required." + ) + elif len(pos) < input_col_size: + if not var_positional: + raise ValueError( + f"The function {fn_name} takes {len(pos)} " + f"positional parameters, but {input_col_size} are required." + ) + + +def _is_local_fn(fn): + # Functions or Methods + if hasattr(fn, "__code__"): + return fn.__code__.co_flags & inspect.CO_NESTED + # Callable Objects + else: + if hasattr(fn, "__qualname__"): + return "" in fn.__qualname__ + fn_type = type(fn) + if hasattr(fn_type, "__qualname__"): + return "" in fn_type.__qualname__ + return False + + +def _check_unpickable_fn(fn: Callable) -> None: + """ + Check function is pickable or not. + + If it is a lambda or local function, a UserWarning will be raised. If it's not a callable function, a TypeError will be raised. + """ + if not callable(fn): + raise TypeError(f"A callable function is expected, but {type(fn)} is provided.") + + # Extract function from partial object + # Nested partial function is automatically expanded as a single partial object + if isinstance(fn, functools.partial): + fn = fn.func + + # Local function + if _is_local_fn(fn) and not dill_available(): + warnings.warn( + "Local function is not supported by pickle, please use " + "regular python function or functools.partial instead.", + stacklevel=2, + ) + return + + # Lambda function + if hasattr(fn, "__name__") and fn.__name__ == "" and not dill_available(): + warnings.warn( + "Lambda function is not supported by pickle, please use " + "regular python function or functools.partial instead.", + stacklevel=2, + ) + return + + +def match_masks(name: str, masks: str | list[str]) -> bool: + # empty mask matches any input name + if not masks: + return True + + if isinstance(masks, str): + return fnmatch.fnmatch(name, masks) + + for mask in masks: + if fnmatch.fnmatch(name, mask): + return True + return False + + +def get_file_pathnames_from_root( + root: str, + masks: str | list[str], + recursive: bool = False, + abspath: bool = False, + non_deterministic: bool = False, +) -> Iterable[str]: + # print out an error message and raise the error out + def onerror(err: OSError) -> NoReturn: + warnings.warn(err.filename + " : " + err.strerror, stacklevel=2) + raise err + + if os.path.isfile(root): + path = root + if abspath: + path = os.path.abspath(path) + fname = os.path.basename(path) + if match_masks(fname, masks): + yield path + else: + for path, dirs, files in os.walk(root, onerror=onerror): + if abspath: + path = os.path.abspath(path) + if not non_deterministic: + files.sort() + for f in files: + if match_masks(f, masks): + yield os.path.join(path, f) + if not recursive: + break + if not non_deterministic: + # Note that this is in-place modifying the internal list from `os.walk` + # This only works because `os.walk` doesn't shallow copy before turn + # https://github.com/python/cpython/blob/f4c03484da59049eb62a9bf7777b963e2267d187/Lib/os.py#L407 + dirs.sort() + + +def get_file_binaries_from_pathnames( + pathnames: Iterable, mode: str, encoding: str | None = None +): + if not isinstance(pathnames, Iterable): + pathnames = [ + pathnames, + ] + + if mode in ("b", "t"): + mode = "r" + mode + + for pathname in pathnames: + if not isinstance(pathname, str): + raise TypeError( + f"Expected string type for pathname, but got {type(pathname)}" + ) + yield pathname, StreamWrapper(open(pathname, mode, encoding=encoding)) # noqa:SIM115 + + +def validate_pathname_binary_tuple(data: tuple[str, IOBase]) -> None: + if not isinstance(data, tuple): + raise TypeError( + f"pathname binary data should be tuple type, but it is type {type(data)}" + ) + if len(data) != 2: + raise TypeError( + f"pathname binary stream tuple length should be 2, but got {len(data)}" + ) + if not isinstance(data[0], str): + raise TypeError( + f"pathname within the tuple should have string type pathname, but it is type {type(data[0])}" + ) + if not isinstance(data[1], IOBase) and not isinstance(data[1], StreamWrapper): + raise TypeError( + f"binary stream within the tuple should have IOBase or" + f"its subclasses as type, but it is type {type(data[1])}" + ) + + +# Deprecated function names and its corresponding DataPipe type and kwargs for the `_deprecation_warning` function +_iter_deprecated_functional_names: dict[str, dict] = {} +_map_deprecated_functional_names: dict[str, dict] = {} + + +def _deprecation_warning( + old_class_name: str, + *, + deprecation_version: str, + removal_version: str, + old_functional_name: str = "", + old_argument_name: str = "", + new_class_name: str = "", + new_functional_name: str = "", + new_argument_name: str = "", + deprecate_functional_name_only: bool = False, +) -> None: + if new_functional_name and not old_functional_name: + raise ValueError( + "Old functional API needs to be specified for the deprecation warning." + ) + if new_argument_name and not old_argument_name: + raise ValueError( + "Old argument name needs to be specified for the deprecation warning." + ) + + if old_functional_name and old_argument_name: + raise ValueError( + "Deprecating warning for functional API and argument should be separated." + ) + + msg = f"`{old_class_name}()`" + if deprecate_functional_name_only and old_functional_name: + msg = f"{msg}'s functional API `.{old_functional_name}()` is" + elif old_functional_name: + msg = f"{msg} and its functional API `.{old_functional_name}()` are" + elif old_argument_name: + msg = f"The argument `{old_argument_name}` of {msg} is" + else: + msg = f"{msg} is" + msg = ( + f"{msg} deprecated since {deprecation_version} and will be removed in {removal_version}." + f"\nSee https://github.com/pytorch/data/issues/163 for details." + ) + + if new_class_name or new_functional_name: + msg = f"{msg}\nPlease use" + if new_class_name: + msg = f"{msg} `{new_class_name}()`" + if new_class_name and new_functional_name: + msg = f"{msg} or" + if new_functional_name: + msg = f"{msg} `.{new_functional_name}()`" + msg = f"{msg} instead." + + if new_argument_name: + msg = f"{msg}\nPlease use `{old_class_name}({new_argument_name}=)` instead." + + warnings.warn(msg, FutureWarning, stacklevel=2) + + +class StreamWrapper: + """ + StreamWrapper is introduced to wrap file handler generated by DataPipe operation like `FileOpener`. + + StreamWrapper would guarantee the wrapped file handler is closed when it's out of scope. + """ + + session_streams: dict[Any, int] = {} + debug_unclosed_streams: bool = False + + def __init__(self, file_obj, parent_stream=None, name=None) -> None: + self.file_obj = file_obj + self.child_counter = 0 + self.parent_stream = parent_stream + self.close_on_last_child = False + self.name = name + self.closed = False + if parent_stream is not None: + if not isinstance(parent_stream, StreamWrapper): + raise RuntimeError( + f"Parent stream should be StreamWrapper, {type(parent_stream)} was given" + ) + parent_stream.child_counter += 1 + self.parent_stream = parent_stream + if StreamWrapper.debug_unclosed_streams: + StreamWrapper.session_streams[self] = 1 + + @classmethod + def close_streams(cls, v, depth=0) -> None: + """Traverse structure and attempts to close all found StreamWrappers on best effort basis.""" + if depth > 10: + return + if isinstance(v, StreamWrapper): + v.close() + else: + # Traverse only simple structures + if isinstance(v, dict): + for vv in v.values(): + cls.close_streams(vv, depth=depth + 1) + elif isinstance(v, (list, tuple)): + for vv in v: + cls.close_streams(vv, depth=depth + 1) + + def __getattr__(self, name): + file_obj = self.__dict__["file_obj"] + return getattr(file_obj, name) + + def close(self, *args, **kwargs) -> None: + if self.closed: + return + if StreamWrapper.debug_unclosed_streams: + del StreamWrapper.session_streams[self] + if hasattr(self, "parent_stream") and self.parent_stream is not None: + self.parent_stream.child_counter -= 1 + if ( + not self.parent_stream.child_counter + and self.parent_stream.close_on_last_child + ): + self.parent_stream.close() + try: + self.file_obj.close(*args, **kwargs) + except AttributeError: + pass + self.closed = True + + def autoclose(self) -> None: + """Automatically close stream when all child streams are closed or if there are none.""" + self.close_on_last_child = True + if self.child_counter == 0: + self.close() + + def __dir__(self): + attrs = list(self.__dict__.keys()) + list(StreamWrapper.__dict__.keys()) + attrs += dir(self.file_obj) + return list(set(attrs)) + + def __del__(self) -> None: + if not self.closed: + self.close() + + def __iter__(self): + yield from self.file_obj + + def __next__(self): + return next(self.file_obj) + + def __repr__(self) -> str: + if self.name is None: + return f"StreamWrapper<{self.file_obj!r}>" + else: + return f"StreamWrapper<{self.name},{self.file_obj!r}>" + + def __getstate__(self): + return self.file_obj + + def __setstate__(self, obj): + self.file_obj = obj diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/decoder.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..2f33c5cc7e0e7312d0746292b8f714c10f9907a2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/decoder.py @@ -0,0 +1,389 @@ +# mypy: allow-untyped-defs +# This file takes partial of the implementation from NVIDIA's webdataset at here: +# https://github.com/tmbdev/webdataset/blob/master/webdataset/autodecode.py + +import io +import json +import os.path +import pickle +import tempfile + +import torch +from torch.utils.data.datapipes.utils.common import StreamWrapper + + +__all__ = [ + "Decoder", + "ImageHandler", + "MatHandler", + "audiohandler", + "basichandlers", + "extension_extract_fn", + "handle_extension", + "imagehandler", + "mathandler", + "videohandler", +] + + +################################################################ +# handle basic datatypes +################################################################ +def basichandlers(extension: str, data): + """Transforms raw data (byte stream) into python objects. + + Looks at the extension and loads the data into a python object supporting + the corresponding extension. + + Args: + extension (str): The file extension + data (byte stream): Data to load into a python object. + + Returns: + object: The data loaded into a corresponding python object + supporting the extension. + + Example: + >>> import pickle + >>> data = pickle.dumps("some data") + >>> new_data = basichandlers("pickle", data) + >>> new_data + some data + + The transformation of data for extensions are: + - txt, text, transcript: utf-8 decoded data of str format + - cls, cls2, class, count, index, inx, id: int + - json, jsn: json loaded data + - pickle, pyd: pickle loaded data + - pt: torch loaded data + """ + + if extension in "txt text transcript": + return data.decode("utf-8") + + if extension in ["cls", "cls2", "class", "count", "index", "inx", "id"]: + try: + return int(data) + except ValueError: + return None + + if extension in "json jsn": + return json.loads(data) + + if extension in ["pyd", "pickle"]: + return pickle.loads(data) + + if extension == "pt": + stream = io.BytesIO(data) + return torch.load(stream) + + # if extension in "ten tb".split(): + # from . import tenbin + # return tenbin.decode_buffer(data) + + # if extension in "mp msgpack msg".split(): + # import msgpack + # return msgpack.unpackb(data) + + return None + + +################################################################ +# handle images +################################################################ +imagespecs = { + "l8": ("numpy", "uint8", "l"), + "rgb8": ("numpy", "uint8", "rgb"), + "rgba8": ("numpy", "uint8", "rgba"), + "l": ("numpy", "float", "l"), + "rgb": ("numpy", "float", "rgb"), + "rgba": ("numpy", "float", "rgba"), + "torchl8": ("torch", "uint8", "l"), + "torchrgb8": ("torch", "uint8", "rgb"), + "torchrgba8": ("torch", "uint8", "rgba"), + "torchl": ("torch", "float", "l"), + "torchrgb": ("torch", "float", "rgb"), + "torch": ("torch", "float", "rgb"), + "torchrgba": ("torch", "float", "rgba"), + "pill": ("pil", None, "l"), + "pil": ("pil", None, "rgb"), + "pilrgb": ("pil", None, "rgb"), + "pilrgba": ("pil", None, "rgba"), +} + + +def handle_extension(extensions, f): + """ + Return a decoder handler function for the list of extensions. + + Extensions can be a space separated list of extensions. + Extensions can contain dots, in which case the corresponding number + of extension components must be present in the key given to f. + Comparisons are case insensitive. + Examples: + handle_extension("jpg jpeg", my_decode_jpg) # invoked for any file.jpg + handle_extension("seg.jpg", special_case_jpg) # invoked only for file.seg.jpg + """ + extensions = extensions.lower().split() + + def g(key, data): + extension = key.lower().split(".") + + for target in extensions: + target = target.split(".") + if len(target) > len(extension): + continue + + if extension[-len(target) :] == target: + return f(data) + return None + + return g + + +class ImageHandler: + """ + Decode image data using the given `imagespec`. + + The `imagespec` specifies whether the image is decoded + to numpy/torch/pi, decoded to uint8/float, and decoded + to l/rgb/rgba: + + - l8: numpy uint8 l + - rgb8: numpy uint8 rgb + - rgba8: numpy uint8 rgba + - l: numpy float l + - rgb: numpy float rgb + - rgba: numpy float rgba + - torchl8: torch uint8 l + - torchrgb8: torch uint8 rgb + - torchrgba8: torch uint8 rgba + - torchl: torch float l + - torchrgb: torch float rgb + - torch: torch float rgb + - torchrgba: torch float rgba + - pill: pil None l + - pil: pil None rgb + - pilrgb: pil None rgb + - pilrgba: pil None rgba + """ + + def __init__(self, imagespec) -> None: + if imagespec not in list(imagespecs.keys()): + raise AssertionError(f"unknown image specification: {imagespec}") + self.imagespec = imagespec.lower() + + def __call__(self, extension, data): + if extension.lower() not in ["jpg", "jpeg", "png", "ppm", "pgm", "pbm", "pnm"]: + return None + + try: + import numpy as np + except ModuleNotFoundError as e: + raise ModuleNotFoundError( + "Package `numpy` is required to be installed for default image decoder." + "Please use `pip install numpy` to install the package" + ) from e + + try: + import PIL.Image + except ModuleNotFoundError as e: + raise ModuleNotFoundError( + "Package `PIL` is required to be installed for default image decoder." + "Please use `pip install Pillow` to install the package" + ) from e + + imagespec = self.imagespec + atype, etype, mode = imagespecs[imagespec] + + with io.BytesIO(data) as stream: + img = PIL.Image.open(stream) + img.load() + img = img.convert(mode.upper()) + if atype == "pil": + return img + elif atype == "numpy": + result = np.asarray(img) + if result.dtype != np.uint8: + raise AssertionError( + f"numpy image array should be type uint8, but got {result.dtype}" + ) + if etype == "uint8": + return result + else: + return result.astype("f") / 255.0 + elif atype == "torch": + result = np.asarray(img) + if result.dtype != np.uint8: + raise AssertionError( + f"numpy image array should be type uint8, but got {result.dtype}" + ) + + if etype == "uint8": + result = np.array(result.transpose(2, 0, 1)) + return torch.tensor(result) + else: + result = np.array(result.transpose(2, 0, 1)) + return torch.tensor(result) / 255.0 + return None + + +def imagehandler(imagespec): + return ImageHandler(imagespec) + + +################################################################ +# torch video +################################################################ +def videohandler(extension, data): + if extension not in [ + "mp4", + "ogv", + "mjpeg", + "avi", + "mov", + "h264", + "mpg", + "webm", + "wmv", + ]: + return None + + try: + import torchvision.io + except ImportError as e: + raise ModuleNotFoundError( + "Package `torchvision` is required to be installed for default video file loader." + "Please use `pip install torchvision`" + "to install the package" + ) from e + + with tempfile.TemporaryDirectory() as dirname: + fname = os.path.join(dirname, f"file.{extension}") + with open(fname, "wb") as stream: + stream.write(data) + return torchvision.io.read_video(fname) + + +################################################################ +# torchaudio +################################################################ +def audiohandler(extension, data): + if extension not in ["flac", "mp3", "sox", "wav", "m4a", "ogg", "wma"]: + return None + + try: + import torchaudio # type: ignore[import] + except ImportError as e: + raise ModuleNotFoundError( + "Package `torchaudio` is required to be installed for default audio file loader." + "Please use `pip install torchaudio`" + "to install the package" + ) from e + + with tempfile.TemporaryDirectory() as dirname: + fname = os.path.join(dirname, f"file.{extension}") + with open(fname, "wb") as stream: + stream.write(data) + return torchaudio.load(fname) + + +################################################################ +# mat +################################################################ +class MatHandler: + def __init__(self, **loadmat_kwargs) -> None: + try: + import scipy.io as sio + except ImportError as e: + raise ModuleNotFoundError( + "Package `scipy` is required to be installed for mat file." + "Please use `pip install scipy`" + "to install the package" + ) from e + self.sio = sio + self.loadmat_kwargs = loadmat_kwargs + + def __call__(self, extension, data): + if extension != "mat": + return None + with io.BytesIO(data) as stream: + return self.sio.loadmat(stream, **self.loadmat_kwargs) + + +def mathandler(**loadmat_kwargs): + return MatHandler(**loadmat_kwargs) + + +################################################################ +# a sample decoder +################################################################ +# Extract extension from pathname +def extension_extract_fn(pathname): + ext = os.path.splitext(pathname)[1] + # Remove dot + if ext: + ext = ext[1:] + return ext + + +class Decoder: + """ + Decode key/data sets using a list of handlers. + + For each key/data item, this iterates through the list of + handlers until some handler returns something other than None. + """ + + def __init__(self, *handler, key_fn=extension_extract_fn) -> None: + self.handlers = list(handler) if handler else [] + self.key_fn = key_fn + + # Insert new handler from the beginning of handlers list to make sure the new + # handler having the highest priority + def add_handler(self, *handler) -> None: + if not handler: + return + self.handlers = list(handler) + self.handlers + + @staticmethod + def _is_stream_handle(data): + obj_to_check = data.file_obj if isinstance(data, StreamWrapper) else data + return isinstance(obj_to_check, (io.BufferedIOBase, io.RawIOBase)) + + def decode1(self, key, data): + if not data: + return data + + # if data is a stream handle, we need to read all the content before decoding + if Decoder._is_stream_handle(data): + ds = data + # The behavior of .read can differ between streams (e.g. HTTPResponse), hence this is used instead + data = b"".join(data) + ds.close() + + for f in self.handlers: + result = f(key, data) + if result is not None: + return result + return data + + def decode(self, data): + result = {} + # single data tuple(pathname, data stream) + if isinstance(data, tuple): + data = [data] + + if data is not None: + for k, v in data: + # TODO: xinyu, figure out why Nvidia do this? + if k[0] == "_": + if isinstance(v, bytes): + v = v.decode("utf-8") + result[k] = v + continue + result[k] = self.decode1(self.key_fn(k), v) + return result + + def __call__(self, data): + return self.decode(data) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/snapshot.py b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..42aec1aa308a9b21b251de595cddfbe171930bb6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/datapipes/utils/snapshot.py @@ -0,0 +1,65 @@ +# mypy: allow-untyped-defs +from torch.utils.data.datapipes._hook_iterator import _SnapshotState +from torch.utils.data.datapipes.datapipe import IterDataPipe +from torch.utils.data.graph_settings import apply_random_seed + + +# TODO: Caveats +# 1. Caller (either the ReadingService or DataLoader) must pass in the initial RNG +# 2. `in_batch_shuffle` and `bucketbatch` are not compatible with this because they currently +# lack the option to `set_seed`. +def _simple_graph_snapshot_restoration( + datapipe: IterDataPipe, n_iterations: int, rng=None +) -> None: + r""" + Fast-forward the given DataPipe and its parents by ``n_iterations``, re-doing computations to restore a snapshot. + + For instance, applying this function to the final DataPipe of a graph will restore the snapshot + (via fast-forward) every DataPipe within the graph. + + After you deserialize a DataPipe, you can use its `_number_of_samples_yielded` attribute as the input + to this function to forward the DataPipe. + + A DataPipe cannot be restored twice in a row unless there is an iteration started between the restoration + attempts. + + Note: + This is the simplest but least efficient way to fast-forward a DataPipe. Usage of other fast-forwarding + methods (custom ones if necessary) are recommended. + + Args: + datapipe: IterDataPipe to be fast-forwarded + n_iterations: number of iterations to fast-forward + rng: ``Optional[torch.Generator]``. If not ``None``, this RNG will be used for shuffling. The generator + should be in its `initial` state as it was first passed into ``DataLoader`` or ``ReadingService``. + """ + if datapipe._snapshot_state == _SnapshotState.Restored: + raise RuntimeError( + "Snapshot restoration cannot be applied. You can only restore simple snapshot to the graph " + "if your graph has not been restored." + ) + + # For this snapshot restoration function, we want the DataPipe to be at its initial state prior to + # simple fast-forwarding. Therefore, we need to call `reset` twice, because if `SnapshotState` is `Restored`, + # the first reset will not actually reset. + datapipe.reset() # This ensures `SnapshotState` is `Iterating` by this point, even if it was `Restored`. + # pyrefly: ignore [bad-argument-type] + apply_random_seed(datapipe, rng) + + remainder = n_iterations + it = iter(datapipe) # This always reset the DataPipe if it hasn't already. + while remainder > 0: + try: + next(it) + remainder -= 1 + except StopIteration as e: + raise RuntimeError( + f"Fast-forward {datapipe} by {n_iterations} iterations " + "exceeds the number of samples available." + ) from e + datapipe._fast_forward_iterator = it + # While the DataPipe has `_fast_forward_iterator`, `next()` will get result from there instead of elsewhere. + + # This will prevent the DataPipe from resetting in the `iter()` call + # If another DataPipe is consuming it, it won't have to start over again + datapipe._snapshot_state = _SnapshotState.Restored diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/dataset.py b/.venv/lib/python3.12/site-packages/torch/utils/data/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..66435aeeb593129e643626a0329eee8a155e090f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/dataset.py @@ -0,0 +1,511 @@ +# mypy: allow-untyped-defs +import bisect +import itertools +import math +import warnings +from collections.abc import Sequence + +# UP006 wants 'Iterable' to be imported from collections.abc but it needs to +# stay from typing for now due to BC concerns. In particular several internal +# targets fail to typecheck with: +# TypeError: Cannot create a consistent method resolution order (MRO) for +# bases Iterable, Generic +from typing import cast, Generic, Iterable, TypeVar # noqa: UP035 +from typing_extensions import deprecated + +# No 'default_generator' in torch/__init__.pyi +from torch import default_generator, Generator, randperm, Tensor + + +__all__ = [ + "Dataset", + "IterableDataset", + "TensorDataset", + "StackDataset", + "ConcatDataset", + "ChainDataset", + "Subset", + "random_split", +] + + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_T_dict = dict[str, _T_co] +_T_tuple = tuple[_T_co, ...] +_T_stack = TypeVar("_T_stack", _T_tuple, _T_dict) + + +class Dataset(Generic[_T_co]): + r"""An abstract class representing a :class:`Dataset`. + + All datasets that represent a map from keys to data samples should subclass + it. All subclasses should overwrite :meth:`__getitem__`, supporting fetching a + data sample for a given key. Subclasses could also optionally overwrite + :meth:`__len__`, which is expected to return the size of the dataset by many + :class:`~torch.utils.data.Sampler` implementations and the default options + of :class:`~torch.utils.data.DataLoader`. Subclasses could also + optionally implement :meth:`__getitems__`, for speedup batched samples + loading. This method accepts list of indices of samples of batch and returns + list of samples. + + .. note:: + :class:`~torch.utils.data.DataLoader` by default constructs an index + sampler that yields integral indices. To make it work with a map-style + dataset with non-integral indices/keys, a custom sampler must be provided. + """ + + def __getitem__(self, index) -> _T_co: + raise NotImplementedError("Subclasses of Dataset should implement __getitem__.") + + # def __getitems__(self, indices: List) -> List[_T_co]: + # Not implemented to prevent false-positives in fetcher check in + # torch.utils.data._utils.fetch._MapDatasetFetcher + + def __add__(self, other: "Dataset[_T_co]") -> "ConcatDataset[_T_co]": + return ConcatDataset([self, other]) + + # No `def __len__(self)` default? + # See NOTE [ Lack of Default `__len__` in Python Abstract Base Classes ] + # in pytorch/torch/utils/data/sampler.py + + +class IterableDataset(Dataset[_T_co], Iterable[_T_co]): + r"""An iterable Dataset. + + All datasets that represent an iterable of data samples should subclass it. + Such form of datasets is particularly useful when data come from a stream. + + All subclasses should overwrite :meth:`__iter__`, which would return an + iterator of samples in this dataset. + + When a subclass is used with :class:`~torch.utils.data.DataLoader`, each + item in the dataset will be yielded from the :class:`~torch.utils.data.DataLoader` + iterator. When :attr:`num_workers > 0`, each worker process will have a + different copy of the dataset object, so it is often desired to configure + each copy independently to avoid having duplicate data returned from the + workers. :func:`~torch.utils.data.get_worker_info`, when called in a worker + process, returns information about the worker. It can be used in either the + dataset's :meth:`__iter__` method or the :class:`~torch.utils.data.DataLoader` 's + :attr:`worker_init_fn` option to modify each copy's behavior. + + Example 1: splitting workload across all workers in :meth:`__iter__`:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_DATALOADER) + >>> # xdoctest: +SKIP("Fails on MacOS12") + >>> class MyIterableDataset(torch.utils.data.IterableDataset): + ... def __init__(self, start, end): + ... super(MyIterableDataset).__init__() + ... assert end > start, "this example only works with end >= start" + ... self.start = start + ... self.end = end + ... + ... def __iter__(self): + ... worker_info = torch.utils.data.get_worker_info() + ... if worker_info is None: # single-process data loading, return the full iterator + ... iter_start = self.start + ... iter_end = self.end + ... else: # in a worker process + ... # split workload + ... per_worker = int(math.ceil((self.end - self.start) / float(worker_info.num_workers))) + ... worker_id = worker_info.id + ... iter_start = self.start + worker_id * per_worker + ... iter_end = min(iter_start + per_worker, self.end) + ... return iter(range(iter_start, iter_end)) + ... + >>> # should give same set of data as range(3, 7), i.e., [3, 4, 5, 6]. + >>> ds = MyIterableDataset(start=3, end=7) + + >>> # Single-process loading + >>> print(list(torch.utils.data.DataLoader(ds, num_workers=0))) + [tensor([3]), tensor([4]), tensor([5]), tensor([6])] + + >>> # xdoctest: +REQUIRES(POSIX) + >>> # Multi-process loading with two worker processes + >>> # Worker 0 fetched [3, 4]. Worker 1 fetched [5, 6]. + >>> # xdoctest: +IGNORE_WANT("non deterministic") + >>> print(list(torch.utils.data.DataLoader(ds, num_workers=2))) + [tensor([3]), tensor([5]), tensor([4]), tensor([6])] + + >>> # With even more workers + >>> # xdoctest: +IGNORE_WANT("non deterministic") + >>> print(list(torch.utils.data.DataLoader(ds, num_workers=12))) + [tensor([3]), tensor([5]), tensor([4]), tensor([6])] + + Example 2: splitting workload across all workers using :attr:`worker_init_fn`:: + + >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_DATALOADER) + >>> class MyIterableDataset(torch.utils.data.IterableDataset): + ... def __init__(self, start, end): + ... super(MyIterableDataset).__init__() + ... assert end > start, "this example only works with end >= start" + ... self.start = start + ... self.end = end + ... + ... def __iter__(self): + ... return iter(range(self.start, self.end)) + ... + >>> # should give same set of data as range(3, 7), i.e., [3, 4, 5, 6]. + >>> ds = MyIterableDataset(start=3, end=7) + + >>> # Single-process loading + >>> print(list(torch.utils.data.DataLoader(ds, num_workers=0))) + [3, 4, 5, 6] + >>> + >>> # Directly doing multi-process loading yields duplicate data + >>> print(list(torch.utils.data.DataLoader(ds, num_workers=2))) + [3, 3, 4, 4, 5, 5, 6, 6] + + >>> # Define a `worker_init_fn` that configures each dataset copy differently + >>> def worker_init_fn(worker_id): + ... worker_info = torch.utils.data.get_worker_info() + ... dataset = worker_info.dataset # the dataset copy in this worker process + ... overall_start = dataset.start + ... overall_end = dataset.end + ... # configure the dataset to only process the split workload + ... per_worker = int(math.ceil((overall_end - overall_start) / float(worker_info.num_workers))) + ... worker_id = worker_info.id + ... dataset.start = overall_start + worker_id * per_worker + ... dataset.end = min(dataset.start + per_worker, overall_end) + ... + + >>> # Multi-process loading with the custom `worker_init_fn` + >>> # Worker 0 fetched [3, 4]. Worker 1 fetched [5, 6]. + >>> print(list(torch.utils.data.DataLoader(ds, num_workers=2, worker_init_fn=worker_init_fn))) + [3, 5, 4, 6] + + >>> # With even more workers + >>> print(list(torch.utils.data.DataLoader(ds, num_workers=12, worker_init_fn=worker_init_fn))) + [3, 4, 5, 6] + """ + + def __add__(self, other: Dataset[_T_co]): + return ChainDataset([self, other]) + + # No `def __len__(self)` default? Subclasses raise `TypeError` when needed. + # See NOTE [ Lack of Default `__len__` in Python Abstract Base Classes ] + + +class TensorDataset(Dataset[tuple[Tensor, ...]]): + r"""Dataset wrapping tensors. + + Each sample will be retrieved by indexing tensors along the first dimension. + + Args: + *tensors (Tensor): tensors that have the same size of the first dimension. + """ + + tensors: tuple[Tensor, ...] + + def __init__(self, *tensors: Tensor) -> None: + if any(tensors[0].size(0) != tensor.size(0) for tensor in tensors): + raise AssertionError("Size mismatch between tensors") + self.tensors = tensors + + def __getitem__(self, index): + return tuple(tensor[index] for tensor in self.tensors) + + def __len__(self) -> int: + return self.tensors[0].size(0) + + +class StackDataset(Dataset[_T_stack]): + r"""Dataset as a stacking of multiple datasets. + + This class is useful to assemble different parts of complex input data, given as datasets. + + Example: + >>> # xdoctest: +SKIP + >>> images = ImageDataset() + >>> texts = TextDataset() + >>> tuple_stack = StackDataset(images, texts) + >>> tuple_stack[0] == (images[0], texts[0]) + >>> dict_stack = StackDataset(image=images, text=texts) + >>> dict_stack[0] == {"image": images[0], "text": texts[0]} + + Args: + *args (Dataset): Datasets for stacking returned as tuple. + **kwargs (Dataset): Datasets for stacking returned as dict. + """ + + datasets: tuple | dict + + def __init__(self, *args: Dataset[_T_co], **kwargs: Dataset[_T_co]) -> None: + if args: + if kwargs: + raise ValueError( + "Supported either ``tuple``- (via ``args``) or" + "``dict``- (via ``kwargs``) like input/output, but both types are given." + ) + self._length = len(args[0]) # type: ignore[arg-type] + if any(self._length != len(dataset) for dataset in args): # type: ignore[arg-type] + raise ValueError("Size mismatch between datasets") + self.datasets = args + elif kwargs: + tmp = list(kwargs.values()) + self._length = len(tmp[0]) # type: ignore[arg-type] + if any(self._length != len(dataset) for dataset in tmp): # type: ignore[arg-type] + raise ValueError("Size mismatch between datasets") + self.datasets = kwargs + else: + raise ValueError("At least one dataset should be passed") + + def __getitem__(self, index): + if isinstance(self.datasets, dict): + return {k: dataset[index] for k, dataset in self.datasets.items()} + return tuple(dataset[index] for dataset in self.datasets) + + def __getitems__(self, indices: list): + # add batched sampling support when parent datasets supports it. + if isinstance(self.datasets, dict): + dict_batch: list[_T_dict] = [{} for _ in indices] + for k, dataset in self.datasets.items(): + if callable(getattr(dataset, "__getitems__", None)): + items = dataset.__getitems__(indices) # type: ignore[attr-defined] + if len(items) != len(indices): + raise ValueError( + "Nested dataset's output size mismatch." + f" Expected {len(indices)}, got {len(items)}" + ) + for data, d_sample in zip(items, dict_batch, strict=True): + d_sample[k] = data + else: + for idx, d_sample in zip(indices, dict_batch, strict=True): + d_sample[k] = dataset[idx] + return dict_batch + + # tuple data + list_batch: list[list] = [[] for _ in indices] + for dataset in self.datasets: + if callable(getattr(dataset, "__getitems__", None)): + items = dataset.__getitems__(indices) # type: ignore[attr-defined] + if len(items) != len(indices): + raise ValueError( + "Nested dataset's output size mismatch." + f" Expected {len(indices)}, got {len(items)}" + ) + for data, t_sample in zip(items, list_batch, strict=True): + t_sample.append(data) + else: + for idx, t_sample in zip(indices, list_batch, strict=True): + t_sample.append(dataset[idx]) + tuple_batch: list[_T_tuple] = [tuple(sample) for sample in list_batch] + return tuple_batch + + def __len__(self) -> int: + return self._length + + +class ConcatDataset(Dataset[_T_co]): + r"""Dataset as a concatenation of multiple datasets. + + This class is useful to assemble different existing datasets. + + Args: + datasets (sequence): List of datasets to be concatenated + """ + + datasets: list[Dataset[_T_co]] + cumulative_sizes: list[int] + + @staticmethod + def cumsum(sequence): + r, s = [], 0 + for e in sequence: + l = len(e) + r.append(l + s) + s += l + return r + + def __init__(self, datasets: Iterable[Dataset]) -> None: + super().__init__() + self.datasets = list(datasets) + if len(self.datasets) == 0: + raise AssertionError("datasets should not be an empty iterable") + for d in self.datasets: + if isinstance(d, IterableDataset): + raise AssertionError("ConcatDataset does not support IterableDataset") + self.cumulative_sizes = self.cumsum(self.datasets) + + def __len__(self) -> int: + return self.cumulative_sizes[-1] + + def __getitem__(self, idx): + if idx < 0: + if -idx > len(self): + raise ValueError( + "absolute value of index should not exceed dataset length" + ) + idx = len(self) + idx + dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx) + if dataset_idx == 0: + sample_idx = idx + else: + sample_idx = idx - self.cumulative_sizes[dataset_idx - 1] + return self.datasets[dataset_idx][sample_idx] + + @property + @deprecated( + "`cummulative_sizes` attribute is renamed to `cumulative_sizes`", + category=FutureWarning, + ) + def cummulative_sizes(self): + return self.cumulative_sizes + + +class ChainDataset(IterableDataset): + r"""Dataset for chaining multiple :class:`IterableDataset` s. + + This class is useful to assemble different existing dataset streams. The + chaining operation is done on-the-fly, so concatenating large-scale + datasets with this class will be efficient. + + Args: + datasets (iterable of IterableDataset): datasets to be chained together + """ + + def __init__(self, datasets: Iterable[Dataset]) -> None: + super().__init__() + self.datasets = datasets + + def __iter__(self): + for d in self.datasets: + if not isinstance(d, IterableDataset): + raise AssertionError("ChainDataset only supports IterableDataset") + yield from d + + def __len__(self) -> int: + total = 0 + for d in self.datasets: + if not isinstance(d, IterableDataset): + raise AssertionError("ChainDataset only supports IterableDataset") + total += len(d) # type: ignore[arg-type] + return total + + +class Subset(Dataset[_T_co]): + r""" + Subset of a dataset at specified indices. + + .. note:: + When subclassing `Subset` and overriding `__getitem__`, you **must** also + override `__getitems__` to ensure `DataLoader` works correctly with your + custom logic. If you override only `__getitem__`, a `NotImplementedError` + will be raised when using `DataLoader`. + + A simple implementation of `__getitems__` can delegate to `__getitem__`: + + .. code-block:: python + + def __getitems__(self, indices): + return [self.__getitem__(idx) for idx in indices] + + For better performance, consider implementing batch-aware logic in + `__getitems__` instead of calling `__getitem__` multiple times. + + Args: + dataset (Dataset): The whole Dataset + indices (sequence): Indices in the whole set selected for subset + """ + + dataset: Dataset[_T_co] + indices: Sequence[int] + + def __init__(self, dataset: Dataset[_T_co], indices: Sequence[int]) -> None: + self.dataset = dataset + self.indices = indices + + # Check if __getitem__ is overridden but __getitems__ is not + if ( + type(self).__getitem__ is not Subset.__getitem__ + and type(self).__getitems__ is Subset.__getitems__ + ): + raise NotImplementedError( + f"{type(self).__name__} overrides __getitem__ but not __getitems__. " + "When subclassing Subset and overriding __getitem__, you must also override " + "__getitems__ to ensure DataLoader works correctly with your custom logic. " + "A simple implementation:\n\n" + "def __getitems__(self, indices):\n" + " return [self.__getitem__(idx) for idx in indices]" + ) + + def __getitem__(self, idx): + if isinstance(idx, list): + return self.dataset[[self.indices[i] for i in idx]] + return self.dataset[self.indices[idx]] + + def __getitems__(self, indices: list[int]) -> list[_T_co]: + # add batched sampling support when parent dataset supports it. + # see torch.utils.data._utils.fetch._MapDatasetFetcher + if callable(getattr(self.dataset, "__getitems__", None)): + return self.dataset.__getitems__([self.indices[idx] for idx in indices]) # type: ignore[attr-defined] + else: + return [self.dataset[self.indices[idx]] for idx in indices] + + def __len__(self) -> int: + return len(self.indices) + + +def random_split( + dataset: Dataset[_T], + lengths: Sequence[int | float], + generator: Generator | None = default_generator, +) -> list[Subset[_T]]: + r""" + Randomly split a dataset into non-overlapping new datasets of given lengths. + + If a list of fractions that sum up to 1 is given, + the lengths will be computed automatically as + floor(frac * len(dataset)) for each fraction provided. + + After computing the lengths, if there are any remainders, 1 count will be + distributed in round-robin fashion to the lengths + until there are no remainders left. + + Optionally fix the generator for reproducible results, e.g.: + + Example: + >>> # xdoctest: +SKIP + >>> generator1 = torch.Generator().manual_seed(42) + >>> generator2 = torch.Generator().manual_seed(42) + >>> random_split(range(10), [3, 7], generator=generator1) + >>> random_split(range(30), [0.3, 0.3, 0.4], generator=generator2) + + Args: + dataset (Dataset): Dataset to be split + lengths (sequence): lengths or fractions of splits to be produced + generator (Generator): Generator used for the random permutation. + """ + if math.isclose(sum(lengths), 1) and sum(lengths) <= 1: + subset_lengths: list[int] = [] + for i, frac in enumerate(lengths): + if frac < 0 or frac > 1: + raise ValueError(f"Fraction at index {i} is not between 0 and 1") + n_items_in_split = math.floor(len(dataset) * frac) # type: ignore[arg-type] + subset_lengths.append(n_items_in_split) + remainder = len(dataset) - sum(subset_lengths) # type: ignore[arg-type] + # add 1 to all the lengths in round-robin fashion until the remainder is 0 + for i in range(remainder): + idx_to_add_at = i % len(subset_lengths) + subset_lengths[idx_to_add_at] += 1 + lengths = subset_lengths + for i, length in enumerate(lengths): + if length == 0: + warnings.warn( + f"Length of split at index {i} is 0. " + f"This might result in an empty dataset.", + stacklevel=2, + ) + + # Cannot verify that dataset is Sized + if sum(lengths) != len(dataset): # type: ignore[arg-type] + raise ValueError( + "Sum of input lengths does not equal the length of the input dataset!" + ) + + indices = randperm(sum(lengths), generator=generator).tolist() # type: ignore[arg-type, call-overload] + lengths = cast(Sequence[int], lengths) + return [ + Subset(dataset, indices[offset - length : offset]) + for offset, length in zip(itertools.accumulate(lengths), lengths, strict=True) + ] diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/distributed.py b/.venv/lib/python3.12/site-packages/torch/utils/data/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..5179d7698ffee0f2acda62a2b2073df176aae794 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/distributed.py @@ -0,0 +1,157 @@ +import math +from collections.abc import Iterator +from typing import TypeVar + +import torch +import torch.distributed as dist +from torch.utils.data.dataset import Dataset +from torch.utils.data.sampler import Sampler + + +__all__ = ["DistributedSampler"] + + +_T_co = TypeVar("_T_co", covariant=True) + + +class DistributedSampler(Sampler[_T_co]): + r"""Sampler that restricts data loading to a subset of the dataset. + + It is especially useful in conjunction with + :class:`torch.nn.parallel.DistributedDataParallel`. In such a case, each + process can pass a :class:`~torch.utils.data.DistributedSampler` instance as a + :class:`~torch.utils.data.DataLoader` sampler, and load a subset of the + original dataset that is exclusive to it. + + .. note:: + Dataset is assumed to be of constant size and that any instance of it always + returns the same elements in the same order. + + Args: + dataset: Dataset used for sampling. + num_replicas (int, optional): Number of processes participating in + distributed training. By default, :attr:`world_size` is retrieved from the + current distributed group. + rank (int, optional): Rank of the current process within :attr:`num_replicas`. + By default, :attr:`rank` is retrieved from the current distributed + group. + shuffle (bool, optional): If ``True`` (default), sampler will shuffle the + indices. + seed (int, optional): random seed used to shuffle the sampler if + :attr:`shuffle=True`. This number should be identical across all + processes in the distributed group. Default: ``0``. + drop_last (bool, optional): if ``True``, then the sampler will drop the + tail of the data to make it evenly divisible across the number of + replicas. If ``False``, the sampler will add extra indices to make + the data evenly divisible across the replicas. Default: ``False``. + + .. warning:: + In distributed mode, calling the :meth:`set_epoch` method at + the beginning of each epoch **before** creating the :class:`DataLoader` iterator + is necessary to make shuffling work properly across multiple epochs. Otherwise, + the same ordering will be always used. + + Example:: + + >>> # xdoctest: +SKIP + >>> sampler = DistributedSampler(dataset) if is_distributed else None + >>> loader = DataLoader(dataset, shuffle=(sampler is None), + ... sampler=sampler) + >>> for epoch in range(start_epoch, n_epochs): + ... if is_distributed: + ... sampler.set_epoch(epoch) + ... train(loader) + """ + + def __init__( + self, + dataset: Dataset, + num_replicas: int | None = None, + rank: int | None = None, + shuffle: bool = True, + seed: int = 0, + drop_last: bool = False, + ) -> None: + if num_replicas is None: + if not dist.is_available(): + raise RuntimeError("Requires distributed package to be available") + num_replicas = dist.get_world_size() + if rank is None: + if not dist.is_available(): + raise RuntimeError("Requires distributed package to be available") + rank = dist.get_rank() + if rank >= num_replicas or rank < 0: + raise ValueError( + f"Invalid rank {rank}, rank should be in the interval [0, {num_replicas - 1}]" + ) + self.dataset = dataset + self.num_replicas = num_replicas + self.rank = rank + self.epoch = 0 + self.drop_last = drop_last + # If the dataset length is evenly divisible by # of replicas, then there + # is no need to drop any data, since the dataset will be split equally. + if self.drop_last and len(self.dataset) % self.num_replicas != 0: # type: ignore[arg-type] + # Split to nearest available length that is evenly divisible. + # This is to ensure each rank receives the same amount of data when + # using this Sampler. + self.num_samples = math.ceil( + (len(self.dataset) - self.num_replicas) / self.num_replicas # type: ignore[arg-type] + ) + else: + self.num_samples = math.ceil(len(self.dataset) / self.num_replicas) # type: ignore[arg-type] + self.total_size = self.num_samples * self.num_replicas + self.shuffle = shuffle + self.seed = seed + + def __iter__(self) -> Iterator[_T_co]: + if self.shuffle: + # deterministically shuffle based on epoch and seed + g = torch.Generator() + g.manual_seed(self.seed + self.epoch) + indices = torch.randperm(len(self.dataset), generator=g).tolist() # type: ignore[arg-type] + else: + indices = list(range(len(self.dataset))) # type: ignore[arg-type] + + if not self.drop_last: + # add extra samples to make it evenly divisible + padding_size = self.total_size - len(indices) + if padding_size <= len(indices): + indices += indices[:padding_size] + else: + indices += (indices * math.ceil(padding_size / len(indices)))[ + :padding_size + ] + else: + # remove tail of data to make it evenly divisible. + indices = indices[: self.total_size] + if len(indices) != self.total_size: + raise AssertionError( + f"Number of indices ({len(indices)}) does not match total_size ({self.total_size})" + ) + + # subsample + indices = indices[self.rank : self.total_size : self.num_replicas] + if len(indices) != self.num_samples: + raise AssertionError( + f"Number of subsampled indices ({len(indices)}) does not match num_samples ({self.num_samples})" + ) + + # pyrefly: ignore [bad-return] + return iter(indices) + + def __len__(self) -> int: + return self.num_samples + + def set_epoch(self, epoch: int) -> None: + r""" + Set the epoch for this sampler. + + When :attr:`shuffle=True`, this ensures all replicas + use a different random ordering for each epoch. Otherwise, the next iteration of this + sampler will yield the same ordering. + + Args: + epoch (int): Epoch number. + """ + self.epoch = epoch diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/graph.py b/.venv/lib/python3.12/site-packages/torch/utils/data/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..341146281a3280ed5dc66dbeb968f7fe24db6401 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/graph.py @@ -0,0 +1,163 @@ +# mypy: allow-untyped-defs +import io +import pickle +import warnings +from collections.abc import Collection + +from torch.utils._import_utils import dill_available +from torch.utils.data.datapipes.datapipe import IterDataPipe, MapDataPipe + + +__all__ = ["traverse", "traverse_dps"] + +DataPipe = IterDataPipe | MapDataPipe +# pyrefly: ignore [invalid-type-alias] +DataPipeGraph = dict[int, tuple[DataPipe, "DataPipeGraph"]] + + +def _stub_unpickler() -> str: + return "STUB" + + +# TODO(VitalyFedyunin): Make sure it works without dill module installed +def _list_connected_datapipes( + scan_obj: DataPipe, only_datapipe: bool, cache: set[int] +) -> list[DataPipe]: + f = io.BytesIO() + p = pickle.Pickler( + f + ) # Not going to work for lambdas, but dill infinite loops on typing and can't be used as is + if dill_available(): + from dill import Pickler as dill_Pickler + + d = dill_Pickler(f) + else: + d = None + + captured_connections = [] + + def getstate_hook(ori_state): + state = None + if isinstance(ori_state, dict): + state = {} + for k, v in ori_state.items(): + if isinstance(v, (IterDataPipe, MapDataPipe, Collection)): + state[k] = v + elif isinstance(ori_state, (tuple, list)): + state = [] # type: ignore[assignment] + for v in ori_state: + if isinstance(v, (IterDataPipe, MapDataPipe, Collection)): + state.append(v) # type: ignore[attr-defined] + elif isinstance(ori_state, (IterDataPipe, MapDataPipe, Collection)): + state = ori_state # type: ignore[assignment] + return state + + def reduce_hook(obj): + if obj == scan_obj or id(obj) in cache: + raise NotImplementedError + else: + captured_connections.append(obj) + # Adding id to remove duplicate DataPipe serialized at the same level + cache.add(id(obj)) + return _stub_unpickler, () + + datapipe_classes: tuple[type[DataPipe]] = (IterDataPipe, MapDataPipe) # type: ignore[assignment] + + try: + for cls in datapipe_classes: + cls.set_reduce_ex_hook(reduce_hook) + if only_datapipe: + cls.set_getstate_hook(getstate_hook) + try: + p.dump(scan_obj) + except (pickle.PickleError, AttributeError, TypeError): + if dill_available(): + # pyrefly: ignore [missing-attribute] + d.dump(scan_obj) + else: + raise + finally: + for cls in datapipe_classes: + cls.set_reduce_ex_hook(None) + if only_datapipe: + cls.set_getstate_hook(None) + if dill_available(): + from dill import extend as dill_extend + + dill_extend(False) # Undo change to dispatch table + return captured_connections + + +def traverse_dps(datapipe: DataPipe) -> DataPipeGraph: + r""" + Traverse the DataPipes and their attributes to extract the DataPipe graph. + + This only looks into the attribute from each DataPipe that is either a + DataPipe and a Python collection object such as ``list``, ``tuple``, + ``set`` and ``dict``. + + Args: + datapipe: the end DataPipe of the graph + Returns: + A graph represented as a nested dictionary, where keys are ids of DataPipe instances + and values are tuples of DataPipe instance and the sub-graph + """ + cache: set[int] = set() + return _traverse_helper(datapipe, only_datapipe=True, cache=cache) + + +def traverse(datapipe: DataPipe, only_datapipe: bool | None = None) -> DataPipeGraph: + r""" + Traverse the DataPipes and their attributes to extract the DataPipe graph. + + [Deprecated] + When ``only_dataPipe`` is specified as ``True``, it would only look into the + attribute from each DataPipe that is either a DataPipe and a Python collection object + such as ``list``, ``tuple``, ``set`` and ``dict``. + + Note: + This function is deprecated. Please use `traverse_dps` instead. + + Args: + datapipe: the end DataPipe of the graph + only_datapipe: If ``False`` (default), all attributes of each DataPipe are traversed. + This argument is deprecated and will be removed after the next release. + Returns: + A graph represented as a nested dictionary, where keys are ids of DataPipe instances + and values are tuples of DataPipe instance and the sub-graph + """ + msg = ( + "`traverse` function is deprecated and will be removed after 1.13. " + "Please use `traverse_dps` instead." + ) + if not only_datapipe: + msg += " And, the behavior will be changed to the equivalent of `only_datapipe=True`." + warnings.warn(msg, FutureWarning, stacklevel=2) + if only_datapipe is None: + only_datapipe = False + cache: set[int] = set() + return _traverse_helper(datapipe, only_datapipe, cache) + + +# Add cache here to prevent infinite recursion on DataPipe +def _traverse_helper( + datapipe: DataPipe, only_datapipe: bool, cache: set[int] +) -> DataPipeGraph: + if not isinstance(datapipe, (IterDataPipe, MapDataPipe)): + raise RuntimeError( + f"Expected `IterDataPipe` or `MapDataPipe`, but {type(datapipe)} is found" + ) + + dp_id = id(datapipe) + if dp_id in cache: + return {} + cache.add(dp_id) + # Using cache.copy() here is to prevent the same DataPipe pollutes the cache on different paths + items = _list_connected_datapipes(datapipe, only_datapipe, cache.copy()) + d: DataPipeGraph = {dp_id: (datapipe, {})} + for item in items: + # Using cache.copy() here is to prevent recursion on a single path rather than global graph + # Single DataPipe can present multiple times in different paths in graph + # pyrefly: ignore [no-matching-overload] + d[dp_id][1].update(_traverse_helper(item, only_datapipe, cache.copy())) + return d diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/graph_settings.py b/.venv/lib/python3.12/site-packages/torch/utils/data/graph_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..03096398a6738b29c22aad044caaf16e4c45a7d0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/graph_settings.py @@ -0,0 +1,173 @@ +# mypy: allow-untyped-defs +import inspect +import warnings +from typing import Any +from typing_extensions import deprecated + +import torch +from torch.utils.data.datapipes.iter.sharding import ( + _ShardingIterDataPipe, + SHARDING_PRIORITIES, +) +from torch.utils.data.graph import DataPipe, DataPipeGraph, traverse_dps + + +__all__ = [ + "apply_random_seed", + "apply_sharding", + "apply_shuffle_seed", + "apply_shuffle_settings", + "get_all_graph_pipes", +] + + +def get_all_graph_pipes(graph: DataPipeGraph) -> list[DataPipe]: + return _get_all_graph_pipes_helper(graph, set()) + + +def _get_all_graph_pipes_helper( + graph: DataPipeGraph, id_cache: set[int] +) -> list[DataPipe]: + results: list[DataPipe] = [] + for dp_id, (datapipe, sub_graph) in graph.items(): + if dp_id in id_cache: + continue + id_cache.add(dp_id) + results.append(datapipe) + results.extend(_get_all_graph_pipes_helper(sub_graph, id_cache)) + return results + + +def _is_sharding_datapipe(datapipe: DataPipe) -> bool: + return isinstance(datapipe, _ShardingIterDataPipe) or ( + hasattr(datapipe, "apply_sharding") + and inspect.ismethod(datapipe.apply_sharding) + ) + + +def apply_sharding( + datapipe: DataPipe, + num_of_instances: int, + instance_id: int, + sharding_group=SHARDING_PRIORITIES.DEFAULT, +) -> DataPipe: + r""" + Apply dynamic sharding over the ``sharding_filter`` DataPipe that has a method ``apply_sharding``. + + RuntimeError will be raised when multiple ``sharding_filter`` are presented in the same branch. + """ + graph = traverse_dps(datapipe) + + def _helper(graph, prev_applied=None) -> None: + for dp, sub_graph in graph.values(): + applied = None + if _is_sharding_datapipe(dp): + if prev_applied is not None: + raise RuntimeError( + "Sharding twice on a single pipeline is likely unintended and will cause data loss. " + f"Sharding already applied to {prev_applied} while trying to apply to {dp}" + ) + # For BC, only provide sharding_group if accepted + sig = inspect.signature(dp.apply_sharding) + if len(sig.parameters) < 3: + dp.apply_sharding(num_of_instances, instance_id) + else: + dp.apply_sharding( + num_of_instances, instance_id, sharding_group=sharding_group + ) + applied = dp + if applied is None: + applied = prev_applied + _helper(sub_graph, applied) + + _helper(graph) + + return datapipe + + +def _is_shuffle_datapipe(datapipe: DataPipe) -> bool: + return ( + hasattr(datapipe, "set_shuffle") + and hasattr(datapipe, "set_seed") + and inspect.ismethod(datapipe.set_shuffle) + and inspect.ismethod(datapipe.set_seed) + ) + + +def apply_shuffle_settings(datapipe: DataPipe, shuffle: bool | None = None) -> DataPipe: + r""" + Traverse the graph of ``DataPipes`` to find and set shuffle attribute. + + Apply the method to each `DataPipe` that has APIs of ``set_shuffle`` + and ``set_seed``. + + Args: + datapipe: DataPipe that needs to set shuffle attribute + shuffle: Shuffle option (default: ``None`` and no-op to the graph) + """ + if shuffle is None: + return datapipe + + graph = traverse_dps(datapipe) + all_pipes = get_all_graph_pipes(graph) + shufflers = [pipe for pipe in all_pipes if _is_shuffle_datapipe(pipe)] + if not shufflers and shuffle: + warnings.warn( + "`shuffle=True` was set, but the datapipe does not contain a `Shuffler`. Adding one at the end. " + "Be aware that the default buffer size might not be sufficient for your task.", + stacklevel=2, + ) + datapipe = datapipe.shuffle() + shufflers = [ + datapipe, + ] + + for shuffler in shufflers: + shuffler.set_shuffle(shuffle) + + return datapipe + + +@deprecated( + "`apply_shuffle_seed` is deprecated since 1.12 and will be removed in the future releases. " + "Please use `apply_random_seed` instead.", + category=FutureWarning, +) +def apply_shuffle_seed(datapipe: DataPipe, rng: Any) -> DataPipe: + return apply_random_seed(datapipe, rng) + + +def _is_random_datapipe(datapipe: DataPipe) -> bool: + return hasattr(datapipe, "set_seed") and inspect.ismethod(datapipe.set_seed) + + +def apply_random_seed(datapipe: DataPipe, rng: torch.Generator) -> DataPipe: + r""" + Traverse the graph of ``DataPipes`` to find random ``DataPipe`` with an API of ``set_seed``. + + Then set the random seed based on the provided RNG to those ``DataPipe``. + + Args: + datapipe: DataPipe that needs to set randomness + rng: Random number generator to generate random seeds + """ + graph = traverse_dps(datapipe) + all_pipes = get_all_graph_pipes(graph) + # Using a set to track id of DataPipe to prevent setting randomness per DataPipe more than once. + # And, `id` is used in case of unhashable DataPipe + cache = set() + random_datapipes = [] + for pipe in all_pipes: + if id(pipe) in cache: + continue + if _is_random_datapipe(pipe): + random_datapipes.append(pipe) + cache.add(id(pipe)) + + for pipe in random_datapipes: + random_seed = int( + torch.empty((), dtype=torch.int64).random_(generator=rng).item() + ) + pipe.set_seed(random_seed) + + return datapipe diff --git a/.venv/lib/python3.12/site-packages/torch/utils/data/sampler.py b/.venv/lib/python3.12/site-packages/torch/utils/data/sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..aa13bb8e0a3e146bd7bfbc766fdfcb822efa9313 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/data/sampler.py @@ -0,0 +1,354 @@ +# mypy: allow-untyped-defs +import itertools +from collections.abc import Iterable, Iterator, Sequence, Sized +from typing import Generic, TypeVar + +import torch + + +# Note: For benchmarking changes to samplers, see: +# /benchmarks/data/samplers_bench.py +# This benchmark compares the performance of different sampler implementations +# and can be used to evaluate the impact of optimizations. + + +__all__ = [ + "BatchSampler", + "RandomSampler", + "Sampler", + "SequentialSampler", + "SubsetRandomSampler", + "WeightedRandomSampler", +] + + +_T_co = TypeVar("_T_co", covariant=True) + + +class Sampler(Generic[_T_co]): + r"""Base class for all Samplers. + + Every Sampler subclass has to provide an :meth:`__iter__` method, providing a + way to iterate over indices or lists of indices (batches) of dataset elements, + and may provide a :meth:`__len__` method that returns the length of the returned iterators. + + Example: + >>> # xdoctest: +SKIP + >>> class AccedingSequenceLengthSampler(Sampler[int]): + >>> def __init__(self, data: List[str]) -> None: + >>> self.data = data + >>> + >>> def __len__(self) -> int: + >>> return len(self.data) + >>> + >>> def __iter__(self) -> Iterator[int]: + >>> sizes = torch.tensor([len(x) for x in self.data]) + >>> yield from torch.argsort(sizes).tolist() + >>> + >>> class AccedingSequenceLengthBatchSampler(Sampler[List[int]]): + >>> def __init__(self, data: List[str], batch_size: int) -> None: + >>> self.data = data + >>> self.batch_size = batch_size + >>> + >>> def __len__(self) -> int: + >>> return (len(self.data) + self.batch_size - 1) // self.batch_size + >>> + >>> def __iter__(self) -> Iterator[List[int]]: + >>> sizes = torch.tensor([len(x) for x in self.data]) + >>> for batch in torch.chunk(torch.argsort(sizes), len(self)): + >>> yield batch.tolist() + + .. note:: The :meth:`__len__` method isn't strictly required by + :class:`~torch.utils.data.DataLoader`, but is expected in any + calculation involving the length of a :class:`~torch.utils.data.DataLoader`. + """ + + def __iter__(self) -> Iterator[_T_co]: + raise NotImplementedError + + # NOTE [ Lack of Default `__len__` in Python Abstract Base Classes ] + # + # Many times we have an abstract class representing a collection/iterable of + # data, e.g., `torch.utils.data.Sampler`, with its subclasses optionally + # implementing a `__len__` method. In such cases, we must make sure to not + # provide a default implementation, because both straightforward default + # implementations have their issues: + # + # + `return NotImplemented`: + # Calling `len(subclass_instance)` raises: + # TypeError: 'NotImplementedType' object cannot be interpreted as an integer + # + # + `raise NotImplementedError`: + # This prevents triggering some fallback behavior. E.g., the built-in + # `list(X)` tries to call `len(X)` first, and executes a different code + # path if the method is not found or `NotImplemented` is returned, while + # raising a `NotImplementedError` will propagate and make the call fail + # where it could have used `__iter__` to complete the call. + # + # Thus, the only two sensible things to do are + # + # + **not** provide a default `__len__`. + # + # + raise a `TypeError` instead, which is what Python uses when users call + # a method that is not defined on an object. + # (@ssnl verifies that this works on at least Python 3.7.) + + +class SequentialSampler(Sampler[int]): + r"""Samples elements sequentially, always in the same order. + + Args: + data_source (Sized): data source to sample from. Must implement __len__. + """ + + data_source: Sized + + def __init__(self, data_source: Sized) -> None: + self.data_source = data_source + + def __iter__(self) -> Iterator[int]: + return iter(range(len(self.data_source))) + + def __len__(self) -> int: + return len(self.data_source) + + +class RandomSampler(Sampler[int]): + r"""Samples elements randomly. If without replacement, then sample from a shuffled dataset. + + If with replacement, then user can specify :attr:`num_samples` to draw. + + Args: + data_source (Sized): data source to sample from. Must implement __len__. + replacement (bool): samples are drawn on-demand with replacement if ``True``, default=``False`` + num_samples (int): number of samples to draw, default=`len(dataset)`. + generator (Generator): Generator used in sampling. + """ + + data_source: Sized + replacement: bool + + def __init__( + self, + data_source: Sized, + replacement: bool = False, + num_samples: int | None = None, + generator=None, + ) -> None: + self.data_source = data_source + self.replacement = replacement + self._num_samples = num_samples + self.generator = generator + + if not isinstance(self.replacement, bool): + raise TypeError( + f"replacement should be a boolean value, but got replacement={self.replacement}" + ) + + if not isinstance(self.num_samples, int) or self.num_samples <= 0: + raise ValueError( + f"num_samples should be a positive integer value, but got num_samples={self.num_samples}" + ) + + @property + def num_samples(self) -> int: + # dataset size might change at runtime + if self._num_samples is None: + return len(self.data_source) + return self._num_samples + + def __iter__(self) -> Iterator[int]: + n = len(self.data_source) + if self.generator is None: + seed = int(torch.empty((), dtype=torch.int64).random_().item()) + generator = torch.Generator() + generator.manual_seed(seed) + else: + generator = self.generator + + if self.replacement: + for _ in range(self.num_samples // 32): + yield from torch.randint( + high=n, size=(32,), dtype=torch.int64, generator=generator + ).tolist() + yield from torch.randint( + high=n, + size=(self.num_samples % 32,), + dtype=torch.int64, + generator=generator, + ).tolist() + else: + for _ in range(self.num_samples // n): + yield from torch.randperm(n, generator=generator).tolist() + yield from torch.randperm(n, generator=generator).tolist()[ + : self.num_samples % n + ] + + def __len__(self) -> int: + return self.num_samples + + +class SubsetRandomSampler(Sampler[int]): + r"""Samples elements randomly from a given list of indices, without replacement. + + Args: + indices (sequence): a sequence of indices + generator (Generator): Generator used in sampling. + """ + + indices: Sequence[int] + + def __init__(self, indices: Sequence[int], generator=None) -> None: + self.indices = indices + self.generator = generator + + def __iter__(self) -> Iterator[int]: + for i in torch.randperm(len(self.indices), generator=self.generator).tolist(): + yield self.indices[i] + + def __len__(self) -> int: + return len(self.indices) + + +class WeightedRandomSampler(Sampler[int]): + r"""Samples elements from ``[0,..,len(weights)-1]`` with given probabilities (weights). + + Args: + weights (sequence) : a sequence of weights, not necessary summing up to one + num_samples (int): number of samples to draw + replacement (bool): if ``True``, samples are drawn with replacement. + If not, they are drawn without replacement, which means that when a + sample index is drawn for a row, it cannot be drawn again for that row. + generator (Generator): Generator used in sampling. + + Example: + >>> # xdoctest: +IGNORE_WANT("non-deterministic") + >>> list( + ... WeightedRandomSampler( + ... [0.1, 0.9, 0.4, 0.7, 3.0, 0.6], 5, replacement=True + ... ) + ... ) + [4, 4, 1, 4, 5] + >>> list( + ... WeightedRandomSampler( + ... [0.9, 0.4, 0.05, 0.2, 0.3, 0.1], 5, replacement=False + ... ) + ... ) + [0, 1, 4, 3, 2] + """ + + weights: torch.Tensor + num_samples: int + replacement: bool + + def __init__( + self, + weights: Sequence[float], + num_samples: int, + replacement: bool = True, + generator=None, + ) -> None: + if ( + not isinstance(num_samples, int) + or isinstance(num_samples, bool) + or num_samples <= 0 + ): + raise ValueError( + f"num_samples should be a positive integer value, but got num_samples={num_samples}" + ) + if not isinstance(replacement, bool): + raise ValueError( + f"replacement should be a boolean value, but got replacement={replacement}" + ) + + weights_tensor = torch.as_tensor(weights, dtype=torch.double) + if len(weights_tensor.shape) != 1: + raise ValueError( + "weights should be a 1d sequence but given " + f"weights have shape {tuple(weights_tensor.shape)}" + ) + + self.weights = weights_tensor + self.num_samples = num_samples + self.replacement = replacement + self.generator = generator + + def __iter__(self) -> Iterator[int]: + rand_tensor = torch.multinomial( + self.weights, self.num_samples, self.replacement, generator=self.generator + ) + yield from iter(rand_tensor.tolist()) + + def __len__(self) -> int: + return self.num_samples + + +class BatchSampler(Sampler[list[int]]): + r"""Wraps another sampler to yield a mini-batch of indices. + + Args: + sampler (Sampler or Iterable): Base sampler. Can be any iterable object + batch_size (int): Size of mini-batch. + drop_last (bool): If ``True``, the sampler will drop the last batch if + its size would be less than ``batch_size`` + + Example: + >>> list( + ... BatchSampler( + ... SequentialSampler(range(10)), batch_size=3, drop_last=False + ... ) + ... ) + [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] + >>> list( + ... BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=True) + ... ) + [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + """ + + def __init__( + self, + sampler: Sampler[int] | Iterable[int], + batch_size: int, + drop_last: bool, + ) -> None: + # Since collections.abc.Iterable does not check for `__getitem__`, which + # is one way for an object to be an iterable, we don't do an `isinstance` + # check here. + if ( + not isinstance(batch_size, int) + or isinstance(batch_size, bool) + or batch_size <= 0 + ): + raise ValueError( + f"batch_size should be a positive integer value, but got batch_size={batch_size}" + ) + if not isinstance(drop_last, bool): + raise ValueError( + f"drop_last should be a boolean value, but got drop_last={drop_last}" + ) + self.sampler = sampler + self.batch_size = batch_size + self.drop_last = drop_last + + def __iter__(self) -> Iterator[list[int]]: + sampler_iter = iter(self.sampler) + if self.drop_last: + # Create multiple references to the same iterator + args = [sampler_iter] * self.batch_size + for batch_droplast in zip(*args, strict=False): + yield [*batch_droplast] + else: + batch = [*itertools.islice(sampler_iter, self.batch_size)] + while batch: + yield batch + batch = [*itertools.islice(sampler_iter, self.batch_size)] + + def __len__(self) -> int: + # Can only be called if self.sampler has __len__ implemented + # We cannot enforce this condition, so we turn off typechecking for the + # implementation below. + # Somewhat related: see NOTE [ Lack of Default `__len__` in Python Abstract Base Classes ] + if self.drop_last: + return len(self.sampler) // self.batch_size # type: ignore[arg-type] + else: + return (len(self.sampler) + self.batch_size - 1) // self.batch_size # type: ignore[arg-type] diff --git a/.venv/lib/python3.12/site-packages/torch/utils/debug_log.py b/.venv/lib/python3.12/site-packages/torch/utils/debug_log.py new file mode 100644 index 0000000000000000000000000000000000000000..5ecf80a135d31cb632fc270b9078ce6d027d40bb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/debug_log.py @@ -0,0 +1,68 @@ +"""Compile-safe backward gradient logging for multiple tensors. + +``debug_grad_log`` logs gradient norms during backward for one or more tensors. +It is a leaf function with a ``register_multi_grad_hook`` that fires exactly +once when all requires_grad tensor inputs have their gradients computed. + +Example:: + + import torch + from torch.utils.debug_log import debug_grad_log + + x = torch.randn(4, requires_grad=True) + y = torch.randn(4, requires_grad=True) + z = x * 2 + y * 3 + + debug_grad_log(x, y) + + z.sum().backward() + # Logs: [rank 0][bwd] t0_grad_norm=... t1_grad_norm=... +""" + +import logging + +import torch +from torch._dynamo.decorators import leaf_function + + +__all__ = ["debug_grad_log"] + +log = logging.getLogger(__name__) + + +def _get_rank() -> int: + if not torch.distributed.is_available(): + return 0 + import torch.distributed as dist + + return dist.get_rank() if dist.is_initialized() else 0 + + +@leaf_function +def debug_grad_log(*tensors): + """Log gradient norms of multiple tensors during backward. + + This is a no-op in the forward pass. During backward, the hook fires + exactly once when all requires_grad tensor inputs have their gradients + computed, and logs ``[rank R][bwd] t0_grad_norm=... t1_grad_norm=...``. + + Args: + *tensors: One or more tensors to monitor. + + Returns: + None. Call without assignment: ``debug_grad_log(x, y)``. + """ + return None + + +@debug_grad_log.register_fake # pyrefly: ignore[missing-attribute] +def _debug_grad_log_fake(*tensors): + return None + + +@debug_grad_log.register_multi_grad_hook # pyrefly: ignore[missing-attribute] +def _debug_grad_log_hook(*grads): + norms = " ".join( + f"t{i}_grad_norm={g.norm().item():.4f}" for i, g in enumerate(grads) + ) + log.info("[rank %d][bwd] %s", _get_rank(), norms) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/deterministic.py b/.venv/lib/python3.12/site-packages/torch/utils/deterministic.py new file mode 100644 index 0000000000000000000000000000000000000000..a055c43be531a5c65c4f29f6c8165104e98e5ca0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/deterministic.py @@ -0,0 +1,22 @@ +# mypy: allow-untyped-defs +import sys +import types + +import torch + + +class _Deterministic(types.ModuleType): + @property + def fill_uninitialized_memory(self): + """ + Whether to fill uninitialized memory with a known value when + :meth:`torch.use_deterministic_algorithms()` is set to ``True``. + """ + return torch._C._get_deterministic_fill_uninitialized_memory() + + @fill_uninitialized_memory.setter + def fill_uninitialized_memory(self, mode): + return torch._C._set_deterministic_fill_uninitialized_memory(mode) + + +sys.modules[__name__].__class__ = _Deterministic diff --git a/.venv/lib/python3.12/site-packages/torch/utils/dlpack.py b/.venv/lib/python3.12/site-packages/torch/utils/dlpack.py new file mode 100644 index 0000000000000000000000000000000000000000..19677591444676054cad30c2d3e7105b06549c5c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/dlpack.py @@ -0,0 +1,297 @@ +from typing import Any + +import torch +import enum + +from torch._C import _to_dlpack as to_dlpack +from torch.types import Device as _Device + +__all__ = [ + "DLDeviceType", + "from_dlpack", + "ReadOnlyTensorWrapper", +] + +class DLDeviceType(enum.IntEnum): + # Enums as in DLPack specification (aten/src/ATen/dlpack.h) + kDLCPU = 1, + kDLCUDA = 2, + kDLCUDAHost = 3, + kDLOpenCL = 4, + kDLVulkan = 7, + kDLMetal = 8, + kDLVPI = 9, + kDLROCM = 10, + kDLROCMHost = 11, + kDLExtDev = 12, + kDLCUDAManaged = 13, + kDLOneAPI = 14, + kDLWebGPU = 15, + kDLHexagon = 16, + kDLMAIA = 17, + + +class ReadOnlyTensorWrapper(torch.Tensor): + r"""A zero-copy, read-only view of a tensor for DLPack interop only. + + Wrapping a tensor with ``ReadOnlyTensorWrapper`` declares the intent that + consumers must not mutate its data. It changes only the DLPack export + behavior; the wrapper shares storage with the source tensor and does not + copy. + + Both DLPack export paths are routed to read-only variants: + + * the fast ``__dlpack_c_exchange_api__`` C exchange protocol (used by + tvm-ffi / CuteDSL) points at the const exchange API, which exports + through ``const_data_ptr()`` and sets + ``DLPACK_FLAG_BITMASK_READ_ONLY``; + * the ``__dlpack__()`` capsule protocol forces ``read_only=True``. + + Because the export uses ``const_data_ptr()``, exporting a copy-on-write + tensor does not materialize it. + + The wrapper is export-only: every torch operation other than the DLPack + protocol methods raises ``RuntimeError``. Unwrap it (e.g. via the original + tensor) to operate on the data. + + Example:: + + x = torch.randn(8) + ro = ReadOnlyTensorWrapper(x) + cute.runtime.from_dlpack(ro, enable_tvm_ffi=True) # read-only export + """ + + # Consumers discover the C exchange API on the type. Pointing it at the + # const variant makes the fast path export read-only. + # pyrefly: ignore [missing-attribute] + __dlpack_c_exchange_api__: object = torch._C._const_dlpack_exchange_api() + + # The only torch functions the wrapper participates in. Everything else is + # rejected so the wrapper cannot be used as a normal tensor. + _DLPACK_ALLOWED = frozenset( + {torch.Tensor.__dlpack__, torch.Tensor.__dlpack_device__} + ) + + @staticmethod + def __new__(cls, tensor: torch.Tensor) -> "ReadOnlyTensorWrapper": + return tensor.as_subclass(cls) + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + if func in cls._DLPACK_ALLOWED: + # Run as a plain tensor so the export internals (property accesses, + # is_conj(), etc.) are not re-intercepted and re-blocked. + with torch._C.DisableTorchFunctionSubclass(): + return func(*args, **(kwargs or {})) + raise RuntimeError( + f"{cls.__name__} only supports DLPack export; " + f"'{getattr(func, '__name__', func)}' is not allowed. " + "Unwrap the tensor to operate on its data." + ) + + def __dlpack__(self, *, max_version=None, **kwargs): # type: ignore[override] + # The capsule path can only carry read-only on the versioned protocol. + if max_version is None: + max_version = (1, 0) + return super().__dlpack__(max_version=max_version, read_only=True, **kwargs) + + +torch._C._add_docstr(to_dlpack, r"""to_dlpack(tensor) -> PyCapsule + +Returns an opaque object (a "DLPack capsule") representing the tensor. + +.. note:: + ``to_dlpack`` is a legacy DLPack interface. The capsule it returns + cannot be used for anything in Python other than use it as input to + ``from_dlpack``. The more idiomatic use of DLPack is to call + ``from_dlpack`` directly on the tensor object - this works when that + object has a ``__dlpack__`` method, which PyTorch and most other + libraries indeed have now. + +.. warning:: + Only call ``from_dlpack`` once per capsule produced with ``to_dlpack``. + Behavior when a capsule is consumed multiple times is undefined. + +Args: + tensor: a tensor to be exported + +The DLPack capsule shares the tensor's memory. +""") + + +# TODO: add a typing.Protocol to be able to tell Mypy that only objects with +# __dlpack__ and __dlpack_device__ methods are accepted. +def from_dlpack( + ext_tensor: Any, + *, + device: _Device | None = None, + copy: bool | None = None +) -> 'torch.Tensor': + """from_dlpack(ext_tensor) -> Tensor + + Converts a tensor from an external library into a ``torch.Tensor``. + + The returned PyTorch tensor will share the memory with the input tensor + (which may have come from another library). Note that in-place operations + will therefore also affect the data of the input tensor. This may lead to + unexpected issues (e.g., other libraries may have read-only flags or + immutable data structures), so the user should only do this if they know + for sure that this is fine. + + Args: + ext_tensor (object with ``__dlpack__`` attribute, or a DLPack capsule): + The tensor or DLPack capsule to convert. + + If ``ext_tensor`` is a tensor (or ndarray) object, it must support + the ``__dlpack__`` protocol (i.e., have a ``ext_tensor.__dlpack__`` + method). Otherwise ``ext_tensor`` may be a DLPack capsule, which is + an opaque ``PyCapsule`` instance, typically produced by a + ``to_dlpack`` function or method. + + device (torch.device or str or None): An optional PyTorch device + specifying where to place the new tensor. If None (default), the + new tensor will be on the same device as ``ext_tensor``. + + copy (bool or None): An optional boolean indicating whether or not to copy + ``self``. If None, PyTorch will copy only if necessary. + + Examples:: + + >>> import torch.utils.dlpack + >>> t = torch.arange(4) + + # Convert a tensor directly (supported in PyTorch >= 1.10) + >>> t2 = torch.from_dlpack(t) + >>> t2[:2] = -1 # show that memory is shared + >>> t2 + tensor([-1, -1, 2, 3]) + >>> t + tensor([-1, -1, 2, 3]) + + # The old-style DLPack usage, with an intermediate capsule object + >>> capsule = torch.utils.dlpack.to_dlpack(t) + >>> capsule + + >>> t3 = torch.from_dlpack(capsule) + >>> t3 + tensor([-1, -1, 2, 3]) + >>> t3[0] = -9 # now we're sharing memory between 3 tensors + >>> t3 + tensor([-9, -1, 2, 3]) + >>> t2 + tensor([-9, -1, 2, 3]) + >>> t + tensor([-9, -1, 2, 3]) + + """ + + if hasattr(ext_tensor, '__dlpack__'): + # Only populate kwargs if any of the optional arguments are, in fact, not None. Otherwise, + # leave them out, since we might end up falling back to no-extra-kwargs __dlpack__ call. + kwargs: dict[str, Any] = {} + kwargs["max_version"] = (1, 0) + + # Track copy request for potential manual handling + requested_copy = copy + producer_handled_copy = True + cross_device_transfer = False # Will be set to True if device transfer is needed + + if copy is not None: + kwargs["copy"] = copy + + # Parse the device parameter. + # At this moment, it can either be a torch.device or a str representing + # a torch.device, e.g. "cpu", "cuda", etc. + # Get source device first (we need it to detect cross-device transfers) + ext_device = ext_tensor.__dlpack_device__() + + if device is not None: + if isinstance(device, str): + device = torch.device(device) + if not isinstance(device, torch.device): + raise AssertionError(f"from_dlpack: unsupported device type: {type(device)}") + + # Convert target device to DLPack format + target_dl_device = torch._C._torchDeviceToDLDevice(device) + + # Detect cross-device transfer by comparing source and target devices + # E.g. CPU->CUDA, cuda:0->cuda:1, etc. + cross_device_transfer = (ext_device != target_dl_device) + + # Only pass dl_device to producer if NOT cross-device transfer + if not cross_device_transfer: + kwargs["dl_device"] = target_dl_device + + # Cross-device transfer always requires a copy + if cross_device_transfer and copy is False: + raise ValueError( + f"cannot move DLPack tensor from device {ext_device} to {target_dl_device} " + "without copying. Set copy=None or copy=True." + ) + + # ext_device is either CUDA or ROCm, we need to pass the current + # stream + if ext_device[0] in (DLDeviceType.kDLCUDA, DLDeviceType.kDLROCM): + stream = torch.cuda.current_stream(f'cuda:{ext_device[1]}') + # cuda_stream is the pointer to the stream and it is a public + # attribute, but it is not documented + # The array API specify that the default legacy stream must be passed + # with a value of 1 for CUDA + # https://data-apis.org/array-api/latest/API_specification/array_object.html?dlpack-self-stream-none#dlpack-self-stream-none + is_cuda = ext_device[0] == DLDeviceType.kDLCUDA + # Since pytorch is not using PTDS by default, lets directly pass + # the legacy stream + stream_ptr = 1 if is_cuda and stream.cuda_stream == 0 else stream.cuda_stream + kwargs["stream"] = stream_ptr + + # Try different parameter combinations until one works + dlpack = None + + # Attempt 1: Try with all the parameters + try: + dlpack = ext_tensor.__dlpack__(**kwargs) + except TypeError: + pass + + # Attempt 2: Remove max_version + if dlpack is None: + kwargs.pop("max_version", None) + try: + dlpack = ext_tensor.__dlpack__(**kwargs) + except TypeError: + pass + + # Attempt 3: Remove copy + if dlpack is None: + kwargs.pop("copy", None) + producer_handled_copy = False + try: + dlpack = ext_tensor.__dlpack__(**kwargs) + except TypeError: + pass + + # Attempt 4: Remove dl_device + if dlpack is None: + kwargs.pop("dl_device", None) + dlpack = ext_tensor.__dlpack__(**kwargs) + + tensor = torch._C._from_dlpack(dlpack) + + # Manual copy if producer didn't handle it (cross-device already copies via .to()) + if requested_copy is True and not producer_handled_copy and not cross_device_transfer: + tensor = tensor.clone() + + # Handle cross-device transfer by moving tensor to target device + if cross_device_transfer: + tensor = tensor.to(device) + + return tensor + + else: + if device is not None or copy is not None: + raise AssertionError( + "device and copy kwargs not supported when ext_tensor is already a DLPack capsule." + ) + # Old versions just call the converter + dlpack = ext_tensor + return torch._C._from_dlpack(dlpack) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/file_baton.py b/.venv/lib/python3.12/site-packages/torch/utils/file_baton.py new file mode 100644 index 0000000000000000000000000000000000000000..74de1495c8fc572cfc350966f6f0b7997fde7ad1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/file_baton.py @@ -0,0 +1,63 @@ +# mypy: allow-untyped-defs +import os +import time +import warnings + + +class FileBaton: + """A primitive, file-based synchronization utility.""" + + def __init__(self, lock_file_path, wait_seconds=0.1, warn_after_seconds=None) -> None: + """ + Create a new :class:`FileBaton`. + + Args: + lock_file_path: The path to the file used for locking. + wait_seconds: The seconds to periodically sleep (spin) when + calling ``wait()``. + warn_after_seconds: The seconds to wait before showing + lock file path to warn existing lock file. + """ + self.lock_file_path = lock_file_path + self.wait_seconds = wait_seconds + self.fd = None + self.warn_after_seconds = warn_after_seconds + + def try_acquire(self) -> bool | None: + """ + Try to atomically create a file under exclusive access. + + Returns: + True if the file could be created, else False. + """ + try: + self.fd = os.open(self.lock_file_path, os.O_CREAT | os.O_EXCL) + return True + except FileExistsError: + return False + + def wait(self) -> None: + """ + Periodically sleeps for a certain amount until the baton is released. + + The amount of time slept depends on the ``wait_seconds`` parameter + passed to the constructor. + """ + has_warned = False + + start_time = time.time() + while os.path.exists(self.lock_file_path): + time.sleep(self.wait_seconds) + + if self.warn_after_seconds is not None: + if time.time() - start_time > self.warn_after_seconds and not has_warned: + warnings.warn(f'Waited on lock file "{self.lock_file_path}" for ' + f'{self.warn_after_seconds} seconds.', stacklevel=2) + has_warned = True + + def release(self) -> None: + """Release the baton and removes its file.""" + if self.fd is not None: + os.close(self.fd) + + os.remove(self.lock_file_path) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/flop_counter.py b/.venv/lib/python3.12/site-packages/torch/utils/flop_counter.py new file mode 100644 index 0000000000000000000000000000000000000000..43088e695b904bcca06499708a3c6bb755a98ed0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/flop_counter.py @@ -0,0 +1,1159 @@ +# mypy: allow-untyped-defs +"""Utilities for counting theoretical floating point operations. + +``FlopCounterMode`` is a context manager that intercepts PyTorch operators and +adds up their registered FLOP formulas. The result is a shape-based, +theoretical FLOP count for the operators that ran inside the context, not a +hardware performance measurement. + +The counter is useful when comparing model graphs, activation checkpointing +plans, or shape changes with a stable FLOP accounting rule. It should not be +read as kernel instructions, wall-clock time, memory bandwidth, achieved +FLOP/s, Tensor Core utilization, or the exact work done by a fused kernel. + +Counting semantics +------------------ + +* Counts are produced by formulas in ``flop_registry``. Operators without a + formula may be decomposed into registered operators; otherwise they add zero + FLOPs. +* Formula inputs have tensor arguments replaced by their shapes by default. + Non-tensor arguments pass through unchanged. Use + ``register_flop_formula(..., get_raw=True)`` only when the formula needs the + original tensor arguments or metadata. +* Forward and backward operations are counted only if they execute while the + context manager is active. +* The default formulas use dense, naive mathematical definitions. For example, + matrix multiplication counts ``2 * m * n * k`` FLOPs. +* Counts do not automatically adjust for dtype-specific throughput, Tensor + Cores, sparsity, quantization, masking, skipped elements, memory movement, or + data-dependent early exits. A formula must explicitly model those semantics. + For example, the built-in attention formulas are upper bounds for causal or + otherwise masked attention unless the formula explicitly models the mask. +* Higher-order operators and ``torch.compile`` may expose decomposed or fused + work differently from eager execution. Custom operators and custom Triton + kernels need a formula or a decomposition if they should contribute FLOPs. +* Module attribution is tracked through ``ModuleTracker``. Totals are always + available under ``"Global"``; submodule rows are best-effort attribution for + module calls observed during the context. +* The workload still executes normally. Use this mode for a few representative + iterations rather than long training runs if overhead or memory use matters. + +Example +------- + +.. code-block:: python + + import torch + from torch.utils.flop_counter import FlopCounterMode + + model = torch.nn.Linear(16, 32) + x = torch.randn(4, 16) + + with FlopCounterMode(display=False) as mode: + model(x).sum().backward() + + print(mode.get_total_flops()) + print(mode.get_flop_counts()["Global"]) + +Registering a formula for a custom op +------------------------------------- + +Register custom FLOP formulas before constructing ``FlopCounterMode``. The +mode snapshots the global registry during initialization. + +.. code-block:: python + + from math import prod + + import torch + from torch.utils.flop_counter import FlopCounterMode, register_flop_formula + + @torch.library.custom_op("example::scale", mutates_args=()) + def scale(x: torch.Tensor) -> torch.Tensor: + return x * 2 + + @register_flop_formula(torch.ops.example.scale) + def scale_flops(x_shape, *, out_shape=None) -> int: + return prod(x_shape) + + x = torch.randn(8) + with FlopCounterMode(display=False) as mode: + scale(x) + + assert mode.get_total_flops() == 8 +""" +from types import NoneType +import logging +import torch +from torch.utils._pytree import tree_map, tree_flatten, tree_unflatten +from .module_tracker import ModuleTracker +from typing import Any, TypeVar +from collections.abc import Callable +from collections.abc import Iterator +from typing_extensions import ParamSpec +from collections import defaultdict +from torch.utils._python_dispatch import TorchDispatchMode +from math import prod +from functools import wraps +import warnings + +__all__ = ["FlopCounterMode", "register_flop_formula"] + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +log = logging.getLogger(__name__) + + +try: + from triton.runtime.jit import JITFunction as _JITFunction +except ImportError: + if any(getattr(torch.version, attr, None) is not None for attr in ["cuda", "hip", "xpu"]): + log.warning("triton not found; flop counting will not work for triton kernels") + _JITFunction = NoneType + + +aten = torch.ops.aten + +def get_shape(i): + if isinstance(i, torch.Tensor): + return i.shape + return i + +flop_registry: dict[Any, Any] = {} + +def shape_wrapper(f): + @wraps(f) + def nf(*args, out_val=None, **kwargs): + args, kwargs, out_shape = tree_map(get_shape, (args, kwargs, out_val)) + return f(*args, out_shape=out_shape, **kwargs) + return nf + +def register_flop_formula(targets, get_raw=False) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + + def register_fun(flop_formula: Callable[_P, _T]) -> Callable[_P, _T]: + if not get_raw: + flop_formula = shape_wrapper(flop_formula) + + def register(target) -> None: + from torch._ops import HigherOrderOperator + + if not (isinstance(target, (torch._ops.OpOverloadPacket, _JITFunction, HigherOrderOperator))): + raise ValueError( + f"register_flop_formula(targets): expected each target to be " + f"OpOverloadPacket (i.e. torch.ops.mylib.foo), JitFunction, " + f"or HigherOrderOperator" + f", got {target} which is of type {type(target)}") + if target in flop_registry: + raise RuntimeError(f"duplicate registrations for {target}") + flop_registry[target] = flop_formula + + # To handle allowing multiple aten_ops at once + torch.utils._pytree.tree_map_(register, targets) + + return flop_formula + + return register_fun + +@register_flop_formula(aten.mm) +def mm_flop(a_shape, b_shape, *args, out_shape=None, **kwargs) -> int: + """Count flops for matmul.""" + # Inputs should be a list of length 2. + # Inputs contains the shapes of two matrices. + m, k = a_shape + k2, n = b_shape + if k != k2: + raise AssertionError(f"matmul: inner dimensions must match (k == k2), got {k} and {k2}") + # NB(chilli): Should be 2 * k - 1 technically for FLOPs. + return m * n * 2 * k + +@register_flop_formula(aten.addmm) +def addmm_flop(self_shape, a_shape, b_shape, *args, **kwargs) -> int: + """Count flops for addmm.""" + return mm_flop(a_shape, b_shape) + +@register_flop_formula(aten.bmm) +def bmm_flop(a_shape, b_shape, *args, **kwargs) -> int: + """Count flops for the bmm operation.""" + # Inputs should be a list of length 2. + # Inputs contains the shapes of two tensor. + b, m, k = a_shape + b2, k2, n = b_shape + if b != b2: + raise AssertionError(f"bmm: batch dimensions must match (b == b2), got {b} and {b2}") + if k != k2: + raise AssertionError(f"bmm: inner dimensions must match (k == k2), got {k} and {k2}") + # NB(chilli): Should be 2 * k - 1 technically for FLOPs. + flop = b * m * n * 2 * k + return flop + +@register_flop_formula(aten.baddbmm) +def baddbmm_flop(self_shape, a_shape, b_shape, *args, **kwargs) -> int: + """Count flops for the baddbmm operation.""" + # Inputs should be a list of length 3. + # Inputs contains the shapes of three tensors. + return bmm_flop(a_shape, b_shape) + +@register_flop_formula(aten._scaled_mm) +def _scaled_mm_flop( + a_shape, + b_shape, + scale_a_shape, + scale_b_shape, + bias_shape=None, + scale_result_shape=None, + out_dtype=None, + use_fast_accum=False, + out_shape=None, + **kwargs, +) -> int: + """Count flops for _scaled_mm.""" + return mm_flop(a_shape, b_shape) + + +def conv_flop_count( + x_shape: list[int], + w_shape: list[int], + out_shape: list[int], + transposed: bool = False, +) -> int: + """Count flops for convolution. + + Note only multiplication is + counted. Computation for bias are ignored. + Flops for a transposed convolution are calculated as + flops = (x_shape[2:] * prod(w_shape) * batch_size). + Args: + x_shape (list(int)): The input shape before convolution. + w_shape (list(int)): The filter shape. + out_shape (list(int)): The output shape after convolution. + transposed (bool): is the convolution transposed + Returns: + int: the number of flops + """ + batch_size = x_shape[0] + conv_shape = (x_shape if transposed else out_shape)[2:] + c_out, c_in, *filter_size = w_shape + + """ + General idea here is that for a regular conv, for each point in the output + spatial dimension we convolve the filter with something (hence + `prod(conv_shape) * prod(filter_size)` ops). Then, this gets multiplied by + 1. batch_size, 2. the cross product of input and weight channels. + + For the transpose, it's not each point in the *output* spatial dimension but + each point in the *input* spatial dimension. + """ + # NB(chilli): I don't think this properly accounts for padding :think: + # NB(chilli): Should be 2 * c_in - 1 technically for FLOPs. + flop = prod(conv_shape) * prod(filter_size) * batch_size * c_out * c_in * 2 + return flop + +@register_flop_formula([aten.convolution, + aten._convolution, + aten.cudnn_convolution, + aten._slow_conv2d_forward, + aten.convolution_overrideable]) +def conv_flop(x_shape, w_shape, _bias, _stride, _padding, _dilation, transposed, *args, out_shape=None, **kwargs) -> int: + """Count flops for convolution.""" + # pyrefly: ignore [bad-argument-type] + return conv_flop_count(x_shape, w_shape, out_shape, transposed=transposed) + + +@register_flop_formula(aten.convolution_backward) +def conv_backward_flop( + grad_out_shape, + x_shape, + w_shape, + _bias, + _stride, + _padding, + _dilation, + transposed, + _output_padding, + _groups, + output_mask, + out_shape, + **kwargs) -> int: + + def t(shape): + return [shape[1], shape[0]] + list(shape[2:]) + flop_count = 0 + + """ + Let's say we have a regular 1D conv + {A, B, C} [inp] + {i, j} [weight] + => (conv) + {Ai + Bj, Bi + Cj} [out] + + And as a reminder, the transposed conv of the above is + => {Ai, Aj + Bi, Bj + Ci, Cj} [transposed conv out] + + For the backwards of conv, we now have + {D, E} [grad_out] + {A, B, C} [inp] + {i, j} [weight] + + # grad_inp as conv_transpose(grad_out, weight) + Let's first compute grad_inp. To do so, we can simply look at all the + multiplications that each element of inp is involved in. For example, A is + only involved in the first element of the output (and thus only depends upon + D in grad_out), and C is only involved in the last element of the output + (and thus only depends upon E in grad_out) + + {Di, Dj + Ei, Ej} [grad_inp] + + Note that this corresponds to the below conv_transpose. This gives us the + output_mask[0] branch, which is grad_inp. + + {D, E} [inp (grad_out)] + {i, j} [weight] + => (conv_transpose) + {Di, Dj + Ei, Ej} [out (grad_inp)] + + I leave the fact that grad_inp for a transposed conv is just conv(grad_out, + weight) as an exercise for the reader. + + # grad_weight as conv(inp, grad_out) + To compute grad_weight, we again look at the terms in the output, which as + a reminder is: + => {Ai + Bj, Bi + Cj} [out] + => {D, E} [grad_out] + If we manually compute the gradient for the weights, we see it's + {AD + BE, BD + CE} [grad_weight] + + This corresponds to the below conv + {A, B, C} [inp] + {D, E} [weight (grad_out)] + => (conv) + {AD + BE, BD + CE} [out (grad_weight)] + + # grad_weight of transposed conv as conv(grad_out, inp) + As a reminder, the terms of the output of a transposed conv are: + => {Ai, Aj + Bi, Bj + Ci, Cj} [transposed conv out] + => {D, E, F, G} [grad_out] + + Manually computing the gradient for the weights, we see it's + {AD + BE + CF, AE + BF + CG} [grad_weight] + + This corresponds to the below conv + {D, E, F, G} [inp (grad_out)] + {A, B, C} [weight (inp)] + => (conv) + {AD + BE + CF, AE + BF + CG} [out (grad_weight)] + + For the full backwards formula, there are also some details involving + transpose of the batch/channel dimensions and groups, but I skip those for + the sake of brevity (and they're pretty similar to matmul backwards) + + Check [conv backwards decomposition as conv forwards] + """ + # grad_inp as conv_transpose(grad_out, weight) + if output_mask[0]: + grad_input_shape = get_shape(out_shape[0]) + flop_count += conv_flop_count(grad_out_shape, w_shape, grad_input_shape, not transposed) + + if output_mask[1]: + grad_weight_shape = get_shape(out_shape[1]) + if transposed: + # grad_weight of transposed conv as conv(grad_out, inp) + flop_count += conv_flop_count(t(grad_out_shape), t(x_shape), t(grad_weight_shape), transposed=False) + else: + # grad_weight as conv(inp, grad_out) + flop_count += conv_flop_count(t(x_shape), t(grad_out_shape), t(grad_weight_shape), transposed=False) + + return flop_count + +def sdpa_flop_count(query_shape, key_shape, value_shape): + """ + Count flops for self-attention. + + Supports GQA (grouped-query attention) where key/value have fewer heads + than the query. The kernel broadcasts KV heads to match query heads. + """ + b, h_q, s_q, d_q = query_shape + _b2, h_kv, s_k, _d2 = key_shape + _b3, _h3, _s3, d_v = value_shape + if not (b == _b2 == _b3 and h_kv == _h3 and d_q == _d2 and s_k == _s3): + raise AssertionError( + f"sdpa_flop_count: query/key/value shapes are incompatible: " + f"q={query_shape}, k={key_shape}, v={value_shape}" + ) + if h_q < h_kv or h_q % h_kv != 0: + raise AssertionError( + f"sdpa_flop_count: query heads ({h_q}) must be a multiple of " + f"key/value heads ({h_kv})" + ) + total_flops = 0 + # q: [b, h_q, s_q, d_q] @ k: [b, h_q, d_q, s_k] -> scores: [b, h_q, s_q, s_k] + total_flops += bmm_flop((b * h_q, s_q, d_q), (b * h_q, d_q, s_k)) + # scores: [b, h_q, s_q, s_k] @ v: [b, h_q, s_k, d_v] -> out: [b, h_q, s_q, d_v] + total_flops += bmm_flop((b * h_q, s_q, s_k), (b * h_q, s_k, d_v)) + return total_flops + + +@register_flop_formula([aten._scaled_dot_product_efficient_attention, + aten._scaled_dot_product_flash_attention, + aten._scaled_dot_product_cudnn_attention]) +def sdpa_flop(query_shape, key_shape, value_shape, *args, out_shape=None, **kwargs) -> int: + """Count flops for self-attention.""" + # NB: We aren't accounting for causal attention here + return sdpa_flop_count(query_shape, key_shape, value_shape) + + +def _offsets_to_lengths(offsets, max_len): + """ + If the offsets tensor is fake, then we don't know the actual lengths. + In that case, we can just assume the worst case; each batch has max length. + """ + from torch._subclasses.fake_tensor import is_fake_tensor + from torch._subclasses.functional_tensor import FunctionalTensor + if not (is_fake_tensor(offsets) or isinstance(offsets, FunctionalTensor)) and offsets.device.type != "meta": + return offsets.diff().tolist() + return [max_len] * (offsets.size(0) - 1) + + +def _unpack_flash_attention_nested_shapes( + *, + query, + key, + value, + grad_out=None, + cum_seq_q, + cum_seq_k, + max_q, + max_k, +) -> Iterator[tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...], tuple[int, ...] | None]]: + """ + Given inputs to a flash_attention_(forward|backward) kernel, this will handle behavior for + NestedTensor inputs by effectively unbinding the NestedTensor and yielding the shapes for + each batch element. + + In the case that this isn't a NestedTensor kernel, then it just yields the original shapes. + """ + if cum_seq_q is not None: + # This means we should be dealing with a Nested Jagged Tensor query. + # The inputs will have shape (sum(sequence len), heads, dimension) + # In comparison, non-Nested inputs have shape (batch, heads, sequence len, dimension) + # To deal with this, we convert to a shape of (batch, heads, max_seq_len, dimension) + # So the flops calculation in this case is an overestimate of the actual flops. + if len(key.shape) != 3: + raise AssertionError("sdpa_flop_count: expected key.shape to be 3-dimensional") + if len(value.shape) != 3: + raise AssertionError("sdpa_flop_count: expected value.shape to be 3-dimensional") + if grad_out is not None and grad_out.shape != query.shape: + raise AssertionError("sdpa_flop_count: grad_out.shape must match query.shape when provided") + _, h_q, d_q = query.shape + _, h_k, d_k = key.shape + _, h_v, d_v = value.shape + if cum_seq_q is None: + raise AssertionError("sdpa_flop_count: cum_seq_q must not be None") + if cum_seq_k is None: + raise AssertionError("sdpa_flop_count: cum_seq_k must not be None") + if cum_seq_q.shape != cum_seq_k.shape: + raise AssertionError("sdpa_flop_count: cum_seq_q and cum_seq_k must have the same shape") + seq_q_lengths = _offsets_to_lengths(cum_seq_q, max_q) + seq_k_lengths = _offsets_to_lengths(cum_seq_k, max_k) + for (seq_q_len, seq_k_len) in zip(seq_q_lengths, seq_k_lengths, strict=True): + new_query_shape = (1, h_q, seq_q_len, d_q) + new_key_shape = (1, h_k, seq_k_len, d_k) + new_value_shape = (1, h_v, seq_k_len, d_v) + new_grad_out_shape = new_query_shape if grad_out is not None else None + yield new_query_shape, new_key_shape, new_value_shape, new_grad_out_shape + return + + yield query.shape, key.shape, value.shape, grad_out.shape if grad_out is not None else None + + +def _unpack_efficient_attention_nested_shapes( + *, + query, + key, + value, + grad_out=None, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, +) -> Iterator[tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...], tuple[int, ...] | None]]: + """ + Given inputs to a efficient_attention_(forward|backward) kernel, this will handle behavior for + NestedTensor inputs by effectively unbinding the NestedTensor and yielding the shapes for + each batch element. + + In the case that this isn't a NestedTensor kernel, then it just yields the original shapes. + """ + if cu_seqlens_q is not None: + # Unlike flash_attention_forward, we get a 4D tensor instead of a 3D tensor for efficient attention. + # + # This means we should be dealing with a Nested Jagged Tensor query. + # The inputs will have shape (sum(sequence len), heads, dimension) + # In comparison, non-Nested inputs have shape (batch, heads, sequence len, dimension) + # To deal with this, we convert to a shape of (batch, heads, max_seq_len, dimension) + # So the flops calculation in this case is an overestimate of the actual flops. + if len(key.shape) != 4: + raise AssertionError("_unpack_efficient_attention_nested_shapes: expected key.shape to be 4-dimensional") + if len(value.shape) != 4: + raise AssertionError("_unpack_efficient_attention_nested_shapes: expected value.shape to be 4-dimensional") + if grad_out is not None and grad_out.shape != query.shape: + raise AssertionError("_unpack_efficient_attention_nested_shapes: grad_out.shape must match query.shape when provided") + _, _, h_q, d_q = query.shape + _, _, h_k, d_k = key.shape + _, _, h_v, d_v = value.shape + if cu_seqlens_q is None: + raise AssertionError("_unpack_efficient_attention_nested_shapes: cu_seqlens_q must not be None") + if cu_seqlens_k is None: + raise AssertionError("_unpack_efficient_attention_nested_shapes: cu_seqlens_k must not be None") + if cu_seqlens_q.shape != cu_seqlens_k.shape: + raise AssertionError("_unpack_efficient_attention_nested_shapes: " + "cu_seqlens_q and cu_seqlens_k must have the same shape") + seqlens_q = _offsets_to_lengths(cu_seqlens_q, max_seqlen_q) + seqlens_k = _offsets_to_lengths(cu_seqlens_k, max_seqlen_k) + for len_q, len_k in zip(seqlens_q, seqlens_k, strict=True): + new_query_shape = (1, h_q, len_q, d_q) + new_key_shape = (1, h_k, len_k, d_k) + new_value_shape = (1, h_v, len_k, d_v) + new_grad_out_shape = new_query_shape if grad_out is not None else None + yield new_query_shape, new_key_shape, new_value_shape, new_grad_out_shape + return + + yield query.shape, key.shape, value.shape, grad_out.shape if grad_out is not None else None + + +@register_flop_formula(aten._flash_attention_forward, get_raw=True) +def _flash_attention_forward_flop( + query, + key, + value, + cum_seq_q, + cum_seq_k, + max_q, + max_k, + *args, + out_shape=None, + **kwargs +) -> int: + """Count flops for self-attention.""" + # NB: We aren't accounting for causal attention here + if cum_seq_q is None and query.ndim == 4: + query = query.transpose(-2, -3) + key = key.transpose(-2, -3) + value = value.transpose(-2, -3) + # in case this is a nested tensor, we unpack the individual batch elements + # and then sum the flops per batch element + sizes = _unpack_flash_attention_nested_shapes( + query=query, + key=key, + value=value, + cum_seq_q=cum_seq_q, + cum_seq_k=cum_seq_k, + max_q=max_q, + max_k=max_k, + ) + return sum( + sdpa_flop_count(query_shape, key_shape, value_shape) + for query_shape, key_shape, value_shape, _ in sizes + ) + + +@register_flop_formula(aten._efficient_attention_forward, get_raw=True) +def _efficient_attention_forward_flop( + query, + key, + value, + bias, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + *args, + **kwargs +) -> int: + """Count flops for self-attention.""" + # NB: We aren't accounting for causal attention here + # in case this is a nested tensor, we unpack the individual batch elements + # and then sum the flops per batch element + sizes = _unpack_efficient_attention_nested_shapes( + query=query, + key=key, + value=value, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + ) + return sum( + sdpa_flop_count(query_shape, key_shape, value_shape) + for query_shape, key_shape, value_shape, _ in sizes + ) + + +def sdpa_backward_flop_count(grad_out_shape, query_shape, key_shape, value_shape): + b, h_q, s_q, d_q = query_shape + _b2, h_kv, s_k, _d2 = key_shape + _b3, _h3, _s3, d_v = value_shape + _b4, _h4, _s4, _d4 = grad_out_shape + if not (b == _b2 == _b3 == _b4 and h_kv == _h3 and h_q == _h4): + raise AssertionError( + "sdpa_backward_flop_count: batch/heads mismatch among tensors" + ) + if h_q < h_kv or h_q % h_kv != 0: + raise AssertionError( + f"sdpa_backward_flop_count: query heads ({h_q}) must be a multiple of " + f"key/value heads ({h_kv})" + ) + if not (d_q == _d2 and d_v == _d4 and s_k == _s3 and s_q == _s4): + raise AssertionError( + "sdpa_backward_flop_count: grad_out/value/key/query shapes are incompatible" + ) + total_flops = 0 + # Step 1: We recompute the scores matrix. + # q: [b, h_q, s_q, d_q] @ k: [b, h_q, d_q, s_k] -> scores: [b, h_q, s_q, s_k] + total_flops += bmm_flop((b * h_q, s_q, d_q), (b * h_q, d_q, s_k)) + + # Step 2: We propagate the gradients through the score @ v operation. + # gradOut: [b, h_q, s_q, d_v] @ v: [b, h_q, d_v, s_k] -> gradScores: [b, h_q, s_q, s_k] + total_flops += bmm_flop((b * h_q, s_q, d_v), (b * h_q, d_v, s_k)) + # scores: [b, h_q, s_k, s_q] @ gradOut: [b, h_q, s_q, d_v] -> gradV: [b, h_q, s_k, d_v] + total_flops += bmm_flop((b * h_q, s_k, s_q), (b * h_q, s_q, d_v)) + + # Step 3: We propagate the gradients through the k @ v operation + # gradScores: [b, h_q, s_q, s_k] @ k: [b, h_q, s_k, d_q] -> gradQ: [b, h_q, s_q, d_q] + total_flops += bmm_flop((b * h_q, s_q, s_k), (b * h_q, s_k, d_q)) + # q: [b, h_q, d_q, s_q] @ gradScores: [b, h_q, s_q, s_k] -> gradK: [b, h_q, d_q, s_k] + total_flops += bmm_flop((b * h_q, d_q, s_q), (b * h_q, s_q, s_k)) + return total_flops + + +@register_flop_formula([aten._scaled_dot_product_efficient_attention_backward, + aten._scaled_dot_product_flash_attention_backward, + aten._scaled_dot_product_cudnn_attention_backward]) +def sdpa_backward_flop(grad_out_shape, query_shape, key_shape, value_shape, *args, out_shape=None, **kwargs) -> int: + """Count flops for self-attention backward.""" + return sdpa_backward_flop_count(grad_out_shape, query_shape, key_shape, value_shape) + +@register_flop_formula(aten._flash_attention_backward, get_raw=True) +def _flash_attention_backward_flop( + grad_out, + query, + key, + value, + out, # named _out_shape to avoid kwarg collision with out_shape created in wrapper + logsumexp, + cum_seq_q, + cum_seq_k, + max_q, + max_k, + *args, + **kwargs, +) -> int: + if cum_seq_q is None and query.ndim == 4: + grad_out = grad_out.transpose(-2, -3) + query = query.transpose(-2, -3) + key = key.transpose(-2, -3) + value = value.transpose(-2, -3) + # in case this is a nested tensor, we unpack the individual batch elements + # and then sum the flops per batch element + shapes = _unpack_flash_attention_nested_shapes( + query=query, + key=key, + value=value, + grad_out=grad_out, + cum_seq_q=cum_seq_q, + cum_seq_k=cum_seq_k, + max_q=max_q, + max_k=max_k, + ) + return sum( + sdpa_backward_flop_count(grad_out_shape, query_shape, key_shape, value_shape) + for query_shape, key_shape, value_shape, grad_out_shape in shapes + ) + + +@register_flop_formula(aten._efficient_attention_backward, get_raw=True) +def _efficient_attention_backward_flop( + grad_out, + query, + key, + value, + bias, + out, # named _out to avoid kwarg collision with out created in wrapper + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + *args, + **kwargs, +) -> int: + # in case this is a nested tensor, we unpack the individual batch elements + # and then sum the flops per batch element + shapes = _unpack_efficient_attention_nested_shapes( + query=query, + key=key, + value=value, + grad_out=grad_out, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + ) + return sum( + sdpa_backward_flop_count(grad_out_shape, query_shape, key_shape, value_shape) + for query_shape, key_shape, value_shape, grad_out_shape in shapes + ) + + +def _register_flex_attention_flops() -> None: + from torch._higher_order_ops.flex_attention import ( + flex_attention, + flex_attention_backward, + ) + + def _get_sparsity_hint(kwargs: dict[str, Any]) -> float: + node_meta = kwargs.get("_node_meta") + if node_meta is None: + return 0.0 + custom = node_meta.get("custom") + if custom is None: + return 0.0 + return max(0.0, min(1.0, custom.get("sparsity_hint", 0.0))) + + @register_flop_formula(flex_attention, get_raw=True) + def flex_attention_forward_flop( + query, key, value, *args, out_val=None, **kwargs + ) -> int: + flops = sdpa_flop_count(query.shape, key.shape, value.shape) + sparsity = _get_sparsity_hint(kwargs) + return int(flops * (1.0 - sparsity)) if sparsity > 0 else flops + + @register_flop_formula(flex_attention_backward, get_raw=True) + def flex_attention_backward_flop( + query, key, value, out, logsumexp, grad_out, *args, out_val=None, **kwargs + ) -> int: + grad_out_shape = grad_out.shape if grad_out is not None else out.shape + flops = sdpa_backward_flop_count( + grad_out_shape, query.shape, key.shape, value.shape + ) + sparsity = _get_sparsity_hint(kwargs) + return int(flops * (1.0 - sparsity)) if sparsity > 0 else flops + + +def _varlen_attn_forward_flop( + query, + key, + value, + cu_seq_q, + cu_seq_k, + max_q, + max_k, + *args, + out_val=None, + **kwargs, +) -> int: + """Count flops for varlen_attn forward.""" + sizes = _unpack_flash_attention_nested_shapes( + query=query, + key=key, + value=value, + cum_seq_q=cu_seq_q, + cum_seq_k=cu_seq_k if cu_seq_k is not None else cu_seq_q, + max_q=max_q, + max_k=max_k, + ) + return sum( + sdpa_flop_count(query_shape, key_shape, value_shape) + for query_shape, key_shape, value_shape, _ in sizes + ) + + +def _varlen_attn_out_flop( + out, + query, + key, + value, + cu_seq_q, + cu_seq_k, + max_q, + max_k, + *args, + out_val=None, + **kwargs, +) -> int: + """Count flops for varlen_attn_out forward.""" + return _varlen_attn_forward_flop( + query, key, value, cu_seq_q, cu_seq_k, max_q, max_k, + ) + + +def _varlen_attn_backward_flop( + grad_out, + query, + key, + value, + out, + lse, + cu_seq_q, + cu_seq_k, + max_q, + max_k, + *args, + out_val=None, + **kwargs, +) -> int: + """Count flops for varlen_attn backward.""" + sizes = _unpack_flash_attention_nested_shapes( + query=query, + key=key, + value=value, + grad_out=grad_out, + cum_seq_q=cu_seq_q, + cum_seq_k=cu_seq_k, + max_q=max_q, + max_k=max_k, + ) + return sum( + sdpa_backward_flop_count(grad_out_shape, query_shape, key_shape, value_shape) + for query_shape, key_shape, value_shape, grad_out_shape in sizes + ) + + +flop_registry = { + aten.mm: mm_flop, + aten.addmm: addmm_flop, + aten.bmm: bmm_flop, + aten.baddbmm: baddbmm_flop, + aten._scaled_mm: _scaled_mm_flop, + aten.convolution: conv_flop, + aten._convolution: conv_flop, + aten.cudnn_convolution: conv_flop, + aten.convolution_overrideable: conv_flop, + aten._slow_conv2d_forward: conv_flop, + aten.convolution_backward: conv_backward_flop, + aten._scaled_dot_product_efficient_attention: sdpa_flop, + aten._scaled_dot_product_flash_attention: sdpa_flop, + aten._scaled_dot_product_cudnn_attention: sdpa_flop, + aten._scaled_dot_product_efficient_attention_backward: sdpa_backward_flop, + aten._scaled_dot_product_flash_attention_backward: sdpa_backward_flop, + aten._scaled_dot_product_cudnn_attention_backward: sdpa_backward_flop, + aten._flash_attention_forward: _flash_attention_forward_flop, + aten._efficient_attention_forward: _efficient_attention_forward_flop, + aten._flash_attention_backward: _flash_attention_backward_flop, + aten._efficient_attention_backward: _efficient_attention_backward_flop, +} + +_register_flex_attention_flops() + + +def normalize_tuple(x): + if not isinstance(x, tuple): + return (x,) + return x + + +# Define the suffixes for different orders of magnitude +suffixes = ["", "K", "M", "B", "T"] +# Thanks BingChat! +def get_suffix_str(number): + # Find the index of the appropriate suffix based on the number of digits + # with some additional overflow. + # i.e. 1.01B should be displayed as 1001M, not 1.001B + index = max(0, min(len(suffixes) - 1, (len(str(number)) - 2) // 3)) + return suffixes[index] + +def convert_num_with_suffix(number, suffix): + index = suffixes.index(suffix) + # Divide the number by 1000^index and format it to two decimal places + value = f"{number / 1000 ** index:.3f}" + # Return the value and the suffix as a string + return value + suffixes[index] + +def convert_to_percent_str(num, denom) -> str: + if denom == 0: + return "0%" + return f"{num / denom:.2%}" + +def _pytreeify_preserve_structure(f): + @wraps(f) + def nf(args): + flat_args, spec = tree_flatten(args) + out = f(*flat_args) + return tree_unflatten(out, spec) + + return nf + + +class FlopCounterMode: + """Count theoretical FLOPs for operators that run inside the context. + + ``FlopCounterMode`` uses ``TorchDispatchMode`` to intercept operations and + apply registered FLOP formulas. Counts are shape-based and formula-defined; + unsupported operations contribute zero FLOPs unless they decompose into + supported operations. + + The optional ``mods`` argument is no longer needed for module attribution. + When ``display`` is true, exiting the context prints a table. Use + ``get_total_flops()`` or ``get_flop_counts()`` to read the same information + programmatically. + + Example usage: + + .. code-block:: python + + mod = ... + inp = ... + + with FlopCounterMode(display=False) as flop_counter: + mod(inp).sum().backward() + + total = flop_counter.get_total_flops() + + """ + + def __init__( + self, + mods: torch.nn.Module | list[torch.nn.Module] | None = None, + depth: int = 2, + display: bool = True, + custom_mapping: dict[Any, Any] | None = None) -> None: + super().__init__() + self.flop_counts: dict[str, dict[Any, int]] = defaultdict(lambda: defaultdict(int)) + self.depth = depth + self.display = display + self.mode: _FlopCounterMode | None = None + if custom_mapping is None: + custom_mapping = {} + if mods is not None: + warnings.warn("mods argument is not needed anymore, you can stop passing it", stacklevel=2) + self.flop_registry = { + **flop_registry, + **{k: v if getattr(v, "_get_raw", False) else shape_wrapper(v) for k, v in custom_mapping.items()} + } + self.mod_tracker = ModuleTracker() + + def get_total_flops(self) -> int: + return sum(self.flop_counts['Global'].values()) + + def get_flop_counts(self) -> dict[str, dict[Any, int]]: + """Return the flop counts as a dictionary of dictionaries. + + The outer + dictionary is keyed by module name, and the inner dictionary is keyed by + operation name. + + Returns: + Dict[str, Dict[Any, int]]: The flop counts as a dictionary. + """ + return {k: dict(v) for k, v in self.flop_counts.items()} + + def get_table(self, depth=None): + if depth is None: + depth = self.depth + if depth is None: + depth = 999999 + + + import tabulate + + tabulate.PRESERVE_WHITESPACE = True + header = ["Module", "FLOP", "% Total"] + values = [] + global_flops = self.get_total_flops() + global_suffix = get_suffix_str(global_flops) + is_global_subsumed = False + + def process_mod(mod_name, depth): + nonlocal is_global_subsumed + + total_flops = sum(self.flop_counts[mod_name].values()) + + is_global_subsumed |= total_flops >= global_flops + + padding = " " * depth + values = [] + values.append([ + padding + mod_name, + convert_num_with_suffix(total_flops, global_suffix), + convert_to_percent_str(total_flops, global_flops) + ]) + for k, v in self.flop_counts[mod_name].items(): + values.append([ + padding + " - " + str(k), + convert_num_with_suffix(v, global_suffix), + convert_to_percent_str(v, global_flops) + ]) + return values + + for mod in sorted(self.flop_counts.keys()): + if mod == 'Global': + continue + mod_depth = mod.count(".") + 1 + if mod_depth > depth: + continue + + cur_values = process_mod(mod, mod_depth - 1) + values.extend(cur_values) + + # We do a bit of messing around here to only output the "Global" value + # if there are any FLOPs in there that aren't already fully contained by + # a module. + if 'Global' in self.flop_counts and not is_global_subsumed: + for value in values: + value[0] = " " + value[0] + + values = process_mod('Global', 0) + values + + if len(values) == 0: + values = [["Global", "0", "0%"]] + + return tabulate.tabulate(values, headers=header, colalign=("left", "right", "right")) + + # NB: This context manager is NOT reentrant + def __enter__(self): + self.flop_counts.clear() + self.mod_tracker.__enter__() + self.mode = _FlopCounterMode(self) + self.mode.__enter__() + return self + + def __exit__(self, *args): + if self.mode is None: + raise AssertionError("Internal error: FlopCounter.__exit__ called but mode is None") + b = self.mode.__exit__(*args) + self.mode = None # break cycles + self.mod_tracker.__exit__() + if self.display: + print(self.get_table(self.depth)) + return b + + def _count_flops(self, func_packet, out, args, kwargs): + if func_packet in self.flop_registry: + flop_count_func = self.flop_registry[func_packet] + flop_count = flop_count_func(*args, **kwargs, out_val=out) # type: ignore[operator] + for par in set(self.mod_tracker.parents): + self.flop_counts[par][func_packet] += flop_count + return out + +class _FlopCounterMode(TorchDispatchMode): + supports_higher_order_operators = True + + def __init__(self, counter: FlopCounterMode) -> None: + self.counter = counter + + def _execute_with_isolated_flop_counting(self, branch_fn, operands): + """Execute a branch function and capture its FLOP counts without + affecting self.counter.flop_counts + + Args: + branch_fn: The branch function to execute + operands: Arguments to pass to the branch function + + Returns: + Tuple of (result, flop_counts) where result is the branch output + and flop_counts is a copy of the FLOP counts after execution + """ + import copy + checkpointed_flop_counts = copy.copy(self.counter.flop_counts) + with self: + result = branch_fn(*operands) + flop_counts = copy.copy(self.counter.flop_counts) + self.counter.flop_counts = checkpointed_flop_counts + return result, flop_counts + + def _handle_higher_order_ops(self, func, types, args, kwargs): + is_triton = func in {torch.ops.higher_order.triton_kernel_wrapper_mutation, + torch.ops.higher_order.triton_kernel_wrapper_functional} + if is_triton: + from torch._higher_order_ops.triton_kernel_wrap import get_kernel + # Special case - look in the triton flop registry for the kernel + from triton.runtime.jit import JITFunction + kernel_name = get_kernel(kwargs["kernel_idx"]) + # Unwrap heuristics if they are present + while not isinstance(kernel_name, JITFunction): + if hasattr(kernel_name, "fn"): + kernel_name = kernel_name.fn + else: + break + return self.counter._count_flops(kernel_name, None, args, kwargs) + elif func is torch.ops.higher_order.cond: + # The flop counter for cond counts the upper bound of flops. + # For example, if a matmul is executed 2 times in true branch + # but only 1 time in the false branch, the flop counter will + # record the larger number of flops, i.e. 2 times. + pred, true_branch, false_branch, operands = args + # Step 1: Count flops for true branch and false branch separately + true_out, true_flop_counts = self._execute_with_isolated_flop_counting( + true_branch, operands + ) + if true_out is NotImplemented: + return NotImplemented + + false_out, false_flop_counts = self._execute_with_isolated_flop_counting( + false_branch, operands + ) + if false_out is NotImplemented: + return NotImplemented + + # Step 2: merge flop counts + all_mod_keys = set(true_flop_counts.keys()) | set(false_flop_counts.keys()) + merged_flop_counts = {} + for outer_key in all_mod_keys: + true_func_counts = true_flop_counts[outer_key] + false_func_counts = false_flop_counts[outer_key] + + merged_func_counts = {} + all_func_keys = set(true_func_counts.keys()) | set(false_func_counts.keys()) + + for func_key in all_func_keys: + true_val = true_func_counts.get(func_key, 0) + false_val = false_func_counts.get(func_key, 0) + merged_func_counts[func_key] = max(true_val, false_val) + + merged_flop_counts[outer_key] = merged_func_counts + + # Step 3: update the counter with merged counts + for outer_key, inner_dict in merged_flop_counts.items(): + self.counter.flop_counts[outer_key].update(inner_dict) + + # It doesn't matter which one we return since true_fn and false_fn return + # output with the same structure. + return true_out + else: + return NotImplemented + + def __torch_dispatch__(self, func, types, args=(), kwargs=None): + kwargs = kwargs if kwargs else {} + + # Skip ops from non-standard dispatch_sizes_strides_policy such as NJT + if func in {torch.ops.aten.sym_is_contiguous.default, + torch.ops.aten.is_contiguous.default, + torch.ops.aten.is_contiguous.memory_format, + torch.ops.aten.is_strides_like_format.default, + torch.ops.aten.is_non_overlapping_and_dense.default, + torch.ops.aten.size.default, + torch.ops.aten.sym_size.default, + torch.ops.aten.stride.default, + torch.ops.aten.sym_stride.default, + torch.ops.aten.storage_offset.default, + torch.ops.aten.sym_storage_offset.default, + torch.ops.aten.numel.default, + torch.ops.aten.sym_numel.default, + torch.ops.aten.dim.default, + torch.ops.prim.layout.default}: + + return NotImplemented + + if isinstance(func, torch._ops.HigherOrderOperator): + return self._handle_higher_order_ops(func, types, args, kwargs) + + # If we don't have func in flop_registry, see if it can decompose + if func not in self.counter.flop_registry and func is not torch.ops.prim.device.default: + with self: + r = func.decompose(*args, **kwargs) + if r is not NotImplemented: + return r + + # no further decomposition; execute & count flops + out = func(*args, **kwargs) + return self.counter._count_flops(func._overloadpacket, out, args, kwargs) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/hipify/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/hipify/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..58f3ace6c03d093337c9fa417ccbe8bc267b6c69 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/hipify/__init__.py @@ -0,0 +1 @@ +from .version import __version__ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c592ed8d8f185253b2622be75e5b348f14874ba5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/constants.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c47efb2357e31ba56ea215dd5cbf87b19f4aab58 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/constants.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/cuda_to_hip_mappings.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/cuda_to_hip_mappings.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ad8995c730803d6b62d53a2b5cf5b0be52a38ea --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/cuda_to_hip_mappings.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf6d55ff3ab01745bec8400bda9286b4fa0c0b7463f5c4f5e8aab4883108bfa4 +size 166120 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/hipify_python.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/hipify_python.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b62aedecb6a102b28a22f9ce313b011088a43de Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/hipify_python.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8571ef33526eade24899c3266855327dd7d6fc8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/version.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/hipify/constants.py b/.venv/lib/python3.12/site-packages/torch/utils/hipify/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..c9e1bc4dc410cce97c6bc0b55391387fd04c349c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/hipify/constants.py @@ -0,0 +1,66 @@ +"""Constants for annotations in the mapping. + +The constants defined here are used to annotate the mapping tuples in cuda_to_hip_mappings.py. +They are based on +https://github.com/ROCm/HIPIFY/blob/master/src/Statistics.h +and fall in three categories: 1) type of mapping, 2) API of mapping, 3) unsupported +mapping. +""" + +import warnings +warnings.warn("hipify's constants.py is no longer used as of version 2.0.0", FutureWarning) + +CONV_VERSION = 0, +CONV_INIT = 1 +CONV_DEVICE = 2 +CONV_MEM = 3 +CONV_KERN = 4 +CONV_COORD_FUNC = 5 +CONV_MATH_FUNC = 6 +CONV_DEVICE_FUNC = 7 +CONV_SPECIAL_FUNC = 8 +CONV_STREAM = 9 +CONV_EVENT = 10 +CONV_OCCUPANCY = 11 +CONV_CONTEXT = 12 +CONV_PEER = 13 +CONV_MODULE = 14 +CONV_CACHE = 15 +CONV_EXEC = 16 +CONV_ERROR = 17 +CONV_DEF = 18 +CONV_TEX = 19 +CONV_GL = 20 +CONV_GRAPHICS = 21 +CONV_SURFACE = 22 +CONV_JIT = 23 +CONV_D3D9 = 24 +CONV_D3D10 = 25 +CONV_D3D11 = 26 +CONV_VDPAU = 27 +CONV_EGL = 28 +CONV_THREAD = 29 +CONV_OTHER = 30 +CONV_INCLUDE = 31 +CONV_INCLUDE_CUDA_MAIN_H = 32 +CONV_TYPE = 33 +CONV_LITERAL = 34 +CONV_NUMERIC_LITERAL = 35 +CONV_LAST = 36 + +API_DRIVER = 37 +API_RUNTIME = 38 +API_BLAS = 39 +API_SPECIAL = 40 +API_RAND = 41 +API_LAST = 42 +API_FFT = 43 +API_RTC = 44 +API_ROCTX = 45 +API_PYT_EXT = 46 + +HIP_UNSUPPORTED = 47 +API_PYTORCH = 1337 +API_CAFFE2 = 1338 +API_C10 = 1339 +API_ROCMSMI = 1340 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/hipify/cuda_to_hip_mappings.py b/.venv/lib/python3.12/site-packages/torch/utils/hipify/cuda_to_hip_mappings.py new file mode 100644 index 0000000000000000000000000000000000000000..9b2b7727ef32c0e0ea3fedc3bc32bc40b322d221 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/hipify/cuda_to_hip_mappings.py @@ -0,0 +1,3533 @@ +import collections +import os + +""" Mapping of CUDA functions, include files, constants, and types to ROCm/HIP equivalents """ + +_IS_FBCODE = os.environ.get("IS_FBCODE", "0") == "1" + +# FBCODE compiles against rccl sources instead of an installed rccl package. +# The header location is src/rccl.h versus rccl/rccl.h, respectively. +_RCCL_HEADER = "" if _IS_FBCODE else "" + +# List of math functions that should be replaced inside device code only. +MATH_TRANSPILATIONS = collections.OrderedDict([ + ("std::max", ("::max")), + ("std::min", ("::min")), + ("std::ceil", ("::ceil")), + ("std::floor", ("::floor")), + ("std::exp", ("::exp")), + ("std::log", ("::log")), + ("std::pow", ("::pow")), + ("std::fabs", ("::fabs")), + ("std::fmod", ("::fmod")), + ("std::remainder", ("::remainder")), + ("std::frexp", ("::frexp")), +]) + +CUDA_TYPE_NAME_MAP = collections.OrderedDict([ + ("CUresult", "hipError_t"), + ("cudaError_t", "hipError_t"), + ("cudaError", "hipError_t"), + ("CUDA_ARRAY3D_DESCRIPTOR", "HIP_ARRAY3D_DESCRIPTOR"), + ("CUDA_ARRAY_DESCRIPTOR", "HIP_ARRAY_DESCRIPTOR"), + ("CUDA_MEMCPY2D", "hip_Memcpy2D"), + ("CUDA_MEMCPY3D", "HIP_MEMCPY3D"), + ("CUDA_MEMCPY3D_PEER", "HIP_MEMCPY3D_PEER"), + ("CUDA_POINTER_ATTRIBUTE_P2P_TOKENS", "HIP_POINTER_ATTRIBUTE_P2P_TOKENS"), + ("CUDA_RESOURCE_DESC", "HIP_RESOURCE_DESC"), + ("CUDA_RESOURCE_VIEW_DESC", "HIP_RESOURCE_VIEW_DESC"), + ("CUipcEventHandle", "hipIpcEventHandle"), + ("CUipcMemHandle", "hipIpcMemHandle"), + ("CUaddress_mode", "hipAddress_mode"), + ("CUarray_cubemap_face", "hipArray_cubemap_face"), + ("CUarray_format", "hipArray_format"), + ("CUcomputemode", "hipComputemode"), + ("CUmem_advise", "hipMemAdvise"), + ("CUmem_range_attribute", "hipMemRangeAttribute"), + ("CUctx_flags", "hipCctx_flags"), + ("CUdevice", "hipDevice_t"), + ("CUdevice_attribute_enum", "hipDeviceAttribute_t"), + ("CUdevice_attribute", "hipDeviceAttribute_t"), + ("CUpointer_attribute", "hipPointer_attribute"), + ("CU_POINTER_ATTRIBUTE_DEVICE_ORDINAL", "HIP_POINTER_ATTRIBUTE_DEVICE_ORDINAL"), + ("CU_POINTER_ATTRIBUTE_BUFFER_ID", "HIP_POINTER_ATTRIBUTE_BUFFER_ID"), + ("CUdeviceptr", "hipDeviceptr_t"), + ("CUarray_st", "hipArray"), + ("CUarray", "hipArray *"), + ("CUdevprop_st", "hipDeviceProp_t"), + ("CUdevprop", "hipDeviceProp_t"), + ("CUfunction", "hipFunction_t"), + ("CUgraphicsResource", "hipGraphicsResource_t"), + ("CUmipmappedArray", "hipMipmappedArray_t"), + ("CUfunction_attribute", "hipFuncAttribute_t"), + ("CUfunction_attribute_enum", "hipFuncAttribute_t"), + ("CUgraphicsMapResourceFlags", "hipGraphicsMapFlags"), + ("CUgraphicsMapResourceFlags_enum", "hipGraphicsMapFlags"), + ("CUgraphicsRegisterFlags", "hipGraphicsRegisterFlags"), + ("CUgraphicsRegisterFlags_enum", "hipGraphicsRegisterFlags"), + ("CUoccupancy_flags", "hipOccupancyFlags"), + ("CUoccupancy_flags_enum", "hipOccupancyFlags"), + ("CUfunc_cache_enum", "hipFuncCache"), + ("CUfunc_cache", "hipFuncCache"), + ("CUipcMem_flags", "hipIpcMemFlags"), + ("CUipcMem_flags_enum", "hipIpcMemFlags"), + ("CUjit_cacheMode", "hipJitCacheMode"), + ("CUjit_cacheMode_enum", "hipJitCacheMode"), + ("CUjit_fallback", "hipJitFallback"), + ("CUjit_fallback_enum", "hipJitFallback"), + ("CUjit_option", "hipJitOption"), + ("CUjit_option_enum", "hipJitOption"), + ("CUjit_target", "hipJitTarget"), + ("CUjit_target_enum", "hipJitTarget"), + ("CUjitInputType", "hipJitInputType"), + ("CUjitInputType_enum", "hipJitInputType"), + ("CUlimit", "hipLimit_t"), + ("CUlimit_enum", "hipLimit_t"), + ("CUmemAccessDesc", "hipMemAccessDesc"), + ("CUmemAccessDesc_st", "hipMemAccessDesc"), + ("CUmemAccessDesc_v1", "hipMemAccessDesc"), + ("CUmemAttach_flags", "hipMemAttachFlags_t"), + ("CUmemAttach_flags_enum", "hipMemAttachFlags_t"), + ("CUmemAllocationGranularity_flags", "hipMemAllocationGranularity_flags"), + ("CUmemAllocationGranularity_flags_enum", "hipMemAllocationGranularity_flags"), + ("CUmemAllocationHandleType", "hipMemAllocationHandleType"), + ("CUmemAllocationHandleType_enum", "hipMemAllocationHandleType"), + ("CUmemAllocationProp", "hipMemAllocationProp"), + ("CUmemAllocationProp_st", "hipMemAllocationProp"), + ("CUmemAllocationProp_v1", "hipMemAllocationProp"), + ("CUmemAllocationType", "hipMemAllocationType"), + ("CUmemAllocationType_enum", "hipMemAllocationType"), + ("CUmemGenericAllocationHandle", "hipMemGenericAllocationHandle_t"), + ("CUmemGenericAllocationHandle_v1", "hipMemGenericAllocationHandle_t"), + ("CUmemHandleType", "hipMemHandleType"), + ("CUmemHandleType_enum", "hipMemHandleType"), + ("CUmemLocation", "hipMemLocation"), + ("CUmemLocationType", "hipMemLocationType"), + ("CUmemLocationType_enum", "hipMemLocationType"), + ("CUmemLocation_st", "hipMemLocation"), + ("CUmemLocation_v1", "hipMemLocation"), + ("CUmemOperationType", "hipMemOperationType"), + ("CUmemOperationType_enum", "hipMemOperationType"), + ("CUmemPoolHandle_st", "ihipMemPoolHandle_t"), + ("CUmemPoolProps", "hipMemPoolProps"), + ("CUmemPoolProps_st", "hipMemPoolProps"), + ("CUmemPoolProps_v1", "hipMemPoolProps"), + ("CUmemPoolPtrExportData", "hipMemPoolPtrExportData"), + ("CUmemPoolPtrExportData_st", "hipMemPoolPtrExportData"), + ("CUmemPoolPtrExportData_v1", "hipMemPoolPtrExportData"), + ("CUmemPool_attribute", "hipMemPoolAttr"), + ("CUmemPool_attribute_enum", "hipMemPoolAttr"), + ("CUmem_advise_enum", "hipMemoryAdvise"), + ("CUmem_range_attribute_enum", "hipMemRangeAttribute"), + ("CUmemoryPool", "hipMemPool_t"), + ("CUmemorytype", "hipMemType_t"), + ("CUmemorytype_enum", "hipMemType_t"), + ("CUresourcetype", "hipResourceType"), + ("CUresourcetype_enum", "hipResourceType"), + ("CUresourceViewFormat", "hipResourceViewFormat"), + ("CUresourceViewFormat_enum", "hipResourceViewFormat"), + ("CUsharedconfig", "hipSharedMemConfig"), + ("CUsharedconfig_enum", "hipSharedMemConfig"), + ("CUcontext", "hipCtx_t"), + ("CUmodule", "hipModule_t"), + ("CUstream", "hipStream_t"), + ("CUstream_st", "ihipStream_t"), + ("CUstreamCallback", "hipStreamCallback_t"), + ("CUsurfObject", "hipSurfaceObject"), + ("CUsurfref", "hipSurfaceReference_t"), + ("CUtexObject", "hipTextureObject_t"), + ("CUtexref", "textureReference"), + ("CUstream_flags", "hipStreamFlags"), + ("CUstreamWaitValue_flags", "hipStreamWaitValueFlags"), + ("CUstreamWriteValue_flags", "hipStreamWriteValueFlags"), + ("CUstreamBatchMemOpType", "hipStreamBatchMemOpType"), + ("CUdevice_P2PAttribute", "hipDeviceP2PAttribute"), + ("CUevent", "hipEvent_t"), + ("CUevent_st", "ihipEvent_t"), + ("CUevent_flags", "hipEventFlags"), + ("CUfilter_mode", "hipTextureFilterMode"), + ("CUGLDeviceList", "hipGLDeviceList"), + ("CUGLmap_flags", "hipGLMapFlags"), + ("CUd3d9DeviceList", "hipD3D9DeviceList"), + ("CUd3d9map_flags", "hipD3D9MapFlags"), + ("CUd3d9register_flags", "hipD3D9RegisterFlags"), + ("CUd3d10DeviceList", "hipd3d10DeviceList"), + ("CUd3d10map_flags", "hipD3D10MapFlags"), + ("CUd3d10register_flags", "hipD3D10RegisterFlags"), + ("CUd3d11DeviceList", "hipd3d11DeviceList"), + ("CUeglStreamConnection_st", "hipEglStreamConnection"), + ("CUeglStreamConnection", "hipEglStreamConnection"), + ("libraryPropertyType_t", "hipLibraryPropertyType_t"), + ("libraryPropertyType", "hipLibraryPropertyType_t"), + ("cudaStreamCallback_t", "hipStreamCallback_t"), + ("cudaArray", "hipArray"), + ("cudaArray_t", "hipArray_t"), + ("cudaArray_const_t", "hipArray_const_t"), + ("cudaMipmappedArray_t", "hipMipmappedArray_t"), + ("cudaMipmappedArray_const_t", "hipMipmappedArray_const_t"), + ("cudaArrayDefault", "hipArrayDefault"), + ("cudaArrayLayered", "hipArrayLayered"), + ("cudaArraySurfaceLoadStore", "hipArraySurfaceLoadStore"), + ("cudaArrayCubemap", "hipArrayCubemap"), + ("cudaArrayTextureGather", "hipArrayTextureGather"), + ("cudaMemoryAdvise", "hipMemoryAdvise"), + ("cudaMemRangeAttribute", "hipMemRangeAttribute"), + ("cudaMemcpyKind", "hipMemcpyKind"), + ("cudaMemoryType", "hipMemoryType"), + ("cudaExtent", "hipExtent"), + ("cudaPitchedPtr", "hipPitchedPtr"), + ("cudaPos", "hipPos"), + ("cudaEvent_t", "hipEvent_t"), + ("cudaStream_t", "hipStream_t"), + ("cudaPointerAttributes", "hipPointerAttribute_t"), + ("cudaDeviceAttr", "hipDeviceAttribute_t"), + ("cudaDeviceProp", "hipDeviceProp_t"), + ("cudaDeviceP2PAttr", "hipDeviceP2PAttribute"), + ("cudaComputeMode", "hipComputeMode"), + ("cudaFuncCache", "hipFuncCache_t"), + ("cudaFuncAttributes", "hipFuncAttributes"), + ("cudaSharedMemConfig", "hipSharedMemConfig"), + ("cudaLimit", "hipLimit_t"), + ("cudaOutputMode", "hipOutputMode"), + ("cudaTextureReadMode", "hipTextureReadMode"), + ("cudaTextureFilterMode", "hipTextureFilterMode"), + ("cudaChannelFormatKind", "hipChannelFormatKind"), + ("cudaChannelFormatDesc", "hipChannelFormatDesc"), + ("cudaResourceDesc", "hipResourceDesc"), + ("cudaResourceViewDesc", "hipResourceViewDesc"), + ("cudaTextureDesc", "hipTextureDesc"), + ("surfaceReference", "hipSurfaceReference"), + ("cudaTextureObject_t", "hipTextureObject_t"), + ("cudaResourceType", "hipResourceType"), + ("cudaResourceViewFormat", "hipResourceViewFormat"), + ("cudaTextureAddressMode", "hipTextureAddressMode"), + ("cudaSurfaceBoundaryMode", "hipSurfaceBoundaryMode"), + ("cudaSurfaceFormatMode", "hipSurfaceFormatMode"), + ("cudaSurfaceObject_t", "hipSurfaceObject_t"), + ("cudaTextureType1D", "hipTextureType1D"), + ("cudaTextureType2D", "hipTextureType2D"), + ("cudaTextureType3D", "hipTextureType3D"), + ("cudaTextureTypeCubemap", "hipTextureTypeCubemap"), + ("cudaTextureType1DLayered", "hipTextureType1DLayered"), + ("cudaTextureType2DLayered", "hipTextureType2DLayered"), + ("cudaTextureTypeCubemapLayered", "hipTextureTypeCubemapLayered"), + ("cudaUUID_t", "hipUUID"), + ("cudaIpcEventHandle_t", "hipIpcEventHandle_t"), + ("cudaIpcEventHandle_st", "hipIpcEventHandle_t"), + ("cudaIpcMemHandle_t", "hipIpcMemHandle_t"), + ("cudaIpcMemHandle_st", "hipIpcMemHandle_t"), + ("cudaGraphicsCubeFace", "hipGraphicsCubeFace"), + ("cudaGraphicsMapFlags", "hipGraphicsMapFlags"), + ("cudaGraphicsRegisterFlags", "hipGraphicsRegisterFlags"), + ("cudaGLDeviceList", "hipGLDeviceList"), + ("cudaGLMapFlags", "hipGLMapFlags"), + ("cudaD3D9DeviceList", "hipD3D9DeviceList"), + ("cudaD3D9MapFlags", "hipD3D9MapFlags"), + ("cudaD3D9RegisterFlags", "hipD3D9RegisterFlags"), + ("cudaD3D10DeviceList", "hipd3d10DeviceList"), + ("cudaD3D10MapFlags", "hipD3D10MapFlags"), + ("cudaD3D10RegisterFlags", "hipD3D10RegisterFlags"), + ("cudaD3D11DeviceList", "hipd3d11DeviceList"), + ("cudaEglStreamConnection", "hipEglStreamConnection"), + ("cublasHandle_t", "hipblasHandle_t"), + ("cublasOperation_t", "hipblasOperation_t"), + ("cublasStatus_t", "hipblasStatus_t"), + ("cublasFillMode_t", "hipblasFillMode_t"), + ("cublasDiagType_t", "hipblasDiagType_t"), + ("cublasSideMode_t", "hipblasSideMode_t"), + ("cublasPointerMode_t", "hipblasPointerMode_t"), + ("cublasGemmAlgo_t", "hipblasGemmAlgo_t"), + ("cublasAtomicsMode_t", "hipblasAtomicsMode_t"), + ("cublasDataType_t", "hipblasDatatype_t"), + ("curandStatus", "hiprandStatus_t"), + ("curandStatus_t", "hiprandStatus_t"), + ("curandRngType", "hiprandRngType_t"), + ("curandRngType_t", "hiprandRngType_t"), + ("curandGenerator_st", "hiprandGenerator_st"), + ("curandGenerator_t", "hiprandGenerator_t"), + ("curandDirectionVectorSet", "hiprandDirectionVectorSet_t"), + ("curandDirectionVectorSet_t", "hiprandDirectionVectorSet_t"), + ("curandOrdering", "hiprandOrdering_t"), + ("curandOrdering_t", "hiprandOrdering_t"), + ("curandDistribution_st", "hiprandDistribution_st"), + ("curandHistogramM2V_st", "hiprandDistribution_st"), + ("curandDistribution_t", "hiprandDistribution_t"), + ("curandHistogramM2V_t", "hiprandDistribution_t"), + ("curandDistributionShift_st", "hiprandDistributionShift_st"), + ("curandDistributionShift_t", "hiprandDistributionShift_t"), + ("curandDistributionM2Shift_st", "hiprandDistributionM2Shift_st"), + ("curandDistributionM2Shift_t", "hiprandDistributionM2Shift_t"), + ("curandHistogramM2_st", "hiprandHistogramM2_st"), + ("curandHistogramM2_t", "hiprandHistogramM2_t"), + ("curandHistogramM2K_st", "hiprandHistogramM2K_st"), + ("curandHistogramM2K_t", "hiprandHistogramM2K_t"), + ("curandDiscreteDistribution_st", "hiprandDiscreteDistribution_st"), + ("curandDiscreteDistribution_t", "hiprandDiscreteDistribution_t"), + ("curandMethod", "hiprandMethod_t"), + ("curandMethod_t", "hiprandMethod_t"), + ("curandDirectionVectors32_t", "hiprandDirectionVectors32_t"), + ("curandDirectionVectors64_t", "hiprandDirectionVectors64_t"), + ("curandStateMtgp32_t", "hiprandStateMtgp32_t"), + ("curandStateMtgp32", "hiprandStateMtgp32_t"), + ("curandStateScrambledSobol64_t", "hiprandStateScrambledSobol64_t"), + ("curandStateSobol64_t", "hiprandStateSobol64_t"), + ("curandStateScrambledSobol32_t", "hiprandStateScrambledSobol32_t"), + ("curandStateSobol32_t", "hiprandStateSobol32_t"), + ("curandStateMRG32k3a_t", "hiprandStateMRG32k3a_t"), + ("curandStatePhilox4_32_10_t", "hiprandStatePhilox4_32_10_t"), + ("curandStateXORWOW_t", "hiprandStateXORWOW_t"), + ("curandState_t", "hiprandState_t"), + ("curandState", "hiprandState_t"), + ("CUuuid", "hipUUID"), + ("cudaGraph_t", "hipGraph_t"), + ("cudaGraphExec_t", "hipGraphExec_t"), + ("__nv_bfloat16", "__hip_bfloat16"), + ("__nv_bfloat162", "__hip_bfloat162"), + ("CUfileHandle_t", "hipFileHandle_t"), + ("CUfileDescr_t", "hipFileDescr_t"), + ("CUfileError_t", "hipFileError_t"), +]) + +CUDA_INCLUDE_MAP = collections.OrderedDict([ + ("include ", _RCCL_HEADER), + ("nvrtc.h", "hip/hiprtc.h"), + ("thrust/system/cuda", "thrust/system/hip"), + ("cub/util_allocator.cuh", "hipcub/hipcub.hpp"), + ("cub/block/block_reduce.cuh", "hipcub/hipcub.hpp"), + ("cub/block/block_raking_layout.cuh", "hipcub/hipcub.hpp"), + ("cub/cub.cuh", "hipcub/hipcub.hpp"), + ("cub/config.cuh", "hipcub/hipcub.hpp"), + ("cub/util_ptx.cuh", "hipcub/hipcub.hpp"), + ("cub/util_type.cuh", "hipcub/hipcub.hpp"), + ("cub/device/device_run_length_encode.cuh", "hipcub/hipcub.hpp"), + ("cub/block/block_load.cuh", "hipcub/hipcub.hpp"), + ("cub/block/block_store.cuh", "hipcub/hipcub.hpp"), + ("cub/block/block_scan.cuh", "hipcub/hipcub.hpp"), + ("cub/device/device_radix_sort.cuh", "hipcub/hipcub.hpp"), + ("cub/device/device_reduce.cuh", "hipcub/hipcub.hpp"), + ("cub/device/device_scan.cuh", "hipcub/hipcub.hpp"), + ("cub/device/device_select.cuh", "hipcub/hipcub.hpp"), + ("nvtx3/nvtx3.hpp", "roctracer/roctx.h"), + ("nvToolsExt.h", "roctracer/roctx.h"), + ("nvml.h", "amd_smi/amdsmi.h"), + ("tensorpipe/tensorpipe_cuda.h", "tensorpipe/tensorpipe_hip.h"), +]) + +CUDA_IDENTIFIER_MAP = collections.OrderedDict([ + ("__CUDACC__", "__HIPCC__"), + ("CUDA_ERROR_INVALID_CONTEXT", "hipErrorInvalidContext"), + ("CUDA_ERROR_CONTEXT_ALREADY_CURRENT", "hipErrorContextAlreadyCurrent"), + ("CUDA_ERROR_ARRAY_IS_MAPPED", "hipErrorArrayIsMapped"), + ("CUDA_ERROR_ALREADY_MAPPED", "hipErrorAlreadyMapped"), + ("CUDA_ERROR_ALREADY_ACQUIRED", "hipErrorAlreadyAcquired"), + ("CUDA_ERROR_NOT_MAPPED", "hipErrorNotMapped"), + ("CUDA_ERROR_NOT_MAPPED_AS_ARRAY", "hipErrorNotMappedAsArray"), + ("CUDA_ERROR_NOT_MAPPED_AS_POINTER", "hipErrorNotMappedAsPointer"), + ("CUDA_ERROR_CONTEXT_ALREADY_IN_USE", "hipErrorContextAlreadyInUse"), + ("CUDA_ERROR_INVALID_SOURCE", "hipErrorInvalidSource"), + ("CUDA_ERROR_FILE_NOT_FOUND", "hipErrorFileNotFound"), + ("CUDA_ERROR_NOT_FOUND", "hipErrorNotFound"), + ("CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING", "hipErrorLaunchIncompatibleTexturing"), + ("CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE", "hipErrorPrimaryContextActive"), + ("CUDA_ERROR_CONTEXT_IS_DESTROYED", "hipErrorContextIsDestroyed"), + ("CUDA_ERROR_NOT_PERMITTED", "hipErrorNotPermitted"), + ("CUDA_ERROR_NOT_SUPPORTED", "hipErrorNotSupported"), + ("cudaErrorMissingConfiguration", "hipErrorMissingConfiguration"), + ("cudaErrorPriorLaunchFailure", "hipErrorPriorLaunchFailure"), + ("cudaErrorInvalidDeviceFunction", "hipErrorInvalidDeviceFunction"), + ("cudaErrorInvalidConfiguration", "hipErrorInvalidConfiguration"), + ("cudaErrorInvalidPitchValue", "hipErrorInvalidPitchValue"), + ("cudaErrorInvalidSymbol", "hipErrorInvalidSymbol"), + ("cudaErrorInvalidHostPointer", "hipErrorInvalidHostPointer"), + ("cudaErrorInvalidDevicePointer", "hipErrorInvalidDevicePointer"), + ("cudaErrorInvalidTexture", "hipErrorInvalidTexture"), + ("cudaErrorInvalidTextureBinding", "hipErrorInvalidTextureBinding"), + ("cudaErrorInvalidChannelDescriptor", "hipErrorInvalidChannelDescriptor"), + ("cudaErrorInvalidMemcpyDirection", "hipErrorInvalidMemcpyDirection"), + ("cudaErrorAddressOfConstant", "hipErrorAddressOfConstant"), + ("cudaErrorTextureFetchFailed", "hipErrorTextureFetchFailed"), + ("cudaErrorTextureNotBound", "hipErrorTextureNotBound"), + ("cudaErrorSynchronizationError", "hipErrorSynchronizationError"), + ("cudaErrorInvalidFilterSetting", "hipErrorInvalidFilterSetting"), + ("cudaErrorInvalidNormSetting", "hipErrorInvalidNormSetting"), + ("cudaErrorMixedDeviceExecution", "hipErrorMixedDeviceExecution"), + ("cudaErrorNotYetImplemented", "hipErrorNotYetImplemented"), + ("cudaErrorMemoryValueTooLarge", "hipErrorMemoryValueTooLarge"), + ("cudaErrorInsufficientDriver", "hipErrorInsufficientDriver"), + ("cudaErrorSetOnActiveProcess", "hipErrorSetOnActiveProcess"), + ("cudaErrorInvalidSurface", "hipErrorInvalidSurface"), + ("cudaErrorDuplicateVariableName", "hipErrorDuplicateVariableName"), + ("cudaErrorDuplicateTextureName", "hipErrorDuplicateTextureName"), + ("cudaErrorDuplicateSurfaceName", "hipErrorDuplicateSurfaceName"), + ("cudaErrorDevicesUnavailable", "hipErrorDevicesUnavailable"), + ("cudaErrorIncompatibleDriverContext", "hipErrorIncompatibleDriverContext"), + ("cudaErrorDeviceAlreadyInUse", "hipErrorDeviceAlreadyInUse"), + ("cudaErrorLaunchMaxDepthExceeded", "hipErrorLaunchMaxDepthExceeded"), + ("cudaErrorLaunchFileScopedTex", "hipErrorLaunchFileScopedTex"), + ("cudaErrorLaunchFileScopedSurf", "hipErrorLaunchFileScopedSurf"), + ("cudaErrorSyncDepthExceeded", "hipErrorSyncDepthExceeded"), + ("cudaErrorLaunchPendingCountExceeded", "hipErrorLaunchPendingCountExceeded"), + ("cudaErrorNotPermitted", "hipErrorNotPermitted"), + ("cudaErrorNotSupported", "hipErrorNotSupported"), + ("cudaErrorStartupFailure", "hipErrorStartupFailure"), + ("cudaErrorApiFailureBase", "hipErrorApiFailureBase"), + ("CUDA_SUCCESS", "hipSuccess"), + ("cudaSuccess", "hipSuccess"), + ("CUDA_ERROR_INVALID_VALUE", "hipErrorInvalidValue"), + ("cudaErrorInvalidValue", "hipErrorInvalidValue"), + ("CUDA_ERROR_OUT_OF_MEMORY", "hipErrorMemoryAllocation"), + ("cudaErrorMemoryAllocation", "hipErrorMemoryAllocation"), + ("CUDA_ERROR_NOT_INITIALIZED", "hipErrorNotInitialized"), + ("cudaErrorInitializationError", "hipErrorInitializationError"), + ("CUDA_ERROR_DEINITIALIZED", "hipErrorDeinitialized"), + ("cudaErrorCudartUnloading", "hipErrorDeinitialized"), + ("CUDA_ERROR_PROFILER_DISABLED", "hipErrorProfilerDisabled"), + ("cudaErrorProfilerDisabled", "hipErrorProfilerDisabled"), + ("CUDA_ERROR_PROFILER_NOT_INITIALIZED", "hipErrorProfilerNotInitialized"), + ("cudaErrorProfilerNotInitialized", "hipErrorProfilerNotInitialized"), + ("CUDA_ERROR_PROFILER_ALREADY_STARTED", "hipErrorProfilerAlreadyStarted"), + ("cudaErrorProfilerAlreadyStarted", "hipErrorProfilerAlreadyStarted"), + ("CUDA_ERROR_PROFILER_ALREADY_STOPPED", "hipErrorProfilerAlreadyStopped"), + ("cudaErrorProfilerAlreadyStopped", "hipErrorProfilerAlreadyStopped"), + ("CUDA_ERROR_NO_DEVICE", "hipErrorNoDevice"), + ("cudaErrorNoDevice", "hipErrorNoDevice"), + ("CUDA_ERROR_INVALID_DEVICE", "hipErrorInvalidDevice"), + ("cudaErrorInvalidDevice", "hipErrorInvalidDevice"), + ("CUDA_ERROR_INVALID_IMAGE", "hipErrorInvalidImage"), + ("cudaErrorInvalidKernelImage", "hipErrorInvalidImage"), + ("CUDA_ERROR_MAP_FAILED", "hipErrorMapFailed"), + ("cudaErrorMapBufferObjectFailed", "hipErrorMapFailed"), + ("CUDA_ERROR_UNMAP_FAILED", "hipErrorUnmapFailed"), + ("cudaErrorUnmapBufferObjectFailed", "hipErrorUnmapFailed"), + ("CUDA_ERROR_NO_BINARY_FOR_GPU", "hipErrorNoBinaryForGpu"), + ("cudaErrorNoKernelImageForDevice", "hipErrorNoBinaryForGpu"), + ("CUDA_ERROR_ECC_UNCORRECTABLE", "hipErrorECCNotCorrectable"), + ("cudaErrorECCUncorrectable", "hipErrorECCNotCorrectable"), + ("CUDA_ERROR_UNSUPPORTED_LIMIT", "hipErrorUnsupportedLimit"), + ("cudaErrorUnsupportedLimit", "hipErrorUnsupportedLimit"), + ("CUDA_ERROR_PEER_ACCESS_UNSUPPORTED", "hipErrorPeerAccessUnsupported"), + ("cudaErrorPeerAccessUnsupported", "hipErrorPeerAccessUnsupported"), + ("CUDA_ERROR_INVALID_PTX", "hipErrorInvalidKernelFile"), + ("cudaErrorInvalidPtx", "hipErrorInvalidKernelFile"), + ("CUDA_ERROR_INVALID_GRAPHICS_CONTEXT", "hipErrorInvalidGraphicsContext"), + ("cudaErrorInvalidGraphicsContext", "hipErrorInvalidGraphicsContext"), + ("CUDA_ERROR_NVLINK_UNCORRECTABLE", "hipErrorNvlinkUncorrectable"), + ("cudaErrorNvlinkUncorrectable", "hipErrorNvlinkUncorrectable"), + ("CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND", "hipErrorSharedObjectSymbolNotFound"), + ("cudaErrorSharedObjectSymbolNotFound", "hipErrorSharedObjectSymbolNotFound"), + ("CUDA_ERROR_SHARED_OBJECT_INIT_FAILED", "hipErrorSharedObjectInitFailed"), + ("cudaErrorSharedObjectInitFailed", "hipErrorSharedObjectInitFailed"), + ("CUDA_ERROR_OPERATING_SYSTEM", "hipErrorOperatingSystem"), + ("cudaErrorOperatingSystem", "hipErrorOperatingSystem"), + ("CUDA_ERROR_INVALID_HANDLE", "hipErrorInvalidResourceHandle"), + ("cudaErrorInvalidResourceHandle", "hipErrorInvalidResourceHandle"), + ("CUDA_ERROR_NOT_READY", "hipErrorNotReady"), + ("cudaErrorNotReady", "hipErrorNotReady"), + ("CUDA_ERROR_ILLEGAL_ADDRESS", "hipErrorIllegalAddress"), + ("cudaErrorIllegalAddress", "hipErrorIllegalAddress"), + ("CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES", "hipErrorLaunchOutOfResources"), + ("cudaErrorLaunchOutOfResources", "hipErrorLaunchOutOfResources"), + ("CUDA_ERROR_LAUNCH_TIMEOUT", "hipErrorLaunchTimeOut"), + ("cudaErrorLaunchTimeout", "hipErrorLaunchTimeOut"), + ("CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED", "hipErrorPeerAccessAlreadyEnabled"), + ("cudaErrorPeerAccessAlreadyEnabled", "hipErrorPeerAccessAlreadyEnabled"), + ("CUDA_ERROR_PEER_ACCESS_NOT_ENABLED", "hipErrorPeerAccessNotEnabled"), + ("cudaErrorPeerAccessNotEnabled", "hipErrorPeerAccessNotEnabled"), + ("CUDA_ERROR_ASSERT", "hipErrorAssert"), + ("cudaErrorAssert", "hipErrorAssert"), + ("CUDA_ERROR_TOO_MANY_PEERS", "hipErrorTooManyPeers"), + ("cudaErrorTooManyPeers", "hipErrorTooManyPeers"), + ("CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED", "hipErrorHostMemoryAlreadyRegistered"), + ("cudaErrorHostMemoryAlreadyRegistered", "hipErrorHostMemoryAlreadyRegistered"), + ("CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED", "hipErrorHostMemoryNotRegistered"), + ("cudaErrorHostMemoryNotRegistered", "hipErrorHostMemoryNotRegistered"), + ("CUDA_ERROR_HARDWARE_STACK_ERROR", "hipErrorHardwareStackError"), + ("cudaErrorHardwareStackError", "hipErrorHardwareStackError"), + ("CUDA_ERROR_ILLEGAL_INSTRUCTION", "hipErrorIllegalInstruction"), + ("cudaErrorIllegalInstruction", "hipErrorIllegalInstruction"), + ("CUDA_ERROR_MISALIGNED_ADDRESS", "hipErrorMisalignedAddress"), + ("cudaErrorMisalignedAddress", "hipErrorMisalignedAddress"), + ("CUDA_ERROR_INVALID_ADDRESS_SPACE", "hipErrorInvalidAddressSpace"), + ("cudaErrorInvalidAddressSpace", "hipErrorInvalidAddressSpace"), + ("CUDA_ERROR_INVALID_PC", "hipErrorInvalidPc"), + ("cudaErrorInvalidPc", "hipErrorInvalidPc"), + ("CUDA_ERROR_LAUNCH_FAILED", "hipErrorLaunchFailure"), + ("cudaErrorLaunchFailure", "hipErrorLaunchFailure"), + ("CUDA_ERROR_UNKNOWN", "hipErrorUnknown"), + ("cudaErrorUnknown", "hipErrorUnknown"), + ("CU_TR_ADDRESS_MODE_WRAP", "HIP_TR_ADDRESS_MODE_WRAP"), + ("CU_TR_ADDRESS_MODE_CLAMP", "HIP_TR_ADDRESS_MODE_CLAMP"), + ("CU_TR_ADDRESS_MODE_MIRROR", "HIP_TR_ADDRESS_MODE_MIRROR"), + ("CU_TR_ADDRESS_MODE_BORDER", "HIP_TR_ADDRESS_MODE_BORDER"), + ("CU_CUBEMAP_FACE_POSITIVE_X", "HIP_CUBEMAP_FACE_POSITIVE_X"), + ("CU_CUBEMAP_FACE_NEGATIVE_X", "HIP_CUBEMAP_FACE_NEGATIVE_X"), + ("CU_CUBEMAP_FACE_POSITIVE_Y", "HIP_CUBEMAP_FACE_POSITIVE_Y"), + ("CU_CUBEMAP_FACE_NEGATIVE_Y", "HIP_CUBEMAP_FACE_NEGATIVE_Y"), + ("CU_CUBEMAP_FACE_POSITIVE_Z", "HIP_CUBEMAP_FACE_POSITIVE_Z"), + ("CU_CUBEMAP_FACE_NEGATIVE_Z", "HIP_CUBEMAP_FACE_NEGATIVE_Z"), + ("CU_AD_FORMAT_UNSIGNED_INT8", "HIP_AD_FORMAT_UNSIGNED_INT8"), + ("CU_AD_FORMAT_UNSIGNED_INT16", "HIP_AD_FORMAT_UNSIGNED_INT16"), + ("CU_AD_FORMAT_UNSIGNED_INT32", "HIP_AD_FORMAT_UNSIGNED_INT32"), + ("CU_AD_FORMAT_SIGNED_INT8", "HIP_AD_FORMAT_SIGNED_INT8"), + ("CU_AD_FORMAT_SIGNED_INT16", "HIP_AD_FORMAT_SIGNED_INT16"), + ("CU_AD_FORMAT_SIGNED_INT32", "HIP_AD_FORMAT_SIGNED_INT32"), + ("CU_AD_FORMAT_HALF", "HIP_AD_FORMAT_HALF"), + ("CU_AD_FORMAT_FLOAT", "HIP_AD_FORMAT_FLOAT"), + ("CU_COMPUTEMODE_DEFAULT", "hipComputeModeDefault"), + ("CU_COMPUTEMODE_EXCLUSIVE", "hipComputeModeExclusive"), + ("CU_COMPUTEMODE_PROHIBITED", "hipComputeModeProhibited"), + ("CU_COMPUTEMODE_EXCLUSIVE_PROCESS", "hipComputeModeExclusiveProcess"), + ("CU_MEM_ADVISE_SET_READ_MOSTLY", "hipMemAdviseSetReadMostly"), + ("CU_MEM_ADVISE_UNSET_READ_MOSTLY", "hipMemAdviseUnsetReadMostly"), + ("CU_MEM_ADVISE_SET_PREFERRED_LOCATION", "hipMemAdviseSetPreferredLocation"), + ("CU_MEM_ADVISE_UNSET_PREFERRED_LOCATION", "hipMemAdviseUnsetPreferredLocation"), + ("CU_MEM_ADVISE_SET_ACCESSED_BY", "hipMemAdviseSetAccessedBy"), + ("CU_MEM_ADVISE_UNSET_ACCESSED_BY", "hipMemAdviseUnsetAccessedBy"), + ("CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY", "hipMemRangeAttributeReadMostly"), + ("CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION", "hipMemRangeAttributePreferredLocation"), + ("CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY", "hipMemRangeAttributeAccessedBy"), + ("CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION", "hipMemRangeAttributeLastPrefetchLocation"), + ("CU_CTX_SCHED_AUTO", "HIP_CTX_SCHED_AUTO"), + ("CU_CTX_SCHED_SPIN", "HIP_CTX_SCHED_SPIN"), + ("CU_CTX_SCHED_YIELD", "HIP_CTX_SCHED_YIELD"), + ("CU_CTX_SCHED_BLOCKING_SYNC", "HIP_CTX_SCHED_BLOCKING_SYNC"), + ("CU_CTX_BLOCKING_SYNC", "HIP_CTX_BLOCKING_SYNC"), + ("CU_CTX_SCHED_MASK", "HIP_CTX_SCHED_MASK"), + ("CU_CTX_MAP_HOST", "HIP_CTX_MAP_HOST"), + ("CU_CTX_LMEM_RESIZE_TO_MAX", "HIP_CTX_LMEM_RESIZE_TO_MAX"), + ("CU_CTX_FLAGS_MASK", "HIP_CTX_FLAGS_MASK"), + ("CU_LAUNCH_PARAM_BUFFER_POINTER", "HIP_LAUNCH_PARAM_BUFFER_POINTER"), + ("CU_LAUNCH_PARAM_BUFFER_SIZE", "HIP_LAUNCH_PARAM_BUFFER_SIZE"), + ("CU_LAUNCH_PARAM_END", "HIP_LAUNCH_PARAM_END"), + ("CU_IPC_HANDLE_SIZE", "HIP_IPC_HANDLE_SIZE"), + ("CU_MEMHOSTALLOC_DEVICEMAP", "HIP_MEMHOSTALLOC_DEVICEMAP"), + ("CU_MEMHOSTALLOC_PORTABLE", "HIP_MEMHOSTALLOC_PORTABLE"), + ("CU_MEMHOSTALLOC_WRITECOMBINED", "HIP_MEMHOSTALLOC_WRITECOMBINED"), + ("CU_MEMHOSTREGISTER_DEVICEMAP", "HIP_MEMHOSTREGISTER_DEVICEMAP"), + ("CU_MEMHOSTREGISTER_IOMEMORY", "HIP_MEMHOSTREGISTER_IOMEMORY"), + ("CU_MEMHOSTREGISTER_PORTABLE", "HIP_MEMHOSTREGISTER_PORTABLE"), + ("CU_PARAM_TR_DEFAULT", "HIP_PARAM_TR_DEFAULT"), + ("CU_STREAM_LEGACY", "HIP_STREAM_LEGACY"), + ("CU_STREAM_PER_THREAD", "HIP_STREAM_PER_THREAD"), + ("CU_TRSA_OVERRIDE_FORMAT", "HIP_TRSA_OVERRIDE_FORMAT"), + ("CU_TRSF_NORMALIZED_COORDINATES", "HIP_TRSF_NORMALIZED_COORDINATES"), + ("CU_TRSF_READ_AS_INTEGER", "HIP_TRSF_READ_AS_INTEGER"), + ("CU_TRSF_SRGB", "HIP_TRSF_SRGB"), + ("CUDA_ARRAY3D_2DARRAY", "HIP_ARRAY3D_LAYERED"), + ("CUDA_ARRAY3D_CUBEMAP", "HIP_ARRAY3D_CUBEMAP"), + ("CUDA_ARRAY3D_DEPTH_TEXTURE", "HIP_ARRAY3D_DEPTH_TEXTURE"), + ("CUDA_ARRAY3D_LAYERED", "HIP_ARRAY3D_LAYERED"), + ("CUDA_ARRAY3D_SURFACE_LDST", "HIP_ARRAY3D_SURFACE_LDST"), + ("CUDA_ARRAY3D_TEXTURE_GATHER", "HIP_ARRAY3D_TEXTURE_GATHER"), + ("CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK", "hipDeviceAttributeMaxThreadsPerBlock"), + ("CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X", "hipDeviceAttributeMaxBlockDimX"), + ("CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y", "hipDeviceAttributeMaxBlockDimY"), + ("CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z", "hipDeviceAttributeMaxBlockDimZ"), + ("CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X", "hipDeviceAttributeMaxGridDimX"), + ("CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y", "hipDeviceAttributeMaxGridDimY"), + ("CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z", "hipDeviceAttributeMaxGridDimZ"), + ("CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK", "hipDeviceAttributeMaxSharedMemoryPerBlock"), + ("CU_DEVICE_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK", "hipDeviceAttributeMaxSharedMemoryPerBlock"), + ("CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY", "hipDeviceAttributeTotalConstantMemory"), + ("CU_DEVICE_ATTRIBUTE_WARP_SIZE", "hipDeviceAttributeWarpSize"), + ("CU_DEVICE_ATTRIBUTE_MAX_PITCH", "hipDeviceAttributeMaxPitch"), + ("CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK", "hipDeviceAttributeMaxRegistersPerBlock"), + ("CU_DEVICE_ATTRIBUTE_REGISTERS_PER_BLOCK", "hipDeviceAttributeMaxRegistersPerBlock"), + ("CU_DEVICE_ATTRIBUTE_CLOCK_RATE", "hipDeviceAttributeClockRate"), + ("CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT", "hipDeviceAttributeTextureAlignment"), + ("CU_DEVICE_ATTRIBUTE_GPU_OVERLAP", "hipDeviceAttributeAsyncEngineCount"), + ("CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT", "hipDeviceAttributeMultiprocessorCount"), + ("CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT", "hipDeviceAttributeKernelExecTimeout"), + ("CU_DEVICE_ATTRIBUTE_INTEGRATED", "hipDeviceAttributeIntegrated"), + ("CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY", "hipDeviceAttributeCanMapHostMemory"), + ("CU_DEVICE_ATTRIBUTE_COMPUTE_MODE", "hipDeviceAttributeComputeMode"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH", "hipDeviceAttributeMaxTexture1DWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_WIDTH", "hipDeviceAttributeMaxTexture2DWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_HEIGHT", "hipDeviceAttributeMaxTexture2DHeight"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH", "hipDeviceAttributeMaxTexture3DWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT", "hipDeviceAttributeMaxTexture3DHeight"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH", "hipDeviceAttributeMaxTexture3DDepth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH", "hipDeviceAttributeMaxTexture2DLayeredWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT", "hipDeviceAttributeMaxTexture2DLayeredHeight"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS", "hipDeviceAttributeMaxTexture2DLayeredLayers"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_WIDTH", "hipDeviceAttributeMaxTexture2DLayeredWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_HEIGHT", "hipDeviceAttributeMaxTexture2DLayeredHeight"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES", "hipDeviceAttributeMaxTexture2DLayeredLayers"), + ("CU_DEVICE_ATTRIBUTE_SURFACE_ALIGNMENT", "hipDeviceAttributeSurfaceAlignment"), + ("CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS", "hipDeviceAttributeConcurrentKernels"), + ("CU_DEVICE_ATTRIBUTE_ECC_ENABLED", "hipDeviceAttributeEccEnabled"), + ("CU_DEVICE_ATTRIBUTE_PCI_BUS_ID", "hipDeviceAttributePciBusId"), + ("CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID", "hipDeviceAttributePciDeviceId"), + ("CU_DEVICE_ATTRIBUTE_TCC_DRIVER", "hipDeviceAttributeTccDriver"), + ("CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE", "hipDeviceAttributeMemoryClockRate"), + ("CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH", "hipDeviceAttributeMemoryBusWidth"), + ("CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE", "hipDeviceAttributeL2CacheSize"), + ("CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR", "hipDeviceAttributeMaxThreadsPerMultiProcessor"), + ("CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT", "hipDeviceAttributeAsyncEngineCount"), + ("CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING", "hipDeviceAttributeUnifiedAddressing"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_WIDTH", "hipDeviceAttributeMaxTexture1DLayeredWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_LAYERS", "hipDeviceAttributeMaxTexture1DLayeredLayers"), + ("CU_DEVICE_ATTRIBUTE_CAN_TEX2D_GATHER", "hipDeviceAttributeCanTex2DGather"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_WIDTH", "hipDeviceAttributeMaxTexture2DGatherWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_HEIGHT", "hipDeviceAttributeMaxTexture2DGatherHeight"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE", "hipDeviceAttributeMaxTexture3DWidthAlternate"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE", "hipDeviceAttributeMaxTexture3DHeightAlternate"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE", "hipDeviceAttributeMaxTexture3DDepthAlternate"), + ("CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID", "hipDeviceAttributePciDomainId"), + ("CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT", "hipDeviceAttributeTexturePitchAlignment"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_WIDTH", "hipDeviceAttributeMaxTextureCubemapWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH", "hipDeviceAttributeMaxTextureCubemapLayeredWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS", "hipDeviceAttributeMaxTextureCubemapLayeredLayers"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_WIDTH", "hipDeviceAttributeMaxSurface1DWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_WIDTH", "hipDeviceAttributeMaxSurface2DWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_HEIGHT", "hipDeviceAttributeMaxSurface2DHeight"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_WIDTH", "hipDeviceAttributeMaxSurface3DWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_HEIGHT", "hipDeviceAttributeMaxSurface3DHeight"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_DEPTH", "hipDeviceAttributeMaxSurface3DDepth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_WIDTH", "hipDeviceAttributeMaxSurface1DLayeredWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_LAYERS", "hipDeviceAttributeMaxSurface1DLayeredLayers"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_WIDTH", "hipDeviceAttributeMaxSurface2DLayeredWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_HEIGHT", "hipDeviceAttributeMaxSurface2DLayeredHeight"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_LAYERS", "hipDeviceAttributeMaxSurface2DLayeredLayers"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_WIDTH", "hipDeviceAttributeMaxSurfaceCubemapWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH", "hipDeviceAttributeMaxSurfaceCubemapLayeredWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS", "hipDeviceAttributeMaxSurfaceCubemapLayeredLayers"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH", "hipDeviceAttributeMaxTexture1DLinearWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH", "hipDeviceAttributeMaxTexture2DLinearWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT", "hipDeviceAttributeMaxTexture2DLinearHeight"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH", "hipDeviceAttributeMaxTexture2DLinearPitch"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH", "hipDeviceAttributeMaxTexture2DMipmappedWidth"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT", "hipDeviceAttributeMaxTexture2DMipmappedHeight"), + ("CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR", "hipDeviceAttributeComputeCapabilityMajor"), + ("CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR", "hipDeviceAttributeComputeCapabilityMinor"), + ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH", "hipDeviceAttributeMaxTexture1DMipmappedWidth"), + ("CU_DEVICE_ATTRIBUTE_STREAM_PRIORITIES_SUPPORTED", "hipDeviceAttributeStreamPrioritiesSupported"), + ("CU_DEVICE_ATTRIBUTE_GLOBAL_L1_CACHE_SUPPORTED", "hipDeviceAttributeGlobalL1CacheSupported"), + ("CU_DEVICE_ATTRIBUTE_LOCAL_L1_CACHE_SUPPORTED", "hipDeviceAttributeLocalL1CacheSupported"), + ("CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR", "hipDeviceAttributeMaxSharedMemoryPerMultiprocessor"), + ("CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR", "hipDeviceAttributeMaxRegistersPerMultiprocessor"), + ("CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY", "hipDeviceAttributeManagedMemory"), + ("CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD", "hipDeviceAttributeIsMultiGpuBoard"), + ("CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD_GROUP_ID", "hipDeviceAttributeMultiGpuBoardGroupId"), + ("CU_DEVICE_ATTRIBUTE_HOST_NATIVE_ATOMIC_SUPPORTED", "hipDeviceAttributeHostNativeAtomicSupported"), + ("CU_DEVICE_ATTRIBUTE_SINGLE_TO_DOUBLE_PRECISION_PERF_RATIO", "hipDeviceAttributeSingleToDoublePrecisionPerfRatio"), + ("CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS", "hipDeviceAttributePageableMemoryAccess"), + ("CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS", "hipDeviceAttributeConcurrentManagedAccess"), + ("CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED", "hipDeviceAttributeComputePreemptionSupported"), + ("CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM", "hipDeviceAttributeCanUseHostPointerForRegisteredMem"), + ("CU_DEVICE_ATTRIBUTE_MAX", "hipDeviceAttributeMax"), + ("CU_POINTER_ATTRIBUTE_CONTEXT", "hipPointerAttributeContext"), + ("CU_POINTER_ATTRIBUTE_MEMORY_TYPE", "hipPointerAttributeMemoryType"), + ("CU_POINTER_ATTRIBUTE_DEVICE_POINTER", "hipPointerAttributeDevicePointer"), + ("CU_POINTER_ATTRIBUTE_HOST_POINTER", "hipPointerAttributeHostPointer"), + ("CU_POINTER_ATTRIBUTE_P2P_TOKENS", "hipPointerAttributeP2pTokens"), + ("CU_POINTER_ATTRIBUTE_SYNC_MEMOPS", "hipPointerAttributeSyncMemops"), + ("CU_POINTER_ATTRIBUTE_BUFFER_ID", "hipPointerAttributeBufferId"), + ("CU_POINTER_ATTRIBUTE_IS_MANAGED", "hipPointerAttributeIsManaged"), + ("CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK", "hipFuncAttributeMaxThreadsPerBlocks"), + ("CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES", "hipFuncAttributeSharedSizeBytes"), + ("CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES", "hipFuncAttributeMaxDynamicSharedMemorySize"), + ("CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES", "hipFuncAttributeConstSizeBytes"), + ("CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES", "hipFuncAttributeLocalSizeBytes"), + ("CU_FUNC_ATTRIBUTE_NUM_REGS", "hipFuncAttributeNumRegs"), + ("CU_FUNC_ATTRIBUTE_PTX_VERSION", "hipFuncAttributePtxVersion"), + ("CU_FUNC_ATTRIBUTE_BINARY_VERSION", "hipFuncAttributeBinaryVersion"), + ("CU_FUNC_ATTRIBUTE_CACHE_MODE_CA", "hipFuncAttributeCacheModeCA"), + ("CU_FUNC_ATTRIBUTE_MAX", "hipFuncAttributeMax"), + ("CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE", "hipGraphicsMapFlagsNone"), + ("CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY", "hipGraphicsMapFlagsReadOnly"), + ("CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD", "hipGraphicsMapFlagsWriteDiscard"), + ("CU_GRAPHICS_REGISTER_FLAGS_NONE", "hipGraphicsRegisterFlagsNone"), + ("CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY", "hipGraphicsRegisterFlagsReadOnly"), + ("CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD", "hipGraphicsRegisterFlagsWriteDiscard"), + ("CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST", "hipGraphicsRegisterFlagsSurfaceLoadStore"), + ("CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER", "hipGraphicsRegisterFlagsTextureGather"), + ("CU_OCCUPANCY_DEFAULT", "hipOccupancyDefault"), + ("CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE", "hipOccupancyDisableCachingOverride"), + ("CU_FUNC_CACHE_PREFER_NONE", "hipFuncCachePreferNone"), + ("CU_FUNC_CACHE_PREFER_SHARED", "hipFuncCachePreferShared"), + ("CU_FUNC_CACHE_PREFER_L1", "hipFuncCachePreferL1"), + ("CU_FUNC_CACHE_PREFER_EQUAL", "hipFuncCachePreferEqual"), + ("CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS", "hipIpcMemLazyEnablePeerAccess"), + ("CUDA_IPC_HANDLE_SIZE", "HIP_IPC_HANDLE_SIZE"), + ("CU_JIT_CACHE_OPTION_NONE", "hipJitCacheModeOptionNone"), + ("CU_JIT_CACHE_OPTION_CG", "hipJitCacheModeOptionCG"), + ("CU_JIT_CACHE_OPTION_CA", "hipJitCacheModeOptionCA"), + ("CU_PREFER_PTX", "hipJitFallbackPreferPtx"), + ("CU_PREFER_BINARY", "hipJitFallbackPreferBinary"), + ("CU_JIT_MAX_REGISTERS", "hipJitOptionMaxRegisters"), + ("CU_JIT_THREADS_PER_BLOCK", "hipJitOptionThreadsPerBlock"), + ("CU_JIT_WALL_TIME", "hipJitOptionWallTime"), + ("CU_JIT_INFO_LOG_BUFFER", "hipJitOptionInfoLogBuffer"), + ("CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES", "hipJitOptionInfoLogBufferSizeBytes"), + ("CU_JIT_ERROR_LOG_BUFFER", "hipJitOptionErrorLogBuffer"), + ("CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES", "hipJitOptionErrorLogBufferSizeBytes"), + ("CU_JIT_OPTIMIZATION_LEVEL", "hipJitOptionOptimizationLevel"), + ("CU_JIT_TARGET_FROM_CUCONTEXT", "hipJitOptionTargetFromContext"), + ("CU_JIT_TARGET", "hipJitOptionTarget"), + ("CU_JIT_FALLBACK_STRATEGY", "hipJitOptionFallbackStrategy"), + ("CU_JIT_GENERATE_DEBUG_INFO", "hipJitOptionGenerateDebugInfo"), + ("CU_JIT_LOG_VERBOSE", "hipJitOptionLogVerbose"), + ("CU_JIT_GENERATE_LINE_INFO", "hipJitOptionGenerateLineInfo"), + ("CU_JIT_CACHE_MODE", "hipJitOptionCacheMode"), + ("CU_JIT_NEW_SM3X_OPT", "hipJitOptionSm3xOpt"), + ("CU_JIT_FAST_COMPILE", "hipJitOptionFastCompile"), + ("CU_JIT_NUM_OPTIONS", "hipJitOptionNumOptions"), + ("CU_TARGET_COMPUTE_10", "hipJitTargetCompute10"), + ("CU_TARGET_COMPUTE_11", "hipJitTargetCompute11"), + ("CU_TARGET_COMPUTE_12", "hipJitTargetCompute12"), + ("CU_TARGET_COMPUTE_13", "hipJitTargetCompute13"), + ("CU_TARGET_COMPUTE_20", "hipJitTargetCompute20"), + ("CU_TARGET_COMPUTE_21", "hipJitTargetCompute21"), + ("CU_TARGET_COMPUTE_30", "hipJitTargetCompute30"), + ("CU_TARGET_COMPUTE_32", "hipJitTargetCompute32"), + ("CU_TARGET_COMPUTE_35", "hipJitTargetCompute35"), + ("CU_TARGET_COMPUTE_37", "hipJitTargetCompute37"), + ("CU_TARGET_COMPUTE_50", "hipJitTargetCompute50"), + ("CU_TARGET_COMPUTE_52", "hipJitTargetCompute52"), + ("CU_TARGET_COMPUTE_53", "hipJitTargetCompute53"), + ("CU_TARGET_COMPUTE_60", "hipJitTargetCompute60"), + ("CU_TARGET_COMPUTE_61", "hipJitTargetCompute61"), + ("CU_TARGET_COMPUTE_62", "hipJitTargetCompute62"), + ("CU_JIT_INPUT_CUBIN", "hipJitInputTypeBin"), + ("CU_JIT_INPUT_PTX", "hipJitInputTypePtx"), + ("CU_JIT_INPUT_FATBINARY", "hipJitInputTypeFatBinary"), + ("CU_JIT_INPUT_OBJECT", "hipJitInputTypeObject"), + ("CU_JIT_INPUT_LIBRARY", "hipJitInputTypeLibrary"), + ("CU_JIT_NUM_INPUT_TYPES", "hipJitInputTypeNumInputTypes"), + ("CU_LIMIT_STACK_SIZE", "hipLimitStackSize"), + ("CU_LIMIT_PRINTF_FIFO_SIZE", "hipLimitPrintfFifoSize"), + ("CU_LIMIT_MALLOC_HEAP_SIZE", "hipLimitMallocHeapSize"), + ("CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH", "hipLimitDevRuntimeSyncDepth"), + ("CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT", "hipLimitDevRuntimePendingLaunchCount"), + ("CU_MEM_ATTACH_GLOBAL", "hipMemAttachGlobal"), + ("CU_MEM_ATTACH_HOST", "hipMemAttachHost"), + ("CU_MEM_ATTACH_SINGLE", "hipMemAttachSingle"), + ("CU_MEMORYTYPE_HOST", "hipMemTypeHost"), + ("CU_MEMORYTYPE_DEVICE", "hipMemTypeDevice"), + ("CU_MEMORYTYPE_ARRAY", "hipMemTypeArray"), + ("CU_MEMORYTYPE_UNIFIED", "hipMemTypeUnified"), + ("CU_MEMHOSTREGISTER_READ_ONLY", "hipHostRegisterReadOnly"), + ("CU_MEMPOOL_ATTR_RELEASE_THRESHOLD", "hipMemPoolAttrReleaseThreshold"), + ("CU_MEMPOOL_ATTR_RESERVED_MEM_CURRENT", "hipMemPoolAttrReservedMemCurrent"), + ("CU_MEMPOOL_ATTR_RESERVED_MEM_HIGH", "hipMemPoolAttrReservedMemHigh"), + ("CU_MEMPOOL_ATTR_REUSE_ALLOW_INTERNAL_DEPENDENCIES", "hipMemPoolReuseAllowInternalDependencies"), + ("CU_MEMPOOL_ATTR_REUSE_ALLOW_OPPORTUNISTIC", "hipMemPoolReuseAllowOpportunistic"), + ("CU_MEMPOOL_ATTR_REUSE_FOLLOW_EVENT_DEPENDENCIES", "hipMemPoolReuseFollowEventDependencies"), + ("CU_MEMPOOL_ATTR_USED_MEM_CURRENT", "hipMemPoolAttrUsedMemCurrent"), + ("CU_MEMPOOL_ATTR_USED_MEM_HIGH", "hipMemPoolAttrUsedMemHigh"), + ("CU_MEM_ACCESS_FLAGS_PROT_NONE", "hipMemAccessFlagsProtNone"), + ("CU_MEM_ACCESS_FLAGS_PROT_READ", "hipMemAccessFlagsProtRead"), + ("CU_MEM_ACCESS_FLAGS_PROT_READWRITE", "hipMemAccessFlagsProtReadWrite"), + ("CU_MEM_ALLOCATION_TYPE_INVALID", "hipMemAllocationTypeInvalid"), + ("CU_MEM_ALLOCATION_TYPE_MAX", "hipMemAllocationTypeMax"), + ("CU_MEM_ALLOCATION_TYPE_PINNED", "hipMemAllocationTypePinned"), + ("CU_MEM_ALLOC_GRANULARITY_MINIMUM", "hipMemAllocationGranularityMinimum"), + ("CU_MEM_ALLOC_GRANULARITY_RECOMMENDED", "hipMemAllocationGranularityRecommended"), + ("CU_MEM_HANDLE_TYPE_GENERIC", "hipMemHandleTypeGeneric"), + ("CU_MEM_HANDLE_TYPE_NONE", "hipMemHandleTypeNone"), + ("CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR", "hipMemHandleTypePosixFileDescriptor"), + ("CU_MEM_HANDLE_TYPE_WIN32", "hipMemHandleTypeWin32"), + ("CU_MEM_HANDLE_TYPE_WIN32_KMT", "hipMemHandleTypeWin32Kmt"), + ("CU_MEM_LOCATION_TYPE_DEVICE", "hipMemLocationTypeDevice"), + ("CU_MEM_LOCATION_TYPE_HOST", "hipMemLocationTypeHost"), + ("CU_MEM_LOCATION_TYPE_INVALID", "hipMemLocationTypeInvalid"), + ("CU_MEM_OPERATION_TYPE_MAP", "hipMemOperationTypeMap"), + ("CU_MEM_OPERATION_TYPE_UNMAP", "hipMemOperationTypeUnmap"), + ("CU_RESOURCE_TYPE_ARRAY", "hipResourceTypeArray"), + ("CU_RESOURCE_TYPE_MIPMAPPED_ARRAY", "hipResourceTypeMipmappedArray"), + ("CU_RESOURCE_TYPE_LINEAR", "hipResourceTypeLinear"), + ("CU_RESOURCE_TYPE_PITCH2D", "hipResourceTypePitch2D"), + ("CU_RES_VIEW_FORMAT_NONE", "hipResViewFormatNone"), + ("CU_RES_VIEW_FORMAT_UINT_1X8", "hipResViewFormatUnsignedChar1"), + ("CU_RES_VIEW_FORMAT_UINT_2X8", "hipResViewFormatUnsignedChar2"), + ("CU_RES_VIEW_FORMAT_UINT_4X8", "hipResViewFormatUnsignedChar4"), + ("CU_RES_VIEW_FORMAT_SINT_1X8", "hipResViewFormatSignedChar1"), + ("CU_RES_VIEW_FORMAT_SINT_2X8", "hipResViewFormatSignedChar2"), + ("CU_RES_VIEW_FORMAT_SINT_4X8", "hipResViewFormatSignedChar4"), + ("CU_RES_VIEW_FORMAT_UINT_1X16", "hipResViewFormatUnsignedShort1"), + ("CU_RES_VIEW_FORMAT_UINT_2X16", "hipResViewFormatUnsignedShort2"), + ("CU_RES_VIEW_FORMAT_UINT_4X16", "hipResViewFormatUnsignedShort4"), + ("CU_RES_VIEW_FORMAT_SINT_1X16", "hipResViewFormatSignedShort1"), + ("CU_RES_VIEW_FORMAT_SINT_2X16", "hipResViewFormatSignedShort2"), + ("CU_RES_VIEW_FORMAT_SINT_4X16", "hipResViewFormatSignedShort4"), + ("CU_RES_VIEW_FORMAT_UINT_1X32", "hipResViewFormatUnsignedInt1"), + ("CU_RES_VIEW_FORMAT_UINT_2X32", "hipResViewFormatUnsignedInt2"), + ("CU_RES_VIEW_FORMAT_UINT_4X32", "hipResViewFormatUnsignedInt4"), + ("CU_RES_VIEW_FORMAT_SINT_1X32", "hipResViewFormatSignedInt1"), + ("CU_RES_VIEW_FORMAT_SINT_2X32", "hipResViewFormatSignedInt2"), + ("CU_RES_VIEW_FORMAT_SINT_4X32", "hipResViewFormatSignedInt4"), + ("CU_RES_VIEW_FORMAT_FLOAT_1X16", "hipResViewFormatHalf1"), + ("CU_RES_VIEW_FORMAT_FLOAT_2X16", "hipResViewFormatHalf2"), + ("CU_RES_VIEW_FORMAT_FLOAT_4X16", "hipResViewFormatHalf4"), + ("CU_RES_VIEW_FORMAT_FLOAT_1X32", "hipResViewFormatFloat1"), + ("CU_RES_VIEW_FORMAT_FLOAT_2X32", "hipResViewFormatFloat2"), + ("CU_RES_VIEW_FORMAT_FLOAT_4X32", "hipResViewFormatFloat4"), + ("CU_RES_VIEW_FORMAT_UNSIGNED_BC1", "hipResViewFormatUnsignedBlockCompressed1"), + ("CU_RES_VIEW_FORMAT_UNSIGNED_BC2", "hipResViewFormatUnsignedBlockCompressed2"), + ("CU_RES_VIEW_FORMAT_UNSIGNED_BC3", "hipResViewFormatUnsignedBlockCompressed3"), + ("CU_RES_VIEW_FORMAT_UNSIGNED_BC4", "hipResViewFormatUnsignedBlockCompressed4"), + ("CU_RES_VIEW_FORMAT_SIGNED_BC4", "hipResViewFormatSignedBlockCompressed4"), + ("CU_RES_VIEW_FORMAT_UNSIGNED_BC5", "hipResViewFormatUnsignedBlockCompressed5"), + ("CU_RES_VIEW_FORMAT_SIGNED_BC5", "hipResViewFormatSignedBlockCompressed5"), + ("CU_RES_VIEW_FORMAT_UNSIGNED_BC6H", "hipResViewFormatUnsignedBlockCompressed6H"), + ("CU_RES_VIEW_FORMAT_SIGNED_BC6H", "hipResViewFormatSignedBlockCompressed6H"), + ("CU_RES_VIEW_FORMAT_UNSIGNED_BC7", "hipResViewFormatUnsignedBlockCompressed7"), + ("CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE", "hipSharedMemBankSizeDefault"), + ("CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE", "hipSharedMemBankSizeFourByte"), + ("CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE", "hipSharedMemBankSizeEightByte"), + ("CU_STREAM_DEFAULT", "hipStreamDefault"), + ("CU_STREAM_NON_BLOCKING", "hipStreamNonBlocking"), + ("CU_STREAM_WAIT_VALUE_GEQ", "hipStreamWaitValueGeq"), + ("CU_STREAM_WAIT_VALUE_EQ", "hipStreamWaitValueEq"), + ("CU_STREAM_WAIT_VALUE_AND", "hipStreamWaitValueAnd"), + ("CU_STREAM_WAIT_VALUE_FLUSH", "hipStreamWaitValueFlush"), + ("CU_STREAM_WRITE_VALUE_DEFAULT", "hipStreamWriteValueDefault"), + ("CU_STREAM_WRITE_VALUE_NO_MEMORY_BARRIER", "hipStreamWriteValueNoMemoryBarrier"), + ("CU_STREAM_MEM_OP_WAIT_VALUE_32", "hipStreamBatchMemOpWaitValue32"), + ("CU_STREAM_MEM_OP_WRITE_VALUE_32", "hipStreamBatchMemOpWriteValue32"), + ("CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES", "hipStreamBatchMemOpFlushRemoteWrites"), + ("cuGetErrorName", "hipGetErrorName"), + ("cuGetErrorString", "hipDrvGetErrorString"), + ("cuInit", "hipInit"), + ("cuDriverGetVersion", "hipDriverGetVersion"), + ("cuCtxCreate", "hipCtxCreate"), + ("cuCtxCreate_v2", "hipCtxCreate"), + ("cuCtxDestroy", "hipCtxDestroy"), + ("cuCtxDestroy_v2", "hipCtxDestroy"), + ("cuCtxGetApiVersion", "hipCtxGetApiVersion"), + ("cuCtxGetCacheConfig", "hipCtxGetCacheConfig"), + ("cuCtxGetCurrent", "hipCtxGetCurrent"), + ("cuCtxGetDevice", "hipCtxGetDevice"), + ("cuCtxGetFlags", "hipCtxGetFlags"), + ("cuDeviceGetUuid", "hipDeviceGetUuid"), + ("cuCtxGetLimit", "hipCtxGetLimit"), + ("cuCtxGetSharedMemConfig", "hipCtxGetSharedMemConfig"), + ("cuCtxGetStreamPriorityRange", "hipCtxGetStreamPriorityRange"), + ("cuCtxPopCurrent_v2", "hipCtxPopCurrent"), + ("cuCtxPushCurrent_v2", "hipCtxPushCurrent"), + ("cuCtxSetCacheConfig", "hipCtxSetCacheConfig"), + ("cuCtxSetCurrent", "hipCtxSetCurrent"), + ("cuCtxSetLimit", "hipCtxSetLimit"), + ("cuCtxSetSharedMemConfig", "hipCtxSetSharedMemConfig"), + ("cuCtxSynchronize", "hipCtxSynchronize"), + ("cuCtxAttach", "hipCtxAttach"), + ("cuCtxDetach", "hipCtxDetach"), + ("cuCtxEnablePeerAccess", "hipCtxEnablePeerAccess"), + ("cuCtxDisablePeerAccess", "hipCtxDisablePeerAccess"), + ("cuDeviceCanAccessPeer", "hipDeviceCanAccessPeer"), + ("cuDeviceGetP2PAttribute", "hipDeviceGetP2PAttribute"), + ("cuDevicePrimaryCtxGetState", "hipDevicePrimaryCtxGetState"), + ("cuDevicePrimaryCtxRelease", "hipDevicePrimaryCtxRelease"), + ("cuDevicePrimaryCtxReset", "hipDevicePrimaryCtxReset"), + ("cuDevicePrimaryCtxRetain", "hipDevicePrimaryCtxRetain"), + ("cuDevicePrimaryCtxSetFlags", "hipDevicePrimaryCtxSetFlags"), + ("cuDeviceGet", "hipDeviceGet"), + ("cuDeviceGetName", "hipDeviceGetName"), + ("cuDeviceGetCount", "hipGetDeviceCount"), + ("cuDeviceGetAttribute", "hipDeviceGetAttribute"), + ("cuDeviceGetPCIBusId", "hipDeviceGetPCIBusId"), + ("cuDeviceGetByPCIBusId", "hipDeviceGetByPCIBusId"), + ("cuDeviceTotalMem_v2", "hipDeviceTotalMem"), + ("cuDeviceComputeCapability", "hipDeviceComputeCapability"), + ("cuDeviceGetProperties", "hipGetDeviceProperties"), + ("cuLinkAddData", "hipLinkAddData"), + ("cuLinkAddFile", "hipLinkAddFile"), + ("cuLinkComplete", "hipLinkComplete"), + ("cuLinkCreate", "hipLinkCreate"), + ("cuLinkDestroy", "hipLinkDestroy"), + ("cuModuleGetFunction", "hipModuleGetFunction"), + ("cuModuleGetGlobal", "hipModuleGetGlobal"), + ("cuModuleGetGlobal_v2", "hipModuleGetGlobal"), + ("cuModuleGetSurfRef", "hipModuleGetSurfRef"), + ("cuModuleGetTexRef", "hipModuleGetTexRef"), + ("cuModuleLoad", "hipModuleLoad"), + ("cuModuleLoadData", "hipModuleLoadData"), + ("cuModuleLoadDataEx", "hipModuleLoadDataEx"), + ("cuModuleLoadFatBinary", "hipModuleLoadFatBinary"), + ("cuModuleUnload", "hipModuleUnload"), + ("CU_DEVICE_P2P_ATTRIBUTE_PERFORMANCE_RANK", "hipDeviceP2PAttributePerformanceRank"), + ("CU_DEVICE_P2P_ATTRIBUTE_ACCESS_SUPPORTED", "hipDeviceP2PAttributeAccessSupported"), + ("CU_DEVICE_P2P_ATTRIBUTE_NATIVE_ATOMIC_SUPPORTED", "hipDeviceP2PAttributeNativeAtomicSupported"), + ("CU_EVENT_DEFAULT", "hipEventDefault"), + ("CU_EVENT_BLOCKING_SYNC", "hipEventBlockingSync"), + ("CU_EVENT_DISABLE_TIMING", "hipEventDisableTiming"), + ("CU_EVENT_INTERPROCESS", "hipEventInterprocess"), + ("cuEventCreate", "hipEventCreate"), + ("cuEventDestroy", "hipEventDestroy"), + ("cuEventDestroy_v2", "hipEventDestroy"), + ("cuEventElapsedTime", "hipEventElapsedTime"), + ("cuEventQuery", "hipEventQuery"), + ("cuEventRecord", "hipEventRecord"), + ("cuEventSynchronize", "hipEventSynchronize"), + ("cuFuncSetAttribute", "hipFuncSetAttribute"), + ("cuFuncGetAttribute", "hipFuncGetAttribute"), + ("cuFuncSetCacheConfig", "hipFuncSetCacheConfig"), + ("cuFuncSetSharedMemConfig", "hipFuncSetSharedMemConfig"), + ("cuLaunchKernel", "hipModuleLaunchKernel"), + ("cuLaunchCooperativeKernel", "hipModuleLaunchCooperativeKernel"), + ("cuFuncSetBlockShape", "hipFuncSetBlockShape"), + ("cuFuncSetSharedSize", "hipFuncSetSharedSize"), + ("cuLaunch", "hipLaunch"), + ("cuLaunchGrid", "hipLaunchGrid"), + ("cuLaunchGridAsync", "hipLaunchGridAsync"), + ("cuParamSetf", "hipParamSetf"), + ("cuParamSeti", "hipParamSeti"), + ("cuParamSetSize", "hipParamSetSize"), + ("cuParamSetv", "hipParamSetv"), + ("cuOccupancyMaxActiveBlocksPerMultiprocessor", "hipModuleOccupancyMaxActiveBlocksPerMultiprocessor"), + ("cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags", "hipModuleOccupancyMaxActiveBlocksPerMultiprocessorWithFlags"), + ("cuOccupancyMaxPotentialBlockSize", "hipModuleOccupancyMaxPotentialBlockSize"), + ("cuOccupancyMaxPotentialBlockSizeWithFlags", "hipModuleOccupancyMaxPotentialBlockSizeWithFlags"), + ("cuStreamAddCallback", "hipStreamAddCallback"), + ("cuStreamAttachMemAsync", "hipStreamAttachMemAsync"), + ("cuStreamCreate", "hipStreamCreate__"), + ("cuStreamCreateWithPriority", "hipStreamCreateWithPriority"), + ("cuStreamDestroy", "hipStreamDestroy"), + ("cuStreamDestroy_v2", "hipStreamDestroy"), + ("cuStreamGetFlags", "hipStreamGetFlags"), + ("cuStreamGetPriority", "hipStreamGetPriority"), + ("cuStreamQuery", "hipStreamQuery"), + ("cuStreamSynchronize", "hipStreamSynchronize"), + ("cuStreamWaitEvent", "hipStreamWaitEvent"), + ("cuStreamWaitValue32", "hipStreamWaitValue32"), + ("cuStreamWriteValue32", "hipStreamWriteValue32"), + ("cuStreamBatchMemOp", "hipStreamBatchMemOp"), + ("cuArray3DCreate", "hipArray3DCreate"), + ("cuArray3DGetDescriptor", "hipArray3DGetDescriptor"), + ("cuArrayCreate", "hipArrayCreate"), + ("cuArrayDestroy", "hipArrayDestroy"), + ("cuArrayGetDescriptor", "hipArrayGetDescriptor"), + ("cuIpcCloseMemHandle", "hipIpcCloseMemHandle"), + ("cuIpcGetEventHandle", "hipIpcGetEventHandle"), + ("cuIpcGetMemHandle", "hipIpcGetMemHandle"), + ("cuIpcOpenEventHandle", "hipIpcOpenEventHandle"), + ("cuIpcOpenMemHandle", "hipIpcOpenMemHandle"), + ("cuMemAlloc_v2", "hipMalloc"), + ("cuMemAllocHost", "hipMemAllocHost"), + ("cuMemAllocManaged", "hipMemAllocManaged"), + ("cuMemAllocPitch", "hipMemAllocPitch__"), + ("cuMemcpy", "hipMemcpy__"), + ("cuMemcpy2D", "hipMemcpy2D__"), + ("cuMemcpy2DAsync", "hipMemcpy2DAsync__"), + ("cuMemcpy2DUnaligned", "hipMemcpy2DUnaligned"), + ("cuMemcpy3D", "hipMemcpy3D__"), + ("cuMemcpy3DAsync", "hipMemcpy3DAsync__"), + ("cuMemcpy3DPeer", "hipMemcpy3DPeer__"), + ("cuMemcpy3DPeerAsync", "hipMemcpy3DPeerAsync__"), + ("cuMemcpyAsync", "hipMemcpyAsync__"), + ("cuMemcpyAtoA", "hipMemcpyAtoA"), + ("cuMemcpyAtoD", "hipMemcpyAtoD"), + ("cuMemcpyAtoH", "hipMemcpyAtoH"), + ("cuMemcpyAtoHAsync", "hipMemcpyAtoHAsync"), + ("cuMemcpyDtoA", "hipMemcpyDtoA"), + ("cuMemcpyDtoD_v2", "hipMemcpyDtoD"), + ("cuMemcpyDtoDAsync_v2", "hipMemcpyDtoDAsync"), + ("cuMemcpyDtoH_v2", "hipMemcpyDtoH"), + ("cuMemcpyDtoHAsync_v2", "hipMemcpyDtoHAsync"), + ("cuMemcpyHtoA", "hipMemcpyHtoA"), + ("cuMemcpyHtoAAsync", "hipMemcpyHtoAAsync"), + ("cuMemcpyHtoD_v2", "hipMemcpyHtoD"), + ("cuMemcpyHtoDAsync_v2", "hipMemcpyHtoDAsync"), + ("cuMemcpyPeerAsync", "hipMemcpyPeerAsync__"), + ("cuMemcpyPeer", "hipMemcpyPeer__"), + ("cuMemFree", "hipFree"), + ("cuMemFree_v2", "hipFree"), + ("cuMemFreeHost", "hipHostFree"), + ("cuMemGetAddressRange", "hipMemGetAddressRange"), + ("cuMemGetInfo_v2", "hipMemGetInfo"), + ("cuMemHostAlloc", "hipHostMalloc"), + ("cuMemHostGetDevicePointer", "hipMemHostGetDevicePointer"), + ("cuMemHostGetFlags", "hipMemHostGetFlags"), + ("cuMemHostRegister_v2", "hipHostRegister"), + ("cuMemHostUnregister", "hipHostUnregister"), + ("cuMemsetD16_v2", "hipMemsetD16"), + ("cuMemsetD16Async", "hipMemsetD16Async"), + ("cuMemsetD2D16_v2", "hipMemsetD2D16"), + ("cuMemsetD2D16Async", "hipMemsetD2D16Async"), + ("cuMemsetD2D32_v2", "hipMemsetD2D32"), + ("cuMemsetD2D32Async", "hipMemsetD2D32Async"), + ("cuMemsetD2D8_v2", "hipMemsetD2D8"), + ("cuMemsetD2D8Async", "hipMemsetD2D8Async"), + ("cuMemsetD32_v2", "hipMemset"), + ("cuMemsetD32Async", "hipMemsetAsync"), + ("cuMemsetD8_v2", "hipMemsetD8"), + ("cuMemsetD8Async", "hipMemsetD8Async"), + ("cuMipmappedArrayCreate", "hipMipmappedArrayCreate"), + ("cuMipmappedArrayDestroy", "hipMipmappedArrayDestroy"), + ("cuMipmappedArrayGetLevel", "hipMipmappedArrayGetLevel"), + ("cuMemPrefetchAsync", "hipMemPrefetchAsync__"), + ("cuMemAdvise", "hipMemAdvise"), + ("cuMemRangeGetAttribute", "hipMemRangeGetAttribute"), + ("cuMemRangeGetAttributes", "hipMemRangeGetAttributes"), + ("cuPointerGetAttribute", "hipPointerGetAttribute"), + ("cuMemGetAddressRange_v2", "hipMemGetAddressRange"), + ("cuArray3DCreate_v2", "hipArray3DCreate"), + ("cuArray3DGetDescriptor_v2", "hipArray3DGetDescriptor"), + ("cuArrayGetDescriptor_v2", "hipArrayGetDescriptor"), + ("cuMemAlloc", "hipMalloc"), + ("cuMemAllocHost_v2", "hipMemAllocHost"), + ("cuMemAllocPitch_v2", "hipMemAllocPitch"), + ("cuMemGetInfo", "hipMemGetInfo"), + ("cuMemHostGetDevicePointer_v2", "hipHostGetDevicePointer"), + ("cuMemHostRegister", "hipHostRegister"), + ("cuMemcpy2DAsync_v2", "hipMemcpyParam2DAsync"), + ("cuMemcpy2DUnaligned_v2", "hipDrvMemcpy2DUnaligned"), + ("cuMemcpy2D_v2", "hipMemcpyParam2D"), + ("cuMemcpy3DAsync_v2", "hipDrvMemcpy3DAsync"), + ("cuMemcpy3D_v2", "hipDrvMemcpy3D"), + ("cuMemcpyAtoA_v2", "hipMemcpyAtoA"), + ("cuMemcpyAtoD_v2", "hipMemcpyAtoD"), + ("cuMemcpyAtoHAsync_v2", "hipMemcpyAtoHAsync"), + ("cuMemcpyAtoH_v2", "hipMemcpyAtoH"), + ("cuMemcpyDtoA_v2", "hipMemcpyDtoA"), + ("cuMemcpyDtoD", "hipMemcpyDtoD"), + ("cuMemcpyDtoDAsync", "hipMemcpyDtoDAsync"), + ("cuMemcpyDtoH", "hipMemcpyDtoH"), + ("cuMemcpyDtoHAsync", "hipMemcpyDtoHAsync"), + ("cuMemcpyHtoA_v2", "hipMemcpyHtoA"), + ("cuMemcpyHtoD", "hipMemcpyHtoD"), + ("cuMemcpyHtoDAsync", "hipMemcpyHtoDAsync"), + ("cuMemsetD16", "hipMemsetD16"), + ("cuMemsetD32", "hipMemsetD32"), + ("cuMemsetD8", "hipMemsetD8"), + ("cuMemAddressFree", "hipMemAddressFree"), + ("cuMemAddressReserve", "hipMemAddressReserve"), + ("cuMemCreate", "hipMemCreate"), + ("cuMemExportToShareableHandle", "hipMemExportToShareableHandle"), + ("cuMemGetAccess", "hipMemGetAccess"), + ("cuMemGetAllocationGranularity", "hipMemGetAllocationGranularity"), + ("cuMemGetAllocationPropertiesFromHandle", "hipMemGetAllocationPropertiesFromHandle"), + ("cuMemImportFromShareableHandle", "hipMemImportFromShareableHandle"), + ("cuMemMap", "hipMemMap"), + ("cuMemMapArrayAsync", "hipMemMapArrayAsync"), + ("cuMemRelease", "hipMemRelease"), + ("cuMemRetainAllocationHandle", "hipMemRetainAllocationHandle"), + ("cuMemSetAccess", "hipMemSetAccess"), + ("cuMemUnmap", "hipMemUnmap"), + ("cuMemAllocAsync", "hipMallocAsync"), + ("cuMemAllocFromPoolAsync", "hipMallocFromPoolAsync"), + ("cuMemFreeAsync", "hipFreeAsync"), + ("cuMemPoolCreate", "hipMemPoolCreate"), + ("cuMemPoolDestroy", "hipMemPoolDestroy"), + ("cuMemPoolExportPointer", "hipMemPoolExportPointer"), + ("cuMemPoolExportToShareableHandle", "hipMemPoolExportToShareableHandle"), + ("cuMemPoolGetAccess", "hipMemPoolGetAccess"), + ("cuMemPoolGetAttribute", "hipMemPoolGetAttribute"), + ("cuMemPoolImportFromShareableHandle", "hipMemPoolImportFromShareableHandle"), + ("cuMemPoolImportPointer", "hipMemPoolImportPointer"), + ("cuMemPoolSetAccess", "hipMemPoolSetAccess"), + ("cuMemPoolSetAttribute", "hipMemPoolSetAttribute"), + ("cuMemPoolTrimTo", "hipMemPoolTrimTo"), + ("cuPointerGetAttributes", "hipPointerGetAttributes"), + ("cuPointerSetAttribute", "hipPointerSetAttribute"), + ("CU_TR_FILTER_MODE_POINT", "hipFilterModePoint"), + ("CU_TR_FILTER_MODE_LINEAR", "hipFilterModeLinear"), + ("cuTexRefGetAddress", "hipTexRefGetAddress"), + ("cuTexRefGetAddressMode", "hipTexRefGetAddressMode"), + ("cuTexRefGetArray", "hipTexRefGetArray"), + ("cuTexRefGetBorderColor", "hipTexRefGetBorderColor"), + ("cuTexRefGetFilterMode", "hipTexRefGetFilterMode"), + ("cuTexRefGetFlags", "hipTexRefGetFlags"), + ("cuTexRefGetFormat", "hipTexRefGetFormat"), + ("cuTexRefGetMaxAnisotropy", "hipTexRefGetMaxAnisotropy"), + ("cuTexRefGetMipmapFilterMode", "hipTexRefGetMipmapFilterMode"), + ("cuTexRefGetMipmapLevelBias", "hipTexRefGetMipmapLevelBias"), + ("cuTexRefGetMipmapLevelClamp", "hipTexRefGetMipmapLevelClamp"), + ("cuTexRefGetMipmappedArray", "hipTexRefGetMipmappedArray"), + ("cuTexRefSetAddress", "hipTexRefSetAddress"), + ("cuTexRefSetAddress2D", "hipTexRefSetAddress2D"), + ("cuTexRefSetAddressMode", "hipTexRefSetAddressMode"), + ("cuTexRefSetArray", "hipTexRefSetArray"), + ("cuTexRefSetBorderColor", "hipTexRefSetBorderColor"), + ("cuTexRefSetFilterMode", "hipTexRefSetFilterMode"), + ("cuTexRefSetFlags", "hipTexRefSetFlags"), + ("cuTexRefSetFormat", "hipTexRefSetFormat"), + ("cuTexRefSetMaxAnisotropy", "hipTexRefSetMaxAnisotropy"), + ("cuTexRefSetMipmapFilterMode", "hipTexRefSetMipmapFilterMode"), + ("cuTexRefSetMipmapLevelBias", "hipTexRefSetMipmapLevelBias"), + ("cuTexRefSetMipmapLevelClamp", "hipTexRefSetMipmapLevelClamp"), + ("cuTexRefSetMipmappedArray", "hipTexRefSetMipmappedArray"), + ("cuTexRefCreate", "hipTexRefCreate"), + ("cuTexRefDestroy", "hipTexRefDestroy"), + ("cuSurfRefGetArray", "hipSurfRefGetArray"), + ("cuSurfRefSetArray", "hipSurfRefSetArray"), + ("cuTexObjectCreate", "hipTexObjectCreate"), + ("cuTexObjectDestroy", "hipTexObjectDestroy"), + ("cuTexObjectGetResourceDesc", "hipTexObjectGetResourceDesc"), + ("cuTexObjectGetResourceViewDesc", "hipTexObjectGetResourceViewDesc"), + ("cuTexObjectGetTextureDesc", "hipTexObjectGetTextureDesc"), + ("cuSurfObjectCreate", "hipSurfObjectCreate"), + ("cuSurfObjectDestroy", "hipSurfObjectDestroy"), + ("cuSurfObjectGetResourceDesc", "hipSurfObjectGetResourceDesc"), + ("cuGraphicsMapResources", "hipGraphicsMapResources"), + ("cuGraphicsResourceGetMappedMipmappedArray", "hipGraphicsResourceGetMappedMipmappedArray"), + ("cuGraphicsResourceGetMappedPointer", "hipGraphicsResourceGetMappedPointer"), + ("cuGraphicsResourceSetMapFlags", "hipGraphicsResourceSetMapFlags"), + ("cuGraphicsSubResourceGetMappedArray", "hipGraphicsSubResourceGetMappedArray"), + ("cuGraphicsUnmapResources", "hipGraphicsUnmapResources"), + ("cuGraphicsUnregisterResource", "hipGraphicsUnregisterResource"), + ("cuProfilerInitialize", "hipProfilerInitialize"), + ("cuProfilerStart", "hipProfilerStart"), + ("cuProfilerStop", "hipProfilerStop"), + ("CU_GL_DEVICE_LIST_ALL", "HIP_GL_DEVICE_LIST_ALL"), + ("CU_GL_DEVICE_LIST_CURRENT_FRAME", "HIP_GL_DEVICE_LIST_CURRENT_FRAME"), + ("CU_GL_DEVICE_LIST_NEXT_FRAME", "HIP_GL_DEVICE_LIST_NEXT_FRAME"), + ("cuGLGetDevices", "hipGLGetDevices"), + ("cuGraphicsGLRegisterBuffer", "hipGraphicsGLRegisterBuffer"), + ("cuGraphicsGLRegisterImage", "hipGraphicsGLRegisterImage"), + ("cuWGLGetDevice", "hipWGLGetDevice"), + ("CU_GL_MAP_RESOURCE_FLAGS_NONE", "HIP_GL_MAP_RESOURCE_FLAGS_NONE"), + ("CU_GL_MAP_RESOURCE_FLAGS_READ_ONLY", "HIP_GL_MAP_RESOURCE_FLAGS_READ_ONLY"), + ("CU_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD", "HIP_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD"), + ("cuGLCtxCreate", "hipGLCtxCreate"), + ("cuGLInit", "hipGLInit"), + ("cuGLMapBufferObject", "hipGLMapBufferObject"), + ("cuGLMapBufferObjectAsync", "hipGLMapBufferObjectAsync"), + ("cuGLRegisterBufferObject", "hipGLRegisterBufferObject"), + ("cuGLSetBufferObjectMapFlags", "hipGLSetBufferObjectMapFlags"), + ("cuGLUnmapBufferObject", "hipGLUnmapBufferObject"), + ("cuGLUnmapBufferObjectAsync", "hipGLUnmapBufferObjectAsync"), + ("cuGLUnregisterBufferObject", "hipGLUnregisterBufferObject"), + ("CU_D3D9_DEVICE_LIST_ALL", "HIP_D3D9_DEVICE_LIST_ALL"), + ("CU_D3D9_DEVICE_LIST_CURRENT_FRAME", "HIP_D3D9_DEVICE_LIST_CURRENT_FRAME"), + ("CU_D3D9_DEVICE_LIST_NEXT_FRAME", "HIP_D3D9_DEVICE_LIST_NEXT_FRAME"), + ("cuD3D9CtxCreate", "hipD3D9CtxCreate"), + ("cuD3D9CtxCreateOnDevice", "hipD3D9CtxCreateOnDevice"), + ("cuD3D9GetDevice", "hipD3D9GetDevice"), + ("cuD3D9GetDevices", "hipD3D9GetDevices"), + ("cuD3D9GetDirect3DDevice", "hipD3D9GetDirect3DDevice"), + ("cuGraphicsD3D9RegisterResource", "hipGraphicsD3D9RegisterResource"), + ("CU_D3D9_MAPRESOURCE_FLAGS_NONE", "HIP_D3D9_MAPRESOURCE_FLAGS_NONE"), + ("CU_D3D9_MAPRESOURCE_FLAGS_READONLY", "HIP_D3D9_MAPRESOURCE_FLAGS_READONLY"), + ("CU_D3D9_MAPRESOURCE_FLAGS_WRITEDISCARD", "HIP_D3D9_MAPRESOURCE_FLAGS_WRITEDISCARD"), + ("CU_D3D9_REGISTER_FLAGS_NONE", "HIP_D3D9_REGISTER_FLAGS_NONE"), + ("CU_D3D9_REGISTER_FLAGS_ARRAY", "HIP_D3D9_REGISTER_FLAGS_ARRAY"), + ("cuD3D9MapResources", "hipD3D9MapResources"), + ("cuD3D9RegisterResource", "hipD3D9RegisterResource"), + ("cuD3D9ResourceGetMappedArray", "hipD3D9ResourceGetMappedArray"), + ("cuD3D9ResourceGetMappedPitch", "hipD3D9ResourceGetMappedPitch"), + ("cuD3D9ResourceGetMappedPointer", "hipD3D9ResourceGetMappedPointer"), + ("cuD3D9ResourceGetMappedSize", "hipD3D9ResourceGetMappedSize"), + ("cuD3D9ResourceGetSurfaceDimensions", "hipD3D9ResourceGetSurfaceDimensions"), + ("cuD3D9ResourceSetMapFlags", "hipD3D9ResourceSetMapFlags"), + ("cuD3D9UnmapResources", "hipD3D9UnmapResources"), + ("cuD3D9UnregisterResource", "hipD3D9UnregisterResource"), + ("CU_D3D10_DEVICE_LIST_ALL", "HIP_D3D10_DEVICE_LIST_ALL"), + ("CU_D3D10_DEVICE_LIST_CURRENT_FRAME", "HIP_D3D10_DEVICE_LIST_CURRENT_FRAME"), + ("CU_D3D10_DEVICE_LIST_NEXT_FRAME", "HIP_D3D10_DEVICE_LIST_NEXT_FRAME"), + ("cuD3D10GetDevice", "hipD3D10GetDevice"), + ("cuD3D10GetDevices", "hipD3D10GetDevices"), + ("cuGraphicsD3D10RegisterResource", "hipGraphicsD3D10RegisterResource"), + ("CU_D3D10_MAPRESOURCE_FLAGS_NONE", "HIP_D3D10_MAPRESOURCE_FLAGS_NONE"), + ("CU_D3D10_MAPRESOURCE_FLAGS_READONLY", "HIP_D3D10_MAPRESOURCE_FLAGS_READONLY"), + ("CU_D3D10_MAPRESOURCE_FLAGS_WRITEDISCARD", "HIP_D3D10_MAPRESOURCE_FLAGS_WRITEDISCARD"), + ("CU_D3D10_REGISTER_FLAGS_NONE", "HIP_D3D10_REGISTER_FLAGS_NONE"), + ("CU_D3D10_REGISTER_FLAGS_ARRAY", "HIP_D3D10_REGISTER_FLAGS_ARRAY"), + ("cuD3D10CtxCreate", "hipD3D10CtxCreate"), + ("cuD3D10CtxCreateOnDevice", "hipD3D10CtxCreateOnDevice"), + ("cuD3D10GetDirect3DDevice", "hipD3D10GetDirect3DDevice"), + ("cuD3D10MapResources", "hipD3D10MapResources"), + ("cuD3D10RegisterResource", "hipD3D10RegisterResource"), + ("cuD3D10ResourceGetMappedArray", "hipD3D10ResourceGetMappedArray"), + ("cuD3D10ResourceGetMappedPitch", "hipD3D10ResourceGetMappedPitch"), + ("cuD3D10ResourceGetMappedPointer", "hipD3D10ResourceGetMappedPointer"), + ("cuD3D10ResourceGetMappedSize", "hipD3D10ResourceGetMappedSize"), + ("cuD3D10ResourceGetSurfaceDimensions", "hipD3D10ResourceGetSurfaceDimensions"), + ("cuD310ResourceSetMapFlags", "hipD3D10ResourceSetMapFlags"), + ("cuD3D10UnmapResources", "hipD3D10UnmapResources"), + ("cuD3D10UnregisterResource", "hipD3D10UnregisterResource"), + ("CU_D3D11_DEVICE_LIST_ALL", "HIP_D3D11_DEVICE_LIST_ALL"), + ("CU_D3D11_DEVICE_LIST_CURRENT_FRAME", "HIP_D3D11_DEVICE_LIST_CURRENT_FRAME"), + ("CU_D3D11_DEVICE_LIST_NEXT_FRAME", "HIP_D3D11_DEVICE_LIST_NEXT_FRAME"), + ("cuD3D11GetDevice", "hipD3D11GetDevice"), + ("cuD3D11GetDevices", "hipD3D11GetDevices"), + ("cuGraphicsD3D11RegisterResource", "hipGraphicsD3D11RegisterResource"), + ("cuD3D11CtxCreate", "hipD3D11CtxCreate"), + ("cuD3D11CtxCreateOnDevice", "hipD3D11CtxCreateOnDevice"), + ("cuD3D11GetDirect3DDevice", "hipD3D11GetDirect3DDevice"), + ("cuGraphicsVDPAURegisterOutputSurface", "hipGraphicsVDPAURegisterOutputSurface"), + ("cuGraphicsVDPAURegisterVideoSurface", "hipGraphicsVDPAURegisterVideoSurface"), + ("cuVDPAUGetDevice", "hipVDPAUGetDevice"), + ("cuVDPAUCtxCreate", "hipVDPAUCtxCreate"), + ("cuEGLStreamConsumerAcquireFrame", "hipEGLStreamConsumerAcquireFrame"), + ("cuEGLStreamConsumerConnect", "hipEGLStreamConsumerConnect"), + ("cuEGLStreamConsumerConnectWithFlags", "hipEGLStreamConsumerConnectWithFlags"), + ("cuEGLStreamConsumerDisconnect", "hipEGLStreamConsumerDisconnect"), + ("cuEGLStreamConsumerReleaseFrame", "hipEGLStreamConsumerReleaseFrame"), + ("cuEGLStreamProducerConnect", "hipEGLStreamProducerConnect"), + ("cuEGLStreamProducerDisconnect", "hipEGLStreamProducerDisconnect"), + ("cuEGLStreamProducerPresentFrame", "hipEGLStreamProducerPresentFrame"), + ("cuEGLStreamProducerReturnFrame", "hipEGLStreamProducerReturnFrame"), + ("cuGraphicsEGLRegisterImage", "hipGraphicsEGLRegisterImage"), + ("cuGraphicsResourceGetMappedEglFrame", "hipGraphicsResourceGetMappedEglFrame"), + ("cudaDataType_t", "hipDataType"), + ("cudaDataType", "hipDataType"), + ("CUDA_R_32F", "HIP_R_32F"), + ("CUDA_R_64F", "HIP_R_64F"), + ("CUDA_R_16F", "HIP_R_16F"), + ("CUDA_R_8I", "HIP_R_8I"), + ("CUDA_C_32F", "HIP_C_32F"), + ("CUDA_C_64F", "HIP_C_64F"), + ("CUDA_C_16F", "HIP_C_16F"), + ("CUDA_C_8I", "HIP_C_8I"), + ("CUDA_R_8U", "HIP_R_8U"), + ("CUDA_C_8U", "HIP_C_8U"), + ("CUDA_R_32I", "HIP_R_32I"), + ("CUDA_C_32I", "HIP_C_32I"), + ("CUDA_R_32U", "HIP_R_32U"), + ("CUDA_C_32U", "HIP_C_32U"), + ("CUDA_R_16BF", "HIP_R_16BF"), + ("CUDA_C_16BF", "HIP_C_16BF"), + ("CUDA_R_4I", "HIP_R_4I"), + ("CUDA_C_4I", "HIP_C_4I"), + ("CUDA_R_4U", "HIP_R_4U"), + ("CUDA_C_4U", "HIP_C_4U"), + ("CUDA_R_16I", "HIP_R_16I"), + ("CUDA_C_16I", "HIP_C_16I"), + ("CUDA_R_16U", "HIP_R_16U"), + ("CUDA_C_16U", "HIP_C_16U"), + ("CUDA_R_64I", "HIP_R_64I"), + ("CUDA_C_64I", "HIP_C_64I"), + ("CUDA_R_64U", "HIP_R_64U"), + ("CUDA_C_64U", "HIP_C_64U"), + ("CUDA_R_8F_E4M3", "HIP_R_8F_E4M3"), + ("CUDA_R_8F_E5M2", "HIP_R_8F_E5M2"), + ("CUDA_R_4F_E2M1", "HIP_R_4F_E2M1"), + ("MAJOR_VERSION", "hipLibraryMajorVersion"), + ("MINOR_VERSION", "hipLibraryMinorVersion"), + ("PATCH_LEVEL", "hipLibraryPatchVersion"), + ("cudaLaunchKernel", "hipLaunchKernel"), + ("cudaMemAllocationHandleType", "hipMemAllocationHandleType"), + ("cudaMemAllocationType", "hipMemAllocationType"), + ("cudaMemLocationType", "hipMemLocationType"), + ("cudaMemAttachGlobal", "hipMemAttachGlobal"), + ("cudaMemAttachHost", "hipMemAttachHost"), + ("cudaMemAttachSingle", "hipMemAttachSingle"), + ("cudaOccupancyDefault", "hipOccupancyDefault"), + ("cudaOccupancyDisableCachingOverride", "hipOccupancyDisableCachingOverride"), + ("cudaGetLastError", "hipGetLastError"), + ("cudaPeekAtLastError", "hipPeekAtLastError"), + ("cudaGetErrorName", "hipGetErrorName"), + ("cudaGetErrorString", "hipGetErrorString"), + ("cudaMemcpy3DParms", "hipMemcpy3DParms"), + ("cudaMemcpy3DPeerParms", "hipMemcpy3DPeerParms"), + ("cudaMemcpy", "hipMemcpy"), + ("cudaMemcpyToArray", "hipMemcpyToArray"), + ("cudaMemcpyToSymbol", "hipMemcpyToSymbol"), + ("cudaMemcpyToSymbolAsync", "hipMemcpyToSymbolAsync"), + ("cudaMemcpyAsync", "hipMemcpyAsync"), + ("cudaMemcpy2D", "hipMemcpy2D"), + ("cudaMemcpy2DAsync", "hipMemcpy2DAsync"), + ("cudaMemcpy2DToArray", "hipMemcpy2DToArray"), + ("cudaMemcpy2DArrayToArray", "hipMemcpy2DArrayToArray"), + ("cudaMemcpy2DFromArray", "hipMemcpy2DFromArray"), + ("cudaMemcpy2DFromArrayAsync", "hipMemcpy2DFromArrayAsync"), + ("cudaMemcpy2DToArrayAsync", "hipMemcpy2DToArrayAsync"), + ("cudaMemcpy3D", "hipMemcpy3D"), + ("cudaMemcpy3DAsync", "hipMemcpy3DAsync"), + ("cudaMemcpy3DPeer", "hipMemcpy3DPeer"), + ("cudaMemcpy3DPeerAsync", "hipMemcpy3DPeerAsync"), + ("cudaMemcpyArrayToArray", "hipMemcpyArrayToArray"), + ("cudaMemcpyFromArrayAsync", "hipMemcpyFromArrayAsync"), + ("cudaMemcpyFromSymbol", "hipMemcpyFromSymbol"), + ("cudaMemcpyFromSymbolAsync", "hipMemcpyFromSymbolAsync"), + ("cudaMemAdvise", "hipMemAdvise"), + ("cudaMemRangeGetAttribute", "hipMemRangeGetAttribute"), + ("cudaMemRangeGetAttributes", "hipMemRangeGetAttributes"), + ("cudaMemAdviseSetReadMostly", "hipMemAdviseSetReadMostly"), + ("cudaMemAdviseUnsetReadMostly", "hipMemAdviseUnsetReadMostly"), + ("cudaMemAdviseSetPreferredLocation", "hipMemAdviseSetPreferredLocation"), + ("cudaMemAdviseUnsetPreferredLocation", "hipMemAdviseUnsetPreferredLocation"), + ("cudaMemAdviseSetAccessedBy", "hipMemAdviseSetAccessedBy"), + ("cudaMemAdviseUnsetAccessedBy", "hipMemAdviseUnsetAccessedBy"), + ("cudaMemRangeAttributeReadMostly", "hipMemRangeAttributeReadMostly"), + ("cudaMemRangeAttributePreferredLocation", "hipMemRangeAttributePreferredLocation"), + ("cudaMemRangeAttributeAccessedBy", "hipMemRangeAttributeAccessedBy"), + ("cudaMemRangeAttributeLastPrefetchLocation", "hipMemRangeAttributeLastPrefetchLocation"), + ("cudaMemcpyHostToHost", "hipMemcpyHostToHost"), + ("cudaMemcpyHostToDevice", "hipMemcpyHostToDevice"), + ("cudaMemcpyDeviceToHost", "hipMemcpyDeviceToHost"), + ("cudaMemcpyDeviceToDevice", "hipMemcpyDeviceToDevice"), + ("cudaMemcpyDefault", "hipMemcpyDefault"), + ("cudaMemset", "hipMemset"), + ("cudaMemsetAsync", "hipMemsetAsync"), + ("cudaMemset2D", "hipMemset2D"), + ("cudaMemset2DAsync", "hipMemset2DAsync"), + ("cudaMemset3D", "hipMemset3D"), + ("cudaMemset3DAsync", "hipMemset3DAsync"), + ("cudaMemGetInfo", "hipMemGetInfo"), + ("cudaDeviceGetDefaultMemPool", "hipDeviceGetDefaultMemPool"), + ("cudaMemAccessDesc", "hipMemAccessDesc"), + ("cudaMemAccessFlagsProtReadWrite", "hipMemAccessFlagsProtReadWrite"), + ("cudaMemLocationTypeDevice", "hipMemLocationTypeDevice"), + ("cudaMemPoolAttrReleaseThreshold", "hipMemPoolAttrReleaseThreshold"), + ("cudaMemPoolAttrReservedMemCurrent", "hipMemPoolAttrReservedMemCurrent"), + ("cudaMemPoolAttrReservedMemHigh", "hipMemPoolAttrReservedMemHigh"), + ("cudaMemPoolAttrUsedMemCurrent", "hipMemPoolAttrUsedMemCurrent"), + ("cudaMemPoolAttrUsedMemHigh", "hipMemPoolAttrUsedMemHigh"), + ("cudaMemPoolGetAttribute", "hipMemPoolGetAttribute"), + ("cudaMemPoolReuseAllowInternalDependencies", "hipMemPoolReuseAllowInternalDependencies"), + ("cudaMemPoolReuseAllowOpportunistic", "hipMemPoolReuseAllowOpportunistic"), + ("cudaMemPoolReuseFollowEventDependencies", "hipMemPoolReuseFollowEventDependencies"), + ("cudaMemPoolSetAccess", "hipMemPoolSetAccess"), + ("cudaMemPoolSetAttribute", "hipMemPoolSetAttribute"), + ("cudaMemPoolTrimTo", "hipMemPoolTrimTo"), + ("cudaMemPool_t", "hipMemPool_t"), + ("cudaArrayGetInfo", "hipArrayGetInfo"), + ("cudaFreeMipmappedArray", "hipFreeMipmappedArray"), + ("cudaGetMipmappedArrayLevel", "hipGetMipmappedArrayLevel"), + ("cudaGetSymbolAddress", "hipGetSymbolAddress"), + ("cudaGetSymbolSize", "hipGetSymbolSize"), + ("cudaMemPrefetchAsync", "hipMemPrefetchAsync"), + ("cudaMallocHost", "hipHostMalloc"), + ("cudaMallocArray", "hipMallocArray"), + ("cudaMalloc", "hipMalloc"), + ("cudaMalloc3D", "hipMalloc3D"), + ("cudaMalloc3DArray", "hipMalloc3DArray"), + ("cudaMallocAsync", "hipMallocAsync"), + ("cudaMallocManaged", "hipMallocManaged"), + ("cudaMallocMipmappedArray", "hipMallocMipmappedArray"), + ("cudaMallocPitch", "hipMallocPitch"), + ("cudaFreeHost", "hipHostFree"), + ("cudaFreeArray", "hipFreeArray"), + ("cudaFree", "hipFree"), + ("cudaFreeAsync", "hipFreeAsync"), + ("cudaHostRegister", "hipHostRegister"), + ("cudaHostUnregister", "hipHostUnregister"), + ("cudaHostAlloc", "hipHostMalloc"), + ("cudaMemoryTypeHost", "hipMemoryTypeHost"), + ("cudaMemoryTypeDevice", "hipMemoryTypeDevice"), + ("cudaMemoryTypeUnregistered", "hipMemoryTypeUnregistered"), + ("cudaMemoryTypeManaged", "hipMemoryTypeManaged"), + ("make_cudaExtent", "make_hipExtent"), + ("make_cudaPitchedPtr", "make_hipPitchedPtr"), + ("make_cudaPos", "make_hipPos"), + ("cudaHostAllocDefault", "hipHostMallocDefault"), + ("cudaHostAllocPortable", "hipHostMallocPortable"), + ("cudaHostAllocMapped", "hipHostMallocMapped"), + ("cudaHostNodeParams", "hipHostNodeParams"), + ("cudaHostAllocWriteCombined", "hipHostMallocWriteCombined"), + ("cudaHostFn_t", "hipHostFn_t"), + ("cudaHostGetFlags", "hipHostGetFlags"), + ("cudaHostRegisterDefault", "hipHostRegisterDefault"), + ("cudaHostRegisterPortable", "hipHostRegisterPortable"), + ("cudaHostRegisterMapped", "hipHostRegisterMapped"), + ("cudaHostRegisterIoMemory", "hipHostRegisterIoMemory"), + ("cudaEventCreate", "hipEventCreate"), + ("cudaEventCreateWithFlags", "hipEventCreateWithFlags"), + ("cudaEventDestroy", "hipEventDestroy"), + ("cudaEventRecord", "hipEventRecord"), + ("cudaEventRecordWithFlags", "hipEventRecordWithFlags"), + ("cudaEventElapsedTime", "hipEventElapsedTime"), + ("cudaEventSynchronize", "hipEventSynchronize"), + ("cudaEventQuery", "hipEventQuery"), + ("cudaEventDefault", "hipEventDefault"), + ("cudaEventBlockingSync", "hipEventBlockingSync"), + ("cudaEventDisableTiming", "hipEventDisableTiming"), + ("cudaEventInterprocess", "hipEventInterprocess"), + ("cudaEventRecordDefault", "hipEventRecordDefault"), + ("cudaEventRecordExternal", "hipEventRecordExternal"), + ("cudaEventWaitDefault", "hipEventWaitDefault"), + ("cudaEventWaitExternal", "hipEventWaitExternal"), + ("cudaStreamCreate", "hipStreamCreate"), + ("cudaStreamCreateWithFlags", "hipStreamCreateWithFlags"), + ("cudaStreamCreateWithPriority", "hipStreamCreateWithPriority"), + ("cudaStreamDestroy", "hipStreamDestroy"), + ("cudaStreamWaitEvent", "hipStreamWaitEvent"), + ("cudaStreamSynchronize", "hipStreamSynchronize"), + ("cudaStreamGetFlags", "hipStreamGetFlags"), + ("cudaStreamQuery", "hipStreamQuery"), + ("cudaStreamAddCallback", "hipStreamAddCallback"), + ("cudaStreamAttachMemAsync", "hipStreamAttachMemAsync"), + ("cudaStreamGetPriority", "hipStreamGetPriority"), + ("cudaCpuDeviceId", "hipCpuDeviceId"), + ("cudaStreamDefault", "hipStreamDefault"), + ("cudaStreamNonBlocking", "hipStreamNonBlocking"), + ("cudaStreamGetCaptureInfo", "hipStreamGetCaptureInfo"), + ("cudaStreamGetCaptureInfo_v2", "hipStreamGetCaptureInfo_v2"), + ("cudaStreamCaptureStatus", "hipStreamCaptureStatus"), + ("cudaStreamCaptureStatusActive", "hipStreamCaptureStatusActive"), + ("cudaStreamCaptureStatusNone", "hipStreamCaptureStatusNone"), + ("cudaStreamCaptureStatusInvalidated", "hipStreamCaptureStatusInvalidated"), + ("cudaStreamCaptureMode", "hipStreamCaptureMode"), + ("cudaStreamCaptureModeGlobal", "hipStreamCaptureModeGlobal"), + ("cudaStreamCaptureModeRelaxed", "hipStreamCaptureModeRelaxed"), + ("cudaStreamCaptureModeThreadLocal", "hipStreamCaptureModeThreadLocal"), + ("cudaStreamBeginCapture", "hipStreamBeginCapture"), + ("cudaStreamEndCapture", "hipStreamEndCapture"), + ("cudaStreamSetCaptureDependencies", "hipStreamSetCaptureDependencies"), + ("cudaStreamUpdateCaptureDependencies", "hipStreamUpdateCaptureDependencies"), + ("cudaGraphNode_t", "hipGraphNode_t"), + ("cudaGraphInstantiate", "hipGraphInstantiate"), + ("cudaGraphInstantiateWithFlags", "hipGraphInstantiateWithFlags"), + ("cudaGraphInstantiateFlagAutoFreeOnLaunch", "hipGraphInstantiateFlagAutoFreeOnLaunch"), + ("cudaGraphDestroy", "hipGraphDestroy"), + ("cudaGraphExecDestroy", "hipGraphExecDestroy"), + ("cudaGraphLaunch", "hipGraphLaunch"), + ("cudaGraphGetNodes", "hipGraphGetNodes"), + ("cudaGraphDebugDotPrint", "hipGraphDebugDotPrint"), + ("cudaGraphDebugDotFlagsVerbose", "hipGraphDebugDotFlagsVerbose"), + ("cudaGraphRetainUserObject", "hipGraphRetainUserObject"), + ("cudaGraphUserObjectMove", "hipGraphUserObjectMove"), + ("cudaDeviceGetGraphMemAttribute", "hipDeviceGetGraphMemAttribute"), + ("cudaDeviceGraphMemTrim", "hipDeviceGraphMemTrim"), + ("cudaDeviceSetGraphMemAttribute", "hipDeviceSetGraphMemAttribute"), + ("cudaGraphAddChildGraphNode", "hipGraphAddChildGraphNode"), + ("cudaGraphAddDependencies", "hipGraphAddDependencies"), + ("cudaGraphAddEmptyNode", "hipGraphAddEmptyNode"), + ("cudaGraphAddEventRecordNode", "hipGraphAddEventRecordNode"), + ("cudaGraphAddEventWaitNode", "hipGraphAddEventWaitNode"), + ("cudaGraphAddExternalSemaphoresSignalNode", "hipGraphAddExternalSemaphoresSignalNode"), + ("cudaGraphAddExternalSemaphoresWaitNode", "hipGraphAddExternalSemaphoresWaitNode"), + ("cudaGraphAddHostNode", "hipGraphAddHostNode"), + ("cudaGraphAddKernelNode", "hipGraphAddKernelNode"), + ("cudaGraphAddMemAllocNode", "hipGraphAddMemAllocNode"), + ("cudaGraphAddMemFreeNode", "hipGraphAddMemFreeNode"), + ("cudaGraphAddMemcpyNode", "hipGraphAddMemcpyNode"), + ("cudaGraphAddMemcpyNode1D", "hipGraphAddMemcpyNode1D"), + ("cudaGraphAddMemcpyNodeFromSymbol", "hipGraphAddMemcpyNodeFromSymbol"), + ("cudaGraphAddMemcpyNodeToSymbol", "hipGraphAddMemcpyNodeToSymbol"), + ("cudaGraphAddMemsetNode", "hipGraphAddMemsetNode"), + ("cudaGraphAddNode", "hipGraphAddNode"), + ("cudaGraphChildGraphNodeGetGraph", "hipGraphChildGraphNodeGetGraph"), + ("cudaGraphClone", "hipGraphClone"), + ("cudaGraphCreate", "hipGraphCreate"), + ("cudaGraphDestroyNode", "hipGraphDestroyNode"), + ("cudaGraphEventRecordNodeGetEvent", "hipGraphEventRecordNodeGetEvent"), + ("cudaGraphEventRecordNodeSetEvent", "hipGraphEventRecordNodeSetEvent"), + ("cudaGraphEventWaitNodeGetEvent", "hipGraphEventWaitNodeGetEvent"), + ("cudaGraphEventWaitNodeSetEvent", "hipGraphEventWaitNodeSetEvent"), + ("cudaGraphExecChildGraphNodeSetParams", "hipGraphExecChildGraphNodeSetParams"), + ("cudaGraphExecEventRecordNodeSetEvent", "hipGraphExecEventRecordNodeSetEvent"), + ("cudaGraphExecEventWaitNodeSetEvent", "hipGraphExecEventWaitNodeSetEvent"), + ("cudaGraphExecExternalSemaphoresSignalNodeSetParams", "hipGraphExecExternalSemaphoresSignalNodeSetParams"), + ("cudaGraphExecExternalSemaphoresWaitNodeSetParams", "hipGraphExecExternalSemaphoresWaitNodeSetParams"), + ("cudaGraphExecGetFlags", "hipGraphExecGetFlags"), + ("cudaGraphExecHostNodeSetParams", "hipGraphExecHostNodeSetParams"), + ("cudaGraphExecKernelNodeSetParams", "hipGraphExecKernelNodeSetParams"), + ("cudaGraphExecMemcpyNodeSetParams", "hipGraphExecMemcpyNodeSetParams"), + ("cudaGraphExecMemcpyNodeSetParams1D", "hipGraphExecMemcpyNodeSetParams1D"), + ("cudaGraphExecMemcpyNodeSetParamsFromSymbol", "hipGraphExecMemcpyNodeSetParamsFromSymbol"), + ("cudaGraphExecMemcpyNodeSetParamsToSymbol", "hipGraphExecMemcpyNodeSetParamsToSymbol"), + ("cudaGraphExecMemsetNodeSetParams", "hipGraphExecMemsetNodeSetParams"), + ("cudaGraphExecNodeSetParams", "hipGraphExecNodeSetParams"), + ("cudaGraphExecUpdate", "hipGraphExecUpdate"), + ("cudaGraphExternalSemaphoresSignalNodeGetParams", "hipGraphExternalSemaphoresSignalNodeGetParams"), + ("cudaGraphExternalSemaphoresSignalNodeSetParams", "hipGraphExternalSemaphoresSignalNodeSetParams"), + ("cudaGraphExternalSemaphoresWaitNodeGetParams", "hipGraphExternalSemaphoresWaitNodeGetParams"), + ("cudaGraphExternalSemaphoresWaitNodeSetParams", "hipGraphExternalSemaphoresWaitNodeSetParams"), + ("cudaGraphGetEdges", "hipGraphGetEdges"), + ("cudaGraphGetRootNodes", "hipGraphGetRootNodes"), + ("cudaGraphHostNodeGetParams", "hipGraphHostNodeGetParams"), + ("cudaGraphHostNodeSetParams", "hipGraphHostNodeSetParams"), + ("cudaGraphInstantiateWithParams", "hipGraphInstantiateWithParams"), + ("cudaGraphKernelNodeCopyAttributes", "hipGraphKernelNodeCopyAttributes"), + ("cudaGraphKernelNodeGetAttribute", "hipGraphKernelNodeGetAttribute"), + ("cudaGraphKernelNodeGetParams", "hipGraphKernelNodeGetParams"), + ("cudaGraphKernelNodeSetAttribute", "hipGraphKernelNodeSetAttribute"), + ("cudaGraphKernelNodeSetParams", "hipGraphKernelNodeSetParams"), + ("cudaGraphMemAllocNodeGetParams", "hipGraphMemAllocNodeGetParams"), + ("cudaGraphMemFreeNodeGetParams", "hipGraphMemFreeNodeGetParams"), + ("cudaGraphMemcpyNodeGetParams", "hipGraphMemcpyNodeGetParams"), + ("cudaGraphMemcpyNodeSetParams", "hipGraphMemcpyNodeSetParams"), + ("cudaGraphMemcpyNodeSetParams1D", "hipGraphMemcpyNodeSetParams1D"), + ("cudaGraphMemcpyNodeSetParamsFromSymbol", "hipGraphMemcpyNodeSetParamsFromSymbol"), + ("cudaGraphMemcpyNodeSetParamsToSymbol", "hipGraphMemcpyNodeSetParamsToSymbol"), + ("cudaGraphMemsetNodeGetParams", "hipGraphMemsetNodeGetParams"), + ("cudaGraphMemsetNodeSetParams", "hipGraphMemsetNodeSetParams"), + ("cudaGraphNodeFindInClone", "hipGraphNodeFindInClone"), + ("cudaGraphNodeGetDependencies", "hipGraphNodeGetDependencies"), + ("cudaGraphNodeGetDependentNodes", "hipGraphNodeGetDependentNodes"), + ("cudaGraphNodeGetEnabled", "hipGraphNodeGetEnabled"), + ("cudaGraphNodeGetType", "hipGraphNodeGetType"), + ("cudaGraphNodeSetEnabled", "hipGraphNodeSetEnabled"), + ("cudaGraphNodeSetParams", "hipGraphNodeSetParams"), + ("cudaGraphReleaseUserObject", "hipGraphReleaseUserObject"), + ("cudaGraphRemoveDependencies", "hipGraphRemoveDependencies"), + ("cudaGraphUpload", "hipGraphUpload"), + ("cudaUserObjectRelease", "hipUserObjectRelease"), + ("cudaUserObjectRetain", "hipUserObjectRetain"), + ("cudaGraphDebugDotFlags", "hipGraphDebugDotFlags"), + ("cudaGraphDebugDotFlagsEventNodeParams", "hipGraphDebugDotFlagsEventNodeParams"), + ("cudaGraphDebugDotFlagsExtSemasSignalNodeParams", "hipGraphDebugDotFlagsExtSemasSignalNodeParams"), + ("cudaGraphDebugDotFlagsExtSemasWaitNodeParams", "hipGraphDebugDotFlagsExtSemasWaitNodeParams"), + ("cudaGraphDebugDotFlagsHandles", "hipGraphDebugDotFlagsHandles"), + ("cudaGraphDebugDotFlagsHostNodeParams", "hipGraphDebugDotFlagsHostNodeParams"), + ("cudaGraphDebugDotFlagsKernelNodeAttributes", "hipGraphDebugDotFlagsKernelNodeAttributes"), + ("cudaGraphDebugDotFlagsKernelNodeParams", "hipGraphDebugDotFlagsKernelNodeParams"), + ("cudaGraphDebugDotFlagsMemcpyNodeParams", "hipGraphDebugDotFlagsMemcpyNodeParams"), + ("cudaGraphDebugDotFlagsMemsetNodeParams", "hipGraphDebugDotFlagsMemsetNodeParams"), + ("cudaGraphDependencyType", "hipGraphDependencyType"), + ("cudaGraphDependencyTypeDefault", "hipGraphDependencyTypeDefault"), + ("cudaGraphDependencyTypeProgrammatic", "hipGraphDependencyTypeProgrammatic"), + ("cudaGraphDependencyType_enum", "hipGraphDependencyType"), + ("cudaGraphEdgeData", "hipGraphEdgeData"), + ("cudaGraphEdgeData_st", "hipGraphEdgeData"), + ("cudaGraphExecUpdateError", "hipGraphExecUpdateError"), + ("cudaGraphExecUpdateErrorFunctionChanged", "hipGraphExecUpdateErrorFunctionChanged"), + ("cudaGraphExecUpdateErrorNodeTypeChanged", "hipGraphExecUpdateErrorNodeTypeChanged"), + ("cudaGraphExecUpdateErrorNotSupported", "hipGraphExecUpdateErrorNotSupported"), + ("cudaGraphExecUpdateErrorParametersChanged", "hipGraphExecUpdateErrorParametersChanged"), + ("cudaGraphExecUpdateErrorTopologyChanged", "hipGraphExecUpdateErrorTopologyChanged"), + ("cudaGraphExecUpdateErrorUnsupportedFunctionChange", "hipGraphExecUpdateErrorUnsupportedFunctionChange"), + ("cudaGraphExecUpdateResult", "hipGraphExecUpdateResult"), + ("cudaGraphExecUpdateSuccess", "hipGraphExecUpdateSuccess"), + ("cudaGraphInstantiateError", "hipGraphInstantiateError"), + ("cudaGraphInstantiateFlagDeviceLaunch", "hipGraphInstantiateFlagDeviceLaunch"), + ("cudaGraphInstantiateFlagUpload", "hipGraphInstantiateFlagUpload"), + ("cudaGraphInstantiateFlagUseNodePriority", "hipGraphInstantiateFlagUseNodePriority"), + ("cudaGraphInstantiateFlags", "hipGraphInstantiateFlags"), + ("cudaGraphInstantiateInvalidStructure", "hipGraphInstantiateInvalidStructure"), + ("cudaGraphInstantiateMultipleDevicesNotSupported", "hipGraphInstantiateMultipleDevicesNotSupported"), + ("cudaGraphInstantiateNodeOperationNotSupported", "hipGraphInstantiateNodeOperationNotSupported"), + ("cudaGraphInstantiateParams", "hipGraphInstantiateParams"), + ("cudaGraphInstantiateParams_st", "hipGraphInstantiateParams"), + ("cudaGraphInstantiateResult", "hipGraphInstantiateResult"), + ("cudaGraphInstantiateSuccess", "hipGraphInstantiateSuccess"), + ("cudaGraphKernelNodePortDefault", "hipGraphKernelNodePortDefault"), + ("cudaGraphKernelNodePortLaunchCompletion", "hipGraphKernelNodePortLaunchCompletion"), + ("cudaGraphKernelNodePortProgrammatic", "hipGraphKernelNodePortProgrammatic"), + ("cudaGraphMemAttrReservedMemCurrent", "hipGraphMemAttrReservedMemCurrent"), + ("cudaGraphMemAttrReservedMemHigh", "hipGraphMemAttrReservedMemHigh"), + ("cudaGraphMemAttrUsedMemCurrent", "hipGraphMemAttrUsedMemCurrent"), + ("cudaGraphMemAttrUsedMemHigh", "hipGraphMemAttrUsedMemHigh"), + ("cudaGraphMemAttributeType", "hipGraphMemAttributeType"), + ("cudaGraphNodeParams", "hipGraphNodeParams"), + ("cudaGraphNodeType", "hipGraphNodeType"), + ("cudaGraphNodeTypeConditional", "hipGraphNodeTypeConditional"), + ("cudaGraphNodeTypeCount", "hipGraphNodeTypeCount"), + ("cudaGraphNodeTypeEmpty", "hipGraphNodeTypeEmpty"), + ("cudaGraphNodeTypeEventRecord", "hipGraphNodeTypeEventRecord"), + ("cudaGraphNodeTypeExtSemaphoreSignal", "hipGraphNodeTypeExtSemaphoreSignal"), + ("cudaGraphNodeTypeExtSemaphoreWait", "hipGraphNodeTypeExtSemaphoreWait"), + ("cudaGraphNodeTypeGraph", "hipGraphNodeTypeGraph"), + ("cudaGraphNodeTypeHost", "hipGraphNodeTypeHost"), + ("cudaGraphNodeTypeKernel", "hipGraphNodeTypeKernel"), + ("cudaGraphNodeTypeMemAlloc", "hipGraphNodeTypeMemAlloc"), + ("cudaGraphNodeTypeMemFree", "hipGraphNodeTypeMemFree"), + ("cudaGraphNodeTypeMemcpy", "hipGraphNodeTypeMemcpy"), + ("cudaGraphNodeTypeMemset", "hipGraphNodeTypeMemset"), + ("cudaGraphNodeTypeWaitEvent", "hipGraphNodeTypeWaitEvent"), + ("cudaUserObject_t", "hipUserObject_t"), + ("cudaUserObjectCreate", "hipUserObjectCreate"), + ("cudaUserObjectNoDestructorSync", "hipUserObjectNoDestructorSync"), + ("cudaThreadExchangeStreamCaptureMode", "hipThreadExchangeStreamCaptureMode"), + ("cudaStreamIsCapturing", "hipStreamIsCapturing"), + ("cudaDeviceSynchronize", "hipDeviceSynchronize"), + ("cudaDeviceReset", "hipDeviceReset"), + ("cudaSetDevice", "hipSetDevice"), + ("cudaGetDevice", "hipGetDevice"), + ("cudaGetDeviceCount", "hipGetDeviceCount"), + ("cudaChooseDevice", "hipChooseDevice"), + ("cudaThreadExit", "hipDeviceReset"), + ("cudaThreadGetCacheConfig", "hipDeviceGetCacheConfig"), + ("cudaThreadGetLimit", "hipThreadGetLimit"), + ("cudaThreadSetCacheConfig", "hipDeviceSetCacheConfig"), + ("cudaThreadSetLimit", "hipThreadSetLimit"), + ("cudaThreadSynchronize", "hipDeviceSynchronize"), + ("cudaDeviceGetAttribute", "hipDeviceGetAttribute"), + ("cudaDevAttrMaxThreadsPerBlock", "hipDeviceAttributeMaxThreadsPerBlock"), + ("cudaDevAttrMaxBlocksPerMultiprocessor", "hipDeviceAttributeMaxBlocksPerMultiprocessor"), + ("cudaDevAttrMaxBlockDimX", "hipDeviceAttributeMaxBlockDimX"), + ("cudaDevAttrMaxBlockDimY", "hipDeviceAttributeMaxBlockDimY"), + ("cudaDevAttrMaxBlockDimZ", "hipDeviceAttributeMaxBlockDimZ"), + ("cudaDevAttrMaxGridDimX", "hipDeviceAttributeMaxGridDimX"), + ("cudaDevAttrMaxGridDimY", "hipDeviceAttributeMaxGridDimY"), + ("cudaDevAttrMaxGridDimZ", "hipDeviceAttributeMaxGridDimZ"), + ("cudaDevAttrMaxSharedMemoryPerBlock", "hipDeviceAttributeMaxSharedMemoryPerBlock"), + ("cudaDevAttrMaxSharedMemoryPerBlockOptin", "hipDeviceAttributeMaxSharedMemoryPerBlock"), + ("cudaDevAttrTotalConstantMemory", "hipDeviceAttributeTotalConstantMemory"), + ("cudaDevAttrWarpSize", "hipDeviceAttributeWarpSize"), + ("cudaDevAttrMaxPitch", "hipDeviceAttributeMaxPitch"), + ("cudaDevAttrMaxRegistersPerBlock", "hipDeviceAttributeMaxRegistersPerBlock"), + ("cudaDevAttrClockRate", "hipDeviceAttributeClockRate"), + ("cudaDevAttrTextureAlignment", "hipDeviceAttributeTextureAlignment"), + ("cudaDevAttrGpuOverlap", "hipDeviceAttributeGpuOverlap"), + ("cudaDevAttrMultiProcessorCount", "hipDeviceAttributeMultiprocessorCount"), + ("cudaDevAttrKernelExecTimeout", "hipDeviceAttributeKernelExecTimeout"), + ("cudaDevAttrIntegrated", "hipDeviceAttributeIntegrated"), + ("cudaDevAttrReserved94", "hipDeviceAttributeCanUseStreamWaitValue"), + ("cudaDevAttrCooperativeLaunch", "hipDeviceAttributeCooperativeLaunch"), + ("cudaDevAttrCooperativeMultiDeviceLaunch", "hipDeviceAttributeCooperativeMultiDeviceLaunch"), + ("cudaDevAttrCanMapHostMemory", "hipDeviceAttributeCanMapHostMemory"), + ("cudaDevAttrComputeMode", "hipDeviceAttributeComputeMode"), + ("cudaDevAttrMaxTexture1DWidth", "hipDeviceAttributeMaxTexture1DWidth"), + ("cudaDevAttrMaxTexture2DWidth", "hipDeviceAttributeMaxTexture2DWidth"), + ("cudaDevAttrMaxTexture2DHeight", "hipDeviceAttributeMaxTexture2DHeight"), + ("cudaDevAttrMaxTexture3DWidth", "hipDeviceAttributeMaxTexture3DWidth"), + ("cudaDevAttrMaxTexture3DHeight", "hipDeviceAttributeMaxTexture3DHeight"), + ("cudaDevAttrMaxTexture3DDepth", "hipDeviceAttributeMaxTexture3DDepth"), + ("cudaDevAttrMaxTexture2DLayeredWidth", "hipDeviceAttributeMaxTexture2DLayeredWidth"), + ("cudaDevAttrMaxTexture2DLayeredHeight", "hipDeviceAttributeMaxTexture2DLayeredHeight"), + ("cudaDevAttrMaxTexture2DLayeredLayers", "hipDeviceAttributeMaxTexture2DLayeredLayers"), + ("cudaDevAttrSurfaceAlignment", "hipDeviceAttributeSurfaceAlignment"), + ("cudaDevAttrConcurrentKernels", "hipDeviceAttributeConcurrentKernels"), + ("cudaDevAttrEccEnabled", "hipDeviceAttributeEccEnabled"), + ("cudaDevAttrMemoryPoolsSupported", "hipDeviceAttributeMemoryPoolsSupported"), + ("cudaDevAttrPciBusId", "hipDeviceAttributePciBusId"), + ("cudaDevAttrPciDeviceId", "hipDeviceAttributePciDeviceId"), + ("cudaDevAttrTccDriver", "hipDeviceAttributeTccDriver"), + ("cudaDevAttrMemoryClockRate", "hipDeviceAttributeMemoryClockRate"), + ("cudaDevAttrGlobalMemoryBusWidth", "hipDeviceAttributeMemoryBusWidth"), + ("cudaDevAttrL2CacheSize", "hipDeviceAttributeL2CacheSize"), + ("cudaDevAttrMaxThreadsPerMultiProcessor", "hipDeviceAttributeMaxThreadsPerMultiProcessor"), + ("cudaDevAttrAsyncEngineCount", "hipDeviceAttributeAsyncEngineCount"), + ("cudaDevAttrUnifiedAddressing", "hipDeviceAttributeUnifiedAddressing"), + ("cudaDevAttrMaxTexture1DLayeredWidth", "hipDeviceAttributeMaxTexture1DLayeredWidth"), + ("cudaDevAttrMaxTexture1DLayeredLayers", "hipDeviceAttributeMaxTexture1DLayeredLayers"), + ("cudaDevAttrMaxTexture2DGatherWidth", "hipDeviceAttributeMaxTexture2DGatherWidth"), + ("cudaDevAttrMaxTexture2DGatherHeight", "hipDeviceAttributeMaxTexture2DGatherHeight"), + ("cudaDevAttrMaxTexture3DWidthAlt", "hipDeviceAttributeMaxTexture3DWidthAlternate"), + ("cudaDevAttrMaxTexture3DHeightAlt", "hipDeviceAttributeMaxTexture3DHeightAlternate"), + ("cudaDevAttrMaxTexture3DDepthAlt", "hipDeviceAttributeMaxTexture3DDepthAlternate"), + ("cudaDevAttrPciDomainId", "hipDeviceAttributePciDomainId"), + ("cudaDevAttrTexturePitchAlignment", "hipDeviceAttributeTexturePitchAlignment"), + ("cudaDevAttrMaxTextureCubemapWidth", "hipDeviceAttributeMaxTextureCubemapWidth"), + ("cudaDevAttrMaxTextureCubemapLayeredWidth", "hipDeviceAttributeMaxTextureCubemapLayeredWidth"), + ("cudaDevAttrMaxTextureCubemapLayeredLayers", "hipDeviceAttributeMaxTextureCubemapLayeredLayers"), + ("cudaDevAttrMaxSurface1DWidth", "hipDeviceAttributeMaxSurface1DWidth"), + ("cudaDevAttrMaxSurface2DWidth", "hipDeviceAttributeMaxSurface2DWidth"), + ("cudaDevAttrMaxSurface2DHeight", "hipDeviceAttributeMaxSurface2DHeight"), + ("cudaDevAttrMaxSurface3DWidth", "hipDeviceAttributeMaxSurface3DWidth"), + ("cudaDevAttrMaxSurface3DHeight", "hipDeviceAttributeMaxSurface3DHeight"), + ("cudaDevAttrMaxSurface3DDepth", "hipDeviceAttributeMaxSurface3DDepth"), + ("cudaDevAttrMaxSurface1DLayeredWidth", "hipDeviceAttributeMaxSurface1DLayeredWidth"), + ("cudaDevAttrMaxSurface1DLayeredLayers", "hipDeviceAttributeMaxSurface1DLayeredLayers"), + ("cudaDevAttrMaxSurface2DLayeredWidth", "hipDeviceAttributeMaxSurface2DLayeredWidth"), + ("cudaDevAttrMaxSurface2DLayeredHeight", "hipDeviceAttributeMaxSurface2DLayeredHeight"), + ("cudaDevAttrMaxSurface2DLayeredLayers", "hipDeviceAttributeMaxSurface2DLayeredLayers"), + ("cudaDevAttrMaxSurfaceCubemapWidth", "hipDeviceAttributeMaxSurfaceCubemapWidth"), + ("cudaDevAttrMaxSurfaceCubemapLayeredWidth", "hipDeviceAttributeMaxSurfaceCubemapLayeredWidth"), + ("cudaDevAttrMaxSurfaceCubemapLayeredLayers", "hipDeviceAttributeMaxSurfaceCubemapLayeredLayers"), + ("cudaDevAttrMaxTexture1DLinearWidth", "hipDeviceAttributeMaxTexture1DLinearWidth"), + ("cudaDevAttrMaxTexture2DLinearWidth", "hipDeviceAttributeMaxTexture2DLinearWidth"), + ("cudaDevAttrMaxTexture2DLinearHeight", "hipDeviceAttributeMaxTexture2DLinearHeight"), + ("cudaDevAttrMaxTexture2DLinearPitch", "hipDeviceAttributeMaxTexture2DLinearPitch"), + ("cudaDevAttrMaxTexture2DMipmappedWidth", "hipDeviceAttributeMaxTexture2DMipmappedWidth"), + ("cudaDevAttrMaxTexture2DMipmappedHeight", "hipDeviceAttributeMaxTexture2DMipmappedHeight"), + ("cudaDevAttrComputeCapabilityMajor", "hipDeviceAttributeComputeCapabilityMajor"), + ("cudaDevAttrComputeCapabilityMinor", "hipDeviceAttributeComputeCapabilityMinor"), + ("cudaDevAttrMaxTexture1DMipmappedWidth", "hipDeviceAttributeMaxTexture1DMipmappedWidth"), + ("cudaDevAttrStreamPrioritiesSupported", "hipDeviceAttributeStreamPrioritiesSupported"), + ("cudaDevAttrGlobalL1CacheSupported", "hipDeviceAttributeGlobalL1CacheSupported"), + ("cudaDevAttrLocalL1CacheSupported", "hipDeviceAttributeLocalL1CacheSupported"), + ("cudaDevAttrMaxSharedMemoryPerMultiprocessor", "hipDeviceAttributeMaxSharedMemoryPerMultiprocessor"), + ("cudaDevAttrHostRegisterSupported", "hipDeviceAttributeHostRegisterSupported"), + ("cudaDevAttrMaxRegistersPerMultiprocessor", "hipDeviceAttributeMaxRegistersPerMultiprocessor"), + ("cudaDevAttrManagedMemory", "hipDeviceAttributeManagedMemory"), + ("cudaDevAttrDirectManagedMemAccessFromHost", "hipDeviceAttributeDirectManagedMemAccessFromHost"), + ("cudaDevAttrIsMultiGpuBoard", "hipDeviceAttributeIsMultiGpuBoard"), + ("cudaDevAttrMultiGpuBoardGroupID", "hipDeviceAttributeMultiGpuBoardGroupID"), + ("cudaDevAttrHostNativeAtomicSupported", "hipDeviceAttributeHostNativeAtomicSupported"), + ("cudaDevAttrSingleToDoublePrecisionPerfRatio", "hipDeviceAttributeSingleToDoublePrecisionPerfRatio"), + ("cudaDevAttrPageableMemoryAccess", "hipDeviceAttributePageableMemoryAccess"), + ("cudaDevAttrPageableMemoryAccessUsesHostPageTables", "hipDeviceAttributePageableMemoryAccessUsesHostPageTables"), + ("cudaDevAttrConcurrentManagedAccess", "hipDeviceAttributeConcurrentManagedAccess"), + ("cudaDevAttrComputePreemptionSupported", "hipDeviceAttributeComputePreemptionSupported"), + ("cudaDevAttrCanUseHostPointerForRegisteredMem", "hipDeviceAttributeCanUseHostPointerForRegisteredMem"), + ("cudaPointerGetAttributes", "hipPointerGetAttributes"), + ("cudaHostGetDevicePointer", "hipHostGetDevicePointer"), + ("cudaGetDeviceProperties", "hipGetDeviceProperties"), + ("cudaDeviceGetPCIBusId", "hipDeviceGetPCIBusId"), + ("cudaDeviceGetByPCIBusId", "hipDeviceGetByPCIBusId"), + ("cudaDeviceGetStreamPriorityRange", "hipDeviceGetStreamPriorityRange"), + ("cudaSetValidDevices", "hipSetValidDevices"), + ("cudaDevP2PAttrPerformanceRank", "hipDeviceP2PAttributePerformanceRank"), + ("cudaDevP2PAttrAccessSupported", "hipDeviceP2PAttributeAccessSupported"), + ("cudaDevP2PAttrNativeAtomicSupported", "hipDeviceP2PAttributeNativeAtomicSupported"), + ("cudaDeviceGetP2PAttribute", "hipDeviceGetP2PAttribute"), + ("cudaComputeModeDefault", "hipComputeModeDefault"), + ("cudaComputeModeExclusive", "hipComputeModeExclusive"), + ("cudaComputeModeProhibited", "hipComputeModeProhibited"), + ("cudaComputeModeExclusiveProcess", "hipComputeModeExclusiveProcess"), + ("cudaGetDeviceFlags", "hipGetDeviceFlags"), + ("cudaSetDeviceFlags", "hipSetDeviceFlags"), + ("cudaDeviceScheduleAuto", "hipDeviceScheduleAuto"), + ("cudaDeviceScheduleSpin", "hipDeviceScheduleSpin"), + ("cudaDeviceScheduleYield", "hipDeviceScheduleYield"), + ("cudaDeviceBlockingSync", "hipDeviceScheduleBlockingSync"), + ("cudaDeviceScheduleBlockingSync", "hipDeviceScheduleBlockingSync"), + ("cudaDeviceScheduleMask", "hipDeviceScheduleMask"), + ("cudaDeviceMapHost", "hipDeviceMapHost"), + ("cudaDeviceLmemResizeToMax", "hipDeviceLmemResizeToMax"), + ("cudaDeviceMask", "hipDeviceMask"), + ("cudaDeviceSetCacheConfig", "hipDeviceSetCacheConfig"), + ("cudaDeviceGetCacheConfig", "hipDeviceGetCacheConfig"), + ("cudaFuncAttributes", "hipFuncAttributes"), + ("cudaFuncAttributeMaxDynamicSharedMemorySize", "hipFuncAttributeMaxDynamicSharedMemorySize"), + ("cudaFuncAttributePreferredSharedMemoryCarveout", "hipFuncAttributePreferredSharedMemoryCarveout"), + ("cudaFuncSetAttribute", "hipFuncSetAttribute"), + ("cudaFuncSetCacheConfig", "hipFuncSetCacheConfig"), + ("cudaFuncCachePreferNone", "hipFuncCachePreferNone"), + ("cudaFuncCachePreferShared", "hipFuncCachePreferShared"), + ("cudaFuncCachePreferL1", "hipFuncCachePreferL1"), + ("cudaFuncCachePreferEqual", "hipFuncCachePreferEqual"), + ("cudaFuncGetAttributes", "hipFuncGetAttributes"), + ("cudaFuncSetSharedMemConfig", "hipFuncSetSharedMemConfig"), + ("cudaGetParameterBuffer", "hipGetParameterBuffer"), + ("cudaSetDoubleForDevice", "hipSetDoubleForDevice"), + ("cudaSetDoubleForHost", "hipSetDoubleForHost"), + ("cudaConfigureCall", "hipConfigureCall"), + ("cudaLaunch", "hipLaunch"), + ("cudaLaunchCooperativeKernel", "hipLaunchCooperativeKernel"), + ("cudaLaunchHostFunc", "hipLaunchHostFunc"), + ("cudaSetupArgument", "hipSetupArgument"), + ("cudaDriverGetVersion", "hipDriverGetVersion"), + ("cudaRuntimeGetVersion", "hipRuntimeGetVersion"), + ("cudaOccupancyMaxPotentialBlockSize", "hipOccupancyMaxPotentialBlockSize"), + ("cudaErrorContextIsDestroyed", "hipErrorContextIsDestroyed"), + ("cudaDeviceSetLimit", "hipDeviceSetLimit"), + ("cudaMallocFromPoolAsync", "hipMallocFromPoolAsync"), + ("cudaDeviceGetMemPool", "hipDeviceGetMemPool"), + ("cudaDeviceSetMemPool", "hipDeviceSetMemPool"), + ("cudaMemPoolAttr", "hipMemPoolAttr"), + ("cudaMemPoolProps", "hipMemPoolProps"), + ("cudaMemAllocationTypePinned", "hipMemAllocationTypePinned"), + ("cudaMemHandleTypeNone", "hipMemHandleTypeNone"), + ("cudaMemHandleTypePosixFileDescriptor", "hipMemHandleTypePosixFileDescriptor"), + ("cudaMemLocation", "hipMemLocation"), + ("cudaMemPoolCreate", "hipMemPoolCreate"), + ("cudaMemPoolDestroy", "hipMemPoolDestroy"), + ("cudaCreateSurfaceObject", "hipCreateSurfaceObject"), + ("cudaDestroySurfaceObject", "hipDestroySurfaceObject"), + ("cudaGraphUpload", "hipGraphUpload"), + ("cudaOccupancyMaxPotentialBlockSizeWithFlags", "hipOccupancyMaxPotentialBlockSizeWithFlags"), + ("cudaOccupancyMaxActiveBlocksPerMultiprocessor", "hipOccupancyMaxActiveBlocksPerMultiprocessor"), + ("cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags", "hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags"), + ("cudaOccupancyMaxPotentialBlockSizeVariableSMem", "hipOccupancyMaxPotentialBlockSizeVariableSMem"), + ("cudaOccupancyMaxPotentialBlockSizeVariableSMemWithFlags", "hipOccupancyMaxPotentialBlockSizeVariableSMemWithFlags"), + ("cudaDeviceCanAccessPeer", "hipDeviceCanAccessPeer"), + ("cudaDeviceDisablePeerAccess", "hipDeviceDisablePeerAccess"), + ("cudaDeviceEnablePeerAccess", "hipDeviceEnablePeerAccess"), + ("cudaMemcpyPeerAsync", "hipMemcpyPeerAsync"), + ("cudaMemcpyPeer", "hipMemcpyPeer"), + ("cudaIpcMemLazyEnablePeerAccess", "hipIpcMemLazyEnablePeerAccess"), + ("cudaDeviceSetSharedMemConfig", "hipDeviceSetSharedMemConfig"), + ("cudaDeviceGetSharedMemConfig", "hipDeviceGetSharedMemConfig"), + ("cudaSharedMemBankSizeDefault", "hipSharedMemBankSizeDefault"), + ("cudaSharedMemBankSizeFourByte", "hipSharedMemBankSizeFourByte"), + ("cudaSharedMemBankSizeEightByte", "hipSharedMemBankSizeEightByte"), + ("cudaLimitStackSize", "hipLimitStackSize"), + ("cudaLimitPrintfFifoSize", "hipLimitPrintfFifoSize"), + ("cudaLimitMallocHeapSize", "hipLimitMallocHeapSize"), + ("cudaLimitDevRuntimeSyncDepth", "hipLimitDevRuntimeSyncDepth"), + ("cudaLimitDevRuntimePendingLaunchCount", "hipLimitDevRuntimePendingLaunchCount"), + ("cudaDeviceGetLimit", "hipDeviceGetLimit"), + ("cudaProfilerInitialize", "hipProfilerInitialize"), + ("cudaProfilerStart", "hipProfilerStart"), + ("cudaProfilerStop", "hipProfilerStop"), + ("cudaKeyValuePair", "hipKeyValuePair"), + ("cudaCSV", "hipCSV"), + ("cudaReadModeElementType", "hipReadModeElementType"), + ("cudaReadModeNormalizedFloat", "hipReadModeNormalizedFloat"), + ("cudaFilterModePoint", "hipFilterModePoint"), + ("cudaFilterModeLinear", "hipFilterModeLinear"), + ("cudaBindTexture", "hipBindTexture"), + ("cudaUnbindTexture", "hipUnbindTexture"), + ("cudaBindTexture2D", "hipBindTexture2D"), + ("cudaBindTextureToArray", "hipBindTextureToArray"), + ("cudaBindTextureToMipmappedArray", "hipBindTextureToMipmappedArray"), + ("cudaGetTextureAlignmentOffset", "hipGetTextureAlignmentOffset"), + ("cudaGetTextureReference", "hipGetTextureReference"), + ("cudaChannelFormatKindSigned", "hipChannelFormatKindSigned"), + ("cudaChannelFormatKindUnsigned", "hipChannelFormatKindUnsigned"), + ("cudaChannelFormatKindFloat", "hipChannelFormatKindFloat"), + ("cudaChannelFormatKindNone", "hipChannelFormatKindNone"), + ("cudaCreateChannelDesc", "hipCreateChannelDesc"), + ("cudaGetChannelDesc", "hipGetChannelDesc"), + ("cudaResourceTypeArray", "hipResourceTypeArray"), + ("cudaResourceTypeMipmappedArray", "hipResourceTypeMipmappedArray"), + ("cudaResourceTypeLinear", "hipResourceTypeLinear"), + ("cudaResourceTypePitch2D", "hipResourceTypePitch2D"), + ("cudaResViewFormatNone", "hipResViewFormatNone"), + ("cudaResViewFormatUnsignedChar1", "hipResViewFormatUnsignedChar1"), + ("cudaResViewFormatUnsignedChar2", "hipResViewFormatUnsignedChar2"), + ("cudaResViewFormatUnsignedChar4", "hipResViewFormatUnsignedChar4"), + ("cudaResViewFormatSignedChar1", "hipResViewFormatSignedChar1"), + ("cudaResViewFormatSignedChar2", "hipResViewFormatSignedChar2"), + ("cudaResViewFormatSignedChar4", "hipResViewFormatSignedChar4"), + ("cudaResViewFormatUnsignedShort1", "hipResViewFormatUnsignedShort1"), + ("cudaResViewFormatUnsignedShort2", "hipResViewFormatUnsignedShort2"), + ("cudaResViewFormatUnsignedShort4", "hipResViewFormatUnsignedShort4"), + ("cudaResViewFormatSignedShort1", "hipResViewFormatSignedShort1"), + ("cudaResViewFormatSignedShort2", "hipResViewFormatSignedShort2"), + ("cudaResViewFormatSignedShort4", "hipResViewFormatSignedShort4"), + ("cudaResViewFormatUnsignedInt1", "hipResViewFormatUnsignedInt1"), + ("cudaResViewFormatUnsignedInt2", "hipResViewFormatUnsignedInt2"), + ("cudaResViewFormatUnsignedInt4", "hipResViewFormatUnsignedInt4"), + ("cudaResViewFormatSignedInt1", "hipResViewFormatSignedInt1"), + ("cudaResViewFormatSignedInt2", "hipResViewFormatSignedInt2"), + ("cudaResViewFormatSignedInt4", "hipResViewFormatSignedInt4"), + ("cudaResViewFormatHalf1", "hipResViewFormatHalf1"), + ("cudaResViewFormatHalf2", "hipResViewFormatHalf2"), + ("cudaResViewFormatHalf4", "hipResViewFormatHalf4"), + ("cudaResViewFormatFloat1", "hipResViewFormatFloat1"), + ("cudaResViewFormatFloat2", "hipResViewFormatFloat2"), + ("cudaResViewFormatFloat4", "hipResViewFormatFloat4"), + ("cudaResViewFormatUnsignedBlockCompressed1", "hipResViewFormatUnsignedBlockCompressed1"), + ("cudaResViewFormatUnsignedBlockCompressed2", "hipResViewFormatUnsignedBlockCompressed2"), + ("cudaResViewFormatUnsignedBlockCompressed3", "hipResViewFormatUnsignedBlockCompressed3"), + ("cudaResViewFormatUnsignedBlockCompressed4", "hipResViewFormatUnsignedBlockCompressed4"), + ("cudaResViewFormatSignedBlockCompressed4", "hipResViewFormatSignedBlockCompressed4"), + ("cudaResViewFormatUnsignedBlockCompressed5", "hipResViewFormatUnsignedBlockCompressed5"), + ("cudaResViewFormatSignedBlockCompressed5", "hipResViewFormatSignedBlockCompressed5"), + ("cudaResViewFormatUnsignedBlockCompressed6H", "hipResViewFormatUnsignedBlockCompressed6H"), + ("cudaResViewFormatSignedBlockCompressed6H", "hipResViewFormatSignedBlockCompressed6H"), + ("cudaResViewFormatUnsignedBlockCompressed7", "hipResViewFormatUnsignedBlockCompressed7"), + ("cudaAddressModeWrap", "hipAddressModeWrap"), + ("cudaAddressModeClamp", "hipAddressModeClamp"), + ("cudaAddressModeMirror", "hipAddressModeMirror"), + ("cudaAddressModeBorder", "hipAddressModeBorder"), + ("cudaCreateTextureObject", "hipCreateTextureObject"), + ("cudaDestroyTextureObject", "hipDestroyTextureObject"), + ("cudaGetTextureObjectResourceDesc", "hipGetTextureObjectResourceDesc"), + ("cudaGetTextureObjectResourceViewDesc", "hipGetTextureObjectResourceViewDesc"), + ("cudaGetTextureObjectTextureDesc", "hipGetTextureObjectTextureDesc"), + ("cudaBindSurfaceToArray", "hipBindSurfaceToArray"), + ("cudaGetSurfaceReference", "hipGetSurfaceReference"), + ("cudaBoundaryModeZero", "hipBoundaryModeZero"), + ("cudaBoundaryModeClamp", "hipBoundaryModeClamp"), + ("cudaBoundaryModeTrap", "hipBoundaryModeTrap"), + ("cudaFormatModeForced", "hipFormatModeForced"), + ("cudaFormatModeAuto", "hipFormatModeAuto"), + ("cudaGetSurfaceObjectResourceDesc", "hipGetSurfaceObjectResourceDesc"), + ("cudaIpcCloseMemHandle", "hipIpcCloseMemHandle"), + ("cudaIpcGetEventHandle", "hipIpcGetEventHandle"), + ("cudaIpcGetMemHandle", "hipIpcGetMemHandle"), + ("cudaIpcOpenEventHandle", "hipIpcOpenEventHandle"), + ("cudaIpcOpenMemHandle", "hipIpcOpenMemHandle"), + ("cudaGLGetDevices", "hipGLGetDevices"), + ("cudaGraphicsGLRegisterBuffer", "hipGraphicsGLRegisterBuffer"), + ("cudaGraphicsGLRegisterImage", "hipGraphicsGLRegisterImage"), + ("cudaWGLGetDevice", "hipWGLGetDevice"), + ("cudaGraphicsMapResources", "hipGraphicsMapResources"), + ("cudaGraphicsResourceGetMappedMipmappedArray", "hipGraphicsResourceGetMappedMipmappedArray"), + ("cudaGraphicsResourceGetMappedPointer", "hipGraphicsResourceGetMappedPointer"), + ("cudaGraphicsResourceSetMapFlags", "hipGraphicsResourceSetMapFlags"), + ("cudaGraphicsSubResourceGetMappedArray", "hipGraphicsSubResourceGetMappedArray"), + ("cudaGraphicsUnmapResources", "hipGraphicsUnmapResources"), + ("cudaGraphicsUnregisterResource", "hipGraphicsUnregisterResource"), + ("cudaGraphicsCubeFacePositiveX", "hipGraphicsCubeFacePositiveX"), + ("cudaGraphicsCubeFaceNegativeX", "hipGraphicsCubeFaceNegativeX"), + ("cudaGraphicsCubeFacePositiveY", "hipGraphicsCubeFacePositiveY"), + ("cudaGraphicsCubeFaceNegativeY", "hipGraphicsCubeFaceNegativeY"), + ("cudaGraphicsCubeFacePositiveZ", "hipGraphicsCubeFacePositiveZ"), + ("cudaGraphicsCubeFaceNegativeZ", "hipGraphicsCubeFaceNegativeZ"), + ("cudaGraphicsMapFlagsNone", "hipGraphicsMapFlagsNone"), + ("cudaGraphicsMapFlagsReadOnly", "hipGraphicsMapFlagsReadOnly"), + ("cudaGraphicsMapFlagsWriteDiscard", "hipGraphicsMapFlagsWriteDiscard"), + ("cudaGraphicsRegisterFlagsNone", "hipGraphicsRegisterFlagsNone"), + ("cudaGraphicsRegisterFlagsReadOnly", "hipGraphicsRegisterFlagsReadOnly"), + ("cudaGraphicsRegisterFlagsWriteDiscard", "hipGraphicsRegisterFlagsWriteDiscard"), + ("cudaGraphicsRegisterFlagsSurfaceLoadStore", "hipGraphicsRegisterFlagsSurfaceLoadStore"), + ("cudaGraphicsRegisterFlagsTextureGather", "hipGraphicsRegisterFlagsTextureGather"), + ("cudaGLDeviceListAll", "HIP_GL_DEVICE_LIST_ALL"), + ("cudaGLDeviceListCurrentFrame", "HIP_GL_DEVICE_LIST_CURRENT_FRAME"), + ("cudaGLDeviceListNextFrame", "HIP_GL_DEVICE_LIST_NEXT_FRAME"), + ("cudaGLMapFlagsNone", "HIP_GL_MAP_RESOURCE_FLAGS_NONE"), + ("cudaGLMapFlagsReadOnly", "HIP_GL_MAP_RESOURCE_FLAGS_READ_ONLY"), + ("cudaGLMapFlagsWriteDiscard", "HIP_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD"), + ("cudaGLMapBufferObject", "hipGLMapBufferObject__"), + ("cudaGLMapBufferObjectAsync", "hipGLMapBufferObjectAsync__"), + ("cudaGLRegisterBufferObject", "hipGLRegisterBufferObject"), + ("cudaGLSetBufferObjectMapFlags", "hipGLSetBufferObjectMapFlags"), + ("cudaGLSetGLDevice", "hipGLSetGLDevice"), + ("cudaGLUnmapBufferObject", "hipGLUnmapBufferObject"), + ("cudaGLUnmapBufferObjectAsync", "hipGLUnmapBufferObjectAsync"), + ("cudaGLUnregisterBufferObject", "hipGLUnregisterBufferObject"), + ("cudaD3D9DeviceListAll", "HIP_D3D9_DEVICE_LIST_ALL"), + ("cudaD3D9DeviceListCurrentFrame", "HIP_D3D9_DEVICE_LIST_CURRENT_FRAME"), + ("cudaD3D9DeviceListNextFrame", "HIP_D3D9_DEVICE_LIST_NEXT_FRAME"), + ("cudaD3D9GetDevice", "hipD3D9GetDevice"), + ("cudaD3D9GetDevices", "hipD3D9GetDevices"), + ("cudaD3D9GetDirect3DDevice", "hipD3D9GetDirect3DDevice"), + ("cudaD3D9SetDirect3DDevice", "hipD3D9SetDirect3DDevice"), + ("cudaGraphicsD3D9RegisterResource", "hipGraphicsD3D9RegisterResource"), + ("cudaD3D9MapFlags", "hipD3D9MapFlags"), + ("cudaD3D9MapFlagsNone", "HIP_D3D9_MAPRESOURCE_FLAGS_NONE"), + ("cudaD3D9MapFlagsReadOnly", "HIP_D3D9_MAPRESOURCE_FLAGS_READONLY"), + ("cudaD3D9MapFlagsWriteDiscard", "HIP_D3D9_MAPRESOURCE_FLAGS_WRITEDISCARD"), + ("cudaD3D9RegisterFlagsNone", "HIP_D3D9_REGISTER_FLAGS_NONE"), + ("cudaD3D9RegisterFlagsArray", "HIP_D3D9_REGISTER_FLAGS_ARRAY"), + ("cudaD3D9MapResources", "hipD3D9MapResources"), + ("cudaD3D9RegisterResource", "hipD3D9RegisterResource"), + ("cudaD3D9ResourceGetMappedArray", "hipD3D9ResourceGetMappedArray"), + ("cudaD3D9ResourceGetMappedPitch", "hipD3D9ResourceGetMappedPitch"), + ("cudaD3D9ResourceGetMappedPointer", "hipD3D9ResourceGetMappedPointer"), + ("cudaD3D9ResourceGetMappedSize", "hipD3D9ResourceGetMappedSize"), + ("cudaD3D9ResourceGetSurfaceDimensions", "hipD3D9ResourceGetSurfaceDimensions"), + ("cudaD3D9ResourceSetMapFlags", "hipD3D9ResourceSetMapFlags"), + ("cudaD3D9UnmapResources", "hipD3D9UnmapResources"), + ("cudaD3D9UnregisterResource", "hipD3D9UnregisterResource"), + ("cudaD3D10DeviceListAll", "HIP_D3D10_DEVICE_LIST_ALL"), + ("cudaD3D10DeviceListCurrentFrame", "HIP_D3D10_DEVICE_LIST_CURRENT_FRAME"), + ("cudaD3D10DeviceListNextFrame", "HIP_D3D10_DEVICE_LIST_NEXT_FRAME"), + ("cudaD3D10GetDevice", "hipD3D10GetDevice"), + ("cudaD3D10GetDevices", "hipD3D10GetDevices"), + ("cudaGraphicsD3D10RegisterResource", "hipGraphicsD3D10RegisterResource"), + ("cudaD3D10MapFlagsNone", "HIP_D3D10_MAPRESOURCE_FLAGS_NONE"), + ("cudaD3D10MapFlagsReadOnly", "HIP_D3D10_MAPRESOURCE_FLAGS_READONLY"), + ("cudaD3D10MapFlagsWriteDiscard", "HIP_D3D10_MAPRESOURCE_FLAGS_WRITEDISCARD"), + ("cudaD3D10RegisterFlagsNone", "HIP_D3D10_REGISTER_FLAGS_NONE"), + ("cudaD3D10RegisterFlagsArray", "HIP_D3D10_REGISTER_FLAGS_ARRAY"), + ("cudaD3D10GetDirect3DDevice", "hipD3D10GetDirect3DDevice"), + ("cudaD3D10MapResources", "hipD3D10MapResources"), + ("cudaD3D10RegisterResource", "hipD3D10RegisterResource"), + ("cudaD3D10ResourceGetMappedArray", "hipD3D10ResourceGetMappedArray"), + ("cudaD3D10ResourceGetMappedPitch", "hipD3D10ResourceGetMappedPitch"), + ("cudaD3D10ResourceGetMappedPointer", "hipD3D10ResourceGetMappedPointer"), + ("cudaD3D10ResourceGetMappedSize", "hipD3D10ResourceGetMappedSize"), + ("cudaD3D10ResourceGetSurfaceDimensions", "hipD3D10ResourceGetSurfaceDimensions"), + ("cudaD3D10ResourceSetMapFlags", "hipD3D10ResourceSetMapFlags"), + ("cudaD3D10SetDirect3DDevice", "hipD3D10SetDirect3DDevice"), + ("cudaD3D10UnmapResources", "hipD3D10UnmapResources"), + ("cudaD3D10UnregisterResource", "hipD3D10UnregisterResource"), + ("cudaD3D11DeviceListAll", "HIP_D3D11_DEVICE_LIST_ALL"), + ("cudaD3D11DeviceListCurrentFrame", "HIP_D3D11_DEVICE_LIST_CURRENT_FRAME"), + ("cudaD3D11DeviceListNextFrame", "HIP_D3D11_DEVICE_LIST_NEXT_FRAME"), + ("cudaD3D11GetDevice", "hipD3D11GetDevice"), + ("cudaD3D11GetDevices", "hipD3D11GetDevices"), + ("cudaGraphicsD3D11RegisterResource", "hipGraphicsD3D11RegisterResource"), + ("cudaGraphicsVDPAURegisterOutputSurface", "hipGraphicsVDPAURegisterOutputSurface"), + ("cudaGraphicsVDPAURegisterVideoSurface", "hipGraphicsVDPAURegisterVideoSurface"), + ("cudaVDPAUGetDevice", "hipVDPAUGetDevice"), + ("cudaVDPAUSetVDPAUDevice", "hipVDPAUSetDevice"), + ("cudaEGLStreamConsumerAcquireFrame", "hipEGLStreamConsumerAcquireFrame"), + ("cudaEGLStreamConsumerConnect", "hipEGLStreamConsumerConnect"), + ("cudaEGLStreamConsumerConnectWithFlags", "hipEGLStreamConsumerConnectWithFlags"), + ("cudaEGLStreamConsumerReleaseFrame", "hipEGLStreamConsumerReleaseFrame"), + ("cudaEGLStreamProducerConnect", "hipEGLStreamProducerConnect"), + ("cudaEGLStreamProducerDisconnect", "hipEGLStreamProducerDisconnect"), + ("cudaEGLStreamProducerPresentFrame", "hipEGLStreamProducerPresentFrame"), + ("cudaEGLStreamProducerReturnFrame", "hipEGLStreamProducerReturnFrame"), + ("cudaGraphicsEGLRegisterImage", "hipGraphicsEGLRegisterImage"), + ("cudaGraphicsResourceGetMappedEglFrame", "hipGraphicsResourceGetMappedEglFrame"), + ("cublasInit", "hipblasInit"), + ("cublasShutdown", "hipblasShutdown"), + ("cublasGetVersion", "hipblasGetVersion"), + ("cublasGetError", "hipblasGetError"), + ("cublasAlloc", "hipblasAlloc"), + ("cublasFree", "hipblasFree"), + ("cublasSetKernelStream", "hipblasSetKernelStream"), + ("cublasGetAtomicsMode", "hipblasGetAtomicsMode"), + ("cublasSetAtomicsMode", "hipblasSetAtomicsMode"), + ("cublasGetMathMode", "hipblasGetMathMode"), + ("cublasSetMathMode", "hipblasSetMathMode"), + ("CUBLAS_OP_N", "HIPBLAS_OP_N"), + ("CUBLAS_OP_T", "HIPBLAS_OP_T"), + ("CUBLAS_OP_C", "HIPBLAS_OP_C"), + ("CUBLAS_STATUS_SUCCESS", "HIPBLAS_STATUS_SUCCESS"), + ("CUBLAS_STATUS_NOT_INITIALIZED", "HIPBLAS_STATUS_NOT_INITIALIZED"), + ("CUBLAS_STATUS_ALLOC_FAILED", "HIPBLAS_STATUS_ALLOC_FAILED"), + ("CUBLAS_STATUS_INVALID_VALUE", "HIPBLAS_STATUS_INVALID_VALUE"), + ("CUBLAS_STATUS_MAPPING_ERROR", "HIPBLAS_STATUS_MAPPING_ERROR"), + ("CUBLAS_STATUS_EXECUTION_FAILED", "HIPBLAS_STATUS_EXECUTION_FAILED"), + ("CUBLAS_STATUS_INTERNAL_ERROR", "HIPBLAS_STATUS_INTERNAL_ERROR"), + ("CUBLAS_STATUS_NOT_SUPPORTED", "HIPBLAS_STATUS_NOT_SUPPORTED"), + ("CUBLAS_STATUS_ARCH_MISMATCH", "HIPBLAS_STATUS_ARCH_MISMATCH"), + ("CUBLAS_FILL_MODE_LOWER", "HIPBLAS_FILL_MODE_LOWER"), + ("CUBLAS_FILL_MODE_UPPER", "HIPBLAS_FILL_MODE_UPPER"), + ("CUBLAS_DIAG_NON_UNIT", "HIPBLAS_DIAG_NON_UNIT"), + ("CUBLAS_DIAG_UNIT", "HIPBLAS_DIAG_UNIT"), + ("CUBLAS_SIDE_LEFT", "HIPBLAS_SIDE_LEFT"), + ("CUBLAS_SIDE_RIGHT", "HIPBLAS_SIDE_RIGHT"), + ("CUBLAS_POINTER_MODE_HOST", "HIPBLAS_POINTER_MODE_HOST"), + ("CUBLAS_POINTER_MODE_DEVICE", "HIPBLAS_POINTER_MODE_DEVICE"), + ("CUBLAS_ATOMICS_NOT_ALLOWED", "HIPBLAS_ATOMICS_NOT_ALLOWED"), + ("CUBLAS_ATOMICS_ALLOWED", "HIPBLAS_ATOMICS_ALLOWED"), + ("CUBLAS_DATA_FLOAT", "HIPBLAS_DATA_FLOAT"), + ("CUBLAS_DATA_DOUBLE", "HIPBLAS_DATA_DOUBLE"), + ("CUBLAS_DATA_HALF", "HIPBLAS_DATA_HALF"), + ("CUBLAS_DATA_INT8", "HIPBLAS_DATA_INT8"), + ("CUBLAS_GEMM_DEFAULT", "HIPBLAS_GEMM_DEFAULT"), + ("CUBLAS_GEMM_DEFAULT_TENSOR_OP", "HIPBLAS_GEMM_DEFAULT"), + ("cublasCreate", "hipblasCreate"), + ("cublasDestroy", "hipblasDestroy"), + ("cublasSetVector", "hipblasSetVector"), + ("cublasGetVector", "hipblasGetVector"), + ("cublasSetVectorAsync", "hipblasSetVectorAsync"), + ("cublasGetVectorAsync", "hipblasGetVectorAsync"), + ("cublasSetMatrix", "hipblasSetMatrix"), + ("cublasGetMatrix", "hipblasGetMatrix"), + ("cublasGetMatrixAsync", "hipblasGetMatrixAsync"), + ("cublasSetMatrixAsync", "hipblasSetMatrixAsync"), + ("cublasXerbla", "hipblasXerbla"), + ("cublasSnrm2", "hipblasSnrm2"), + ("cublasDnrm2", "hipblasDnrm2"), + ("cublasScnrm2", "hipblasScnrm2"), + ("cublasDznrm2", "hipblasDznrm2"), + ("cublasNrm2Ex", "hipblasNrm2Ex"), + ("cublasSdot", "hipblasSdot"), + ("cublasSdotBatched", "hipblasSdotBatched"), + ("cublasDdot", "hipblasDdot"), + ("cublasDdotBatched", "hipblasDdotBatched"), + ("cublasCdotu", "hipblasCdotu"), + ("cublasCdotc", "hipblasCdotc"), + ("cublasZdotu", "hipblasZdotu"), + ("cublasZdotc", "hipblasZdotc"), + ("cublasSscal", "hipblasSscal"), + ("cublasSscalBatched", "hipblasSscalBatched"), + ("cublasDscal", "hipblasDscal"), + ("cublasDscalBatched", "hipblasDscalBatched"), + ("cublasCscal", "hipblasCscal"), + ("cublasCsscal", "hipblasCsscal"), + ("cublasZscal", "hipblasZscal"), + ("cublasZdscal", "hipblasZdscal"), + ("cublasSaxpy", "hipblasSaxpy"), + ("cublasSaxpyBatched", "hipblasSaxpyBatched"), + ("cublasDaxpy", "hipblasDaxpy"), + ("cublasCaxpy", "hipblasCaxpy"), + ("cublasZaxpy", "hipblasZaxpy"), + ("cublasScopy", "hipblasScopy"), + ("cublasScopyBatched", "hipblasScopyBatched"), + ("cublasDcopy", "hipblasDcopy"), + ("cublasDcopyBatched", "hipblasDcopyBatched"), + ("cublasCcopy", "hipblasCcopy"), + ("cublasZcopy", "hipblasZcopy"), + ("cublasSswap", "hipblasSswap"), + ("cublasDswap", "hipblasDswap"), + ("cublasCswap", "hipblasCswap"), + ("cublasZswap", "hipblasZswap"), + ("cublasIsamax", "hipblasIsamax"), + ("cublasIdamax", "hipblasIdamax"), + ("cublasIcamax", "hipblasIcamax"), + ("cublasIzamax", "hipblasIzamax"), + ("cublasIsamin", "hipblasIsamin"), + ("cublasIdamin", "hipblasIdamin"), + ("cublasIcamin", "hipblasIcamin"), + ("cublasIzamin", "hipblasIzamin"), + ("cublasSasum", "hipblasSasum"), + ("cublasSasumBatched", "hipblasSasumBatched"), + ("cublasDasum", "hipblasDasum"), + ("cublasDasumBatched", "hipblasDasumBatched"), + ("cublasScasum", "hipblasScasum"), + ("cublasDzasum", "hipblasDzasum"), + ("cublasSrot", "hipblasSrot"), + ("cublasDrot", "hipblasDrot"), + ("cublasCrot", "hipblasCrot"), + ("cublasCsrot", "hipblasCsrot"), + ("cublasZrot", "hipblasZrot"), + ("cublasZdrot", "hipblasZdrot"), + ("cublasSrotg", "hipblasSrotg"), + ("cublasDrotg", "hipblasDrotg"), + ("cublasCrotg", "hipblasCrotg"), + ("cublasZrotg", "hipblasZrotg"), + ("cublasSrotm", "hipblasSrotm"), + ("cublasDrotm", "hipblasDrotm"), + ("cublasSrotmg", "hipblasSrotmg"), + ("cublasDrotmg", "hipblasDrotmg"), + ("cublasSgemv", "hipblasSgemv"), + ("cublasSgemvBatched", "hipblasSgemvBatched"), + ("cublasDgemv", "hipblasDgemv"), + ("cublasCgemv", "hipblasCgemv"), + ("cublasZgemv", "hipblasZgemv"), + ("cublasSgbmv", "hipblasSgbmv"), + ("cublasDgbmv", "hipblasDgbmv"), + ("cublasCgbmv", "hipblasCgbmv"), + ("cublasZgbmv", "hipblasZgbmv"), + ("cublasStrmv", "hipblasStrmv"), + ("cublasDtrmv", "hipblasDtrmv"), + ("cublasCtrmv", "hipblasCtrmv"), + ("cublasZtrmv", "hipblasZtrmv"), + ("cublasStbmv", "hipblasStbmv"), + ("cublasDtbmv", "hipblasDtbmv"), + ("cublasCtbmv", "hipblasCtbmv"), + ("cublasZtbmv", "hipblasZtbmv"), + ("cublasStpmv", "hipblasStpmv"), + ("cublasDtpmv", "hipblasDtpmv"), + ("cublasCtpmv", "hipblasCtpmv"), + ("cublasZtpmv", "hipblasZtpmv"), + ("cublasStrsv", "hipblasStrsv"), + ("cublasDtrsv", "hipblasDtrsv"), + ("cublasCtrsv", "hipblasCtrsv"), + ("cublasZtrsv", "hipblasZtrsv"), + ("cublasStpsv", "hipblasStpsv"), + ("cublasDtpsv", "hipblasDtpsv"), + ("cublasCtpsv", "hipblasCtpsv"), + ("cublasZtpsv", "hipblasZtpsv"), + ("cublasStbsv", "hipblasStbsv"), + ("cublasDtbsv", "hipblasDtbsv"), + ("cublasCtbsv", "hipblasCtbsv"), + ("cublasZtbsv", "hipblasZtbsv"), + ("cublasSsymv", "hipblasSsymv"), + ("cublasDsymv", "hipblasDsymv"), + ("cublasCsymv", "hipblasCsymv"), + ("cublasZsymv", "hipblasZsymv"), + ("cublasChemv", "hipblasChemv"), + ("cublasZhemv", "hipblasZhemv"), + ("cublasSsbmv", "hipblasSsbmv"), + ("cublasDsbmv", "hipblasDsbmv"), + ("cublasChbmv", "hipblasChbmv"), + ("cublasZhbmv", "hipblasZhbmv"), + ("cublasSspmv", "hipblasSspmv"), + ("cublasDspmv", "hipblasDspmv"), + ("cublasChpmv", "hipblasChpmv"), + ("cublasZhpmv", "hipblasZhpmv"), + ("cublasSger", "hipblasSger"), + ("cublasDger", "hipblasDger"), + ("cublasCgeru", "hipblasCgeru"), + ("cublasCgerc", "hipblasCgerc"), + ("cublasZgeru", "hipblasZgeru"), + ("cublasZgerc", "hipblasZgerc"), + ("cublasSsyr", "hipblasSsyr"), + ("cublasDsyr", "hipblasDsyr"), + ("cublasCher", "hipblasCher"), + ("cublasZher", "hipblasZher"), + ("cublasSspr", "hipblasSspr"), + ("cublasDspr", "hipblasDspr"), + ("cublasChpr", "hipblasChpr"), + ("cublasZhpr", "hipblasZhpr"), + ("cublasSsyr2", "hipblasSsyr2"), + ("cublasDsyr2", "hipblasDsyr2"), + ("cublasCher2", "hipblasCher2"), + ("cublasZher2", "hipblasZher2"), + ("cublasSspr2", "hipblasSspr2"), + ("cublasDspr2", "hipblasDspr2"), + ("cublasChpr2", "hipblasChpr2"), + ("cublasZhpr2", "hipblasZhpr2"), + ("cublasSgemmBatched", "hipblasSgemmBatched"), + ("cublasDgemmBatched", "hipblasDgemmBatched"), + ("cublasHgemmBatched", "hipblasHgemmBatched"), + ("cublasSgemmStridedBatched", "hipblasSgemmStridedBatched"), + ("cublasDgemmStridedBatched", "hipblasDgemmStridedBatched"), + ("cublasHgemmStridedBatched", "hipblasHgemmStridedBatched"), + ("cublasCgemmBatched", "hipblasCgemmBatched"), + ("cublasCgemm3mBatched", "hipblasCgemm3mBatched"), + ("cublasZgemmBatched", "hipblasZgemmBatched"), + ("cublasCgemmStridedBatched", "hipblasCgemmStridedBatched"), + ("cublasCgemm3mStridedBatched", "hipblasCgemm3mStridedBatched"), + ("cublasZgemmStridedBatched", "hipblasZgemmStridedBatched"), + ("cublasSgemm", "hipblasSgemm"), + ("cublasDgemm", "hipblasDgemm"), + ("cublasCgemm", "hipblasCgemm"), + ("cublasZgemm", "hipblasZgemm"), + ("cublasHgemm", "hipblasHgemm"), + ("cublasSsyrk", "hipblasSsyrk"), + ("cublasDsyrk", "hipblasDsyrk"), + ("cublasCsyrk", "hipblasCsyrk"), + ("cublasZsyrk", "hipblasZsyrk"), + ("cublasCherk", "hipblasCherk"), + ("cublasZherk", "hipblasZherk"), + ("cublasSsyr2k", "hipblasSsyr2k"), + ("cublasDsyr2k", "hipblasDsyr2k"), + ("cublasCsyr2k", "hipblasCsyr2k"), + ("cublasZsyr2k", "hipblasZsyr2k"), + ("cublasSsyrkx", "hipblasSsyrkx"), + ("cublasDsyrkx", "hipblasDsyrkx"), + ("cublasCsyrkx", "hipblasCsyrkx"), + ("cublasZsyrkx", "hipblasZsyrkx"), + ("cublasCher2k", "hipblasCher2k"), + ("cublasZher2k", "hipblasZher2k"), + ("cublasCherkx", "hipblasCherkx"), + ("cublasZherkx", "hipblasZherkx"), + ("cublasSsymm", "hipblasSsymm"), + ("cublasDsymm", "hipblasDsymm"), + ("cublasCsymm", "hipblasCsymm"), + ("cublasZsymm", "hipblasZsymm"), + ("cublasChemm", "hipblasChemm"), + ("cublasZhemm", "hipblasZhemm"), + ("cublasStrsm", "hipblasStrsm"), + ("cublasDtrsm", "hipblasDtrsm"), + ("cublasCtrsm", "hipblasCtrsm"), + ("cublasZtrsm", "hipblasZtrsm"), + ("cublasStrsmBatched", "hipblasStrsmBatched"), + ("cublasDtrsmBatched", "hipblasDtrsmBatched"), + ("cublasCtrsmBatched", "hipblasCtrsmBatched"), + ("cublasZtrsmBatched", "hipblasZtrsmBatched"), + ("cublasStrmm", "hipblasStrmm"), + ("cublasDtrmm", "hipblasDtrmm"), + ("cublasCtrmm", "hipblasCtrmm"), + ("cublasZtrmm", "hipblasZtrmm"), + ("cublasSgeam", "hipblasSgeam"), + ("cublasDgeam", "hipblasDgeam"), + ("cublasCgeam", "hipblasCgeam"), + ("cublasZgeam", "hipblasZgeam"), + ("cublasSgetrfBatched", "hipblasSgetrfBatched"), + ("cublasDgetrfBatched", "hipblasDgetrfBatched"), + ("cublasCgetrfBatched", "hipblasCgetrfBatched"), + ("cublasZgetrfBatched", "hipblasZgetrfBatched"), + ("cublasSgetriBatched", "hipblasSgetriBatched"), + ("cublasDgetriBatched", "hipblasDgetriBatched"), + ("cublasCgetriBatched", "hipblasCgetriBatched"), + ("cublasZgetriBatched", "hipblasZgetriBatched"), + ("cublasSgetrsBatched", "hipblasSgetrsBatched"), + ("cublasDgetrsBatched", "hipblasDgetrsBatched"), + ("cublasCgetrsBatched", "hipblasCgetrsBatched"), + ("cublasZgetrsBatched", "hipblasZgetrsBatched"), + ("cublasSmatinvBatched", "hipblasSmatinvBatched"), + ("cublasDmatinvBatched", "hipblasDmatinvBatched"), + ("cublasCmatinvBatched", "hipblasCmatinvBatched"), + ("cublasZmatinvBatched", "hipblasZmatinvBatched"), + ("cublasSgeqrfBatched", "hipblasSgeqrfBatched"), + ("cublasDgeqrfBatched", "hipblasDgeqrfBatched"), + ("cublasCgeqrfBatched", "hipblasCgeqrfBatched"), + ("cublasZgeqrfBatched", "hipblasZgeqrfBatched"), + ("cublasSgelsBatched", "hipblasSgelsBatched"), + ("cublasDgelsBatched", "hipblasDgelsBatched"), + ("cublasCgelsBatched", "hipblasCgelsBatched"), + ("cublasZgelsBatched", "hipblasZgelsBatched"), + ("cublasSdgmm", "hipblasSdgmm"), + ("cublasDdgmm", "hipblasDdgmm"), + ("cublasCdgmm", "hipblasCdgmm"), + ("cublasZdgmm", "hipblasZdgmm"), + ("cublasStpttr", "hipblasStpttr"), + ("cublasDtpttr", "hipblasDtpttr"), + ("cublasCtpttr", "hipblasCtpttr"), + ("cublasZtpttr", "hipblasZtpttr"), + ("cublasStrttp", "hipblasStrttp"), + ("cublasDtrttp", "hipblasDtrttp"), + ("cublasCtrttp", "hipblasCtrttp"), + ("cublasZtrttp", "hipblasZtrttp"), + ("cublasCreate_v2", "hipblasCreate_v2"), + ("cublasDestroy_v2", "hipblasDestroy_v2"), + ("cublasGetVersion_v2", "hipblasGetVersion_v2"), + ("cublasSetWorkspace", "hipblasSetWorkspace"), + ("cublasSetStream", "hipblasSetStream"), + ("cublasGetStream", "hipblasGetStream"), + ("cublasSetStream_v2", "hipblasSetStream_v2"), + ("cublasGetStream_v2", "hipblasGetStream_v2"), + ("cublasGetPointerMode", "hipblasGetPointerMode"), + ("cublasSetPointerMode", "hipblasSetPointerMode"), + ("cublasGetPointerMode_v2", "hipblasGetPointerMode_v2"), + ("cublasSetPointerMode_v2", "hipblasSetPointerMode_v2"), + ("cublasSgemv_v2", "hipblasSgemv_v2"), + ("cublasDgemv_v2", "hipblasDgemv_v2"), + ("cublasCgemv_v2", "hipblasCgemv_v2"), + ("cublasZgemv_v2", "hipblasZgemv_v2"), + ("cublasSgbmv_v2", "hipblasSgbmv_v2"), + ("cublasDgbmv_v2", "hipblasDgbmv_v2"), + ("cublasCgbmv_v2", "hipblasCgbmv_v2"), + ("cublasZgbmv_v2", "hipblasZgbmv_v2"), + ("cublasStrmv_v2", "hipblasStrmv_v2"), + ("cublasDtrmv_v2", "hipblasDtrmv_v2"), + ("cublasCtrmv_v2", "hipblasCtrmv_v2"), + ("cublasZtrmv_v2", "hipblasZtrmv_v2"), + ("cublasStbmv_v2", "hipblasStbmv_v2"), + ("cublasDtbmv_v2", "hipblasDtbmv_v2"), + ("cublasCtbmv_v2", "hipblasCtbmv_v2"), + ("cublasZtbmv_v2", "hipblasZtbmv_v2"), + ("cublasStpmv_v2", "hipblasStpmv_v2"), + ("cublasDtpmv_v2", "hipblasDtpmv_v2"), + ("cublasCtpmv_v2", "hipblasCtpmv_v2"), + ("cublasZtpmv_v2", "hipblasZtpmv_v2"), + ("cublasStrsv_v2", "hipblasStrsv_v2"), + ("cublasDtrsv_v2", "hipblasDtrsv_v2"), + ("cublasCtrsv_v2", "hipblasCtrsv_v2"), + ("cublasZtrsv_v2", "hipblasZtrsv_v2"), + ("cublasStpsv_v2", "hipblasStpsv_v2"), + ("cublasDtpsv_v2", "hipblasDtpsv_v2"), + ("cublasCtpsv_v2", "hipblasCtpsv_v2"), + ("cublasZtpsv_v2", "hipblasZtpsv_v2"), + ("cublasStbsv_v2", "hipblasStbsv_v2"), + ("cublasDtbsv_v2", "hipblasDtbsv_v2"), + ("cublasCtbsv_v2", "hipblasCtbsv_v2"), + ("cublasZtbsv_v2", "hipblasZtbsv_v2"), + ("cublasSsymv_v2", "hipblasSsymv_v2"), + ("cublasDsymv_v2", "hipblasDsymv_v2"), + ("cublasCsymv_v2", "hipblasCsymv_v2"), + ("cublasZsymv_v2", "hipblasZsymv_v2"), + ("cublasChemv_v2", "hipblasChemv_v2"), + ("cublasZhemv_v2", "hipblasZhemv_v2"), + ("cublasSsbmv_v2", "hipblasSsbmv_v2"), + ("cublasDsbmv_v2", "hipblasDsbmv_v2"), + ("cublasChbmv_v2", "hipblasChbmv_v2"), + ("cublasZhbmv_v2", "hipblasZhbmv_v2"), + ("cublasSspmv_v2", "hipblasSspmv_v2"), + ("cublasDspmv_v2", "hipblasDspmv_v2"), + ("cublasChpmv_v2", "hipblasChpmv_v2"), + ("cublasZhpmv_v2", "hipblasZhpmv_v2"), + ("cublasSger_v2", "hipblasSger_v2"), + ("cublasDger_v2", "hipblasDger_v2"), + ("cublasCgeru_v2", "hipblasCgeru_v2"), + ("cublasCgerc_v2", "hipblasCergc_v2"), + ("cublasZgeru_v2", "hipblasZgeru_v2"), + ("cublasZgerc_v2", "hipblasZgerc_v2"), + ("cublasSsyr_v2", "hipblasSsyr_v2"), + ("cublasDsyr_v2", "hipblasDsyr_v2"), + ("cublasCsyr_v2", "hipblasCsyr_v2"), + ("cublasZsyr_v2", "hipblasZsyr_v2"), + ("cublasCher_v2", "hipblasCher_v2"), + ("cublasZher_v2", "hipblasZher_v2"), + ("cublasSspr_v2", "hipblasSspr_v2"), + ("cublasDspr_v2", "hipblasDspr_v2"), + ("cublasChpr_v2", "hipblasChpr_v2"), + ("cublasZhpr_v2", "hipblasZhpr_v2"), + ("cublasSsyr2_v2", "hipblasSsyr2_v2"), + ("cublasDsyr2_v2", "hipblasDsyr2_v2"), + ("cublasCsyr2_v2", "hipblasCsyr2_v2"), + ("cublasZsyr2_v2", "hipblasZsyr2_v2"), + ("cublasCher2_v2", "hipblasCher2_v2"), + ("cublasZher2_v2", "hipblasZher2_v2"), + ("cublasSspr2_v2", "hipblasSspr2_v2"), + ("cublasDspr2_v2", "hipblasDspr2_v2"), + ("cublasChpr2_v2", "hipblasChpr2_v2"), + ("cublasZhpr2_v2", "hipblasZhpr2_v2"), + ("cublasSgemm_v2", "hipblasSgemm_v2"), + ("cublasDgemm_v2", "hipblasDgemm_v2"), + ("cublasCgemm_v2", "hipblasCgemm_v2"), + ("cublasCgemm3m", "hipblasCgemm3m"), + ("cublasCgemm3mEx", "hipblasCgemm3mEx"), + ("cublasZgemm_v2", "hipblasZgemm_v2"), + ("cublasZgemm3m", "hipblasZgemm3m"), + ("cublasSgemmEx", "hipblasSgemmEx"), + ("cublasGemmEx", "hipblasGemmEx"), + ("cublasGemmBatchedEx", "hipblasGemmBatchedEx"), + ("cublasGemmStridedBatchedEx", "hipblasGemmStridedBatchedEx"), + ("cublasCgemmEx", "hipblasCgemmEx"), + ("cublasUint8gemmBias", "hipblasUint8gemmBias"), + ("cublasSsyrk_v2", "hipblasSsyrk_v2"), + ("cublasDsyrk_v2", "hipblasDsyrk_v2"), + ("cublasCsyrk_v2", "hipblasCsyrk_v2"), + ("cublasZsyrk_v2", "hipblasZsyrk_v2"), + ("cublasCsyrkEx", "hipblasCsyrkEx"), + ("cublasCsyrk3mEx", "hipblasCsyrk3mEx"), + ("cublasCherk_v2", "hipblasCherk_v2"), + ("cublasCherkEx", "hipblasCherkEx"), + ("cublasCherk3mEx", "hipblasCherk3mEx"), + ("cublasZherk_v2", "hipblasZherk_v2"), + ("cublasSsyr2k_v2", "hipblasSsyr2k_v2"), + ("cublasDsyr2k_v2", "hipblasDsyr2k_v2"), + ("cublasCsyr2k_v2", "hipblasCsyr2k_v2"), + ("cublasZsyr2k_v2", "hipblasZsyr2k_v2"), + ("cublasCher2k_v2", "hipblasCher2k_v2"), + ("cublasZher2k_v2", "hipblasZher2k_v2"), + ("cublasSsymm_v2", "hipblasSsymm_v2"), + ("cublasDsymm_v2", "hipblasDsymm_v2"), + ("cublasCsymm_v2", "hipblasCsymm_v2"), + ("cublasZsymm_v2", "hipblasZsymm_v2"), + ("cublasChemm_v2", "hipblasChemm_v2"), + ("cublasZhemm_v2", "hipblasZhemm_v2"), + ("cublasStrsm_v2", "hipblasStrsm_v2"), + ("cublasDtrsm_v2", "hipblasDtrsm_v2"), + ("cublasCtrsm_v2", "hipblasCtrsm_v2"), + ("cublasZtrsm_v2", "hipblasZtrsm_v2"), + ("cublasStrmm_v2", "hipblasStrmm_v2"), + ("cublasDtrmm_v2", "hipblasDtrmm_v2"), + ("cublasCtrmm_v2", "hipblasCtrmm_v2"), + ("cublasZtrmm_v2", "hipblasZtrmm_v2"), + ("cublasSnrm2_v2", "hipblasSnrm2_v2"), + ("cublasDnrm2_v2", "hipblasDnrm2_v2"), + ("cublasScnrm2_v2", "hipblasScnrm2_v2"), + ("cublasDznrm2_v2", "hipblasDznrm2_v2"), + ("cublasDotEx", "hipblasDotEx"), + ("cublasDotcEx", "hipblasDotcEx"), + ("cublasSdot_v2", "hipblasSdot_v2"), + ("cublasDdot_v2", "hipblasDdot_v2"), + ("cublasCdotu_v2", "hipblasCdotu_v2"), + ("cublasCdotc_v2", "hipblasCdotc_v2"), + ("cublasZdotu_v2", "hipblasZdotu_v2"), + ("cublasZdotc_v2", "hipblasZdotc_v2"), + ("cublasScalEx", "hipblasScalEx"), + ("cublasSscal_v2", "hipblasSscal_v2"), + ("cublasDscal_v2", "hipblasDscal_v2"), + ("cublasCscal_v2", "hipblasCscal_v2"), + ("cublasCsscal_v2", "hipblasCsscal_v2"), + ("cublasZscal_v2", "hipblasZcsal_v2"), + ("cublasZdscal_v2", "hipblasZdscal_v2"), + ("cublasAxpyEx", "hipblasAxpyEx"), + ("cublasSaxpy_v2", "hipblasSaxpy_v2"), + ("cublasDaxpy_v2", "hipblasDaxpy_v2"), + ("cublasCaxpy_v2", "hipblasCaxpy_v2"), + ("cublasZaxpy_v2", "hipblasZaxpy_v2"), + ("cublasScopy_v2", "hipblasScopy_v2"), + ("cublasDcopy_v2", "hipblasDcopy_v2"), + ("cublasCcopy_v2", "hipblasCcopy_v2"), + ("cublasZcopy_v2", "hipblasZcopy_v2"), + ("cublasSswap_v2", "hipblasSswap_v2"), + ("cublasDswap_v2", "hipblasDswap_v2"), + ("cublasCswap_v2", "hipblasCswap_v2"), + ("cublasZswap_v2", "hipblasZswap_v2"), + ("cublasIsamax_v2", "hipblasIsamax_v2"), + ("cublasIdamax_v2", "hipblasIdamax_v2"), + ("cublasIcamax_v2", "hipblasIcamax_v2"), + ("cublasIzamax_v2", "hipblasIzamax_v2"), + ("cublasIsamin_v2", "hipblasIsamin_v2"), + ("cublasIdamin_v2", "hipblasIdamin_v2"), + ("cublasIcamin_v2", "hipblasIcamin_v2"), + ("cublasIzamin_v2", "hipblasIzamin_v2"), + ("cublasSasum_v2", "hipblasSasum_v2"), + ("cublasDasum_v2", "hipblasDasum_v2"), + ("cublasScasum_v2", "hipblasScasum_v2"), + ("cublasDzasum_v2", "hipblasDzasum_v2"), + ("cublasSrot_v2", "hipblasSrot_v2"), + ("cublasDrot_v2", "hipblasDrot_v2"), + ("cublasCrot_v2", "hipblasCrot_v2"), + ("cublasCsrot_v2", "hipblasCsrot_v2"), + ("cublasZrot_v2", "hipblasZrot_v2"), + ("cublasZdrot_v2", "hipblasZdrot_v2"), + ("cublasSrotg_v2", "hipblasSrotg_v2"), + ("cublasDrotg_v2", "hipblasDrotg_v2"), + ("cublasCrotg_v2", "hipblasCrotg_v2"), + ("cublasZrotg_v2", "hipblasZrotg_v2"), + ("cublasSrotm_v2", "hipblasSrotm_v2"), + ("cublasDrotm_v2", "hipblasDrotm_v2"), + ("cublasSrotmg_v2", "hipblasSrotmg_v2"), + ("cublasDrotmg_v2", "hipblasDrotmg_v2"), + ("cublasComputeType_t", "hipblasComputeType_t"), + ("CUBLAS_COMPUTE_16F", "HIPBLAS_COMPUTE_16F"), + ("CUBLAS_COMPUTE_32I", "HIPBLAS_COMPUTE_32I"), + ("CUBLAS_COMPUTE_32F", "HIPBLAS_COMPUTE_32F"), + ("CUBLAS_COMPUTE_32F_FAST_TF32", "HIPBLAS_COMPUTE_32F_FAST_TF32"), + ("CUBLAS_COMPUTE_64F", "HIPBLAS_COMPUTE_64F"), + ("cublasMath_t", "hipblasMath_t"), + ("CUBLAS_DEFAULT_MATH", "HIPBLAS_DEFAULT_MATH"), + ("CUBLAS_TENSOR_OP_MATH", "HIPBLAS_TENSOR_OP_MATH"), + ("CUBLAS_PEDANTIC_MATH", "HIPBLAS_PEDANTIC_MATH"), + ("CUBLAS_TF32_TENSOR_OP_MATH", "HIPBLAS_TF32_TENSOR_OP_MATH"), + ( + "CUBLAS_MATH_DISALLOW_REDUCED_PRECISION_REDUCTION", + "HIPBLAS_MATH_DISALLOW_REDUCED_PRECISION_REDUCTION", + ), + ("cublasLtEpilogue_t", "hipblasLtEpilogue_t"), + ("CUBLASLT_EPILOGUE_DEFAULT", "HIPBLASLT_EPILOGUE_DEFAULT"), + ("CUBLASLT_EPILOGUE_RELU", "HIPBLASLT_EPILOGUE_RELU"), + ("CUBLASLT_EPILOGUE_BIAS", "HIPBLASLT_EPILOGUE_BIAS"), + ("CUBLASLT_EPILOGUE_RELU_BIAS", "HIPBLASLT_EPILOGUE_RELU_BIAS"), + ("CUBLASLT_EPILOGUE_GELU", "HIPBLASLT_EPILOGUE_GELU"), + ("CUBLASLT_EPILOGUE_GELU_BIAS", "HIPBLASLT_EPILOGUE_GELU_BIAS"), + ("cublasLtHandle_t", "hipblasLtHandle_t"), + ("cublasLtMatmulDesc_t", "hipblasLtMatmulDesc_t"), + ("cublasLtMatmulDescOpaque_t", "hipblasLtMatmulDescOpaque_t"), + ("cublasLtMatmulDescAttributes_t", "hipblasLtMatmulDescAttributes_t"), + ("CUBLASLT_MATMUL_DESC_TRANSA", "HIPBLASLT_MATMUL_DESC_TRANSA"), + ("CUBLASLT_MATMUL_DESC_TRANSB", "HIPBLASLT_MATMUL_DESC_TRANSB"), + ("CUBLASLT_MATMUL_DESC_EPILOGUE", "HIPBLASLT_MATMUL_DESC_EPILOGUE"), + ("CUBLASLT_MATMUL_DESC_BIAS_POINTER", "HIPBLASLT_MATMUL_DESC_BIAS_POINTER"), + ("CUBLASLT_MATMUL_DESC_A_SCALE_MODE", "HIPBLASLT_MATMUL_DESC_A_SCALE_MODE"), + ("CUBLASLT_MATMUL_DESC_B_SCALE_MODE", "HIPBLASLT_MATMUL_DESC_B_SCALE_MODE"), + ("CUBLASLT_MATMUL_DESC_A_SCALE_POINTER", "HIPBLASLT_MATMUL_DESC_A_SCALE_POINTER"), + ("CUBLASLT_MATMUL_DESC_B_SCALE_POINTER", "HIPBLASLT_MATMUL_DESC_B_SCALE_POINTER"), + ("CUBLASLT_MATMUL_DESC_D_SCALE_POINTER", "HIPBLASLT_MATMUL_DESC_D_SCALE_POINTER"), + ("CUBLASLT_MATMUL_DESC_AMAX_D_POINTER", "HIPBLASLT_MATMUL_DESC_AMAX_D_POINTER"), + ("CUBLASLT_MATMUL_DESC_BIAS_DATA_TYPE", "HIPBLASLT_MATMUL_DESC_BIAS_DATA_TYPE"), + ("CUBLASLT_MATMUL_DESC_POINTER_MODE", "HIPBLASLT_MATMUL_DESC_POINTER_MODE"), + ("CUBLASLT_MATMUL_MATRIX_SCALE_OUTER_VEC_32F", "HIPBLASLT_MATMUL_MATRIX_SCALE_OUTER_VEC_32F"), + ("CUBLASLT_MATMUL_MATRIX_SCALE_VEC32_UE8M0", "HIPBLASLT_MATMUL_MATRIX_SCALE_VEC32_UE8M0"), + ("CUBLASLT_MATMUL_MATRIX_SCALE_VEC16_UE4M3", "HIPBLASLT_MATMUL_MATRIX_SCALE_VEC16_UE4M3"), + ("CUBLASLT_POINTER_MODE_DEVICE", "HIPBLASLT_POINTER_MODE_DEVICE"), + ("CUBLASLT_POINTER_MODE_HOST", "HIPBLASLT_POINTER_MODE_HOST"), + ("cublasLtMatrixLayout_t", "hipblasLtMatrixLayout_t"), + ("cublasLtMatrixLayoutOpaque_t", "hipblasLtMatrixLayoutOpaque_t"), + ("cublasLtMatrixLayoutAttribute_t", "hipblasLtMatrixLayoutAttribute_t"), + ("cublasLtMatrixLayoutCreate", "hipblasLtMatrixLayoutCreate"), + ("cublasLtMatrixLayoutDestroy", "hipblasLtMatrixLayoutDestroy"), + ("cublasLtMatrixLayoutSetAttribute", "hipblasLtMatrixLayoutSetAttribute"), + ("CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT", "HIPBLASLT_MATRIX_LAYOUT_BATCH_COUNT"), + ("CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET", "HIPBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET"), + ("cublasLtMatmulPreference_t", "hipblasLtMatmulPreference_t"), + ("cublasLtMatmulPreferenceOpaque_t", "hipblasLtMatmulPreferenceOpaque_t"), + ("cublasLtMatmulPreferenceAttributes_t", "hipblasLtMatmulPreferenceAttributes_t"), + ("CUBLASLT_MATMUL_PREF_SEARCH_MODE", "HIPBLASLT_MATMUL_PREF_SEARCH_MODE"), + ("CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES", "HIPBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES"), + ("cublasLtMatmulAlgo_t", "hipblasLtMatmulAlgo_t"), + ("cublasLtMatmulHeuristicResult_t", "hipblasLtMatmulHeuristicResult_t"), + ("cublasLtCreate", "hipblasLtCreate"), + ("cublasLtDestroy", "hipblasLtDestroy"), + ("cublasLtMatmulDescCreate", "hipblasLtMatmulDescCreate"), + ("cublasLtMatmulDescDestroy", "hipblasLtMatmulDescDestroy"), + ("cublasLtMatmulDescSetAttribute", "hipblasLtMatmulDescSetAttribute"), + ("cublasLtMatmulPreferenceCreate", "hipblasLtMatmulPreferenceCreate"), + ("cublasLtMatmulPreferenceDestroy", "hipblasLtMatmulPreferenceDestroy"), + ("cublasLtMatmulPreferenceSetAttribute", "hipblasLtMatmulPreferenceSetAttribute"), + ("cublasLtMatmulAlgoGetHeuristic", "hipblasLtMatmulAlgoGetHeuristic"), + ("cublasLtMatmul", "hipblasLtMatmul"), + ("CURAND_STATUS_SUCCESS", "HIPRAND_STATUS_SUCCESS"), + ("CURAND_STATUS_VERSION_MISMATCH", "HIPRAND_STATUS_VERSION_MISMATCH"), + ("CURAND_STATUS_NOT_INITIALIZED", "HIPRAND_STATUS_NOT_INITIALIZED"), + ("CURAND_STATUS_ALLOCATION_FAILED", "HIPRAND_STATUS_ALLOCATION_FAILED"), + ("CURAND_STATUS_TYPE_ERROR", "HIPRAND_STATUS_TYPE_ERROR"), + ("CURAND_STATUS_OUT_OF_RANGE", "HIPRAND_STATUS_OUT_OF_RANGE"), + ("CURAND_STATUS_LENGTH_NOT_MULTIPLE", "HIPRAND_STATUS_LENGTH_NOT_MULTIPLE"), + ("CURAND_STATUS_DOUBLE_PRECISION_REQUIRED", "HIPRAND_STATUS_DOUBLE_PRECISION_REQUIRED"), + ("CURAND_STATUS_LAUNCH_FAILURE", "HIPRAND_STATUS_LAUNCH_FAILURE"), + ("CURAND_STATUS_PREEXISTING_FAILURE", "HIPRAND_STATUS_PREEXISTING_FAILURE"), + ("CURAND_STATUS_INITIALIZATION_FAILED", "HIPRAND_STATUS_INITIALIZATION_FAILED"), + ("CURAND_STATUS_ARCH_MISMATCH", "HIPRAND_STATUS_ARCH_MISMATCH"), + ("CURAND_STATUS_INTERNAL_ERROR", "HIPRAND_STATUS_INTERNAL_ERROR"), + ("CURAND_RNG_TEST", "HIPRAND_RNG_TEST"), + ("mtgp32dc_params_fast_11213", "mtgp32dc_params_fast_11213"), + ("CURAND_RNG_PSEUDO_DEFAULT", "HIPRAND_RNG_PSEUDO_DEFAULT"), + ("CURAND_RNG_PSEUDO_XORWOW", "HIPRAND_RNG_PSEUDO_XORWOW"), + ("CURAND_RNG_PSEUDO_MRG32K3A", "HIPRAND_RNG_PSEUDO_MRG32K3A"), + ("CURAND_RNG_PSEUDO_MTGP32", "HIPRAND_RNG_PSEUDO_MTGP32"), + ("CURAND_RNG_PSEUDO_MT19937", "HIPRAND_RNG_PSEUDO_MT19937"), + ("CURAND_RNG_PSEUDO_PHILOX4_32_10", "HIPRAND_RNG_PSEUDO_PHILOX4_32_10"), + ("CURAND_RNG_QUASI_DEFAULT", "HIPRAND_RNG_QUASI_DEFAULT"), + ("CURAND_RNG_QUASI_SOBOL32", "HIPRAND_RNG_QUASI_SOBOL32"), + ("CURAND_RNG_QUASI_SCRAMBLED_SOBOL32", "HIPRAND_RNG_QUASI_SCRAMBLED_SOBOL32"), + ("CURAND_RNG_QUASI_SOBOL64", "HIPRAND_RNG_QUASI_SOBOL64"), + ("CURAND_RNG_QUASI_SCRAMBLED_SOBOL64", "HIPRAND_RNG_QUASI_SCRAMBLED_SOBOL64"), + ("curand_ORDERING_PSEUDO_BEST", "HIPRAND_ORDERING_PSEUDO_BEST"), + ("curand_ORDERING_PSEUDO_DEFAULT", "HIPRAND_ORDERING_PSEUDO_DEFAULT"), + ("curand_ORDERING_PSEUDO_SEEDED", "HIPRAND_ORDERING_PSEUDO_SEEDED"), + ("curand_ORDERING_QUASI_DEFAULT", "HIPRAND_ORDERING_QUASI_DEFAULT"), + ("curand_DIRECTION_VECTORS_32_JOEKUO6", "HIPRAND_DIRECTION_VECTORS_32_JOEKUO6"), + ("curand_SCRAMBLED_DIRECTION_VECTORS_32_JOEKUO6", "HIPRAND_SCRAMBLED_DIRECTION_VECTORS_32_JOEKUO6"), + ("curand_DIRECTION_VECTORS_64_JOEKUO6", "HIPRAND_DIRECTION_VECTORS_64_JOEKUO6"), + ("curand_SCRAMBLED_DIRECTION_VECTORS_64_JOEKUO6", "HIPRAND_SCRAMBLED_DIRECTION_VECTORS_64_JOEKUO6"), + ("curand_CHOOSE_BEST", "HIPRAND_CHOOSE_BEST"), + ("curand_ITR", "HIPRAND_ITR"), + ("curand_KNUTH", "HIPRAND_KNUTH"), + ("curand_HITR", "HIPRAND_HITR"), + ("curand_M1", "HIPRAND_M1"), + ("curand_M2", "HIPRAND_M2"), + ("curand_BINARY_SEARCH", "HIPRAND_BINARY_SEARCH"), + ("curand_DISCRETE_GAUSS", "HIPRAND_DISCRETE_GAUSS"), + ("curand_REJECTION", "HIPRAND_REJECTION"), + ("curand_DEVICE_API", "HIPRAND_DEVICE_API"), + ("curand_FAST_REJECTION", "HIPRAND_FAST_REJECTION"), + ("curand_3RD", "HIPRAND_3RD"), + ("curand_DEFINITION", "HIPRAND_DEFINITION"), + ("curand_POISSON", "HIPRAND_POISSON"), + ("curandCreateGenerator", "hiprandCreateGenerator"), + ("curandCreateGeneratorHost", "hiprandCreateGeneratorHost"), + ("curandCreatePoissonDistribution", "hiprandCreatePoissonDistribution"), + ("curandDestroyDistribution", "hiprandDestroyDistribution"), + ("curandDestroyGenerator", "hiprandDestroyGenerator"), + ("curandGenerate", "hiprandGenerate"), + ("curandGenerateLogNormal", "hiprandGenerateLogNormal"), + ("curandGenerateLogNormalDouble", "hiprandGenerateLogNormalDouble"), + ("curandGenerateLongLong", "hiprandGenerateLongLong"), + ("curandGenerateNormal", "hiprandGenerateNormal"), + ("curandGenerateNormalDouble", "hiprandGenerateNormalDouble"), + ("curandGeneratePoisson", "hiprandGeneratePoisson"), + ("curandGenerateSeeds", "hiprandGenerateSeeds"), + ("curandGenerateUniform", "hiprandGenerateUniform"), + ("curandGenerateUniformDouble", "hiprandGenerateUniformDouble"), + ("curandGetDirectionVectors32", "hiprandGetDirectionVectors32"), + ("curandGetDirectionVectors64", "hiprandGetDirectionVectors64"), + ("curandGetProperty", "hiprandGetProperty"), + ("curandGetScrambleConstants32", "hiprandGetScrambleConstants32"), + ("curandGetScrambleConstants64", "hiprandGetScrambleConstants64"), + ("curandGetVersion", "hiprandGetVersion"), + ("curandSetGeneratorOffset", "hiprandSetGeneratorOffset"), + ("curandSetGeneratorOrdering", "hiprandSetGeneratorOrdering"), + ("curandSetPseudoRandomGeneratorSeed", "hiprandSetPseudoRandomGeneratorSeed"), + ("curandSetQuasiRandomGeneratorDimensions", "hiprandSetQuasiRandomGeneratorDimensions"), + ("curandSetStream", "hiprandSetStream"), + ("curand", "hiprand"), + ("curand4", "hiprand4"), + ("curand_init", "hiprand_init"), + ("curand_log_normal", "hiprand_log_normal"), + ("curand_log_normal_double", "hiprand_log_normal_double"), + ("curand_log_normal2", "hiprand_log_normal2"), + ("curand_log_normal2_double", "hiprand_log_normal2_double"), + ("curand_log_normal4", "hiprand_log_normal4"), + ("curand_log_normal4_double", "hiprand_log_normal4_double"), + ("curand_mtgp32_single", "hiprand_mtgp32_single"), + ("curand_mtgp32_single_specific", "hiprand_mtgp32_single_specific"), + ("curand_mtgp32_specific", "hiprand_mtgp32_specific"), + ("curand_normal", "hiprand_normal"), + ("curandMakeMTGP32Constants", "hiprandMakeMTGP32Constants"), + ("curandMakeMTGP32KernelState", "hiprandMakeMTGP32KernelState"), + ("curand_normal_double", "hiprand_normal_double"), + ("curand_normal2", "hiprand_normal2"), + ("curand_normal2_double", "hiprand_normal2_double"), + ("curand_normal4", "hiprand_normal4"), + ("curand_normal4_double", "hiprand_normal4_double"), + ("curand_uniform", "hiprand_uniform"), + ("curand_uniform_double", "hiprand_uniform_double"), + ("curand_uniform2_double", "hiprand_uniform2_double"), + ("curand_uniform4", "hiprand_uniform4"), + ("curand_uniform4_double", "hiprand_uniform4_double"), + ("curand_discrete", "hiprand_discrete"), + ("curand_discrete4", "hiprand_discrete4"), + ("curand_poisson", "hiprand_poisson"), + ("curand_poisson4", "hiprand_poisson4"), + ("curand_Philox4x32_10", "hiprand_Philox4x32_10"), + ("mtgp32_kernel_params", "mtgp32_kernel_params_t"), + ("CUFFT_FORWARD", "HIPFFT_FORWARD"), + ("CUFFT_INVERSE", "HIPFFT_BACKWARD"), + ("CUFFT_COMPATIBILITY_DEFAULT", "HIPFFT_COMPATIBILITY_DEFAULT"), + ("cuComplex", "hipComplex"), + ("cuDoubleComplex", "hipDoubleComplex"), + ("cufftResult_t", "hipfftResult_t"), + ("cufftResult", "hipfftResult"), + ("CUFFT_SUCCESS", "HIPFFT_SUCCESS"), + ("CUFFT_INVALID_PLAN", "HIPFFT_INVALID_PLAN"), + ("CUFFT_ALLOC_FAILED", "HIPFFT_ALLOC_FAILED"), + ("CUFFT_INVALID_TYPE", "HIPFFT_INVALID_TYPE"), + ("CUFFT_INVALID_VALUE", "HIPFFT_INVALID_VALUE"), + ("CUFFT_INTERNAL_ERROR", "HIPFFT_INTERNAL_ERROR"), + ("CUFFT_EXEC_FAILED", "HIPFFT_EXEC_FAILED"), + ("CUFFT_SETUP_FAILED", "HIPFFT_SETUP_FAILED"), + ("CUFFT_INVALID_SIZE", "HIPFFT_INVALID_SIZE"), + ("CUFFT_UNALIGNED_DATA", "HIPFFT_UNALIGNED_DATA"), + ("CUFFT_INCOMPLETE_PARAMETER_LIST", "HIPFFT_INCOMPLETE_PARAMETER_LIST"), + ("CUFFT_INVALID_DEVICE", "HIPFFT_INVALID_DEVICE"), + ("CUFFT_PARSE_ERROR", "HIPFFT_PARSE_ERROR"), + ("CUFFT_NO_WORKSPACE", "HIPFFT_NO_WORKSPACE"), + ("CUFFT_NOT_IMPLEMENTED", "HIPFFT_NOT_IMPLEMENTED"), + ("CUFFT_LICENSE_ERROR", "HIPFFT_LICENSE_ERROR"), + ("CUFFT_NOT_SUPPORTED", "HIPFFT_NOT_SUPPORTED"), + ("cufftType_t", "hipfftType_t"), + ("cufftType", "hipfftType"), + ("CUFFT_R2C", "HIPFFT_R2C"), + ("CUFFT_C2R", "HIPFFT_C2R"), + ("CUFFT_C2C", "HIPFFT_C2C"), + ("CUFFT_D2Z", "HIPFFT_D2Z"), + ("CUFFT_Z2D", "HIPFFT_Z2D"), + ("CUFFT_Z2Z", "HIPFFT_Z2Z"), + ("cufftCompatibility_t", "hipfftCompatibility_t"), + ("cufftCompatibility", "hipfftCompatibility"), + ("CUFFT_COMPATIBILITY_FFTW_PADDING", "HIPFFT_COMPATIBILITY_FFTW_PADDING"), + ("cufftReal", "hipfftReal"), + ("cufftDoubleReal", "hipfftDoubleReal"), + ("cufftComplex", "hipfftComplex"), + ("cufftDoubleComplex", "hipfftDoubleComplex"), + ("cufftHandle", "hipfftHandle"), + ("cufftPlan1d", "hipfftPlan1d"), + ("cufftPlan2d", "hipfftPlan2d"), + ("cufftPlan3d", "hipfftPlan3d"), + ("cufftPlanMany", "hipfftPlanMany"), + ("cufftMakePlan1d", "hipfftMakePlan1d"), + ("cufftMakePlan2d", "hipfftMakePlan2d"), + ("cufftMakePlan3d", "hipfftMakePlan3d"), + ("cufftMakePlanMany", "hipfftMakePlanMany"), + ("cufftMakePlanMany64", "hipfftMakePlanMany64"), + ("cufftGetSizeMany64", "hipfftGetSizeMany64"), + ("cufftEstimate1d", "hipfftEstimate1d"), + ("cufftEstimate2d", "hipfftEstimate2d"), + ("cufftEstimate3d", "hipfftEstimate3d"), + ("cufftEstimateMany", "hipfftEstimateMany"), + ("cufftCreate", "hipfftCreate"), + ("cufftGetSize1d", "hipfftGetSize1d"), + ("cufftGetSize2d", "hipfftGetSize2d"), + ("cufftGetSize3d", "hipfftGetSize3d"), + ("cufftGetSizeMany", "hipfftGetSizeMany"), + ("cufftGetSize", "hipfftGetSize"), + ("cufftSetWorkArea", "hipfftSetWorkArea"), + ("cufftSetAutoAllocation", "hipfftSetAutoAllocation"), + ("cufftXtExec", "hipfftXtExec"), + ("cufftXtMakePlanMany", "hipfftXtMakePlanMany"), + ("cufftExecC2C", "hipfftExecC2C"), + ("cufftExecR2C", "hipfftExecR2C"), + ("cufftExecC2R", "hipfftExecC2R"), + ("cufftExecZ2Z", "hipfftExecZ2Z"), + ("cufftExecD2Z", "hipfftExecD2Z"), + ("cufftExecZ2D", "hipfftExecZ2D"), + ("cufftSetStream", "hipfftSetStream"), + ("cufftDestroy", "hipfftDestroy"), + ("cufftGetVersion", "hipfftGetVersion"), + ("cufftGetProperty", "hipfftGetProperty"), + ("nvrtcResult", "hiprtcResult"), + ("NVRTC_SUCCESS", "HIPRTC_SUCCESS"), + ("NVRTC_ERROR_OUT_OF_MEMORY", "HIPRTC_ERROR_OUT_OF_MEMORY"), + ("NVRTC_ERROR_PROGRAM_CREATION_FAILURE", "HIPRTC_ERROR_PROGRAM_CREATION_FAILURE"), + ("NVRTC_ERROR_INVALID_INPUT", "HIPRTC_ERROR_INVALID_INPUT"), + ("NVRTC_ERROR_INVALID_PROGRAM", "HIPRTC_ERROR_INVALID_PROGRAM"), + ("NVRTC_ERROR_COMPILATION", "HIPRTC_ERROR_COMPILATION"), + ("NVRTC_ERROR_BUILTIN_OPERATION_FAILURE", "HIPRTC_ERROR_BUILTIN_OPERATION_FAILURE"), + ("NVRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION", "HIPRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION"), + ("NVRTC_ERROR_NAME_EXPRESSION_NOT_VALID", "HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID"), + ("NVRTC_ERROR_INTERNAL_ERROR", "HIPRTC_ERROR_INTERNAL_ERROR"), + ("nvrtcGetErrorString", "hiprtcGetErrorString"), + ("nvrtcVersion", "hiprtcVersion"), + ("nvrtcProgram", "hiprtcProgram"), + ("nvrtcAddNameExpression", "hiprtcAddNameExpression"), + ("nvrtcCompileProgram", "hiprtcCompileProgram"), + ("nvrtcCreateProgram", "hiprtcCreateProgram"), + ("nvrtcDestroyProgram", "hiprtcDestroyProgram"), + ("nvrtcGetLoweredName", "hiprtcGetLoweredName"), + ("nvrtcGetProgramLog", "hiprtcGetProgramLog"), + ("nvrtcGetProgramLogSize", "hiprtcGetProgramLogSize"), + ("nvrtcGetPTX", "hiprtcGetCode"), + ("nvrtcGetPTXSize", "hiprtcGetCodeSize"), + ("nvrtcGetCUBIN", "hiprtcGetBitcode"), + ("nvrtcGetCUBINSize", "hiprtcGetBitcodeSize"), + ("thrust::cuda", "thrust::hip"), + ("cub::", "hipcub::"), + ("cub::ArgMax", "hipcub::ArgMax"), + ("cub::ArgMin", "hipcub::ArgMin"), + ("cub::BLOCK_SCAN_WARP_SCANS", "hipcub::BLOCK_SCAN_WARP_SCANS"), + ("cub::BLOCK_REDUCE_WARP_REDUCTIONS", "hipcub::BLOCK_REDUCE_WARP_REDUCTIONS"), + ("cub::BLOCK_STORE_WARP_TRANSPOSE", "hipcub::BLOCK_STORE_WARP_TRANSPOSE"), + ("cub::BLOCK_LOAD_DIRECT", "hipcub::BLOCK_LOAD_DIRECT"), + ("cub::BLOCK_STORE_DIRECT", "hipcub::BLOCK_STORE_DIRECT"), + ("cub::BLOCK_REDUCE_RAKING_COMMUTATIVE_ONLY", "hipcub::BLOCK_REDUCE_RAKING_COMMUTATIVE_ONLY"), + ("cub::BlockReduce", "hipcub::BlockReduce"), + ("cub::BlockScan", "hipcub::BlockScan"), + ("cub::BlockLoad", "hipcub::BlockLoad"), + ("cub::BlockStore", "hipcub::BlockStore"), + ("cub::BlockRakingLayout", "hipcub::BlockRakingLayout"), + ("cub::BlockRadixSort", "hipcub::BlockRadixSort"), + ("cub::Uninitialized", "hipcub::Uninitialized"), + ("cub::RowMajorTid", "hipcub::RowMajorTid"), + ("cub::CachingDeviceAllocator", "hipcub::CachingDeviceAllocator"), + ("cub::CountingInputIterator", "hipcub::CountingInputIterator"), + ("cub::DeviceHistogram", "hipcub::DeviceHistogram"), + ("cub::DeviceRadixSort", "hipcub::DeviceRadixSort"), + ("cub::DeviceReduce", "hipcub::DeviceReduce"), + ("cub::DeviceRunLengthEncode", "hipcub::DeviceRunLengthEncode"), + ("cub::DeviceScan", "hipcub::DeviceScan"), + ("cub::DeviceSegmentedRadixSort", "hipcub::DeviceSegmentedRadixSort"), + ("cub::DeviceSegmentedReduce", "hipcub::DeviceSegmentedReduce"), + ("cub::DeviceSelect", "hipcub::DeviceSelect"), + ("cub::FpLimits", "hipcub::FpLimits"), + ("cub::KeyValuePair", "hipcub::KeyValuePair"), + ("cub::Max", "hipcub::Max"), + ("cub::Min", "hipcub::Min"), + ("cub::Sum", "hipcub::Sum"), + ("cub::Log2", "hipcub::Log2"), + ("cub::LaneId", "hipcub::LaneId"), + ("cub::WarpMask", "hipcub::WarpMask"), + ("cub::ShuffleIndex", "hipcub::ShuffleIndex"), + ("cub::ShuffleDown", "hipcub::ShuffleDown"), + ("cub::ArgIndexInputIterator", "hipcub::ArgIndexInputIterator"), + ("cub::TransformInputIterator", "hipcub::TransformInputIterator"), + ("cub::WarpReduce", "hipcub::WarpReduce"), + ("cub::CTA_SYNC", "hipcub::CTA_SYNC"), + ("nvtxMark", "roctxMark"), + ("nvtxMarkA", "roctxMarkA"), + ("nvtxRangePushA", "roctxRangePushA"), + ("nvtxRangePush", "roctxRangePush"), + ("nvtxRangePop", "roctxRangePop"), + ("nvtxRangeStartA", "roctxRangeStartA"), + ("nvtxRangeStart", "roctxRangeStart"), + ("nvtxRangeEnd", "roctxRangeStop"), + ("nvtxRangeId_t", "int"), + ("nvmlReturn_t", "amdsmi_status_t"), + ("NVML_SUCCESS", "AMDSMI_STATUS_SUCCESS"), + ("NVML_P2P_CAPS_INDEX_READ", "AMDSMI_STATUS_SUCCESS"), + ("NVML_P2P_STATUS_OK", "AMDSMI_STATUS_SUCCESS"), + ("NVML_ERROR_INSUFFICIENT_SIZE", "AMDSMI_STATUS_INSUFFICIENT_SIZE"), + ("nvmlDevice_t", "amdsmi_processor_handle"), + ("nvmlGpuP2PStatus_t", "bool"), + ("nvmlProcessInfo_t", "amdsmi_proc_info_t"), + ("nvmlGpuP2PCapsIndex_t", "uint32_t"), + ("cuFileRead", "hipFileRead"), + ("cuFileWrite", "hipFileWrite"), + ("cuFileBufRegister", "hipFileBufRegister"), + ("cuFileBufDeregister", "hipFileBufDeregister"), + ("cuFileHandleRegister", "hipFileHandleRegister"), + ("cuFileHandleDeregister", "hipFileHandleDeregister"), + ("CU_FILE_HANDLE_TYPE_OPAQUE_FD", "hipFileHandleTypeOpaqueFD"), + ("CU_FILE_SUCCESS", "hipFileSuccess"), + ("IS_CUFILE_ERR", "IS_HIPFILE_ERR"), + ("CUFILE_ERRSTR", "HIPFILE_ERRSTR"), + ("IS_CUDA_ERR", "IS_HIP_DRV_ERR"), + ("cu_err", "hip_drv_err"), +]) + +CUDA_SPECIAL_MAP = collections.OrderedDict([ + ("cusparseStatus_t", "hipsparseStatus_t"), + ("cusparseHandle_t", "hipsparseHandle_t"), + ("cuComplex", "hipComplex"), + ("cuDoubleComplex", "hipDoubleComplex"), + ("CUSPARSE_POINTER_MODE_HOST", "HIPSPARSE_POINTER_MODE_HOST"), + ("cusparseOperation_t", "hipsparseOperation_t"), + ("cusparseCreateMatDescr", "hipsparseCreateMatDescr"), + ("cusparseCreate", "hipsparseCreate"), + ("cusparseDestroyMatDescr", "hipsparseDestroyMatDescr"), + ("cusparseDestroy", "hipsparseDestroy"), + ("cusparseGetVersion", "hipsparseGetVersion"), + ("cusparseXcoo2csr", "hipsparseXcoo2csr"), + ("cusparseMatDescr_t", "hipsparseMatDescr_t"), + ("cusparseDiagType_t", "hipsparseDiagType_t"), + ("CUSPARSE_DIAG_TYPE_UNIT", "HIPSPARSE_DIAG_TYPE_UNIT"), + ("CUSPARSE_DIAG_TYPE_NON_UNIT", "HIPSPARSE_DIAG_TYPE_NON_UNIT"), + ("cusparseSetMatDiagType", "hipsparseSetMatDiagType"), + ("cusparseFillMode_t", "hipsparseFillMode_t"), + ("CUSPARSE_FILL_MODE_UPPER", "HIPSPARSE_FILL_MODE_UPPER"), + ("CUSPARSE_FILL_MODE_LOWER", "HIPSPARSE_FILL_MODE_LOWER"), + ("cusparseSetMatFillMode", "hipsparseSetMatFillMode"), + ("cusparseDirection_t", "hipsparseDirection_t"), + ("CUSPARSE_DIRECTION_ROW", "HIPSPARSE_DIRECTION_ROW"), + ("CUSPARSE_DIRECTION_COLUMN", "HIPSPARSE_DIRECTION_COLUMN"), + ("cusparseSolvePolicy_t", "hipsparseSolvePolicy_t"), + ("CUSPARSE_SOLVE_POLICY_NO_LEVEL", "HIPSPARSE_SOLVE_POLICY_NO_LEVEL"), + ("CUSPARSE_SOLVE_POLICY_USE_LEVEL", "HIPSPARSE_SOLVE_POLICY_USE_LEVEL"), + ("cusparseCreateBsrsv2Info", "hipsparseCreateBsrsv2Info"), + ("cusparseCreateBsrsm2Info", "hipsparseCreateBsrsm2Info"), + ("cusparseDestroyBsrsv2Info", "hipsparseDestroyBsrsv2Info"), + ("cusparseDestroyBsrsm2Info", "hipsparseDestroyBsrsm2Info"), + ("cusparseSbsrmm", "hipsparseSbsrmm"), + ("cusparseDbsrmm", "hipsparseDbsrmm"), + ("cusparseCbsrmm", "hipsparseCbsrmm"), + ("cusparseZbsrmm", "hipsparseZbsrmm"), + ("cusparseSbsrmv", "hipsparseSbsrmv"), + ("cusparseDbsrmv", "hipsparseDbsrmv"), + ("cusparseCbsrmv", "hipsparseCbsrmv"), + ("cusparseZbsrmv", "hipsparseZbsrmv"), + ("cusparseSbsrsv2_bufferSize", "hipsparseSbsrsv2_bufferSize"), + ("cusparseDbsrsv2_bufferSize", "hipsparseDbsrsv2_bufferSize"), + ("cusparseCbsrsv2_bufferSize", "hipsparseCbsrsv2_bufferSize"), + ("cusparseZbsrsv2_bufferSize", "hipsparseZbsrsv2_bufferSize"), + ("cusparseSbsrsv2_analysis", "hipsparseSbsrsv2_analysis"), + ("cusparseDbsrsv2_analysis", "hipsparseDbsrsv2_analysis"), + ("cusparseCbsrsv2_analysis", "hipsparseCbsrsv2_analysis"), + ("cusparseZbsrsv2_analysis", "hipsparseZbsrsv2_analysis"), + ("cusparseSbsrsv2_solve", "hipsparseSbsrsv2_solve"), + ("cusparseDbsrsv2_solve", "hipsparseDbsrsv2_solve"), + ("cusparseCbsrsv2_solve", "hipsparseCbsrsv2_solve"), + ("cusparseZbsrsv2_solve", "hipsparseZbsrsv2_solve"), + ("cusparseSbsrsm2_bufferSize", "hipsparseSbsrsm2_bufferSize"), + ("cusparseDbsrsm2_bufferSize", "hipsparseDbsrsm2_bufferSize"), + ("cusparseCbsrsm2_bufferSize", "hipsparseCbsrsm2_bufferSize"), + ("cusparseZbsrsm2_bufferSize", "hipsparseZbsrsm2_bufferSize"), + ("cusparseSbsrsm2_analysis", "hipsparseSbsrsm2_analysis"), + ("cusparseDbsrsm2_analysis", "hipsparseDbsrsm2_analysis"), + ("cusparseCbsrsm2_analysis", "hipsparseCbsrsm2_analysis"), + ("cusparseZbsrsm2_analysis", "hipsparseZbsrsm2_analysis"), + ("cusparseSbsrsm2_solve", "hipsparseSbsrsm2_solve"), + ("cusparseDbsrsm2_solve", "hipsparseDbsrsm2_solve"), + ("cusparseCbsrsm2_solve", "hipsparseCbsrsm2_solve"), + ("cusparseZbsrsm2_solve", "hipsparseZbsrsm2_solve"), + ("cusparseScsrmm2", "hipsparseScsrmm2"), + ("cusparseDcsrmm2", "hipsparseDcsrmm2"), + ("cusparseCcsrmm2", "hipsparseCcsrmm2"), + ("cusparseZcsrmm2", "hipsparseZcsrmm2"), + ("cusparseScsrmm", "hipsparseScsrmm"), + ("cusparseDcsrmm", "hipsparseDcsrmm"), + ("cusparseCcsrmm", "hipsparseCcsrmm"), + ("cusparseZcsrmm", "hipsparseZcsrmm"), + ("cusparseXcsrsort_bufferSizeExt", "hipsparseXcsrsort_bufferSizeExt"), + ("cusparseCreateCsrgemm2Info", "hipsparseCreateCsrgemm2Info"), + ("cusparseDestroyCsrgemm2Info", "hipsparseDestroyCsrgemm2Info"), + ("cusparseXcsrgemm2Nnz", "hipsparseXcsrgemm2Nnz"), + ("cusparseDcsrgemm2_bufferSizeExt", "hipsparseDcsrgemm2_bufferSizeExt"), + ("cusparseScsrgemm2_bufferSizeExt", "hipsparseScsrgemm2_bufferSizeExt"), + ("cusparseDcsrgemm2", "hipsparseDcsrgemm2"), + ("cusparseScsrgemm2", "hipsparseScsrgemm2"), + ("cusparseScsrgemm", "hipsparseScsrgemm"), + ("cusparseDcsrgemm", "hipsparseDcsrgemm"), + ("cusparseCcsrgemm", "hipsparseCcsrgemm"), + ("cusparseZcsrgemm", "hipsparseZcsrgemm"), + ("cusparseSetPointerMode", "hipsparseSetPointerMode"), + ("cusparseXcsrgeam2Nnz", "hipsparseXcsrgeam2Nnz"), + ("cusparseScsrgeam", "hipsparseScsrgeam"), + ("cusparseDcsrgeam", "hipsparseDcsrgeam"), + ("cusparseCcsrgeam", "hipsparseCcsrgeam"), + ("cusparseZcsrgeam", "hipsparseZcsrgeam"), + ("cusparseScsrgeam2_bufferSizeExt", "hipsparseScsrgeam2_bufferSizeExt"), + ("cusparseDcsrgeam2_bufferSizeExt", "hipsparseDcsrgeam2_bufferSizeExt"), + ("cusparseCcsrgeam2_bufferSizeExt", "hipsparseCcsrgeam2_bufferSizeExt"), + ("cusparseZcsrgeam2_bufferSizeExt", "hipsparseZcsrgeam2_bufferSizeExt"), + ("cusparseScsrgeam2", "hipsparseScsrgeam2"), + ("cusparseDcsrgeam2", "hipsparseDcsrgeam2"), + ("cusparseCcsrgeam2", "hipsparseCcsrgeam2"), + ("cusparseZcsrgeam2", "hipsparseZcsrgeam2"), + ("cusparseXcsrsort", "hipsparseXcsrsort"), + ("cusparseXbsrsm2_zeroPivot", "hipsparseXbsrsm2_zeroPivot"), + ("cusparseXbsrsv2_zeroPivot", "hipsparseXbsrsv2_zeroPivot"), + ("cusparseXcoosort_bufferSizeExt", "hipsparseXcoosort_bufferSizeExt"), + ("cusparseXcoosortByRow", "hipsparseXcoosortByRow"), + ("cusparseSetStream", "hipsparseSetStream"), + ("cusparseGetStream", "hipsparseGetStream"), + ("cusparseCreateIdentityPermutation", "hipsparseCreateIdentityPermutation"), + ("cusparseSetMatIndexBase", "hipsparseSetMatIndexBase"), + ("cusparseSetMatType", "hipsparseSetMatType"), + ("cusparseSgthr", "hipsparseSgthr"), + ("cusparseDgthr", "hipsparseDgthr"), + ("cusparseCgthr", "hipsparseCgthr"), + ("cusparseZgthr", "hipsparseZgthr"), + ("cusparseScsrmv", "hipsparseScsrmv"), + ("cusparseDcsrmv", "hipsparseDcsrmv"), + ("cusparseCcsrmv", "hipsparseCcsrmv"), + ("cusparseZcsrmv", "hipsparseZcsrmv"), + ("cusparseSpMV", "hipsparseSpMV"), + ("cusparseSpMV_bufferSize", "hipsparseSpMV_bufferSize"), + ("cusparseSpMM", "hipsparseSpMM"), + ("cusparseSpMM_bufferSize", "hipsparseSpMM_bufferSize"), + ("cusparseCreateCsrsv2Info", "hipsparseCreateCsrsv2Info"), + ("cusparseDestroyCsrsv2Info", "hipsparseDestroyCsrsv2Info"), + ("cusparseScsrsv2_bufferSize", "hipsparseScsrsv2_bufferSize"), + ("cusparseDcsrsv2_bufferSize", "hipsparseDcsrsv2_bufferSize"), + ("cusparseCcsrsv2_bufferSize", "hipsparseCcsrsv2_bufferSize"), + ("cusparseZcsrsv2_bufferSize", "hipsparseZcsrsv2_bufferSize"), + ("cusparseScsrsv2_analysis", "hipsparseScsrsv2_analysis"), + ("cusparseDcsrsv2_analysis", "hipsparseDcsrsv2_analysis"), + ("cusparseCcsrsv2_analysis", "hipsparseCcsrsv2_analysis"), + ("cusparseZcsrsv2_analysis", "hipsparseZcsrsv2_analysis"), + ("cusparseScsrsv2_solve", "hipsparseScsrsv2_solve"), + ("cusparseDcsrsv2_solve", "hipsparseDcsrsv2_solve"), + ("cusparseCcsrsv2_solve", "hipsparseCcsrsv2_solve"), + ("cusparseZcsrsv2_solve", "hipsparseZcsrsv2_solve"), + ("cusparseXcsrsv2_zeroPivot", "hipsparseXcsrsv2_zeroPivot"), + ("cusparseCreateCsrsm2Info", "hipsparseCreateCsrsm2Info"), + ("cusparseDestroyCsrsm2Info", "hipsparseDestroyCsrsm2Info"), + ("cusparseScsrsm2_bufferSizeExt", "hipsparseScsrsm2_bufferSizeExt"), + ("cusparseDcsrsm2_bufferSizeExt", "hipsparseDcsrsm2_bufferSizeExt"), + ("cusparseCcsrsm2_bufferSizeExt", "hipsparseCcsrsm2_bufferSizeExt"), + ("cusparseZcsrsm2_bufferSizeExt", "hipsparseZcsrsm2_bufferSizeExt"), + ("cusparseScsrsm2_analysis", "hipsparseScsrsm2_analysis"), + ("cusparseDcsrsm2_analysis", "hipsparseDcsrsm2_analysis"), + ("cusparseCcsrsm2_analysis", "hipsparseCcsrsm2_analysis"), + ("cusparseZcsrsm2_analysis", "hipsparseZcsrsm2_analysis"), + ("cusparseScsrsm2_solve", "hipsparseScsrsm2_solve"), + ("cusparseDcsrsm2_solve", "hipsparseDcsrsm2_solve"), + ("cusparseCcsrsm2_solve", "hipsparseCcsrsm2_solve"), + ("cusparseZcsrsm2_solve", "hipsparseZcsrsm2_solve"), + ("cusparseXcsrsm2_zeroPivot", "hipsparseXcsrsm2_zeroPivot"), + ("cusparseXcsrgeamNnz", "hipsparseXcsrgeamNnz"), + ("cusparseXcsrgemmNnz", "hipsparseXcsrgemmNnz"), + ("cusparseCcsrgemm2_bufferSizeExt", "hipsparseCcsrgemm2_bufferSizeExt"), + ("cusparseZcsrgemm2_bufferSizeExt", "hipsparseZcsrgemm2_bufferSizeExt"), + ("cusparseCcsrgemm2", "hipsparseCcsrgemm2"), + ("cusparseZcsrgemm2", "hipsparseZcsrgemm2"), + ("cusparseScsc2dense", "hipsparseScsc2dense"), + ("cusparseDcsc2dense", "hipsparseDcsc2dense"), + ("cusparseCcsc2dense", "hipsparseCcsc2dense"), + ("cusparseZcsc2dense", "hipsparseZcsc2dense"), + ("cusparseXcsr2coo", "hipsparseXcsr2coo"), + ("cusparseScsr2csc", "hipsparseScsr2csc"), + ("cusparseDcsr2csc", "hipsparseDcsr2csc"), + ("cusparseCcsr2csc", "hipsparseCcsr2csc"), + ("cusparseZcsr2csc", "hipsparseZcsr2csc"), + ("cusparseScsr2dense", "hipsparseScsr2dense"), + ("cusparseDcsr2dense", "hipsparseDcsr2dense"), + ("cusparseCcsr2dense", "hipsparseCcsr2dense"), + ("cusparseZcsr2dense", "hipsparseZcsr2dense"), + ("cusparseSnnz_compress", "hipsparseSnnz_compress"), + ("cusparseDnnz_compress", "hipsparseDnnz_compress"), + ("cusparseCnnz_compress", "hipsparseCnnz_compress"), + ("cusparseZnnz_compress", "hipsparseZnnz_compress"), + ("cusparseScsr2csr_compress", "hipsparseScsr2csr_compress"), + ("cusparseDcsr2csr_compress", "hipsparseDcsr2csr_compress"), + ("cusparseCcsr2csr_compress", "hipsparseCcsr2csr_compress"), + ("cusparseZcsr2csr_compress", "hipsparseZcsr2csr_compress"), + ("cusparseSdense2csc", "hipsparseSdense2csc"), + ("cusparseDdense2csc", "hipsparseDdense2csc"), + ("cusparseCdense2csc", "hipsparseCdense2csc"), + ("cusparseZdense2csc", "hipsparseZdense2csc"), + ("cusparseSdense2csr", "hipsparseSdense2csr"), + ("cusparseDdense2csr", "hipsparseDdense2csr"), + ("cusparseCdense2csr", "hipsparseCdense2csr"), + ("cusparseZdense2csr", "hipsparseZdense2csr"), + ("cusparseSnnz", "hipsparseSnnz"), + ("cusparseDnnz", "hipsparseDnnz"), + ("cusparseCnnz", "hipsparseCnnz"), + ("cusparseZnnz", "hipsparseZnnz"), + ("cusparseXcoosortByColumn", "hipsparseXcoosortByColumn"), + ("cusparseXcscsort_bufferSizeExt", "hipsparseXcscsort_bufferSizeExt"), + ("cusparseXcscsort", "hipsparseXcscsort"), + ("cusparseCreateCsrilu02Info", "hipsparseCreateCsrilu02Info"), + ("cusparseDestroyCsrilu02Info", "hipsparseDestroyCsrilu02Info"), + ("cusparseCreateBsrilu02Info", "hipsparseCreateBsrilu02Info"), + ("cusparseDestroyBsrilu02Info", "hipsparseDestroyBsrilu02Info"), + ("cusparseCreateCsric02Info", "hipsparseCreateCsric02Info"), + ("cusparseDestroyCsric02Info", "hipsparseDestroyCsric02Info"), + ("cusparseCreateBsric02Info", "hipsparseCreateBsric02Info"), + ("cusparseDestroyBsric02Info", "hipsparseDestroyBsric02Info"), + ("cusparseScsrilu02_numericBoost", "hipsparseScsrilu02_numericBoost"), + ("cusparseDcsrilu02_numericBoost", "hipsparseDcsrilu02_numericBoost"), + ("cusparseCcsrilu02_numericBoost", "hipsparseCcsrilu02_numericBoost"), + ("cusparseZcsrilu02_numericBoost", "hipsparseZcsrilu02_numericBoost"), + ("cusparseXcsrilu02_zeroPivot", "hipsparseXcsrilu02_zeroPivot"), + ("cusparseScsrilu02_bufferSize", "hipsparseScsrilu02_bufferSize"), + ("cusparseDcsrilu02_bufferSize", "hipsparseDcsrilu02_bufferSize"), + ("cusparseCcsrilu02_bufferSize", "hipsparseCcsrilu02_bufferSize"), + ("cusparseZcsrilu02_bufferSize", "hipsparseZcsrilu02_bufferSize"), + ("cusparseScsrilu02_analysis", "hipsparseScsrilu02_analysis"), + ("cusparseDcsrilu02_analysis", "hipsparseDcsrilu02_analysis"), + ("cusparseCcsrilu02_analysis", "hipsparseCcsrilu02_analysis"), + ("cusparseZcsrilu02_analysis", "hipsparseZcsrilu02_analysis"), + ("cusparseScsrilu02", "hipsparseScsrilu02"), + ("cusparseDcsrilu02", "hipsparseDcsrilu02"), + ("cusparseCcsrilu02", "hipsparseCcsrilu02"), + ("cusparseZcsrilu02", "hipsparseZcsrilu02"), + ("cusparseSbsrilu02_numericBoost", "hipsparseSbsrilu02_numericBoost"), + ("cusparseDbsrilu02_numericBoost", "hipsparseDbsrilu02_numericBoost"), + ("cusparseCbsrilu02_numericBoost", "hipsparseCbsrilu02_numericBoost"), + ("cusparseZbsrilu02_numericBoost", "hipsparseZbsrilu02_numericBoost"), + ("cusparseXbsrilu02_zeroPivot", "hipsparseXbsrilu02_zeroPivot"), + ("cusparseSbsrilu02_bufferSize", "hipsparseSbsrilu02_bufferSize"), + ("cusparseDbsrilu02_bufferSize", "hipsparseDbsrilu02_bufferSize"), + ("cusparseCbsrilu02_bufferSize", "hipsparseCbsrilu02_bufferSize"), + ("cusparseZbsrilu02_bufferSize", "hipsparseZbsrilu02_bufferSize"), + ("cusparseSbsrilu02_analysis", "hipsparseSbsrilu02_analysis"), + ("cusparseDbsrilu02_analysis", "hipsparseDbsrilu02_analysis"), + ("cusparseCbsrilu02_analysis", "hipsparseCbsrilu02_analysis"), + ("cusparseZbsrilu02_analysis", "hipsparseZbsrilu02_analysis"), + ("cusparseSbsrilu02", "hipsparseSbsrilu02"), + ("cusparseDbsrilu02", "hipsparseDbsrilu02"), + ("cusparseCbsrilu02", "hipsparseCbsrilu02"), + ("cusparseZbsrilu02", "hipsparseZbsrilu02"), + ("cusparseXcsric02_zeroPivot", "hipsparseXcsric02_zeroPivot"), + ("cusparseScsric02_bufferSize", "hipsparseScsric02_bufferSize"), + ("cusparseDcsric02_bufferSize", "hipsparseDcsric02_bufferSize"), + ("cusparseCcsric02_bufferSize", "hipsparseCcsric02_bufferSize"), + ("cusparseZcsric02_bufferSize", "hipsparseZcsric02_bufferSize"), + ("cusparseScsric02_analysis", "hipsparseScsric02_analysis"), + ("cusparseDcsric02_analysis", "hipsparseDcsric02_analysis"), + ("cusparseCcsric02_analysis", "hipsparseCcsric02_analysis"), + ("cusparseZcsric02_analysis", "hipsparseZcsric02_analysis"), + ("cusparseScsric02", "hipsparseScsric02"), + ("cusparseDcsric02", "hipsparseDcsric02"), + ("cusparseCcsric02", "hipsparseCcsric02"), + ("cusparseZcsric02", "hipsparseZcsric02"), + ("cusparseXbsric02_zeroPivot", "hipsparseXbsric02_zeroPivot"), + ("cusparseSbsric02_bufferSize", "hipsparseSbsric02_bufferSize"), + ("cusparseDbsric02_bufferSize", "hipsparseDbsric02_bufferSize"), + ("cusparseCbsric02_bufferSize", "hipsparseCbsric02_bufferSize"), + ("cusparseZbsric02_bufferSize", "hipsparseZbsric02_bufferSize"), + ("cusparseSbsric02_analysis", "hipsparseSbsric02_analysis"), + ("cusparseDbsric02_analysis", "hipsparseDbsric02_analysis"), + ("cusparseCbsric02_analysis", "hipsparseCbsric02_analysis"), + ("cusparseZbsric02_analysis", "hipsparseZbsric02_analysis"), + ("cusparseSbsric02", "hipsparseSbsric02"), + ("cusparseDbsric02", "hipsparseDbsric02"), + ("cusparseCbsric02", "hipsparseCbsric02"), + ("cusparseZbsric02", "hipsparseZbsric02"), + ("cusparseSgtsv2_bufferSizeExt", "hipsparseSgtsv2_bufferSizeExt"), + ("cusparseDgtsv2_bufferSizeExt", "hipsparseDgtsv2_bufferSizeExt"), + ("cusparseCgtsv2_bufferSizeExt", "hipsparseCgtsv2_bufferSizeExt"), + ("cusparseZgtsv2_bufferSizeExt", "hipsparseZgtsv2_bufferSizeExt"), + ("cusparseSgtsv2", "hipsparseSgtsv2"), + ("cusparseDgtsv2", "hipsparseDgtsv2"), + ("cusparseCgtsv2", "hipsparseCgtsv2"), + ("cusparseZgtsv2", "hipsparseZgtsv2"), + ("cusparseSgtsv2_nopivot_bufferSizeExt", "hipsparseSgtsv2_nopivot_bufferSizeExt"), + ("cusparseDgtsv2_nopivot_bufferSizeExt", "hipsparseDgtsv2_nopivot_bufferSizeExt"), + ("cusparseCgtsv2_nopivot_bufferSizeExt", "hipsparseCgtsv2_nopivot_bufferSizeExt"), + ("cusparseZgtsv2_nopivot_bufferSizeExt", "hipsparseZgtsv2_nopivot_bufferSizeExt"), + ("cusparseSgtsv2_nopivot", "hipsparseSgtsv2_nopivot"), + ("cusparseDgtsv2_nopivot", "hipsparseDgtsv2_nopivot"), + ("cusparseCgtsv2_nopivot", "hipsparseCgtsv2_nopivot"), + ("cusparseZgtsv2_nopivot", "hipsparseZgtsv2_nopivot"), + ("cusparseSgtsv2StridedBatch_bufferSizeExt", "hipsparseSgtsv2StridedBatch_bufferSizeExt"), + ("cusparseDgtsv2StridedBatch_bufferSizeExt", "hipsparseDgtsv2StridedBatch_bufferSizeExt"), + ("cusparseCgtsv2StridedBatch_bufferSizeExt", "hipsparseCgtsv2StridedBatch_bufferSizeExt"), + ("cusparseZgtsv2StridedBatch_bufferSizeExt", "hipsparseZgtsv2StridedBatch_bufferSizeExt"), + ("cusparseSgtsv2StridedBatch", "hipsparseSgtsv2StridedBatch"), + ("cusparseDgtsv2StridedBatch", "hipsparseDgtsv2StridedBatch"), + ("cusparseCgtsv2StridedBatch", "hipsparseCgtsv2StridedBatch"), + ("cusparseZgtsv2StridedBatch", "hipsparseZgtsv2StridedBatch"), + ("cusparseSgtsvInterleavedBatch_bufferSizeExt", "hipsparseSgtsvInterleavedBatch_bufferSizeExt"), + ("cusparseDgtsvInterleavedBatch_bufferSizeExt", "hipsparseDgtsvInterleavedBatch_bufferSizeExt"), + ("cusparseCgtsvInterleavedBatch_bufferSizeExt", "hipsparseCgtsvInterleavedBatch_bufferSizeExt"), + ("cusparseZgtsvInterleavedBatch_bufferSizeExt", "hipsparseZgtsvInterleavedBatch_bufferSizeExt"), + ("cusparseSgtsvInterleavedBatch", "hipsparseSgtsvInterleavedBatch"), + ("cusparseDgtsvInterleavedBatch", "hipsparseDgtsvInterleavedBatch"), + ("cusparseCgtsvInterleavedBatch", "hipsparseCgtsvInterleavedBatch"), + ("cusparseZgtsvInterleavedBatch", "hipsparseZgtsvInterleavedBatch"), + ("cusparseSgpsvInterleavedBatch_bufferSizeExt", "hipsparseSgpsvInterleavedBatch_bufferSizeExt"), + ("cusparseDgpsvInterleavedBatch_bufferSizeExt", "hipsparseDgpsvInterleavedBatch_bufferSizeExt"), + ("cusparseCgpsvInterleavedBatch_bufferSizeExt", "hipsparseCgpsvInterleavedBatch_bufferSizeExt"), + ("cusparseZgpsvInterleavedBatch_bufferSizeExt", "hipsparseZgpsvInterleavedBatch_bufferSizeExt"), + ("cusparseSgpsvInterleavedBatch", "hipsparseSgpsvInterleavedBatch"), + ("cusparseDgpsvInterleavedBatch", "hipsparseDgpsvInterleavedBatch"), + ("cusparseCgpsvInterleavedBatch", "hipsparseCgpsvInterleavedBatch"), + ("cusparseZgpsvInterleavedBatch", "hipsparseZgpsvInterleavedBatch"), + ("cusparseCreateSpVec", "hipsparseCreateSpVec"), + ("cusparseDestroySpVec", "hipsparseDestroySpVec"), + ("cusparseSpVecGet", "hipsparseSpVecGet"), + ("cusparseSpVecGetIndexBase", "hipsparseSpVecGetIndexBase"), + ("cusparseSpVecGetValues", "hipsparseSpVecGetValues"), + ("cusparseSpVecSetValues", "hipsparseSpVecSetValues"), + ("cusparseCreateCooAoS", "hipsparseCreateCooAoS"), + ("cusparseCooGet", "hipsparseCooGet"), + ("cusparseCooAoSGet", "hipsparseCooAoSGet"), + ("cusparseCsrGet", "hipsparseCsrGet"), + ("cusparseSpMatGetFormat", "hipsparseSpMatGetFormat"), + ("cusparseSpMatGetIndexBase", "hipsparseSpMatGetIndexBase"), + ("cusparseSpMatGetValues", "hipsparseSpMatGetValues"), + ("cusparseSpMatGetStridedBatch", "hipsparseSpMatGetStridedBatch"), + ("cusparseSpMatSetStridedBatch", "hipsparseSpMatSetStridedBatch"), + ("cusparseDnVecGet", "hipsparseDnVecGet"), + ("cusparseDnVecGetValues", "hipsparseDnVecGetValues"), + ("cusparseDnVecSetValues", "hipsparseDnVecSetValues"), + ("cusparseDnMatGet", "hipsparseDnMatGet"), + ("cusparseDnMatGetValues", "hipsparseDnMatGetValues"), + ("cusparseDnMatSetValues", "hipsparseDnMatSetValues"), + ("cusparseDnMatGetStridedBatch", "hipsparseDnMatGetStridedBatch"), + ("cusparseSpVV_bufferSize", "hipsparseSpVV_bufferSize"), + ("cusparseSpVV", "hipsparseSpVV"), + ("cusparseCsr2cscEx2_bufferSize", "hipsparseCsr2cscEx2_bufferSize"), + ("cusparseCsr2cscEx2", "hipsparseCsr2cscEx2"), + ("cusparseCreateDnMat", "hipsparseCreateDnMat"), + ("cusparseDnMatSetStridedBatch", "hipsparseDnMatSetStridedBatch"), + ("cusparseCsrSetStridedBatch", "hipsparseCsrSetStridedBatch"), + ("cusparseCreateDnVec", "hipsparseCreateDnVec"), + ("cusparseCreateCsr", "hipsparseCreateCsr"), + ("cusparseDestroyDnMat", "hipsparseDestroyDnMat"), + ("cusparseDestroyDnVec", "hipsparseDestroyDnVec"), + ("cusparseDestroySpMat", "hipsparseDestroySpMat"), + ("cusparseSpGEMM_destroyDescr", "hipsparseSpGEMM_destroyDescr"), + ("cusparseCreateCoo", "hipsparseCreateCoo"), + ("cusparseSpGEMM_createDescr", "hipsparseSpGEMM_createDescr"), + ("cusparseSpGEMM_copy", "hipsparseSpGEMM_copy"), + ("cusparseSDDMM_bufferSize", "hipsparseSDDMM_bufferSize"), + ("cusparseSDDMM_preprocess", "hipsparseSDDMM_preprocess"), + ("cusparseSDDMM", "hipsparseSDDMM"), + ("cusparseSpGEMM_compute", "hipsparseSpGEMM_compute"), + ("cusparseSpGEMM_workEstimation", "hipsparseSpGEMM_workEstimation"), + ("cusparseSpMatGetSize", "hipsparseSpMatGetSize"), + ("cusparseCsrSetPointers", "hipsparseCsrSetPointers"), + ("cusparseCreateCsc", "hipsparseCreateCsc"), + ("cusparseSpMatSetValues", "hipsparseSpMatSetValues"), + ("cusparseSpMatSetAttribute", "hipsparseSpMatSetAttribute"), + ("cusparseSpSM_createDescr", "hipsparseSpSM_createDescr"), + ("cusparseSpSM_destroyDescr", "hipsparseSpSM_destroyDescr"), + ("cusparseSpSM_bufferSize", "hipsparseSpSM_bufferSize"), + ("cusparseSpSM_analysis", "hipsparseSpSM_analysis"), + ("cusparseSpSM_solve", "hipsparseSpSM_solve"), + ("cusparseSpSV_createDescr", "hipsparseSpSV_createDescr"), + ("cusparseSpSV_destroyDescr", "hipsparseSpSV_destroyDescr"), + ("cusparseSpSV_bufferSize", "hipsparseSpSV_bufferSize"), + ("cusparseSpSV_analysis", "hipsparseSpSV_analysis"), + ("cusparseSpSV_solve", "hipsparseSpSV_solve"), + ("cusparseSparseToDense_bufferSize", "hipsparseSparseToDense_bufferSize"), + ("cusparseSparseToDense", "hipsparseSparseToDense"), + ("cusparseDenseToSparse_bufferSize", "hipsparseDenseToSparse_bufferSize"), + ("cusparseDenseToSparse_analysis", "hipsparseDenseToSparse_analysis"), + ("cusparseDenseToSparse_convert", "hipsparseDenseToSparse_convert"), + ("cusparseSpMVAlg_t", "hipsparseSpMVAlg_t"), + ("cusparseSpMMAlg_t", "hipsparseSpMMAlg_t"), + ("cusparseIndexType_t", "hipsparseIndexType_t"), + ("cusparseDnMatDescr_t", "hipsparseDnMatDescr_t"), + ("cusparseDnVecDescr_t", "hipsparseDnVecDescr_t"), + ("cusparseSpMatDescr_t", "hipsparseSpMatDescr_t"), + ("cusparseSpGEMMDescr_t", "hipsparseSpGEMMDescr_t"), + ("CUSPARSE_INDEX_32I", "HIPSPARSE_INDEX_32I"), + ("CUSPARSE_INDEX_64I", "HIPSPARSE_INDEX_64I"), + ("CUSPARSE_ORDER_COL", "HIPSPARSE_ORDER_COL"), + ("CUSPARSE_MV_ALG_DEFAULT", "HIPSPARSE_MV_ALG_DEFAULT"), + ("CUSPARSE_MM_ALG_DEFAULT", "HIPSPARSE_MM_ALG_DEFAULT"), + ("CUSPARSE_SPMM_COO_ALG1", "HIPSPARSE_SPMM_COO_ALG1"), + ("CUSPARSE_SPMM_COO_ALG2", "HIPSPARSE_SPMM_COO_ALG2"), + ("CUSPARSE_COOMM_ALG1", "HIPSPARSE_COOMM_ALG1"), + ("CUSPARSE_COOMM_ALG2", "HIPSPARSE_COOMM_ALG2"), + ("CUSPARSE_COOMM_ALG3", "HIPSPARSE_COOMM_ALG3"), + ("CUSPARSE_COOMV_ALG", "HIPSPARSE_COOMV_ALG"), + ("CUSPARSE_CSRMM_ALG1", "HIPSPARSE_CSRMM_ALG1"), + ("CUSPARSE_SPMM_CSR_ALG1", "HIPSPARSE_SPMM_CSR_ALG1"), + ("CUSPARSE_SPMM_CSR_ALG2", "HIPSPARSE_SPMM_CSR_ALG2"), + ("CUSPARSE_SPMM_CSR_ALG3", "HIPSPARSE_SPMM_CSR_ALG3"), + ("CUSPARSE_SPGEMM_DEFAULT", "HIPSPARSE_SPGEMM_DEFAULT"), + ("CUSPARSE_SDDMM_ALG_DEFAULT", "HIPSPARSE_SDDMM_ALG_DEFAULT"), + ("CUSPARSE_STATUS_SUCCESS", "HIPSPARSE_STATUS_SUCCESS"), + ("CUSPARSE_STATUS_NOT_INITIALIZED", "HIPSPARSE_STATUS_NOT_INITIALIZED"), + ("CUSPARSE_STATUS_ALLOC_FAILED", "HIPSPARSE_STATUS_ALLOC_FAILED"), + ("CUSPARSE_STATUS_INVALID_VALUE", "HIPSPARSE_STATUS_INVALID_VALUE"), + ("CUSPARSE_STATUS_MAPPING_ERROR", "HIPSPARSE_STATUS_MAPPING_ERROR"), + ("CUSPARSE_STATUS_EXECUTION_FAILED", "HIPSPARSE_STATUS_EXECUTION_FAILED"), + ("CUSPARSE_STATUS_INTERNAL_ERROR", "HIPSPARSE_STATUS_INTERNAL_ERROR"), + ("CUSPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED", "HIPSPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED"), + ("CUSPARSE_STATUS_ARCH_MISMATCH", "HIPSPARSE_STATUS_ARCH_MISMATCH"), + ("CUSPARSE_STATUS_ZERO_PIVOT", "HIPSPARSE_STATUS_ZERO_PIVOT"), + ("CUSPARSE_OPERATION_TRANSPOSE", "HIPSPARSE_OPERATION_TRANSPOSE"), + ("CUSPARSE_OPERATION_NON_TRANSPOSE", "HIPSPARSE_OPERATION_NON_TRANSPOSE"), + ("CUSPARSE_OPERATION_CONJUGATE_TRANSPOSE", "HIPSPARSE_OPERATION_CONJUGATE_TRANSPOSE"), + ("CUSPARSE_INDEX_BASE_ZERO", "HIPSPARSE_INDEX_BASE_ZERO"), + ("CUSPARSE_INDEX_BASE_ONE", "HIPSPARSE_INDEX_BASE_ONE"), + ("CUSPARSE_MATRIX_TYPE_GENERAL", "HIPSPARSE_MATRIX_TYPE_GENERAL"), + ("cusparseGetErrorName", "hipsparseGetErrorName"), + ("cusparseOrder_t", "hipsparseOrder_t"), + ("cusparseSpGEMMAlg_t", "hipsparseSpGEMMAlg_t"), + ("cusparseCsr2CscAlg_t", "hipsparseCsr2CscAlg_t"), + ("cusparseGetErrorString", "hipsparseGetErrorString"), + ("cusparseGather", "hipsparseGather"), + ("cusparseSparseToDenseAlg_t", "hipsparseSparseToDenseAlg_t"), + ("cusparseDenseToSparseAlg_t", "hipsparseDenseToSparseAlg_t"), + ("cusparseIndexBase_t", "hipsparseIndexBase_t"), + ("cusparseMatrixType_t", "hipsparseMatrixType_t"), + ("cusparsePointerMode_t", "hipsparsePointerMode_t"), + ("cusparseAction_t", "hipsparseAction_t"), + ("cusparseFormat_t", "hipsparseFormat_t"), + ("cusparseSpSMAlg_t", "hipsparseSpSMAlg_t"), + ("cusparseSpSVAlg_t", "hipsparseSpSVAlg_t"), + ("cusparseSpMatAttribute_t", "hipsparseSpMatAttribute_t"), + ("cusparseSpVecDescr_t", "hipsparseSpVecDescr_t"), + ("cusparseSpSMDescr_t", "hipsparseSpSMDescr_t"), + ("cusparseSpSVDescr_t", "hipsparseSpSVDescr_t"), + ("CUSPARSE_POINTER_MODE_DEVICE", "HIPSPARSE_POINTER_MODE_DEVICE"), + ("CUSPARSE_ACTION_SYMBOLIC", "HIPSPARSE_ACTION_SYMBOLIC"), + ("CUSPARSE_ACTION_NUMERIC", "HIPSPARSE_ACTION_NUMERIC"), + ("CUSPARSE_MATRIX_TYPE_SYMMETRIC", "HIPSPARSE_MATRIX_TYPE_SYMMETRIC"), + ("CUSPARSE_MATRIX_TYPE_HERMITIAN", "HIPSPARSE_MATRIX_TYPE_HERMITIAN"), + ("CUSPARSE_MATRIX_TYPE_TRIANGULAR", "HIPSPARSE_MATRIX_TYPE_TRIANGULAR"), + ("CUSPARSE_FORMAT_CSR", "HIPSPARSE_FORMAT_CSR"), + ("CUSPARSE_FORMAT_CSC", "HIPSPARSE_FORMAT_CSC"), + ("CUSPARSE_FORMAT_COO", "HIPSPARSE_FORMAT_COO"), + ("CUSPARSE_FORMAT_COO_AOS", "HIPSPARSE_FORMAT_COO_AOS"), + ("CUSPARSE_ORDER_ROW", "HIPSPARSE_ORDER_ROW"), + ("CUSPARSE_CSRMV_ALG1", "HIPSPARSE_CSRMV_ALG1"), + ("CUSPARSE_CSRMV_ALG2", "HIPSPARSE_CSRMV_ALG2"), + ("CUSPARSE_INDEX_16U", "HIPSPARSE_INDEX_16U"), + ("CUSPARSE_SPMAT_FILL_MODE", "HIPSPARSE_SPMAT_FILL_MODE"), + ("CUSPARSE_SPMAT_DIAG_TYPE", "HIPSPARSE_SPMAT_DIAG_TYPE"), + ("CUSPARSE_CSR2CSC_ALG1", "HIPSPARSE_CSR2CSC_ALG1"), + ("CUSPARSE_CSR2CSC_ALG2", "HIPSPARSE_CSR2CSC_ALG2"), + ("CUSPARSE_SPSM_ALG_DEFAULT", "HIPSPARSE_SPSM_ALG_DEFAULT"), + ("CUSPARSE_SPSV_ALG_DEFAULT", "HIPSPARSE_SPSV_ALG_DEFAULT"), + ("CUSPARSE_SPARSETODENSE_ALG_DEFAULT", "HIPSPARSE_SPARSETODENSE_ALG_DEFAULT"), + ("CUSPARSE_DENSETOSPARSE_ALG_DEFAULT", "HIPSPARSE_DENSETOSPARSE_ALG_DEFAULT"), + ("cuSPARSELt", "hipSPARSELt"), + ("AT_CUSPARSELT_ENABLED", "AT_HIPSPARSELT_ENABLED"), + ("CUSPARSELT_SPARSITY_50_PERCENT", "HIPSPARSELT_SPARSITY_50_PERCENT"), + ("cusparseComputeType", "hipsparseLtComputetype_t"), + ("CUSPARSE_COMPUTE_32F", "HIPSPARSELT_COMPUTE_32F"), + ("CUSPARSE_COMPUTE_16F", "HIPSPARSELT_COMPUTE_16F"), + ("CUSPARSE_COMPUTE_32I", "HIPSPARSELT_COMPUTE_32I"), + ("CUSPARSE_COMPUTE_TF32", "HIPSPARSELT_COMPUTE_TF32"), + ("CUSPARSELT_MATMUL_BIAS_POINTER", "HIPSPARSELT_MATMUL_BIAS_POINTER"), + ("CUSPARSELT_MATMUL_ALG_DEFAULT", "HIPSPARSELT_MATMUL_ALG_DEFAULT"), + ("CUSPARSELT_MATMUL_ALG_CONFIG_ID", "HIPSPARSELT_MATMUL_ALG_CONFIG_ID"), + ("CUSPARSELT_MATMUL_ALG_CONFIG_MAX_ID", "HIPSPARSELT_MATMUL_ALG_CONFIG_MAX_ID"), + ("CUSPARSELT_MATMUL_ALPHA_VECTOR_SCALING", "HIPSPARSELT_MATMUL_ALPHA_VECTOR_SCALING"), + ("CUSPARSELT_MATMUL_SPLIT_K", "HIPSPARSELT_MATMUL_SPLIT_K"), + ("CUSPARSELT_MATMUL_SPLIT_K_MODE", "HIPSPARSELT_MATMUL_SPLIT_K_MODE"), + ("cusparseLtHandle_t", "hipsparseLtHandle_t"), + ("cusparseLtMatDescriptor_t", "hipsparseLtMatDescriptor_t"), + ("cusparseLtInit", "hipsparseLtInit"), + ("cusparseLtStructuredDescriptorInit", "hipsparseLtStructuredDescriptorInit"), + ("cusparseLtSplitKMode_t", "hipsparseLtSplitKMode_t"), + ("cusparseLtSpMMACompressedSize2", "hipsparseLtSpMMACompressedSize2"), + ("cusparseLtSpMMACompress2", "hipsparseLtSpMMACompress2"), + ("cusparseLtMatmulDescriptor_t", "hipsparseLtMatmulDescriptor_t"), + ("cusparseLtMatmulPlan_t", "hipsparseLtMatmulPlan_t"), + ("cusparseLtMatmulAlgSelection_t", "hipsparseLtMatmulAlgSelection_t"), + ("cusparseLtDenseDescriptorInit", "hipsparseLtDenseDescriptorInit"), + ("cusparseLtMatmulDescriptorInit", "hipsparseLtMatmulDescriptorInit"), + ("cusparseLtMatmulDescSetAttribute", "hipsparseLtMatmulDescSetAttribute"), + ("cusparseLtMatmulAlgSelectionInit", "hipsparseLtMatmulAlgSelectionInit"), + ("cusparseLtMatmulAlgSetAttribute", "hipsparseLtMatmulAlgSetAttribute"), + ("cusparseLtMatmulPlanInit", "hipsparseLtMatmulPlanInit"), + ("cusparseLtMatmulGetWorkspace", "hipsparseLtMatmulGetWorkspace"), + ("cusparseLtMatmulSearch", "hipsparseLtMatmulSearch"), + ("cusparseLtMatmulAlgGetAttribute", "hipsparseLtMatmulAlgGetAttribute"), + ("cusparseLtMatmul", "hipsparseLtMatmul"), + ("cusparseLtMatDescriptorDestroy", "hipsparseLtMatDescriptorDestroy"), + ("cusparseLtMatmulPlanDestroy", "hipsparseLtMatmulPlanDestroy"), + ("cusolverEigMode_t", "hipsolverEigMode_t"), + ("cusolverEigType_t", "hipsolverEigType_t"), + ("CUSOLVER_EIG_MODE_VECTOR", "HIPSOLVER_EIG_MODE_VECTOR"), + ("CUSOLVER_EIG_MODE_NOVECTOR", "HIPSOLVER_EIG_MODE_NOVECTOR"), + ("CUSOLVER_EIG_TYPE_1", "HIPSOLVER_EIG_TYPE_1"), + ("CUSOLVER_EIG_TYPE_2", "HIPSOLVER_EIG_TYPE_2"), + ("CUSOLVER_EIG_TYPE_3", "HIPSOLVER_EIG_TYPE_3"), + ("syevjInfo_t", "hipsolverSyevjInfo_t"), + ("cusolverDnCreateSyevjInfo", "hipsolverDnCreateSyevjInfo"), + ("cusolverDnXsyevjSetSortEig", "hipsolverDnXsyevjSetSortEig"), + ("cusolverDnDestroySyevjInfo", "hipsolverDnDestroySyevjInfo"), + ("gesvdjInfo_t", "hipsolverGesvdjInfo_t"), + ("cusolverDnCreateGesvdjInfo", "hipsolverDnCreateGesvdjInfo"), + ("cusolverDnXgesvdjSetSortEig", "hipsolverDnXgesvdjSetSortEig"), + ("cusolverDnDestroyGesvdjInfo", "hipsolverDnDestroyGesvdjInfo"), + ("cusolverDnHandle_t", "hipsolverDnHandle_t"), + ("cusolverDnCreate", "hipsolverDnCreate"), + ("cusolverDnSetStream", "hipsolverDnSetStream"), + ("cusolverDnGetStream", "hipsolverDnGetStream"), + ("cusolverDnDestroy", "hipsolverDnDestroy"), + ("cusolverDnParams_t", "hipsolverDnParams_t"), + ("cusolverDnCreateParams", "hipsolverDnCreateParams"), + ("cusolverDnDestroyParams", "hipsolverDnDestroyParams"), + ("cusolverDnCgeqrf", "hipsolverDnCgeqrf"), + ("cusolverDnCgeqrf_bufferSize", "hipsolverDnCgeqrf_bufferSize"), + ("cusolverDnCgesvd", "hipsolverDnCgesvd"), + ("cusolverDnCgesvd_bufferSize", "hipsolverDnCgesvd_bufferSize"), + ("cusolverDnCgesvdj", "hipsolverDnCgesvdj"), + ("cusolverDnCgesvdjBatched", "hipsolverDnCgesvdjBatched"), + ("cusolverDnCgesvdjBatched_bufferSize", "hipsolverDnCgesvdjBatched_bufferSize"), + ("cusolverDnCgesvdj_bufferSize", "hipsolverDnCgesvdj_bufferSize"), + ("cusolverDnCgetrf", "hipsolverDnCgetrf"), + ("cusolverDnCgetrf_bufferSize", "hipsolverDnCgetrf_bufferSize"), + ("cusolverDnCgetrs", "hipsolverDnCgetrs"), + ("cusolverDnCheevd", "hipsolverDnCheevd"), + ("cusolverDnCheevd_bufferSize", "hipsolverDnCheevd_bufferSize"), + ("cusolverDnCheevj", "hipsolverDnCheevj"), + ("cusolverDnCheevjBatched", "hipsolverDnCheevjBatched"), + ("cusolverDnCheevjBatched_bufferSize", "hipsolverDnCheevjBatched_bufferSize"), + ("cusolverDnCheevj_bufferSize", "hipsolverDnCheevj_bufferSize"), + ("cusolverDnCpotrf", "hipsolverDnCpotrf"), + ("cusolverDnCpotrfBatched", "hipsolverDnCpotrfBatched"), + ("cusolverDnCpotrf_bufferSize", "hipsolverDnCpotrf_bufferSize"), + ("cusolverDnCpotrs", "hipsolverDnCpotrs"), + ("cusolverDnCpotrsBatched", "hipsolverDnCpotrsBatched"), + ("cusolverDnCungqr", "hipsolverDnCungqr"), + ("cusolverDnCungqr_bufferSize", "hipsolverDnCungqr_bufferSize"), + ("cusolverDnCunmqr", "hipsolverDnCunmqr"), + ("cusolverDnCunmqr_bufferSize", "hipsolverDnCunmqr_bufferSize"), + ("cusolverDnDgeqrf", "hipsolverDnDgeqrf"), + ("cusolverDnDgeqrf_bufferSize", "hipsolverDnDgeqrf_bufferSize"), + ("cusolverDnDgesvd", "hipsolverDnDgesvd"), + ("cusolverDnDgesvd_bufferSize", "hipsolverDnDgesvd_bufferSize"), + ("cusolverDnDgesvdj", "hipsolverDnDgesvdj"), + ("cusolverDnDgesvdjBatched", "hipsolverDnDgesvdjBatched"), + ("cusolverDnDgesvdjBatched_bufferSize", "hipsolverDnDgesvdjBatched_bufferSize"), + ("cusolverDnDgesvdj_bufferSize", "hipsolverDnDgesvdj_bufferSize"), + ("cusolverDnDgetrf", "hipsolverDnDgetrf"), + ("cusolverDnDgetrf_bufferSize", "hipsolverDnDgetrf_bufferSize"), + ("cusolverDnDgetrs", "hipsolverDnDgetrs"), + ("cusolverDnDorgqr", "hipsolverDnDorgqr"), + ("cusolverDnDorgqr_bufferSize", "hipsolverDnDorgqr_bufferSize"), + ("cusolverDnDormqr", "hipsolverDnDormqr"), + ("cusolverDnDormqr_bufferSize", "hipsolverDnDormqr_bufferSize"), + ("cusolverDnDpotrf", "hipsolverDnDpotrf"), + ("cusolverDnDpotrfBatched", "hipsolverDnDpotrfBatched"), + ("cusolverDnDpotrf_bufferSize", "hipsolverDnDpotrf_bufferSize"), + ("cusolverDnDpotrs", "hipsolverDnDpotrs"), + ("cusolverDnDpotrsBatched", "hipsolverDnDpotrsBatched"), + ("cusolverDnDsyevd", "hipsolverDnDsyevd"), + ("cusolverDnDsyevd_bufferSize", "hipsolverDnDsyevd_bufferSize"), + ("cusolverDnDsyevj", "hipsolverDnDsyevj"), + ("cusolverDnDsyevjBatched", "hipsolverDnDsyevjBatched"), + ("cusolverDnDsyevjBatched_bufferSize", "hipsolverDnDsyevjBatched_bufferSize"), + ("cusolverDnDsyevj_bufferSize", "hipsolverDnDsyevj_bufferSize"), + ("cusolverDnSgeqrf", "hipsolverDnSgeqrf"), + ("cusolverDnSgeqrf_bufferSize", "hipsolverDnSgeqrf_bufferSize"), + ("cusolverDnSgesvd", "hipsolverDnSgesvd"), + ("cusolverDnSgesvd_bufferSize", "hipsolverDnSgesvd_bufferSize"), + ("cusolverDnSgesvdj", "hipsolverDnSgesvdj"), + ("cusolverDnSgesvdjBatched", "hipsolverDnSgesvdjBatched"), + ("cusolverDnSgesvdjBatched_bufferSize", "hipsolverDnSgesvdjBatched_bufferSize"), + ("cusolverDnSgesvdj_bufferSize", "hipsolverDnSgesvdj_bufferSize"), + ("cusolverDnSgetrf", "hipsolverDnSgetrf"), + ("cusolverDnSgetrf_bufferSize", "hipsolverDnSgetrf_bufferSize"), + ("cusolverDnSgetrs", "hipsolverDnSgetrs"), + ("cusolverDnSorgqr", "hipsolverDnSorgqr"), + ("cusolverDnSorgqr_bufferSize", "hipsolverDnSorgqr_bufferSize"), + ("cusolverDnSormqr", "hipsolverDnSormqr"), + ("cusolverDnSormqr_bufferSize", "hipsolverDnSormqr_bufferSize"), + ("cusolverDnSpotrf", "hipsolverDnSpotrf"), + ("cusolverDnSpotrfBatched", "hipsolverDnSpotrfBatched"), + ("cusolverDnSpotrf_bufferSize", "hipsolverDnSpotrf_bufferSize"), + ("cusolverDnSpotrs", "hipsolverDnSpotrs"), + ("cusolverDnSpotrsBatched", "hipsolverDnSpotrsBatched"), + ("cusolverDnSsyevd", "hipsolverDnSsyevd"), + ("cusolverDnSsyevd_bufferSize", "hipsolverDnSsyevd_bufferSize"), + ("cusolverDnSsyevj", "hipsolverDnSsyevj"), + ("cusolverDnSsyevjBatched", "hipsolverDnSsyevjBatched"), + ("cusolverDnSsyevjBatched_bufferSize", "hipsolverDnSsyevjBatched_bufferSize"), + ("cusolverDnSsyevj_bufferSize", "hipsolverDnSsyevj_bufferSize"), + ("cusolverDnXgeev", "hipsolverDnXgeev"), + ("cusolverDnXgeev_bufferSize", "hipsolverDnXgeev_bufferSize"), + ("cusolverDnXgeqrf", "hipsolverDnXgeqrf"), + ("cusolverDnXgeqrf_bufferSize", "hipsolverDnXgeqrf_bufferSize"), + ("cusolverDnXpotrf", "hipsolverDnXpotrf"), + ("cusolverDnXpotrf_bufferSize", "hipsolverDnXpotrf_bufferSize"), + ("cusolverDnXpotrs", "hipsolverDnXpotrs"), + ("cusolverDnXsyevBatched", "hipsolverDnXsyevBatched"), + ("cusolverDnXsyevBatched_bufferSize", "hipsolverDnXsyevBatched_bufferSize"), + ("cusolverDnXsyevd", "hipsolverDnXsyevd"), + ("cusolverDnXsyevd_bufferSize", "hipsolverDnXsyevd_bufferSize"), + ("cusolverDnZgeqrf", "hipsolverDnZgeqrf"), + ("cusolverDnZgeqrf_bufferSize", "hipsolverDnZgeqrf_bufferSize"), + ("cusolverDnZgesvd", "hipsolverDnZgesvd"), + ("cusolverDnZgesvd_bufferSize", "hipsolverDnZgesvd_bufferSize"), + ("cusolverDnZgesvdj", "hipsolverDnZgesvdj"), + ("cusolverDnZgesvdjBatched", "hipsolverDnZgesvdjBatched"), + ("cusolverDnZgesvdjBatched_bufferSize", "hipsolverDnZgesvdjBatched_bufferSize"), + ("cusolverDnZgesvdj_bufferSize", "hipsolverDnZgesvdj_bufferSize"), + ("cusolverDnZgetrf", "hipsolverDnZgetrf"), + ("cusolverDnZgetrf_bufferSize", "hipsolverDnZgetrf_bufferSize"), + ("cusolverDnZgetrs", "hipsolverDnZgetrs"), + ("cusolverDnZheevd", "hipsolverDnZheevd"), + ("cusolverDnZheevd_bufferSize", "hipsolverDnZheevd_bufferSize"), + ("cusolverDnZheevj", "hipsolverDnZheevj"), + ("cusolverDnZheevjBatched", "hipsolverDnZheevjBatched"), + ("cusolverDnZheevjBatched_bufferSize", "hipsolverDnZheevjBatched_bufferSize"), + ("cusolverDnZheevj_bufferSize", "hipsolverDnZheevj_bufferSize"), + ("cusolverDnZpotrf", "hipsolverDnZpotrf"), + ("cusolverDnZpotrfBatched", "hipsolverDnZpotrfBatched"), + ("cusolverDnZpotrf_bufferSize", "hipsolverDnZpotrf_bufferSize"), + ("cusolverDnZpotrs", "hipsolverDnZpotrs"), + ("cusolverDnZpotrsBatched", "hipsolverDnZpotrsBatched"), + ("cusolverDnZungqr", "hipsolverDnZungqr"), + ("cusolverDnZungqr_bufferSize", "hipsolverDnZungqr_bufferSize"), + ("cusolverDnZunmqr", "hipsolverDnZunmqr"), + ("cusolverDnZunmqr_bufferSize", "hipsolverDnZunmqr_bufferSize"), + ("cusolverDnDsytrf_bufferSize", "hipsolverDnDsytrf_bufferSize"), + ("cusolverDnSsytrf_bufferSize", "hipsolverDnSsytrf_bufferSize"), + ("cusolverDnZsytrf_bufferSize", "hipsolverDnZsytrf_bufferSize"), + ("cusolverDnCsytrf_bufferSize", "hipsolverDnCsytrf_bufferSize"), + ("cusolverDnDsytrf", "hipsolverDnDsytrf"), + ("cusolverDnSsytrf", "hipsolverDnSsytrf"), + ("cusolverDnZsytrf", "hipsolverDnZsytrf"), + ("cusolverDnCsytrf", "hipsolverDnCsytrf"), + ("cusolverDnXsytrs_bufferSize", "hipsolverDnXsytrs_bufferSize"), + ("cusolverDnXsytrs", "hipsolverDnXsytrs"), + ("cusolverDnSgesvdaStridedBatched_bufferSize", "hipsolverDnSgesvdaStridedBatched_bufferSize"), + ("cusolverDnDgesvdaStridedBatched_bufferSize", "hipsolverDnDgesvdaStridedBatched_bufferSize"), + ("cusolverDnCgesvdaStridedBatched_bufferSize", "hipsolverDnCgesvdaStridedBatched_bufferSize"), + ("cusolverDnZgesvdaStridedBatched_bufferSize", "hipsolverDnZgesvdaStridedBatched_bufferSize"), + ("cusolverDnSgesvdaStridedBatched", "hipsolverDnSgesvdaStridedBatched"), + ("cusolverDnDgesvdaStridedBatched", "hipsolverDnDgesvdaStridedBatched"), + ("cusolverDnCgesvdaStridedBatched", "hipsolverDnCgesvdaStridedBatched"), + ("cusolverDnZgesvdaStridedBatched", "hipsolverDnZgesvdaStridedBatched"), + ("cusolverDnXgesvdjSetTolerance", "hipsolverDnXgesvdjSetTolerance"), + ("cusolverDnXgesvdjSetMaxSweeps", "hipsolverDnXgesvdjSetMaxSweeps"), + ("cusolverDnSgebrd_bufferSize", "hipsolverDnSgebrd_bufferSize"), + ("cusolverDnDgebrd_bufferSize", "hipsolverDnDgebrd_bufferSize"), + ("cusolverDnCgebrd_bufferSize", "hipsolverDnCgebrd_bufferSize"), + ("cusolverDnZgebrd_bufferSize", "hipsolverDnZgebrd_bufferSize"), + ("cusolverDnSgebrd", "hipsolverDnSgebrd"), + ("cusolverDnDgebrd", "hipsolverDnDgebrd"), + ("cusolverDnCgebrd", "hipsolverDnCgebrd"), + ("cusolverDnZgebrd", "hipsolverDnZgebrd"), + ("cusolverDnXgesvdjGetSweeps", "hipsolverDnXgesvdjGetSweeps"), + ("cusolverDnXsyevjSetTolerance", "hipsolverDnXsyevjSetTolerance"), + ("cusolverDnXsyevjSetMaxSweeps", "hipsolverDnXsyevjSetMaxSweeps"), + ("cusolverDnXsyevjGetResidual", "hipsolverDnXsyevjGetResidual"), + ("cusolverDnXgesvdjGetResidual", "hipsolverDnXgesvdjGetResidual"), + ("cusolverDnXsyevjGetSweeps", "hipsolverDnXsyevjGetSweeps"), +]) + +PYTORCH_SPECIFIC_MAPPINGS = collections.OrderedDict([ + ("USE_CUDA", "USE_ROCM"), + ("CUDA_VERSION", "TORCH_HIP_VERSION"), + ("gloo/cuda.h", "gloo/hip.h"), + ("gloo/cuda_allreduce_halving_doubling.h", "gloo/hip_allreduce_halving_doubling.h"), + ("gloo/cuda_allreduce_halving_doubling_pipelined.h", "gloo/hip_allreduce_halving_doubling_pipelined.h"), + ("gloo/cuda_allreduce_ring.h", "gloo/hip_allreduce_ring.h"), + ("gloo/cuda_allreduce_ring_chunked.h", "gloo/hip_allreduce_ring_chunked.h"), + ("gloo/cuda_broadcast_one_to_all.h", "gloo/hip_broadcast_one_to_all.h"), + ("gloo::CudaAllreduceHalvingDoublingPipelined", "gloo::HipAllreduceHalvingDoublingPipelined"), + ("gloo::CudaAllreduceRingChunked", "gloo::HipAllreduceRingChunked"), + ("gloo::CudaBroadcastOneToAll", "gloo::HipBroadcastOneToAll"), + ("gloo::CudaHostWorkspace", "gloo::HipHostWorkspace"), + ("gloo::CudaDeviceWorkspace", "gloo::HipDeviceWorkspace"), + ("CUDNN_RNN_RELU", "miopenRNNRELU"), + ("CUDNN_RNN_TANH", "miopenRNNTANH"), + ("CUDNN_LSTM", "miopenLSTM"), + ("CUDNN_GRU", "miopenGRU"), + ("cudnnRNNMode_t", "miopenRNNMode_t"), + ("magma_queue_create_from_cuda", "magma_queue_create_from_hip"), + # TODO: Remove these. They were necessary for Meta-internal builds. + ("cudnnHandle_t", "miopenHandle_t"), + ("cudnnCreate", "miopenCreate"), + ("cudnnDestroy", "miopenDestroy"), + ("cudnnSetStream", "miopenSetStream"), + ("cudnnTensorDescriptor_t ", "miopenTensorDescriptor_t "), + ("CUDNN_ENFORCE", "MIOPEN_ENFORCE"), + ("CUDNN_CHECK", "MIOPEN_CHECK"), + # NVSHMEM → rocSHMEM mappings (only symbols used in hipified files: + # NVSHMEMSymmetricMemory.cpp and nvshmem_team_manager.hpp). + ("NVSHMEM_TEAM_INVALID", "rocshmem::ROCSHMEM_TEAM_INVALID"), + ("NVSHMEM_TEAM_WORLD", "rocshmem::ROCSHMEM_TEAM_WORLD"), + ("NVSHMEMX_INIT_WITH_UNIQUEID", "rocshmem::ROCSHMEM_INIT_WITH_UNIQUEID"), + + ("nvshmem_malloc", "rocshmem::rocshmem_malloc"), + ("nvshmem_free", "rocshmem::rocshmem_free"), + ("nvshmem_ptr", "rocshmem::rocshmem_ptr"), + ("nvshmem_team_t", "rocshmem::rocshmem_team_t"), + ("nvshmem_team_split_strided", "rocshmem::rocshmem_team_split_strided"), + + ("nvshmemx_uniqueid_t", "rocshmem::rocshmem_uniqueid_t"), + ("nvshmemx_get_uniqueid", "rocshmem::rocshmem_get_uniqueid"), + ("nvshmemx_init_attr", "rocshmem::rocshmem_init_attr"), + ("nvshmemx_init_attr_t", "rocshmem::rocshmem_init_attr_t"), + ("nvshmemx_set_attr_uniqueid_args", "rocshmem::rocshmem_set_attr_uniqueid_args"), +]) + +C10_MAPPINGS = collections.OrderedDict([ + ("CUDA_VERSION", "TORCH_HIP_VERSION"), + ("CUDA_LAUNCH_BLOCKING=1", "AMD_SERIALIZE_KERNEL=3"), + ("CUDA_LAUNCH_BLOCKING", "AMD_SERIALIZE_KERNEL"), + ("c10/cuda/CUDAAlgorithm.h", "c10/hip/HIPAlgorithm.h"), + ("c10/cuda/CUDAAllocatorConfig.h", "c10/hip/HIPAllocatorConfig.h"), + ("c10/cuda/CUDACachingAllocator.h", "c10/hip/HIPCachingAllocator.h"), + ("c10/cuda/CUDADeviceAssertion.h", "c10/hip/HIPDeviceAssertion.h"), + ("c10/cuda/CUDADeviceAssertionHost.h", "c10/hip/HIPDeviceAssertionHost.h"), + ("c10/cuda/CUDAException.h", "c10/hip/HIPException.h"), + ("c10/cuda/CUDAFunctions.h", "c10/hip/HIPFunctions.h"), + ("c10/cuda/CUDAGraphsC10Utils.h", "c10/hip/HIPGraphsC10Utils.h"), + ("c10/cuda/CUDAGuard.h", "c10/hip/HIPGuard.h"), + ("c10/cuda/CUDAMacros.h", "c10/hip/HIPMacros.h"), + ("c10/cuda/CUDAMathCompat.h", "c10/hip/HIPMathCompat.h"), + ("c10/cuda/CUDAMiscFunctions.h", "c10/hip/HIPMiscFunctions.h"), + ("c10/cuda/CUDAStream.h", "c10/hip/HIPStream.h"), + ("c10/cuda/PeerToPeerAccess.h", "c10/hip/PeerToPeerAccess.h"), + ("c10/cuda/CUDAEvent.h", "c10/hip/HIPEvent.h"), + ("c10/cuda/impl/CUDAGuardImpl.h", "c10/hip/impl/HIPGuardImpl.h"), + ("c10/cuda/impl/CUDATest.h", "c10/hip/impl/HIPTest.h"), + ("CUDATest.hpp", "HIPTest.hpp"), + ("c10/cuda/impl/cuda_cmake_macros.h", "c10/hip/impl/hip_cmake_macros.h"), + # TODO: Remove these. They were necessary for Meta-internal builds. + ("c10::hip::c10_hip_check_implementation", "c10::cuda::c10_cuda_check_implementation"), +]) + +# TODO: Remove CAFFE2_SPECIFIC_MAPPINGS. They were necessary for Meta-internal builds. +# CAFFE2 mappings for simple filename patterns (no path separators) +# These work with the word-boundary regex approach +# NOTE: Removed broad "context_gpu" mapping to prevent double transformation. +# Use CAFFE2_PATH_MAPPINGS for specific path transformations instead. +CAFFE2_SPECIFIC_MAPPINGS = collections.OrderedDict([ + ("cuda_nccl_gpu", "hip/hip_nccl_gpu"), + ("mixed_utils", "hip/mixed_utils"), + ("operator_fallback_gpu", "hip/operator_fallback_gpu"), + ("spatial_batch_norm_op_impl", "hip/spatial_batch_norm_op_impl"), + ("recurrent_network_executor_gpu", "hip/recurrent_network_executor_gpu"), + ("generate_proposals_op_util_nms_gpu", "hip/generate_proposals_op_util_nms_gpu"), + ("max_pool_with_index_gpu", "hip/max_pool_with_index_gpu"), + ("THCCachingAllocator_gpu", "hip/THCCachingAllocator_gpu"), + ("top_k_heap_selection", "hip/top_k_heap_selection"), + ("top_k_radix_selection", "hip/top_k_radix_selection"), + ("GpuAtomics", "hip/GpuAtomics"), + ("GpuDefs", "hip/GpuDefs"), + ("GpuScanUtils", "hip/GpuScanUtils"), + ("GpuBitonicSort", "hip/GpuBitonicSort"), + # ("gather_op", "hip/gather_op"), # gather_op.h is device-agnostic, no path transform needed + ("HIP_CHECK", "CUDA_CHECK"), + # ("HIPContext", "CUDAContext"), + ("CUBLAS_ENFORCE", "HIPBLAS_ENFORCE"), + ("CaffeHipGetDevice", "CaffeCudaGetDevice"), +]) + +# TODO: Remove CAFFE2_PATH_MAPPINGS. They were necessary for Meta-internal builds. +# CAFFE2 path mappings (contain slashes - need special handling in hipify_python.py) +CAFFE2_PATH_MAPPINGS = collections.OrderedDict([ + ("math/reduce.cuh", "math/hip/reduce.cuh"), + ("operators/gather_op.cuh", "operators/hip/gather_op.cuh"), + ("sgd/adagrad_fused_op_gpu.cuh", "sgd/hip/adagrad_fused_op_gpu.cuh"), + ("operators/segment_reduction_op_gpu.cuh", "operators/hip/segment_reduction_op_gpu.cuh"), + ("caffe2/core/common_cudnn.h", "caffe2/core/hip/common_miopen.h"), + # Add specific mappings for common_gpu and context_gpu to prevent double transformation + ("caffe2/core/common_gpu.h", "caffe2/core/hip/common_gpu.h"), + ("caffe2/core/context_gpu.h", "caffe2/core/hip/context_gpu.h"), + ("hip/hip/", "hip/"), +]) + +CUDA_TO_HIP_MAPPINGS = [ + CUDA_IDENTIFIER_MAP, + CUDA_TYPE_NAME_MAP, + CUDA_INCLUDE_MAP, + CUDA_SPECIAL_MAP, + PYTORCH_SPECIFIC_MAPPINGS, + C10_MAPPINGS, + # TODO: Remove CAFFE2_SPECIFIC_MAPPINGS and CAFFE2_PATH_MAPPINGS. See above. + CAFFE2_SPECIFIC_MAPPINGS, + CAFFE2_PATH_MAPPINGS +] diff --git a/.venv/lib/python3.12/site-packages/torch/utils/hipify/hipify_python.py b/.venv/lib/python3.12/site-packages/torch/utils/hipify/hipify_python.py new file mode 100644 index 0000000000000000000000000000000000000000..cc8452dfe980d6ee726c75480b494036a3de6eb6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/hipify/hipify_python.py @@ -0,0 +1,1175 @@ +#!/usr/bin/env python3 +# mypy: allow-untyped-defs +""" The Python Hipify script. +## +# Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. +# 2017-2018 Advanced Micro Devices, Inc. and +# Facebook Inc. All rights reserved. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +""" +import argparse +import fnmatch +import re +import shutil +import sys +import os +import warnings + +from .cuda_to_hip_mappings import CUDA_TO_HIP_MAPPINGS +from .cuda_to_hip_mappings import MATH_TRANSPILATIONS +from .cuda_to_hip_mappings import CAFFE2_PATH_MAPPINGS + +from collections.abc import Iterator +from collections.abc import Mapping, Iterable +from enum import Enum +import functools +import hashlib + +def _deprecated(name): + warnings.warn(f"hipify version 2.0.0 no longer uses function {name}", FutureWarning, stacklevel=2) + +class CurrentState(Enum): + INITIALIZED = 1 + DONE = 2 + +class HipifyResult: + def __init__(self, current_state, hipified_path) -> None: + self.current_state = current_state + self.hipified_path = hipified_path + self.status = "" + + def __str__(self) -> str: + return (f"HipifyResult:: current_state: {self.current_state}, hipified_path : {self.hipified_path}, status: {self.status}") + +HipifyFinalResult = dict[str, HipifyResult] +HIPIFY_C_BREADCRUMB = "// !!! This is a file automatically generated by hipify!!!\n" +HIPIFY_FINAL_RESULT: HipifyFinalResult = {} + +# Hardcode the PyTorch template map +"""This dictionary provides the mapping from PyTorch kernel template types +to their actual types.""" +PYTORCH_TEMPLATE_MAP = {"Dtype": "scalar_t", "T": "scalar_t"} + +__all__ = ['InputError', 'openf', 'bcolors', 'GeneratedFileCleaner', 'match_extensions', 'matched_files_iter', + 'preprocess_file_and_save_result', 'compute_stats', 'add_dim3', 'processKernelLaunches', 'find_closure_group', + 'find_bracket_group', 'find_parentheses_group', 'replace_math_functions', 'hip_header_magic', 'replace_extern_shared', + 'get_hip_file_path', 'is_out_of_place', 'is_pytorch_file', 'is_cusparse_file', 'is_special_file', 'is_caffe2_gpu_file', + 'Trie', 'preprocessor', 'file_specific_replacement', 'file_add_header', + 'fix_static_global_kernels', 'extract_arguments', 'str2bool', 'CurrentState', 'HipifyResult', 'hipify'] + + +class InputError(Exception): + # Exception raised for errors in the input. + + def __init__(self, message) -> None: + super().__init__(message) + self.message = message + + def __str__(self) -> str: + return f"Input error: {self.message}" + + +def openf(filename, mode): + return open(filename, mode, errors='ignore') + + +# Color coding for printing +class bcolors: + HEADER = '\033[95m' + OKBLUE = '\033[94m' + OKGREEN = '\033[92m' + WARNING = '\033[93m' + FAIL = '\033[91m' + ENDC = '\033[0m' + BOLD = '\033[1m' + UNDERLINE = '\033[4m' + + +# To the programmer, the output of hipify most likely are intermediates. +# This class allows users of hipify to ask for a cleanup by running the +# hipify and compilation in a with instantiating this context manager class +# with keep_intermediates=False. +# The main usecase is the cpp_extensions, specifically the load method. +# It is a good idea to keep intermediates (in case of errors or to +# not recompile unchanged files), but in cases where you don't want to +# keep them (e.g. in the CI), this can be used to remove files. +class GeneratedFileCleaner: + """Context Manager to clean up generated files""" + def __init__(self, keep_intermediates=False) -> None: + self.keep_intermediates = keep_intermediates + self.files_to_clean = set() + self.dirs_to_clean = [] + + def __enter__(self): + return self + + def open(self, fn, *args, **kwargs): + if not os.path.exists(fn): + self.files_to_clean.add(os.path.abspath(fn)) + + return open(fn, *args, **kwargs) + + def makedirs(self, dn, exist_ok=False) -> None: + parent, n = os.path.split(dn) + if not n: + parent, n = os.path.split(parent) + if parent and n and not os.path.exists(parent): + self.makedirs(parent, exist_ok=True) + if not os.path.isdir(dn) or not exist_ok: + os.mkdir(dn) + self.dirs_to_clean.append(os.path.abspath(dn)) + + def __exit__(self, type, value, traceback): + if not self.keep_intermediates: + for f in self.files_to_clean: + os.unlink(f) + for d in self.dirs_to_clean[::-1]: + os.rmdir(d) + +# Follow UNIX convention for paths to use '/' instead of '\\' on Windows +def _to_unix_path(path: str) -> str: + return path.replace(os.sep, '/') + +def match_extensions(filename: str, extensions: Iterable) -> bool: + """Helper method to see if filename ends with certain extension""" + return any(filename.endswith(e) for e in extensions) + + +def _fnmatch(filepath, patterns): + return any(fnmatch.fnmatch(filepath, pattern) for pattern in patterns) + + +def matched_files_iter( + root_path: str, + includes: Iterable = (), + ignores: Iterable = (), + extensions: Iterable = (), + out_of_place_only: bool = False, + is_pytorch_extension: bool = False) -> Iterator[str]: + + exact_matches = set(includes) + + # This is a very rough heuristic; really, we want to avoid scanning + # any file which is not checked into source control, but this script + # needs to work even if you're in a Git or Hg checkout, so easier to + # just block the biggest time sinks that won't matter in the + # end. + for (abs_dirpath, dirs, filenames) in os.walk(root_path, topdown=True): + rel_dirpath = os.path.relpath(abs_dirpath, root_path) + if rel_dirpath == '.': + # Blah blah blah O(n) blah blah + if ".git" in dirs: + dirs.remove(".git") + if "build" in dirs: + dirs.remove("build") + if "third_party" in dirs: + dirs.remove("third_party") + dirs.append("third_party/nvfuser") + for filename in filenames: + filepath = _to_unix_path(os.path.join(abs_dirpath, filename)) + # We respect extensions, UNLESS you wrote the entire + # filename verbatim, in which case we always accept it + if ( + _fnmatch(filepath, includes) + and (not _fnmatch(filepath, ignores)) + and (match_extensions(filepath, extensions) or filepath in exact_matches) + ): + yield filepath + + +def preprocess_file_and_save_result( + output_directory: str, + filepath: str, + all_files: Iterable, + header_include_dirs: Iterable, + stats: dict[str, list], + hip_clang_launch: bool, + is_pytorch_extension: bool, + clean_ctx: GeneratedFileCleaner, + show_progress: bool) -> None: + fin_path = os.path.abspath(os.path.join(output_directory, filepath)) + hipify_result = HipifyResult(current_state=CurrentState.INITIALIZED, hipified_path=fin_path) + HIPIFY_FINAL_RESULT[fin_path] = hipify_result + result = preprocessor(output_directory, filepath, all_files, header_include_dirs, stats, + hip_clang_launch, is_pytorch_extension, clean_ctx, show_progress) + + # Show what happened + if show_progress and "ignored" not in result.status: + print( + fin_path, "->", + result.hipified_path, result.status, flush=True) + + HIPIFY_FINAL_RESULT[fin_path] = result + + +def compute_stats(stats) -> None: + unsupported_calls = {cuda_call for (cuda_call, _filepath) in stats["unsupported_calls"]} + + # Print the number of unsupported calls + print(f"Total number of unsupported CUDA function calls: {len(unsupported_calls):d}") + + # Print the list of unsupported calls + print(", ".join(unsupported_calls)) + + # Print the number of kernel launches + print(f"\nTotal number of replaced kernel launches: {len(stats['kernel_launches']):d}") + + +def add_dim3(kernel_string, cuda_kernel): + '''adds dim3() to the second and third arguments in the kernel launch''' + count = 0 + closure = 0 + kernel_string = kernel_string.replace("<<<", "").replace(">>>", "") + arg_locs: list[dict[str, int]] = [{} for _ in range(2)] + arg_locs[count]['start'] = 0 + for ind, c in enumerate(kernel_string): + if count > 1: + break + if c == "(": + closure += 1 + elif c == ")": + closure -= 1 + if (c == "," or ind == len(kernel_string) - 1) and closure == 0: + arg_locs[count]['end'] = ind + (c != ",") + count += 1 + if count < 2: + arg_locs[count]['start'] = ind + 1 + + first_arg_raw = kernel_string[arg_locs[0]['start']:arg_locs[0]['end'] + 1] + second_arg_raw = kernel_string[arg_locs[1]['start']:arg_locs[1]['end']] + + first_arg_clean = kernel_string[arg_locs[0]['start']:arg_locs[0]['end']].replace("\n", "").strip(" ") + second_arg_clean = kernel_string[arg_locs[1]['start']:arg_locs[1]['end']].replace("\n", "").strip(" ") + + first_arg_dim3 = f"dim3({first_arg_clean})" + second_arg_dim3 = f"dim3({second_arg_clean})" + + first_arg_raw_dim3 = first_arg_raw.replace(first_arg_clean, first_arg_dim3) + second_arg_raw_dim3 = second_arg_raw.replace(second_arg_clean, second_arg_dim3) + cuda_kernel = cuda_kernel.replace(first_arg_raw + second_arg_raw, first_arg_raw_dim3 + second_arg_raw_dim3) + return cuda_kernel + + +RE_KERNEL_LAUNCH = re.compile(r'([ ]+)(detail?)::[ ]+\\\n[ ]+') + + +def processKernelLaunches(string, stats): + """ Replace the CUDA style Kernel launches with the HIP style kernel launches.""" + # Concat the namespace with the kernel names. (Find cleaner way of doing this later). + string = RE_KERNEL_LAUNCH.sub(lambda inp: f"{inp.group(1)}{inp.group(2)}::", string) + + def grab_method_and_template(in_kernel): + # The positions for relevant kernel components. + pos = { + "kernel_launch": {"start": in_kernel["start"], "end": in_kernel["end"]}, + "kernel_name": {"start": -1, "end": -1}, + "template": {"start": -1, "end": -1} + } + + # Count for balancing template + count = {"<>": 0} + + # Status for whether we are parsing a certain item. + START = 0 + AT_TEMPLATE = 1 + AFTER_TEMPLATE = 2 + AT_KERNEL_NAME = 3 + + status = START + + # Parse the string character by character + for i in range(pos["kernel_launch"]["start"] - 1, -1, -1): + char = string[i] + + # Handle Templating Arguments + if status in (START, AT_TEMPLATE): + if char == ">": + if status == START: + status = AT_TEMPLATE + pos["template"]["end"] = i + count["<>"] += 1 + + if char == "<": + count["<>"] -= 1 + if count["<>"] == 0 and (status == AT_TEMPLATE): + pos["template"]["start"] = i + status = AFTER_TEMPLATE + + # Handle Kernel Name + if status != AT_TEMPLATE: + if string[i].isalnum() or string[i] in {'(', ')', '_', ':', '#'}: + if status != AT_KERNEL_NAME: + status = AT_KERNEL_NAME + pos["kernel_name"]["end"] = i + + # Case: Kernel name starts the string. + if i == 0: + pos["kernel_name"]["start"] = 0 + + # Finished + return [(pos["kernel_name"]), (pos["template"]), (pos["kernel_launch"])] + + else: + # Potential ending point if we're already traversing a kernel's name. + if status == AT_KERNEL_NAME: + pos["kernel_name"]["start"] = i + + # Finished + return [(pos["kernel_name"]), (pos["template"]), (pos["kernel_launch"])] + + def find_kernel_bounds(string): + """Finds the starting and ending points for all kernel launches in the string.""" + kernel_end = 0 + kernel_positions = [] + + # Continue until we cannot find any more kernels anymore. + while string.find("<<<", kernel_end) != -1: + # Get kernel starting position (starting from the previous ending point) + kernel_start = string.find("<<<", kernel_end) + + # Get kernel ending position (adjust end point past the >>>) + kernel_end = string.find(">>>", kernel_start) + 3 + if kernel_end <= 0: + raise InputError("no kernel end found") + + # Add to list of traversed kernels + kernel_positions.append({"start": kernel_start, "end": kernel_end, + "group": string[kernel_start: kernel_end]}) + + return kernel_positions + + # Replace comments and string literals from the code so that find_kernel_bounds does not + # wrongly capture kernels in comments and string literals. + # This function replaces them with "x" to keep positions. + def mask_comments(string): + in_comment = '' + prev_c = '' + new_string = '' + for c in string: + if in_comment == '': + # Outside comments + if c == '/' and prev_c == '/': + in_comment = '//' + elif c == '*' and prev_c == '/': + in_comment = '/*' + elif c == '"' and prev_c != '\\' and prev_c != "'": + in_comment = '"' + elif in_comment == '//': + # In // xxx + if c == '\r' or c == '\n': + in_comment = '' + elif in_comment == '/*': + # In /* xxx */ + if c == '/' and prev_c == '*': + in_comment = '' + elif in_comment == '"': + # In "" + if c == '"' and prev_c != '\\': + in_comment = '' + prev_c = c + if in_comment == '': + new_string += c + else: + new_string += 'x' + return new_string + + # Grab positional ranges of all kernel launches + get_kernel_positions = list(find_kernel_bounds(mask_comments(string))) + output_string = string + + # Replace each CUDA kernel with a HIP kernel. + for kernel in get_kernel_positions: + # Get kernel components + params = grab_method_and_template(kernel) + + # Find parenthesis after kernel launch + parenthesis = string.find("(", kernel["end"]) + + # Extract cuda kernel + cuda_kernel = string[params[0]["start"]:parenthesis + 1] + kernel_string = string[kernel['start']:kernel['end']] + end_param_index = 0 if params[1]['end'] == -1 else 1 + kernel_name_with_template = string[params[0]['start']:params[end_param_index]['end'] + 1] + cuda_kernel_dim3 = add_dim3(kernel_string, cuda_kernel) + # Keep number of kernel launch params consistent (grid dims, group dims, stream, dynamic shared size) + num_klp = len(extract_arguments(0, kernel["group"].replace("<<<", "(").replace(">>>", ")"))) + + hip_kernel = "hipLaunchKernelGGL(" + cuda_kernel_dim3[0:-1].replace( + ">>>", ", 0" * (4 - num_klp) + ">>>").replace("<<<", ", ").replace( + ">>>", ", ").replace(kernel_name_with_template, "(" + kernel_name_with_template + ")") + + # Replace cuda kernel with hip kernel + output_string = output_string.replace(cuda_kernel, hip_kernel) + + # Update the statistics + stats["kernel_launches"].append(hip_kernel) + + return output_string + + +def find_closure_group(input_string, start, group): + """Generalization for finding a balancing closure group + + if group = ["(", ")"], then finds the first balanced parentheses. + if group = ["{", "}"], then finds the first balanced bracket. + + Given an input string, a starting position in the input string, and the group type, + find_closure_group returns the positions of group[0] and group[1] as a tuple. + + Example: + >>> find_closure_group("(hi)", 0, ["(", ")"]) + (0, 3) + """ + + inside_parenthesis = False + parens = 0 + pos = start + p_start, p_end = -1, -1 + + while pos < len(input_string): + if input_string[pos] == group[0]: + if inside_parenthesis is False: + inside_parenthesis = True + parens = 1 + p_start = pos + else: + parens += 1 + elif input_string[pos] == group[1] and inside_parenthesis: + parens -= 1 + + if parens == 0: + p_end = pos + return p_start, p_end + + pos += 1 + return None, None + + +def find_bracket_group(input_string, start): + """Finds the first balanced parentheses.""" + return find_closure_group(input_string, start, group=["{", "}"]) + + +def find_parentheses_group(input_string, start): + """Finds the first balanced bracket.""" + return find_closure_group(input_string, start, group=["(", ")"]) + + +RE_ASSERT = re.compile(r"\bassert[ ]*\(") + + +def replace_math_functions(input_string): + """FIXME: Temporarily replace std:: invocations of math functions + with non-std:: versions to prevent linker errors NOTE: This + can lead to correctness issues when running tests, since the + correct version of the math function (exp/expf) might not get + called. Plan is to remove this function once HIP supports + std:: math function calls inside device code + + """ + output_string = input_string + for func in MATH_TRANSPILATIONS: + output_string = output_string.replace(fr'{func}(', f'{MATH_TRANSPILATIONS[func]}(') + + return output_string + + +RE_SYNCTHREADS = re.compile(r":?:?\b(__syncthreads)\b(\w*\()") + + +def hip_header_magic(input_string): + """If the file makes kernel builtin calls and does not include the cuda_runtime.h header, + then automatically add an #include to match the "magic" includes provided by NVCC. + TODO: + Update logic to ignore cases where the cuda_runtime.h is included by another file. + """ + + # Copy the input. + output_string = input_string + + # Check if one of the following headers is already included. + headers = ["hip/hip_runtime.h", "hip/hip_runtime_api.h"] + if any(re.search(fr'#include ("{ext}"|<{ext}>)', output_string) for ext in headers): + return output_string + + # Rough logic to detect if we're inside device code + hasDeviceLogic: int + hasDeviceLogic = "hipLaunchKernelGGL" in output_string + hasDeviceLogic += "__global__" in output_string + hasDeviceLogic += "__shared__" in output_string + hasDeviceLogic += RE_SYNCTHREADS.search(output_string) is not None + + # If device logic found, provide the necessary header. + if hasDeviceLogic: + output_string = '#include "hip/hip_runtime.h"\n' + input_string + + return output_string + + +RE_EXTERN_SHARED = re.compile(r"extern\s+([\w\(\)]+)?\s*__shared__\s+([\w:<>\s]+)\s+(\w+)\s*\[\s*\]\s*;") + + +def replace_extern_shared(input_string): + """ + Match 'extern __shared__ type foo[];' syntax and use HIP_DYNAMIC_SHARED() MACRO instead. + See: https://github.com/ROCm/hip/blob/master/docs/markdown/hip_kernel_language.md#__shared__ + Examples: + "extern __shared__ char smemChar[];" + => "HIP_DYNAMIC_SHARED( char, smemChar)" + "extern __shared__ unsigned char smem[];" + => "HIP_DYNAMIC_SHARED( unsigned char, my_smem)" + """ + output_string = input_string + output_string = RE_EXTERN_SHARED.sub( + lambda inp: f"HIP_DYNAMIC_SHARED({inp.group(1) or ''} {inp.group(2)}, {inp.group(3)})", output_string) + + return output_string + + +def get_hip_file_path(rel_filepath, is_pytorch_extension=False): + """ + Returns the new name of the hipified file + """ + # At the moment, some PyTorch source files are HIPified in place. The predicate + # is_out_of_place tells us if this is the case or not. + if os.path.isabs(rel_filepath): + raise AssertionError("rel_filepath must be a relative path") + if not is_pytorch_extension and not is_out_of_place(rel_filepath): + return rel_filepath + + dirpath, filename = os.path.split(rel_filepath) + root, ext = os.path.splitext(filename) + + # Here's the plan: + # + # In general, we need to disambiguate the HIPified filename so that + # it gets a different name from the original filename, so + # that we don't overwrite the original file + # + # There's a lot of different naming conventions across PyTorch, + # but the general recipe is to convert occurrences + # of cuda/gpu to hip, and add hip if there are no occurrences + # of cuda/gpu anywhere. + # + # Concretely, we do the following: + # + # - If there is a directory component named "cuda", replace + # it with "hip", AND + # + # - If the file name contains "CUDA", replace it with "HIP", AND + # + # - ALWAYS replace '.cu' with '.hip', because those files + # contain CUDA kernels that needs to be hipified and processed with + # hip compiler + # + # - If we are not hipifying a PyTorch extension, and the parent + # directory name did not change as a result of the above + # transformations, insert "hip" in the file path + # as the direct parent folder of the file + # + # - If we are hipifying a PyTorch extension, and the parent directory + # name as well as the filename (incl. extension) did not change as + # a result of the above transformations, insert "_hip" in the filename + # + # This isn't set in stone; we might adjust this to support other + # naming conventions. + + if ext == '.cu': + ext = '.hip' + + orig_filename = filename + orig_dirpath = dirpath + + dirpath = dirpath.replace('cuda', 'hip') + dirpath = dirpath.replace('CUDA', 'HIP') + dirpath = dirpath.replace('THC', 'THH') + + root = root.replace('cuda', 'hip') + root = root.replace('CUDA', 'HIP') + # Special case to handle caffe2/core/THCCachingAllocator + if dirpath != "caffe2/core": + root = root.replace('THC', 'THH') + + if not is_pytorch_extension and dirpath == orig_dirpath: + dirpath = os.path.join(dirpath, 'hip') + + if is_pytorch_extension and dirpath == orig_dirpath and (root + ext) == orig_filename: + root = root + "_hip" + + return os.path.join(dirpath, root + ext) + + +def is_out_of_place(rel_filepath) -> bool: + if os.path.isabs(rel_filepath): + raise AssertionError("rel_filepath must be a relative path") + if rel_filepath.startswith("torch/"): + return False + if rel_filepath.startswith("third_party/nvfuser/"): + return False + if rel_filepath.startswith("tools/autograd/templates/"): + return False + return True + + +# Keep this synchronized with includes/ignores in build_amd.py +def is_pytorch_file(rel_filepath) -> bool: + _deprecated("is_pytorch_file") + if os.path.isabs(rel_filepath): + raise AssertionError("rel_filepath must be a relative path") + if rel_filepath.startswith("aten/"): + if rel_filepath.startswith("aten/src/ATen/core/"): + return False + return True + if rel_filepath.startswith("torch/"): + return True + if rel_filepath.startswith("third_party/nvfuser/"): + return True + if rel_filepath.startswith("third_party/fbgemm/"): + return True + if rel_filepath.startswith("third_party/mslk/"): + return True + if rel_filepath.startswith("tools/autograd/templates/"): + return True + if rel_filepath.startswith("test/cpp/c10d/"): + return True + return False + + +def is_cusparse_file(rel_filepath): + _deprecated("is_cusparse_file") + if is_pytorch_file(rel_filepath): + return "sparse" in rel_filepath.lower() + return False + + +def is_special_file(rel_filepath) -> bool: + _deprecated("is_special_file") + if is_pytorch_file(rel_filepath): + if "sparse" in rel_filepath.lower(): + return True + elif "linalg" in rel_filepath.lower(): + if "batchlinearalgebralibblas" in rel_filepath.lower(): + return False # don't use "special" mappings for this specific linalg cublas file + return True + return False + + +def is_caffe2_gpu_file(rel_filepath): + _deprecated("is_caffe2_gpu_file") + if os.path.isabs(rel_filepath): + raise AssertionError("rel_filepath must be a relative path") + if rel_filepath.startswith("c10/cuda"): + return True + filename = os.path.basename(rel_filepath) + _, ext = os.path.splitext(filename) + + return ('gpu' in filename or ext in ['.cu', '.cuh']) and ('cudnn' not in filename) + + +class TrieNode: + """A Trie node whose children are represented as a dictionary of char: TrieNode. + A special char '' represents end of word + """ + + def __init__(self) -> None: + self.children = {} + + +class Trie: + """Creates a Trie out of a list of words. The trie can be exported to a Regex pattern. + The corresponding Regex should match much faster than a simple Regex union.""" + + def __init__(self) -> None: + """Initialize the trie with an empty root node.""" + self.root = TrieNode() + self._hash = hashlib.md5(usedforsecurity=False) + self._digest = self._hash.digest() + + def add(self, word) -> None: + """Add a word to the Trie. """ + self._hash.update(word.encode()) + self._digest = self._hash.digest() + node = self.root + + for char in word: + node.children.setdefault(char, TrieNode()) + node = node.children[char] + node.children[''] = True # Mark the end of the word + + def dump(self): + """Return the root node of Trie. """ + return self.root + + def quote(self, char): + """ Escape a char for regex. """ + return re.escape(char) + + def search(self, word): + """Search whether word is present in the Trie. + Returns True if yes, else return False""" + node = self.root + for char in word: + if char in node.children: + node = node.children[char] + else: + return False + + # make sure to check the end-of-word marker present + return '' in node.children + + @functools.lru_cache # noqa: B019 + def _pattern(self, root, digest): + """Convert a Trie into a regular expression pattern + + Memoized on the hash digest of the trie, which is built incrementally + during add(). + """ + node = root + + if "" in node.children and len(node.children.keys()) == 1: + return None + + alt = [] # store alternative patterns + cc = [] # store char to char classes + q = 0 # for node representing the end of word + for char in sorted(node.children.keys()): + if isinstance(node.children[char], TrieNode): + try: + recurse = self._pattern(node.children[char], self._digest) + alt.append(self.quote(char) + recurse) + except Exception: + cc.append(self.quote(char)) + else: + q = 1 + cconly = not len(alt) > 0 + + if len(cc) > 0: + if len(cc) == 1: + alt.append(cc[0]) + else: + alt.append('[' + ''.join(cc) + ']') + + if len(alt) == 1: + result = alt[0] + else: + result = "(?:" + "|".join(alt) + ")" + + if q: + if cconly: + result += "?" + else: + result = f"(?:{result})?" + return result + + def pattern(self): + """Export the Trie to a regex pattern.""" + return self._pattern(self.root, self._digest) + + def export_to_regex(self): + """Export the Trie to a regex pattern.""" + return self._pattern(self.root, self._digest) + +PYTORCH_TRIE = Trie() +PYTORCH_MAP: dict[str, object] = {} + +for mapping in CUDA_TO_HIP_MAPPINGS: + if not isinstance(mapping, Mapping): + raise TypeError("Expected each mapping in CUDA_TO_HIP_MAPPINGS to be a Mapping") + for src, dst in mapping.items(): + PYTORCH_TRIE.add(src) + PYTORCH_MAP[src] = dst + +RE_PYTORCH_PREPROCESSOR = re.compile(fr'(?<=\W)({PYTORCH_TRIE.export_to_regex()})(?=\W)') + +RE_QUOTE_HEADER = re.compile(r'#include "([^"]+)"') +RE_ANGLE_HEADER = re.compile(r'#include <([^>]+)>') +RE_THC_GENERIC_FILE = re.compile(r'#define THC_GENERIC_FILE "([^"]+)"') +RE_CU_SUFFIX = re.compile(r'\.cu\b') # be careful not to pick up .cuh + +""" +Returns a HipifyResult object with the following details: + "hipified_path" : absolute path of hipified source file + "status" : "ok" if hipified file was written out + "skipped" if an identical hipified file already existed or hipified file couldn't be written out + "ignored" if the source file was a hipified file itself or not meant to be hipified + "current_state" : CurrentState.INITIALIZED if source file is first ready to be hipified + CurrentState.DONE if source file is done with hipification process +""" + + +def preprocessor( + output_directory: str, + filepath: str, + all_files: Iterable, + header_include_dirs: Iterable, + stats: dict[str, list], + hip_clang_launch: bool, + is_pytorch_extension: bool, + clean_ctx: GeneratedFileCleaner, + show_progress: bool) -> HipifyResult: + """ Executes the CUDA -> HIP conversion on the specified file. """ + fin_path = os.path.abspath(os.path.join(output_directory, filepath)) + filepath = _to_unix_path(filepath) + hipify_result = HIPIFY_FINAL_RESULT[fin_path] + if filepath not in all_files: + hipify_result.hipified_path = None + hipify_result.status = "[ignored, not to be hipified]" + hipify_result.current_state = CurrentState.DONE + return hipify_result + + rel_filepath = _to_unix_path(os.path.relpath(filepath, output_directory)) + + with open(fin_path, encoding='utf-8') as fin: + if fin.readline() == HIPIFY_C_BREADCRUMB: + hipify_result.hipified_path = None + hipify_result.status = "[ignored, input is hipified output]" + hipify_result.current_state = CurrentState.DONE + return hipify_result + fin.seek(0) + output_source = fin.read() + + orig_output_source = output_source + + # get_hip_file_path needs a relative path to work correctly + fout_path = os.path.abspath(os.path.join(output_directory, get_hip_file_path(rel_filepath, is_pytorch_extension))) + if not os.path.exists(os.path.dirname(fout_path)): + clean_ctx.makedirs(os.path.dirname(fout_path)) + + # unsupported_calls statistics reporting is broken atm + def pt_repl(m): + return PYTORCH_MAP[m.group(0)] + + output_source = RE_PYTORCH_PREPROCESSOR.sub(pt_repl, output_source) + + # TODO: Remove CAFFE2_PATH_MAPPINGS. They were necessary for Meta-internal builds. + # Apply CAFFE2 path mappings (simple string replacement for paths containing slashes) + # Need to be careful to avoid double-transformations when source file has #ifdef blocks + # with HIP-specific paths already in them (e.g., caffe2/core/hip/context_gpu.h) + for cuda_path, hip_path in CAFFE2_PATH_MAPPINGS.items(): + # Use regex to ensure we don't match paths that already have been hipified + # We need to avoid transforming "caffe2/core/hip/context_gpu.h" when looking for "caffe2/core/context_gpu.h" + # The key insight: if hip_path contains /hip/ and cuda_path doesn't, we need to be careful + if "/hip/" in hip_path and "/hip/" not in cuda_path: + # Only replace cuda_path if it's not preceded by "/hip/" + # Use negative lookbehind to prevent matching already-hipified paths + # The pattern checks that the cuda_path is not immediately preceded by "/hip/" + pattern = r'(?', False), output_source) + output_source = RE_THC_GENERIC_FILE.sub(mk_repl('#define THC_GENERIC_FILE "{0}"'), output_source) + + # CMakeLists.txt rewrites + if filepath.endswith('CMakeLists.txt'): + output_source = output_source.replace('CUDA', 'HIP') + output_source = output_source.replace('THC', 'THH') + output_source = RE_CU_SUFFIX.sub('.hip', output_source) + + # Perform Kernel Launch Replacements + if not hip_clang_launch: + output_source = processKernelLaunches(output_source, stats) + + # Replace std:: with non-std:: versions + if (filepath.endswith((".cu", ".cuh"))) and "PowKernel" not in filepath: + output_source = replace_math_functions(output_source) + + # Include header if device code is contained. + output_source = hip_header_magic(output_source) + + # Replace the extern __shared__ + # NOTE: No longer needed after transition from hcc to hipclang. + # output_source = replace_extern_shared(output_source) + + # Don't write out identical hipified files for extensions if dirpath has not changed + if ( + is_pytorch_extension + and orig_output_source == output_source + and os.path.dirname(fin_path) == os.path.dirname(fout_path) + ): + hipify_result.hipified_path = fin_path + hipify_result.status = "[skipped, no changes]" + hipify_result.current_state = CurrentState.DONE + return hipify_result + + # Add hipify breadcrumb for C-style files to avoid re-hipification + if fin_path != fout_path and match_extensions(fin_path, (".cu", ".cuh", ".c", ".cc", ".cpp", ".h", ".hpp")): + output_source = HIPIFY_C_BREADCRUMB + output_source + + do_write = True + if os.path.exists(fout_path): + with open(fout_path, encoding='utf-8') as fout_old: + do_write = fout_old.read() != output_source + if do_write: + try: + with clean_ctx.open(fout_path, 'w', encoding='utf-8') as fout: + fout.write(output_source) + hipify_result.hipified_path = fout_path + hipify_result.status = "[ok]" + hipify_result.current_state = CurrentState.DONE + return hipify_result + except OSError as e: + print(f'{bcolors.WARNING}Failed to save {fout_path} with "{e.strerror}", leaving {fin_path} unchanged.{bcolors.ENDC}', + file=sys.stderr) + hipify_result.hipified_path = fin_path + hipify_result.status = "[skipped, no permissions]" + hipify_result.current_state = CurrentState.DONE + return hipify_result + else: + hipify_result.hipified_path = fout_path + hipify_result.status = "[skipped, already hipified]" + hipify_result.current_state = CurrentState.DONE + return hipify_result + +def file_specific_replacement(filepath, search_string, replace_string, strict=False) -> None: + with openf(filepath, "r+") as f: + contents = f.read() + if strict: + contents = re.sub(fr'\b({re.escape(search_string)})\b', lambda x: replace_string, contents) + else: + contents = contents.replace(search_string, replace_string) + f.seek(0) + f.write(contents) + f.truncate() + + +def file_add_header(filepath, header) -> None: + with openf(filepath, "r+") as f: + contents = f.read() + if header[0] != "<" and header[-1] != ">": + header = f'"{header}"' + contents = (f'#include {header} \n') + contents + f.seek(0) + f.write(contents) + f.truncate() + + +def fix_static_global_kernels(in_txt): + """Static global kernels in HIP results in a compilation error.""" + in_txt = in_txt.replace(" __global__ static", "__global__") + return in_txt + + +RE_INCLUDE = re.compile(r"#include .*\n") + + +def extract_arguments(start, string): + """ + Return the list of arguments in the upcoming function parameter closure. + Example: + string (input): '(blocks, threads, 0, THCState_getCurrentStream(state))' + arguments (output): [{'start': 1, 'end': 7}, {'start': 8, 'end': 16}, \ + {'start': 17, 'end': 19}, {'start': 20, 'end': 53}] + """ + + arguments = [] + closures = { + "<": 0, + "(": 0 + } + current_position = start + argument_start_pos = current_position + 1 + + # Search for final parenthesis + while current_position < len(string): + if string[current_position] == "(": + closures["("] += 1 + elif string[current_position] == ")": + closures["("] -= 1 + elif string[current_position] == "<": + closures["<"] += 1 + elif string[current_position] == ">" and string[current_position - 1] != "-" and closures["<"] > 0: + closures["<"] -= 1 + + # Finished all arguments + if closures["("] == 0 and closures["<"] == 0: + # Add final argument + arguments.append({"start": argument_start_pos, "end": current_position}) + break + + # Finished current argument + if closures["("] == 1 and closures["<"] == 0 and string[current_position] == ",": + arguments.append({"start": argument_start_pos, "end": current_position}) + argument_start_pos = current_position + 1 + + current_position += 1 + + return arguments + + +def str2bool(v : str) -> bool: + """ArgumentParser doesn't support type=bool. Thus, this helper method will convert + from possible string types to True / False.""" + if v.lower() in ('yes', 'true', 't', 'y', '1'): + return True + elif v.lower() in ('no', 'false', 'f', 'n', '0'): + return False + else: + raise argparse.ArgumentTypeError('Boolean value expected.') + + +def hipify( + project_directory: str, + show_detailed: bool = False, + extensions: Iterable = (".cu", ".cuh", ".c", ".cc", ".cpp", ".h", ".in", ".hpp"), + header_extensions: Iterable = (".cuh", ".h", ".hpp"), + output_directory: str = "", + header_include_dirs: Iterable = (), + includes: Iterable = ('*',), + extra_files: Iterable = (), + out_of_place_only: bool = False, + ignores: Iterable = (), + show_progress: bool = True, + hip_clang_launch: bool = False, + is_pytorch_extension: bool = False, + hipify_extra_files_only: bool = False, + clean_ctx: GeneratedFileCleaner | None = None +) -> HipifyFinalResult: + if project_directory == "": + project_directory = os.getcwd() + + # Verify the project directory exists. + if not os.path.exists(project_directory): + print("The project folder specified does not exist.") + sys.exit(1) + + # If no output directory, provide a default one. + if not output_directory: + project_directory.rstrip("/") + output_directory = project_directory + "_amd" + + if project_directory != output_directory: + includes = [include.replace(project_directory, output_directory) for include in includes] + ignores = [ignore.replace(project_directory, output_directory) for ignore in ignores] + + # Copy from project directory to output directory if not done already. + if not os.path.exists(output_directory): + shutil.copytree(project_directory, output_directory) + + includes = list(map(_to_unix_path, includes)) + ignores = list(map(_to_unix_path, ignores)) + + all_files = list(matched_files_iter(output_directory, includes=includes, + ignores=ignores, extensions=extensions, + out_of_place_only=out_of_place_only, + is_pytorch_extension=is_pytorch_extension)) + all_files_set = set(all_files) + + for f in extra_files: + if not os.path.isabs(f): + f = os.path.join(output_directory, f) + if f not in all_files_set: + all_files.append(f) + + # List all files in header_include_paths to ensure they are hipified + from pathlib import Path + for header_include_dir in header_include_dirs: + if os.path.isabs(header_include_dir): + header_include_dir_path = Path(header_include_dir) + else: + header_include_dir_path = Path(os.path.join(output_directory, header_include_dir)) + all_files.extend( + str(path) for path in header_include_dir_path.rglob('*') if path.is_file() + and _fnmatch(str(path), includes) + and (not _fnmatch(str(path), ignores)) + and match_extensions(path.name, header_extensions) + ) + + if clean_ctx is None: + clean_ctx = GeneratedFileCleaner(keep_intermediates=True) + + # Preprocessing statistics. + stats: dict[str, list] = {"unsupported_calls": [], "kernel_launches": []} + + for filepath in (all_files if not hipify_extra_files_only else extra_files): + preprocess_file_and_save_result(output_directory, filepath, all_files, header_include_dirs, + stats, hip_clang_launch, is_pytorch_extension, clean_ctx, show_progress) + + print(bcolors.OKGREEN + "Successfully preprocessed all matching files." + bcolors.ENDC, file=sys.stderr) + + # Show detailed summary + if show_detailed: + compute_stats(stats) + + return HIPIFY_FINAL_RESULT diff --git a/.venv/lib/python3.12/site-packages/torch/utils/hipify/version.py b/.venv/lib/python3.12/site-packages/torch/utils/hipify/version.py new file mode 100644 index 0000000000000000000000000000000000000000..afced14728f75ce3cd253465517ccc1032a62309 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/hipify/version.py @@ -0,0 +1 @@ +__version__ = '2.0.0' diff --git a/.venv/lib/python3.12/site-packages/torch/utils/hooks.py b/.venv/lib/python3.12/site-packages/torch/utils/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..4fd9770b305996429468b26d444d45d7b9cadbb0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/hooks.py @@ -0,0 +1,261 @@ +# mypy: allow-untyped-defs +import torch +from collections import OrderedDict +import weakref +import warnings +from typing import Any + +__all__ = ["RemovableHandle", "unserializable_hook", "warn_if_has_hooks", "BackwardHook"] + +class RemovableHandle: + r""" + A handle which provides the capability to remove a hook. + + Args: + hooks_dict (dict): A dictionary of hooks, indexed by hook ``id``. + extra_dict (Union[dict, List[dict]]): An additional dictionary or list of + dictionaries whose keys will be deleted when the same keys are + removed from ``hooks_dict``. + """ + + id: int + next_id: int = 0 + + def __init__(self, hooks_dict: Any, *, extra_dict: Any = None) -> None: + self.hooks_dict_ref = weakref.ref(hooks_dict) + self.id = RemovableHandle.next_id + RemovableHandle.next_id += 1 + + self.extra_dict_ref: tuple = () + if isinstance(extra_dict, dict): + self.extra_dict_ref = (weakref.ref(extra_dict),) + elif isinstance(extra_dict, list): + self.extra_dict_ref = tuple(weakref.ref(d) for d in extra_dict) + + def remove(self) -> None: + hooks_dict = self.hooks_dict_ref() + if hooks_dict is not None and self.id in hooks_dict: + del hooks_dict[self.id] + + for ref in self.extra_dict_ref: + extra_dict = ref() + if extra_dict is not None and self.id in extra_dict: + del extra_dict[self.id] + + def __getstate__(self): + if self.extra_dict_ref is None: + return (self.hooks_dict_ref(), self.id) + else: + return (self.hooks_dict_ref(), self.id, tuple(ref() for ref in self.extra_dict_ref)) + + def __setstate__(self, state) -> None: + if state[0] is None: + # create a dead reference + self.hooks_dict_ref = weakref.ref(OrderedDict()) + else: + self.hooks_dict_ref = weakref.ref(state[0]) + self.id = state[1] + RemovableHandle.next_id = max(RemovableHandle.next_id, self.id + 1) + + if len(state) < 3 or state[2] is None: + self.extra_dict_ref = () + else: + self.extra_dict_ref = tuple(weakref.ref(d) for d in state[2]) + + def __enter__(self) -> "RemovableHandle": + return self + + def __exit__(self, type: Any, value: Any, tb: Any) -> None: + self.remove() + + +def unserializable_hook(f): + """ + Mark a function as an unserializable hook with this decorator. + + This suppresses warnings that would otherwise arise if you attempt + to serialize a tensor that has a hook. + """ + f.__torch_unserializable__ = True + return f + + +def warn_if_has_hooks(tensor) -> None: + if tensor._backward_hooks: + for k in tensor._backward_hooks: + hook = tensor._backward_hooks[k] + if not hasattr(hook, "__torch_unserializable__"): + warnings.warn(f"backward hook {repr(hook)} on tensor will not be " + "serialized. If this is expected, you can " + "decorate the function with @torch.utils.hooks.unserializable_hook " + "to suppress this warning", stacklevel=2) + +class BackwardHook: + """ + A wrapper class to implement nn.Module backward hooks. + + It handles: + - Ignoring non-Tensor inputs and replacing them by None before calling the user hook + - Generating the proper Node to capture a set of Tensor's gradients + - Linking the gradients captures for the outputs with the gradients captured for the input + - Calling the user hook once both output and input gradients are available + """ + + def __init__(self, module, user_hooks, user_pre_hooks) -> None: + self.user_hooks = user_hooks + self.user_pre_hooks = user_pre_hooks + self.module = module + + self.grad_outputs = None + self.n_outputs = -1 + self.output_tensors_index = None + self.n_inputs = -1 + self.input_tensors_index = None + + def _pack_with_none(self, indices, values, size): + res = [None] * size + for idx, val in zip(indices, values, strict=True): + res[idx] = val + + return tuple(res) + + def _unpack_none(self, indices, values): + res = [values[idx] for idx in indices] + + return tuple(res) + + def _set_user_hook(self, grad_fn) -> None: + def hook(grad_input, _): + if self.grad_outputs is None: + # This happens because the gradient in your nn.Module flows to + # the Module's input without " passing through the Module's + # output, e.g. when you're doing double backward. + return + res = self._pack_with_none(self.input_tensors_index, grad_input, self.n_inputs) + + for hook in self.user_hooks: + out = hook(self.module, res, self.grad_outputs) + + if out is None: + continue + + if len(out) != len(res): + raise RuntimeError("Backward hook returned an invalid number of grad_input, " + f"got {len(out)}, but expected {len(res)}") + + res = out + + self.grad_outputs = None + + return self._unpack_none(self.input_tensors_index, res) + + grad_fn.register_hook(hook) + + def _apply_on_tensors(self, fn, args): + # Can be used to apply the given function to the tensors contained in the + # args. Will return updated args and the tensors indices + tensors_idx = [] + tensors = [] + + requires_grad = False + for i, arg in enumerate(args): + if isinstance(arg, torch.Tensor): + tensors_idx.append(i) + tensors.append(arg) + requires_grad |= arg.requires_grad + + if not (requires_grad and torch.is_grad_enabled()): + return args, None + + new_tensors = torch.nn.modules._functions.BackwardHookFunction.apply(*tensors) + if len(new_tensors) == 0: + raise RuntimeError("Cannot set Module backward hook for a Module with no input Tensors.") + + grad_fns = [t.grad_fn for t in new_tensors if t.grad_fn is not None and t.grad_fn.name() == "BackwardHookFunctionBackward"] + if len(grad_fns) == 0: + raise RuntimeError("Error while setting up backward hooks. Please open " + "an issue with a code sample to reproduce this.") + + fn(grad_fns[0]) + + arg_list = list(args) + for idx, val in zip(tensors_idx, new_tensors, strict=True): + arg_list[idx] = val + + if type(args) is tuple: + out = tuple(arg_list) + else: + out = type(args)(*arg_list) + return out, tensors_idx + + def setup_input_hook(self, args): + def fn(grad_fn) -> None: + self._set_user_hook(grad_fn) + + res, input_idx = self._apply_on_tensors(fn, args) + self.n_inputs = len(args) + self.input_tensors_index = input_idx + return res + + def setup_output_hook(self, args): + def fn(grad_fn) -> None: + def hook(_, grad_output): + self.grad_outputs = self._pack_with_none(self.output_tensors_index, + grad_output, + self.n_outputs) + + if self.user_pre_hooks: + expected_len = len(self.grad_outputs) + for user_pre_hook in self.user_pre_hooks: + hook_grad_outputs = user_pre_hook(self.module, self.grad_outputs) + if hook_grad_outputs is None: + continue + + actual_len = len(hook_grad_outputs) + if actual_len != expected_len: + raise RuntimeError("Backward pre hook returned an invalid number of grad_output, " + f"got {actual_len}, but expected {expected_len}") + self.grad_outputs = hook_grad_outputs + + # We need to be able to clear self.grad_outputs but also return it + local_grad_outputs = self.grad_outputs + + # Special case if no input required gradients, this hook should call the user + # hook directly + if self.input_tensors_index is None: + # Only full backward hooks (not pre-hooks) receive grad_input + # and are the subject of the warning; pre-hooks already ran + # above from grad_output. Skip both when none are registered. + if self.user_hooks: + warnings.warn("Full backward hook is firing when gradients are computed " + "with respect to module outputs since no inputs require gradients. See " + "https://docs.pytorch.org/docs/main/generated/torch.nn.Module.html#torch.nn.Module.register_full_backward_hook " + "for more details.", + stacklevel=5) + grad_inputs = self._pack_with_none([], [], self.n_inputs) + for user_hook in self.user_hooks: + res = user_hook(self.module, grad_inputs, self.grad_outputs) + if res is not None and not (isinstance(res, tuple) and all(el is None for el in res)): + raise RuntimeError("Backward hook for Modules where no input requires " + "gradient should always return None or None for all gradients.") + self.grad_outputs = None + + if local_grad_outputs is not None: + if self.output_tensors_index is None: + raise AssertionError("output_tensors_index should not be None when grad_outputs is not None") + return tuple(local_grad_outputs[i] for i in self.output_tensors_index) + + grad_fn.register_hook(hook) + + is_tuple = True + if not isinstance(args, tuple): + args = (args,) + is_tuple = False + + res, output_idx = self._apply_on_tensors(fn, args) + self.n_outputs = len(args) + self.output_tensors_index = output_idx + + if not is_tuple: + res = res[0] + return res diff --git a/.venv/lib/python3.12/site-packages/torch/utils/jit/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/jit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/jit/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/jit/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c30b2ba5d09f658f49e237614c718ef0c90145ce Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/jit/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/jit/__pycache__/log_extract.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/jit/__pycache__/log_extract.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0885583acc15b645df3fe312cc5334e743b30cf5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/jit/__pycache__/log_extract.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/jit/log_extract.py b/.venv/lib/python3.12/site-packages/torch/utils/jit/log_extract.py new file mode 100644 index 0000000000000000000000000000000000000000..9e018457802f4aafd05ba6a8d10ef1c4953b1047 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/jit/log_extract.py @@ -0,0 +1,118 @@ +# mypy: allow-untyped-defs +from contextlib import contextmanager +from typing import Any, cast +import random +import torch +import time +from torch.utils.benchmark import Timer + +def extract_ir(filename: str) -> list[str]: + BEGIN = "" + END = "" + pfx = None + graphs = [] + with open(filename) as f: + split_strs = f.read().split(BEGIN) + for i, split_str in enumerate(split_strs): + if i == 0: + continue + end_loc = split_str.find(END) + if end_loc == -1: + continue + s = split_str[:end_loc] + pfx = split_strs[i - 1].splitlines()[-1] + lines = [x[len(pfx):] for x in s.splitlines(keepends=True)] + graphs.append(''.join(lines)) + + return graphs + + +def make_tensor_from_type(inp_type: torch._C.TensorType): + size = inp_type.sizes() + stride = inp_type.strides() + device = inp_type.device() + dtype = inp_type.dtype() + if size is None: + raise AssertionError("make_tensor_from_type: 'size' is None (inp_type.sizes() returned None)") + if stride is None: + raise AssertionError("make_tensor_from_type: 'stride' is None (inp_type.strides() returned None)") + if device is None: + raise AssertionError("make_tensor_from_type: 'device' is None (inp_type.device() returned None)") + if dtype is None: + raise AssertionError("make_tensor_from_type: 'dtype' is None (inp_type.dtype() returned None)") + return torch.empty_strided(size=size, stride=stride, device=device, dtype=dtype) + +def load_graph_and_inputs(ir: str) -> tuple[Any, list[Any]]: + graph = torch._C.parse_ir(ir, parse_tensor_constants=True) + graph.makeMultiOutputIntoTuple() + inputs = [] + for inp in graph.inputs(): + if isinstance(inp.type(), torch._C.FloatType): + inputs.append(random.uniform(.1, 100)) + elif isinstance(inp.type(), torch._C.IntType): + inputs.append(random.randint(1, 100)) + elif isinstance(inp.type(), torch._C.TensorType): + tensorType = cast(torch._C.TensorType, inp.type()) + inputs.append(make_tensor_from_type(tensorType)) + elif isinstance(inp.type(), torch._C.BoolType): + inputs.append(random.randint(0, 1) == 1) + else: + raise NotImplementedError(f"A default value is not implemented for type {inp.type()}") + + func = torch._C._create_function_from_graph("forward", graph) + torch._C._jit_pass_erase_shape_information(func.graph) + return (func, inputs) + +def time_cuda(fn, inputs, test_runs): + t = Timer(stmt="fn(*inputs)", globals={"fn": fn, "inputs" : inputs}) + times = t.blocked_autorange() + return times.median * 1000 # time in ms + +def time_cpu(fn, inputs, test_runs): + s = time.perf_counter() + for _ in range(test_runs): + fn(*inputs) + e = time.perf_counter() + return (e - s) / test_runs * 1000 # time in ms + +def run_test(ir, inputs, *, warmup_runs=10, test_runs=20) -> float: + graph, _ = load_graph_and_inputs(ir) + for _ in range(warmup_runs): + graph(*inputs) + + is_cpu = None + for input in inputs: + if isinstance(input, torch.Tensor): + is_cpu = input.device.type == "cpu" + break + if is_cpu is None: + raise AssertionError("No tensor found in inputs") + + out = time_cpu(graph, inputs, test_runs) if is_cpu else time_cuda(graph, inputs, test_runs) + return out + +@contextmanager +def no_fuser(*args, **kwargs): + old_optimize = torch._C._get_graph_executor_optimize(False) + try: + yield + finally: + torch._C._get_graph_executor_optimize(old_optimize) + +def run_baseline_no_fusion(ir, inputs) -> float: + with no_fuser(): + return run_test(ir, inputs) + + +def run_nnc(ir, inputs, dynamic) -> float: + try: + strat = [("DYNAMIC", 10)] if dynamic else [("STATIC", 10)] + old_strat = torch.jit.set_fusion_strategy(strat) + with torch.jit.fuser("fuser1"): + return run_test(ir, inputs) + finally: + torch.jit.set_fusion_strategy(old_strat) + +def run_nvfuser(ir, inputs) -> float: + with torch.jit.fuser("fuser2"): + return run_test(ir, inputs) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/mkldnn.py b/.venv/lib/python3.12/site-packages/torch/utils/mkldnn.py new file mode 100644 index 0000000000000000000000000000000000000000..cc5f5c138e5d4da3a68ec56e8800fc971189b42b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/mkldnn.py @@ -0,0 +1,267 @@ +# mypy: allow-untyped-defs +import functools + +import torch + + +# The Mkldnn* classes subclass torch.jit.ScriptModule, whose metaclass compiles +# @torch.jit.script_method members at class-definition time. Building them lazily +# keeps `import torch.utils.mkldnn` (and its transitive importers) free of any +# TorchScript compilation until MKLDNN conversion is actually used. +@functools.lru_cache(None) +def _get_mkldnn_classes(): + class MkldnnLinear(torch.jit.ScriptModule): + def __init__(self, dense_module, dtype) -> None: + super().__init__() + self.register_buffer('weight', dense_module.weight.to_mkldnn(dtype)) + if dense_module.bias is not None: + # Bias can be fp32 or bf16 for OneDNN bf16 path, but for good accuracy, + # we use fp32 dtype. + self.register_buffer('bias', dense_module.bias.to_mkldnn()) + else: + # TODO: Remove this once ScriptModule supports registering None buffer + self.register_buffer( + 'bias', + torch.zeros([dense_module.weight.size(0)], dtype=torch.float).to_mkldnn()) + + @torch.jit.script_method + def __getstate__(self): + return (self.weight.to_dense(), self.bias.to_dense(), self.training) + + @torch.jit.script_method + def __setstate__(self, state): + self.weight = state[0].to_mkldnn() + self.bias = state[1].to_mkldnn() + self.training = state[2] + + @torch.jit.script_method + def forward(self, x): + x_mkldnn = x if x.is_mkldnn else x.to_mkldnn() + y_mkldnn = torch._C._nn.mkldnn_linear(x_mkldnn, self.weight, self.bias) + y = y_mkldnn if x.is_mkldnn else y_mkldnn.to_dense() + return y + + class _MkldnnConvNd(torch.jit.ScriptModule): + """Common base of MkldnnConv1d and MkldnnConv2d.""" + + __constants__ = ['stride', 'padding', 'dilation', 'groups'] + + def __init__(self, dense_module) -> None: + super().__init__() + + self.stride = dense_module.stride + self.padding = dense_module.padding + self.dilation = dense_module.dilation + self.groups = dense_module.groups + + if dense_module.bias is not None: + self.register_buffer('bias', dense_module.bias.to_mkldnn()) + else: + # Bias can be fp32 or bf16 for OneDNN bf16 path, but for good accuracy, + # we use fp32 dtype. + # TODO: Remove this once ScriptModule supports registering None buffer + self.register_buffer( + 'bias', + torch.zeros([dense_module.weight.size(0)], dtype=torch.float).to_mkldnn()) + + @torch.jit.script_method + def __getstate__(self): + return (self.weight.to_dense(), self.bias.to_dense(), self.training) + + @torch.jit.script_method + def forward(self, x): + return torch.mkldnn_convolution( + x, + self.weight, + self.bias, + self.padding, + self.stride, + self.dilation, + self.groups) + + class MkldnnConv1d(_MkldnnConvNd): + def __init__(self, dense_module, dtype) -> None: + super().__init__(dense_module) + + self.register_buffer('weight', dense_module.weight.to_mkldnn(dtype)) + + @torch.jit.script_method + def __setstate__(self, state): + self.weight = state[0].to_mkldnn() + self.bias = state[1].to_mkldnn() + self.training = state[2] + + class MkldnnConv2d(_MkldnnConvNd): + def __init__(self, dense_module, dtype) -> None: + super().__init__(dense_module) + + self.register_buffer('weight', torch._C._nn.mkldnn_reorder_conv2d_weight( + dense_module.weight.to_mkldnn(dtype), + self.padding, + self.stride, + self.dilation, + self.groups)) + + @torch.jit.script_method + def __setstate__(self, state): + self.weight = torch._C._nn.mkldnn_reorder_conv2d_weight( + state[0].to_mkldnn(), + self.padding, + self.stride, + self.dilation, + self.groups) + self.bias = state[1].to_mkldnn() + self.training = state[2] + + class MkldnnConv3d(_MkldnnConvNd): + def __init__(self, dense_module, dtype) -> None: + super().__init__(dense_module) + + self.register_buffer('weight', torch._C._nn.mkldnn_reorder_conv3d_weight( + dense_module.weight.to_mkldnn(dtype), + self.padding, + self.stride, + self.dilation, + self.groups)) + + @torch.jit.script_method + def __setstate__(self, state): + self.weight = torch._C._nn.mkldnn_reorder_conv3d_weight( + state[0].to_mkldnn(), + self.padding, + self.stride, + self.dilation, + self.groups) + self.bias = state[1].to_mkldnn() + self.training = state[2] + + class MkldnnBatchNorm(torch.jit.ScriptModule): + __constants__ = ['exponential_average_factor', 'eps'] + + def __init__(self, dense_module) -> None: + super().__init__() + + if dense_module.training: + raise AssertionError("Only support eval mode batchnorm for mkldnn path now") + if not dense_module.track_running_stats: + raise AssertionError("Only support track_running_stats=True for mkldnn path now") + if not dense_module.affine: + raise AssertionError("Only support affine=True for mkldnn path now") + + if dense_module.momentum is None: + self.exponential_average_factor = 0.0 + else: + self.exponential_average_factor = dense_module.momentum + self.eps = dense_module.eps + + self.register_buffer('weight', dense_module.weight.to_mkldnn()) + self.register_buffer('bias', dense_module.bias.to_mkldnn()) + self.register_buffer('running_mean', dense_module.running_mean.to_mkldnn()) + self.register_buffer('running_var', dense_module.running_var.to_mkldnn()) + + @torch.jit.script_method + def __getstate__(self): + weight = self.weight.to_dense() + bias = self.bias.to_dense() + running_mean = self.running_mean.to_dense() + running_var = self.running_var.to_dense() + return (weight, bias, running_mean, running_var, self.training) + + @torch.jit.script_method + def __setstate__(self, state): + self.weight = state[0].to_mkldnn() + self.bias = state[1].to_mkldnn() + self.running_mean = state[2].to_mkldnn() + self.running_var = state[3].to_mkldnn() + self.training = state[4] + + @torch.jit.script_method + def forward(self, x): + return torch.batch_norm( + x, + self.weight, + self.bias, + self.running_mean, + self.running_var, + False, # training + self.exponential_average_factor, + self.eps, + False, # cuda_enabled + ) + + class MkldnnPrelu(torch.jit.ScriptModule): + def __init__(self, dense_module, dtype) -> None: + super().__init__() + self.register_buffer('weight', dense_module.weight.to_mkldnn(dtype)) + + @torch.jit.script_method + def __getstate__(self): + return (self.weight.to_dense(), self.training) + + @torch.jit.script_method + def __setstate__(self, state): + self.weight = state[0].to_mkldnn() + self.training = state[1] + + @torch.jit.script_method + def forward(self, x): + x_mkldnn = x if x.is_mkldnn else x.to_mkldnn() + y_mkldnn = torch.prelu(x_mkldnn, self.weight) + y = y_mkldnn if x.is_mkldnn else y_mkldnn.to_dense() + return y + + return { + 'MkldnnLinear': MkldnnLinear, + '_MkldnnConvNd': _MkldnnConvNd, + 'MkldnnConv1d': MkldnnConv1d, + 'MkldnnConv2d': MkldnnConv2d, + 'MkldnnConv3d': MkldnnConv3d, + 'MkldnnBatchNorm': MkldnnBatchNorm, + 'MkldnnPrelu': MkldnnPrelu, + } + + +def __getattr__(name): + classes = _get_mkldnn_classes() + if name in classes: + return classes[name] + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +def to_mkldnn(module, dtype=torch.float): + if dtype not in (torch.float, torch.bfloat16, torch.half): + raise AssertionError("MKLDNN only support float, bfloat16, and half path now") + + classes = _get_mkldnn_classes() + MkldnnLinear = classes['MkldnnLinear'] + MkldnnConv1d = classes['MkldnnConv1d'] + MkldnnConv2d = classes['MkldnnConv2d'] + MkldnnConv3d = classes['MkldnnConv3d'] + MkldnnBatchNorm = classes['MkldnnBatchNorm'] + MkldnnPrelu = classes['MkldnnPrelu'] + + def m_fn(m, d): + if isinstance(m, torch.nn.Linear): + return MkldnnLinear(m, d) + elif isinstance(m, torch.nn.Conv1d): + return MkldnnConv1d(m, d) + elif isinstance(m, torch.nn.Conv2d): + return MkldnnConv2d(m, d) + elif isinstance(m, torch.nn.Conv3d): + return MkldnnConv3d(m, d) + elif isinstance(m, (torch.nn.BatchNorm2d, torch.nn.BatchNorm3d)): + # For batchnorm bf16 path, OneDNN requires weight and bias need fp32 dtype. + # so it doesn't need dtype argument. + return MkldnnBatchNorm(m) + elif isinstance(m, torch.nn.PReLU): + return MkldnnPrelu(m, d) + else: + return m + + def m_fn_rec(m, d): + new_m = m_fn(m, d) + for name, sub_m in m.named_children(): + setattr(new_m, name, m_fn_rec(sub_m, d)) + return new_m + + return m_fn_rec(module, dtype) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/mobile_optimizer.py b/.venv/lib/python3.12/site-packages/torch/utils/mobile_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..12073c3b8061067289d0cd5c65184416c0193c03 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/mobile_optimizer.py @@ -0,0 +1,135 @@ +# mypy: allow-untyped-defs +"""This module contains utility method for mobile model optimization and lint.""" + +import torch +from enum import Enum +from torch._C import _MobileOptimizerType as MobileOptimizerType +from typing import AnyStr + +class LintCode(Enum): + BUNDLED_INPUT = 1 + REQUIRES_GRAD = 2 + DROPOUT = 3 + BATCHNORM = 4 + +def optimize_for_mobile( + script_module: torch.jit.ScriptModule, + optimization_blocklist: set[MobileOptimizerType] | None = None, + preserved_methods: list[AnyStr] | None = None, + backend: str = 'CPU') -> torch.jit.RecursiveScriptModule: + """ + Optimize a torch script module for mobile deployment. + + Args: + script_module: An instance of torch script module with type of ScriptModule. + optimization_blocklist: A set with type of MobileOptimizerType. When set is not passed, + optimization method will run all the optimizer pass; otherwise, optimizer + method will run the optimization pass that is not included inside optimization_blocklist. + preserved_methods: A list of methods that needed to be preserved when freeze_module pass is invoked + backend: Device type to use for running the result model ('CPU'(default), 'Vulkan' or 'Metal'). + Returns: + A new optimized torch script module + """ + if not isinstance(script_module, torch.jit.ScriptModule): + raise TypeError( + f'Got {type(script_module)}, but ScriptModule is expected.') + + if optimization_blocklist is None: + optimization_blocklist = set() + + if preserved_methods is None: + preserved_methods = [] + + # Convert potential byte arrays into strings (if there is any) to pass type checking + # Here we use a new name as assigning it back to preserved_methods will invoke + # mypy errors (i.e. List[AnyStr] = List[str]) + preserved_methods_str: list[str] = [str(method) for method in preserved_methods] + + bundled_inputs_attributes = _get_bundled_inputs_preserved_attributes(script_module, preserved_methods_str) + if all(hasattr(script_module, method) for method in bundled_inputs_attributes): + preserved_methods_str = list(set(preserved_methods_str + bundled_inputs_attributes)) + + non_exist_methods = [method for method in preserved_methods_str if not hasattr(script_module, method)] + if non_exist_methods: + raise AttributeError( + f"The following methods to preserve do not exist in script_module: {', '.join(non_exist_methods)}") + + backend = backend.lower() + if backend == 'cpu': + optimized_cpp_module = torch._C._jit_pass_optimize_for_mobile( + script_module._c, + optimization_blocklist, + preserved_methods_str) + elif backend == 'vulkan': + optimized_cpp_module = torch._C._jit_pass_vulkan_optimize_for_mobile( + script_module._c, + optimization_blocklist, + preserved_methods_str) + elif backend == 'metal': + optimized_cpp_module = torch._C._jit_pass_metal_optimize_for_mobile(script_module._c, preserved_methods_str) + else: + raise TypeError("Unknown backend, must be one of 'CPU', 'Vulkan' or 'Metal'") + + return torch.jit._recursive.wrap_cpp_module(optimized_cpp_module) + + +def generate_mobile_module_lints(script_module: torch.jit.ScriptModule): + """ + Generate a list of lints for a given torch script module. + + Args: + script_module: An instance of torch script module with type of ScriptModule. + + Returns: + lint_map: A list of dictionary that contains modules lints + """ + if not isinstance(script_module, torch.jit.ScriptModule): + raise TypeError( + f'Got {type(script_module)}, but ScriptModule is expected.') + + lint_list = [] + + if not hasattr(script_module, "_generate_bundled_inputs_for_forward"): + lint_list.append({"name": LintCode.BUNDLED_INPUT.name, "message": "No bundled input for forward, please add bundled inputs " + "before saving the module using torch.utils.bundled_inputs.augment_model_with_bundled_inputs."}) + + for name, param in script_module.named_parameters(): + if param.requires_grad: + lint_list.append({"name": LintCode.REQUIRES_GRAD.name, "message": f"Param {name} requires grad, " + "please set torch.no_grad() to reduce memory usage and improve computation speed during " + "inference phase."}) + + op_names = torch.jit.export_opnames(script_module) + for op_name in op_names: + if "dropout" in op_name: + lint_list.append({"name": LintCode.DROPOUT.name, + "message": f"Operator {op_name} exists, remember to call eval() before " + "saving the module and call torch.utils.mobile_optimizer.optimize_for_mobile to drop dropout " + "operator."}) + if "batch_norm" in op_name: + lint_list.append({"name": LintCode.BATCHNORM.name, + "message": f"Operator {op_name} exists, remember to call eval() before " + "saving the module and call torch.utils.mobile_optimizer.optimize_for_mobile to drop batch_norm " + "operator."}) + + return lint_list + +def _get_bundled_inputs_preserved_attributes(script_module: torch.jit.ScriptModule, preserved_methods: list[str]) -> list[str]: + + bundled_inputs_attributes = [] + # Has bundled inputs for forward + if hasattr(script_module, 'get_all_bundled_inputs'): + bundled_inputs_attributes.append('get_all_bundled_inputs') + bundled_inputs_attributes.append('get_num_bundled_inputs') + + # Bundled inputs in module after the change that introduced bundled inputs for multiple functions + if hasattr(script_module, 'get_bundled_inputs_functions_and_info'): + bundled_inputs_attributes.append('get_bundled_inputs_functions_and_info') + all_info = script_module.get_bundled_inputs_functions_and_info() + for function_name in all_info: + if function_name not in preserved_methods: + bundled_inputs_attributes.append(function_name) + bundled_inputs_attributes.append("get_all_bundled_inputs_for_" + function_name) + bundled_inputs_attributes.append("_bundled_inputs_deflated_" + function_name) + + return bundled_inputs_attributes diff --git a/.venv/lib/python3.12/site-packages/torch/utils/model_dump/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/model_dump/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..16d1ab1c6dd1a2d422cae74eaa5b5888dd2fa175 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/model_dump/__init__.py @@ -0,0 +1,450 @@ +#!/usr/bin/env python3 +# mypy: allow-untyped-defs +""" +model_dump: a one-stop shop for TorchScript model inspection. + +The goal of this tool is to provide a simple way to extract lots of +useful information from a TorchScript model and make it easy for humans +to consume. It (mostly) replaces zipinfo, common uses of show_pickle, +and various ad-hoc analysis notebooks. + +The tool extracts information from the model and serializes it as JSON. +That JSON can then be rendered by an HTML+JS page, either by +loading the JSON over HTTP or producing a fully self-contained page +with all of the code and data burned-in. +""" + +# Maintainer notes follow. +""" +The implementation strategy has tension between 3 goals: +- Small file size. +- Fully self-contained. +- Easy, modern JS environment. +Using Preact and HTM achieves 1 and 2 with a decent result for 3. +However, the models I tested with result in ~1MB JSON output, +so even using something heavier like full React might be tolerable +if the build process can be worked out. + +One principle I have followed that I think is very beneficial +is to keep the JSON data as close as possible to the model +and do most of the rendering logic on the client. +This makes for easier development (just refresh, usually), +allows for more laziness and dynamism, and lets us add more +views of the same data without bloating the HTML file. + +Currently, this code doesn't actually load the model or even +depend on any part of PyTorch. I don't know if that's an important +feature to maintain, but it's probably worth preserving the ability +to run at least basic analysis on models that cannot be loaded. + +I think the easiest way to develop this code is to cd into model_dump and +run "python -m http.server", then load http://localhost:8000/skeleton.html +in the browser. In another terminal, run +"python -m torch.utils.model_dump --style=json FILE > \ + torch/utils/model_dump/model_info.json" +every time you update the Python code or model. +When you update JS, just refresh. + +Possible improvements: + - Fix various TODO comments in this file and the JS. + - Make the HTML much less janky, especially the auxiliary data panel. + - Make the auxiliary data panel start small, expand when + data is available, and have a button to clear/contract. + - Clean up the JS. There's a lot of copypasta because + I don't really know how to use Preact. + - Make the HTML render and work nicely inside a Jupyter notebook. + - Add the ability for JS to choose the URL to load the JSON based + on the page URL (query or hash). That way we could publish the + inlined skeleton once and have it load various JSON blobs. + - Add a button to expand all expandable sections so ctrl-F works well. + - Add hyperlinking from data to code, and code to code. + - Add hyperlinking from debug info to Diffusion. + - Make small tensor contents available. + - Do something nice for quantized models + (they probably don't work at all right now). +""" + +import argparse +import io +import itertools +import json +import os +import pickle +import pprint +import re +import sys +import urllib.parse +import zipfile +from pathlib import Path +import warnings + +import torch.utils.show_pickle + + +DEFAULT_EXTRA_FILE_SIZE_LIMIT = 16 * 1024 + +__all__ = ['get_storage_info', 'hierarchical_pickle', 'get_model_info', 'get_inline_skeleton', + 'burn_in_info', 'get_info_and_burn_skeleton'] + +def get_storage_info(storage): + if not isinstance(storage, torch.utils.show_pickle.FakeObject): + raise AssertionError(f"storage is not FakeObject: {type(storage)}") + if storage.module != "pers": + raise AssertionError(f"storage.module is not 'pers': {storage.module!r}") + if storage.name != "obj": + raise AssertionError(f"storage.name is not 'obj': {storage.name!r}") + if storage.state is not None: + raise AssertionError(f"storage.state is not None: {storage.state!r}") + if not isinstance(storage.args, tuple): + raise AssertionError(f"storage.args is not a tuple: {type(storage.args)}") + if len(storage.args) != 1: + raise AssertionError(f"len(storage.args) is not 1: {len(storage.args)}") + sa = storage.args[0] + if not isinstance(sa, tuple): + raise AssertionError(f"sa is not a tuple: {type(sa)}") + if len(sa) != 5: + raise AssertionError(f"len(sa) is not 5: {len(sa)}") + if sa[0] != "storage": + raise AssertionError(f"sa[0] is not 'storage': {sa[0]!r}") + if not isinstance(sa[1], torch.utils.show_pickle.FakeClass): + raise AssertionError(f"sa[1] is not FakeClass: {type(sa[1])}") + if sa[1].module != "torch": + raise AssertionError(f"sa[1].module is not 'torch': {sa[1].module!r}") + if not sa[1].name.endswith("Storage"): + raise AssertionError(f"sa[1].name does not end with 'Storage': {sa[1].name!r}") + storage_info = [sa[1].name.replace("Storage", "")] + list(sa[2:]) + return storage_info + + +def hierarchical_pickle(data): + if isinstance(data, (bool, int, float, str, type(None))): + return data + if isinstance(data, list): + return [hierarchical_pickle(d) for d in data] + if isinstance(data, tuple): + return { + "__tuple_values__": hierarchical_pickle(list(data)), + } + if isinstance(data, dict): + return { + "__is_dict__": True, + "keys": hierarchical_pickle(list(data.keys())), + "values": hierarchical_pickle(list(data.values())), + } + if isinstance(data, torch.utils.show_pickle.FakeObject): + typename = f"{data.module}.{data.name}" + if ( + typename.startswith(('__torch__.', 'torch.jit.LoweredWrapper.', 'torch.jit.LoweredModule.')) + ): + if data.args != (): + raise AssertionError("data.args is not ()") + return { + "__module_type__": typename, + "state": hierarchical_pickle(data.state), + } + if typename == "torch._utils._rebuild_tensor_v2": + if data.state is not None: + raise AssertionError("data.state is not None") + storage, offset, size, stride, requires_grad, *_ = data.args + storage_info = get_storage_info(storage) + return {"__tensor_v2__": [storage_info, offset, size, stride, requires_grad]} + if typename == "torch._utils._rebuild_qtensor": + if data.state is not None: + raise AssertionError("data.state is not None") + storage, offset, size, stride, quantizer, requires_grad, *_ = data.args + storage_info = get_storage_info(storage) + if not isinstance(quantizer, tuple): + raise AssertionError("quantizer is not a tuple") + if not isinstance(quantizer[0], torch.utils.show_pickle.FakeClass): + raise AssertionError("quantizer[0] is not a FakeClass") + if quantizer[0].module != "torch": + raise AssertionError("quantizer[0].module is not torch") + if quantizer[0].name == "per_tensor_affine": + if len(quantizer) != 3: + raise AssertionError("len(quantizer) is not 3") + if not isinstance(quantizer[1], float): + raise AssertionError("quantizer[1] is not a float") + if not isinstance(quantizer[2], int): + raise AssertionError("quantizer[2] is not an int") + quantizer_extra = list(quantizer[1:3]) + else: + quantizer_extra = [] + quantizer_json = [quantizer[0].name] + quantizer_extra + return {"__qtensor__": [storage_info, offset, size, stride, quantizer_json, requires_grad]} + if typename == "torch.jit._pickle.restore_type_tag": + if data.state is not None: + raise AssertionError("data.state is not None") + obj, typ = data.args + if not isinstance(typ, str): + raise AssertionError("typ is not a string") + return hierarchical_pickle(obj) + if re.fullmatch(r"torch\.jit\._pickle\.build_[a-z]+list", typename): + if data.state is not None: + raise AssertionError("data.state is not None") + ls, = data.args + if not isinstance(ls, list): + raise AssertionError("ls is not a list") + return hierarchical_pickle(ls) + if typename == "torch.device": + if data.state is not None: + raise AssertionError("data.state is not None") + name, = data.args + if not isinstance(name, str): + raise AssertionError("name is not a string") + # Just forget that it was a device and return the name. + return name + if typename == "builtin.UnicodeDecodeError": + if data.state is not None: + raise AssertionError("data.state is not None") + msg, = data.args + if not isinstance(msg, str): + raise AssertionError("msg is not a string") + # Hack: Pretend this is a module so we don't need custom serialization. + # Hack: Wrap the message in a tuple so it looks like a nice state object. + # TODO: Undo at least that second hack. We should support string states. + return { + "__module_type__": typename, + "state": hierarchical_pickle((msg,)), + } + raise Exception(f"Can't prepare fake object of type for JS: {typename}") # noqa: TRY002 + raise Exception(f"Can't prepare data of type for JS: {type(data)}") # noqa: TRY002 + + +def get_model_info( + path_or_file, + title=None, + extra_file_size_limit=DEFAULT_EXTRA_FILE_SIZE_LIMIT): + """Get JSON-friendly information about a model. + + The result is suitable for being saved as model_info.json, + or passed to burn_in_info. + """ + + if isinstance(path_or_file, os.PathLike): + default_title = os.fspath(path_or_file) + file_size = path_or_file.stat().st_size # type: ignore[attr-defined] + elif isinstance(path_or_file, str): + default_title = path_or_file + file_size = Path(path_or_file).stat().st_size + else: + default_title = "buffer" + path_or_file.seek(0, io.SEEK_END) + file_size = path_or_file.tell() + path_or_file.seek(0) + + title = title or default_title + + with zipfile.ZipFile(path_or_file) as zf: + path_prefix = None + zip_files = [] + # pyrefly: ignore [bad-assignment] + for zi in zf.infolist(): + prefix = re.sub("/.*", "", zi.filename) + if path_prefix is None: + path_prefix = prefix + elif prefix != path_prefix: + raise Exception(f"Mismatched prefixes: {path_prefix} != {prefix}") # noqa: TRY002 + zip_files.append( + { + "filename": zi.filename, + "compression": zi.compress_type, + "compressed_size": zi.compress_size, + "file_size": zi.file_size, + } + ) + if path_prefix is None: + raise AssertionError("path_prefix is None") + version = zf.read(path_prefix + "/version").decode("utf-8").strip() + + def get_pickle(name): + if path_prefix is None: + raise AssertionError("path_prefix is None") + with zf.open(path_prefix + f"/{name}.pkl") as handle: + raw = torch.utils.show_pickle.DumpUnpickler(handle, catch_invalid_utf8=True).load() + return hierarchical_pickle(raw) + + model_data = get_pickle("data") + constants = get_pickle("constants") + + # Intern strings that are likely to be reused. + # Pickle automatically detects shared structure, + # so reused strings are stored efficiently. + # However, JSON has no way of representing this, + # so we have to do it manually. + interned_strings : dict[str, int] = {} + + def intern(s): + if s not in interned_strings: + interned_strings[s] = len(interned_strings) + return interned_strings[s] + + code_files = {} + for zi in zf.infolist(): + if not zi.filename.endswith(".py"): + continue + with zf.open(zi) as handle: + raw_code = handle.read() + with zf.open(zi.filename + ".debug_pkl") as handle: + raw_debug = handle.read() + + # Parse debug info and add begin/end markers if not present + # to ensure that we cover the entire source code. + debug_info_t = pickle.loads(raw_debug) + text_table = None + + if (len(debug_info_t) == 3 and + isinstance(debug_info_t[0], str) and + debug_info_t[0] == 'FORMAT_WITH_STRING_TABLE'): + _, text_table, content = debug_info_t + + def parse_new_format(line): + # (0, (('', '', 0), 0, 0)) + num, ((text_indexes, fname_idx, offset), start, end), tag = line + text = ''.join(text_table[x] for x in text_indexes) # type: ignore[index] + fname = text_table[fname_idx] # type: ignore[index] + return num, ((text, fname, offset), start, end), tag + + debug_info_t = map(parse_new_format, content) + + debug_info = list(debug_info_t) + if not debug_info: + debug_info.append((0, (('', '', 0), 0, 0))) + if debug_info[-1][0] != len(raw_code): + debug_info.append((len(raw_code), (('', '', 0), 0, 0))) + + code_parts = [] + for di, di_next in itertools.pairwise(debug_info): + start, source_range, *_ = di + end = di_next[0] + if end <= start: + raise AssertionError("end is not greater than start") + source, s_start, s_end = source_range + s_text, s_file, s_line = source + # TODO: Handle this case better. TorchScript ranges are in bytes, + # but JS doesn't really handle byte strings. + # if bytes and chars are not equivalent for this string, + # zero out the ranges so we don't highlight the wrong thing. + if len(s_text) != len(s_text.encode("utf-8")): + s_start = 0 + s_end = 0 + text = raw_code[start:end] + code_parts.append([text.decode("utf-8"), intern(s_file), s_line, intern(s_text), s_start, s_end]) + code_files[zi.filename] = code_parts + + extra_files_json_pattern = re.compile(re.escape(path_prefix) + "/extra/.*\\.json") + extra_files_jsons = {} + for zi in zf.infolist(): + if not extra_files_json_pattern.fullmatch(zi.filename): + continue + if zi.file_size > extra_file_size_limit: + continue + with zf.open(zi) as handle: + try: + json_content = json.load(handle) + extra_files_jsons[zi.filename] = json_content + except json.JSONDecodeError: + extra_files_jsons[zi.filename] = "INVALID JSON" + + always_render_pickles = { + "bytecode.pkl", + } + extra_pickles = {} + for zi in zf.infolist(): + if not zi.filename.endswith(".pkl"): + continue + with zf.open(zi) as handle: + # TODO: handle errors here and just ignore the file? + # NOTE: For a lot of these files (like bytecode), + # we could get away with just unpickling, but this should be safer. + obj = torch.utils.show_pickle.DumpUnpickler(handle, catch_invalid_utf8=True).load() + buf = io.StringIO() + pprint.pprint(obj, buf) + contents = buf.getvalue() + # Checked the rendered length instead of the file size + # because pickles with shared structure can explode in size during rendering. + if os.path.basename(zi.filename) not in always_render_pickles and \ + len(contents) > extra_file_size_limit: + continue + extra_pickles[zi.filename] = contents + + return { + "model": { + "title": title, + "file_size": file_size, + "version": version, + "zip_files": zip_files, + "interned_strings": list(interned_strings), + "code_files": code_files, + "model_data": model_data, + "constants": constants, + "extra_files_jsons": extra_files_jsons, + "extra_pickles": extra_pickles, + } + } + + +def get_inline_skeleton(): + """Get a fully-inlined skeleton of the frontend. + + The returned HTML page has no external network dependencies for code. + It can load model_info.json over HTTP, or be passed to burn_in_info. + """ + + import importlib.resources + + # pyrefly: ignore [bad-argument-type] + skeleton = importlib.resources.read_text(__package__, "skeleton.html") + # pyrefly: ignore [bad-argument-type] + js_code = importlib.resources.read_text(__package__, "code.js") + for js_module in ["preact", "htm"]: + # pyrefly: ignore [bad-argument-type] + js_lib = importlib.resources.read_binary(__package__, f"{js_module}.mjs") + js_url = "data:application/javascript," + urllib.parse.quote(js_lib) + js_code = js_code.replace(f"https://unpkg.com/{js_module}?module", js_url) + skeleton = skeleton.replace(' src="./code.js">', ">\n" + js_code) + return skeleton + + +def burn_in_info(skeleton, info): + """Burn model info into the HTML skeleton. + + The result will render the hard-coded model info and + have no external network dependencies for code or data. + """ + + # Note that Python's json serializer does not escape slashes in strings. + # Since we're inlining this JSON directly into a script tag, a string + # containing "" would end the script prematurely and + # mess up our page. Unconditionally escape fixes that. + return skeleton.replace( + "BURNED_IN_MODEL_INFO = null", + "BURNED_IN_MODEL_INFO = " + json.dumps(info, sort_keys=True).replace("/", "\\/")) + + +def get_info_and_burn_skeleton(path_or_bytesio, **kwargs): + model_info = get_model_info(path_or_bytesio, **kwargs) + skeleton = get_inline_skeleton() + page = burn_in_info(skeleton, model_info) + return page + + +def main(argv, *, stdout=None) -> None: + warnings.warn("torch.utils.model_dump is deprecated and will be removed in a future PyTorch release.", stacklevel=2) + parser = argparse.ArgumentParser() + parser.add_argument("--style", choices=["json", "html"]) + parser.add_argument("--title") + parser.add_argument("model") + args = parser.parse_args(argv[1:]) + + info = get_model_info(args.model, title=args.title) + + output = stdout or sys.stdout + + if args.style == "json": + output.write(json.dumps(info, sort_keys=True) + "\n") + elif args.style == "html": + skeleton = get_inline_skeleton() + page = burn_in_info(skeleton, info) + output.write(page) + else: + raise Exception("Invalid style") # noqa: TRY002 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/model_dump/__main__.py b/.venv/lib/python3.12/site-packages/torch/utils/model_dump/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..5d4bdac389bb1f270d74efb6c876258d46077110 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/model_dump/__main__.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python3 +import sys +from . import main + +sys.exit(main(sys.argv)) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/model_dump/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/model_dump/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2facfc56a1a5d5279be79a533d5ababb0e3167a2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/model_dump/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/model_dump/__pycache__/__main__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/model_dump/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82b3b24fdab4c22f00b39d4969a9adfcbec0abfd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/model_dump/__pycache__/__main__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/model_dump/code.js b/.venv/lib/python3.12/site-packages/torch/utils/model_dump/code.js new file mode 100644 index 0000000000000000000000000000000000000000..173ddfb639d847159ee4fdf46691404bf1bbb7a3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/model_dump/code.js @@ -0,0 +1,689 @@ +import { h, Component, render } from 'https://unpkg.com/preact?module'; +import htm from 'https://unpkg.com/htm?module'; + +const html = htm.bind(h); + +const BURNED_IN_MODEL_INFO = null; + +// https://stackoverflow.com/a/20732091 +function humanFileSize(size) { + if (size == 0) { return "0 B"; } + var i = Math.floor( Math.log(size) / Math.log(1024) ); + return (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i]; +} + +function caret(down) { + return down ? "\u25BE" : "\u25B8"; +} + +class Blamer { + constructor() { + this.blame_on_click = false; + this.aux_content_pane = null; + } + + setAuxContentPane(pane) { + this.aux_content_pane = pane; + } + + readyBlame() { + this.blame_on_click = true; + } + + maybeBlame(arg) { + if (!this.blame_on_click) { + return; + } + this.blame_on_click = false; + if (!this.aux_content_pane) { + return; + } + this.aux_content_pane.doBlame(arg); + } +} + +let blame = new Blamer(); + +class Hider extends Component { + constructor() { + super(); + this.state = { shown: null }; + } + + componentDidMount() { + this.setState({ shown: this.props.shown === "true" }); + } + + render({name, children}, {shown}) { + let my_caret = html` this.click()} >${caret(shown)}`; + return html`
+

${my_caret} ${name}

+
${shown ? this.props.children : []}
`; + } + + click() { + this.setState({shown: !this.state.shown}); + } +} + +function ModelSizeSection({model: {file_size, zip_files}}) { + let store_size = 0; + let compr_size = 0; + for (const zi of zip_files) { + if (zi.compression === 0) { + // TODO: Maybe check that compressed_size === file_size. + store_size += zi.compressed_size; + } else { + compr_size += zi.compressed_size; + } + } + let zip_overhead = file_size - store_size - compr_size; + // TODO: Better formatting. Right-align this. + return html` + <${Hider} name="Model Size" shown=true> +
.
+      Model size: ${file_size} (${humanFileSize(file_size)})
+      Stored files: ${store_size} (${humanFileSize(store_size)})
+      Compressed files: ${compr_size} (${humanFileSize(compr_size)})
+      Zip overhead: ${zip_overhead} (${humanFileSize(zip_overhead)})
+    
`; +} + +function StructuredDataSection({name, data, shown}) { + return html` + <${Hider} name=${name} shown=${shown}> +
+ <${StructuredData} data=${data} indent="" prefix=""/> +
`; +} + +class StructuredData extends Component { + constructor() { + super(); + this.state = { shown: false }; + + this.INLINE_TYPES = new Set(["boolean", "number", "string"]) + this.IGNORED_STATE_KEYS = new Set(["training", "_is_full_backward_hook"]) + } + + click() { + this.setState({shown: !this.state.shown}); + } + + expando(data) { + if (data === null || this.INLINE_TYPES.has(typeof(data))) { + return false; + } + if (typeof(data) != "object") { + throw new Error("Not an object"); + } + if (Array.isArray(data)) { + // TODO: Maybe show simple lists and tuples on one line. + return true; + } + if (data.__tuple_values__) { + // TODO: Maybe show simple lists and tuples on one line. + return true; + } + if (data.__is_dict__) { + // TODO: Maybe show simple (empty?) dicts on one line. + return true; + } + if (data.__module_type__) { + return true; + } + if (data.__tensor_v2__) { + return false; + } + if (data.__qtensor__) { + return false; + } + throw new Error("Can't handle data type.", data); + } + + renderHeadline(data) { + if (data === null) { + return "None"; + } + if (typeof(data) == "boolean") { + const sd = String(data); + return sd.charAt(0).toUpperCase() + sd.slice(1); + } + if (typeof(data) == "number") { + return JSON.stringify(data); + } + if (typeof(data) == "string") { + return JSON.stringify(data); + } + if (typeof(data) != "object") { + throw new Error("Not an object"); + } + if (Array.isArray(data)) { + return "list(["; + } + if (data.__tuple_values__) { + return "tuple(("; + } + if (data.__is_dict__) { + return "dict({"; + } + if (data.__module_type__) { + return data.__module_type__ + "()"; + } + if (data.__tensor_v2__) { + const [storage, offset, size, stride, grad] = data.__tensor_v2__; + const [dtype, key, device, numel] = storage; + return this.renderTensor( + "tensor", dtype, key, device, numel, offset, size, stride, grad, []); + } + if (data.__qtensor__) { + const [storage, offset, size, stride, quantizer, grad] = data.__qtensor__; + const [dtype, key, device, numel] = storage; + let extra_parts = []; + if (quantizer[0] == "per_tensor_affine") { + extra_parts.push(`scale=${quantizer[1]}`); + extra_parts.push(`zero_point=${quantizer[2]}`); + } else { + extra_parts.push(`quantizer=${quantizer[0]}`); + } + return this.renderTensor( + "qtensor", dtype, key, device, numel, offset, size, stride, grad, extra_parts); + } + throw new Error("Can't handle data type.", data); + } + + renderTensor( + prefix, + dtype, + storage_key, + device, + storage_numel, + offset, + size, + stride, + grad, + extra_parts) { + let parts = [ + "(" + size.join(",") + ")", + dtype, + ]; + parts.push(...extra_parts); + if (device != "cpu") { + parts.push(device); + } + if (grad) { + parts.push("grad"); + } + // TODO: Check stride and indicate if the tensor is channels-last or non-contiguous + // TODO: Check size, stride, offset, and numel and indicate if + // the tensor doesn't use all data in storage. + // TODO: Maybe show key? + void(offset); + void(stride); + void(storage_key); + void(storage_numel); + return prefix + "(" + parts.join(", ") + ")"; + } + + renderBody(indent, data) { + if (data === null || this.INLINE_TYPES.has(typeof(data))) { + throw "Should not reach here." + } + if (typeof(data) != "object") { + throw new Error("Not an object"); + } + if (Array.isArray(data)) { + let new_indent = indent + "\u00A0\u00A0"; + let parts = []; + for (let idx = 0; idx < data.length; idx++) { + // Does it make sense to put explicit index numbers here? + parts.push(html`
<${StructuredData} prefix=${idx + ": "} indent=${new_indent} data=${data[idx]} />`); + } + return parts; + } + if (data.__tuple_values__) { + // Handled the same as lists. + return this.renderBody(indent, data.__tuple_values__); + } + if (data.__is_dict__) { + let new_indent = indent + "\u00A0\u00A0"; + let parts = []; + for (let idx = 0; idx < data.keys.length; idx++) { + if (typeof(data.keys[idx]) != "string") { + parts.push(html`
${new_indent}Non-string key`); + } else { + parts.push(html`
<${StructuredData} prefix=${data.keys[idx] + ": "} indent=${new_indent} data=${data.values[idx]} />`); + } + } + return parts; + } + if (data.__module_type__) { + const mstate = data.state; + if (mstate === null || typeof(mstate) != "object") { + throw new Error("Bad module state"); + } + let new_indent = indent + "\u00A0\u00A0"; + let parts = []; + if (mstate.__is_dict__) { + // TODO: Less copy/paste between this and normal dicts. + for (let idx = 0; idx < mstate.keys.length; idx++) { + if (typeof(mstate.keys[idx]) != "string") { + parts.push(html`
${new_indent}Non-string key`); + } else if (this.IGNORED_STATE_KEYS.has(mstate.keys[idx])) { + // Do nothing. + } else { + parts.push(html`
<${StructuredData} prefix=${mstate.keys[idx] + ": "} indent=${new_indent} data=${mstate.values[idx]} />`); + } + } + } else if (mstate.__tuple_values__) { + parts.push(html`
<${StructuredData} prefix="" indent=${new_indent} data=${mstate} />`); + } else if (mstate.__module_type__) { + // We normally wouldn't have the state of a module be another module, + // but we use "modules" to encode special values (like Unicode decode + // errors) that might be valid states. Just go with it. + parts.push(html`
<${StructuredData} prefix="" indent=${new_indent} data=${mstate} />`); + } else { + throw new Error("Bad module state"); + } + return parts; + } + if (data.__tensor_v2__) { + throw "Should not reach here." + } + if (data.__qtensor__) { + throw "Should not reach here." + } + throw new Error("Can't handle data type.", data); + } + + render({data, indent, prefix}, {shown}) { + const exp = this.expando(data) ? html` this.click()} >${caret(shown)} ` : ""; + const headline = this.renderHeadline(data); + const body = shown ? this.renderBody(indent, data) : ""; + return html`${indent}${exp}${prefix}${headline}${body}`; + } +} + +function ZipContentsSection({model: {zip_files}}) { + // TODO: Add human-readable sizes? + // TODO: Add sorting options? + // TODO: Add hierarchical collapsible tree? + return html` + <${Hider} name="Zip Contents" shown=false> + + + + + + + + + + + ${zip_files.map(zf => html` + + + + + `)} + +
ModeSizeCompressedName
${{0: "store", 8: "deflate"}[zf.compression] || zf.compression}${zf.file_size}${zf.compressed_size}${zf.filename}
`; +} + +function CodeSection({model: {code_files}}) { + return html` + <${Hider} name="Code" shown=false> +
+ ${Object.entries(code_files).map(([fn, code]) => html`<${OneCodeSection} + filename=${fn} code=${code} />`)} +
`; +} + +class OneCodeSection extends Component { + constructor() { + super(); + this.state = { shown: false }; + } + + click() { + const shown = !this.state.shown; + this.setState({shown: shown}); + } + + render({filename, code}, {shown}) { + const header = html` +

+ this.click()} >${caret(shown)} + ${filename}

+ `; + if (!shown) { + return header; + } + return html` + ${header} +
${code.map(c => this.renderBlock(c))}
+ `; + } + + renderBlock([text, ist_file, line, ist_s_text, s_start, s_end]) { + return html` blame.maybeBlame({ist_file, line, ist_s_text, s_start, s_end})} + >${text}`; + } +} + +function ExtraJsonSection({files}) { + return html` + <${Hider} name="Extra files (JSON)" shown=false> +
+

Use "Log Raw Model Info" for hierarchical view in browser console.

+ ${Object.entries(files).map(([fn, json]) => html`<${OneJsonSection} + filename=${fn} json=${json} />`)} +
`; +} + +class OneJsonSection extends Component { + constructor() { + super(); + this.state = { shown: false }; + } + + click() { + const shown = !this.state.shown; + this.setState({shown: shown}); + } + + render({filename, json}, {shown}) { + const header = html` +

+ this.click()} >${caret(shown)} + ${filename}

+ `; + if (!shown) { + return header; + } + return html` + ${header} +
${JSON.stringify(json, null, 2)}
+ `; + } +} + +function ExtraPicklesSection({files}) { + return html` + <${Hider} name="Extra Pickles" shown=false> +
+ ${Object.entries(files).map(([fn, content]) => html`<${OnePickleSection} + filename=${fn} content=${content} />`)} +
`; +} + +class OnePickleSection extends Component { + constructor() { + super(); + this.state = { shown: false }; + } + + click() { + const shown = !this.state.shown; + this.setState({shown: shown}); + } + + render({filename, content}, {shown}) { + const header = html` +

+ this.click()} >${caret(shown)} + ${filename}

+ `; + if (!shown) { + return header; + } + return html` + ${header} +
${content}
+ `; + } +} + +function assertStorageAreEqual(key, lhs, rhs) { + if (lhs.length !== rhs.length || + !lhs.every((val, idx) => val === rhs[idx])) { + throw new Error("Storage mismatch for key '" + key + "'"); + } +} + +function computeTensorMemory(numel, dtype) { + const sizes = { + "Byte": 1, + "Char": 1, + "Short": 2, + "Int": 4, + "Long": 8, + "Half": 2, + "Float": 4, + "Double": 8, + "ComplexHalf": 4, + "ComplexFloat": 8, + "ComplexDouble": 16, + "Bool": 1, + "QInt8": 1, + "QUInt8": 1, + "QInt32": 4, + "BFloat16": 2, + }; + let dtsize = sizes[dtype]; + if (!dtsize) { + throw new Error("Unrecognized dtype: " + dtype); + } + return numel * dtsize; +} + +// TODO: Maybe track by dtype as well. +// TODO: Maybe distinguish between visible size and storage size. +function getTensorStorages(data) { + if (data === null) { + return new Map(); + } + if (typeof(data) == "boolean") { + return new Map(); + } + if (typeof(data) == "number") { + return new Map(); + } + if (typeof(data) == "string") { + return new Map(); + } + if (typeof(data) != "object") { + throw new Error("Not an object"); + } + if (Array.isArray(data)) { + let result = new Map(); + for (const item of data) { + const tensors = getTensorStorages(item); + for (const [key, storage] of tensors.entries()) { + if (!result.has(key)) { + result.set(key, storage); + } else { + const old_storage = result.get(key); + assertStorageAreEqual(key, old_storage, storage); + } + } + } + return result; + } + if (data.__tuple_values__) { + return getTensorStorages(data.__tuple_values__); + } + if (data.__is_dict__) { + return getTensorStorages(data.values); + } + if (data.__module_type__) { + return getTensorStorages(data.state); + } + if (data.__tensor_v2__) { + const [storage, offset, size, stride, grad] = data.__tensor_v2__; + const [dtype, key, device, numel] = storage; + return new Map([[key, storage]]); + } + if (data.__qtensor__) { + const [storage, offset, size, stride, quantizer, grad] = data.__qtensor__; + const [dtype, key, device, numel] = storage; + return new Map([[key, storage]]); + } + throw new Error("Can't handle data type.", data); +} + +function getTensorMemoryByDevice(pickles) { + let all_tensors = []; + for (const [name, pickle] of pickles) { + const tensors = getTensorStorages(pickle); + all_tensors.push(...tensors.values()); + } + let result = {}; + for (const storage of all_tensors.values()) { + const [dtype, key, device, numel] = storage; + const size = computeTensorMemory(numel, dtype); + result[device] = (result[device] || 0) + size; + } + return result; +} + +// Make this a separate component so it is rendered lazily. +class OpenTensorMemorySection extends Component { + render({model: {model_data, constants}}) { + let sizes = getTensorMemoryByDevice(new Map([ + ["data", model_data], + ["constants", constants], + ])); + return html` + + + + + + + + + + ${Object.entries(sizes).map(([dev, size]) => html` + + + + `)} + +
DeviceBytesHuman
${dev}${size}${humanFileSize(size)}
`; + } +} + +function TensorMemorySection({model}) { + return html` + <${Hider} name="Tensor Memory" shown=false> + <${OpenTensorMemorySection} model=${model} />`; +} + +class AuxContentPane extends Component { + constructor() { + super(); + this.state = { + blame_info: null, + }; + } + + doBlame(arg) { + this.setState({...this.state, blame_info: arg}); + } + + render({model: {interned_strings}}, {blame_info}) { + let blame_content = ""; + if (blame_info) { + const {ist_file, line, ist_s_text, s_start, s_end} = blame_info; + let s_text = interned_strings[ist_s_text]; + if (s_start != 0 || s_end != s_text.length) { + let prefix = s_text.slice(0, s_start); + let main = s_text.slice(s_start, s_end); + let suffix = s_text.slice(s_end); + s_text = html`${prefix}${main}${suffix}`; + } + blame_content = html` +

${interned_strings[ist_file]}:${line}

+
${s_start}:${s_end}
+
${s_text}

+ `; + } + return html` + +
+ ${blame_content} + `; + } +} + +class App extends Component { + constructor() { + super(); + this.state = { + err: false, + model: null, + }; + } + + componentDidMount() { + const app = this; + if (BURNED_IN_MODEL_INFO !== null) { + app.setState({model: BURNED_IN_MODEL_INFO}); + } else { + fetch("./model_info.json").then(function(response) { + if (!response.ok) { + throw new Error("Response not ok."); + } + return response.json(); + }).then(function(body) { + app.setState({model: body}); + }).catch(function(error) { + console.log("Top-level error: ", error); + }); + } + } + + componentDidCatch(error) { + void(error); + this.setState({...this.state, err: true}); + } + + render(_, {err}) { + if (this.state.model === null) { + return html`

Loading...

`; + } + + const model = this.state.model.model; + + let error_msg = ""; + if (err) { + error_msg = html`

An error occurred. Check console

`; + } + + return html` + ${error_msg} +
+

TorchScript Model (version ${model.version}): ${model.title}

+ + <${ModelSizeSection} model=${model}/> + <${StructuredDataSection} name="Model Data" data=${model.model_data} shown=true/> + <${StructuredDataSection} name="Constants" data=${model.constants} shown=false/> + <${ZipContentsSection} model=${model}/> + <${CodeSection} model=${model}/> + <${ExtraJsonSection} files=${model.extra_files_jsons}/> + <${ExtraPicklesSection} files=${model.extra_pickles}/> + <${TensorMemorySection} model=${model}/> +
+
+ <${AuxContentPane} + err=${this.state.error} + model=${model} + ref=${(p) => blame.setAuxContentPane(p)}/> +
+ `; + } +} + +render(h(App), document.body); diff --git a/.venv/lib/python3.12/site-packages/torch/utils/model_dump/htm.mjs b/.venv/lib/python3.12/site-packages/torch/utils/model_dump/htm.mjs new file mode 100644 index 0000000000000000000000000000000000000000..06f25a13d8021ff4f43de442bbf0279f24735d6c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/model_dump/htm.mjs @@ -0,0 +1,2 @@ +// HTM, Apache License +var n=function(t,s,r,e){var u;s[0]=0;for(var h=1;h=5&&((e||!n&&5===r)&&(h.push(r,0,e,s),r=6),n&&(h.push(r,n,0,s),r=6)),e=""},a=0;a"===t?(r=1,e=""):e=t+e[0]:u?t===u?u="":e+=t:'"'===t||"'"===t?u=t:">"===t?(p(),r=1):r&&("="===t?(r=5,s=e,e=""):"/"===t&&(r<5||">"===n[a][l+1])?(p(),3===r&&(h=h[0]),r=h,(h=h[0]).push(2,0,r),r=0):" "===t||"\t"===t||"\n"===t||"\r"===t?(p(),r=2):e+=t),3===r&&"!--"===e&&(r=4,h=h[0])}return p(),h}(s)),r),arguments,[])).length>1?r:r[0]} diff --git a/.venv/lib/python3.12/site-packages/torch/utils/model_dump/preact.mjs b/.venv/lib/python3.12/site-packages/torch/utils/model_dump/preact.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8c85bd948c6772ca8d40fc8d6fab6a220d55a1ef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/model_dump/preact.mjs @@ -0,0 +1,2 @@ +// Preact, MIT License +var n,l,u,i,t,o,r={},f=[],e=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function c(e,n){for(var t in n)e[t]=n[t];return e}function s(e){var n=e.parentNode;n&&n.removeChild(e)}function a(e,n,t){var _,l,o,r=arguments,i={};for(o in n)"key"==o?_=n[o]:"ref"==o?l=n[o]:i[o]=n[o];if(arguments.length>3)for(t=[t],o=3;o0?v(m.type,m.props,m.key,null,m.__v):m)){if(m.__=t,m.__b=t.__b+1,null===(h=P[p])||h&&m.key==h.key&&m.type===h.type)P[p]=void 0;else for(a=0;a3)for(t=[t],o=3;o + + + TorchScript Model + + + + + + + + diff --git a/.venv/lib/python3.12/site-packages/torch/utils/model_zoo.py b/.venv/lib/python3.12/site-packages/torch/utils/model_zoo.py new file mode 100644 index 0000000000000000000000000000000000000000..e0c6004e23ea806a2c83e12cd2998e0279e0b16f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/model_zoo.py @@ -0,0 +1,2 @@ +# torchvision imports tqdm from here. +from torch.hub import tqdm, load_state_dict_from_url as load_url # noqa: F401 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/module_tracker.py b/.venv/lib/python3.12/site-packages/torch/utils/module_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..7b5a8aad4dda9880c860850e42071a55ee7442e5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/module_tracker.py @@ -0,0 +1,160 @@ +# mypy: allow-untyped-defs +import logging +import weakref +from typing import TYPE_CHECKING + +import torch +from torch.autograd.graph import register_multi_grad_hook +from torch.nn.modules.module import ( + register_module_forward_hook, + register_module_forward_pre_hook, +) +from torch.utils._pytree import tree_flatten + + +if TYPE_CHECKING: + from torch.utils.hooks import RemovableHandle + + +logger = logging.getLogger(__name__) + + +__all__ = ["ModuleTracker"] + + +class ModuleTracker: + """ + ``ModuleTracker`` is a context manager that tracks the nn.Module hierarchy during execution + so that other system can query which Module is currently being executed (or its backward is being + executed). + + You can access the ``parents`` attribute on this context manager to get the set of all the + Modules currently being executed via their fqn (fully qualified name, also used as the key within + the state_dict). + You can access the ``is_bw`` attribute to know if you are currently running in backward or not. + + Note that ``parents`` is never empty and always contains the "Global" key. The ``is_bw`` flag + will remain ``True`` after the forward until another Module is executed. If you need it to be + more accurate, please submit an issue requesting this. Adding a map from fqn to the module instance + is possible but not done yet, please submit an issue requesting this if you need it. + + Example usage + + .. code-block:: python + + mod = torch.nn.Linear(2, 2) + + with ModuleTracker() as tracker: + # Access anything during the forward pass + def my_linear(m1, m2, bias): + print(f"Current modules: {tracker.parents}") + return torch.mm(m1, m2.t()) + bias + + torch.nn.functional.linear = my_linear + + mod(torch.rand(2, 2)) + + """ + + parents: set[str] + """ + A Set containing the fqn for each module currently running their forward + """ + + def __init__(self) -> None: + self.parents = {"Global"} + self._known_modules: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary() + self._seen_modules: weakref.WeakSet = weakref.WeakSet() + self._has_callback = False + self._hooks: list[RemovableHandle] = [] + + def _maybe_set_engine_callback(self) -> None: + # This assumes no concurrent calls to backward + if self._has_callback: + return + + def callback() -> None: + self.parents = {"Global"} + self._has_callback = False + + torch.autograd.Variable._execution_engine.queue_callback(callback) + self._has_callback = True + + @property + def is_bw(self): + """ + A boolean marking if this is currently running during the backward pass or not + """ + return torch._C._current_graph_task_id() != -1 + + def _get_mod_name(self, mod): + if mod not in self._known_modules: + self._known_modules[mod] = type(mod).__name__ + mod_name = self._known_modules[mod] + if mod not in self._seen_modules: + for name, submod in mod.named_children(): + self._known_modules[submod] = f"{mod_name}.{name}" + self._get_mod_name(submod) + self._seen_modules.add(mod) + return mod_name + + def _get_append_fn(self, name, is_bw): + def fn(*args) -> None: + if is_bw: + self._maybe_set_engine_callback() + if name in self.parents: + logger.info( + "The module hierarchy tracking seems to be broken as this Module was already entered. %s during %s", + name, + "backward" if is_bw else "forward", + ) + self.parents.add(name) + + return fn + + def _get_pop_fn(self, name, is_bw): + def fn(*args) -> None: + if name in self.parents: + self.parents.remove(name) + else: + logger.info( + "The Module hierarchy tracking is confused as we're exiting a Module that was never entered. %s during %s", + name, + "backward" if is_bw else "forward", + ) + + return fn + + def _fw_pre_hook(self, mod, input) -> None: + name = self._get_mod_name(mod) + self._get_append_fn(name, False)() + + args, _ = tree_flatten(input) + tensors = [a for a in args if isinstance(a, torch.Tensor) and a.requires_grad] + if tensors: + self._hooks.append( + register_multi_grad_hook(tensors, self._get_pop_fn(name, True)) + ) + + def _fw_post_hook(self, mod, input, output) -> None: + name = self._get_mod_name(mod) + self._get_pop_fn(name, False)() + + args, _ = tree_flatten(output) + tensors = [a for a in args if isinstance(a, torch.Tensor) and a.requires_grad] + if tensors: + self._hooks.append( + register_multi_grad_hook(tensors, self._get_append_fn(name, True)) + ) + + def __enter__(self): + self._fw_pre_handle = register_module_forward_pre_hook(self._fw_pre_hook) + self._fw_post_handle = register_module_forward_hook(self._fw_post_hook) + return self + + def __exit__(self, *args): + self._fw_pre_handle.remove() + self._fw_post_handle.remove() + for hook in self._hooks: + hook.remove() + self._hooks.clear() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/serialization/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/serialization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d63bc18b69b138a026622de599aed656cc868c8e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/serialization/__init__.py @@ -0,0 +1 @@ +from . import config diff --git a/.venv/lib/python3.12/site-packages/torch/utils/serialization/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/serialization/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff5775d8087e0aad7ba8af96cfa3fbbdb4fd5e83 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/serialization/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/serialization/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/serialization/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7ab8770bd53d7054bf44977d1362b8caf9c993e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/serialization/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/serialization/config.py b/.venv/lib/python3.12/site-packages/torch/utils/serialization/config.py new file mode 100644 index 0000000000000000000000000000000000000000..c3e6729c68583f7206d07df7bfa2666007a6bd67 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/serialization/config.py @@ -0,0 +1,25 @@ +import sys +from typing import Optional as _Optional, TYPE_CHECKING as _TYPE_CHECKING + + +if _TYPE_CHECKING: + from torch.serialization import LoadEndianness as _LoadEndianess + +from torch.utils._config_module import install_config_module as _install_config_module + + +class load: + mmap: bool = False + endianness: _Optional["_LoadEndianess"] = None + # MAP_PRIVATE = 2 + mmap_flags: int | None = None if sys.platform == "win32" else 2 + calculate_storage_offsets: bool = False + + +class save: + compute_crc32: bool = True + use_pinned_memory_for_d2h: bool = False + storage_alignment: int = 64 + + +_install_config_module(sys.modules[__name__]) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/show_pickle.py b/.venv/lib/python3.12/site-packages/torch/utils/show_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..269ba3fbda4230c71ff14fe0e97872f6a8c57e6d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/show_pickle.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +# mypy: allow-untyped-defs +import sys +import pickle +import struct +import pprint +import zipfile +import fnmatch +from typing import Any, IO + +__all__ = ["FakeObject", "FakeClass", "DumpUnpickler", "main"] + +class FakeObject: + def __init__(self, module, name, args) -> None: + self.module = module + self.name = name + self.args = args + # NOTE: We don't distinguish between state never set and state set to None. + self.state = None + + def __repr__(self) -> str: + state_str = "" if self.state is None else f"(state={self.state!r})" + return f"{self.module}.{self.name}{self.args!r}{state_str}" + + def __setstate__(self, state): + self.state = state + + @staticmethod + def pp_format(printer, obj, stream, indent, allowance, context, level) -> None: + if not obj.args and obj.state is None: + stream.write(repr(obj)) + return + if obj.state is None: + stream.write(f"{obj.module}.{obj.name}") + printer._format(obj.args, stream, indent + 1, allowance + 1, context, level) + return + if not obj.args: + stream.write(f"{obj.module}.{obj.name}()(state=\n") + indent += printer._indent_per_level + stream.write(" " * indent) + printer._format(obj.state, stream, indent, allowance + 1, context, level + 1) + stream.write(")") + return + raise Exception("Need to implement") # noqa: TRY002 + + +class FakeClass: + def __init__(self, module, name) -> None: + self.module = module + self.name = name + self.__new__ = self.fake_new # type: ignore[assignment] + + def __repr__(self) -> str: + return f"{self.module}.{self.name}" + + def __call__(self, *args): + return FakeObject(self.module, self.name, args) + + def fake_new(self, *args): + return FakeObject(self.module, self.name, args[1:]) + + +class DumpUnpickler(pickle._Unpickler): # type: ignore[name-defined] + def __init__( + self, + file, + *, + catch_invalid_utf8=False, + **kwargs) -> None: + super().__init__(file, **kwargs) + self.catch_invalid_utf8 = catch_invalid_utf8 + + def find_class(self, module, name): + return FakeClass(module, name) + + def persistent_load(self, pid): + return FakeObject("pers", "obj", (pid,)) + + dispatch = dict(pickle._Unpickler.dispatch) # type: ignore[attr-defined] + + # Custom objects in TorchScript are able to return invalid UTF-8 strings + # from their pickle (__getstate__) functions. Install a custom loader + # for strings that catches the decode exception and replaces it with + # a sentinel object. + def load_binunicode(self) -> None: + strlen, = struct.unpack(" sys.maxsize: + raise Exception("String too long.") # noqa: TRY002 + str_bytes = self.read(strlen) # type: ignore[attr-defined] + obj: Any + try: + obj = str(str_bytes, "utf-8", "surrogatepass") + except UnicodeDecodeError as exn: + if not self.catch_invalid_utf8: + raise + obj = FakeObject("builtin", "UnicodeDecodeError", (str(exn),)) + self.append(obj) # type: ignore[attr-defined] + dispatch[pickle.BINUNICODE[0]] = load_binunicode # type: ignore[assignment] + + @classmethod + def dump(cls, in_stream, out_stream): + value = cls(in_stream).load() + pprint.pprint(value, stream=out_stream) + return value + + +def main(argv, output_stream=None) -> int | None: + if len(argv) != 2: + # Don't spam stderr if not using stdout. + if output_stream is not None: + raise Exception("Pass argv of length 2.") # noqa: TRY002 + sys.stderr.write("usage: show_pickle PICKLE_FILE\n") + sys.stderr.write(" PICKLE_FILE can be any of:\n") + sys.stderr.write(" path to a pickle file\n") + sys.stderr.write(" file.zip@member.pkl\n") + sys.stderr.write(" file.zip@*/pattern.*\n") + sys.stderr.write(" (shell glob pattern for members)\n") + sys.stderr.write(" (only first match will be shown)\n") + return 2 + + fname = argv[1] + handle: IO[bytes] + if "@" not in fname: + with open(fname, "rb") as handle: + DumpUnpickler.dump(handle, output_stream) + else: + zfname, mname = fname.split("@", 1) + with zipfile.ZipFile(zfname) as zf: + if "*" not in mname: + with zf.open(mname) as handle: + DumpUnpickler.dump(handle, output_stream) + else: + found = False + for info in zf.infolist(): + if fnmatch.fnmatch(info.filename, mname): + with zf.open(info) as handle: + DumpUnpickler.dump(handle, output_stream) + found = True + break + if not found: + raise Exception(f"Could not find member matching {mname} in {zfname}") # noqa: TRY002 + + +if __name__ == "__main__": + # This hack works on every version of Python I've tested. + # I've tested on the following versions: + # 3.7.4 + if True: + pprint.PrettyPrinter._dispatch[FakeObject.__repr__] = FakeObject.pp_format # type: ignore[attr-defined] + + sys.exit(main(sys.argv)) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a9b2ac5edd05e16ef51e75f2ca68864b65da5d58 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__init__.py @@ -0,0 +1,19 @@ +import tensorboard +from torch._vendor.packaging.version import Version + +if not hasattr(tensorboard, "__version__") or Version( + tensorboard.__version__ +) < Version("1.15"): + raise ImportError("TensorBoard logging requires TensorBoard version 1.15 or above") + +del Version +del tensorboard + +from .writer import FileWriter, SummaryWriter +from tensorboard.summary.writer.record_writer import RecordWriter + +__all__ = [ + "FileWriter", + "RecordWriter", + "SummaryWriter", +] diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3132d6d57ce98892987dafbcd19013fa926c563 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_convert_np.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_convert_np.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6055445ca14caa69e637783dd90977604c83f1df Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_convert_np.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_embedding.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_embedding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01c29d9051a10e792031da3ac736061711de8c63 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_embedding.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_onnx_graph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_onnx_graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..915cc9b62a0a76da5760883650d2e2eec07eb268 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_onnx_graph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_proto_graph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_proto_graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f9f5507dd1d48ab79e9a45efa768a4755ce9a46 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_proto_graph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_pytorch_graph.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_pytorch_graph.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b969dd522d06b5e6a77f308ed68b28b911b54f1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_pytorch_graph.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..023b2cbcf3cf31bb8f99882923fec6cc387b490f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/summary.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/summary.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa0338d7d475a027e4cab3f2c1089027a335f1a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/summary.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/writer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/writer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37bb330e4a8ecf86d9737d38e9d250ee71ba30c4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/__pycache__/writer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_convert_np.py b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_convert_np.py new file mode 100644 index 0000000000000000000000000000000000000000..f0e8910580de16d9e7cf90f10d6327556e9a37a6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_convert_np.py @@ -0,0 +1,37 @@ +"""This module converts objects into numpy array.""" + +import numpy as np + +import torch + + +def make_np(x: torch.Tensor) -> np.ndarray: + """ + Convert an object into numpy array. + + Args: + x: An instance of torch tensor + + Returns: + numpy.array: Numpy array + """ + if isinstance(x, np.ndarray): + return x + if np.isscalar(x): + return np.array([x]) + if isinstance(x, torch.Tensor): + if x.device.type == "meta": + return np.random.randn(1) + return _prepare_pytorch(x) + raise NotImplementedError( + f"Got {type(x)}, but numpy array or torch tensor are expected." + ) + + +def _prepare_pytorch(x: torch.Tensor) -> np.ndarray: + if x.dtype == torch.bfloat16: + x = x.to(torch.float16) + # pyrefly: ignore [bad-assignment] + x = x.detach().cpu().numpy() + # pyrefly: ignore [bad-return] + return x diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_embedding.py b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..73413e219d0efbabe7d66747bd108ee5e8be4319 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_embedding.py @@ -0,0 +1,87 @@ +# mypy: allow-untyped-defs +import math +import numpy as np +from ._convert_np import make_np +from ._utils import make_grid +from tensorboard.compat import tf +from tensorboard.plugins.projector.projector_config_pb2 import EmbeddingInfo + + +_HAS_GFILE_JOIN = hasattr(tf.io.gfile, "join") + + +def _gfile_join(a, b): + # The join API is different between tensorboard's TF stub and TF: + # https://github.com/tensorflow/tensorboard/issues/6080 + # We need to try both because `tf` may point to either the stub or the real TF. + if _HAS_GFILE_JOIN: + return tf.io.gfile.join(a, b) + else: + fs = tf.io.gfile.get_filesystem(a) + return fs.join(a, b) + + +def make_tsv(metadata, save_path, metadata_header=None) -> None: + if not metadata_header: + metadata = [str(x) for x in metadata] + else: + if len(metadata_header) != len( + metadata[0] + ): + raise AssertionError("len of header must be equal to the number of columns in metadata") + metadata = ["\t".join(str(e) for e in l) for l in [metadata_header] + metadata] + + metadata_bytes = tf.compat.as_bytes("\n".join(metadata) + "\n") + with tf.io.gfile.GFile(_gfile_join(save_path, "metadata.tsv"), "wb") as f: + f.write(metadata_bytes) + + +# https://github.com/tensorflow/tensorboard/issues/44 image label will be squared +def make_sprite(label_img, save_path) -> None: + from PIL import Image + from io import BytesIO + + # this ensures the sprite image has correct dimension as described in + # https://www.tensorflow.org/get_started/embedding_viz + nrow = math.ceil((label_img.size(0)) ** 0.5) + arranged_img_CHW = make_grid(make_np(label_img), ncols=nrow) + + # augment images so that #images equals nrow*nrow + arranged_augment_square_HWC = np.zeros( + (arranged_img_CHW.shape[2], arranged_img_CHW.shape[2], 3) + ) + arranged_img_HWC = arranged_img_CHW.transpose(1, 2, 0) # chw -> hwc + arranged_augment_square_HWC[: arranged_img_HWC.shape[0], :, :] = arranged_img_HWC + im = Image.fromarray(np.uint8((arranged_augment_square_HWC * 255).clip(0, 255))) + + with BytesIO() as buf: + im.save(buf, format="PNG") + im_bytes = buf.getvalue() + + with tf.io.gfile.GFile(_gfile_join(save_path, "sprite.png"), "wb") as f: + f.write(im_bytes) + + +def get_embedding_info(metadata, label_img, subdir, global_step, tag): + info = EmbeddingInfo() + info.tensor_name = f"{tag}:{str(global_step).zfill(5)}" + info.tensor_path = _gfile_join(subdir, "tensors.tsv") + if metadata is not None: + info.metadata_path = _gfile_join(subdir, "metadata.tsv") + if label_img is not None: + info.sprite.image_path = _gfile_join(subdir, "sprite.png") + info.sprite.single_image_dim.extend([label_img.size(3), label_img.size(2)]) + return info + + +def write_pbtxt(save_path, contents) -> None: + config_path = _gfile_join(save_path, "projector_config.pbtxt") + with tf.io.gfile.GFile(config_path, "wb") as f: + f.write(tf.compat.as_bytes(contents)) + + +def make_mat(matlist, save_path) -> None: + with tf.io.gfile.GFile(_gfile_join(save_path, "tensors.tsv"), "wb") as f: + for x in matlist: + x = [str(i.item()) for i in x] + f.write(tf.compat.as_bytes("\t".join(x) + "\n")) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_onnx_graph.py b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_onnx_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..59d1d5b5f0a5cc0bf1d3694184b9727661d06093 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_onnx_graph.py @@ -0,0 +1,60 @@ +# mypy: allow-untyped-defs +from tensorboard.compat.proto.graph_pb2 import GraphDef +from tensorboard.compat.proto.node_def_pb2 import NodeDef +from tensorboard.compat.proto.versions_pb2 import VersionDef +from tensorboard.compat.proto.attr_value_pb2 import AttrValue +from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto + + +def load_onnx_graph(fname): + import onnx + m = onnx.load(fname) # type: ignore[attr-defined] + g = m.graph + return parse(g) + + +def parse(graph): + nodes = [] + import itertools + + nodes_proto = list(itertools.chain(graph.input, graph.output)) + + for node in nodes_proto: + print(node.name) + shapeproto = TensorShapeProto( + dim=[ + TensorShapeProto.Dim(size=d.dim_value) + for d in node.type.tensor_type.shape.dim + ] + ) + nodes.append( + NodeDef( + name=node.name.encode(encoding="utf_8"), + op="Variable", + input=[], + attr={ + "dtype": AttrValue(type=node.type.tensor_type.elem_type), + "shape": AttrValue(shape=shapeproto), + }, + ) + ) + + for node in graph.node: + _attr = [" = ".join([str(f[1]) for f in s.ListFields()]) for s in node.attribute] + attr = ", ".join(_attr).encode(encoding="utf_8") + print(node.output[0]) + nodes.append( + NodeDef( + name=node.output[0].encode(encoding="utf_8"), + op=node.op_type, + input=node.input, + attr={"parameters": AttrValue(s=attr)}, + ) + ) + + # two pass token replacement, appends opname to object id + mapping = {} + for node in nodes: + mapping[node.name] = node.op + "_" + node.name + + return GraphDef(node=nodes, versions=VersionDef(producer=22)) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_proto_graph.py b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_proto_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..8a9dc8536755c173f64bd5186af680d8438067ab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_proto_graph.py @@ -0,0 +1,55 @@ +import torch + +from collections.abc import Sequence +from tensorboard.compat.proto.node_def_pb2 import NodeDef +from tensorboard.compat.proto.attr_value_pb2 import AttrValue +from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto + + +def attr_value_proto(dtype: object, shape: Sequence[int] | None, s: str | None) -> dict[str, AttrValue]: + """Create a dict of objects matching a NodeDef's attr field. + + Follows https://github.com/tensorflow/tensorboard/blob/master/tensorboard/compat/proto/attr_value.proto + specifically designed for a NodeDef. The values have been reverse engineered from + standard TensorBoard logged data. + """ + attr = {} + if s is not None: + attr["attr"] = AttrValue(s=s.encode(encoding="utf_8")) + if shape is not None: + shapeproto = tensor_shape_proto(shape) + attr["_output_shapes"] = AttrValue(list=AttrValue.ListValue(shape=[shapeproto])) + return attr + + +def tensor_shape_proto(outputsize: Sequence[int]) -> TensorShapeProto: + """Create an object matching a tensor_shape field. + + Follows https://github.com/tensorflow/tensorboard/blob/master/tensorboard/compat/proto/tensor_shape.proto . + """ + return TensorShapeProto(dim=[TensorShapeProto.Dim(size=d) for d in outputsize]) + + +def node_proto( + name: str, + op: str = "UnSpecified", + input: list[str] | str | None = None, + dtype: torch.dtype | None = None, + shape: tuple[int, ...] | None = None, + outputsize: Sequence[int] | None = None, + attributes: str = "", +) -> NodeDef: + """Create an object matching a NodeDef. + + Follows https://github.com/tensorflow/tensorboard/blob/master/tensorboard/compat/proto/node_def.proto . + """ + if input is None: + input = [] + if not isinstance(input, list): + input = [input] + return NodeDef( + name=name.encode(encoding="utf_8"), + op=op, + input=input, + attr=attr_value_proto(dtype, outputsize, attributes), + ) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_pytorch_graph.py b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_pytorch_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..d20d2b51cf7f7ab222257d8945ba177945a26fd6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_pytorch_graph.py @@ -0,0 +1,378 @@ +# mypy: allow-untyped-defs +from collections import OrderedDict +import contextlib +from typing import Any + +from tensorboard.compat.proto.config_pb2 import RunMetadata +from tensorboard.compat.proto.graph_pb2 import GraphDef +from tensorboard.compat.proto.step_stats_pb2 import StepStats, DeviceStepStats +from tensorboard.compat.proto.versions_pb2 import VersionDef + +import torch +from ._proto_graph import node_proto + +methods_OP = [ + "attributeNames", + "hasMultipleOutputs", + "hasUses", + "inputs", + "kind", + "outputs", + "outputsSize", + "scopeName", +] +# Some additional methods to explore for methods_IO are +# +# 'unique' (type int) +# 'type' (type >) +# +# But the below are sufficient for now. +methods_IO = ["node", "offset", "debugName"] + +GETATTR_KIND = "prim::GetAttr" +CLASSTYPE_KIND = "ClassType" + + +class NodeBase: + def __init__( + self, + debugName=None, + inputs=None, + scope=None, + tensor_size=None, + op_type="UnSpecified", + attributes="", + ) -> None: + # TODO; Specify a __slots__ for this class or potentially + # used namedtuple instead + self.debugName = debugName + self.inputs = inputs + self.tensor_size = tensor_size + self.kind = op_type + self.attributes = attributes + self.scope = scope + + def __repr__(self) -> str: + repr = [] + repr.append(str(type(self))) + repr.extend( + m + ": " + str(getattr(self, m)) + str(type(getattr(self, m))) + for m in dir(self) + if "__" not in m + ) + return "\n".join(repr) + "\n\n" + + +class NodePy(NodeBase): + def __init__(self, node_cpp, valid_methods) -> None: + super().__init__(node_cpp) + valid_methods = valid_methods[:] + self.inputs = [] + + for m in valid_methods: + if m == "inputs" or m == "outputs": + list_of_node = list(getattr(node_cpp, m)()) + io_unique_names = [] + io_tensor_sizes = [] + for n in list_of_node: + io_unique_names.append(n.debugName()) + if n.isCompleteTensor(): + io_tensor_sizes.append(n.type().sizes()) + else: + io_tensor_sizes.append(None) + + setattr(self, m, io_unique_names) + setattr(self, m + "tensor_size", io_tensor_sizes) + + else: + setattr(self, m, getattr(node_cpp, m)()) + + +class NodePyIO(NodePy): + def __init__(self, node_cpp, input_or_output=None) -> None: + super().__init__(node_cpp, methods_IO) + try: + tensor_size = node_cpp.type().sizes() + except RuntimeError: + tensor_size = [ + 1, + ] # fail when constant model is used. + self.tensor_size = tensor_size + # Kind attribute string is purely descriptive and will be shown + # in detailed information for the node in TensorBoard's graph plugin. + # + # NodePyOP nodes get this from their kind() method. + self.kind = "Parameter" + if input_or_output: + self.input_or_output = input_or_output + self.kind = "IO Node" + + +class NodePyOP(NodePy): + def __init__(self, node_cpp) -> None: + super().__init__(node_cpp, methods_OP) + # Replace single quote which causes strange behavior in TensorBoard + # TODO: See if we can remove this in the future + self.attributes = str( + {k: _node_get(node_cpp, k) for k in node_cpp.attributeNames()} + ).replace("'", " ") + self.kind = node_cpp.kind() + + +class GraphPy: + """Helper class to convert torch.nn.Module to GraphDef proto and visualization with TensorBoard. + + GraphDef generation operates in two passes: + + In the first pass, all nodes are read and saved to two lists. + One list is for input/output nodes (nodes_io), which only have inbound + or outbound connections, but not both. Another list is for internal + operator nodes (nodes_op). The first pass also saves all scope name + appeared in the nodes in scope_name_appeared list for later processing. + + In the second pass, scope names are fully applied to all nodes. + debugNameToScopedName is a mapping from a node's ID to its fully qualified + scope name. e.g. Net1/Linear[0]/1. Unfortunately torch.jit doesn't have + totally correct scope output, so this is nontrivial. The function + populate_namespace_from_OP_to_IO and find_common_root are used to + assign scope name to a node based on the connection between nodes + in a heuristic kind of way. Bookkeeping is done with shallowest_scope_name + and scope_name_appeared. + """ + + def __init__(self) -> None: + self.nodes_op = [] + self.nodes_io = OrderedDict() + self.unique_name_to_scoped_name = {} + self.shallowest_scope_name = "default" + self.scope_name_appeared = [] + + def append(self, x) -> None: + if isinstance(x, NodePyIO): + self.nodes_io[x.debugName] = x + if isinstance(x, NodePyOP): + self.nodes_op.append(x) + + def printall(self) -> None: + print("all nodes") + for node in self.nodes_op: + print(node) + for key in self.nodes_io: + print(self.nodes_io[key]) + + def find_common_root(self) -> None: + for fullscope in self.scope_name_appeared: + if fullscope: + self.shallowest_scope_name = fullscope.split("/")[0] + + def populate_namespace_from_OP_to_IO(self) -> None: + for node in self.nodes_op: + for node_output, outputSize in zip(node.outputs, node.outputstensor_size, strict=True): + self.scope_name_appeared.append(node.scopeName) + self.nodes_io[node_output] = NodeBase( + node_output, + node.inputs, + node.scopeName, + outputSize, + op_type=node.kind, + attributes=node.attributes, + ) + + self.find_common_root() + + for node in self.nodes_op: + for input_node_id in node.inputs: + self.unique_name_to_scoped_name[input_node_id] = ( + node.scopeName + "/" + input_node_id + ) + + for key, node in self.nodes_io.items(): + if type(node) is NodeBase: + # pyrefly: ignore [unsupported-operation] + self.unique_name_to_scoped_name[key] = node.scope + "/" + node.debugName + if hasattr(node, "input_or_output"): + self.unique_name_to_scoped_name[key] = ( + node.input_or_output + "/" + node.debugName + ) + + if hasattr(node, "scope") and node.scope is not None: + self.unique_name_to_scoped_name[key] = node.scope + "/" + node.debugName + if node.scope == "" and self.shallowest_scope_name: + self.unique_name_to_scoped_name[node.debugName] = ( + + self.shallowest_scope_name + "/" + node.debugName + ) + + # replace name + for key, node in self.nodes_io.items(): + self.nodes_io[key].inputs = [ + self.unique_name_to_scoped_name[node_input_id] + for node_input_id in node.inputs + ] + if node.debugName in self.unique_name_to_scoped_name: + self.nodes_io[key].debugName = self.unique_name_to_scoped_name[ + node.debugName + ] + + def to_proto(self): + """Convert graph representation of GraphPy object to TensorBoard required format.""" + # TODO: compute correct memory usage and CPU time once + # PyTorch supports it + nodes = [ + node_proto( + v.debugName, + input=v.inputs, + outputsize=v.tensor_size, + op=v.kind, + attributes=v.attributes, + ) + for v in self.nodes_io.values() + ] + return nodes + + +def parse(graph, trace, args=None, omit_useless_nodes=True): + """Parse an optimized PyTorch model graph and produces a list of nodes and node stats. + + Useful for eventual conversion to TensorBoard protobuf format. + + Args: + graph (PyTorch module): The model graph to be parsed. + trace (PyTorch JIT TracedModule): The model trace to be parsed. + args (tuple): input tensor[s] for the model. + omit_useless_nodes (boolean): Whether to remove nodes from the graph. + """ + nodes_py = GraphPy() + for node in graph.inputs(): + if omit_useless_nodes: + if ( + len(node.uses()) == 0 + ): # number of user of the node (= number of outputs/ fanout) + continue + + if node.type().kind() != CLASSTYPE_KIND: + nodes_py.append(NodePyIO(node, "input")) + + attr_to_scope: dict[Any, str] = {} + for node in graph.nodes(): + if node.kind() == GETATTR_KIND: + attr_name = node.s("name") + attr_key = node.output().debugName() + parent = node.input().node() + if ( + parent.kind() == GETATTR_KIND + ): # If the parent node is not the top-level "self" node + parent_attr_key = parent.output().debugName() + parent_scope = attr_to_scope[parent_attr_key] + attr_scope = parent_scope.split("/")[-1] + attr_to_scope[attr_key] = f"{parent_scope}/{attr_scope}.{attr_name}" + else: + attr_to_scope[attr_key] = f"__module.{attr_name}" + # We don't need classtype nodes; scope will provide this information + if node.output().type().kind() != CLASSTYPE_KIND: + node_py = NodePyOP(node) + node_py.scopeName = attr_to_scope[attr_key] # type: ignore[attr-defined] + nodes_py.append(node_py) + else: + nodes_py.append(NodePyOP(node)) + + for i, node in enumerate(graph.outputs()): # Create sink nodes for output ops + node_pyio = NodePyIO(node, "output") + node_pyio.debugName = f"output.{i + 1}" + node_pyio.inputs = [node.debugName()] + nodes_py.append(node_pyio) + + def parse_traced_name(module): + if isinstance(module, torch.jit.TracedModule): + module_name = module._name + else: + module_name = getattr(module, "original_name", "Module") + return module_name + + alias_to_name = {} + base_name = parse_traced_name(trace) + for name, module in trace.named_modules(prefix="__module"): + mod_name = parse_traced_name(module) + attr_name = name.split(".")[-1] + alias_to_name[name] = f"{mod_name}[{attr_name}]" + + for node in nodes_py.nodes_op: + module_aliases = node.scopeName.split("/") + replacements = [ + alias_to_name[alias] if alias in alias_to_name else alias.split(".")[-1] + for alias in module_aliases + ] + node.scopeName = base_name + if any(replacements): + node.scopeName += "/" + "/".join(replacements) + + nodes_py.populate_namespace_from_OP_to_IO() + return nodes_py.to_proto() + + +def graph(model, args, verbose=False, use_strict_trace=True): + """ + Process a PyTorch model and produces a `GraphDef` proto that can be logged to TensorBoard. + + Args: + model (PyTorch module): The model to be parsed. + args (tuple): input tensor[s] for the model. + verbose (bool): Whether to print out verbose information while + processing. + use_strict_trace (bool): Whether to pass keyword argument `strict` to + `torch.jit.trace`. Pass False when you want the tracer to + record your mutable container types (list, dict) + """ + with _set_model_to_eval(model): + try: + trace = torch.jit.trace(model, args, strict=use_strict_trace) + graph = trace.graph + torch._C._jit_pass_inline(graph) + except RuntimeError as e: + print(e) + print("Error occurs, No graph saved") + raise e + + if verbose: + print(graph) + list_of_nodes = parse(graph, trace, args) + # We are hardcoding that this was run on CPU even though it might have actually + # run on GPU. Note this is what is shown in TensorBoard and has no bearing + # on actual execution. + # TODO: See if we can extract GPU vs CPU information from the PyTorch model + # and pass it correctly to TensorBoard. + # + # Definition of StepStats and DeviceStepStats can be found at + # https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/graph/tf_graph_common/proto.ts + # and + # https://github.com/tensorflow/tensorboard/blob/master/tensorboard/compat/proto/step_stats.proto + stepstats = RunMetadata( + step_stats=StepStats(dev_stats=[DeviceStepStats(device="/device:CPU:0")]) + ) + return GraphDef(node=list_of_nodes, versions=VersionDef(producer=22)), stepstats + # The producer version has been reverse engineered from standard + # TensorBoard logged data. + + +@contextlib.contextmanager +def _set_model_to_eval(model): + """Context manager to temporarily set the training mode of ``model`` to eval.""" + if not isinstance(model, torch.jit.ScriptFunction): + originally_training = model.training + model.train(False) + try: + yield + finally: + model.train(originally_training) + else: + # Do nothing for ScriptFunction + try: + yield + finally: + pass + + +def _node_get(node: torch._C.Node, key: str): + """Get attributes of a node which is polymorphic over return type.""" + sel = node.kindOf(key) + return getattr(node, sel)(key) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_utils.py b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e11ff464dc1ffe620296bc100fc7db01360845c0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/_utils.py @@ -0,0 +1,131 @@ +# mypy: allow-untyped-defs +import numpy as np +import numpy.typing as npt + + +# Functions for converting +def figure_to_image(figures, close=True): + """Render matplotlib figure to numpy format. + + Note that this requires the ``matplotlib`` package. + + Args: + figures (matplotlib.pyplot.figure or list of figures): figure or a list of figures + close (bool): Flag to automatically close the figure + + Returns: + numpy.array: image in [CHW] order + """ + import matplotlib.pyplot as plt + import matplotlib.backends.backend_agg as plt_backend_agg + + def render_to_rgb(figure): + canvas = plt_backend_agg.FigureCanvasAgg(figure) + canvas.draw() + data: npt.NDArray = np.frombuffer(canvas.buffer_rgba(), dtype=np.uint8) + w, h = figure.canvas.get_width_height() + image_hwc = data.reshape([h, w, 4])[:, :, 0:3] + image_chw = np.moveaxis(image_hwc, source=2, destination=0) + if close: + plt.close(figure) + return image_chw + + if isinstance(figures, list): + images = [render_to_rgb(figure) for figure in figures] + return np.stack(images) + else: + image = render_to_rgb(figures) + return image + + +def _prepare_video(V): + """ + Convert a 5D tensor into 4D tensor. + + Conversion is done from [batchsize, time(frame), channel(color), height, width] (5D tensor) + to [time(frame), new_width, new_height, channel] (4D tensor). + + A batch of images are spread to a grid, which forms a frame. + e.g. Video with batchsize 16 will have a 4x4 grid. + """ + b, t, c, h, w = V.shape + + if V.dtype == np.uint8: + V = np.float32(V) / 255.0 + + def is_power2(num): + return num != 0 and ((num & (num - 1)) == 0) + + # pad to nearest power of 2, all at once + + if not is_power2(V.shape[0]): + + len_addition = int(2 ** V.shape[0].bit_length() - V.shape[0]) + V = np.concatenate((V, np.zeros(shape=(len_addition, t, c, h, w))), axis=0) + + n_rows = 2 ** ((b.bit_length() - 1) // 2) + + n_cols = V.shape[0] // n_rows + + V = np.reshape(V, (n_rows, n_cols, t, c, h, w)) + V = np.transpose(V, axes=(2, 0, 4, 1, 5, 3)) + V = np.reshape(V, (t, n_rows * h, n_cols * w, c)) + + return V + + +def make_grid(I, ncols=8): + # I: N1HW or N3HW + if not isinstance(I, np.ndarray): + raise AssertionError("plugin error, should pass numpy array here") + if I.shape[1] == 1: + I = np.concatenate([I, I, I], 1) + if I.ndim != 4 or I.shape[1] != 3: + raise AssertionError("Input should be a 4D numpy array with 3 channels") + nimg = I.shape[0] + H = I.shape[2] + W = I.shape[3] + ncols = min(nimg, ncols) + nrows = int(np.ceil(float(nimg) / ncols)) + canvas = np.zeros((3, H * nrows, W * ncols), dtype=I.dtype) + i = 0 + for y in range(nrows): + for x in range(ncols): + if i >= nimg: + break + canvas[:, y * H : (y + 1) * H, x * W : (x + 1) * W] = I[i] + i = i + 1 + return canvas + + # if modality == 'IMG': + # if x.dtype == np.uint8: + # x = x.astype(np.float32) / 255.0 + + +def convert_to_HWC(tensor, input_format): # tensor: numpy array + if len(set(input_format)) != len(input_format): + raise AssertionError(f"You can not use the same dimension shorthand twice. \ + input_format: {input_format}") + if len(tensor.shape) != len(input_format): + raise AssertionError(f"size of input tensor and input format are different. \ + tensor shape: {tensor.shape}, input_format: {input_format}") + input_format = input_format.upper() + + if len(input_format) == 4: + index = [input_format.find(c) for c in "NCHW"] + tensor_NCHW = tensor.transpose(index) + tensor_CHW = make_grid(tensor_NCHW) + return tensor_CHW.transpose(1, 2, 0) + + if len(input_format) == 3: + index = [input_format.find(c) for c in "HWC"] + tensor_HWC = tensor.transpose(index) + if tensor_HWC.shape[2] == 1: + tensor_HWC = np.concatenate([tensor_HWC, tensor_HWC, tensor_HWC], 2) + return tensor_HWC + + if len(input_format) == 2: + index = [input_format.find(c) for c in "HW"] + tensor = tensor.transpose(index) + tensor = np.stack([tensor, tensor, tensor], 2) + return tensor diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/summary.py b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/summary.py new file mode 100644 index 0000000000000000000000000000000000000000..f5d86875387bfe8032a5440208512fea801b79e4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/summary.py @@ -0,0 +1,986 @@ +# mypy: allow-untyped-defs +import json +import logging +import struct + +from typing import Any + +import torch +import numpy as np + + +from google.protobuf import struct_pb2 + +from tensorboard.compat.proto.summary_pb2 import ( + HistogramProto, + Summary, + SummaryMetadata, +) +from tensorboard.compat.proto.tensor_pb2 import TensorProto +from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto +from tensorboard.plugins.custom_scalar import layout_pb2 +from tensorboard.plugins.pr_curve.plugin_data_pb2 import PrCurvePluginData +from tensorboard.plugins.text.plugin_data_pb2 import TextPluginData + +from ._convert_np import make_np +from ._utils import _prepare_video, convert_to_HWC + +__all__ = [ + "half_to_int", + "int_to_half", + "hparams", + "scalar", + "histogram_raw", + "histogram", + "make_histogram", + "image", + "image_boxes", + "draw_boxes", + "make_image", + "video", + "make_video", + "audio", + "custom_scalars", + "text", + "tensor_proto", + "pr_curve_raw", + "pr_curve", + "compute_curve", + "mesh", +] + +logger = logging.getLogger(__name__) + +def half_to_int(f: float) -> int: + """Casts a half-precision float value into an integer. + + Converts a half precision floating point value, such as `torch.half` or + `torch.bfloat16`, into an integer value which can be written into the + half_val field of a TensorProto for storage. + + To undo the effects of this conversion, use int_to_half(). + + """ + buf = struct.pack("f", f) + return struct.unpack("i", buf)[0] + +def int_to_half(i: int) -> float: + """Casts an integer value to a half-precision float. + + Converts an integer value obtained from half_to_int back into a floating + point value. + + """ + buf = struct.pack("i", i) + return struct.unpack("f", buf)[0] + +def _tensor_to_half_val(t: torch.Tensor) -> list[int]: + return [half_to_int(x) for x in t.flatten().tolist()] + +def _tensor_to_complex_val(t: torch.Tensor) -> list[float]: + return torch.view_as_real(t).flatten().tolist() + +def _tensor_to_list(t: torch.Tensor) -> list[Any]: + return t.flatten().tolist() + +# type maps: torch.Tensor type -> (protobuf type, protobuf val field) +_TENSOR_TYPE_MAP = { + torch.half: ("DT_HALF", "half_val", _tensor_to_half_val), + torch.float16: ("DT_HALF", "half_val", _tensor_to_half_val), + torch.bfloat16: ("DT_BFLOAT16", "half_val", _tensor_to_half_val), + torch.float32: ("DT_FLOAT", "float_val", _tensor_to_list), + torch.float: ("DT_FLOAT", "float_val", _tensor_to_list), + torch.float64: ("DT_DOUBLE", "double_val", _tensor_to_list), + torch.double: ("DT_DOUBLE", "double_val", _tensor_to_list), + torch.int8: ("DT_INT8", "int_val", _tensor_to_list), + torch.uint8: ("DT_UINT8", "int_val", _tensor_to_list), + torch.qint8: ("DT_UINT8", "int_val", _tensor_to_list), + torch.int16: ("DT_INT16", "int_val", _tensor_to_list), + torch.short: ("DT_INT16", "int_val", _tensor_to_list), + torch.int: ("DT_INT32", "int_val", _tensor_to_list), + torch.int32: ("DT_INT32", "int_val", _tensor_to_list), + torch.qint32: ("DT_INT32", "int_val", _tensor_to_list), + torch.int64: ("DT_INT64", "int64_val", _tensor_to_list), + torch.complex32: ("DT_COMPLEX32", "scomplex_val", _tensor_to_complex_val), + torch.chalf: ("DT_COMPLEX32", "scomplex_val", _tensor_to_complex_val), + torch.complex64: ("DT_COMPLEX64", "scomplex_val", _tensor_to_complex_val), + torch.cfloat: ("DT_COMPLEX64", "scomplex_val", _tensor_to_complex_val), + torch.bool: ("DT_BOOL", "bool_val", _tensor_to_list), + torch.complex128: ("DT_COMPLEX128", "dcomplex_val", _tensor_to_complex_val), + torch.cdouble: ("DT_COMPLEX128", "dcomplex_val", _tensor_to_complex_val), + torch.uint8: ("DT_UINT8", "uint32_val", _tensor_to_list), + torch.quint8: ("DT_UINT8", "uint32_val", _tensor_to_list), + torch.quint4x2: ("DT_UINT8", "uint32_val", _tensor_to_list), +} + + +def _calc_scale_factor(tensor) -> int: + converted = tensor.numpy() if not isinstance(tensor, np.ndarray) else tensor + return 1 if converted.dtype == np.uint8 else 255 + + +def _draw_single_box( + image, + xmin, + ymin, + xmax, + ymax, + display_str, + color="black", + color_text="black", + thickness=2, +): + from PIL import ImageDraw, ImageFont + + font = ImageFont.load_default() + draw = ImageDraw.Draw(image) + (left, right, top, bottom) = (xmin, xmax, ymin, ymax) + draw.line( + [(left, top), (left, bottom), (right, bottom), (right, top), (left, top)], + width=thickness, + fill=color, + ) + if display_str: + text_bottom = bottom + # Reverse list and print from bottom to top. + _left, _top, _right, _bottom = font.getbbox(display_str) + text_width, text_height = _right - _left, _bottom - _top + margin = np.ceil(0.05 * text_height) + draw.rectangle( + [ + (left, text_bottom - text_height - 2 * margin), + (left + text_width, text_bottom), + ], + fill=color, + ) + draw.text( + (left + margin, text_bottom - text_height - margin), + display_str, + fill=color_text, + font=font, + ) + return image + + +def hparams(hparam_dict=None, metric_dict=None, hparam_domain_discrete=None): + """Output three `Summary` protocol buffers needed by hparams plugin. + + `Experiment` keeps the metadata of an experiment, such as the name of the + hyperparameters and the name of the metrics. + `SessionStartInfo` keeps key-value pairs of the hyperparameters + `SessionEndInfo` describes status of the experiment e.g. STATUS_SUCCESS + + Args: + hparam_dict: A dictionary that contains names of the hyperparameters + and their values. + metric_dict: A dictionary that contains names of the metrics + and their values. + hparam_domain_discrete: (Optional[Dict[str, List[Any]]]) A dictionary that + contains names of the hyperparameters and all discrete values they can hold + + Returns: + The `Summary` protobufs for Experiment, SessionStartInfo and + SessionEndInfo + """ + import torch + from tensorboard.plugins.hparams.api_pb2 import ( + DataType, + Experiment, + HParamInfo, + MetricInfo, + MetricName, + Status, + ) + from tensorboard.plugins.hparams.metadata import ( + EXPERIMENT_TAG, + PLUGIN_DATA_VERSION, + PLUGIN_NAME, + SESSION_END_INFO_TAG, + SESSION_START_INFO_TAG, + ) + from tensorboard.plugins.hparams.plugin_data_pb2 import ( + HParamsPluginData, + SessionEndInfo, + SessionStartInfo, + ) + + # TODO: expose other parameters in the future. + # hp = HParamInfo(name='lr',display_name='learning rate', + # type=DataType.DATA_TYPE_FLOAT64, domain_interval=Interval(min_value=10, + # max_value=100)) + # mt = MetricInfo(name=MetricName(tag='accuracy'), display_name='accuracy', + # description='', dataset_type=DatasetType.DATASET_VALIDATION) + # exp = Experiment(name='123', description='456', time_created_secs=100.0, + # hparam_infos=[hp], metric_infos=[mt], user='tw') + + if not isinstance(hparam_dict, dict): + logger.warning("parameter: hparam_dict should be a dictionary, nothing logged.") + raise TypeError( + "parameter: hparam_dict should be a dictionary, nothing logged." + ) + if not isinstance(metric_dict, dict): + logger.warning("parameter: metric_dict should be a dictionary, nothing logged.") + raise TypeError( + "parameter: metric_dict should be a dictionary, nothing logged." + ) + + hparam_domain_discrete = hparam_domain_discrete or {} + if not isinstance(hparam_domain_discrete, dict): + raise TypeError( + "parameter: hparam_domain_discrete should be a dictionary, nothing logged." + ) + for k, v in hparam_domain_discrete.items(): + if ( + k not in hparam_dict + or not isinstance(v, list) + or not all(isinstance(d, type(hparam_dict[k])) for d in v) + ): + raise TypeError( + f"parameter: hparam_domain_discrete[{k}] should be a list of same type as hparam_dict[{k}]." + ) + hps = [] + + ssi = SessionStartInfo() + for k, v in hparam_dict.items(): + if v is None: + continue + if isinstance(v, (int, float)): + ssi.hparams[k].number_value = v + + if k in hparam_domain_discrete: + domain_discrete: struct_pb2.ListValue | None = struct_pb2.ListValue( + values=[ + struct_pb2.Value(number_value=d) + for d in hparam_domain_discrete[k] + ] + ) + else: + domain_discrete = None + + hps.append( + HParamInfo( + name=k, + type=DataType.Value("DATA_TYPE_FLOAT64"), + domain_discrete=domain_discrete, + ) + ) + continue + + if isinstance(v, str): + ssi.hparams[k].string_value = v + + if k in hparam_domain_discrete: + domain_discrete = struct_pb2.ListValue( + values=[ + struct_pb2.Value(string_value=d) + for d in hparam_domain_discrete[k] + ] + ) + else: + domain_discrete = None + + hps.append( + HParamInfo( + name=k, + type=DataType.Value("DATA_TYPE_STRING"), + domain_discrete=domain_discrete, + ) + ) + continue + + if isinstance(v, bool): + ssi.hparams[k].bool_value = v + + if k in hparam_domain_discrete: + domain_discrete = struct_pb2.ListValue( + values=[ + struct_pb2.Value(bool_value=d) + for d in hparam_domain_discrete[k] + ] + ) + else: + domain_discrete = None + + hps.append( + HParamInfo( + name=k, + type=DataType.Value("DATA_TYPE_BOOL"), + domain_discrete=domain_discrete, + ) + ) + continue + + if isinstance(v, torch.Tensor): + v = make_np(v)[0] + ssi.hparams[k].number_value = v + hps.append(HParamInfo(name=k, type=DataType.Value("DATA_TYPE_FLOAT64"))) + continue + raise ValueError( + "value should be one of int, float, str, bool, or torch.Tensor" + ) + + content = HParamsPluginData(session_start_info=ssi, version=PLUGIN_DATA_VERSION) + smd = SummaryMetadata( + plugin_data=SummaryMetadata.PluginData( + plugin_name=PLUGIN_NAME, content=content.SerializeToString() + ) + ) + ssi = Summary(value=[Summary.Value(tag=SESSION_START_INFO_TAG, metadata=smd)]) + + mts = [MetricInfo(name=MetricName(tag=k)) for k in metric_dict] + + exp = Experiment(hparam_infos=hps, metric_infos=mts) + + content = HParamsPluginData(experiment=exp, version=PLUGIN_DATA_VERSION) + smd = SummaryMetadata( + plugin_data=SummaryMetadata.PluginData( + plugin_name=PLUGIN_NAME, content=content.SerializeToString() + ) + ) + exp = Summary(value=[Summary.Value(tag=EXPERIMENT_TAG, metadata=smd)]) + + sei = SessionEndInfo(status=Status.Value("STATUS_SUCCESS")) + content = HParamsPluginData(session_end_info=sei, version=PLUGIN_DATA_VERSION) + smd = SummaryMetadata( + plugin_data=SummaryMetadata.PluginData( + plugin_name=PLUGIN_NAME, content=content.SerializeToString() + ) + ) + sei = Summary(value=[Summary.Value(tag=SESSION_END_INFO_TAG, metadata=smd)]) + + return exp, ssi, sei + + +def scalar(name, tensor, collections=None, new_style=False, double_precision=False): + """Output a `Summary` protocol buffer containing a single scalar value. + + The generated Summary has a Tensor.proto containing the input Tensor. + Args: + name: A name for the generated node. Will also serve as the series name in + TensorBoard. + tensor: A real numeric Tensor containing a single value. + collections: Optional list of graph collections keys. The new summary op is + added to these collections. Defaults to `[GraphKeys.SUMMARIES]`. + new_style: Whether to use new style (tensor field) or old style (simple_value + field). New style could lead to faster data loading. + Returns: + A scalar `Tensor` of type `string`. Which contains a `Summary` protobuf. + Raises: + ValueError: If tensor has the wrong shape or type. + """ + tensor = make_np(tensor).squeeze() + if tensor.ndim != 0: + raise AssertionError(f"Tensor should contain one element (0 dimensions). \ + Was given size: {tensor.size} and {tensor.ndim} dimensions.") + # python float is double precision in numpy + scalar = float(tensor) + if new_style: + tensor_proto = TensorProto(float_val=[scalar], dtype="DT_FLOAT") + if double_precision: + tensor_proto = TensorProto(double_val=[scalar], dtype="DT_DOUBLE") + + plugin_data = SummaryMetadata.PluginData(plugin_name="scalars") + smd = SummaryMetadata(plugin_data=plugin_data) + return Summary( + value=[ + Summary.Value( + tag=name, + tensor=tensor_proto, + metadata=smd, + ) + ] + ) + else: + return Summary(value=[Summary.Value(tag=name, simple_value=scalar)]) + + +def tensor_proto(tag, tensor): + """Outputs a `Summary` protocol buffer containing the full tensor. + The generated Summary has a Tensor.proto containing the input Tensor. + Args: + tag: A name for the generated node. Will also serve as the series name in + TensorBoard. + tensor: Tensor to be converted to protobuf + Returns: + A tensor protobuf in a `Summary` protobuf. + Raises: + ValueError: If tensor is too big to be converted to protobuf, or + tensor data type is not supported + """ + if tensor.numel() * tensor.itemsize >= (1 << 31): + raise ValueError( + "tensor is bigger than protocol buffer's hard limit of 2GB in size" + ) + + if tensor.dtype in _TENSOR_TYPE_MAP: + dtype, field_name, conversion_fn = _TENSOR_TYPE_MAP[tensor.dtype] + tensor_proto = TensorProto( + **{ + "dtype": dtype, + "tensor_shape": TensorShapeProto( + dim=[TensorShapeProto.Dim(size=x) for x in tensor.shape] + ), + field_name: conversion_fn(tensor), + }, + ) + else: + raise ValueError(f"{tag} has unsupported tensor dtype {tensor.dtype}") + + plugin_data = SummaryMetadata.PluginData(plugin_name="tensor") + smd = SummaryMetadata(plugin_data=plugin_data) + return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor_proto)]) + + +def histogram_raw(name, min, max, num, sum, sum_squares, bucket_limits, bucket_counts): + # pylint: disable=line-too-long + """Output a `Summary` protocol buffer with a histogram. + + The generated + [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) + has one summary value containing a histogram for `values`. + Args: + name: A name for the generated node. Will also serve as a series name in + TensorBoard. + min: A float or int min value + max: A float or int max value + num: Int number of values + sum: Float or int sum of all values + sum_squares: Float or int sum of squares for all values + bucket_limits: A numeric `Tensor` with upper value per bucket + bucket_counts: A numeric `Tensor` with number of values per bucket + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + """ + hist = HistogramProto( + min=min, + max=max, + num=num, + sum=sum, + sum_squares=sum_squares, + bucket_limit=bucket_limits, + bucket=bucket_counts, + ) + return Summary(value=[Summary.Value(tag=name, histo=hist)]) + + +def histogram(name, values, bins, max_bins=None): + # pylint: disable=line-too-long + """Output a `Summary` protocol buffer with a histogram. + + The generated + [`Summary`](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) + has one summary value containing a histogram for `values`. + This op reports an `InvalidArgument` error if any value is not finite. + Args: + name: A name for the generated node. Will also serve as a series name in + TensorBoard. + values: A real numeric `Tensor`. Any shape. Values to use to + build the histogram. + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + """ + values = make_np(values) + hist = make_histogram(values.astype(float), bins, max_bins) + return Summary(value=[Summary.Value(tag=name, histo=hist)]) + + +def make_histogram(values, bins, max_bins=None): + """Convert values into a histogram proto using logic from histogram.cc.""" + if values.size == 0: + raise ValueError("The input has no element.") + values = values.reshape(-1) + counts, limits = np.histogram(values, bins=bins) + num_bins = len(counts) + if max_bins is not None and num_bins > max_bins: + subsampling = num_bins // max_bins + subsampling_remainder = num_bins % subsampling + if subsampling_remainder != 0: + # pyrefly: ignore [no-matching-overload] + counts = np.pad( + counts, + pad_width=[[0, subsampling - subsampling_remainder]], + mode="constant", + constant_values=0, + ) + counts = counts.reshape(-1, subsampling).sum(axis=-1) + new_limits = np.empty((counts.size + 1,), limits.dtype) + new_limits[:-1] = limits[:-1:subsampling] + new_limits[-1] = limits[-1] + limits = new_limits + + # Find the first and the last bin defining the support of the histogram: + + cum_counts = np.cumsum(np.greater(counts, 0)) + start, end = np.searchsorted(cum_counts, [0, cum_counts[-1] - 1], side="right") + start = int(start) + end = int(end) + 1 + del cum_counts + + # TensorBoard only includes the right bin limits. To still have the leftmost limit + # included, we include an empty bin left. + # If start == 0, we need to add an empty one left, otherwise we can just include the bin left to the + # first nonzero-count bin: + counts = ( + counts[start - 1 : end] if start > 0 else np.concatenate([[0], counts[:end]]) + ) + limits = limits[start : end + 1] + + if counts.size == 0 or limits.size == 0: + raise ValueError("The histogram is empty, please file a bug report.") + + sum_sq = values.dot(values) + return HistogramProto( + min=values.min(), + max=values.max(), + num=len(values), + sum=values.sum(), + sum_squares=sum_sq, + bucket_limit=limits.tolist(), + bucket=counts.tolist(), + ) + + +def image(tag, tensor, rescale=1, dataformats="NCHW"): + """Output a `Summary` protocol buffer with images. + + The summary has up to `max_images` summary values containing images. The + images are built from `tensor` which must be 3-D with shape `[height, width, + channels]` and where `channels` can be: + * 1: `tensor` is interpreted as Grayscale. + * 3: `tensor` is interpreted as RGB. + * 4: `tensor` is interpreted as RGBA. + The `name` in the outputted Summary.Value protobufs is generated based on the + name, with a suffix depending on the max_outputs setting: + * If `max_outputs` is 1, the summary value tag is '*name*/image'. + * If `max_outputs` is greater than 1, the summary value tags are + generated sequentially as '*name*/image/0', '*name*/image/1', etc. + Args: + tag: A name for the generated node. Will also serve as a series name in + TensorBoard. + tensor: A 3-D `uint8` or `float32` `Tensor` of shape `[height, width, + channels]` where `channels` is 1, 3, or 4. + 'tensor' can either have values in [0, 1] (float32) or [0, 255] (uint8). + The image() function will scale the image values to [0, 255] by applying + a scale factor of either 1 (uint8) or 255 (float32). Out-of-range values + will be clipped. + Returns: + A scalar `Tensor` of type `string`. The serialized `Summary` protocol + buffer. + """ + tensor = make_np(tensor) + tensor = convert_to_HWC(tensor, dataformats) + # Do not assume that user passes in values in [0, 255], use data type to detect + scale_factor = _calc_scale_factor(tensor) + tensor = tensor.astype(np.float32) + tensor = (tensor * scale_factor).clip(0, 255).astype(np.uint8) + image = make_image(tensor, rescale=rescale) + return Summary(value=[Summary.Value(tag=tag, image=image)]) + + +def image_boxes( + tag, tensor_image, tensor_boxes, rescale=1, dataformats="CHW", labels=None +): + """Output a `Summary` protocol buffer with images.""" + tensor_image = make_np(tensor_image) + tensor_image = convert_to_HWC(tensor_image, dataformats) + tensor_boxes = make_np(tensor_boxes) + tensor_image = tensor_image.astype(np.float32) * _calc_scale_factor(tensor_image) + image = make_image( + tensor_image.clip(0, 255).astype(np.uint8), + rescale=rescale, + rois=tensor_boxes, + labels=labels, + ) + return Summary(value=[Summary.Value(tag=tag, image=image)]) + + +def draw_boxes(disp_image, boxes, labels=None): + # xyxy format + num_boxes = boxes.shape[0] + list_gt = range(num_boxes) + for i in list_gt: + disp_image = _draw_single_box( + disp_image, + boxes[i, 0], + boxes[i, 1], + boxes[i, 2], + boxes[i, 3], + display_str=None if labels is None else labels[i], + color="Red", + ) + return disp_image + + +def make_image(tensor, rescale=1, rois=None, labels=None): + """Convert a numpy representation of an image to Image protobuf.""" + from PIL import Image + + height, width, channel = tensor.shape + scaled_height = int(height * rescale) + scaled_width = int(width * rescale) + image = Image.fromarray(tensor) + if rois is not None: + image = draw_boxes(image, rois, labels=labels) + ANTIALIAS = Image.Resampling.LANCZOS + image = image.resize((scaled_width, scaled_height), ANTIALIAS) + import io + + output = io.BytesIO() + image.save(output, format="PNG") + image_string = output.getvalue() + output.close() + return Summary.Image( + height=height, + width=width, + colorspace=channel, + encoded_image_string=image_string, + ) + + +def video(tag, tensor, fps=4): + tensor = make_np(tensor) + tensor = _prepare_video(tensor) + # If user passes in uint8, then we don't need to rescale by 255 + scale_factor = _calc_scale_factor(tensor) + tensor = tensor.astype(np.float32) + tensor = (tensor * scale_factor).clip(0, 255).astype(np.uint8) + video = make_video(tensor, fps) + return Summary(value=[Summary.Value(tag=tag, image=video)]) + + +def make_video(tensor, fps): + try: + import moviepy # noqa: F401 + except ImportError: + print("add_video needs package moviepy") + return + try: + from moviepy import editor as mpy + except ImportError: + print( + "moviepy is installed, but can't import moviepy.editor.", + "Some packages could be missing [imageio, requests]", + ) + return + import tempfile + + _t, h, w, c = tensor.shape + + # encode sequence of images into gif string + clip = mpy.ImageSequenceClip(list(tensor), fps=fps) + + with tempfile.NamedTemporaryFile(suffix=".gif") as f: + filename = f.name + try: # newer version of moviepy use logger instead of progress_bar argument. + clip.write_gif(filename, verbose=False, logger=None) + except TypeError: + try: # older version of moviepy does not support progress_bar argument. + clip.write_gif(filename, verbose=False, progress_bar=False) + except TypeError: + clip.write_gif(filename, verbose=False) + + f.seek(0) + tensor_string = f.read() + + return Summary.Image( + height=h, width=w, colorspace=c, encoded_image_string=tensor_string + ) + + +def audio(tag, tensor, sample_rate=44100): + array = make_np(tensor) + array = array.squeeze() + if abs(array).max() > 1: + print("warning: audio amplitude out of range, auto clipped.") + array = array.clip(-1, 1) + if array.ndim != 1: + raise AssertionError("input tensor should be 1 dimensional.") + # pyrefly: ignore [no-matching-overload] + array = (array * np.iinfo(np.int16).max).astype(" 127: # weird, value > 127 breaks protobuf + num_thresholds = 127 + data = np.stack((tp, fp, tn, fn, precision, recall)) + pr_curve_plugin_data = PrCurvePluginData( + version=0, num_thresholds=num_thresholds + ).SerializeToString() + plugin_data = SummaryMetadata.PluginData( + plugin_name="pr_curves", content=pr_curve_plugin_data + ) + smd = SummaryMetadata(plugin_data=plugin_data) + tensor = TensorProto( + dtype="DT_FLOAT", + float_val=data.reshape(-1).tolist(), + tensor_shape=TensorShapeProto( + dim=[ + TensorShapeProto.Dim(size=data.shape[0]), + TensorShapeProto.Dim(size=data.shape[1]), + ] + ), + ) + return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor)]) + + +def pr_curve(tag, labels, predictions, num_thresholds=127, weights=None): + # weird, value > 127 breaks protobuf + num_thresholds = min(num_thresholds, 127) + data = compute_curve( + labels, predictions, num_thresholds=num_thresholds, weights=weights + ) + pr_curve_plugin_data = PrCurvePluginData( + version=0, num_thresholds=num_thresholds + ).SerializeToString() + plugin_data = SummaryMetadata.PluginData( + plugin_name="pr_curves", content=pr_curve_plugin_data + ) + smd = SummaryMetadata(plugin_data=plugin_data) + tensor = TensorProto( + dtype="DT_FLOAT", + float_val=data.reshape(-1).tolist(), + tensor_shape=TensorShapeProto( + dim=[ + TensorShapeProto.Dim(size=data.shape[0]), + TensorShapeProto.Dim(size=data.shape[1]), + ] + ), + ) + return Summary(value=[Summary.Value(tag=tag, metadata=smd, tensor=tensor)]) + + +# https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/pr_curve/summary.py +def compute_curve(labels, predictions, num_thresholds=None, weights=None): + _MINIMUM_COUNT = 1e-7 + + if weights is None: + weights = 1.0 + + # Compute bins of true positives and false positives. + # pyrefly: ignore [unsupported-operation] + bucket_indices = np.int32(np.floor(predictions * (num_thresholds - 1))) + float_labels = labels.astype(np.float64) + # pyrefly: ignore [unsupported-operation] + histogram_range = (0, num_thresholds - 1) + tp_buckets, _ = np.histogram( + bucket_indices, + # pyrefly: ignore [bad-argument-type] + bins=num_thresholds, + range=histogram_range, + weights=float_labels * weights, + ) + fp_buckets, _ = np.histogram( + bucket_indices, + # pyrefly: ignore [bad-argument-type] + bins=num_thresholds, + range=histogram_range, + weights=(1.0 - float_labels) * weights, + ) + + # Obtain the reverse cumulative sum. + tp = np.cumsum(tp_buckets[::-1])[::-1] + fp = np.cumsum(fp_buckets[::-1])[::-1] + tn = fp[0] - fp + fn = tp[0] - tp + precision = tp / np.maximum(_MINIMUM_COUNT, tp + fp) + recall = tp / np.maximum(_MINIMUM_COUNT, tp + fn) + return np.stack((tp, fp, tn, fn, precision, recall)) + + +def _get_tensor_summary( + name, display_name, description, tensor, content_type, components, json_config +): + """Create a tensor summary with summary metadata. + + Args: + name: Uniquely identifiable name of the summary op. Could be replaced by + combination of name and type to make it unique even outside of this + summary. + display_name: Will be used as the display name in TensorBoard. + Defaults to `name`. + description: A longform readable description of the summary data. Markdown + is supported. + tensor: Tensor to display in summary. + content_type: Type of content inside the Tensor. + components: Bitmask representing present parts (vertices, colors, etc.) that + belong to the summary. + json_config: A string, JSON-serialized dictionary of ThreeJS classes + configuration. + + Returns: + Tensor summary with metadata. + """ + import torch + from tensorboard.plugins.mesh import metadata + + tensor = torch.as_tensor(tensor) + + tensor_metadata = metadata.create_summary_metadata( + name, + display_name, + content_type, + components, + tensor.shape, + description, + json_config=json_config, + ) + + tensor = TensorProto( + dtype="DT_FLOAT", + float_val=tensor.reshape(-1).tolist(), + tensor_shape=TensorShapeProto( + dim=[ + TensorShapeProto.Dim(size=tensor.shape[0]), + TensorShapeProto.Dim(size=tensor.shape[1]), + TensorShapeProto.Dim(size=tensor.shape[2]), + ] + ), + ) + + tensor_summary = Summary.Value( + tag=metadata.get_instance_name(name, content_type), + tensor=tensor, + metadata=tensor_metadata, + ) + + return tensor_summary + + +def _get_json_config(config_dict): + """Parse and returns JSON string from python dictionary.""" + json_config = "{}" + if config_dict is not None: + json_config = json.dumps(config_dict, sort_keys=True) + return json_config + + +# https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/mesh/summary.py +def mesh( + tag, vertices, colors, faces, config_dict, display_name=None, description=None +): + """Output a merged `Summary` protocol buffer with a mesh/point cloud. + + Args: + tag: A name for this summary operation. + vertices: Tensor of shape `[dim_1, ..., dim_n, 3]` representing the 3D + coordinates of vertices. + faces: Tensor of shape `[dim_1, ..., dim_n, 3]` containing indices of + vertices within each triangle. + colors: Tensor of shape `[dim_1, ..., dim_n, 3]` containing colors for each + vertex. + display_name: If set, will be used as the display name in TensorBoard. + Defaults to `name`. + description: A longform readable description of the summary data. Markdown + is supported. + config_dict: Dictionary with ThreeJS classes names and configuration. + + Returns: + Merged summary for mesh/point cloud representation. + """ + from tensorboard.plugins.mesh import metadata + from tensorboard.plugins.mesh.plugin_data_pb2 import MeshPluginData + + json_config = _get_json_config(config_dict) + + summaries = [] + tensors = [ + (vertices, MeshPluginData.VERTEX), + (faces, MeshPluginData.FACE), + (colors, MeshPluginData.COLOR), + ] + tensors = [tensor for tensor in tensors if tensor[0] is not None] + components = metadata.get_components_bitmask( + [content_type for (tensor, content_type) in tensors] + ) + + for tensor, content_type in tensors: + summaries.append( + _get_tensor_summary( + tag, + display_name, + description, + tensor, + content_type, + components, + json_config, + ) + ) + + return Summary(value=summaries) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/writer.py b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/writer.py new file mode 100644 index 0000000000000000000000000000000000000000..b23f30854f921740971dd0e226977dcd7905be12 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/tensorboard/writer.py @@ -0,0 +1,1216 @@ +# mypy: allow-untyped-defs +"""Provide an API for writing protocol buffers to event files to be consumed by TensorBoard for visualization.""" +from __future__ import annotations + +import os +import time +from typing import TYPE_CHECKING + +import torch + +if TYPE_CHECKING: + from matplotlib.figure import Figure +from tensorboard.compat import tf +from tensorboard.compat.proto import event_pb2 +from tensorboard.compat.proto.event_pb2 import Event, SessionLog +from tensorboard.plugins.projector.projector_config_pb2 import ProjectorConfig +from tensorboard.summary.writer.event_file_writer import EventFileWriter + +from ._convert_np import make_np +from ._embedding import get_embedding_info, make_mat, make_sprite, make_tsv, write_pbtxt +from ._onnx_graph import load_onnx_graph +from ._pytorch_graph import graph +from ._utils import figure_to_image +from .summary import ( + audio, + custom_scalars, + histogram, + histogram_raw, + hparams, + image, + image_boxes, + mesh, + pr_curve, + pr_curve_raw, + scalar, + tensor_proto, + text, + video, +) + +__all__ = ["FileWriter", "SummaryWriter"] + + +class FileWriter: + """Writes protocol buffers to event files to be consumed by TensorBoard. + + The `FileWriter` class provides a mechanism to create an event file in a + given directory and add summaries and events to it. The class updates the + file contents asynchronously. This allows a training program to call methods + to add data to the file directly from the training loop, without slowing down + training. + """ + + def __init__(self, log_dir, max_queue=10, flush_secs=120, filename_suffix="") -> None: + """Create a `FileWriter` and an event file. + + On construction the writer creates a new event file in `log_dir`. + The other arguments to the constructor control the asynchronous writes to + the event file. + + Args: + log_dir: A string. Directory where event file will be written. + max_queue: Integer. Size of the queue for pending events and + summaries before one of the 'add' calls forces a flush to disk. + Default is ten items. + flush_secs: Number. How often, in seconds, to flush the + pending events and summaries to disk. Default is every two minutes. + filename_suffix: A string. Suffix added to all event filenames + in the log_dir directory. More details on filename construction in + tensorboard.summary.writer.event_file_writer.EventFileWriter. + """ + # Sometimes PosixPath is passed in and we need to coerce it to + # a string in all cases + # TODO: See if we can remove this in the future if we are + # actually the ones passing in a PosixPath + log_dir = str(log_dir) + self.event_writer = EventFileWriter( + log_dir, max_queue, flush_secs, filename_suffix + ) + + def get_logdir(self): + """Return the directory where event file will be written.""" + return self.event_writer.get_logdir() + + def add_event(self, event, step=None, walltime=None) -> None: + """Add an event to the event file. + + Args: + event: An `Event` protocol buffer. + step: Number. Optional global step value for training process + to record with the event. + walltime: float. Optional walltime to override the default (current) + walltime (from time.time()) seconds after epoch + """ + event.wall_time = time.time() if walltime is None else walltime + if step is not None: + # Make sure step is converted from numpy or other formats + # since protobuf might not convert depending on version + event.step = int(step) + self.event_writer.add_event(event) + + def add_summary(self, summary, global_step=None, walltime=None) -> None: + """Add a `Summary` protocol buffer to the event file. + + This method wraps the provided summary in an `Event` protocol buffer + and adds it to the event file. + + Args: + summary: A `Summary` protocol buffer. + global_step: Number. Optional global step value for training process + to record with the summary. + walltime: float. Optional walltime to override the default (current) + walltime (from time.time()) seconds after epoch + """ + event = event_pb2.Event(summary=summary) + self.add_event(event, global_step, walltime) + + def add_graph(self, graph_profile, walltime=None) -> None: + """Add a `Graph` and step stats protocol buffer to the event file. + + Args: + graph_profile: A `Graph` and step stats protocol buffer. + walltime: float. Optional walltime to override the default (current) + walltime (from time.time()) seconds after epoch + """ + graph = graph_profile[0] + stepstats = graph_profile[1] + event = event_pb2.Event(graph_def=graph.SerializeToString()) + self.add_event(event, None, walltime) + + trm = event_pb2.TaggedRunMetadata( + tag="step1", run_metadata=stepstats.SerializeToString() + ) + event = event_pb2.Event(tagged_run_metadata=trm) + self.add_event(event, None, walltime) + + def add_onnx_graph(self, graph, walltime=None) -> None: + """Add a `Graph` protocol buffer to the event file. + + Args: + graph: A `Graph` protocol buffer. + walltime: float. Optional walltime to override the default (current) + _get_file_writerfrom time.time()) + """ + event = event_pb2.Event(graph_def=graph.SerializeToString()) + self.add_event(event, None, walltime) + + def flush(self) -> None: + """Flushes the event file to disk. + + Call this method to make sure that all pending events have been written to + disk. + """ + self.event_writer.flush() + + def close(self) -> None: + """Flushes the event file to disk and close the file. + + Call this method when you do not need the summary writer anymore. + """ + self.event_writer.close() + + def reopen(self) -> None: + """Reopens the EventFileWriter. + + Can be called after `close()` to add more events in the same directory. + The events will go into a new events file. + Does nothing if the EventFileWriter was not closed. + """ + self.event_writer.reopen() + + +class SummaryWriter: + """Writes entries directly to event files in the log_dir to be consumed by TensorBoard. + + The `SummaryWriter` class provides a high-level API to create an event file + in a given directory and add summaries and events to it. The class updates the + file contents asynchronously. This allows a training program to call methods + to add data to the file directly from the training loop, without slowing down + training. + """ + + def __init__( + self, + log_dir=None, + comment="", + purge_step=None, + max_queue=10, + flush_secs=120, + filename_suffix="", + ) -> None: + """Create a `SummaryWriter` that will write out events and summaries to the event file. + + Args: + log_dir (str): Save directory location. Default is + runs/**CURRENT_DATETIME_HOSTNAME**, which changes after each run. + Use hierarchical folder structure to compare + between runs easily. e.g. pass in 'runs/exp1', 'runs/exp2', etc. + for each new experiment to compare across them. + comment (str): Comment log_dir suffix appended to the default + ``log_dir``. If ``log_dir`` is assigned, this argument has no effect. + purge_step (int): + When logging crashes at step :math:`T+X` and restarts at step :math:`T`, + any events whose global_step larger or equal to :math:`T` will be + purged and hidden from TensorBoard. + Note that crashed and resumed experiments should have the same ``log_dir``. + max_queue (int): Size of the queue for pending events and + summaries before one of the 'add' calls forces a flush to disk. + Default is ten items. + flush_secs (int): How often, in seconds, to flush the + pending events and summaries to disk. Default is every two minutes. + filename_suffix (str): Suffix added to all event filenames in + the log_dir directory. More details on filename construction in + tensorboard.summary.writer.event_file_writer.EventFileWriter. + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + + # create a summary writer with automatically generated folder name. + writer = SummaryWriter() + # folder location: runs/May04_22-14-54_s-MacBook-Pro.local/ + + # create a summary writer using the specified folder name. + writer = SummaryWriter("my_experiment") + # folder location: my_experiment + + # create a summary writer with comment appended. + writer = SummaryWriter(comment="LR_0.1_BATCH_16") + # folder location: runs/May04_22-14-54_s-MacBook-Pro.localLR_0.1_BATCH_16/ + + """ + torch._C._log_api_usage_once("tensorboard.create.summarywriter") + if not log_dir: + import socket + from datetime import datetime + + current_time = datetime.now().strftime("%b%d_%H-%M-%S") + log_dir = os.path.join( + "runs", current_time + "_" + socket.gethostname() + comment + ) + self.log_dir = log_dir + self.purge_step = purge_step + self.max_queue = max_queue + self.flush_secs = flush_secs + self.filename_suffix = filename_suffix + + # Initialize the file writers, but they can be cleared out on close + # and recreated later as needed. + self.file_writer = self.all_writers = None + self._get_file_writer() + + # Create default bins for histograms, see generate_testdata.py in tensorflow/tensorboard + v = 1e-12 + buckets = [] + neg_buckets = [] + while v < 1e20: + buckets.append(v) + neg_buckets.append(-v) + v *= 1.1 + self.default_bins = neg_buckets[::-1] + [0] + buckets + + def _get_file_writer(self): + """Return the default FileWriter instance. Recreates it if closed.""" + if self.all_writers is None or self.file_writer is None: + # pyrefly: ignore [bad-assignment] + self.file_writer = FileWriter( + self.log_dir, self.max_queue, self.flush_secs, self.filename_suffix + ) + # pyrefly: ignore [bad-assignment, missing-attribute] + self.all_writers = {self.file_writer.get_logdir(): self.file_writer} + if self.purge_step is not None: + most_recent_step = self.purge_step + # pyrefly: ignore [missing-attribute] + self.file_writer.add_event( + Event(step=most_recent_step, file_version="brain.Event:2") + ) + # pyrefly: ignore [missing-attribute] + self.file_writer.add_event( + Event( + step=most_recent_step, + session_log=SessionLog(status=SessionLog.START), + ) + ) + self.purge_step = None + return self.file_writer + + def get_logdir(self): + """Return the directory where event files will be written.""" + return self.log_dir + + def add_hparams( + self, + hparam_dict, + metric_dict, + hparam_domain_discrete=None, + run_name=None, + global_step=None, + ) -> None: + """Add a set of hyperparameters to be compared in TensorBoard. + + Args: + hparam_dict (dict): Each key-value pair in the dictionary is the + name of the hyper parameter and its corresponding value. + The type of the value can be one of `bool`, `string`, `float`, + `int`, or `None`. + metric_dict (dict): Each key-value pair in the dictionary is the + name of the metric and its corresponding value. Note that the key used + here should be unique in the tensorboard record. Otherwise the value + you added by ``add_scalar`` will be displayed in hparam plugin. In most + cases, this is unwanted. + hparam_domain_discrete: (Optional[Dict[str, List[Any]]]) A dictionary that + contains names of the hyperparameters and all discrete values they can hold + run_name (str): Name of the run, to be included as part of the logdir. + If unspecified, will use current timestamp. + global_step (int): Global step value to record + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + with SummaryWriter() as w: + for i in range(5): + w.add_hparams({'lr': 0.1*i, 'bsize': i}, + {'hparam/accuracy': 10*i, 'hparam/loss': 10*i}) + + Expected result: + + .. image:: _static/img/tensorboard/add_hparam.png + :scale: 50 % + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_hparams") + if type(hparam_dict) is not dict or type(metric_dict) is not dict: + raise TypeError("hparam_dict and metric_dict should be dictionary.") + exp, ssi, sei = hparams(hparam_dict, metric_dict, hparam_domain_discrete) + + if not run_name: + run_name = str(time.time()) + logdir = os.path.join(self._get_file_writer().get_logdir(), run_name) + with SummaryWriter(log_dir=logdir) as w_hp: + w_hp.file_writer.add_summary(exp, global_step) + w_hp.file_writer.add_summary(ssi, global_step) + w_hp.file_writer.add_summary(sei, global_step) + for k, v in metric_dict.items(): + w_hp.add_scalar(k, v, global_step) + + def add_scalar( + self, + tag, + scalar_value, + global_step=None, + walltime=None, + new_style=False, + double_precision=False, + ) -> None: + """Add scalar data to summary. + + Args: + tag (str): Data identifier + scalar_value (float or string/blobname): Value to save + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + with seconds after epoch of event + new_style (boolean): Whether to use new style (tensor field) or old + style (simple_value field). New style could lead to faster data loading. + Examples:: + + from torch.utils.tensorboard import SummaryWriter + writer = SummaryWriter() + x = range(100) + for i in x: + writer.add_scalar('y=2x', i * 2, i) + writer.close() + + Expected result: + + .. image:: _static/img/tensorboard/add_scalar.png + :scale: 50 % + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_scalar") + + summary = scalar( + tag, scalar_value, new_style=new_style, double_precision=double_precision + ) + self._get_file_writer().add_summary(summary, global_step, walltime) + + def add_scalars(self, main_tag, tag_scalar_dict, global_step=None, walltime=None) -> None: + """Add many scalar data to summary. + + Args: + main_tag (str): The parent name for the tags + tag_scalar_dict (dict): Key-value pair storing the tag and corresponding values + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + writer = SummaryWriter() + r = 5 + for i in range(100): + writer.add_scalars('run_14h', {'xsinx':i*np.sin(i/r), + 'xcosx':i*np.cos(i/r), + 'tanx': np.tan(i/r)}, i) + writer.close() + # This call adds three values to the same scalar plot with the tag + # 'run_14h' in TensorBoard's scalar section. + + Expected result: + + .. image:: _static/img/tensorboard/add_scalars.png + :scale: 50 % + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_scalars") + walltime = time.time() if walltime is None else walltime + fw_logdir = self._get_file_writer().get_logdir() + for tag, scalar_value in tag_scalar_dict.items(): + fw_tag = fw_logdir + "/" + main_tag.replace("/", "_") + "_" + tag + if self.all_writers is None: + raise AssertionError("self.all_writers is None") + if fw_tag in self.all_writers: + fw = self.all_writers[fw_tag] + else: + fw = FileWriter( + fw_tag, self.max_queue, self.flush_secs, self.filename_suffix + ) + self.all_writers[fw_tag] = fw + fw.add_summary(scalar(main_tag, scalar_value), global_step, walltime) + + def add_tensor( + self, + tag, + tensor, + global_step=None, + walltime=None, + ) -> None: + """Add tensor data to summary. + + Args: + tag (str): Data identifier + tensor (torch.Tensor): tensor to save + global_step (int): Global step value to record + Examples:: + + from torch.utils.tensorboard import SummaryWriter + writer = SummaryWriter() + x = torch.tensor([1,2,3]) + writer.add_scalar('x', x) + writer.close() + + Expected result: + Summary::tensor::float_val [1,2,3] + ::tensor::shape [3] + ::tag 'x' + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_tensor") + + summary = tensor_proto(tag, tensor) + self._get_file_writer().add_summary(summary, global_step, walltime) + + def add_histogram( + self, + tag, + values, + global_step=None, + bins="tensorflow", + walltime=None, + max_bins=None, + ) -> None: + """Add histogram to summary. + + Args: + tag (str): Data identifier + values (torch.Tensor, numpy.ndarray, or string/blobname): Values to build histogram + global_step (int): Global step value to record + bins (str): One of {'tensorflow','auto', 'fd', ...}. This determines how the bins are made. You can find + other options in: https://numpy.org/doc/stable/reference/generated/numpy.histogram.html + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + import numpy as np + writer = SummaryWriter() + for i in range(10): + x = np.random.random(1000) + writer.add_histogram('distribution centers', x + i, i) + writer.close() + + Expected result: + + .. image:: _static/img/tensorboard/add_histogram.png + :scale: 50 % + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_histogram") + if isinstance(bins, str) and bins == "tensorflow": + bins = self.default_bins + self._get_file_writer().add_summary( + histogram(tag, values, bins, max_bins=max_bins), global_step, walltime + ) + + def add_histogram_raw( + self, + tag, + min, + max, + num, + sum, + sum_squares, + bucket_limits, + bucket_counts, + global_step=None, + walltime=None, + ) -> None: + """Add histogram with raw data. + + Args: + tag (str): Data identifier + min (float or int): Min value + max (float or int): Max value + num (int): Number of values + sum (float or int): Sum of all values + sum_squares (float or int): Sum of squares for all values + bucket_limits (torch.Tensor, numpy.ndarray): Upper value per bucket. + The number of elements of it should be the same as `bucket_counts`. + bucket_counts (torch.Tensor, numpy.ndarray): Number of values per bucket + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + see: https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/histogram/README.md + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + import numpy as np + writer = SummaryWriter() + dummy_data = [] + for idx, value in enumerate(range(50)): + dummy_data += [idx + 0.001] * value + + bins = list(range(50+2)) + bins = np.array(bins) + values = np.array(dummy_data).astype(float).reshape(-1) + counts, limits = np.histogram(values, bins=bins) + sum_sq = values.dot(values) + writer.add_histogram_raw( + tag='histogram_with_raw_data', + min=values.min(), + max=values.max(), + num=len(values), + sum=values.sum(), + sum_squares=sum_sq, + bucket_limits=limits[1:].tolist(), + bucket_counts=counts.tolist(), + global_step=0) + writer.close() + + Expected result: + + .. image:: _static/img/tensorboard/add_histogram_raw.png + :scale: 50 % + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_histogram_raw") + if len(bucket_limits) != len(bucket_counts): + raise ValueError( + "len(bucket_limits) != len(bucket_counts), see the document." + ) + self._get_file_writer().add_summary( + histogram_raw( + tag, min, max, num, sum, sum_squares, bucket_limits, bucket_counts + ), + global_step, + walltime, + ) + + def add_image( + self, tag, img_tensor, global_step=None, walltime=None, dataformats="CHW" + ) -> None: + """Add image data to summary. + + Note that this requires the ``pillow`` package. + + Args: + tag (str): Data identifier + img_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Image data + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + dataformats (str): Image data format specification of the form + CHW, HWC, HW, WH, etc. + Shape: + img_tensor: Default is :math:`(3, H, W)`. You can use ``torchvision.utils.make_grid()`` to + convert a batch of tensor into 3xHxW format or call ``add_images`` and let us do the job. + Tensor with :math:`(1, H, W)`, :math:`(H, W)`, :math:`(H, W, 3)` is also suitable as long as + corresponding ``dataformats`` argument is passed, e.g. ``CHW``, ``HWC``, ``HW``. + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + import numpy as np + img = np.zeros((3, 100, 100)) + img[0] = np.arange(0, 10000).reshape(100, 100) / 10000 + img[1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000 + + img_HWC = np.zeros((100, 100, 3)) + img_HWC[:, :, 0] = np.arange(0, 10000).reshape(100, 100) / 10000 + img_HWC[:, :, 1] = 1 - np.arange(0, 10000).reshape(100, 100) / 10000 + + writer = SummaryWriter() + writer.add_image('my_image', img, 0) + + # If you have non-default dimension setting, set the dataformats argument. + writer.add_image('my_image_HWC', img_HWC, 0, dataformats='HWC') + writer.close() + + Expected result: + + .. image:: _static/img/tensorboard/add_image.png + :scale: 50 % + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_image") + self._get_file_writer().add_summary( + image(tag, img_tensor, dataformats=dataformats), global_step, walltime + ) + + def add_images( + self, tag, img_tensor, global_step=None, walltime=None, dataformats="NCHW" + ) -> None: + """Add batched image data to summary. + + Note that this requires the ``pillow`` package. + + Args: + tag (str): Data identifier + img_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Image data + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + dataformats (str): Image data format specification of the form + NCHW, NHWC, CHW, HWC, HW, WH, etc. + Shape: + img_tensor: Default is :math:`(N, 3, H, W)`. If ``dataformats`` is specified, other shape will be + accepted. e.g. NCHW or NHWC. + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + import numpy as np + + img_batch = np.zeros((16, 3, 100, 100)) + for i in range(16): + img_batch[i, 0] = np.arange(0, 10000).reshape(100, 100) / 10000 / 16 * i + img_batch[i, 1] = (1 - np.arange(0, 10000).reshape(100, 100) / 10000) / 16 * i + + writer = SummaryWriter() + writer.add_images('my_image_batch', img_batch, 0) + writer.close() + + Expected result: + + .. image:: _static/img/tensorboard/add_images.png + :scale: 30 % + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_images") + self._get_file_writer().add_summary( + image(tag, img_tensor, dataformats=dataformats), global_step, walltime + ) + + def add_image_with_boxes( + self, + tag, + img_tensor, + box_tensor, + global_step=None, + walltime=None, + rescale=1, + dataformats="CHW", + labels=None, + ) -> None: + """Add image and draw bounding boxes on the image. + + Args: + tag (str): Data identifier + img_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Image data + box_tensor (torch.Tensor, numpy.ndarray, or string/blobname): Box data (for detected objects) + box should be represented as [x1, y1, x2, y2]. + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + rescale (float): Optional scale override + dataformats (str): Image data format specification of the form + NCHW, NHWC, CHW, HWC, HW, WH, etc. + labels (list of string): The label to be shown for each bounding box. + Shape: + img_tensor: Default is :math:`(3, H, W)`. It can be specified with ``dataformats`` argument. + e.g. CHW or HWC + + box_tensor: (torch.Tensor, numpy.ndarray, or string/blobname): NX4, where N is the number of + boxes and each 4 elements in a row represents (xmin, ymin, xmax, ymax). + """ + torch._C._log_api_usage_once("tensorboard.logging.add_image_with_boxes") + if labels is not None: + if isinstance(labels, str): + labels = [labels] + if len(labels) != box_tensor.shape[0]: + labels = None + self._get_file_writer().add_summary( + image_boxes( + tag, + img_tensor, + box_tensor, + rescale=rescale, + dataformats=dataformats, + labels=labels, + ), + global_step, + walltime, + ) + + def add_figure( + self, + tag: str, + figure: Figure | list[Figure], + global_step: int | None = None, + close: bool = True, + walltime: float | None = None, + ) -> None: + """Render matplotlib figure into an image and add it to summary. + + Note that this requires the ``matplotlib`` package. + + Args: + tag: Data identifier + figure: Figure or a list of figures + global_step: Global step value to record + close: Flag to automatically close the figure + walltime: Optional override default walltime (time.time()) + seconds after epoch of event + """ + torch._C._log_api_usage_once("tensorboard.logging.add_figure") + if isinstance(figure, list): + self.add_image( + tag, + figure_to_image(figure, close), + global_step, + walltime, + dataformats="NCHW", + ) + else: + self.add_image( + tag, + figure_to_image(figure, close), + global_step, + walltime, + dataformats="CHW", + ) + + def add_video(self, tag, vid_tensor, global_step=None, fps=4, walltime=None) -> None: + """Add video data to summary. + + Note that this requires the ``moviepy`` package. + + Args: + tag (str): Data identifier + vid_tensor (torch.Tensor): Video data + global_step (int): Global step value to record + fps (float or int): Frames per second + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + Shape: + vid_tensor: :math:`(N, T, C, H, W)`. The values should lie in [0, 255] for type `uint8` or [0, 1] for type `float`. + """ + torch._C._log_api_usage_once("tensorboard.logging.add_video") + self._get_file_writer().add_summary( + video(tag, vid_tensor, fps), global_step, walltime + ) + + def add_audio( + self, tag, snd_tensor, global_step=None, sample_rate=44100, walltime=None + ) -> None: + """Add audio data to summary. + + Args: + tag (str): Data identifier + snd_tensor (torch.Tensor): Sound data + global_step (int): Global step value to record + sample_rate (int): sample rate in Hz + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + Shape: + snd_tensor: :math:`(1, L)`. The values should lie between [-1, 1]. + """ + torch._C._log_api_usage_once("tensorboard.logging.add_audio") + self._get_file_writer().add_summary( + audio(tag, snd_tensor, sample_rate=sample_rate), global_step, walltime + ) + + def add_text(self, tag, text_string, global_step=None, walltime=None) -> None: + """Add text data to summary. + + Args: + tag (str): Data identifier + text_string (str): String to save + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + Examples:: + + writer.add_text('lstm', 'This is an lstm', 0) + writer.add_text('rnn', 'This is an rnn', 10) + """ + torch._C._log_api_usage_once("tensorboard.logging.add_text") + self._get_file_writer().add_summary( + text(tag, text_string), global_step, walltime + ) + + def add_onnx_graph(self, prototxt) -> None: + torch._C._log_api_usage_once("tensorboard.logging.add_onnx_graph") + self._get_file_writer().add_onnx_graph(load_onnx_graph(prototxt)) + + def add_graph( + self, model, input_to_model=None, verbose=False, use_strict_trace=True + ) -> None: + """Add graph data to summary. + + Args: + model (torch.nn.Module): Model to draw. + input_to_model (torch.Tensor or list of torch.Tensor): A variable or a tuple of + variables to be fed. + verbose (bool): Whether to print graph structure in console. + use_strict_trace (bool): Whether to pass keyword argument `strict` to + `torch.jit.trace`. Pass False when you want the tracer to + record your mutable container types (list, dict) + """ + torch._C._log_api_usage_once("tensorboard.logging.add_graph") + # A valid PyTorch model should have a 'forward' method + self._get_file_writer().add_graph( + graph(model, input_to_model, verbose, use_strict_trace) + ) + + @staticmethod + def _encode(rawstr): + # I'd use urllib but, I'm unsure about the differences from python3 to python2, etc. + retval = rawstr + retval = retval.replace("%", f"%{ord('%'):02x}") + retval = retval.replace("/", f"%{ord('/'):02x}") + retval = retval.replace("\\", "%%%02x" % (ord("\\"))) # noqa: UP031 + return retval + + def add_embedding( + self, + mat, + metadata=None, + label_img=None, + global_step=None, + tag="default", + metadata_header=None, + ) -> None: + """Add embedding projector data to summary. + + Args: + mat (torch.Tensor or numpy.ndarray): A matrix which each row is the feature vector of the data point + metadata (list): A list of labels, each element will be converted to string + label_img (torch.Tensor): Images correspond to each data point + global_step (int): Global step value to record + tag (str): Name for the embedding + metadata_header (list): A list of headers for multi-column metadata. If given, each metadata must be + a list with values corresponding to headers. + Shape: + mat: :math:`(N, D)`, where N is number of data and D is feature dimension + + label_img: :math:`(N, C, H, W)` + + Examples:: + + import keyword + import torch + meta = [] + while len(meta)<100: + meta = meta+keyword.kwlist # get some strings + meta = meta[:100] + + for i, v in enumerate(meta): + meta[i] = v+str(i) + + label_img = torch.rand(100, 3, 10, 32) + for i in range(100): + label_img[i]*=i/100.0 + + writer.add_embedding(torch.randn(100, 5), metadata=meta, label_img=label_img) + writer.add_embedding(torch.randn(100, 5), label_img=label_img) + writer.add_embedding(torch.randn(100, 5), metadata=meta) + + .. note:: + Categorical (i.e. non-numeric) metadata cannot have more than 50 unique values if they are to be used for + coloring in the embedding projector. + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_embedding") + mat = make_np(mat) + if global_step is None: + global_step = 0 + # clear pbtxt? + + # Maybe we should encode the tag so slashes don't trip us up? + # I don't think this will mess us up, but better safe than sorry. + subdir = f"{str(global_step).zfill(5)}/{self._encode(tag)}" + save_path = os.path.join(self._get_file_writer().get_logdir(), subdir) + + fs = tf.io.gfile + if fs.exists(save_path): + if fs.isdir(save_path): + print( + "warning: Embedding dir exists, did you set global_step for add_embedding()?" + ) + else: + raise NotADirectoryError( + f"Path: `{save_path}` exists, but is a file. Cannot proceed." + ) + else: + fs.makedirs(save_path) + + if metadata is not None: + if mat.shape[0] != len( + metadata + ): + raise AssertionError("#labels should equal with #data points") + make_tsv(metadata, save_path, metadata_header=metadata_header) + + if label_img is not None: + if mat.shape[0] != label_img.shape[0]: + raise AssertionError("#images should equal with #data points") + make_sprite(label_img, save_path) + + if mat.ndim != 2: + raise AssertionError("mat should be 2D, where mat.size(0) is the number of data points") + make_mat(mat, save_path) + + # Filesystem doesn't necessarily have append semantics, so we store an + # internal buffer to append to and re-write whole file after each + # embedding is added + if not hasattr(self, "_projector_config"): + self._projector_config = ProjectorConfig() + embedding_info = get_embedding_info( + metadata, label_img, subdir, global_step, tag + ) + self._projector_config.embeddings.extend([embedding_info]) + + + from google.protobuf import text_format + + config_pbtxt = text_format.MessageToString(self._projector_config) + write_pbtxt(self._get_file_writer().get_logdir(), config_pbtxt) + + def add_pr_curve( + self, + tag, + labels, + predictions, + global_step=None, + num_thresholds=127, + weights=None, + walltime=None, + ) -> None: + """Add precision recall curve. + + Plotting a precision-recall curve lets you understand your model's + performance under different threshold settings. With this function, + you provide the ground truth labeling (T/F) and prediction confidence + (usually the output of your model) for each target. The TensorBoard UI + will let you choose the threshold interactively. + + Args: + tag (str): Data identifier + labels (torch.Tensor, numpy.ndarray, or string/blobname): + Ground truth data. Binary label for each element. + predictions (torch.Tensor, numpy.ndarray, or string/blobname): + The probability that an element be classified as true. + Value should be in [0, 1] + global_step (int): Global step value to record + num_thresholds (int): Number of thresholds used to draw the curve. + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + import numpy as np + labels = np.random.randint(2, size=100) # binary label + predictions = np.random.rand(100) + writer = SummaryWriter() + writer.add_pr_curve('pr_curve', labels, predictions, 0) + writer.close() + + """ + torch._C._log_api_usage_once("tensorboard.logging.add_pr_curve") + labels, predictions = make_np(labels), make_np(predictions) + self._get_file_writer().add_summary( + pr_curve(tag, labels, predictions, num_thresholds, weights), + global_step, + walltime, + ) + + def add_pr_curve_raw( + self, + tag, + true_positive_counts, + false_positive_counts, + true_negative_counts, + false_negative_counts, + precision, + recall, + global_step=None, + num_thresholds=127, + weights=None, + walltime=None, + ) -> None: + """Add precision recall curve with raw data. + + Args: + tag (str): Data identifier + true_positive_counts (torch.Tensor, numpy.ndarray, or string/blobname): true positive counts + false_positive_counts (torch.Tensor, numpy.ndarray, or string/blobname): false positive counts + true_negative_counts (torch.Tensor, numpy.ndarray, or string/blobname): true negative counts + false_negative_counts (torch.Tensor, numpy.ndarray, or string/blobname): false negative counts + precision (torch.Tensor, numpy.ndarray, or string/blobname): precision + recall (torch.Tensor, numpy.ndarray, or string/blobname): recall + global_step (int): Global step value to record + num_thresholds (int): Number of thresholds used to draw the curve. + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + see: https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/pr_curve/README.md + """ + torch._C._log_api_usage_once("tensorboard.logging.add_pr_curve_raw") + self._get_file_writer().add_summary( + pr_curve_raw( + tag, + true_positive_counts, + false_positive_counts, + true_negative_counts, + false_negative_counts, + precision, + recall, + num_thresholds, + weights, + ), + global_step, + walltime, + ) + + def add_custom_scalars_multilinechart( + self, tags, category="default", title="untitled" + ) -> None: + """Shorthand for creating multilinechart. Similar to ``add_custom_scalars()``, but the only necessary argument is *tags*. + + Args: + tags (list): list of tags that have been used in ``add_scalar()`` + + Examples:: + + writer.add_custom_scalars_multilinechart(['twse/0050', 'twse/2330']) + """ + torch._C._log_api_usage_once( + "tensorboard.logging.add_custom_scalars_multilinechart" + ) + layout = {category: {title: ["Multiline", tags]}} + self._get_file_writer().add_summary(custom_scalars(layout)) + + def add_custom_scalars_marginchart( + self, tags, category="default", title="untitled" + ) -> None: + """Shorthand for creating marginchart. + + Similar to ``add_custom_scalars()``, but the only necessary argument is *tags*, + which should have exactly 3 elements. + + Args: + tags (list): list of tags that have been used in ``add_scalar()`` + + Examples:: + + writer.add_custom_scalars_marginchart(['twse/0050', 'twse/2330', 'twse/2006']) + """ + torch._C._log_api_usage_once( + "tensorboard.logging.add_custom_scalars_marginchart" + ) + if len(tags) != 3: + raise AssertionError(f"Expected 3 tags, got {len(tags)}.") + layout = {category: {title: ["Margin", tags]}} + self._get_file_writer().add_summary(custom_scalars(layout)) + + def add_custom_scalars(self, layout) -> None: + """Create special chart by collecting charts tags in 'scalars'. + + NOTE: This function can only be called once for each SummaryWriter() object. + + Because it only provides metadata to tensorboard, the function can be called before or after the training loop. + + Args: + layout (dict): {categoryName: *charts*}, where *charts* is also a dictionary + {chartName: *ListOfProperties*}. The first element in *ListOfProperties* is the chart's type + (one of **Multiline** or **Margin**) and the second element should be a list containing the tags + you have used in add_scalar function, which will be collected into the new chart. + + Examples:: + + layout = {'Taiwan':{'twse':['Multiline',['twse/0050', 'twse/2330']]}, + 'USA':{ 'dow':['Margin', ['dow/aaa', 'dow/bbb', 'dow/ccc']], + 'nasdaq':['Margin', ['nasdaq/aaa', 'nasdaq/bbb', 'nasdaq/ccc']]}} + + writer.add_custom_scalars(layout) + """ + torch._C._log_api_usage_once("tensorboard.logging.add_custom_scalars") + self._get_file_writer().add_summary(custom_scalars(layout)) + + def add_mesh( + self, + tag, + vertices, + colors=None, + faces=None, + config_dict=None, + global_step=None, + walltime=None, + ) -> None: + """Add meshes or 3D point clouds to TensorBoard. + + The visualization is based on Three.js, + so it allows users to interact with the rendered object. Besides the basic definitions + such as vertices, faces, users can further provide camera parameter, lighting condition, etc. + Please check https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene for + advanced usage. + + Args: + tag (str): Data identifier + vertices (torch.Tensor): List of the 3D coordinates of vertices. + colors (torch.Tensor): Colors for each vertex + faces (torch.Tensor): Indices of vertices within each triangle. (Optional) + config_dict: Dictionary with ThreeJS classes names and configuration. + global_step (int): Global step value to record + walltime (float): Optional override default walltime (time.time()) + seconds after epoch of event + + Shape: + vertices: :math:`(B, N, 3)`. (batch, number_of_vertices, channels) + + colors: :math:`(B, N, 3)`. The values should lie in [0, 255] for type `uint8` or [0, 1] for type `float`. + + faces: :math:`(B, N, 3)`. The values should lie in [0, number_of_vertices] for type `uint8`. + + Examples:: + + from torch.utils.tensorboard import SummaryWriter + vertices_tensor = torch.as_tensor([ + [1, 1, 1], + [-1, -1, 1], + [1, -1, -1], + [-1, 1, -1], + ], dtype=torch.float).unsqueeze(0) + colors_tensor = torch.as_tensor([ + [255, 0, 0], + [0, 255, 0], + [0, 0, 255], + [255, 0, 255], + ], dtype=torch.int).unsqueeze(0) + faces_tensor = torch.as_tensor([ + [0, 2, 3], + [0, 3, 1], + [0, 1, 2], + [1, 3, 2], + ], dtype=torch.int).unsqueeze(0) + + writer = SummaryWriter() + writer.add_mesh('my_mesh', vertices=vertices_tensor, colors=colors_tensor, faces=faces_tensor) + + writer.close() + """ + torch._C._log_api_usage_once("tensorboard.logging.add_mesh") + self._get_file_writer().add_summary( + mesh(tag, vertices, colors, faces, config_dict), global_step, walltime + ) + + def flush(self) -> None: + """Flushes the event file to disk. + + Call this method to make sure that all pending events have been written to + disk. + """ + if self.all_writers is None: + return + for writer in self.all_writers.values(): + writer.flush() + + def close(self) -> None: + if self.all_writers is None: + return # ignore double close + for writer in self.all_writers.values(): + writer.flush() + writer.close() + # pyrefly: ignore [bad-assignment] + self.file_writer = self.all_writers = None + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() diff --git a/.venv/lib/python3.12/site-packages/torch/utils/throughput_benchmark.py b/.venv/lib/python3.12/site-packages/torch/utils/throughput_benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..e7637c1188d072c8702dcbeb024b86d9c16e8158 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/throughput_benchmark.py @@ -0,0 +1,161 @@ +# mypy: allow-untyped-defs + +import torch._C + + +def format_time(time_us=None, time_ms=None, time_s=None) -> str: + """Define time formatting.""" + if sum([time_us is not None, time_ms is not None, time_s is not None]) != 1: + raise AssertionError("Expected only one of time_us, time_ms, time_s is given.") + + US_IN_SECOND = 1e6 + US_IN_MS = 1e3 + + if time_us is None: + if time_ms is not None: + time_us = time_ms * US_IN_MS + elif time_s is not None: + time_us = time_s * US_IN_SECOND + else: + raise AssertionError("Shouldn't reach here :)") + + if time_us >= US_IN_SECOND: + return f'{time_us / US_IN_SECOND:.3f}s' + if time_us >= US_IN_MS: + return f'{time_us / US_IN_MS:.3f}ms' + return f'{time_us:.3f}us' + + +class ExecutionStats: + def __init__(self, c_stats, benchmark_config) -> None: + self._c_stats = c_stats + self.benchmark_config = benchmark_config + + @property + def latency_avg_ms(self): + return self._c_stats.latency_avg_ms + + @property + def num_iters(self): + return self._c_stats.num_iters + + @property + def iters_per_second(self): + """Return total number of iterations per second across all calling threads.""" + return self.num_iters / self.total_time_seconds + + @property + def total_time_seconds(self): + return self.num_iters * ( + self.latency_avg_ms / 1000.0) / self.benchmark_config.num_calling_threads + + def __str__(self) -> str: + return '\n'.join([ + "Average latency per example: " + format_time(time_ms=self.latency_avg_ms), + f"Total number of iterations: {self.num_iters}", + f"Total number of iterations per second (across all threads): {self.iters_per_second:.2f}", + "Total time: " + format_time(time_s=self.total_time_seconds) + ]) + + +class ThroughputBenchmark: + """ + This class is a wrapper around a c++ component throughput_benchmark::ThroughputBenchmark. + + This wrapper on the throughput_benchmark::ThroughputBenchmark component is responsible + for executing a PyTorch module (nn.Module or ScriptModule) under an inference + server like load. It can emulate multiple calling threads to a single module + provided. In the future we plan to enhance this component to support inter and + intra-op parallelism as well as multiple models running in a single process. + + Please note that even though nn.Module is supported, it might incur an overhead + from the need to hold GIL every time we execute Python code or pass around + inputs as Python objects. As soon as you have a ScriptModule version of your + model for inference deployment it is better to switch to using it in this + benchmark. + + Example:: + + >>> # xdoctest: +SKIP("undefined vars") + >>> from torch.utils import ThroughputBenchmark + >>> bench = ThroughputBenchmark(my_module) + >>> # Pre-populate benchmark's data set with the inputs + >>> for input in inputs: + ... # Both args and kwargs work, same as any PyTorch Module / ScriptModule + ... bench.add_input(input[0], x2=input[1]) + >>> # Inputs supplied above are randomly used during the execution + >>> stats = bench.benchmark( + ... num_calling_threads=4, + ... num_warmup_iters = 100, + ... num_iters = 1000, + ... ) + >>> print("Avg latency (ms): {}".format(stats.latency_avg_ms)) + >>> print("Number of iterations: {}".format(stats.num_iters)) + """ + + def __init__(self, module) -> None: + if isinstance(module, torch.jit.ScriptModule): + self._benchmark = torch._C.ThroughputBenchmark(module._c) + else: + self._benchmark = torch._C.ThroughputBenchmark(module) + + def run_once(self, *args, **kwargs): + """ + Given input id (input_idx) run benchmark once and return prediction. + + This is useful for testing that benchmark actually runs the module you + want it to run. input_idx here is an index into inputs array populated + by calling add_input() method. + """ + return self._benchmark.run_once(*args, **kwargs) + + def add_input(self, *args, **kwargs) -> None: + """ + Store a single input to a module into the benchmark memory and keep it there. + + During the benchmark execution every thread is going to pick up a + random input from all the inputs ever supplied to the benchmark via + this function. + """ + self._benchmark.add_input(*args, **kwargs) + + def benchmark( + self, + num_calling_threads=1, + num_warmup_iters=10, + num_iters=100, + profiler_output_path=""): + """ + Run a benchmark on the module. + + Args: + num_warmup_iters (int): Warmup iters are used to make sure we run a module + a few times before actually measuring things. This way we avoid cold + caches and any other similar problems. This is the number of warmup + iterations for each of the threads separately + + num_iters (int): Number of iterations the benchmark should run with. + This number is separate from the warmup iterations. Also the number is + shared across all the threads. Once the num_iters iterations across all + the threads is reached, we will stop execution. Though total number of + iterations might be slightly larger. Which is reported as + stats.num_iters where stats is the result of this function + + profiler_output_path (str): Location to save Autograd Profiler trace. + If not empty, Autograd Profiler will be enabled for the main benchmark + execution (but not the warmup phase). The full trace will be saved + into the file path provided by this argument + + + This function returns BenchmarkExecutionStats object which is defined via pybind11. + It currently has two fields: + - num_iters - number of actual iterations the benchmark have made + - avg_latency_ms - average time it took to infer on one input example in milliseconds + """ + config = torch._C.BenchmarkConfig() + config.num_calling_threads = num_calling_threads + config.num_warmup_iters = num_warmup_iters + config.num_iters = num_iters + config.profiler_output_path = profiler_output_path + c_stats = self._benchmark.benchmark(config) + return ExecutionStats(c_stats, config) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/viz/__init__.py b/.venv/lib/python3.12/site-packages/torch/utils/viz/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torch/utils/viz/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/viz/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfeeeea66921f8ddf64316b12ec75c180c5a05a2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/viz/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/viz/__pycache__/_cycles.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/utils/viz/__pycache__/_cycles.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3185b7d3e029ef18fe6133e67c84fb47405baa3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/utils/viz/__pycache__/_cycles.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/utils/viz/_cycles.py b/.venv/lib/python3.12/site-packages/torch/utils/viz/_cycles.py new file mode 100644 index 0000000000000000000000000000000000000000..d093f9ec3160f0207eef7495c24aa854ac6604f3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/viz/_cycles.py @@ -0,0 +1,505 @@ +# mypy: allow-untyped-defs +import gc +import sys +from typing import Any, NamedTuple +import types +import weakref +import json +from tempfile import NamedTemporaryFile +import torch +from torch.cuda._memory_viz import _frames_fmt, _block_extra +import atexit +import logging +logger = logging.getLogger(__name__) + +def observe_garbage(observer): + enabled = True + + def disable() -> None: + # when GC runs during exit, things like `sys` will already be unloaded + # so we have to disable the callback to avoid hitting errors. + nonlocal enabled + enabled = False + atexit.register(disable) + + def gc_callback(phase, info) -> None: + nonlocal enabled + if not enabled: + return + if phase == "start": + gc.set_debug(gc.DEBUG_SAVEALL) + elif phase == "stop": + orig_trace = sys.getprofile() + self_return = [False] + + def do_collect(*args, **kwargs): + nonlocal enabled + if not self_return[0]: + self_return[0] = True + else: + sys.setprofile(orig_trace) + enabled = False + try: + # things in gc.garbage have survived a collection + # so to free them we have to collect a generation greater than them + # but that might _also_ free other stuff and we don't want to miss + # that stuff. So we have to now force gc at the highest level here, + # report all of what we found, _then_ we can free it up. + if info['generation'] != 2: + gc.collect() + observer(gc.garbage) + gc.garbage.clear() + # we have to re-run GC to clean up the cycles + # we saved from before. + gc.set_debug(0) + before = torch.cuda.memory_allocated() + gc.collect() + after = torch.cuda.memory_allocated() + if before != after: + logger.warning("CUDA Memory changed during GC, %d bytes freed.", before - after) + finally: + enabled = True + if orig_trace is not None: + return orig_trace(*args, **kwargs) + sys.setprofile(do_collect) + + gc.callbacks.append(gc_callback) + + # provide a way to disarm the callback + def remove() -> None: + gc.callbacks.remove(gc_callback) + return remove + +# Function to visualize cycles adapted from refcycle: +# Copyright 2013 Mark Dickinson +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +def _get_cell_type(): + def f(x=None): + return lambda: x + return type(f().__closure__[0]) + +CellType = _get_cell_type() + +def annotated_references(obj): + """ + Return known information about references held by the given object. + + Returns a mapping from referents to lists of descriptions. Note that there + may be more than one edge leading to any particular referent; hence the + need for a list. Descriptions are currently strings. + + """ + references: dict[int, list[str]] = {} + + def add_reference(name, obj) -> None: + references.setdefault(id(obj), []).append(name) + + def add_attrs(*attrs) -> None: + for attr in attrs: + if hasattr(obj, attr): + add_reference(attr, getattr(obj, attr)) + + def add_cell_references() -> None: + try: + add_attrs("cell_contents") + except ValueError: + # if cell_contents is empty, + # accessing it raises ValueError + # in this case there is no object to + # annotate + pass + + def add_function_references() -> None: + add_attrs("__defaults__", + "__closure__", + "__globals__", + "__code__", + "__name__", + "__module__", + "__doc__" + "__qualname__", + "__annotations__", + "__kwdefaults__") + + + def add_sequence_references() -> None: + for position, item in enumerate(obj): + add_reference(f"[{position}]", item) + + def add_dict_references() -> None: + for key, value in obj.items(): + add_reference("key", key) + add_reference(f"[{repr(key)}]", value) + + def add_set_references() -> None: + for elt in obj: + add_reference("element", elt) + + def add_bound_method_references() -> None: + add_attrs("__self__", "__func__", "im_class") + + def add_weakref_references() -> None: + # For subclasses of weakref, we can't reliably distinguish the + # callback (if any) from other attributes. + if type(obj) is weakref.ref: + referents = gc.get_referents(obj) + if len(referents) == 1: + target = referents[0] + add_reference("__callback__", target) + + + def add_frame_references() -> None: + f_locals = obj.f_locals + add_attrs("f_back", "f_code", "f_builtins", "f_globals", "f_trace", "f_locals") + # Some badly-behaved code replaces the f_locals dict with + # something that doesn't support the full dict interface. So we + # only continue with the annotation if f_locals is a Python dict. + if type(f_locals) is dict: + for name, local in obj.f_locals.items(): + add_reference(f"local {name}", local) + + def add_getset_descriptor_references() -> None: + add_attrs("__objclass__", "__name__", "__doc__") + + type_based_references = { + tuple: add_sequence_references, + list: add_sequence_references, + dict: add_dict_references, + set: add_set_references, + frozenset: add_set_references, + types.FunctionType: add_function_references, + types.FrameType: add_frame_references, + CellType: add_cell_references, + types.MethodType: add_bound_method_references, + weakref.ref: add_weakref_references, + types.GetSetDescriptorType: add_getset_descriptor_references, + } + + for type_ in type(obj).__mro__: + if type_ in type_based_references: + type_based_references[type_]() + + add_attrs("__dict__", "__class__") + if isinstance(obj, type): + add_attrs("__mro__") + + return references + +############################################################################### +# Object annotations. + + +BASE_TYPES = (int, float, complex, type(None), str, bytes) +FRAME_FILENAME_LIMIT = 32 + +def object_annotation(obj): + """ + Return a string to be used for Graphviz nodes. + + The string should be short but as informative as possible. + """ + + def format_sequence(obj): + body = ','.join(repr(x) if isinstance(x, BASE_TYPES) else type(x).__name__ for x in obj[:8]) + if len(obj) > 8: + body = f'{body}, ...{len(obj) - 8}' + return body + + # For basic types, use the repr. + if isinstance(obj, BASE_TYPES): + return repr(obj) + if type(obj).__name__ == 'function': + return f"function\n{obj.__name__}" + elif isinstance(obj, types.MethodType): + try: + func_name = obj.__func__.__qualname__ + except AttributeError: + func_name = "" + return f"instancemethod\n{func_name}" + elif isinstance(obj, list): + return f"[{format_sequence(obj)}]" + elif isinstance(obj, tuple): + return f"({format_sequence(obj)})" + elif isinstance(obj, dict): + return f"dict[{len(obj)}]" + elif isinstance(obj, types.ModuleType): + return f"module\n{obj.__name__}" + elif isinstance(obj, type): + return f"type\n{obj.__name__}" + elif isinstance(obj, weakref.ref): + referent = obj() + if referent is None: + return "weakref (dead referent)" + else: + return f"weakref to id 0x{id(referent):x}" + elif isinstance(obj, types.FrameType): + filename = obj.f_code.co_filename + if len(filename) > FRAME_FILENAME_LIMIT: + filename = "..." + filename[-(FRAME_FILENAME_LIMIT - 3):] + return f"frame\n{filename}:{obj.f_lineno}" + elif is_cuda_tensor(obj): + return f"object\n{type(obj).__module__}.{type(obj).__name__} ({obj.shape})" + else: + return f"object\n{type(obj).__module__}.{type(obj).__name__}" + + + +class Node(NamedTuple): + label: str + context: str | None + root: bool + referrents: list[tuple[str, int]] + +def create_graph(objects, *, context=None, filter=None): + if context is None: + context = cuda_allocation_context() + if filter is None: + filter = is_cuda_tensor + + objects = [obj for obj in objects if not isinstance(obj, weakref.ProxyTypes)] + nodes = [Node(object_annotation(obj), context(obj), filter(obj), []) for obj in objects] + node_referrers: list[list[int]] = [[] for obj in objects] + + id_to_node = {id(obj): i for i, obj in enumerate(objects)} + for obj in objects: + fidx = id_to_node[id(obj)] + f = nodes[fidx] + references = annotated_references(obj) + for referrent in gc.get_referents(obj): + rid = id(referrent) + tidx = id_to_node.get(rid) + if tidx is None: + continue + labels = references.get(rid, ["?"]) + node_referrers[tidx].append(fidx) + for label in labels: + f.referrents.append((label, tidx)) + + to_search = [i for i, n in enumerate(nodes) if n.root] + to_keep = set() + while to_search: + idx = to_search.pop() + if idx in to_keep: + continue + to_keep.add(idx) + referrers = node_referrers[idx] + to_search.extend(referrers) + id_to_filtered_id: dict[int, int] = {} + filtered: list[Any] = [] + for i, n in enumerate(nodes): + if i in to_keep: + id_to_filtered_id[i] = len(id_to_filtered_id) + filtered.append(n) + for n in filtered: + n.referrents[:] = [(label, id_to_filtered_id[idx]) + for (label, idx) in n.referrents + if idx in id_to_filtered_id] + return filtered + +def escape(n): + return json.dumps(n) + + +def is_cuda_tensor(obj): + return ( + isinstance(obj, torch.Tensor) and + obj.device.type == "cuda" and + not torch._subclasses.fake_tensor.is_fake_tensor(obj) + ) + +def cuda_allocation_context(): + snapshot = torch.cuda.memory._snapshot() + addr_to_frame = {} + for seg in snapshot['segments']: + addr = seg['address'] + for blk in seg['blocks']: + if blk['state'] == 'active_allocated': + frames, _real_size = _block_extra(blk) + addr_to_frame[addr] = frames + addr += blk['size'] + + def object_context(obj): + if is_cuda_tensor(obj): + addr = obj.untyped_storage().data_ptr() + frames = addr_to_frame.get(addr) + if frames is not None: + return '\n'.join(_frames_fmt(frames, full_filename=True)) + return None + return object_context + +def to_dot(nodes): + lines = ["digraph GraphName {", "node [shape=rect];", 'rankdir=LR;'] + for i, n in enumerate(nodes): + lines.append(f'{i} [label={escape(n.label)}, color={"red" if n.root else "black"}];') + + for i, f in enumerate(nodes): + for label, j in f.referrents: + lines.append(f'{i} -> {j} [label = {escape(label)}]') + lines.append("}\n") + return '\n'.join(lines) + +_template = """ + + + + + + +
+
+
+
+
Mouse over tensor objects to see where they were allocated.
+
+
+ + + + +""" +_listener_template = """ +document.getElementById('node{id}').addEventListener('mouseover', function(event) {{ + document.getElementById("stacktrace").textContent = {stack} +}}) +""" +def to_html(nodes): + listeners = [] + for i, n in enumerate(nodes): + if n.context is None: + continue + s = _listener_template.format(id=str(i + 1), stack=escape(f'{n.label}:\n{n.context}')) + listeners.append(s) + dot = to_dot(nodes) + return _template.replace('$DOT', repr(dot)).replace('$LISTENERS', '\n'.join(listeners)) + +def observe_tensor_cycles(callback): + torch.cuda.memory._record_memory_history(max_entries=100000) + + def observer(garbage) -> None: + if garbage: + if not any(is_cuda_tensor(obj) for obj in garbage): + logger.info("No CUDA Tensors found in garbage") + return + callback(to_html(create_graph(garbage))) + return observe_garbage(observer) + + +def warn_tensor_cycles(): + """ + Install a warning that reports whenever a cycle that is holding CUDA memory is observed. + + The warning produces an .html file that visualizes the cycle, + and links it to the stack frame that allocated the CUDA tensor. + + Reference cycles are freed by the cycle collector rather than being cleaned up + when the objects in the cycle first become unreachable. If a cycle points to a tensor, + the CUDA memory for that tensor will not be freed until garbage collection runs. + Accumulation of CUDA allocations can lead to out of memory errors (OOMs), as well as + non-deterministic allocation behavior which is harder to debug. + """ + logger.info("Watching Python reference cycles for CUDA Tensors.") + + def write_and_log(html) -> None: + with NamedTemporaryFile('w', suffix='.html') as f: + f.write(html) + logger.warning('Reference cycle includes a CUDA Tensor see visualization of cycle %s', f.name) + return observe_tensor_cycles(write_and_log) diff --git a/.venv/lib/python3.12/site-packages/torch/utils/weak.py b/.venv/lib/python3.12/site-packages/torch/utils/weak.py new file mode 100644 index 0000000000000000000000000000000000000000..fa22b2b3765e9f68dd37b3af32e764ce3c074e9d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/utils/weak.py @@ -0,0 +1,367 @@ +# mypy: allow-untyped-defs +from __future__ import annotations + +import collections.abc as _collections_abc +import weakref +from collections.abc import Mapping, MutableMapping +from weakref import ref + +from torch import Tensor + + +WeakRef = ref + + +__all__ = [ + "TensorWeakRef", + "WeakIdRef", + "WeakIdKeyDictionary", + "WeakTensorKeyDictionary", +] + + +# TODO: make weakref properly thread safe following +# https://github.com/python/cpython/pull/125325 +class _IterationGuard: + # This context manager registers itself in the current iterators of the + # weak container, such as to delay all removals until the context manager + # exits. + # This technique should be relatively thread-safe (since sets are). + + def __init__(self, weakcontainer) -> None: + # Don't create cycles + self.weakcontainer = ref(weakcontainer) + + def __enter__(self): + w = self.weakcontainer() + if w is not None: + w._iterating.add(self) + return self + + def __exit__(self, e, t, b): + w = self.weakcontainer() + if w is not None: + s = w._iterating + s.remove(self) + if not s: + w._commit_removals() + + +# This file defines a variant of WeakKeyDictionary that overrides the hashing +# behavior of the key to use object identity, rather than the builtin +# __eq__/__hash__ functions. This is useful for Tensor weak keys, as their +# __eq__ implementation return a Tensor (elementwise equality), which means +# you can't use them directly with the WeakKeyDictionary in standard library. +# +# Our implementation strategy is to create a wrapper weak key object, which we +# use as a key in a stock Python dictionary. This is similar to how weakref +# implements WeakKeyDictionary, but instead of using weakref.ref as the +# wrapper, we use a custom wrapper that has different __eq__ and __hash__ +# behavior. Note that we subsequently store this weak key directly in an +# ORDINARY dictionary, since the newly constructed WeakIdKey's only use would +# be a dictionary so it would have no strong references. Ensuring that +# only live WeakIdKeys are in the map is handled by putting finalizers on the +# original key object. + + +# It is simpler to implement this with composition, but if we want to +# directly reuse the callback mechanism on weakref, we need the weakref +# and the key to be exactly the same object. Reusing the callback mechanism +# minimizes the divergence between our implementation and Lib/weakref.py +# +# NB: Prefer using this when working with weakrefs of Tensors; e.g., do +# WeakIdRef(tensor) rather than weakref.ref(tensor); it handles a number of +# easy to get wrong cases transparently for you. +class WeakIdRef(weakref.ref): + __slots__ = ["_id"] + + def __init__(self, key, callback=None) -> None: + # Unlike stock weakref, which preserves hash semantics of the + # original object but lazily defers hash calls until the first + # time the user attempts to hash the weakref, we can eagerly + # cache the id of the key as we know this is definitely the hash + # method + self._id = id(key) + super().__init__(key, callback) # type: ignore[call-arg] + + def __call__(self): + r = super().__call__() + # Special logic for Tensor PyObject resurrection + if hasattr(r, "_fix_weakref"): + r._fix_weakref() # type: ignore[union-attr] + return r + + def __hash__(self): + return self._id + + def __eq__(self, other): + # An attractive but wrong alternate implementation is to only test if + # the stored _ids match. This can lead to an ABA problem if you have: + # + # a1 = A() + # w1 = WeakIdRef(a1) + # del a1 + # a2 = A() # suppose it gets the same ID as a1 + # w2 = WeakIdRef(a2) + # print(w1 == w2) + # + # This should be False, as a1 and a2 are unrelated (and a1 is + # dead anyway) + a = self() + b = other() + if a is not None and b is not None: + return a is b + return self is other + + +# This is the same as WeakIdRef but equality is checked using hash() rather than id. +# This will be equivalent to the one above except for classes where hash is not their id. +class _WeakHashRef(weakref.ref): + __slots__ = ["_id"] + + def __init__(self, key, callback=None) -> None: + # Unlike stock weakref, which preserves hash semantics of the + # original object but lazily defers hash calls until the first + # time the user attempts to hash the weakref, we can eagerly + # cache the id of the key as we know this is definitely the hash + # method + self._id = hash(key) + super().__init__(key, callback) # type: ignore[call-arg] + + def __call__(self): + r = super().__call__() + # Special logic for Tensor PyObject resurrection + if hasattr(r, "_fix_weakref"): + r._fix_weakref() # type: ignore[union-attr] + return r + + def __hash__(self): + return self._id + + def __eq__(self, other): + # Use hash equality to determine ref equality. + # ScriptObject implements __hash__ to return the wrapped IValue's id, so + # this is equivalent to doing an identity comparison. + a = self() + b = other() + if a is not None and b is not None: + return hash(a) == hash(b) + return self is other + + +# This is directly adapted from cpython/Lib/weakref.py +class WeakIdKeyDictionary(MutableMapping): + def __init__(self, dict=None, ref_type=WeakIdRef) -> None: # CHANGED + self.data = {} + + self.ref_type = ref_type # CHANGED + + def remove(k, selfref=ref(self)) -> None: + self = selfref() + if self is not None: + if self._iterating: + self._pending_removals.append(k) + else: + try: + del self.data[k] + except KeyError: + pass + + self._remove = remove + # A list of dead weakrefs (keys to be removed) + self._pending_removals = [] + self._iterating = set() + self._dirty_len = False + if dict is not None: + self.update(dict) + + def _commit_removals(self) -> None: + # NOTE: We don't need to call this method before mutating the dict, + # because a dead weakref never compares equal to a live weakref, + # even if they happened to refer to equal objects. + # However, it means keys may already have been removed. + pop = self._pending_removals.pop + d = self.data + while True: + try: + key = pop() + except IndexError: + return + + try: + del d[key] + except KeyError: + pass + + def _scrub_removals(self) -> None: + d = self.data + self._pending_removals = [k for k in self._pending_removals if k in d] + self._dirty_len = False + + def __delitem__(self, key) -> None: + self._dirty_len = True + del self.data[self.ref_type(key)] # CHANGED + + def __getitem__(self, key): + return self.data[self.ref_type(key)] # CHANGED + + def __len__(self) -> int: + if self._dirty_len and self._pending_removals: + # self._pending_removals may still contain keys which were + # explicitly removed, we have to scrub them (see issue #21173). + self._scrub_removals() + return len(self.data) - len(self._pending_removals) + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} at {id(self):#x}>" + + def __setitem__(self, key, value) -> None: + self.data[self.ref_type(key, self._remove)] = value # CHANGED + + def copy(self): + new = WeakIdKeyDictionary() + with _IterationGuard(self): + for key, value in self.data.items(): + o = key() + if o is not None: + new[o] = value + return new + + __copy__ = copy + + def __deepcopy__(self, memo): + from copy import deepcopy + + new = self.__class__() + with _IterationGuard(self): + for key, value in self.data.items(): + o = key() + if o is not None: + new[o] = deepcopy(value, memo) + return new + + def get(self, key, default=None): + return self.data.get(self.ref_type(key), default) # CHANGED + + def __contains__(self, key) -> bool: + try: + wr = self.ref_type(key) # CHANGED + except TypeError: + return False + return wr in self.data + + def items(self): + with _IterationGuard(self): + for wr, value in self.data.items(): + key = wr() + if key is not None: + yield key, value + + def keys(self): + with _IterationGuard(self): + for wr in self.data: + obj = wr() + if obj is not None: + yield obj + + __iter__ = keys + + def values(self): + with _IterationGuard(self): + for wr, value in self.data.items(): + if wr() is not None: + yield value + + def keyrefs(self): + """Return a list of weak references to the keys. + + The references are not guaranteed to be 'live' at the time + they are used, so the result of calling the references needs + to be checked before being used. This can be used to avoid + creating references that will cause the garbage collector to + keep the keys around longer than needed. + + """ + return list(self.data) + + def popitem(self): + self._dirty_len = True + while True: + key, value = self.data.popitem() + o = key() + if o is not None: + return o, value + + # pyrefly: ignore [bad-override] + def pop(self, key, *args): + self._dirty_len = True + + return self.data.pop(self.ref_type(key), *args) # CHANGED + + def setdefault(self, key, default=None): + return self.data.setdefault( + self.ref_type(key, self._remove), default + ) # CHANGED + + def update(self, dict=None, **kwargs) -> None: # type: ignore[override] + d = self.data + if dict is not None: + if not hasattr(dict, "items"): + dict = type({})(dict) + for key, value in dict.items(): + d[self.ref_type(key, self._remove)] = value # CHANGED + if kwargs: + self.update(kwargs) + + def __ior__(self, other): + self.update(other) + return self + + def __or__(self, other): + if isinstance(other, _collections_abc.Mapping): + c = self.copy() + c.update(other) + return c + return NotImplemented + + def __ror__(self, other): + if isinstance(other, _collections_abc.Mapping): + c = self.__class__() + c.update(other) + c.update(self) + return c + return NotImplemented + + # Default Mapping equality will tests keys for equality, but + # we want to test ids for equality + def __eq__(self, other): + if not isinstance(other, Mapping): + return NotImplemented + return {id(k): v for k, v in self.items()} == { + id(k): v for k, v in other.items() + } + + +# Convenience alias +WeakTensorKeyDictionary = WeakIdKeyDictionary + + +class TensorWeakRef: + """Wrapper around a weak ref of a Tensor that handles the _fix_weakref() call required when unwrapping a Tensor weakref.""" + + ref: WeakRef[Tensor] + + def __init__(self, tensor: Tensor) -> None: + if not isinstance(tensor, Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(tensor)}.") + self.ref = weakref.ref(tensor) + + def __call__(self): + out = self.ref() + if out is None: + return out + if not isinstance(out, Tensor): + raise AssertionError(f"expected torch.Tensor, got {type(out)}.") + # TODO, add _fix_weakref type binding + out._fix_weakref() # type: ignore[attr-defined] + return out diff --git a/.venv/lib/python3.12/site-packages/torch/version.py b/.venv/lib/python3.12/site-packages/torch/version.py new file mode 100644 index 0000000000000000000000000000000000000000..a30468910d2c9fa7671ec39ab963b72d1ed28357 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/version.py @@ -0,0 +1,10 @@ +from typing import Optional + +__all__ = ['__version__', 'debug', 'cuda', 'git_version', 'hip', 'rocm', 'xpu'] +__version__ = '2.14.0+cpu' +debug = False +cuda: Optional[str] = None +git_version = '08187d9e0fba026dc8217405802ab5381dc88d90' +hip: Optional[str] = None +rocm: Optional[str] = None +xpu: Optional[str] = None diff --git a/.venv/lib/python3.12/site-packages/torch/xpu/__init__.py b/.venv/lib/python3.12/site-packages/torch/xpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3f7ea3730c9e0baf784cb2bdd145428776426f3d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/xpu/__init__.py @@ -0,0 +1,1497 @@ +# mypy: allow-untyped-defs +r""" +This package introduces support for the XPU backend, specifically tailored for +Intel GPU optimization. + +This package is lazily initialized, so you can always import it, and use +:func:`is_available()` to determine if your system supports XPU. +""" + +from __future__ import annotations + +import dataclasses +import os +import threading +import traceback +import warnings +from ctypes import byref, c_double, c_uint32, c_void_p, cast, pointer +from functools import lru_cache +from typing import Any, NewType, TYPE_CHECKING + +import torch +import torch._C +from torch._utils import _dummy_type, _LazySeedTracker + + +if TYPE_CHECKING: + from collections.abc import Callable + + from torch.types import Device + +from ._utils import _get_device_index +from .graphs import ( + graph, + graph_pool_handle, + is_current_stream_capturing, + make_graphed_callables, + XPUGraph, +) +from .streams import Event, Stream + + +_initialized = False +_tls = threading.local() +_initialization_lock = threading.Lock() +_queued_calls: list[ + tuple[Callable[[], None], list[str]] +] = [] # don't invoke these until initialization occurs +_is_in_bad_fork = getattr(torch._C, "_xpu_isInBadFork", lambda: False) +_lazy_seed_tracker = _LazySeedTracker() +default_generators: tuple[torch._C.Generator] = () # type: ignore[assignment] +_cached_device_count: int | None = None + + +@dataclasses.dataclass +class _ZesDeviceInfo: + device_handle: c_void_p + subdevice_id: int | None = None + is_integrated: bool = False + temperature_handle: c_void_p | None = None + frequency_handle: c_void_p | None = None + power_handle: c_void_p | None = None + engine_handle: c_void_p | None = None + memory_handle: c_void_p | None = None + + +_cached_zes_device_infos: list[_ZesDeviceInfo] = [] +# Interval between two HW counter reads; must be >=100ms for fresh data. +_zes_sample_interval_ms = 150 + + +def _is_compiled() -> bool: + r"""Return true if compile with XPU support.""" + return torch._C._has_xpu + + +if _is_compiled(): + _XpuDeviceProperties = torch._C._XpuDeviceProperties + _exchange_device = torch._C._xpu_exchangeDevice + _maybe_exchange_device = torch._C._xpu_maybeExchangeDevice +else: + # Define dummy if PyTorch was compiled without XPU + _XpuDeviceProperties = _dummy_type("_XpuDeviceProperties") # type: ignore[assignment, misc] + + def _exchange_device(device: int) -> int: + raise NotImplementedError("PyTorch was compiled without XPU support") + + def _maybe_exchange_device(device: int) -> int: + raise NotImplementedError("PyTorch was compiled without XPU support") + + +def _parse_visible_devices(strict=False) -> list[int]: + r"""Parse ``ZE_AFFINITY_MASK`` and return visible device ordinals. + + Returns a list of non-negative device ordinals specified by the mask. + When the mask is unset, returns ``[0, 1, ..., 127]`` (the maximum range + for ``int8_t`` device indices). Returns an empty list for unsupported + COMPOSITE-style masks (e.g. ``"0.0,0.1"``). + + Args: + strict (bool): If ``True``, raises ``ValueError`` on unsupported mask + formats (e.g. COMPOSITE-style ``"0.0,0.1"``). If ``False`` + (default), returns an empty list instead. + """ + var = os.getenv("ZE_AFFINITY_MASK") + if var is None: + # DeviceIndex is stored as int8_t, so valid indices are 0–127 + # (up to 128 devices). Return the full range when no mask is set. + return list(range(128)) + + visible_devices: list[int] = [] + for elem in var.split(","): + try: + x = int(elem.strip()) + except ValueError: + # A non-integer token (e.g. "0.0" in COMPOSITE-mode format) + # means the mask is unsupported here; signal that by returning + # an empty list. + if strict: + raise ValueError( + f"Unsupported ZE_AFFINITY_MASK format: '{var}'. Expected a comma-separated list of integers, e.g. '0,1,2'." + ) from None + return [] + if x >= 0 and x not in visible_devices: + visible_devices.append(x) + return visible_devices + + +def _enum_zes_device_infos(visible_mask: list[int]) -> int: + r"""Enumerate visible XPU devices via Level Zero Sysman and cache their info. + + Enumerates devices from the first Level Zero Sysman driver and counts those + whose logical index appears in *visible_mask*. Only devices listed in + the visible mask participate in counting. + The populated ``_cached_zes_device_infos`` list is indexed by PyTorch + device ordinal. + + Discrete GPUs (dGPUs) take priority: if any visible dGPU is found, only + dGPUs are counted; integrated GPUs (iGPUs) are counted only when no + visible dGPU exists. + + For tiled dGPUs (``numSubdevices > 0``), the counting depends on + ``ZE_FLAT_DEVICE_HIERARCHY``: + + - **FLAT / COMBINED** (default): each sub-device is exposed as a + separate top-level device and counted individually. + - **COMPOSITE**: sub-devices are hidden; the whole physical device + counts as one. + + Returns the visible device count, or a negative value on failure. + """ + try: + import pyzes # type: ignore[import] + except Exception: + return -1 + + global _cached_zes_device_infos + + def _zes_check_warn(rc: int, msg: str) -> bool: + """Return True if the call failed (rc != ZE_RESULT_SUCCESS) after issuing a warning.""" + if rc != pyzes.ZE_RESULT_SUCCESS: + warnings.warn(msg, stacklevel=3) + return rc != pyzes.ZE_RESULT_SUCCESS + + if _zes_check_warn(pyzes.zesInit(0), "Can't initialize Level Zero Sysman"): + return -1 + + driver_count = c_uint32(0) + if _zes_check_warn( + pyzes.zesDriverGet(byref(driver_count), None), + "Can't get Level Zero Sysman driver count", + ): + return -1 + if driver_count.value == 0: + return 0 + + drivers = (pyzes.zes_driver_handle_t * driver_count.value)() + if _zes_check_warn( + pyzes.zesDriverGet(byref(driver_count), drivers), + "Can't get Level Zero Sysman driver handles", + ): + return -1 + + device_count = c_uint32(0) + if _zes_check_warn( + pyzes.zesDeviceGet(drivers[0], byref(device_count), None), + "Can't get Level Zero Sysman device count", + ): + return -1 + + devices = (pyzes.zes_device_handle_t * device_count.value)() + if _zes_check_warn( + pyzes.zesDeviceGet(drivers[0], byref(device_count), devices), + "Can't get Level Zero Sysman device handles", + ): + return -1 + + # --- Count visible dGPUs and iGPUs --- + ZES_DEVICE_PROPERTY_FLAG_INTEGRATED = 1 << 0 + expose_subdevices = os.getenv("ZE_FLAT_DEVICE_HIERARCHY") != "COMPOSITE" + + _cached_zes_device_infos.clear() + visible = set(visible_mask) + logical_index = 0 + num_igpu = 0 + num_dgpu = 0 + + for device in devices: + props = pyzes.zes_device_properties_t() + props.stype = pyzes.ZES_STRUCTURE_TYPE_DEVICE_PROPERTIES + ext_props = pyzes.zes_device_ext_properties_t() + ext_props.stype = pyzes.ZES_STRUCTURE_TYPE_DEVICE_EXT_PROPERTIES + props.pNext = cast(pointer(ext_props), c_void_p) + if _zes_check_warn( + pyzes.zesDeviceGetProperties(device, byref(props)), + "Can't get Level Zero Sysman device properties", + ): + return -1 + + is_integrated = bool(ext_props.flags & ZES_DEVICE_PROPERTY_FLAG_INTEGRATED) + + # Tiled dGPUs in FLAT/COMBINED mode expose each sub-device as a + # separate logical device; everything else counts as one slot. + tiled = not is_integrated and props.numSubdevices > 0 and expose_subdevices + num_slots = props.numSubdevices if tiled else 1 + + for slot in range(num_slots): + if logical_index in visible: + _cached_zes_device_infos.append( + _ZesDeviceInfo( + device_handle=device, + subdevice_id=slot if tiled else None, + is_integrated=is_integrated, + ) + ) + if is_integrated: + num_igpu += 1 + else: + num_dgpu += 1 + logical_index += 1 + + # dGPUs take priority; strip iGPUs when at least one dGPU is visible. + if num_dgpu and num_igpu: + _cached_zes_device_infos = [ + info for info in _cached_zes_device_infos if not info.is_integrated + ] + return num_dgpu or num_igpu + + +def _raw_device_count_zes(visible_mask: list[int]) -> int: + r"""Return the visible XPU device count via Level Zero Sysman, or negative on failure.""" + return _enum_zes_device_infos(visible_mask) + + +def _device_count_zes() -> int: + r"""Return the number of visible XPU devices, or -1 on failure.""" + visible_devices = _parse_visible_devices() + if not visible_devices: + return -1 + return _raw_device_count_zes(visible_devices) + + +def device_count() -> int: + r""" + Return the number of XPU device available. + + .. note:: This API will NOT poison fork if Level Zero Sysman discovery succeeds. + See :ref:`multiprocessing-poison-fork-note` for more details. + """ + if not _is_compiled(): + return 0 + global _cached_device_count + if _cached_device_count is not None: + return _cached_device_count + if _initialized or hasattr(_tls, "is_initializing"): + count = torch._C._xpu_getDeviceCount() + else: + zes_count = _device_count_zes() + count = torch._C._xpu_getDeviceCount() if zes_count < 0 else zes_count + # Do not cache the device count prior to XPU initialization, because + # the number of devices can change due to changes to ZE_AFFINITY_MASK + # setting prior to XPU initialization. + if _initialized: + _cached_device_count = count + return count + + +def is_available() -> bool: + r"""Return a bool indicating if XPU is currently available.""" + # This function never throws. + return device_count() > 0 + + +def is_bf16_supported(including_emulation: bool = True) -> bool: + r"""Return a bool indicating if the current XPU device supports dtype bfloat16.""" + if not is_available(): + return False + return ( + including_emulation + or torch.xpu.get_device_properties().has_bfloat16_conversions + ) + + +def is_tf32_supported() -> bool: + r"""Return a bool indicating if the current XPU device supports dtype tf32.""" + if not is_available(): + return False + # On Intel Xe architecture and newer, TF32 operations can be accelerated + # through DPAS (Dot Product Accumulate Systolic) instructions. Therefore, + # TF32 support can be determined by checking whether the device supports + # subgroup matrix multiply-accumulate operations. + return torch.xpu.get_device_properties().has_subgroup_matrix_multiply_accumulate + + +def is_initialized(): + r"""Return whether PyTorch's XPU state has been initialized.""" + return _initialized and not _is_in_bad_fork() + + +def _lazy_call(callable, **kwargs) -> None: + with _initialization_lock: + if is_initialized(): + callable() + else: + global _lazy_seed_tracker + if kwargs.get("seed_all", False): + _lazy_seed_tracker.queue_seed_all(callable, traceback.format_stack()) + elif kwargs.get("seed", False): + _lazy_seed_tracker.queue_seed(callable, traceback.format_stack()) + else: + # Don't store the actual traceback to avoid memory cycle + _queued_calls.append((callable, traceback.format_stack())) + + +def init() -> None: + r"""Initialize PyTorch's XPU state. + This is a Python API about lazy initialization that avoids initializing + XPU until the first time it is accessed. Does nothing if the XPU state is + already initialized. + """ + _lazy_init() + + +def _lazy_init() -> None: + global _initialized, _queued_calls + if is_initialized() or hasattr(_tls, "is_initializing"): + return + with _initialization_lock: + # This test was protected via GIL. Double-check whether XPU has + # already been initialized. + if is_initialized(): + return + # Stop promptly upon encountering a bad fork error. + if _is_in_bad_fork(): + raise RuntimeError( + "Cannot re-initialize XPU in forked subprocess. To use XPU with " + "multiprocessing, you must use the 'spawn' start method" + ) + if not _is_compiled(): + raise AssertionError("Torch not compiled with XPU enabled") + # This function inits XPU backend and detects bad fork processing. + torch._C._xpu_init() + # Some of the queued calls may reentrantly call _lazy_init(); We need to + # just return without initializing in that case. + _tls.is_initializing = True + + _queued_calls.extend(calls for calls in _lazy_seed_tracker.get_calls() if calls) + + try: + for queued_call, orig_traceback in _queued_calls: + try: + queued_call() + except Exception as e: + msg = ( + f"XPU call failed lazily at initialization with error: {str(e)}\n\n" + f"XPU call was originally invoked at:\n\n{''.join(orig_traceback)}" + ) + raise Exception(msg) from e # noqa: TRY002 + finally: + delattr(_tls, "is_initializing") + _initialized = True + + +class _DeviceGuard: + def __init__(self, index: int) -> None: + self.idx = index + self.prev_idx = -1 + + def __enter__(self): + self.prev_idx = torch.xpu._exchange_device(self.idx) + + def __exit__(self, type: Any, value: Any, traceback: Any): + self.idx = torch.xpu._maybe_exchange_device(self.prev_idx) + return False + + +class device: + r"""Context-manager that changes the selected device. + + Args: + device (torch.device or int or str): device index to select. It's a no-op if + this argument is a negative integer or ``None``. + """ + + def __init__(self, device: Any) -> None: + self.idx = _get_device_index(device, optional=True) + self.prev_idx = -1 + + def __enter__(self): + self.prev_idx = torch.xpu._exchange_device(self.idx) + + def __exit__(self, type: Any, value: Any, traceback: Any): + self.idx = torch.xpu._maybe_exchange_device(self.prev_idx) + return False + + +class device_of(device): + r"""Context-manager that changes the current device to that of given object. + + You can use both tensors and storages as arguments. If a given object is + not allocated on a XPU, this is a no-op. + + Args: + obj (Tensor or Storage): object allocated on the selected device. + """ + + def __init__(self, obj) -> None: + idx = obj.get_device() if obj.is_xpu else -1 + super().__init__(idx) + + +def set_device(device: Device) -> None: + r"""Set the current device. + + Args: + device (torch.device or int or str): selected device. This function is a + no-op if this argument is negative. + """ + _lazy_init() + device = _get_device_index(device) + if device >= 0: + torch._C._xpu_setDevice(device) + + +def get_device_name(device: Device = None) -> str: + r"""Get the name of a device. + + Args: + device (torch.device or int or str, optional): device for which to + return the name. This function is a no-op if this argument is a + negative integer. It uses the current device, given by :func:`~torch.xpu.current_device`, + if :attr:`device` is ``None`` (default). + + Returns: + str: the name of the device + """ + return get_device_properties(device).name + + +@lru_cache(None) +def get_device_capability(device: Device = None) -> dict[str, Any]: + r"""Get the xpu capability of a device. + + Args: + device (torch.device or int or str, optional): device for which to + return the device capability. This function is a no-op if this + argument is a negative integer. It uses the current device, given by + :func:`~torch.xpu.current_device`, if :attr:`device` is ``None`` + (default). + + Returns: + dict[str, Any]: the xpu capability dictionary of the device + """ + props = get_device_properties(device) + # Only keep attributes that are safe for dictionary serialization. + serializable_types = (int, float, bool, str, type(None), list, tuple, dict) + return { + key: value + for key in dir(props) + if not key.startswith("__") + and isinstance((value := getattr(props, key)), serializable_types) + } + + +def get_device_properties( + device: Device = None, +) -> _XpuDeviceProperties: + r"""Get the properties of a device. Returns _XpuDeviceProperties containing the following device properties: + + - ``name`` (str): device name. + - ``platform_name`` (str): SYCL platform name. + - ``vendor`` (str): device vendor. + - ``device_id`` (int): device identifier (product ID). + - ``driver_version`` (str): driver version. + - ``version`` (str): runtime version. + - ``max_compute_units`` (int): number of parallel compute units. + - ``gpu_eu_count`` (int): number of EUs (Execution Unit). + - ``max_work_group_size``: (int): maximum number of work-items permitted in a work-group. + - ``max_num_sub_groups`` (int): maximum number of sub-groups supported in a work-group. + - ``memory_clock_rate`` (int) maximum clock rate of device's global memory in MHz. + - ``memory_bus_width`` (int) maximum bus width between device and memory in bits. + - ``sub_group_sizes``: (list[int]): a list of supported sub-group sizes. + - ``local_mem_size`` (int): device local memory capacity that can be allocated per work-group in bytes. + - ``last_level_cache_size`` (int): size in bytes of the device's last-level memory cache, shared across all Xe Cores (analogous to CUDA ``L2_cache_size``). + - ``has_fp16`` (bool): whether float16 dtype is supported. + - ``has_fp64`` (bool): whether float64 dtype is supported. + - ``has_atomic64`` (bool): whether 64-bit atomic operations are supported. + - ``has_bfloat16_conversions`` (bool): whether bfloat16 conversions are supported. + - ``has_subgroup_matrix_multiply_accumulate`` (bool): whether DPAS (Dot Product Accumulate Systolic) is supported. + - ``has_subgroup_matrix_multiply_accumulate_tensor_float32`` (bool): whether DPAS with tf32 inputs is supported. + - ``has_subgroup_2d_block_io`` (bool): whether 2D block I/O for efficient matrix multiplication is supported. + - ``is_integrated_gpu`` (bool): whether the device is an integrated GPU (iGPU). + - ``total_memory`` (int): device global memory in bytes. + - ``gpu_subslice_count`` (int): number of subslice. + - ``architecture`` (int): device architecture identifier (experimental). + - ``type`` (str): device type, e.g. 'cpu', 'gpu', accelerator', 'host', 'unknown'. + - ``uuid`` (Any): device UUID (Universal Unique ID), 16 bytes. + + Args: + device (torch.device or int or str): device for which to return the + properties of the device. + + Returns: + _XpuDeviceProperties: the properties of the device + """ + _lazy_init() + device = _get_device_index(device, optional=True) + return _get_device_properties(device) # type: ignore[name-defined] # noqa: F821 + + +def current_device() -> int: + r"""Return the index of a currently selected device.""" + _lazy_init() + return torch._C._xpu_getDevice() + + +def _get_device(device: int | str | torch.device) -> torch.device: + r"""Return the torch.device type object from the passed in device. + + Args: + device (torch.device or int or str): selected device. + """ + if isinstance(device, str): + device = torch.device(device) + elif isinstance(device, int): + device = torch.device("xpu", device) + return device + + +def can_device_access_peer(device: Device, peer: Device) -> bool: + r"""Query whether a device can access a peer device's memory. + + Args: + device (torch.device or int or str): selected device. + peer (torch.device or int or str): peer device to query access to. + + Returns: + bool: ``True`` if ``device`` can access ``peer``, ``False`` otherwise. + """ + _lazy_init() + device = _get_device_index(device, optional=True) + peer = _get_device_index(peer, optional=True) + return torch._C._xpu_canDeviceAccessPeer(device, peer) + + +class StreamContext: + r"""Context-manager that selects a given stream. + + All XPU kernels queued within its context will be enqueued on a selected + stream. + + Args: + Stream (Stream): selected stream. This manager is a no-op if it's + ``None``. + .. note:: Streams are per-device. + """ + + cur_stream: torch.xpu.Stream | None + + def __init__(self, stream: torch.xpu.Stream | None) -> None: + self.stream = stream + self.idx = _get_device_index(None, True) + if self.idx is None: + self.idx = -1 # pyrefly: ignore [bad-assignment] + + def __enter__(self): + cur_stream = self.stream + if cur_stream is None or self.idx == -1: + return + self.src_prev_stream = torch.xpu.current_stream(None) + + # If the stream is not on the current device, then set the current stream on the device + if self.src_prev_stream.device != cur_stream.device: + with device(cur_stream.device): + self.dst_prev_stream = torch.xpu.current_stream(cur_stream.device) + torch.xpu.set_stream(cur_stream) + + def __exit__(self, type: Any, value: Any, traceback: Any): + cur_stream = self.stream + if cur_stream is None or self.idx == -1: + return + + # Reset the stream on the original device and destination device + if self.src_prev_stream.device != cur_stream.device: + torch.xpu.set_stream(self.dst_prev_stream) + torch.xpu.set_stream(self.src_prev_stream) + + +def stream(stream: torch.xpu.Stream | None) -> StreamContext: + r"""Wrap around the Context-manager StreamContext that selects a given stream. + + Arguments: + stream (Stream): selected stream. This manager is a no-op if it's ``None``. + """ + return StreamContext(stream) + + +def _set_stream_by_id(stream_id, device_index, device_type) -> None: + r"""set stream specified by the stream id, device index and device type + + Args: stream_id (int): not visible to the user, used to assigned to the specific stream. + device_index (int): selected device index. + device_type (int): selected device type. + """ + torch._C._xpu_setStream( + stream_id=stream_id, + device_index=device_index, + device_type=device_type, + ) + + +def set_stream(stream: Stream) -> None: + r"""Set the current stream. This is a wrapper API to set the stream. + Usage of this function is discouraged in favor of the ``stream`` + context manager. + + Args: + stream (Stream): selected stream. This function is a no-op + if this argument is ``None``. + """ + if stream is None: + return + _lazy_init() + _set_stream_by_id( + stream_id=stream.stream_id, + device_index=stream.device_index, + device_type=stream.device_type, + ) + + +def current_stream(device: Device = None) -> Stream: + r"""Return the currently selected :class:`Stream` for a given device. + + Args: + device (torch.device or int, optional): selected device. Returns + the currently selected :class:`Stream` for the current device, given + by :func:`~torch.xpu.current_device`, if :attr:`device` is ``None`` + (default). + """ + _lazy_init() + streamdata = torch._C._xpu_getCurrentStream( + _get_device_index(device, optional=True) + ) + return Stream( + stream_id=streamdata[0], device_index=streamdata[1], device_type=streamdata[2] + ) + + +def get_stream_from_external(data_ptr: int, device: Device = None) -> Stream: + r"""Return a :class:`Stream` from an external SYCL queue. + + This function is used to wrap SYCL queue created in other libraries in order + to facilitate data exchange and multi-library interactions. + + .. note:: This function doesn't manage the queue life-cycle, it is the user + responsibility to keep the referenced queue alive while this returned stream is + being used. The different SYCL queue pointers will result in distinct + :class:`Stream` objects, even if the SYCL queues they dereference are equivalent. + + Args: + data_ptr(int): Integer representation of the `sycl::queue*` value passed externally. + device(torch.device or int, optional): the device where the queue was originally created. + It is the user responsibility to ensure the device is specified correctly. + """ + _lazy_init() + streamdata = torch._C._xpu_getStreamFromExternal( + data_ptr, _get_device_index(device, optional=True) + ) + return Stream( + stream_id=streamdata[0], device_index=streamdata[1], device_type=streamdata[2] + ) + + +def synchronize(device: Device = None) -> None: + r"""Wait for all kernels in all streams on a XPU device to complete. + + Args: + device (torch.device or int, optional): device for which to synchronize. + It uses the current device, given by :func:`~torch.xpu.current_device`, + if :attr:`device` is ``None`` (default). + """ + _lazy_init() + device = _get_device_index(device, optional=True) + return torch._C._xpu_synchronize(device) + + +def _sleep(cycles: int) -> None: + r"""Spin the current XPU device for the given number of device clock cycles. + + The kernel is enqueued on the current stream and returns immediately on the + host; the device-side spin runs asynchronously. + + Args: + cycles (int): number of device clock cycles to spin. + """ + torch._C._xpu_sleep(cycles) + + +def get_arch_list() -> list[str]: + r"""Return list XPU architectures this library was compiled for.""" + if not _is_compiled(): + return [] + arch_flags = torch._C._xpu_getArchFlags() + if arch_flags is None: + return [] + return arch_flags.split() + + +def get_gencode_flags() -> str: + r"""Return XPU AOT(ahead-of-time) build flags this library was compiled with.""" + arch_list = get_arch_list() + if len(arch_list) == 0: + return "" + return f"-device {','.join(arch for arch in arch_list)}" + + +def _get_generator(device: torch.device) -> torch._C.Generator: + r"""Return the XPU Generator object for the given device. + + Args: + device (torch.device): selected device. + """ + idx = device.index + if idx is None: + idx = current_device() + return torch.xpu.default_generators[idx] + + +def _set_rng_state_offset( + offset: int, device: int | str | torch.device = "xpu" +) -> None: + r"""Set the random number generator state offset of the specified GPU. + + Args: + offset (int): The desired offset + device (torch.device or int, optional): The device to set the RNG state. + Default: ``'xpu'`` (i.e., ``torch.device('xpu')``, the current XPU device). + """ + final_device = _get_device(device) + + def cb() -> None: + default_generator = _get_generator(final_device) + default_generator.set_offset(offset) + + _lazy_call(cb) + + +def _get_rng_state_offset(device: int | str | torch.device = "xpu") -> int: + r"""Return the random number generator state offset of the specified GPU. + + Args: + device (torch.device or int, optional): The device to return the RNG state offset of. + Default: ``'xpu'`` (i.e., ``torch.device('xpu')``, the current XPU device). + + .. warning:: + This function eagerly initializes XPU. + """ + _lazy_init() + final_device = _get_device(device) + default_generator = _get_generator(final_device) + return default_generator.get_offset() + + +def _import_pyzes(): + """Return the imported pyzes module; raise ImportError if missing, RuntimeError if the GPU driver is unavailable.""" + try: + import pyzes # type: ignore[import] + except ImportError: + raise ImportError( + "pyzes is required; install it with 'pip install pyzes'." + ) from None + except Exception as err: + raise RuntimeError( + "Failed to import pyzes. Ensure the GPU driver is installed with Level Zero Sysman support." + ) from err + return pyzes + + +def _get_pyzes_version() -> tuple[int, ...]: + """ + Return the version of the pyzes package as a tuple of integers (major, minor, patch). + Always ensure that the pyzes package is installed before calling this function. + """ + from importlib.metadata import version + + return tuple(map(int, version("pyzes").split("."))) + + +def _zes_check(rc: int, msg: str) -> None: + """Raise RuntimeError if the Level Zero Sysman call failed (rc != ZE_RESULT_SUCCESS).""" + import pyzes # type: ignore[import] + + if rc != pyzes.ZE_RESULT_SUCCESS: + raise RuntimeError(f"{msg} (rc={rc})") + + +def _zes_ensure_device_infos(device: int): + """Ensure the ZES device info cache is populated and validate the device index.""" + if not _cached_zes_device_infos: + if _enum_zes_device_infos(_parse_visible_devices(strict=True)) < 0: + raise RuntimeError("Failed to enumerate devices via Level Zero Sysman.") + + total_devices = len(_cached_zes_device_infos) + if device >= total_devices: + raise RuntimeError( + f"The device {device} is out of range for Level Zero Sysman. It must be in the range [0, {total_devices})." + ) + + +def _get_zes_temperature_handle(device: Device = None) -> c_void_p: + r"""Return the Level Zero Sysman GPU temperature sensor handle for the specified device. + + The result is cached in ``_ZesDeviceInfo.temperature_handle`` so that + repeated calls skip sensor enumeration. ``_cached_zes_device_infos`` + is lazily populated on the first call. + + Args: + device (torch.device, str or int, optional): target device. Uses the + current device, given by :func:`~torch.xpu.current_device`, + if ``None`` (default). + """ + pyzes = _import_pyzes() + + device = _get_device_index(device, optional=True) + _zes_ensure_device_infos(device) + + info = _cached_zes_device_infos[device] + if info.temperature_handle is not None: + return info.temperature_handle + + device_handle = info.device_handle + subdevice_id = info.subdevice_id + + # Note [telemetry handle selection]: + # For tiled dGPUs, pick the handle whose subdeviceId matches. + # For non-tiled devices, pick the root-level (non-subdevice) handle. + temp_count = c_uint32(0) + _zes_check( + pyzes.zesDeviceEnumTemperatureSensors(device_handle, byref(temp_count), None), + "Can't get Level Zero Sysman temperature sensor count.", + ) + if temp_count.value == 0: + raise RuntimeError("No Level Zero Sysman temperature sensors found.") + temp_handles = (pyzes.zes_temp_handle_t * temp_count.value)() + _zes_check( + pyzes.zesDeviceEnumTemperatureSensors( + device_handle, byref(temp_count), temp_handles + ), + "Can't get Level Zero Sysman temperature sensor handles.", + ) + + temperature_handle = None + for temp_handle in temp_handles: + temp_props = pyzes.zes_temp_properties_t() + temp_props.stype = pyzes.ZES_STRUCTURE_TYPE_TEMP_PROPERTIES + _zes_check( + pyzes.zesTemperatureGetProperties(temp_handle, byref(temp_props)), + "Can't get Level Zero Sysman temperature properties.", + ) + if temp_props.type != pyzes.ZES_TEMP_SENSORS_GPU: + continue + if subdevice_id is not None: + if temp_props.onSubdevice and temp_props.subdeviceId == subdevice_id: + temperature_handle = temp_handle + break + else: + if not temp_props.onSubdevice: + temperature_handle = temp_handle + break + + if temperature_handle is None: + raise RuntimeError("No Level Zero Sysman GPU temperature handle found.") + info.temperature_handle = temperature_handle + return temperature_handle + + +def temperature(device: Device = None) -> float: + r"""Return the GPU temperature in degrees Celsius. + + Args: + device (torch.device, str or int, optional): selected device. Uses the + current device, given by :func:`~torch.xpu.current_device`, + if ``None`` (default). + + .. note:: This API may require elevated privileges (e.g. ``sudo``) to access GPU temperature information. + """ + temperature_handle = _get_zes_temperature_handle(device) + + import pyzes # type: ignore[import] + + temp = c_double(0.0) + rc = pyzes.zesTemperatureGetState(temperature_handle, byref(temp)) + if rc == pyzes.ZE_RESULT_ERROR_NOT_AVAILABLE: + raise RuntimeError( + "GPU temperature querying is not available. Try running with elevated privileges (e.g. sudo)." + ) + if rc != pyzes.ZE_RESULT_SUCCESS: + raise RuntimeError(f"Can't get Level Zero Sysman GPU temperature (rc={rc}).") + return temp.value + + +def _get_zes_frequency_handle(device: Device = None) -> c_void_p: + r"""Return the Level Zero Sysman GPU frequency domain handle for the specified device. + + The result is cached in ``_ZesDeviceInfo.frequency_handle`` so that + repeated calls skip domain enumeration. ``_cached_zes_device_infos`` + is lazily populated on the first call. + + Args: + device (torch.device, str or int, optional): target device. Uses the + current device, given by :func:`~torch.xpu.current_device`, + if ``None`` (default). + """ + pyzes = _import_pyzes() + + device = _get_device_index(device, optional=True) + _zes_ensure_device_infos(device) + + info = _cached_zes_device_infos[device] + if info.frequency_handle is not None: + return info.frequency_handle + + device_handle = info.device_handle + subdevice_id = info.subdevice_id + + # Enumerate all frequency domains under this device handle. + freq_count = c_uint32(0) + _zes_check( + pyzes.zesDeviceEnumFrequencyDomains(device_handle, byref(freq_count), None), + "Can't get Level Zero Sysman frequency domains count.", + ) + if freq_count.value == 0: + raise RuntimeError("No Level Zero Sysman frequency domains found.") + freq_handles = (pyzes.zes_freq_handle_t * freq_count.value)() + _zes_check( + pyzes.zesDeviceEnumFrequencyDomains( + device_handle, byref(freq_count), freq_handles + ), + "Can't get Level Zero Sysman frequency domain handles.", + ) + + if _get_pyzes_version() < (0, 1, 2): + frequency_handle = freq_handles[0] + info.frequency_handle = frequency_handle + return frequency_handle + + frequency_handle = None + for freq_handle in freq_handles: + freq_props = pyzes.zes_freq_properties_t() + freq_props.stype = pyzes.ZES_STRUCTURE_TYPE_FREQ_PROPERTIES + _zes_check( + pyzes.zesFrequencyGetProperties(freq_handle, byref(freq_props)), + "Can't get Level Zero Sysman frequency properties.", + ) + if freq_props.type != pyzes.ZES_FREQ_DOMAIN_GPU: + continue + if subdevice_id is not None: + if freq_props.onSubdevice and freq_props.subdeviceId == subdevice_id: + frequency_handle = freq_handle + break + else: + if not freq_props.onSubdevice: + frequency_handle = freq_handle + break + + if frequency_handle is None: + raise RuntimeError("No Level Zero Sysman GPU frequency handle found.") + info.frequency_handle = frequency_handle + return frequency_handle + + +def clock_rate(device: Device = None) -> float: + r"""Return the GPU clock rate in MHz. + + Args: + device (torch.device, str or int, optional): selected device. Uses the + current device, given by :func:`~torch.xpu.current_device`, + if ``None`` (default). + """ + frequency_handle = _get_zes_frequency_handle(device) + + import pyzes # type: ignore[import] + + freq_state = pyzes.zes_freq_state_t() + rc = pyzes.zesFrequencyGetState(frequency_handle, byref(freq_state)) + if rc != pyzes.ZE_RESULT_SUCCESS: + raise RuntimeError(f"Can't get Level Zero Sysman GPU clock rate (rc={rc}).") + return freq_state.actual + + +def _get_zes_power_handle(device: Device = None) -> c_void_p: + r"""Return the Level Zero Sysman GPU power domain handle for the specified device. + + The result is cached in ``_ZesDeviceInfo.power_handle`` so that + repeated calls skip domain enumeration. ``_cached_zes_device_infos`` + is lazily populated on the first call. + + Args: + device (torch.device, str or int, optional): target device. Uses the + current device, given by :func:`~torch.xpu.current_device`, + if ``None`` (default). + """ + pyzes = _import_pyzes() + + device = _get_device_index(device, optional=True) + _zes_ensure_device_infos(device) + + info = _cached_zes_device_infos[device] + if info.power_handle is not None: + return info.power_handle + + device_handle = info.device_handle + subdevice_id = info.subdevice_id + + # Enumerate all power domains under this device handle. + power_count = c_uint32(0) + _zes_check( + pyzes.zesDeviceEnumPowerDomains(device_handle, byref(power_count), None), + "Can't get Level Zero Sysman power domains count.", + ) + if power_count.value == 0: + raise RuntimeError("No Level Zero Sysman power domains found.") + power_handles = (pyzes.zes_pwr_handle_t * power_count.value)() + _zes_check( + pyzes.zesDeviceEnumPowerDomains( + device_handle, byref(power_count), power_handles + ), + "Can't get Level Zero Sysman power domain handles.", + ) + + if _get_pyzes_version() < (0, 1, 2): + power_handle = power_handles[0] + info.power_handle = power_handle + return power_handle + + power_handle = None + for pwr_handle in power_handles: + pwr_props = pyzes.zes_power_properties_t() + pwr_props.stype = pyzes.ZES_STRUCTURE_TYPE_POWER_PROPERTIES + ext_pwr_props = pyzes.zes_power_ext_properties_t() + ext_pwr_props.stype = pyzes.ZES_STRUCTURE_TYPE_POWER_EXT_PROPERTIES + pwr_props.pNext = cast(pointer(ext_pwr_props), c_void_p) + _zes_check( + pyzes.zesPowerGetProperties(pwr_handle, byref(pwr_props)), + "Can't get Level Zero Sysman power properties.", + ) + if ext_pwr_props.domain not in ( + pyzes.ZES_POWER_DOMAIN_CARD, + pyzes.ZES_POWER_DOMAIN_PACKAGE, + ): + continue + if subdevice_id is not None: + if pwr_props.onSubdevice and pwr_props.subdeviceId == subdevice_id: + power_handle = pwr_handle + if ext_pwr_props.domain == pyzes.ZES_POWER_DOMAIN_CARD: + break + else: + if not pwr_props.onSubdevice: + power_handle = pwr_handle + if ext_pwr_props.domain == pyzes.ZES_POWER_DOMAIN_CARD: + break + + if power_handle is None: + raise RuntimeError("No Level Zero Sysman GPU power handle found.") + info.power_handle = power_handle + return power_handle + + +def power_draw(device: Device = None) -> float: + r"""Return the GPU card power draw in watts. + + The value is computed by dividing the energy delta by the time delta between + two energy-counter reads separated by a 100ms sampling interval. + + Args: + device (torch.device, str or int, optional): selected device. Uses the + current device, given by :func:`~torch.xpu.current_device`, + if ``None`` (default). + + .. note:: This function blocks for approximately 100ms per call due to the + sampling interval required to compute an accurate power reading. + + .. note:: This API may require elevated privileges (e.g. ``sudo``) to access GPU power information. + + .. note:: On Intel Xe2 and newer GPUs, card-level power is reported directly. On older GPUs, + package-level power is used as a fallback and may not reflect the full card power draw. + """ + power_handle = _get_zes_power_handle(device) + + import pyzes # type: ignore[import] + + counter_start = pyzes.zes_power_energy_counter_t() + rc = pyzes.zesPowerGetEnergyCounter(power_handle, byref(counter_start)) + if rc == pyzes.ZE_RESULT_ERROR_NOT_AVAILABLE: + raise RuntimeError( + "GPU power draw querying is not available. Try running with elevated privileges (e.g. sudo)." + ) + if rc != pyzes.ZE_RESULT_SUCCESS: + raise RuntimeError(f"Can't get Level Zero Sysman GPU power draw (rc={rc}).") + + import time + + time.sleep(_zes_sample_interval_ms / 1000.0) + + counter_end = pyzes.zes_power_energy_counter_t() + _zes_check( + pyzes.zesPowerGetEnergyCounter(power_handle, byref(counter_end)), + "Can't get Level Zero Sysman GPU power energy counter.", + ) + # energy is in microjoules, timestamp is in microseconds (per L0 Sysman spec). + # microjoules / microseconds = watts, so the micro factors cancel. + dt = counter_end.timestamp - counter_start.timestamp + return (counter_end.energy - counter_start.energy) / dt + + +def _get_zes_engine_handle(device: Device = None) -> c_void_p: + r"""Return the Level Zero Sysman GPU engine group handle for the specified device. + + The result is cached in ``_ZesDeviceInfo.engine_handle`` so that + repeated calls skip group enumeration. ``_cached_zes_device_infos`` + is lazily populated on the first call. + + Args: + device (torch.device, str or int, optional): target device. Uses the + current device, given by :func:`~torch.xpu.current_device`, + if ``None`` (default). + """ + pyzes = _import_pyzes() + + device = _get_device_index(device, optional=True) + _zes_ensure_device_infos(device) + + info = _cached_zes_device_infos[device] + if info.engine_handle is not None: + return info.engine_handle + + device_handle = info.device_handle + subdevice_id = info.subdevice_id + + # See Note [telemetry handle selection] + engine_count = c_uint32(0) + _zes_check( + pyzes.zesDeviceEnumEngineGroups(device_handle, byref(engine_count), None), + "Can't get Level Zero Sysman engine group count.", + ) + # TODO: zesDeviceEnumEngineGroups does not return ZE_RESULT_ERROR_INSUFFICIENT_PERMISSIONS on privilege errors; + # instead it succeeds with count=0. Treat that as an error with a helpful hint about elevated privileges. + if engine_count.value == 0: + raise RuntimeError( + "No Level Zero Sysman engine groups found. The GPU may not support engine monitoring, or try running with elevated privileges (e.g. sudo)." + ) + engine_handles = (pyzes.zes_engine_handle_t * engine_count.value)() + _zes_check( + pyzes.zesDeviceEnumEngineGroups( + device_handle, byref(engine_count), engine_handles + ), + "Can't get Level Zero Sysman engine group handles.", + ) + + engine_handle = None + for eng_handle in engine_handles: + eng_props = pyzes.zes_engine_properties_t() + eng_props.stype = pyzes.ZES_STRUCTURE_TYPE_ENGINE_PROPERTIES + _zes_check( + pyzes.zesEngineGetProperties(eng_handle, byref(eng_props)), + "Can't get Level Zero Sysman engine properties.", + ) + if eng_props.type != pyzes.ZES_ENGINE_GROUP_ALL: + continue + if subdevice_id is not None: + if eng_props.onSubdevice and eng_props.subdeviceId == subdevice_id: + engine_handle = eng_handle + break + else: + if not eng_props.onSubdevice: + engine_handle = eng_handle + break + + if engine_handle is None: + raise RuntimeError("No Level Zero Sysman GPU engine handle found.") + info.engine_handle = engine_handle + return engine_handle + + +def utilization(device: Device = None) -> float: + r"""Return the GPU engine utilization as a percentage. + + The value is computed by dividing the active-time delta by the time delta + between two engine-activity reads separated by a 100ms sampling interval. + + Args: + device (torch.device, str or int, optional): selected device. Uses the + current device, given by :func:`~torch.xpu.current_device`, + if ``None`` (default). + + .. note:: This function blocks for approximately 100ms per call due to the + sampling interval required to compute an accurate utilization reading. + + .. note:: This API may require elevated privileges (e.g. ``sudo``) to access GPU utilization information. + """ + engine_handle = _get_zes_engine_handle(device) + + import pyzes # type: ignore[import] + + stats_start = pyzes.zes_engine_stats_t() + rc = pyzes.zesEngineGetActivity(engine_handle, byref(stats_start)) + if rc == pyzes.ZE_RESULT_ERROR_NOT_AVAILABLE: + raise RuntimeError( + "GPU utilization querying is not available. Try running with elevated privileges (e.g. sudo)." + ) + if rc != pyzes.ZE_RESULT_SUCCESS: + raise RuntimeError( + f"Can't get Level Zero Sysman GPU engine activity (rc={rc})." + ) + + import time + + time.sleep(_zes_sample_interval_ms / 1000.0) + + stats_end = pyzes.zes_engine_stats_t() + _zes_check( + pyzes.zesEngineGetActivity(engine_handle, byref(stats_end)), + "Can't get Level Zero Sysman GPU engine activity.", + ) + # activeTime and timestamp are monotonic counters in microseconds. + dt = stats_end.timestamp - stats_start.timestamp + return (stats_end.activeTime - stats_start.activeTime) / dt * 100 + + +def _zes_get_memory_handle(device: Device = None) -> c_void_p: + r"""Return the Level Zero Sysman GPU memory module handle for the specified device. + + The result is cached in ``_ZesDeviceInfo.memory_handle`` so that + repeated calls skip module enumeration. ``_cached_zes_device_infos`` + is lazily populated on the first call. + + Args: + device (torch.device, str or int, optional): target device. Uses the + current device, given by :func:`~torch.xpu.current_device`, + if ``None`` (default). + """ + pyzes = _import_pyzes() + + device = _get_device_index(device, optional=True) + _zes_ensure_device_infos(device) + + info = _cached_zes_device_infos[device] + if info.memory_handle is not None: + return info.memory_handle + + device_handle = info.device_handle + subdevice_id = info.subdevice_id + + # See Note [telemetry handle selection] + mem_count = c_uint32(0) + _zes_check( + pyzes.zesDeviceEnumMemoryModules(device_handle, byref(mem_count), None), + "Can't get Level Zero Sysman memory module count.", + ) + if mem_count.value == 0: + raise RuntimeError("No Level Zero Sysman memory modules found.") + memory_handles = (pyzes.zes_mem_handle_t * mem_count.value)() + _zes_check( + pyzes.zesDeviceEnumMemoryModules( + device_handle, byref(mem_count), memory_handles + ), + "Can't get Level Zero Sysman memory module handles.", + ) + + memory_handle = None + for mem_handle in memory_handles: + mem_props = pyzes.zes_mem_properties_t() + mem_props.stype = pyzes.ZES_STRUCTURE_TYPE_MEM_PROPERTIES + _zes_check( + pyzes.zesMemoryGetProperties(mem_handle, byref(mem_props)), + "Can't get Level Zero Sysman memory properties.", + ) + if mem_props.location != pyzes.ZES_MEM_LOC_DEVICE: + continue + if subdevice_id is not None: + if mem_props.onSubdevice and mem_props.subdeviceId == subdevice_id: + memory_handle = mem_handle + break + else: + if not mem_props.onSubdevice: + memory_handle = mem_handle + break + + if memory_handle is None: + raise RuntimeError("No Level Zero Sysman GPU memory handle found.") + info.memory_handle = memory_handle + return memory_handle + + +def memory_usage(device: Device = None) -> float: + r"""Return the GPU memory bandwidth usage as a percentage. + + The value is computed by dividing the byte-transfer delta by the time delta + between two bandwidth-counter reads separated by a 100ms sampling interval, + then normalizing by the peak bandwidth reported by the hardware. + + Args: + device (torch.device, str or int, optional): selected device. Uses the + current device, given by :func:`~torch.xpu.current_device`, + if ``None`` (default). + + .. note:: This function blocks for approximately 100ms per call due to the + sampling interval required to compute an accurate bandwidth reading. + + .. note:: This API may require elevated privileges (e.g. ``sudo``) to access GPU memory bandwidth usage information. + """ + memory_handle = _zes_get_memory_handle(device) + + import pyzes # type: ignore[import] + + bandwidth_start = pyzes.zes_mem_bandwidth_t() + rc = pyzes.zesMemoryGetBandwidth(memory_handle, byref(bandwidth_start)) + if rc == pyzes.ZE_RESULT_ERROR_NOT_AVAILABLE: + raise RuntimeError( + "GPU memory bandwidth usage querying is not available. Try running with elevated privileges (e.g. sudo)." + ) + if rc != pyzes.ZE_RESULT_SUCCESS: + raise RuntimeError( + f"Can't get Level Zero Sysman GPU memory bandwidth (rc={rc})." + ) + + import time + + time.sleep(_zes_sample_interval_ms / 1000.0) + + bandwidth_end = pyzes.zes_mem_bandwidth_t() + _zes_check( + pyzes.zesMemoryGetBandwidth(memory_handle, byref(bandwidth_end)), + "Can't get Level Zero Sysman GPU memory bandwidth.", + ) + dt = bandwidth_end.timestamp - bandwidth_start.timestamp + # readCounter and writeCounter are cumulative byte counts (per L0 Sysman spec). + read_delta = bandwidth_end.readCounter - bandwidth_start.readCounter + write_delta = bandwidth_end.writeCounter - bandwidth_start.writeCounter + # maxBandwidth is in bytes/sec; dt is in microseconds; the 1e6 factor converts dt to seconds. + return 1e6 * (read_delta + write_delta) / (bandwidth_end.maxBandwidth * dt) * 100 + + +def device_memory_used(device: Device = None) -> int: + r"""Return the current GPU used global (device) memory in bytes. + + Args: + device (torch.device, str or int, optional): selected device. Uses the + current device, given by :func:`~torch.xpu.current_device`, + if ``None`` (default). + + .. note:: This API may require elevated privileges (e.g. ``sudo``) to access GPU memory usage information. + """ + memory_handle = _zes_get_memory_handle(device) + + import pyzes # type: ignore[import] + + mem_state = pyzes.zes_mem_state_t() + rc = pyzes.zesMemoryGetState(memory_handle, byref(mem_state)) + if rc == pyzes.ZE_RESULT_ERROR_NOT_AVAILABLE: + raise RuntimeError( + "GPU memory usage querying is not available. Try running with elevated privileges (e.g. sudo)." + ) + if rc != pyzes.ZE_RESULT_SUCCESS: + raise RuntimeError(f"Can't get Level Zero Sysman GPU memory state (rc={rc}).") + mem_props = pyzes.zes_mem_properties_t() + mem_props.stype = pyzes.ZES_STRUCTURE_TYPE_MEM_PROPERTIES + _zes_check( + pyzes.zesMemoryGetProperties(memory_handle, byref(mem_props)), + "Can't get Level Zero Sysman memory properties.", + ) + # TODO: Some drivers report physicalSize as 0 on client GPUs; fall back to + # the allocatable size as an approximation in that case. + total = mem_props.physicalSize if mem_props.physicalSize != 0 else mem_state.size + return total - mem_state.free + + +# import here to avoid circular import +from .memory import ( + change_current_allocator, + empty_cache, + get_per_process_memory_fraction, + list_gpu_processes, + max_memory_allocated, + max_memory_reserved, + mem_get_info, + memory_allocated, + memory_reserved, + memory_snapshot, + memory_stats, + memory_stats_as_nested_dict, + MemPool, + reset_accumulated_memory_stats, + reset_peak_memory_stats, + set_per_process_memory_fraction, + use_mem_pool, + XPUPluggableAllocator, +) +from .random import ( + get_rng_state, + get_rng_state_all, + initial_seed, + manual_seed, + manual_seed_all, + seed, + seed_all, + set_rng_state, + set_rng_state_all, +) + + +_POOL_HANDLE = NewType("_POOL_HANDLE", tuple[int, int]) +__all__ = [ + "Event", + "Stream", + "StreamContext", + "XPUPluggableAllocator", + "XPUGraph", + "can_device_access_peer", + "change_current_allocator", + "clock_rate", + "current_device", + "current_stream", + "default_generators", + "device", + "device_of", + "device_count", + "device_memory_used", + "empty_cache", + "get_arch_list", + "get_device_capability", + "get_device_name", + "get_device_properties", + "get_gencode_flags", + "get_per_process_memory_fraction", + "get_rng_state", + "get_rng_state_all", + "get_stream_from_external", + "graph", + "graph_pool_handle", + "init", + "initial_seed", + "is_available", + "is_bf16_supported", + "is_current_stream_capturing", + "is_initialized", + "is_tf32_supported", + "list_gpu_processes", + "make_graphed_callables", + "manual_seed", + "manual_seed_all", + "max_memory_allocated", + "max_memory_reserved", + "mem_get_info", + "memory_allocated", + "memory_reserved", + "memory_snapshot", + "memory_stats", + "memory_stats_as_nested_dict", + "memory_usage", + "MemPool", + "power_draw", + "use_mem_pool", + "reset_accumulated_memory_stats", + "reset_peak_memory_stats", + "seed", + "seed_all", + "set_device", + "set_per_process_memory_fraction", + "set_rng_state", + "set_rng_state_all", + "set_stream", + "stream", + "streams", + "synchronize", + "temperature", + "utilization", +] diff --git a/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61bdfa7729137ed3cee303f25c0e12b1eed2fed9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/_gpu_trace.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/_gpu_trace.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d795a937e552cd5eaea436422c793b84d96594f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/_gpu_trace.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28b4c7201577f29532ba05df43557e750b002eaf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/graphs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/graphs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70b5d2e97a74165f461af68ae86d0feb32c5e52d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/graphs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/memory.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/memory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91ec2e511f968532851d3596a095dde17fb72a53 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/memory.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/random.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/random.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b218ec61ea2fb3f2f981680d25357772ba9c36f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/random.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/streams.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/streams.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f4a2bf9400248695dc76247e4ea0ca2ad15b018 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torch/xpu/__pycache__/streams.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torch/xpu/_gpu_trace.py b/.venv/lib/python3.12/site-packages/torch/xpu/_gpu_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..7c3a8b9bf785bee0d46f657d0ea1754dea3c7dcc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/xpu/_gpu_trace.py @@ -0,0 +1,69 @@ +from collections.abc import Callable + +from torch._utils import CallbackRegistry + + +EventCreationCallbacks: "CallbackRegistry[int]" = CallbackRegistry("XPU event creation") +EventDeletionCallbacks: "CallbackRegistry[int]" = CallbackRegistry("XPU event deletion") +EventRecordCallbacks: "CallbackRegistry[int, int]" = CallbackRegistry( + "XPU event record" +) +EventWaitCallbacks: "CallbackRegistry[int, int]" = CallbackRegistry("XPU event wait") +MemoryAllocationCallbacks: "CallbackRegistry[int]" = CallbackRegistry( + "XPU memory allocation" +) +MemoryDeallocationCallbacks: "CallbackRegistry[int]" = CallbackRegistry( + "XPU memory deallocation" +) +StreamCreationCallbacks: "CallbackRegistry[int]" = CallbackRegistry( + "XPU stream creation" +) +DeviceSynchronizationCallbacks: "CallbackRegistry[[]]" = CallbackRegistry( + "XPU device synchronization" +) +StreamSynchronizationCallbacks: "CallbackRegistry[int]" = CallbackRegistry( + "XPU stream synchronization" +) +EventSynchronizationCallbacks: "CallbackRegistry[int]" = CallbackRegistry( + "XPU event synchronization" +) + + +def register_callback_for_event_creation(cb: Callable[[int], None]) -> None: + EventCreationCallbacks.add_callback(cb) + + +def register_callback_for_event_deletion(cb: Callable[[int], None]) -> None: + EventDeletionCallbacks.add_callback(cb) + + +def register_callback_for_event_record(cb: Callable[[int, int], None]) -> None: + EventRecordCallbacks.add_callback(cb) + + +def register_callback_for_event_wait(cb: Callable[[int, int], None]) -> None: + EventWaitCallbacks.add_callback(cb) + + +def register_callback_for_memory_allocation(cb: Callable[[int], None]) -> None: + MemoryAllocationCallbacks.add_callback(cb) + + +def register_callback_for_memory_deallocation(cb: Callable[[int], None]) -> None: + MemoryDeallocationCallbacks.add_callback(cb) + + +def register_callback_for_stream_creation(cb: Callable[[int], None]) -> None: + StreamCreationCallbacks.add_callback(cb) + + +def register_callback_for_device_synchronization(cb: Callable[[], None]) -> None: + DeviceSynchronizationCallbacks.add_callback(cb) + + +def register_callback_for_stream_synchronization(cb: Callable[[int], None]) -> None: + StreamSynchronizationCallbacks.add_callback(cb) + + +def register_callback_for_event_synchronization(cb: Callable[[int], None]) -> None: + EventSynchronizationCallbacks.add_callback(cb) diff --git a/.venv/lib/python3.12/site-packages/torch/xpu/_utils.py b/.venv/lib/python3.12/site-packages/torch/xpu/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8f738267459a2791a4a33ca4bec74800a58f0b9a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/xpu/_utils.py @@ -0,0 +1,39 @@ +from typing import Any + +import torch + +# The _get_device_index has been moved to torch.utils._get_device_index +from torch._utils import _get_device_index as _torch_get_device_index + + +def _get_device_index( + device: Any, optional: bool = False, allow_cpu: bool = False +) -> int: + r"""Get the device index from :attr:`device`, which can be a torch.device + object, a Python integer, or ``None``. + + If :attr:`device` is a torch.device object, returns the device index if it + is a XPU device. Note that for a XPU device without a specified index, + i.e., ``torch.device('xpu')``, this will return the current default XPU + device if :attr:`optional` is ``True``. If :attr:`allow_cpu` is ``True``, + CPU devices will be accepted and ``-1`` will be returned in this case. + + If :attr:`device` is a Python integer, it is returned as is. + + If :attr:`device` is ``None``, this will return the current default XPU + device if :attr:`optional` is ``True``. + """ + if isinstance(device, int): + return device + if isinstance(device, str): + device = torch.device(device) + if isinstance(device, torch.device): + if allow_cpu: + if device.type not in ["xpu", "cpu"]: + raise ValueError(f"Expected a xpu or cpu device, but got: {device}") + elif device.type != "xpu": + raise ValueError(f"Expected a xpu device, but got: {device}") + if not torch.jit.is_scripting(): + if isinstance(device, torch.xpu.device): + return device.idx + return _torch_get_device_index(device, optional, allow_cpu) diff --git a/.venv/lib/python3.12/site-packages/torch/xpu/graphs.py b/.venv/lib/python3.12/site-packages/torch/xpu/graphs.py new file mode 100644 index 0000000000000000000000000000000000000000..a90135e00f4918f11325b92530ee037052ead5f6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/xpu/graphs.py @@ -0,0 +1,529 @@ +from __future__ import annotations + +import typing +from collections.abc import Callable +from typing import overload, TYPE_CHECKING, TypeAlias +from typing_extensions import ParamSpec, Self, TypeVar + +import torch +from torch import Tensor + + +if TYPE_CHECKING: + from torch.xpu import _POOL_HANDLE + +from .._utils import _dummy_type + + +__all__ = [ + "is_current_stream_capturing", + "graph_pool_handle", + "XPUGraph", + "graph", + "make_graphed_callables", +] + +_R = TypeVar("_R") +_P = ParamSpec("_P") + +if not hasattr(torch._C, "_XpuStreamBase"): + # Define dummy base classes + torch._C.__dict__["_XPUGraph"] = _dummy_type("_XPUGraph") + torch._C.__dict__["_xpu_graph_pool_handle"] = _dummy_type("_xpu_graph_pool_handle") + torch._C.__dict__["_xpu_isCurrentStreamCapturing"] = _dummy_type( + "_xpu_isCurrentStreamCapturing" + ) + +from torch._C import _xpu_graph_pool_handle, _xpu_isCurrentStreamCapturing, _XPUGraph + + +def is_current_stream_capturing() -> bool: + r"""Return True if XPU graph capture is underway on the current XPU stream, False otherwise. + + If a XPU context does not exist on the current device, returns False without initializing the context. + """ + return _xpu_isCurrentStreamCapturing() + + +def graph_pool_handle() -> _POOL_HANDLE: + r"""Return an opaque token representing the id of a graph memory pool.""" + return torch.xpu._POOL_HANDLE(_xpu_graph_pool_handle()) + + +class XPUGraph(_XPUGraph): + r"""Wrapper around a XPU graph. + + Arguments: + keep_graph (bool, optional): If ``keep_graph=False``, the + executable command graph will be instantiated on GPU at the end of + ``capture_end`` and the underlying modifiable command graph will be + destroyed. Note that the executable command graph will not be + instantiated at the end of ``capture_end`` in this + case. Instead, it will be instantiated via an explicit called + to ``instantiate`` or automatically on the first call to + ``replay`` if ``instantiate`` was not already called. Calling + ``instantiate`` manually before ``replay`` is recommended to + prevent increased latency on the first call to ``replay``. + + """ + + def __new__(cls, keep_graph: bool = False) -> Self: + return super().__new__(cls, keep_graph) + + def capture_begin(self, pool: _POOL_HANDLE | None = None) -> None: + r"""Begin capturing XPU work on the current xpu stream. + + Typically, you shouldn't call ``capture_begin`` yourself. + Use :class:`~torch.xpu.graph`, which call ``capture_begin`` internally. + + Arguments: + pool (optional): Token (returned by :func:`~torch.xpu.graph_pool_handle` or + :meth:`other_Graph_instance.pool()`) that hints this graph may share memory + with the indicated pool. + """ + super().capture_begin(pool=pool) + + def capture_end(self) -> None: + r"""End XPU graph capture on the current stream. + + After ``capture_end``, ``replay`` may be called on this instance. + + Typically, you shouldn't call ``capture_end`` yourself. + Use :class:`~torch.xpu.graph`, which call ``capture_end`` internally. + """ + super().capture_end() + + def instantiate(self) -> None: + r"""Instantiate the XPU graph. Will be called by + ``capture_end`` if ``keep_graph=False``, or by ``replay`` if + ``keep_graph=True`` and ``instantiate`` has not already been + explicitly called. Does not destroy the xpu modify command graph returned + by ``raw_xpu_graph``. + """ + super().instantiate() + + def replay(self) -> None: + r"""Replay the XPU work captured by this graph.""" + super().replay() + + def reset(self) -> None: + r"""Delete the graph currently held by this instance.""" + super().reset() + + def pool(self) -> _POOL_HANDLE: + r"""Return an opaque token representing the id of this graph's memory pool. + + This id can optionally be passed to another graph's ``capture_begin``, + which hints the other graph may share the same memory pool. + """ + return super().pool() + + def enable_debug_mode(self) -> None: + r"""Enable debugging mode for XPUGraph.debug_dump.""" + return super().enable_debug_mode() + + def debug_dump(self, debug_path: str) -> None: + r""" + Arguments: + debug_path (required): Path to dump the graph to. + + Calls a debugging function to dump the graph if the debugging is + enabled via XPUGraph.enable_debug_mode() + """ + return super().debug_dump(debug_path) + + def raw_xpu_graph(self) -> int: + r"""Returns the underlying xpuGraph_t. ``keep_graph`` must be True. + + XPU doesn't provide APIs to manipulate this object. + """ + return super().raw_xpu_graph() + + def raw_xpu_graph_exec(self) -> int: + r"""Returns the underlying xpuGraphExec_t. ``instantiate`` must have been called if ``keep_graph`` is True, or ``capture_end`` must have been called if ``keep_graph`` is False. If you call ``instantiate()`` after ``raw_xpu_graph_exec()``, the previously returned xpuGraphExec_t will be destroyed. It is your responsibility not to use this object after destruction. + + XPU doesn't provide APIs to manipulate this object. + """ + return super().raw_xpu_graph_exec() + + +class graph: + r"""Context-manager that captures XPU work into a :class:`torch.xpu.XPUGraph` object for later replay. + + Arguments: + xpu_graph (torch.xpu.XPUGraph): Graph object used for capture. + pool (optional): Opaque token (returned by a call to :func:`~torch.xpu.graph_pool_handle()` or + :meth:`other_Graph_instance.pool()`) hinting this graph's capture + may share memory from the specified pool. + stream (torch.xpu.Stream, optional): If supplied, will be set as the current stream in the context. + If not supplied, ``graph`` sets its own internal side stream as the current stream in the context. + + .. note:: + For effective memory sharing, if you pass a ``pool`` used by a previous capture and the previous capture + used an explicit ``stream`` argument, you should pass the same ``stream`` argument to this capture. + + """ + + default_capture_stream: torch.xpu.Stream | None = None + + def __init__( + self, + xpu_graph: XPUGraph, + pool: _POOL_HANDLE | None = None, + stream: torch.xpu.Stream | None = None, + ): + # Lazy-init of default_capture_stream helps avoid circular-import errors. + # Not thread safe, but graphs already have the general (explicitly documented) + # restriction that only one capture may be underway at a time in the process. + if self.__class__.default_capture_stream is None: + self.__class__.default_capture_stream = torch.xpu.Stream() + + self.pool: tuple[()] | tuple[_POOL_HANDLE] = () if pool is None else (pool,) + self.capture_stream = ( + stream if stream is not None else self.__class__.default_capture_stream + ) + if self.capture_stream is None: + raise AssertionError("capture_stream must not be None") + self.stream_ctx = self.capture_stream + self.xpu_graph = xpu_graph + + def __enter__(self) -> None: + # Free as much memory as we can for the graph + torch.xpu.synchronize() + + torch.xpu.empty_cache() + self.stream_ctx.__enter__() + + self.xpu_graph.capture_begin(*self.pool) + + def __exit__(self, *args: object) -> None: + self.xpu_graph.capture_end() + self.stream_ctx.__exit__(*args) + + +_ModuleOrCallable: TypeAlias = torch.nn.Module | Callable[..., object] + + +@overload +def make_graphed_callables( + callables: _ModuleOrCallable, + sample_args: tuple[Tensor, ...], + num_warmup_iters: int = 3, + allow_unused_input: bool = False, + pool: _POOL_HANDLE | None = None, +) -> _ModuleOrCallable: ... + + +@overload +def make_graphed_callables( + callables: tuple[_ModuleOrCallable, ...], + sample_args: tuple[tuple[Tensor, ...], ...], + num_warmup_iters: int = 3, + allow_unused_input: bool = False, + pool: _POOL_HANDLE | None = None, +) -> tuple[_ModuleOrCallable, ...]: ... + + +def make_graphed_callables( + callables: _ModuleOrCallable | tuple[_ModuleOrCallable, ...], + sample_args: tuple[Tensor, ...] | tuple[tuple[Tensor, ...], ...], + num_warmup_iters: int = 3, + allow_unused_input: bool = False, + pool: _POOL_HANDLE | None = None, +) -> _ModuleOrCallable | tuple[_ModuleOrCallable, ...]: + r"""Accept callables (functions or :class:`nn.Module`\ s) and returns graphed versions. + + Each graphed callable's forward pass runs its source callable's + forward XPU work as a XPU graph inside a single autograd node. + + The graphed callable's forward pass also appends + a backward node to the autograd graph. During backward, this node runs the + callable's backward work as a XPU graph. + + Therefore, each graphed callable should be a drop-in replacement for its source callable + in an autograd-enabled training loop. + + See :ref:`Partial-network capture` for detailed use and constraints. + + If you pass a tuple of several callables, their captures will use the same memory pool. + + Arguments: + callables (torch.nn.Module or Python function, or tuple of these): Callable or callables to graph. + If you pass a tuple of callables, their order in the tuple must be the same order they'll run + in the live workload. + sample_args (tuple of Tensors, or tuple of tuples of Tensors): Samples args for each callable. + If a single callable was passed, ``sample_args`` must be a single tuple of argument Tensors. + If a tuple of callables was passed, ``sample_args`` must be tuple of tuples of argument Tensors. + num_warmup_iters (int): The number of warmup iterations. Currently, ``DataDistributedParallel`` needs + 11 iterations for warm up. Default: ``3``. + allow_unused_input (bool): If False, specifying inputs that were not used when computing outputs + (and therefore their grad is always zero) is an error. Defaults to False. + pool (optional): Token (returned by :func:`~torch.xpu.graph_pool_handle` or + :meth:`other_Graph_instance.pool()`) that hints this graph may share memory + with the indicated pool. + .. note:: + The ``requires_grad`` state of each Tensor in ``sample_args`` must match the state + that's expected for the corresponding real input in the training loop. + + .. warning:: + This API is in beta and may change in future releases. + + .. warning:: + ``sample_args`` for each callable must contain only Tensors. Other types are not allowed. + + .. warning:: + Returned callables do not support higher order differentiation (e.g., double backward). + + .. warning:: + In any :class:`~torch.nn.Module` passed to :func:`~make_graphed_callables`, only parameters + may be trainable. Buffers must have ``requires_grad=False``. + + .. warning:: + After you pass a :class:`torch.nn.Module` through :func:`~make_graphed_callables`, + you may not add or remove any of that Module's parameters or buffers. + + .. warning:: + :class:`torch.nn.Module`\s passed to :func:`~torch.xpu.make_graphed_callables` must not have module hooks + registered on them at the time they are passed. However, registering hooks on modules *after* passing them + through :func:`~torch.xpu.make_graphed_callables` is allowed. + + .. warning:: + When running a graphed callable, you must pass its arguments in the same order and format + they appeared in that callable's ``sample_args``. + + .. warning:: + The automatic mixed precision is supported in :func:`~torch.xpu.make_graphed_callables` only with disabled + caching. The context manager `torch.amp.autocast()` must have `cache_enabled=False`. + """ + if torch.is_autocast_enabled("xpu") and torch.is_autocast_cache_enabled(): + raise RuntimeError( + "make_graphed_callables does not support the autocast caching. Please set `cache_enabled=False`." + ) + + just_one_callable = False + + _sample_args: tuple[tuple[Tensor, ...], ...] + if not isinstance(callables, tuple): + just_one_callable = True + callables = (callables,) + _sample_args = (typing.cast(tuple[Tensor, ...], sample_args),) + else: + _sample_args = typing.cast(tuple[tuple[Tensor, ...], ...], sample_args) + + flatten_sample_args = [] + + for c, args in zip(callables, _sample_args): + if isinstance(c, torch.nn.Module): + if not ( + len(c._backward_hooks) == 0 + and len(c._forward_hooks) == 0 + and len(c._forward_pre_hooks) == 0 + ): + raise RuntimeError( + "Modules must not have hooks registered at the time they are passed. However, registering hooks " + + "on modules after passing them through make_graphed_callables is allowed." + ) + if not all(b.requires_grad is False for b in c.buffers()): + raise RuntimeError( + "In any :class:`~torch.nn.Module` passed to " + + ":func:`~make_graphed_callables`, only parameters may be trainable. All buffers must have " + + "``requires_grad=False``." + ) + flatten_arg = torch.utils._pytree.arg_tree_leaves(*args) + flatten_sample_args.append(tuple(flatten_arg)) + if not all(isinstance(arg, torch.Tensor) for arg in flatten_arg): + raise TypeError( + "In the beta API, sample_args " + + "for each callable must contain only Tensors. Other types are not allowed." + ) + + # If a callable is an nn.Module, its graph's full input surface is the args the user explicitly + # passes to forward (ie, its sample_args) AND the module's parameter attributes. + per_callable_len_user_args = [len(args) for args in flatten_sample_args] + per_callable_module_params = [ + tuple(c.parameters()) if isinstance(c, torch.nn.Module) else () + for c in callables + ] + per_callable_static_input_surfaces = [ + flatten_sample_args[i] + per_callable_module_params[i] + for i in range(len(callables)) + ] + + fwd_graphs = [torch.xpu.XPUGraph() for _ in range(len(callables))] + bwd_graphs = [torch.xpu.XPUGraph() for _ in range(len(callables))] + + mempool = graph_pool_handle() if pool is None else pool + + # Warmup + torch.xpu.synchronize() + with torch.xpu.stream(torch.xpu.Stream()): + for func, args, static_input_surface in zip( + callables, _sample_args, per_callable_static_input_surfaces + ): + grad_inputs, outputs, outputs_grad = None, None, None + for _ in range(num_warmup_iters): + outputs = torch.utils._pytree.tree_leaves(func(*args)) + outputs_grad = tuple(o for o in outputs if o.requires_grad) + if len(outputs_grad) > 0: + grad_inputs = torch.autograd.grad( + outputs=outputs_grad, + inputs=tuple( + i for i in static_input_surface if i.requires_grad + ), + grad_outputs=tuple( + torch.empty_like(o) for o in outputs if o.requires_grad + ), + only_inputs=True, + allow_unused=allow_unused_input, + ) + for v in [outputs, outputs_grad, grad_inputs]: + del v + + torch.xpu.synchronize() + + # Capture forward graphs + per_callable_static_outputs = [] + per_callable_output_unflatten_spec = [] + for func, args, fwd_graph in zip(callables, _sample_args, fwd_graphs): + # each graph uses the same mempool + with torch.xpu.graph(fwd_graph, pool=mempool): + func_outputs = func(*args) + + flatten_outputs, spec = torch.utils._pytree.tree_flatten(func_outputs) + per_callable_static_outputs.append(tuple(flatten_outputs)) + per_callable_output_unflatten_spec.append(spec) + + # Capture backward graphs in reverse order + per_callable_static_grad_outputs = [] + per_callable_static_grad_inputs = [] + for static_input_surface, static_outputs, bwd_graph in zip( + reversed(per_callable_static_input_surfaces), + reversed(per_callable_static_outputs), + reversed(bwd_graphs), + ): + static_grad_outputs = tuple( + torch.empty_like(o) if o.requires_grad else None for o in static_outputs + ) + + outputs_grad = tuple(o for o in static_outputs if o.requires_grad) + grad_inputs = None + if len(outputs_grad) > 0: + with torch.xpu.graph(bwd_graph, pool=mempool): + grad_inputs = torch.autograd.grad( + outputs=outputs_grad, + inputs=tuple(i for i in static_input_surface if i.requires_grad), + grad_outputs=tuple(o for o in static_grad_outputs if o is not None), + only_inputs=True, + allow_unused=allow_unused_input, + ) + + static_grad_inputs = [] + grad_idx = 0 + for arg in static_input_surface: + if arg.requires_grad and grad_inputs is not None: + static_grad_inputs.append(grad_inputs[grad_idx]) + grad_idx += 1 + else: + static_grad_inputs.append(None) # type: ignore[arg-type] + static_grad_inputs = tuple(static_grad_inputs) # type: ignore[assignment] + + per_callable_static_grad_outputs.append(static_grad_outputs) + per_callable_static_grad_inputs.append(static_grad_inputs) + + # Reverses the most recent two lists + per_callable_static_grad_outputs.reverse() + per_callable_static_grad_inputs.reverse() + + def make_graphed_autograd_function( + fwd_graph: XPUGraph, + bwd_graph: XPUGraph, + module_params: tuple[torch.nn.Parameter, ...], + len_user_args: int, + output_unflatten_spec: torch.utils._pytree.TreeSpec, + static_input_surface: tuple[Tensor, ...], + static_outputs: tuple[Tensor, ...], + static_grad_outputs: tuple[Tensor | None, ...], + static_grad_inputs: tuple[Tensor, ...], + ) -> Callable[..., object]: + class Graphed(torch.autograd.Function): + @staticmethod + # pyrefly: ignore [bad-override] + def forward(ctx: object, *inputs: Tensor) -> tuple[Tensor, ...]: + # At this stage, only the user args may (potentially) be new tensors. + for i in range(len_user_args): + if static_input_surface[i].data_ptr() != inputs[i].data_ptr(): + static_input_surface[i].copy_(inputs[i]) + fwd_graph.replay() + if not isinstance(static_outputs, tuple): + raise RuntimeError("static_outputs must be a tuple") + return tuple(o.detach() for o in static_outputs) + + @staticmethod + @torch.autograd.function.once_differentiable + # pyrefly: ignore [bad-override] + def backward(ctx: object, *grads: Tensor) -> tuple[Tensor, ...]: + if len(grads) != len(static_grad_outputs): + raise RuntimeError( + f"Expected {len(static_grad_outputs)} gradients but got {len(grads)}" + ) + for g, grad in zip(static_grad_outputs, grads): + if g is not None: + if g.data_ptr() != grad.data_ptr(): + g.copy_(grad) + bwd_graph.replay() + + if not isinstance(static_grad_inputs, tuple): + raise RuntimeError("static_grad_inputs must be a tuple") + return tuple( + b.detach() if b is not None else b for b in static_grad_inputs + ) + + def functionalized(*user_args: object) -> object: + # Runs the new autograd function which replays the XPU graphs + flatten_user_args = torch.utils._pytree.arg_tree_leaves(*user_args) + out = Graphed.apply(*(tuple(flatten_user_args) + module_params)) + return torch.utils._pytree.tree_unflatten(out, output_unflatten_spec) + + return functionalized + + ret: list[_ModuleOrCallable] = [] + for i, func in enumerate(callables): + graphed = make_graphed_autograd_function( + fwd_graphs[i], + bwd_graphs[i], + per_callable_module_params[i], + per_callable_len_user_args[i], + per_callable_output_unflatten_spec[i], + per_callable_static_input_surfaces[i], + per_callable_static_outputs[i], + per_callable_static_grad_outputs[i], + per_callable_static_grad_inputs[i], + ) + + if isinstance(func, torch.nn.Module): + + def make_graphed_forward( + func: torch.nn.Module, + graph_training_state: bool, + graphed: Callable[_P, _R], + orig_fwd: Callable[_P, _R], + ) -> Callable[_P, _R]: + def new_fwd(*user_args: _P.args, **user_kwargs: _P.kwargs) -> _R: + if func.training == graph_training_state: + return graphed(*user_args, **user_kwargs) + else: + return orig_fwd(*user_args, **user_kwargs) + + return new_fwd + + func.forward = make_graphed_forward( + func, func.training, graphed, func.forward + ) + ret.append(func) + else: + ret.append(graphed) + + if just_one_callable: + return ret[0] + + return tuple(ret) diff --git a/.venv/lib/python3.12/site-packages/torch/xpu/memory.py b/.venv/lib/python3.12/site-packages/torch/xpu/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..d59f84e4f6e83a3ea12b78a8515a40c7158f4cf9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/xpu/memory.py @@ -0,0 +1,706 @@ +import collections +import contextlib +import ctypes +import pickle +import sys +from typing import Any, Literal + +import torch +from torch._utils import _augment_memory_snapshot_stack_traces, _dummy_type +from torch.types import Device + +from . import _get_device_index, _is_compiled, _lazy_init, is_initialized + + +if not _is_compiled(): + # Define dummy base classes + torch._C.__dict__["_xpu_XPUAllocator"] = _dummy_type("_xpu_XPUAllocator") + torch._C.__dict__["_XPUMemPool"] = _dummy_type("_XPUMemPool") + torch._C.__dict__["_xpu_beginAllocateCurrentThreadToPool"] = _dummy_type( + "_xpu_beginAllocateCurrentThreadToPool" + ) + torch._C.__dict__["_xpu_endAllocateToPool"] = _dummy_type("_xpu_endAllocateToPool") + torch._C.__dict__["_xpu_releasePool"] = _dummy_type("_xpu_releasePool") + + +def empty_cache() -> None: + r"""Release all unoccupied cached memory currently held by the caching + allocator so that those can be used in other XPU application. + + .. note:: + :func:`~torch.xpu.empty_cache` doesn't increase the amount of XPU + memory available for PyTorch. However, it may help reduce fragmentation + of XPU memory in certain cases. + """ + if is_initialized(): + torch._C._xpu_emptyCache() + + +def reset_peak_memory_stats(device: Device = None) -> None: + r"""Reset the "peak" stats tracked by the XPU memory allocator. + + See :func:`~torch.xpu.memory_stats` for details. Peak stats correspond to the + `"peak"` key in each individual stat dict. + + Args: + device (torch.device or int or str, optional): selected device. Returns + statistic for the current device, given by :func:`~torch.xpu.current_device`, + if :attr:`device` is ``None`` (default). + """ + device = _get_device_index(device, optional=True) + return torch._C._xpu_resetPeakMemoryStats(device) + + +def reset_accumulated_memory_stats(device: Device = None) -> None: + r"""Reset the "accumulated" (historical) stats tracked by the XPU memory allocator. + + See :func:`~torch.xpu.memory_stats` for details. Accumulated stats correspond to + the `"allocated"` and `"freed"` keys in each individual stat dict. + + Args: + device (torch.device or int or str, optional): selected device. Returns + statistic for the current device, given by :func:`~torch.xpu.current_device`, + if :attr:`device` is ``None`` (default). + """ + device = _get_device_index(device, optional=True) + return torch._C._xpu_resetAccumulatedMemoryStats(device) + + +def memory_stats_as_nested_dict(device: Device = None) -> dict[str, Any]: + r"""Return the result of :func:`~torch.xpu.memory_stats` as a nested dictionary.""" + if not is_initialized(): + return {} + device = _get_device_index(device, optional=True) + return torch._C._xpu_memoryStats(device) + + +def _recurse_add_to_result( + result: list[tuple[str, Any]], prefix: str, obj: Any +) -> None: + if isinstance(obj, dict): + if prefix: + prefix += "." + for key, value in obj.items(): + _recurse_add_to_result(result, prefix + key, value) + else: + result.append((prefix, obj)) + + +def memory_stats(device: Device = None) -> dict[str, Any]: + r"""Return a dictionary of XPU memory allocator statistics for a given device. + + The return value of this function is a dictionary of statistics, each of + which is a non-negative integer. + + Core statistics: + + - ``"allocated_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``: + amount of allocated memory. + - ``"reserved_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``: + amount of reserved memory. + - ``"active_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``: + amount of active memory. + - ``"requested_bytes.{all,large_pool,small_pool}.{current,peak,allocated,freed}"``: + memory requested by client code, compare this with allocated_bytes to check if + allocation rounding adds too much overhead. + + For these core statistics, values are broken down as follows. + + Pool type: + + - ``all``: combined statistics across all memory pools. + - ``large_pool``: statistics for the large allocation pool (for size >= 1MB allocations). + - ``small_pool``: statistics for the small allocation pool (for size < 1MB allocations). + + Metric type: + + - ``current``: current value of this metric. + - ``peak``: maximum value of this metric. + - ``allocated``: historical total increase in this metric. + - ``freed``: historical total decrease in this metric. + + Args: + device (torch.device or int or str, optional): selected device. Returns + statistics for the current device, given by :func:`~torch.xpu.current_device`, + if :attr:`device` is ``None`` (default). + """ + result = [] + + stats = memory_stats_as_nested_dict(device=device) + _recurse_add_to_result(result, "", stats) + result.sort() + + return collections.OrderedDict(result) + + +def memory_allocated(device: Device = None) -> int: + r"""Return the current GPU memory occupied by tensors in bytes for a given device. + + Args: + device (torch.device or int or str, optional): selected device. Returns + statistic for the current device, given by :func:`~torch.xpu.current_device`, + if :attr:`device` is ``None`` (default). + + .. note:: + This is likely less than the amount shown in `xpu-smi` since some + unused memory can be held by the caching allocator and some context + needs to be created on GPU. + """ + return memory_stats(device=device).get("allocated_bytes.all.current", 0) + + +def max_memory_allocated(device: Device = None) -> int: + r"""Return the maximum GPU memory occupied by tensors in bytes for a given device. + + By default, this returns the peak allocated memory since the beginning of + this program. :func:`~torch.xpu.reset_peak_memory_stats` can be used to + reset the starting point in tracking this metric. For example, these two + functions can measure the peak allocated memory usage of each iteration in a + training loop. + + Args: + device (torch.device or int or str, optional): selected device. Returns + statistic for the current device, given by :func:`~torch.xpu.current_device`, + if :attr:`device` is ``None`` (default). + """ + return memory_stats(device=device).get("allocated_bytes.all.peak", 0) + + +def memory_reserved(device: Device = None) -> int: + r"""Return the current GPU memory managed by the caching allocator in bytes for a given device. + + Args: + device (torch.device or int or str, optional): selected device. Returns + statistic for the current device, given by :func:`~torch.xpu.current_device`, + if :attr:`device` is ``None`` (default). + """ + return memory_stats(device=device).get("reserved_bytes.all.current", 0) + + +def max_memory_reserved(device: Device = None) -> int: + r"""Return the maximum GPU memory managed by the caching allocator in bytes for a given device. + + By default, this returns the peak cached memory since the beginning of this + program. :func:`~torch.xpu.reset_peak_memory_stats` can be used to reset + the starting point in tracking this metric. For example, these two functions + can measure the peak cached memory amount of each iteration in a training + loop. + + Args: + device (torch.device or int or str, optional): selected device. Returns + statistic for the current device, given by :func:`~torch.xpu.current_device`, + if :attr:`device` is ``None`` (default). + """ + return memory_stats(device=device).get("reserved_bytes.all.peak", 0) + + +def mem_get_info(device: Device = None) -> tuple[int, int]: + r"""Return the global free and total GPU memory for a given device. + + Args: + device (torch.device or int or str, optional): selected device. Returns + statistic for the current device, given by :func:`~torch.xpu.current_device`, + if :attr:`device` is ``None`` (default). + + Returns: + tuple[int, int]: a tuple of two integers (free_memory, total_memory) in bytes. + The first value is the free memory on the device (available across all processes and applications), + The second value is the device's total hardware memory capacity. + """ + _lazy_init() + device = _get_device_index(device, optional=True) + return torch._C._xpu_getMemoryInfo(device) + + +def get_per_process_memory_fraction(device: Device = None) -> float: + r""" + Retrieve the memory fraction currently set for a process on a given XPU device. + This fraction represents the portion of the total device memory that + the caching allocator is allowed to use. The allowed memory is calculated as: + + .. math:: \text{allowed\_memory} = \text{total\_memory} \times \text{fraction} + + Args: + device (torch.device or int or str, optional): selected device. It uses the current device, + given by :func:`~torch.xpu.current_device`, if :attr:`device` is ``None`` (default). + + Returns: + float: The memory fraction in the range 0.0 to 1.0. + """ + _lazy_init() + device = _get_device_index(device, optional=True) + return torch._C._xpu_getMemoryFraction(device) + + +def set_per_process_memory_fraction(fraction: float, device: Device = None) -> None: + r""" + Set the memory fraction for a single process on XPU device. + This function limits the amount of memory that the caching allocator can allocate + on the specified XPU device. The allowed memory is computed as: + + .. math:: \text{allowed\_memory} = \text{total\_memory} \times \text{fraction} + + If the process attempts to allocate more than this allowed memory, + an out-of-memory error will be raised by the allocator. + + Arguments: + fraction (float): Range: 0~1. Allowed memory equals total_memory * fraction. + device (torch.device or int or str, optional): selected device. It uses the current device, + given by :func:`~torch.xpu.current_device`, if :attr:`device` is ``None`` (default). + + .. note:: In general, the total available free memory is less than the total capacity. + """ + _lazy_init() + device = _get_device_index(device, optional=True) + if not isinstance(fraction, float): + raise TypeError("Invalid type for fraction argument, must be `float`") + torch._C._xpu_setMemoryFraction(fraction, device) + + +def memory_snapshot( + mempool_id: tuple[int, int] | None = None, +) -> list[dict[str, Any]]: + r""" + Return a snapshot of the XPU memory allocator state across all devices. + Provides detailed information for each memory segment managed by the allocator + including its size, owning pool, associated stream, call stack traces, and other relevant attributes. + + Arguments: + mempool_id (tuple[int, int] or None, optional): The memory pool id. If None, the default memory pool is used. + + Returns: + list[dict[str, Any]]: List of memory segments and their attributes. + """ + if not is_initialized(): + return [] + return torch._C._xpu_memorySnapshot(mempool_id)["segments"] + + +def _snapshot(device: Device = None, augment_with_fx_traces: bool = False): + """ + Capture a snapshot of the XPU memory state at the time this function is called. + + The returned snapshot is a dictionary with the following structure. + + .. code-block:: python + + class Snapshot(TypedDict): + segments: List[Segment] + device_traces: List[List[TraceEntry]] + + + class Segment(TypedDict): + # A Segment represents a contiguous memory region returned by the SYCL runtime. + # + # All reserved memory is composed of these segments. Segments are + # cached and reused by the allocator. When allocations are smaller + # than the segment, the segment may be split into multiple Blocks. + # + # Calling :func:`~torch.xpu.memory.empty_cache` releases segments that are entirely inactive. + address: int + total_size: int # total size of segment + stream: int + segment_type: Literal["small", "large"] # 'large' (>1MB) + allocated_size: int # size of memory in use + active_size: int # size of memory in use or in active_awaiting_free state + blocks: List[Block] + + + class Block(TypedDict): + # A sub-region of a Segment, either currently allocated or cached for reuse. + size: int + requested_size: int # Original requested size (may be smaller than `size`) + address: int + state: Literal[ + "active_allocated", # used by a tensor + "active_awaiting_free", # waiting for another stream synchronization, then become free + "inactive", # free for reuse + ] + frames: List[Frame] # stack trace from where the allocation occurred + + + class Frame(TypedDict): + filename: str + line: int + name: str + # Optional fields when `augment_with_fx_traces=True` and the frame + # corresponds to FX-generated code. + fx_node_op: str # FX node operation type (e.g., 'call_function', 'output') + fx_node_name: str # FX node name (e.g., 'linear', 'relu_1') + fx_original_trace: str # Original model source code stack trace + + + class TraceEntry(TypedDict): + # Trace entries are recorded only when :func:`~torch.xpu.memory._record_memory_history` is enabled. + action: Literal[ + "alloc" # memory allocated + "free_requested", # received a call to free memory + "free_completed", # memory reclaimed and reusable + "segment_alloc", # ask SYCL runtime for more memory + "segment_free", # called SYCL runtime to return memory to XPU + "segment_map", # ask SYCL runtime to map memory + "segment_unmap", # called SYCL runtime to unmap memory + "snapshot", # snapshot taken + "oom", # threw an OOM exception + ] + addr: int # not present for OOM + frames: List[Frame] + size: int + stream: int + device_free: int # only present for OOM, the amount of free memory reported by the device + + Arguments: + device (torch.device or int or str, optional): selected device. It uses the current device, + given by :func:`~torch.xpu.current_device`, if :attr:`device` is ``None`` (default). + augment_with_fx_traces (bool, optional): If True, augment stack trace frames with FX debug information + that maps generated FX code back to original model source code. This adds the FX-related + fields (fx_node_op, fx_node_name, fx_original_trace) to Frame objects. Default is ``False``. + + Returns: + The Snapshot dictionary object + """ + s = torch._C._xpu_memorySnapshot(None) + if augment_with_fx_traces: + s = _augment_memory_snapshot_stack_traces(s) # type: ignore[assignment, arg-type] + return s + + +def _dump_snapshot( + filename: str = "dump_snapshot.pickle", augment_with_fx_traces: bool = False +) -> None: + """ + Save a pickled version of the `torch.memory._snapshot()` dictionary to a file. + + This file can be opened by the interactive snapshot viewer at pytorch.org/memory_viz + + Snapshot file sizes scale with `max_entries` and stack trace depth per entry, + with several KB per entry. These can easily be in the GB range for longer running + workflows with large `max_entries`. + + Arguments: + filename (str, optional): Name of the file to create. Defaults to "dump_snapshot.pickle". + augment_with_fx_traces (bool, optional): If True, augment the snapshot with FX debug information + before dumping. This maps generated FX code stack traces back to original model + source code. Defaults to ``False``. + """ + s = _snapshot(augment_with_fx_traces=augment_with_fx_traces) + + with open(filename, "wb") as f: + pickle.dump(s, f) + + +def _record_memory_history( + enabled: Literal["state", "all"] | None = "all", + context: Literal["state", "alloc", "all"] | None = "all", + stacks: Literal["python", "all"] = "all", + max_entries: int = sys.maxsize, + clear_history: bool = False, + skip_actions: list[str] | None = None, +) -> None: + """ + Enable recording of stack traces associated with memory allocations, so you can + tell what allocated any piece of memory in :func:`~torch.xpu.memory._snapshot()`. + + In addition to keeping stack traces with each current allocation and free, + this will also enable recording of a history of all alloc/free events. + + Use :func:`~torch.xpu.memory._snapshot()` to retrieve this information, + and the tools in `_memory_viz.py` to visualize snapshots. + + Buffer behavior + --------------- + + This will store up to `max_entries` instances of `TraceEntry` when enabled. + Python trace collection defaults to `sys.maxsize`, meaning long-running + or indefinitely running jobs should set a reasonable limit to avoid excessive + memory use. Expect each entry to be several KB. + + Longer running workflows or those with smaller `max_entries` values will only + store the last accumulated `max_entries` entries, meaning new entries overwrite + older entries, reference to ring buffer behavior. + + Latency impact + -------------- + + The Python trace collection is fast (2us per trace), so you may consider + enabling this on production jobs if you anticipate ever having to debug + memory issues. + + C++ trace collection is also fast (~50ns/frame), which for many typical programs + works out to ~2us per trace, but can vary depending on stack depth. + + Arguments: + enabled (Literal["state", "all"], optional): + `None`, disable recording memory history. + `"state"`, keep information for currently allocated memory. + `"all"`, additionally keep a history of all alloc/free calls. + Defaults to "all". + context (Literal["state", "alloc", "all"], optional): + `None`, Do not record any tracebacks. + `"state"`, Record tracebacks for currently allocated memory. + `"alloc"`, additionally keep tracebacks for alloc calls. + `"all"`, additionally keep tracebacks for free calls. + Defaults to "all". + stacks (Literal["python", "all"], optional): + `"python"`, include Python, TorchScript, and inductor frames in tracebacks. + `"all"`, additionally include C++ frames. + Defaults to "all". + max_entries (int, optional): Keep a maximum of `max_entries` + alloc/free events in the recorded history recorded. + clear_history (bool, optional): Clear history when enabling, defaults to ``False``. + skip_actions (list[str], optional): List of action types to skip when recording + memory history. This can be used to reduce memory overhead by excluding + certain types of events from being recorded. Valid action types are: + + - `"alloc"`: Memory allocation events + - `"free_requested"`: Free requests (memory marked for freeing) + - `"free_completed"`: Completed free operations (memory actually freed) + - `"segment_alloc"`: Segment allocation from SYCL runtime + - `"segment_free"`: Segment freed back to XPU via SYCL runtime + - `"segment_map"`: Segment map events + - `"segment_unmap"`: Segment unmap events + - `"snapshot"`: Memory snapshot generation events + - `"oom"`: Out-of-memory exceptions + + For example, to skip recording free_requested events: + `skip_actions=["free_requested"]` + + Defaults to ``None`` (record all actions). + """ + torch._C._xpu_recordMemoryHistory( + enabled, + context, + stacks, + max_entries, + clear_history, + skip_actions if skip_actions is not None else [], + ) + + +class _XPUAllocator: + r"""Wrapper over internal XPU memory allocators.""" + + def __init__(self, allocator: torch._C._xpu_XPUAllocator): + self._allocator = allocator + + def allocator(self): + return self._allocator + + +class XPUPluggableAllocator(_XPUAllocator): + r""" + XPU memory allocator loaded dynamically from a shared library. + + This lets users provide custom allocation and free functions implemented + in a separate shared library. The allocator is registered and could become + available for use via :func:`~torch.xpu.memory.change_current_allocator`. + + Arguments: + path_to_lib_file (str): + Filesystem path to the shared library file containing the allocation + and free functions. + alloc_fn_name (str): + Name of the allocation function exported from the shared library. + The function must have the signature: + + ``void* alloc_fn(size_t size, int device, sycl::queue* queue);`` + + free_fn_name (str): + Name of the free function exported from the shared library. + The function must have the signature: + + ``void free_fn(void* ptr, size_t size, int device, sycl::queue* queue);`` + """ + + def __init__(self, path_to_lib_file: str, alloc_fn_name: str, free_fn_name: str): + allocator_lib = ctypes.CDLL(path_to_lib_file) + + alloc_fn_ptr = getattr(allocator_lib, alloc_fn_name) + free_fn_ptr = getattr(allocator_lib, free_fn_name) + + alloc_fn_addr = ctypes.cast(alloc_fn_ptr, ctypes.c_void_p).value + free_fn_addr = ctypes.cast(free_fn_ptr, ctypes.c_void_p).value + + if alloc_fn_addr is None or free_fn_addr is None: + raise RuntimeError( + "Failed to load allocator symbols from the shared library." + ) + + self._allocator = torch._C._xpu_customAllocator(alloc_fn_addr, free_fn_addr) + + +def change_current_allocator(allocator: _XPUAllocator) -> None: + r"""Change the currently used memory allocator to be the one provided. + + .. note:: + If the current allocator has already been used/initialized, this function will error. + + Arguments: + allocator (torch.xpu.memory._XPUAllocator): allocator to be set as the active one. + """ + torch._C._xpu_changeCurrentAllocator(allocator.allocator()) + + +def _get_current_allocator() -> _XPUAllocator: + r"""Return the allocator being currently used. + + Returns: + _XPUAllocator: the allocator being currently used. + """ + return _XPUAllocator(torch._C._xpu_getAllocator()) + + +class MemPool(torch._C._XPUMemPool): + r"""MemPool represents a pool of memory in a caching allocator. Currently, + it's just the ID of the pool object maintained in the XPUCachingAllocator. + + Args: + allocator(torch._C._xpu_XPUAllocator, optional): a + torch._C._xpu_XPUAllocator object that can be used to + define how memory gets allocated in the pool. If :attr:`allocator` + is ``None`` (default), memory allocation follows the default/ + current configuration of the XPUCachingAllocator. + use_on_oom(bool): a bool that indicates if this pool can be used + as a last resort if a memory allocation outside of the pool fails due + to Out Of Memory. This is ``False`` by default. + """ + + def __init__( + self, + allocator: torch._C._xpu_XPUAllocator | None = None, + use_on_oom: bool = False, + ): + super().__init__(allocator, True, use_on_oom) + + @property + def id(self) -> tuple[int, int]: + r"""Returns the ID of this pool as a tuple of two ints.""" + return super().id + + @property + def allocator(self) -> torch._C._xpu_XPUAllocator | None: + r"""Returns the allocator this MemPool routes allocations to.""" + return super().allocator + + def use_count(self) -> int: + r"""Returns the reference count of this pool.""" + return super().use_count() + + def snapshot(self): + r"""Return a snapshot of the XPU memory allocator pool state across all + devices. + + Interpreting the output of this function requires familiarity with the + memory allocator internals. + """ + snapshot = torch.xpu.memory_snapshot(self.id) + return snapshot + + +@contextlib.contextmanager +def use_mem_pool(pool: MemPool, device: "Device" = None): + r"""A context manager that routes allocations to a given pool. + + Args: + pool(torch.xpu.MemPool): a :class:`MemPool` object to be made active so that + allocations route to this pool. + device (torch.device or int, optional): selected device. Uses :class:`MemPool on + the current device, given by :func:`~torch.xpu.current_device`, + if :attr:`device` is ``None`` (default). + + .. note:: + This context manager makes only current thread's allocations route to + the given pool. If a new thread is spawned inside the context manager + (e.g. by calling backward) the allocations in that thread will not + route to the given pool. + """ + device_index = ( + torch.xpu.current_device() if device is None else _get_device_index(device) + ) + torch._C._xpu_beginAllocateCurrentThreadToPool(device_index, pool.id) + try: + yield + finally: + torch._C._xpu_endAllocateToPool(device_index, pool.id) + torch._C._xpu_releasePool(device_index, pool.id) + + +def list_gpu_processes(device: "Device" = None) -> str: + r"""Return a printout of running processes and their GPU memory usage on a given device. + + Args: + device (torch.device, str or int, optional): selected device. Uses the + current device, given by :func:`~torch.xpu.current_device`, + if ``None`` (default). + + Returns: + str: A human-readable summary of each running process and the given GPU memory usage in MB. + + .. note:: Process status is reported at the physical device level and reflects all processes + associated with the device. + """ + from ctypes import byref, c_uint32 + + from . import ( + _cached_zes_device_infos, + _get_pyzes_version, + _import_pyzes, + _zes_check, + _zes_ensure_device_infos, + ) + + pyzes = _import_pyzes() + version = _get_pyzes_version() + if version < (0, 1, 2): + raise RuntimeError( + f"list_gpu_processes requires pyzes version >= 0.1.2, but found {'.'.join(map(str, version))}" + ) + device = _get_device_index(device, optional=True) + _zes_ensure_device_infos(device) + + info = _cached_zes_device_infos[device] + device_handle = info.device_handle + proc_count = c_uint32(0) + _zes_check( + pyzes.zesDeviceProcessesGetState(device_handle, byref(proc_count), None), + "Can't get Level Zero Sysman host processes count.", + ) + process_states = (pyzes.zes_process_state_t * proc_count.value)() + _zes_check( + pyzes.zesDeviceProcessesGetState( + device_handle, byref(proc_count), process_states + ), + "Can't get Level Zero Sysman host processes state.", + ) + + lines = [f"GPU:{device}"] + if proc_count.value == 0: + lines.append(" no processes are running") + for state in process_states: + mem_mb = state.memSize / (1024 * 1024) + lines.append( + f" process {state.processId:>10d} uses {mem_mb:>12.3f} MB GPU memory" + ) + return "\n".join(lines) + + +__all__ = [ + "MemPool", + "XPUPluggableAllocator", + "change_current_allocator", + "empty_cache", + "get_per_process_memory_fraction", + "list_gpu_processes", + "max_memory_allocated", + "max_memory_reserved", + "mem_get_info", + "memory_allocated", + "memory_reserved", + "memory_snapshot", + "memory_stats", + "memory_stats_as_nested_dict", + "reset_accumulated_memory_stats", + "reset_peak_memory_stats", + "set_per_process_memory_fraction", + "use_mem_pool", +] diff --git a/.venv/lib/python3.12/site-packages/torch/xpu/random.py b/.venv/lib/python3.12/site-packages/torch/xpu/random.py new file mode 100644 index 0000000000000000000000000000000000000000..f58e49e29d1a93954353f6f24cb0696a37e17d23 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/xpu/random.py @@ -0,0 +1,176 @@ +# mypy: allow-untyped-defs +from collections.abc import Iterable + +import torch +from torch import Tensor + +from . import _lazy_call, _lazy_init, current_device, device_count, is_initialized + + +def get_rng_state(device: int | str | torch.device = "xpu") -> Tensor: + r"""Return the random number generator state of the specified GPU as a ByteTensor. + + Args: + device (torch.device or int, optional): The device to return the RNG state of. + Default: ``'xpu'`` (i.e., ``torch.device('xpu')``, the current XPU device). + + .. warning:: + This function eagerly initializes XPU. + """ + _lazy_init() + if isinstance(device, str): + device = torch.device(device) + elif isinstance(device, int): + device = torch.device("xpu", device) + idx = device.index + if idx is None: + idx = current_device() + default_generator = torch.xpu.default_generators[idx] + return default_generator.get_state() + + +def get_rng_state_all() -> list[Tensor]: + r"""Return a list of ByteTensor representing the random number states of all devices.""" + results = [get_rng_state(i) for i in range(device_count())] + return results + + +def set_rng_state(new_state: Tensor, device: int | str | torch.device = "xpu") -> None: + r"""Set the random number generator state of the specified GPU. + + Args: + new_state (torch.ByteTensor): The desired state + device (torch.device or int, optional): The device to set the RNG state. + Default: ``'xpu'`` (i.e., ``torch.device('xpu')``, the current XPU device). + """ + if not is_initialized(): + with torch._C._DisableFuncTorch(): + new_state = new_state.clone(memory_format=torch.contiguous_format) + + if isinstance(device, str): + device = torch.device(device) + elif isinstance(device, int): + device = torch.device("xpu", device) + + def cb() -> None: + idx = device.index + if idx is None: + idx = current_device() + default_generator = torch.xpu.default_generators[idx] + default_generator.set_state(new_state) + + _lazy_call(cb) + + +def set_rng_state_all(new_states: Iterable[Tensor]) -> None: + r"""Set the random number generator state of all devices. + + Args: + new_states (Iterable of torch.ByteTensor): The desired state for each device. + """ + for i, state in enumerate(new_states): + set_rng_state(state, i) + + +def manual_seed(seed: int) -> None: + r"""Set the seed for generating random numbers for the current GPU. + + It's safe to call this function if XPU is not available; in that case, it is silently ignored. + + Args: + seed (int): The desired seed. + + .. warning:: + If you are working with a multi-GPU model, this function is insufficient + to get determinism. To seed all GPUs, use :func:`manual_seed_all`. + """ + seed = int(seed) + + def cb() -> None: + idx = current_device() + default_generator = torch.xpu.default_generators[idx] + default_generator.manual_seed(seed) + + _lazy_call(cb, seed=True) + + +def manual_seed_all(seed: int) -> None: + r"""Set the seed for generating random numbers on all GPUs. + + It's safe to call this function if XPU is not available; in that case, it is silently ignored. + + Args: + seed (int): The desired seed. + """ + seed = int(seed) + + def cb() -> None: + for i in range(device_count()): + default_generator = torch.xpu.default_generators[i] + default_generator.manual_seed(seed) + + _lazy_call(cb, seed_all=True) + + +def seed() -> None: + r"""Set the seed for generating random numbers to a random number for the current GPU. + + It's safe to call this function if XPU is not available; in that case, it is silently ignored. + + .. warning:: + If you are working with a multi-GPU model, this function will only initialize + the seed on one GPU. To initialize all GPUs, use :func:`seed_all`. + """ + + def cb() -> None: + idx = current_device() + default_generator = torch.xpu.default_generators[idx] + default_generator.seed() + + _lazy_call(cb) + + +def seed_all() -> None: + r"""Set the seed for generating random numbers to a random number on all GPUs. + + It's safe to call this function if XPU is not available; in that case, it is silently ignored. + """ + + def cb() -> None: + random_seed = 0 + seeded = False + for i in range(device_count()): + default_generator = torch.xpu.default_generators[i] + if not seeded: + default_generator.seed() + random_seed = default_generator.initial_seed() + seeded = True + else: + default_generator.manual_seed(random_seed) + + _lazy_call(cb) + + +def initial_seed() -> int: + r"""Return the current random seed of the current GPU. + + .. warning:: + This function eagerly initializes XPU. + """ + _lazy_init() + idx = current_device() + default_generator = torch.xpu.default_generators[idx] + return default_generator.initial_seed() + + +__all__ = [ + "get_rng_state", + "get_rng_state_all", + "set_rng_state", + "set_rng_state_all", + "manual_seed", + "manual_seed_all", + "seed", + "seed_all", + "initial_seed", +] diff --git a/.venv/lib/python3.12/site-packages/torch/xpu/streams.py b/.venv/lib/python3.12/site-packages/torch/xpu/streams.py new file mode 100644 index 0000000000000000000000000000000000000000..3e5068ee3b44b4427c21c15ac82cbdbfcb456372 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torch/xpu/streams.py @@ -0,0 +1,181 @@ +# mypy: allow-untyped-defs +# pylint: disable=useless-parent-delegation +from __future__ import annotations + +import ctypes + +import torch +from torch._utils import _dummy_type + + +if not hasattr(torch._C, "_XpuStreamBase"): + # Define dummy base classes + torch._C.__dict__["_XpuStreamBase"] = _dummy_type("_XpuStreamBase") + torch._C.__dict__["_XpuEventBase"] = _dummy_type("_XpuEventBase") + + +class Stream(torch._C._XpuStreamBase): + r"""Wrapper around a XPU stream. + + A XPU stream is a linear sequence of execution that belongs to a specific + device, independent from other streams. It supports with statement as a + context manager to ensure the operators within the with block are running + on the corresponding stream. + + Args: + device(torch.device or int, optional): a device on which to allocate + the stream. If :attr:`device` is ``None`` (default) or a negative + integer, this will use the current device. + priority(int, optional): priority of the stream, which can be positive, 0, or negative. + A lower number indicates a higher priority. By default, the priority is set to 0. + If the value falls outside of the allowed priority range, it will automatically be + mapped to the nearest valid priority (lowest for large positive numbers or + highest for large negative numbers). + """ + + def __new__(cls, device=None, priority=0, **kwargs): + # setting device manager is expensive, so we avoid it unless necessary + if device is None or ("stream_id" in kwargs and "device_index" in kwargs): + return super().__new__(cls, priority=priority, **kwargs) + else: + with torch.xpu.device(device): + return super().__new__(cls, priority=priority, **kwargs) + + def wait_event(self, event: Event | torch.Event) -> None: + r"""Make all future work submitted to the stream wait for an event. + + Args: + event (Event, torch.Event): an event to wait for. + """ + event.wait(self) + + def wait_stream(self, stream: Stream | torch.Stream) -> None: + r"""Synchronize with another stream. + + All future work submitted to this stream will wait until all kernels + submitted to a given stream at the time of call complete. + + Args: + stream (Stream, torch.Stream): a stream to synchronize. + """ + self.wait_event(stream.record_event()) + + def record_event(self, event: Event | torch.Event | None = None): + r"""Record an event. + + Args: + event (Event, torch.Event, optional): event to record. If not given, a new one + will be allocated. + + Returns: + Recorded event. + """ + if event is None: + event = Event() + event.record(self) + return event + + def query(self) -> bool: + r"""Check if all the work submitted has been completed. + + Returns: + A boolean indicating if all kernels in this stream are completed. + """ + return super().query() + + def synchronize(self) -> None: + r"""Wait for all the kernels in this stream to complete.""" + super().synchronize() + + @property + def _as_parameter_(self): + return ctypes.c_void_p(self.sycl_queue) + + def __eq__(self, o): + if isinstance(o, Stream): + return super().__eq__(o) + return False + + def __hash__(self): + return hash((self.sycl_queue, self.device)) + + def __repr__(self) -> str: + return f"torch.xpu.Stream(device={self.device} sycl_queue={self.sycl_queue:#x})" + + +class Event(torch._C._XpuEventBase): + r"""Wrapper around a XPU event. + + XPU events are synchronization markers that can be used to monitor the + device's progress, and to synchronize XPU streams. + + The underlying XPU events are lazily initialized when the event is first + recorded. After creation, only streams on the same device may record the + event. However, streams on any device can wait on the event. + + Args: + enable_timing (bool, optional): indicates if the event should measure time + (default: ``False``) + """ + + def __new__(cls, enable_timing=False): + return super().__new__(cls, enable_timing=enable_timing) + + def record(self, stream: Stream | torch.Stream | None = None) -> None: + r"""Record the event in a given stream. + + Args: + stream (Stream, torch.Stream, optional): Uses ``torch.xpu.current_stream()`` if no stream is specified. + The stream's device must match the event's device. + """ + if stream is None: + stream = torch.xpu.current_stream() + super().record(stream) + + def wait(self, stream: Stream | torch.Stream | None = None) -> None: + r"""Make all future work submitted to the given stream wait for this event. + + Args: + stream (Stream, torch.Stream, optional): Uses ``torch.xpu.current_stream()`` if no stream is specified. + """ + if stream is None: + stream = torch.xpu.current_stream() + super().wait(stream) + + def query(self) -> bool: + r"""Check if all work currently captured by event has completed. + + Returns: + A boolean indicating if all work currently captured by event has + completed. + """ + return super().query() + + def elapsed_time(self, end_event: Event): + r"""Return the time elapsed. + + Time reported in milliseconds after the event was recorded and + before the end_event was recorded. + + Args: + end_event (Event): the end event. + """ + return super().elapsed_time(end_event) + + def synchronize(self) -> None: + r"""Wait for the event to complete. + + Waits until the completion of all work currently captured in this event. + This prevents the CPU thread from proceeding until the event completes. + """ + super().synchronize() + + @property + def _as_parameter_(self): + return ctypes.c_void_p(self.sycl_event) + + def __repr__(self) -> str: + if self.sycl_event: + return f"torch.xpu.Event(sycl_event={self.sycl_event:#x})" + else: + return "torch.xpu.Event(uninitialized)" diff --git a/.venv/lib/python3.12/site-packages/torchgen/__init__.py b/.venv/lib/python3.12/site-packages/torchgen/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2d5dbf0667a022caa07ec30bb10db5b4f83159dd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/__init__.py @@ -0,0 +1,10 @@ +"""torchgen + +This module contains codegeneration utilities for PyTorch. It is used to +build PyTorch from source, but may also be used for out-of-tree projects +that extend PyTorch. + +Note well that we provide no BC guarantees for torchgen. If you're interested +in using torchgen and want the PyTorch team to be aware, please reach out +on GitHub. +""" diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b78a8a140dee8e49dc2f4b4a3a25ff6a227d3829 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/code_template.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/code_template.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c12f64d02d4a1aa85b14ec8e3ae65fb2c2cd7ff Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/code_template.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..233994b9c0a2eb619241517921ac9937b63680de Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d42bce41e417cc67f2419a6ebc444da651f435ec --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2af721324de851ee117bc4b7e1069b72005764efb33ea9f83cc0eeea313725df +size 114188 diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_aoti_c_shim.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_aoti_c_shim.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4434e9d5a60b48af35647a0543e5de2350a4bcf8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_aoti_c_shim.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_backend_stubs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_backend_stubs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5798c7784b734e533ca142aa101f530fbfe20ba3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_backend_stubs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_functionalization_type.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_functionalization_type.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d9370384d882a5777251a81eeab3e56cd29a049 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_functionalization_type.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_lazy_tensor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_lazy_tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e2f7338f33b799ff42012ce5474c09a516856f7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_lazy_tensor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_schema_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_schema_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1495f2f2544efe9c93868a5e50a7a448dbeeb55 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_schema_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_vmap_plumbing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_vmap_plumbing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a0298d1ae65cc89e82d571b0bf65cad1841f078 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen_vmap_plumbing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/local.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/local.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..687646db2921f52b92861f9063b382ba026e96d6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/local.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/model.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6663e028be7c5afa67db5af3a369cafe322dc8b3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/model.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2677fdfa0083349372fa21185c9d58b8f5fdd5d3d6a07adfcc7eeb6d25b15a6f +size 118346 diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/native_function_generation.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/native_function_generation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..191c4fff0afb351622b7e348679ff7f05a674794 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/native_function_generation.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3c97536601f2d028678e6d0e2394e7bf9242688 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/__pycache__/yaml_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/yaml_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85bbf8a21bc26f0119945f6c26e1cd7ae8cde86f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/__pycache__/yaml_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/aoti/__init__.py b/.venv/lib/python3.12/site-packages/torchgen/aoti/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torchgen/aoti/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/aoti/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7281857db6b2b7eaa2b46a45bff9c244484e10d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/aoti/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/aoti/__pycache__/fallback_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/aoti/__pycache__/fallback_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb18602e230b17cfabcf59f50e54b4c96a89b74f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/aoti/__pycache__/fallback_ops.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/aoti/fallback_ops.py b/.venv/lib/python3.12/site-packages/torchgen/aoti/fallback_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..acc9aec014c0eee6c93a5d30746f92dd9f2e6bc9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/aoti/fallback_ops.py @@ -0,0 +1,232 @@ +# Be extra careful when you edit this file, because it affects AOTInductor ABI compatibility. See +# https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 +# for details. +# +# The inductor_fallback_ops list is based on the fallback ops from torch/_inductor/lowering.py. +# +# Generally speaking, it is ok to add a new op to the list, but you need to run +# `python torchgen/gen.py --update-aoti-c-shim` in order to regenerate C shim header files. +# But it is NOT ok to remove an existing fallback op from the list, since that will break +# some existing AOTInductor-compiled models. +# +# A fallback op version defaults to 1. If you want to extend an existing fallback op by adding +# a new argument with a default value, while it is fine in the Python world, it will be BC-breaking +# when generating C shim. Thus you need to bump up the version number of that fallback op by +# updating the entry in the inductor_fallback_ops list, adding a new version number with a list +# of new arguments, and then run `python torchgen/gen.py --update-aoti-c-shim` to regenerate. +# +# A "since" key (top-level for v1, or nested inside a vN entry of the form +# {"new_args": [...], "since": "TORCH_VERSION_X_Y_Z"}) +# records the earliest TORCH_VERSION at which that op variant became available. When present, +# codegen wraps the generated declaration in a +# #if TORCH_FEATURE_VERSION >= +# ... +# #endif +# guard. When absent, the declaration is emitted ungated, which would signify that the op was +# available since torch 2.9. ALL NEWLY ADDED OPS MUST INCLUDE A "since" KEY WITH THE VALUE SET +# TO THE CURRENT TORCH VERSION (the version when the op was added). + +inductor_fallback_ops: dict[str, dict[str, str | dict[str, list[str] | str]]] = { + "aten._adaptive_avg_pool2d_backward.default": {}, + "aten._adaptive_avg_pool2d.default": {}, + "aten._adaptive_avg_pool3d_backward.default": {}, + "aten._adaptive_avg_pool3d.default": {}, + "aten._addmm_activation.default": {}, + "aten._cdist_backward.default": {}, + "aten._cdist_forward.default": {}, + "aten._cudnn_rnn.default": {}, + "aten._dyn_quant_matmul_4bit.default": {}, + "aten._dyn_quant_pack_4bit_weight.default": {}, + "aten._efficient_attention_backward.default": {}, + "aten._efficient_attention_forward.default": {}, + "aten._efficientzerotensor.default": {}, + "aten._embedding_bag_dense_backward.default": {}, + "aten._embedding_bag_forward_only.default": {}, + "aten._embedding_bag_per_sample_weights_backward.default": {}, + "aten._embedding_bag.default": {}, + "aten._fft_c2c.default": {}, + "aten._fft_r2c.default": {}, + "aten._flash_attention_backward.default": {}, + "aten._flash_attention_forward.default": { + "v2": { + "new_args": ["block_table", "num_splits"], + "since": "TORCH_VERSION_2_12_0", + } + }, + "aten._flash_attention_forward_no_dropout_inplace.default": { + "since": "TORCH_VERSION_2_12_0", + "v2": {"new_args": ["num_splits"], "since": "TORCH_VERSION_2_12_0"}, + }, + "aten._flash_attention_forward.quantized": {"since": "TORCH_VERSION_2_11_0"}, + "aten._fused_moving_avg_obs_fq_helper_functional.default": {}, + "aten._fused_moving_avg_obs_fq_helper.default": {}, + "aten._fused_rms_norm.default": {}, + "aten._grouped_mm.default": {"since": "TORCH_VERSION_2_12_0"}, + "aten._histogramdd_from_bin_cts.default": {}, + "aten._int_mm.out": {}, + "aten._pdist_backward.default": {}, + "aten._pdist_forward.default": {}, + "aten._scaled_dot_product_attention_math_for_mps.default": { + "v2": {"new_args": ["enable_gqa"], "since": "TORCH_VERSION_2_13_0"} + }, + "aten._scaled_dot_product_cudnn_attention_backward.default": {}, + "aten._scaled_dot_product_cudnn_attention.default": {}, + "aten._scaled_dot_product_efficient_attention_backward.default": {}, + "aten._scaled_dot_product_efficient_attention.default": {}, + "aten._scaled_dot_product_flash_attention_backward.default": {}, + "aten._scaled_dot_product_flash_attention_for_cpu_backward.default": {}, + "aten._scaled_dot_product_flash_attention_for_cpu.default": {}, + "aten._scaled_dot_product_flash_attention.default": {}, + "aten._scaled_dot_product_flash_attention.quantized": { + "since": "TORCH_VERSION_2_11_0" + }, + "aten._scaled_dot_product_fused_attention_overrideable_backward.default": {}, + "aten._scaled_dot_product_fused_attention_overrideable.default": {}, + "aten._scaled_mm.default": {}, + "aten._scaled_grouped_mm.default": {"since": "TORCH_VERSION_2_10_0"}, + "aten._scaled_mm.out": {}, + "aten._segment_reduce_backward.default": {}, + "aten._thnn_fused_lstm_cell.default": {}, + "aten._to_sparse.default": {}, + "aten._trilinear.default": {}, + "aten._weight_int4pack_mm.default": {}, + "aten._weight_int8pack_mm.default": {}, + "aten.abs.default": {}, + "aten.adaptive_max_pool2d_backward.default": {}, + "aten.adaptive_max_pool2d.default": {}, + "aten.adaptive_max_pool3d_backward.default": {}, + "aten.adaptive_max_pool3d.default": {}, + "aten.add.Scalar": {}, + "aten.add.Tensor": {}, + "aten.addbmm.default": {}, + "aten.addmm.out": {}, + "aten.addmv.default": {}, + "aten.angle.default": {}, + "aten.avg_pool2d_backward.default": {}, + "aten.avg_pool2d.default": {}, + "aten.avg_pool3d_backward.default": {}, + "aten.avg_pool3d.default": {}, + "aten.baddbmm.out": {}, + "aten.bernoulli_.float": {}, + "aten.bernoulli_.Tensor": {}, + "aten.bmm.out": {}, + "aten.bucketize.Tensor": {}, + "aten.cat.default": {}, + "aten.cholesky_inverse.default": {}, + "aten.cholesky_solve.default": {}, + "aten.convolution_backward.default": {}, + "aten.convolution.default": {}, + "aten.cummax.default": {}, + "aten.cummin.default": {}, + "aten.cumprod.default": {}, + "aten.cumsum.default": {}, + "aten.exponential.default": {}, + "aten.fill_.Scalar": {}, + "aten.fractional_max_pool2d_backward.default": {}, + "aten.fractional_max_pool2d.default": {}, + "aten.fractional_max_pool3d_backward.default": {}, + "aten.fractional_max_pool3d.default": {}, + "aten.gcd.default": {}, + "aten.geqrf.default": {}, + "aten.grid_sampler_2d_backward.default": {}, + "aten.grid_sampler_3d.default": {"since": "TORCH_VERSION_2_13_0"}, + "aten.grid_sampler_3d_backward.default": {"since": "TORCH_VERSION_2_13_0"}, + "aten.hann_window.default": {}, + "aten.histc.default": {}, + "aten.histogram.bin_ct": {}, + "aten.index_put.default": {}, + "aten.index_reduce.default": {}, + "aten.index.Tensor": {}, + "aten.kthvalue.default": {}, + "aten.logcumsumexp.default": {}, + "aten.lu_unpack.default": {}, + "aten.masked_scatter_backward.default": {}, + "aten.masked_scatter.default": {}, + "aten.masked_select.default": {}, + "aten.max_pool2d_with_indices_backward.default": {}, + "aten.max_pool2d_with_indices.default": {}, + "aten.max_pool3d_with_indices_backward.default": {}, + "aten.max_pool3d_with_indices.default": {}, + "aten.max_unpool2d.default": {}, + "aten.max_unpool3d.default": {}, + "aten.median.default": {}, + "aten.mm.out": {}, + "aten.mm.dtype_out": {"since": "TORCH_VERSION_2_11_0"}, + "aten.mode.default": {}, + "aten.mul.Scalar": {}, + "aten.mul.Tensor": {}, + "aten.nanmedian.default": {}, + "aten.narrow.default": {}, + "aten.native_dropout.default": {}, + "aten.nonzero.default": {}, + "aten.nonzero_static.default": {"since": "TORCH_VERSION_2_11_0"}, + "aten.normal_functional.default": {}, + "aten.ormqr.default": {}, + "aten.pad.default": {}, + "aten.permute.default": {}, + "aten.polar.default": {}, + "aten.pow.Scalar": {}, + "aten.pow.Tensor_Scalar": {}, + "aten.pow.Tensor_Tensor": {}, + "aten.rand.default": {}, + "aten.rand.generator": {}, + "aten.randint.default": {}, + "aten.randint.generator": {}, + "aten.randint.low_out": {}, + "aten.randint.low": {}, + "aten.randn.default": {}, + "aten.randn.generator": {}, + "aten.randperm.default": {}, + "aten.rand_like.default": {"since": "TORCH_VERSION_2_12_0"}, + "aten.rand_like.generator": {"since": "TORCH_VERSION_2_12_0"}, + "aten.randint_like.default": {"since": "TORCH_VERSION_2_12_0"}, + "aten.randint_like.low_dtype": {"since": "TORCH_VERSION_2_12_0"}, + "aten.randn_like.default": {"since": "TORCH_VERSION_2_12_0"}, + "aten.randn_like.generator": {"since": "TORCH_VERSION_2_12_0"}, + "aten.repeat_interleave.Tensor": {}, + "aten.replication_pad1d_backward.default": {}, + "aten.replication_pad2d_backward.default": {}, + "aten.reshape.default": {}, + "aten.resize_.default": {}, + "aten.resize_as_.default": {}, + "aten.scatter_reduce.two_out": {}, + "aten.scatter.src_out": {}, + "aten.scatter.value_out": {}, + "aten.searchsorted.Scalar": {}, + "aten.searchsorted.Tensor": {}, + "aten.segment_reduce.default": {}, + "aten.set_.source_Tensor": {}, + "aten.slice.Tensor": {}, + "aten.soft_margin_loss_backward.default": {}, + "aten.sort.default": {}, + "aten.sort.stable": {}, + "aten.squeeze.dim": {}, + "aten.to_sparse.default": {}, + "aten.topk.default": {}, + "aten.triangular_solve.default": {}, + "aten.uniform.default": {}, + "aten.upsample_bicubic2d_backward.default": {}, + "aten.upsample_linear1d_backward.default": {}, + "aten.upsample_trilinear3d_backward.default": {}, + "aten.view_as_complex.default": {}, + "aten.view_as_real.default": {}, + "aten.view.dtype": {}, + "aten._weight_int4pack_mm_with_scales_and_zeros.default": {}, +} + +# `python torchgen/gen.py --update-aoti-c-shim` will automatically generate +# c_shim_aten.{h/cpp} based on the list below. +# Operators in this list are intended to be used in torch/csrc/stable/ops.h +# Unlike other c_shims, operators in this file do not bypass the dispatcher. +# The same BC rules apply as inductor_fallback_ops, read about the "since" +# key above. +aten_shimified_ops: dict[str, dict[str, str | dict[str, list[str] | str]]] = { + "aten.fill_.Scalar": {}, + "aten.pad.default": {}, + "aten.narrow.default": {}, + "aten.amax.default": {}, + "aten.new_empty.default": {}, + "aten.new_zeros.default": {}, + "aten.full.default": {"since": "TORCH_VERSION_2_10_0"}, + "aten.subtract.Tensor": {"since": "TORCH_VERSION_2_10_0"}, +} diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/__init__.py b/.venv/lib/python3.12/site-packages/torchgen/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8ca2b0d8ceffc601aec6c4f6a0fe1bcc8c0ba1c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/autograd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/autograd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eee4545920fed954e200aea7b379563544359ba1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/autograd.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/cpp.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/cpp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a3cf183ccf931a314e0127e9b272f227921cad8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/cpp.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/dispatcher.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/dispatcher.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1047148f2c0fbdc19398dc9b3a2c0df8cd8db9f3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/dispatcher.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/functionalization.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/functionalization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c1ee1f3a22b1cdffffb2792cec23092443190e9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/functionalization.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/lazy.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/lazy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95466837f9d70c604d5a644264a4bd88e737cd15 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/lazy.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/meta.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/meta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..918fba5d90625ce63565f2623c88305022a37810 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/meta.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/native.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/native.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84f25fa7b7eddff841240ce2bca8d2e985e72c2e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/native.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/python.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/python.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..413e3102e0233d5fd8f757db18de9c89b144f276 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/python.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/structured.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/structured.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afa56afa7476f459fc73cdfb361a98f811f76408 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/structured.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/translate.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/translate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e6bb07a953deabeb78cc5044930f675e5927149 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/translate.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/ufunc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/ufunc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7b3e334e40ac305caab46f0761ac125d708929a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/ufunc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/unboxing.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/unboxing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..799a1d2f09f151a5f068c917661267f90c62ca06 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/__pycache__/unboxing.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/autograd.py b/.venv/lib/python3.12/site-packages/torchgen/api/autograd.py new file mode 100644 index 0000000000000000000000000000000000000000..477be3c528433ecd2d4b065ab5844b77790a5322 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/autograd.py @@ -0,0 +1,892 @@ +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import cast, TYPE_CHECKING + +from torchgen import local +from torchgen.api import cpp +from torchgen.api.types import BaseCType, Binding, NamedCType, tensorListT +from torchgen.model import ( + BaseTy, + BaseType, + FunctionSchema, + ListType, + NativeFunction, + NativeFunctionsViewGroup, + SchemaKind, + Type, +) +from torchgen.utils import IDENT_REGEX + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +# Represents a saved attribute involved in backward calculation. +# Note that it can be a derived property of an input argument, e.g.: +# we could save `other.scalar_type()` instead of the entire `other` tensor. +@dataclass(frozen=True) +class SavedAttribute: + # The NamedCType holds the updated name and cpp type of the attribute + # for the name, Suffix is appended if it's derived property, e.g.: `other_scalar_type` + nctype: NamedCType + + # The expression to read the derived property at save time, e.g.: + # `other.scalar_type()`. + expr: str + + +# Represents a backward formula that calculates derivatives for one +# or more tensors. +@dataclass(frozen=True) +class Derivative: + # The formula string (legit C++ expression). + # Note that expressions against input arguments have been replaced with the + # corresponding saved attributes. + # E.g.: + # raw formula: `mul_tensor_backward(grad, self, other.scalar_type())` + # here: `mul_tensor_backward(grad, self, other_scalar_type)` + formula: str + + # The formula string before input argument replacement + original_formula: str + + # Names of the arguments for which this formula calculates derivatives. + var_names: tuple[str, ...] + + # Saved inputs that are referenced by the formula. + saved_inputs: tuple[SavedAttribute, ...] + + # Saved outputs that are referenced by the formula. + saved_outputs: tuple[SavedAttribute, ...] + + # Gradients that are referenced by name in the formula. + named_gradients: set[str] + + +# Represents a forward formula that calculates forward derivatives +# for one tensor. +@dataclass(frozen=True) +class ForwardDerivative: + # The formula string (legit C++ expression). + # Note that special keywords such as "linear" or "element_wise" have been + # replaced by the automatically generated formula. + formula: str + + # Name of the output arguments for which this formula calculates forward + # derivatives + var_names: tuple[str, ...] + + # Type of the output arguments for which this formula calculates forward + # derivatives + var_types: tuple[Type, ...] + + # Inputs for which the forward derivatives are required for this formula + required_inputs_fw_grad: tuple[str, ...] | None + + # Inputs for which the primal is required for this formula + required_inputs_primal: tuple[str, ...] | None + + # Flag to specify if this formula requires the original value of self + # This is only used by inplace operations + required_original_self_value: bool + + # If this formula is specified in derivatives.yaml or if we are reusing the + # out of place formula for inplace + is_reusing_outplace_formula: bool + + +# Represents differentiability info for a NativeFunction. +@dataclass(frozen=True) +class DifferentiabilityInfo: + # The base name read from derivatives.yaml. + name: str + + # The matching native function. + # + # There can be multiple NativeFunction having the same base name: + # - different overloads with different types of input arguments; + # - in-place/out/functional variants of the same function; + # + # We first use the schema string (under the 'name' key) in derivatives.yaml + # to find the NativeFunction having the same schema string. + # Then we find the in-place/out/functional variants of the matching function. + # Among these variants, we choose the one having the same name as the + # derivatives.yaml entry. If there is no exact match, then we choose the + # in-place variant. + # TODO: maybe the logic to search for all variants is no longer necessary? + func: NativeFunction + + # The name of the generated autograd function. + # It's set only if we will calculate a derivative, i.e. + # 'args_with_derivatives' is not empty. + op: str | None + + # The derivatives formulae for this function. + # Note that the length of this sequence is the number of differentiable inputs + derivatives: Sequence[Derivative] + + # The forward derivatives formulae for this function. + # Note that the length of this sequence is the number of differentiable outputs + forward_derivatives: Sequence[ForwardDerivative] + + # The union of 'saved_inputs' of all 'derivatives'. + all_saved_inputs: Sequence[SavedAttribute] + + # The union of 'saved_outputs' of all 'derivatives'. + all_saved_outputs: Sequence[SavedAttribute] + + # All named gradients that are available for use, in the same + # order as in the grads vector. + available_named_gradients: Sequence[str] + + # The named gradients that are used in any of the derivatives. + # Invariant: all(name in available_named_gradients for name in used_named_gradients) + used_named_gradients: set[str] + + # The function's input arguments for which it calculates derivatives. + # It's the union of 'var_names' of all 'derivatives', sorted by the + # argument order in the function schema. + args_with_derivatives: Sequence[Binding] + + # Names of arguments whose derivative formula is 'non_differentiable'. + non_differentiable_arg_names: Sequence[str] + + # Raw data read from derivatives.yaml. + output_differentiability: list[bool] | None + + # output_differentiability in derivatives.yaml can be a list of + # conditions that express if the output is differentiable. In this case, + # the number of conditions must match the number of outputs + # (NB: we only support one condition right now). + # output_differentiability gets populated with True for each condition, + # while output_differentiability_conditions gets populated with the conditions + output_differentiability_conditions: list[str] | None + + @property + def has_derivatives(self) -> bool: + return len(self.args_with_derivatives) > 0 + + # Generates a new DifferentiabilityInfo using the exact same set of derivative information, + # but with a new operator name. + # This is used when generating "copy" variants of view ops, + # which are able to use the exact same derivative formula as the original view op + # See Note [Codegen'd {view}_copy Operators] + def create_view_copy_from_view_derivative( + self, g: NativeFunctionsViewGroup + ) -> DifferentiabilityInfo | None: + if g.view_copy is None: + return None + f = g.view_copy + + name_split_by_period = self.name.split(".", maxsplit=2) + # Append a "_copy" to the base name of the operator (but keep the overload name the same) + view_copy_name = f"{name_split_by_period[0]}_copy." + ".".join( + name_split_by_period[1:] + ) + view_copy_op_name = None if self.op is None else f"{self.op}_copy" + + return DifferentiabilityInfo( + # Use the "_copy" version of name/func/op + name=view_copy_name, + func=f, + op=view_copy_op_name, + # But keep all derivative info the same + derivatives=self.derivatives, + forward_derivatives=self.forward_derivatives, + all_saved_inputs=self.all_saved_inputs, + all_saved_outputs=self.all_saved_outputs, + available_named_gradients=self.available_named_gradients, + used_named_gradients=self.used_named_gradients, + args_with_derivatives=self.args_with_derivatives, + non_differentiable_arg_names=self.non_differentiable_arg_names, + output_differentiability=self.output_differentiability, + output_differentiability_conditions=self.output_differentiability_conditions, + ) + + +def uses_ident(info: DifferentiabilityInfo | None, ident: str) -> bool: + if info is None: + return False + for derivative in info.derivatives: + formula = derivative.formula + if re.search(IDENT_REGEX.format(ident), formula): + return True + return False + + +def uses_retain_variables(info: DifferentiabilityInfo | None) -> bool: + return uses_ident(info, "retain_variables") + + +def uses_single_grad(info: DifferentiabilityInfo | None) -> bool: + return uses_ident(info, "grad") + + +# Represents a differentiable `Argument`. +# How is it different from the `Argument` type? +# - It's processed Arguments which are differentiable and only used in the +# context of the autograd codegen; +# - It can represent SelfArgument or regular Argument but not TensorOptionsArgument; +@dataclass(frozen=True) +class DifferentiableInput: + name: str + type: Type + + # TODO: only to keep it byte-for-byte compatible with the old codegen, should remove. + cpp_type: str + + +# Represents a differentiable `Return`. +# How is it different from the `Return` type? +# - The name in `Return` is optional. Here it is always populated using the same +# `cpp.return_names()` method. +# TODO: some cpp naming logic (e.g. resolving name conflict) might be irrelevant? +# - It's processed Returns which are differentiable, in compliance with the +# `output_differentiability` field defined in derivatives.yaml (if specified), +# and are only used in the context of the autograd codegen; +@dataclass(frozen=True) +class DifferentiableOutput: + name: str + type: Type + + # TODO: only to keep it byte-for-byte compatible with the old codegen, should remove. + cpp_type: str + + +@dataclass(frozen=True) +class NativeFunctionWithDifferentiabilityInfo: + func: NativeFunction + info: dict[str, DifferentiabilityInfo] | None + fw_derivatives: dict[str, Sequence[ForwardDerivative]] | None + + +# TODO: Update comment below since it is out of date. +def dispatch_strategy(fn: NativeFunctionWithDifferentiabilityInfo) -> str: + """How are we going to call the underlying implementation of a + declaration? There are two strategies: + - use_derived: we want to call the implementation on CPUDoubleType + (or a similar, derived Type instance). Because these derived + instances deal in Tensors, not Variables (it's a completely different + object, so it doesn't dispatch back to VariableType), code on + this dispatch path needs to wrap/unwrap tensors. If the + derived implementation takes and returns tensors, the + implementation is usually differentiable (although we also use + the derived dispatch path for non-differentiable functions + that we still want to dispatch on the derived Type instance; + e.g., size()) + - use_type: we want to call the implementation on Type, because + it is implemented concretely, and the functions it invokes will + get dispatched back to VariableType (which will ensure that they + are differentiable.) + """ + # fn is derived as long as any of its per-key differentiability infos + # has_derivatives. dispatch_strategy() is used to guard generation of fns in VariableType + # and ADInplaceOrViewType. We want to generate these functions as long as a + # derivative is defined for ANY dispatch key. + if fn.func.is_abstract or ( + fn.info is not None and any(info.has_derivatives for info in fn.info.values()) + ): + # If the function is abstract (not implemented on at::Type), we must + # call the implementation on the derived type with unpacked tensors. + + # If the function has a derivative specified and is concrete, we could + # call either implementation. We prefer the calling the derived + # type's implementation with unpacked tensors because it is more + # performant in some cases: any internal calls to other ATen functions + # won't have the history tracked. + + # If the function has a type dispatched argument (i.e. is a factory), + # we prefer calling the derived type's implementation both because it is + # more performant and to ensure factory functions return tensors with _version + # of 0 (probably not strictly necessary, but nice to have to keeps versions simple + # to understand. + + return "use_derived" + else: + # If the function is concrete (we don't have to override it) and we + # didn't declare it in derivatives.yaml, we'll assume that it is + # actually implemented out of differentiable functions. (This + # assumption might not hold, but then you'll see gradcheck fail.) + return "use_type" + + +def is_foreach_func(f: NativeFunction) -> bool: + return f.func.name.name.base.startswith("_foreach_") + + +# note(crcrpar): Most foreach functions can reference an out-place `torch` function whose schema kind +# is functional for their backward derivatives (and forward derivatives in the future), i.e., +# they would find such one in `functional_info_by_signature`. There however are some exceptions: +_foreach_with_inplace_ref = {"_foreach_zero_"} +_foreach_with_tensor_overload = { + "_foreach_add.Tensor", + "_foreach_mul.Tensor", + "_foreach_div.Tensor", +} +# The following do not support the alpha kwarg, which the nonforeach versions support. +_skip_argument_len_check = { + "_foreach_add.Scalar", + "_foreach_add_.Scalar", + "_foreach_add.ScalarList", + "_foreach_add_.ScalarList", + "_foreach_sub.Scalar", + "_foreach_sub_.Scalar", + "_foreach_sub.ScalarList", + "_foreach_sub_.ScalarList", +} + + +# Checks if `function_schema` is a native, non-foreach function which `f`, a foreach function +# reference to generate derivatives. +def is_reference_for_foreach( + f: NativeFunction, + function_schema: FunctionSchema, +) -> bool: + return ( + f.func.name.name.base.split("_foreach_")[-1] == function_schema.name.name.base + and ( + not function_schema.name.name.inplace + or str(f.func.name) in _foreach_with_inplace_ref + ) + and ( + str(f.func.name) in _skip_argument_len_check + or len(f.func.arguments.flat_non_out) + == len(function_schema.arguments.flat_non_out) + ) + and all( + ref_arg.type in (arg.type, getattr(arg.type, "elem", None)) + for arg, ref_arg in zip( + f.func.arguments.flat_non_out, + function_schema.arguments.flat_non_out, + ) + ) + ) + + +# TODO(crcrpar): Avoid hard coding "Default" ideally. +def gen_foreach_derivativeinfo( + foreach_function: NativeFunction, + functional_info_by_signature: dict[ + FunctionSchema, dict[str, DifferentiabilityInfo] + ], + non_functional_info_by_signature: dict[ + FunctionSchema, dict[str, DifferentiabilityInfo] + ], + dispatch_key: str = "Default", +) -> tuple[DifferentiabilityInfo | None, bool]: + """Generate DifferentiabilityInfo for out-place foreach function, return the existing one for in-place. + + The second return value indicates whether the info is generated in this function. + """ + ref_diff_info: DifferentiabilityInfo | None = None + + for function_schema, diff_info in functional_info_by_signature.items(): + if not is_reference_for_foreach(foreach_function, function_schema): + continue + ref_diff_info = diff_info[dispatch_key] + if ref_diff_info is not None: + break + # note(crcrpar): It seems like `zero`'s info isn't available in functional_info_by_signature + # while the info of `zero_` is in non_functional_info_by_signature + if ( + ref_diff_info is None + and foreach_function.func.kind() == SchemaKind.inplace + and str(foreach_function.func.name) in _foreach_with_inplace_ref + ): + for function_schema, diff_info in non_functional_info_by_signature.items(): + if not is_reference_for_foreach(foreach_function, function_schema): + continue + ref_diff_info = diff_info[dispatch_key] + if ref_diff_info is not None: + break + if ref_diff_info is None: + return None, False + + # non out-place uses the existing Derivative. + if foreach_function.func.kind() == SchemaKind.inplace: + return ref_diff_info, False + + map_refarg2foreacharg, map_name2arg = {}, {} + for i, (arg, ref_arg) in enumerate( + zip( + foreach_function.func.arguments.flat_non_out, + function_schema.arguments.flat_non_out, + ) + ): + map_refarg2foreacharg[ref_arg.name] = arg.name + map_name2arg[arg.name] = arg + + all_saved_inputs, all_saved_outputs, all_var_names = [], [], [] + modified_derivative_formulas = [] + for i, derivative in enumerate(ref_diff_info.derivatives): + modified_formula = derivative.formula.replace("grad", "grads[i]").replace( + "result", "result[i]" + ) + saved_inputs, saved_outputs = [], [] + # note(crcrpar): This context seems necessary to call `cpp.argument_type` + with local.parametrize( + use_const_ref_for_mutable_tensors=foreach_function.use_const_ref_for_mutable_tensors, + use_ilistref_for_tensor_lists=foreach_function.part_of_structured_group, + ): + for ref_input in derivative.saved_inputs: + ref_input_jit_name = ref_input.expr.split(".")[0] + mapped_name = map_refarg2foreacharg[ref_input_jit_name] + if isinstance(map_name2arg[mapped_name].type, ListType): + mapped_expr = mapped_name + "[i]" + else: + mapped_expr = mapped_name + new_expr = ref_input.expr.replace(ref_input_jit_name, mapped_expr) + modified_formula = modified_formula.replace( + cast(str, ref_input.nctype.name), new_expr + ) + + nctype = cpp.argument_type(map_name2arg[mapped_name], binds=mapped_name) + canonical_nctype = NamedCType( + nctype.name, nctype.type.remove_const_ref() + ) + saved_inputs.append( + SavedAttribute(nctype=canonical_nctype, expr=mapped_name) + ) + for ref_output in derivative.saved_outputs: + if ref_output.nctype.name == "result": + saved_outputs.append( + SavedAttribute( + nctype=NamedCType( + name="result", type=BaseCType(tensorListT) + ), + expr="result", + ) + ) + else: + raise RuntimeError("") + var_names = [map_refarg2foreacharg[var] for var in derivative.var_names] + all_var_names.extend(var_names) + all_saved_inputs.extend(saved_inputs) + all_saved_outputs.extend(saved_outputs) + modified_derivative = Derivative( + formula=modified_formula, + original_formula=derivative.formula, + var_names=tuple(var_names), + saved_inputs=tuple(saved_inputs), + saved_outputs=tuple(saved_outputs), + named_gradients=set(), + ) + modified_derivative_formulas.append(modified_derivative) + + with local.parametrize( + use_const_ref_for_mutable_tensors=foreach_function.use_const_ref_for_mutable_tensors, + use_ilistref_for_tensor_lists=foreach_function.part_of_structured_group, + ): + args_with_derivatives = [ + Binding( + name=arg.name, + nctype=cpp.argument_type(arg, binds=arg.name), + argument=arg, + default=None, + ) + for arg in foreach_function.func.arguments.flat_non_out + if arg.name in all_var_names + ] + + forward_derivatives: list[ForwardDerivative] = [] + fw_derivative: ForwardDerivative + for fw_derivative in ref_diff_info.forward_derivatives: + var_names: list[str] = list(fw_derivative.var_names) # type: ignore[no-redef] + var_types: list[Type] = list(fw_derivative.var_types) + required_inputs_fw_grad: list[str] = [] + required_inputs_primal: list[str] = [] + if fw_derivative.required_inputs_fw_grad is not None: + required_inputs_fw_grad = list(fw_derivative.required_inputs_fw_grad) + if fw_derivative.required_inputs_primal: + required_inputs_primal = list(fw_derivative.required_inputs_primal) + modified_formula = fw_derivative.formula + + # Foreach's result is TensorList + if "result" in modified_formula: + modified_formula = fw_derivative.formula.replace("result", "result[i]") + + for foreach_arg, ref_arg in zip( + foreach_function.func.arguments.flat_non_out, + ref_diff_info.func.func.arguments.flat_non_out, + ): + # Modify reference forward formula + if ( + isinstance(foreach_arg.type, ListType) + and not foreach_arg.type.is_tensor_like() + ): + # Assuming ScalarList + modified_formula = modified_formula.replace( + ref_arg.name, foreach_arg.name + "[i]" + ) + elif foreach_arg.type.is_tensor_like(): + # Assuming TensorList / Tensor + if not ( + isinstance(foreach_arg.type, ListType) + or ( + foreach_arg.type == BaseType(BaseTy.Tensor) + and str(foreach_function.func.name) + in _foreach_with_tensor_overload + ) + ): + raise AssertionError( + f"{foreach_function.func.name}, {foreach_arg.type}" + ) + for suffix in ("_p", "_t"): + curr_expr = ref_arg.name + suffix + if curr_expr in modified_formula: + new_expr = foreach_arg.name + suffix + modified_formula = modified_formula.replace(curr_expr, new_expr) + else: + # Assuming Scalar + if foreach_arg.name != ref_arg.name: + modified_formula = modified_formula.replace( + ref_arg.name, foreach_arg.name + ) + + # note(crcrpar): there should exist a cooler way... + for i, name in enumerate(var_names): + if name == ref_arg.name: + var_names[i] = foreach_arg.name + var_types[i] = foreach_arg.type + for i, name in enumerate(required_inputs_fw_grad): + if name == ref_arg.name: + required_inputs_fw_grad[i] = foreach_arg.name + for i, name in enumerate(required_inputs_primal): + if name == ref_arg.name: + required_inputs_primal[i] = foreach_arg.name + forward_derivatives.append( + ForwardDerivative( + formula=modified_formula, + var_names=tuple(var_names), + var_types=tuple(var_types), + required_inputs_fw_grad=tuple(required_inputs_fw_grad), + required_inputs_primal=tuple(required_inputs_primal), + required_original_self_value=fw_derivative.required_original_self_value, + is_reusing_outplace_formula=fw_derivative.is_reusing_outplace_formula, + ) + ) + + return ( + DifferentiabilityInfo( + name=foreach_function.func.name.name.base, + func=foreach_function, + op=f"Foreach{ref_diff_info.op}{foreach_function.func.name.overload_name}", + derivatives=modified_derivative_formulas, + forward_derivatives=forward_derivatives, + all_saved_inputs=tuple(set(all_saved_inputs)), + all_saved_outputs=tuple(set(all_saved_outputs)), + available_named_gradients=(), + used_named_gradients=set(), + args_with_derivatives=args_with_derivatives, + non_differentiable_arg_names=[], + output_differentiability=None, + output_differentiability_conditions=None, + ), + True, + ) + + +def match_differentiability_info( + native_functions: list[NativeFunction], + differentiability_infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]], +) -> list[NativeFunctionWithDifferentiabilityInfo]: + """Sets the "derivative" key on declarations to matching autograd function + In-place functions will use the out-of-place derivative definition if there + is no in-place specific derivative. + """ + + functional_info_by_signature = { + schema.signature(strip_default=True): info_dict + for schema, info_dict in differentiability_infos.items() + if schema.kind() == SchemaKind.functional + } + non_functional_info_by_signature = { + schema.signature(strip_default=True): info_dict + for schema, info_dict in differentiability_infos.items() + if schema.kind() != SchemaKind.functional + } + + def find_info( + f: NativeFunction, + ) -> tuple[dict[str, DifferentiabilityInfo] | None, bool]: + # Don't bother matching info to generated out= variants + if "generated" in f.tags and f.func.kind() == SchemaKind.out: + return None, False + + # (1) Check for an exact match + if f.func in differentiability_infos: + return differentiability_infos[f.func], True + + # (2) If no exact match, check if the out-of-place variant + # of this operator has a match. + # i.e mul() for mul_() or mul_out() + # note(crcrpar): Check foreach or not because in-place foreach functions use backward defined for the existing + # native functions instead of the out-place counterparts. + f_sig = f.func.signature(strip_default=True) + if f_sig in functional_info_by_signature and not is_foreach_func(f): + return functional_info_by_signature[f_sig], False + + # (3) Some operators have a derivative explicitly defined for the mutable + # variant, but get a code-generated out-of-place variant which does *not* + # come with a derivative formula. + # For the generated out-of-place variant, use the mutable variant's formula + # if it exists. + if "generated" in f.tags and f_sig in non_functional_info_by_signature: + info_dict = non_functional_info_by_signature[f_sig] + # See https://github.com/pytorch/pytorch/pull/76320/files#r874816389 + if any( + any("self" in str(input.nctype.name) for input in info.all_saved_inputs) + for info in info_dict.values() + ): + raise AssertionError( + f"Attempted to convert a derivative formula for a mutable operator " + f'to be used automatically by its functional variant ("{str(f.func)}"). ' + "This is not currently supported (we'd need to fix up the formula in the codegen)." + ) + return info_dict, False + + # (4) Generate derivative information of foreach functions if none is defined in `derivatives.yaml` + if is_foreach_func(f): + if f.func in differentiability_infos: + raise AssertionError( + f"Foreach function {f.func.name} already has differentiability info" + ) + diff_info, is_generated = gen_foreach_derivativeinfo( + f, + functional_info_by_signature, + non_functional_info_by_signature, + ) + if diff_info is None: + return None, False + # TODO(crcrpar): Avoid hard coding "Default" ideally. + diff_info_dict = {"Default": diff_info} + if is_generated: + differentiability_infos[f.func] = diff_info_dict + functional_info_by_signature[f.func] = diff_info_dict + return diff_info_dict, is_generated + + return None, False + + result: list[NativeFunctionWithDifferentiabilityInfo] = [] + for f in native_functions: + info_dict, is_exact_match = find_info(f) + + # Currently, the '.strides()' to 'strides_or_error' replacement does not support + # 'self' derivatives of an inplace function, so we must check for this case. + if f.func.kind() == SchemaKind.inplace and (info_dict is not None): + for info in info_dict.values(): + for derivative in info.derivatives: + if "self" in derivative.var_names: + for saved_input in derivative.saved_inputs: + if "strides_or_error" in saved_input.expr: + raise AssertionError( + "Calling '.strides()' in the 'self' derivative formula of an " + f"in-place function is not supported: {f.func}" + ) + + if not info_dict: + result.append( + NativeFunctionWithDifferentiabilityInfo( + func=f, info=None, fw_derivatives=None + ) + ) + continue + + fw_derivative_dict: dict[str, Sequence[ForwardDerivative]] = {} + for key, info in info_dict.items(): + if not info.forward_derivatives: + fw_derivative_dict[key] = [] + continue + + forward_derivatives = info.forward_derivatives + + # For functions that have a single def for out-of-place and inplace (like abs()) + if f.func.kind() == SchemaKind.inplace: + # For inplace functions there is a little bit of work to do: + # 1) Validate the formula and make sure the input that is modified in not used: + # - If there is a formula for the inplace variant of the function (is_exact_match == True) then + # we make sure that the original value of the input that is being modified inplace (self_p) is + # not used in the formula. Note that the formula can use "original_self_p" here and that would + # trigger a clone of the original input. + # - If we are reusing the out of place formula (is_exact_match == False) then we replace every + # occurrence of self_p and self_t by original_self_p and original_self_t. These will be + # populated by cloned version of the original input (either the clone done by the backward AD + # logic if self is also used in a backward formula or a special clone that we add). + # 2) At this point, there cannot be a self_p in the formula. + # 3) Change "result" into "self_p" as by design, in the inplace function codegen, the result is + # simply called self (as it is modified inplace). + # 4) Update the required primals data in case it used to contain "result" but should now contain + # "self" + # 5) If it is not an exact match, the user formula is not modifying the existing forward grad + # inplace as it should. So add some code that makes sure that we do so if the forward grad + # already exists. + + if len(info.forward_derivatives) != 1: + raise AssertionError( + "Only single output inplace should exist, " + f"got {len(info.forward_derivatives)}" + ) + fw_info = info.forward_derivatives[0] + formula = fw_info.formula + + def replace_self_with_original_self(formula: str, postfix: str) -> str: + def repl(m: re.Match[str]) -> str: + return f"{m.group(1)}original_self{postfix}{m.group(2)}" + + return re.sub(IDENT_REGEX.format(f"self{postfix}"), repl, formula) + + if re.search(IDENT_REGEX.format("self_p"), formula): + if is_exact_match: + # For manually defined formulas, don't allow the original value to be used + raise RuntimeError( + f'The formula for "{f.func.name}" is using the original value of self ' + "that is being modified inplace. This would lead to wrong forward gradients. " + 'Please use "result" in the formula only.' + ) + else: + # When the original formula is out of place, we save a clone of the primal + # value to be able to access this value if needed + # replace "self_p"/"self_t" from the formula by "original_self_p"/"original_self_t" + formula = replace_self_with_original_self(formula, "_p") + formula = replace_self_with_original_self(formula, "_t") + + # replace "result" from the formula by "self_p" + def repl(m: re.Match[str]) -> str: + return f"{m.group(1)}self_p{m.group(2)}" + + formula = re.sub(IDENT_REGEX.format("result"), repl, formula) + + required_primals = fw_info.required_inputs_primal + if re.search(IDENT_REGEX.format("self_p"), formula): + required_primals = ( + required_primals + ("self",) if required_primals else ("self",) + ) + + if not is_exact_match: + # NOTE [In-place forward AD formula Optimization] + # + # This optimization transforms the formula to directly do inplace, i.e. + # instead of self_t.copy_(self_t.op()) we do self_t.op_() when the following are met: + # + # 1) the formula satisfies the pattern: "self_t.op(*args)" + # 2) "op" in (1) needs to be the same as the op the derivative is for + # + # (2) may seem too strict, but currently the only ops that satisfy (1) also satisfy (2) + # If there is a need, we can relax (2) to allow any op that has an in-place variant + is_single_method_on_self_t = False + directly_do_inplace = False + op_name: str | None = None + between_parens: str | None = None + match = re.fullmatch(r"self_t.([\w]*)\((.*)\)", formula) + if match: + op_name, between_parens = match.group(1), match.group(2) + + # We want to... + # Match: self_t.op1(other_p.op2(arg)) + # Avoid: self_t.op1(args) + self_t.op2(args) + # Avoid: self_t.op1(other_p.op2(arg)) + self_t.op2(args) + def check_parens_nest_level_gt_zero(s: str) -> bool: + level = 1 + for ch in s: + if ch == ")": + level -= 1 + if level == 0: + return False + if ch == "(": + level += 1 + return True + + is_single_method_on_self_t = check_parens_nest_level_gt_zero( + between_parens + ) + directly_do_inplace = ( + is_single_method_on_self_t and op_name == info.name + ) + + if directly_do_inplace: + if op_name is None: + raise AssertionError("op_name must be non-None for inplace") + if between_parens is None: + raise AssertionError( + "between_parens must be non-None for inplace" + ) + formula = f"self_t_raw.defined() ? self_t_raw.{op_name}_({between_parens}) : {formula}" + else: + # Make sure that the forward grad is modified inplace when the original formula + # is out of place + formula = f"self_t_raw.defined() ? self_t_raw.copy_({formula}) : {formula}" + + required_original_self_value = bool( + re.search(IDENT_REGEX.format("original_self_p"), formula) + ) or bool(re.search(IDENT_REGEX.format("original_self_t"), formula)) + + forward_derivatives = [ + ForwardDerivative( + formula=formula, + var_names=("self",), + var_types=fw_info.var_types, + required_inputs_fw_grad=fw_info.required_inputs_fw_grad, + required_inputs_primal=required_primals, + required_original_self_value=required_original_self_value, + is_reusing_outplace_formula=not is_exact_match, + ), + ] + + fw_derivative_dict[key] = forward_derivatives + + result.append( + NativeFunctionWithDifferentiabilityInfo( + func=f, info=info_dict, fw_derivatives=fw_derivative_dict + ) + ) + + return result + + +def is_differentiable( + name: str, type: Type, info: DifferentiabilityInfo | None +) -> bool: + return type.is_tensor_like() and ( + info is None or name not in info.non_differentiable_arg_names + ) + + +def gen_differentiable_outputs( + fn: NativeFunctionWithDifferentiabilityInfo, key: str = "Default" +) -> list[DifferentiableOutput]: + f = fn.func + info = fn.info[key] if fn.info else None + outputs: list[DifferentiableOutput] = [ + DifferentiableOutput( + name=name, + type=ret.type, + cpp_type=cpp.return_type(ret, symint=True).cpp_type(), + ) + for name, ret in zip(cpp.return_names(f), f.func.returns) + ] + output_differentiability = info.output_differentiability if info else None + if output_differentiability is not None: + if len(output_differentiability) != len(outputs): + raise RuntimeError( + f"The length of output_differentiability ({len(output_differentiability)}), " + f"does not match the number of outputs ({len(outputs)})." + ) + differentiable_outputs: list[DifferentiableOutput] = [] + if False in output_differentiability and f.func.kind() == SchemaKind.inplace: + raise RuntimeError( + "output_differentiability=False for inplace operation (version_counter won't get updated)" + ) + for differentiable, output in zip(output_differentiability, outputs): + if differentiable: + differentiable_outputs.append(output) + return differentiable_outputs + candidate_differentiable_outputs = list( + filter(lambda r: is_differentiable(r.name, r.type, info), outputs) + ) + if uses_single_grad(info): + return candidate_differentiable_outputs[:1] + else: + return candidate_differentiable_outputs diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/cpp.py b/.venv/lib/python3.12/site-packages/torchgen/api/cpp.py new file mode 100644 index 0000000000000000000000000000000000000000..728bde0f648eea18f39cff33204ac3f7a0544de2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/cpp.py @@ -0,0 +1,480 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING +from typing_extensions import assert_never + +from torchgen import local +from torchgen.api.types import ( + ArgName, + ArrayCType, + ArrayRefCType, + BaseCType, + BaseTypeToCppMapping, + Binding, + boolT, + ConstRefCType, + CType, + intArrayRefT, + iTensorListRefT, + ListCType, + longT, + MutRefCType, + NamedCType, + OptionalCType, + optionalIntArrayRefT, + optionalSymIntArrayRefT, + scalarT, + SpecialArgName, + symIntArrayRefT, + SymIntT, + tensorListT, + tensorOptionsT, + tensorT, + TupleCType, + VectorCType, + voidT, +) +from torchgen.model import ( + Argument, + Arguments, + BaseTy, + BaseType, + FunctionSchema, + ListType, + NativeFunction, + OptionalType, + Return, + SelfArgument, + TensorOptionsArguments, + Type, +) + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +# This file describes the translation of JIT schema to the public C++ +# API, which is what people use when they call functions like at::add. +# +# Prominent characteristics of the C++ API: +# +# - dtype, layout, device and pin_memory are collected into +# a single C++ type TensorOptions (the native functions API +# also has this, but tensor options is really most relevant +# for the C++ API; it makes calling kwarg factory functions +# pleasant) +# +# - defaulting lives here (in fact, the dispatcher is completely +# oblivious of defaults!) +# +# BTW: policy on name collisions: we try not to have types with +# collisions, but functions are fair game to collide + + +def name( + func: FunctionSchema, + *, + faithful_name_for_out_overloads: bool = False, + symint_overload: bool = False, +) -> str: + name = str(func.name.name) + if symint_overload: + name += "_symint" + if func.is_out_fn(): + if faithful_name_for_out_overloads: + name += "_outf" + else: + name += "_out" + + return name + + +# Translation of "value types" in JIT schema to C++ API type. Value +# types look the same no matter if they are argument types or return +# types. Returns None if the type in question is not a value type. +def valuetype_type( + t: Type, + *, + binds: ArgName, + mutable: bool = True, + symint: bool = False, +) -> NamedCType | None: + if isinstance(t, BaseType): + if t.name in (BaseTy.Tensor, BaseTy.Scalar): + return None + elif str(t) == "SymInt": + if symint: + return NamedCType(binds, BaseCType(SymIntT)) + else: + return NamedCType(binds, BaseCType(longT)) + # All other BaseType currently map directly to BaseCppTypes. + return NamedCType(binds, BaseCType(BaseTypeToCppMapping[t.name])) + elif isinstance(t, OptionalType): + elem = valuetype_type(t.elem, binds=binds, mutable=mutable, symint=symint) + if elem is None: + return None + return NamedCType(binds, OptionalCType(elem.type)) + elif isinstance(t, ListType): + if str(t.elem) == "bool": + if t.size is None: + raise AssertionError("bool ListType must have a size") + return NamedCType(binds, ArrayCType(BaseCType(boolT), t.size)) + else: + return None + else: + raise AssertionError(f"unrecognized type {repr(t)}") + + +# Translation of types occurring in JIT arguments to a C++ argument type. +# If remove_non_owning_ref_types is set, we'll guarantee that the output CType is not a non-owning reference type. +# For example, we'll return std::vector instead of IntArrayRef, and at::Tensor instead of const at::Tensor&. +# See Note [translation from C++ reference to value types] +def argumenttype_type( + t: Type, + *, + mutable: bool, + binds: ArgName, + remove_non_owning_ref_types: bool = False, + symint: bool = False, +) -> NamedCType: + # If it's a value type, do the value type translation + r = valuetype_type( + t, + binds=binds, + mutable=mutable, + symint=symint, + ) + if r is not None: + return r + + if isinstance(t, BaseType): + if t.name == BaseTy.Tensor: + if mutable and not local.use_const_ref_for_mutable_tensors(): + return NamedCType(binds, MutRefCType(BaseCType(tensorT))) + elif remove_non_owning_ref_types: + return NamedCType(binds, BaseCType(tensorT)) + else: + return NamedCType(binds, ConstRefCType(BaseCType(tensorT))) + elif t.name == BaseTy.Scalar: + if remove_non_owning_ref_types: + return NamedCType(binds, BaseCType(scalarT)) + return NamedCType(binds, ConstRefCType(BaseCType(scalarT))) + else: + raise AssertionError(f"base type should have been value type {t}") + elif isinstance(t, OptionalType): + if str(t.elem) == "Tensor": + if mutable and not local.use_const_ref_for_mutable_tensors(): + return NamedCType( + binds, MutRefCType(BaseCType(tensorT)) + ) # TODO: fix this discrepancy + elif remove_non_owning_ref_types: + return NamedCType(binds, OptionalCType(BaseCType(tensorT))) + else: + return NamedCType( + binds, ConstRefCType(OptionalCType(BaseCType(tensorT))) + ) + elif str(t.elem) == "Scalar": + if remove_non_owning_ref_types: + return NamedCType(binds, OptionalCType(BaseCType(scalarT))) + return NamedCType(binds, ConstRefCType(OptionalCType(BaseCType(scalarT)))) + elif isinstance(t.elem, ListType) and str(t.elem.elem) == "int": + return NamedCType(binds, BaseCType(optionalIntArrayRefT)) + elif isinstance(t.elem, ListType) and str(t.elem.elem) == "SymInt": + if symint: + return NamedCType(binds, BaseCType(optionalSymIntArrayRefT)) + else: + return NamedCType(binds, BaseCType(optionalIntArrayRefT)) + elem = argumenttype_type(t.elem, mutable=mutable, binds=binds, symint=symint) + return NamedCType(binds, OptionalCType(elem.type)) + elif isinstance(t, ListType): + # TODO: remove these special cases, ArrayRef fallthrough works fine + if str(t.elem) == "int": + if remove_non_owning_ref_types: + return NamedCType(binds, VectorCType(BaseCType(longT))) + else: + return NamedCType(binds, BaseCType(intArrayRefT)) + if str(t.elem) == "SymInt": + if remove_non_owning_ref_types: + if symint: + return NamedCType(binds, VectorCType(BaseCType(SymIntT))) + else: + return NamedCType(binds, VectorCType(BaseCType(longT))) + else: + if symint: + return NamedCType(binds, BaseCType(symIntArrayRefT)) + else: + return NamedCType(binds, BaseCType(intArrayRefT)) + if str(t.elem) == "Tensor": + if local.use_ilistref_for_tensor_lists(): + return NamedCType(binds, ConstRefCType(BaseCType(iTensorListRefT))) + else: + return NamedCType(binds, BaseCType(tensorListT)) + elif str(t.elem) == "Scalar": + return NamedCType(binds, ArrayRefCType(BaseCType(scalarT))) + elif str(t.elem) == "Tensor?": + return NamedCType( + binds, ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT)))) + ) + elem = argumenttype_type(t.elem, mutable=mutable, binds=binds, symint=symint) + return NamedCType(binds, ArrayRefCType(elem.type)) + else: + raise AssertionError(f"unrecognized type {repr(t)}") + + +# Translate a JIT argument into its C++ type +def argument_type(a: Argument, *, binds: ArgName, symint: bool = False) -> NamedCType: + return argumenttype_type(a.type, mutable=a.is_write, symint=symint, binds=binds) + + +# Translation of a (non-multi) return type from JIT to C++ +# N.B: returntype_type returns a CType, not a NamedCType. +# This is mostly because of the mismatch between return types and return names. +# e.g. a function with a return type of 'void' has 0 return names, +# and a function with a return type of 'std::tuple' has >1 return name. +def returntype_type(t: Type, *, mutable: bool, symint: bool = False) -> CType: + # placeholder is ignored + # NB: symint is ALWAYS respected for return types. So symint argument + # here is IGNORED + r = valuetype_type(t, binds="__placeholder__", mutable=mutable, symint=True) + if r is not None: + return r.type + + if isinstance(t, BaseType): + if t.name == BaseTy.Tensor: + if mutable: + if local.use_const_ref_for_mutable_tensors(): + return ConstRefCType(BaseCType(tensorT)) + else: + return MutRefCType(BaseCType(tensorT)) + else: + # Note [Tensor Copy Returns] + # Currently, we use "Argument.is_write" to determine + # whether or not Tensor return types should be copies or references. + # If that ever changes, take a look at other locations of this note! + return BaseCType(tensorT) + elif t.name == BaseTy.Scalar: + return BaseCType(scalarT) + elif isinstance(t, ListType): + if mutable: + raise AssertionError( + "Native functions should never return a mutable tensor list. " + "They should return void." + ) + elem = returntype_type(t.elem, mutable=False) + if t.size is not None: + raise AssertionError(f"fixed size list returns not supported: {t}") + return VectorCType(elem) + elif isinstance(t, OptionalType): + elem = returntype_type(t.elem, mutable=mutable) + if str(t.elem) == "Tensor": + return OptionalCType(elem) + + raise AssertionError(f"unrecognized return type {t}") + + +# Translation of a single return to its C++ type +def return_type(r: Return, *, symint: bool = False) -> CType: + return returntype_type(r.type, mutable=r.is_write, symint=symint) + + +# Translation of a full (possibly multi) return from JIT to its C++ type +def returns_type(rs: Sequence[Return], *, symint: bool = False) -> CType: + if len(rs) == 0: + return BaseCType(voidT) + elif len(rs) == 1: + return return_type(rs[0], symint=symint) + else: + return TupleCType([return_type(r, symint=symint) for r in rs]) + + +def return_names(f: NativeFunction, *, fallback_name: str = "result") -> Sequence[str]: + returns: list[str] = [] + for i, r in enumerate(f.func.returns): + # If we have an inplace function, the return argument is + # implicitly named self. + # TODO: Consider incorporating this into the data model + if f.func.name.name.inplace: + if i != 0: + raise AssertionError("illegal inplace function with multiple returns") + name = "self" + # If we are out function, the name is the name of the + # corresponding output function (r.name will get recorded + # in field_name later.) + elif f.func.is_out_fn(): + name = f.func.arguments.out[i].name + # If the return argument is explicitly named... + elif r.name: + name_conflict = any( + r.name == a.name for a in f.func.schema_order_arguments() + ) + if name_conflict and not f.func.is_out_fn(): + name = f"{r.name}_return" + else: + name = r.name + # If there is no explicit name and no fallback name was passed in, we just name the output result, + # unless it's a multi-return, in which case it's result0, + # result1, etc (zero-indexed) + else: + name = fallback_name if len(f.func.returns) == 1 else f"{fallback_name}{i}" + returns.append(name) + return returns + + +JIT_TO_CPP_DEFAULT = { + "False": "false", + "True": "true", + "None": "::std::nullopt", # UGH this one is type directed + "Mean": "at::Reduction::Mean", + "[]": "{}", + "contiguous_format": "c10::MemoryFormat::Contiguous", + "long": "at::kLong", +} + + +# Convert a JIT default into C++ expression representing the default +def default_expr(d: str, t: Type, *, symint: bool) -> str: + if d == "None" and str(t) == "Tensor?": + return "{}" + if isinstance(t, BaseType) and t.name is BaseTy.str: + # Schema allows single quotes but C++ needs double + if len(d) >= 2 and d[0] == "'" and d[-1] == "'": + s = "" + i = 1 + while i + 1 < len(d): + if d[i] != "\\": + if d[i] == '"': + s += '\\"' + else: + s += d[i] + i += 1 + else: + if d[i + 1] == "'": + s += "'" + else: + s += d[i : i + 2] + i += 2 + + return f'"{s}"' + + if isinstance(t, OptionalType): + if d == "None": + return "::std::nullopt" + + return default_expr(d, t.elem, symint=symint) + + if isinstance(t, ListType): + if d.startswith("[") and d.endswith("]"): + return "{" + d[1:-1] + "}" + elif symint and d.isdigit() and str(t.elem) == "SymInt": + return f"c10::SymInt({d})" + elif t.size is None: + # NOTE: Sized lists can have scalar defaults + raise ValueError(f"Expected a list default '[...]' but found: '{d}'") + + return JIT_TO_CPP_DEFAULT.get(d, d) + + +# Convert an argument into its C++ API form + + +def argument( + a: Argument | TensorOptionsArguments | SelfArgument, + *, + cpp_no_default_args: set[str], + method: bool, + faithful: bool, + symint: bool = False, + has_tensor_options: bool, +) -> list[Binding]: + def sub_argument( + a: Argument | TensorOptionsArguments | SelfArgument, + ) -> list[Binding]: + return argument( + a, + cpp_no_default_args=cpp_no_default_args, + method=method, + faithful=faithful, + symint=symint, + has_tensor_options=has_tensor_options, + ) + + if isinstance(a, Argument): + binds: ArgName + if a.name == "memory_format" and has_tensor_options: + binds = SpecialArgName.possibly_redundant_memory_format + else: + binds = a.name + default: str | None = None + if a.name not in cpp_no_default_args and a.default is not None: + default = default_expr(a.default, a.type, symint=symint) + return [ + Binding( + nctype=argument_type(a, binds=binds, symint=symint), + name=a.name, + default=default, + argument=a, + ) + ] + elif isinstance(a, TensorOptionsArguments): + if faithful: + return ( + sub_argument(a.dtype) + + sub_argument(a.layout) + + sub_argument(a.device) + + sub_argument(a.pin_memory) + ) + else: + default = None + # Enforced by NativeFunction.__post_init__ + if "options" in cpp_no_default_args: + raise AssertionError("'options' should not be in cpp_no_default_args") + if all(x.default == "None" for x in a.all()): + default = "{}" + elif a.dtype.default == "long": + default = "at::kLong" # TODO: this is wrong + return [ + Binding( + nctype=NamedCType("options", BaseCType(tensorOptionsT)), + name="options", + default=default, + argument=a, + ) + ] + elif isinstance(a, SelfArgument): + if method: + # Caller is responsible for installing implicit this in context! + return [] + else: + return sub_argument(a.argument) + else: + assert_never(a) + + +def arguments( + arguments: Arguments, + *, + faithful: bool, + symint: bool = False, + method: bool, + cpp_no_default_args: set[str], +) -> list[Binding]: + args: list[Argument | TensorOptionsArguments | SelfArgument] = [] + if faithful: + args.extend(arguments.non_out) + args.extend(arguments.out) + else: + args.extend(arguments.out) + args.extend(arguments.non_out) + return [ + r.no_default() if faithful else r + for a in args + for r in argument( + a, + faithful=faithful, + symint=symint, + method=method, + has_tensor_options=arguments.tensor_options is not None, + cpp_no_default_args=cpp_no_default_args, + ) + ] diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/dispatcher.py b/.venv/lib/python3.12/site-packages/torchgen/api/dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..fcca7a60fec1829c5783197055733467fcdd63fe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/dispatcher.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +import itertools +from typing import TYPE_CHECKING +from typing_extensions import assert_never + +from torchgen.api import cpp +from torchgen.api.types import ArgName, Binding, CType, NamedCType +from torchgen.model import ( + Argument, + FunctionSchema, + Return, + SelfArgument, + TensorOptionsArguments, + Type, +) +from torchgen.utils import concatMap + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +# This file describes the translation of JIT schema to the dispatcher +# API, the *unboxed* calling convention by which invocations through +# the dispatcher are made. Historically, the dispatcher API matched +# the C++ API, but with the establishment of the boxed API, we've +# made changes to the dispatcher API to so that the unboxed API +# better aligns with the boxed API. The dispatcher API hooks heavily +# into our template based boxing/unboxing machinery, so changes +# to this convention will usually need template updates too. +# +# Prominent characteristics of the dispatcher API: +# +# - dtype, layout, device and pin_memory are represented as separate +# arguments. +# + + +def name(func: FunctionSchema) -> str: + return cpp.name(func) + + +def argumenttype_type( + t: Type, + *, + mutable: bool, + binds: ArgName, + remove_non_owning_ref_types: bool = False, + symint: bool = True, +) -> NamedCType: + # This is a faux amis. If it makes sense in the future to add + # more special cases here, or invert things so cpp.argument_type + # calls this, or just completely inline the function, please do + # it. + return cpp.argumenttype_type( + t, + mutable=mutable, + binds=binds, + symint=symint, + remove_non_owning_ref_types=remove_non_owning_ref_types, + ) + + +def argument_type( + a: Argument, + *, + binds: ArgName, + remove_non_owning_ref_types: bool = False, + symint: bool = True, +) -> NamedCType: + return argumenttype_type( + a.type, + mutable=a.is_write, + binds=binds, + remove_non_owning_ref_types=remove_non_owning_ref_types, + symint=symint, + ) + + +def returns_type(rs: Sequence[Return], *, symint: bool = True) -> CType: + # At present, there is no difference. But there could be! + return cpp.returns_type(rs, symint=symint) + + +def jit_arguments(func: FunctionSchema) -> list[Argument]: + def to_argument( + a: Argument | TensorOptionsArguments | SelfArgument, + ) -> list[Argument]: + if isinstance(a, Argument): + return [a] + elif isinstance(a, SelfArgument): + return [a.argument] + elif isinstance(a, TensorOptionsArguments): + return [a.dtype, a.layout, a.device, a.pin_memory] + else: + assert_never(a) + + return list( + concatMap( + to_argument, + itertools.chain( + func.arguments.positional, func.arguments.kwarg_only, func.arguments.out + ), + ) + ) + + +def argument( + a: Argument, *, remove_non_owning_ref_types: bool = False, symint: bool = True +) -> Binding: + return Binding( + nctype=argument_type( + a, + binds=a.name, + remove_non_owning_ref_types=remove_non_owning_ref_types, + symint=symint, + ), + name=a.name, + argument=a, + ) + + +def arguments(func: FunctionSchema, *, symint: bool = True) -> list[Binding]: + return [argument(a, symint=symint) for a in jit_arguments(func)] diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/functionalization.py b/.venv/lib/python3.12/site-packages/torchgen/api/functionalization.py new file mode 100644 index 0000000000000000000000000000000000000000..0d097e28a04a93df5b6ea9cef0c5abe41ef55509 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/functionalization.py @@ -0,0 +1,222 @@ +from __future__ import annotations + +from torchgen.api import dispatcher +from torchgen.api.types import ( + BaseCppType, + BaseCType, + Binding, + boolT, + ConstRefCType, + CType, + longT, + NamedCType, + tensorT, +) +from torchgen.model import ( + Argument, + BaseTy, + BaseType, + FunctionSchema, + NativeFunction, + NativeFunctionsViewGroup, +) + + +# This file describes the translation of JIT schema to API's used +# when creating `ViewMeta` specializations that are used by the functionalization pass. +# These API's mostly follow the dispatcher API, with one difference: +# - While the forward function just directly calls into the at::_ops API +# (following the dispatcher convention), the logic here for the reverse function +# is responsible for generating both the call-site, and the declarations +# (which are implemented manually in the at::functionalization::impl namespace). + +# Define some specific lambda input arguments. +base_binding = Binding( + name="base", + nctype=NamedCType(name="base", type=ConstRefCType(BaseCType(tensorT))), + argument=Argument( + name="base", type=BaseType(BaseTy.Tensor), default=None, annotation=None + ), + default=None, +) + +has_symbolic_inputs_binding = Binding( + name="has_symbolic_inputs", + nctype=NamedCType(name="has_symbolic_inputs", type=BaseCType(boolT)), + argument=Argument( + name="has_symbolic_inputs", + type=BaseType(BaseTy.bool), + default=None, + annotation=None, + ), + default=None, +) +mutated_view_binding = Binding( + name="mutated_view", + nctype=NamedCType(name="mutated_view", type=ConstRefCType(BaseCType(tensorT))), + argument=Argument( + name="base", type=BaseType(BaseTy.Tensor), default=None, annotation=None + ), + default=None, +) +out_index_binding = Binding( + name="out_index", + nctype=NamedCType(name="out_index", type=BaseCType(longT)), + argument=Argument( + name="out_index", type=BaseType(BaseTy.int), default=None, annotation=None + ), + default=None, +) +reapply_views_binding = Binding( + name="reapply_views", + nctype=NamedCType(name="reapply_views", type=BaseCType(boolT)), + argument=Argument( + name="reapply_views", type=BaseType(BaseTy.bool), default=None, annotation=None + ), + default=None, +) + +InverseReturnModeT = BaseCppType("at::functionalization", "InverseReturnMode") +inverse_return_mode_binding = Binding( + name="inverse_return_mode", + nctype=NamedCType(name="inverse_return_mode", type=BaseCType(InverseReturnModeT)), + argument=Argument( + name="inverse_return_mode", + # NB: not actually a bool but it doesn't matter because this isn't used + type=BaseType(BaseTy.bool), + default=None, + annotation=None, + ), + default=None, +) + + +# Name of the `ViewMeta` specialization class created. +def classname(func: FunctionSchema, with_namespace: bool = False) -> str: + namespace = "at::functionalization::" if with_namespace else "" + return f"{namespace}{func.name.unambiguous_name()}_ViewMeta" + + +# Name of the operation called inside the `forward`/`reverse` implementations. +def name( + g: NativeFunctionsViewGroup, + *, + is_reverse: bool, + include_namespace: bool, + reapply_views: bool | None = None, +) -> str: + if reapply_views is None: + # reapply_views is only important for the fwd lambda, + # since we always plumb the runtime "reapply_views" argument into the reverse function. + if not is_reverse: + raise AssertionError("reapply_views can only be None for reverse") + if is_reverse: + return reverse_name(g.view, include_namespace) + # in the forward case, we just directly call into the at::_ops API (so we always need the namespace) + if not include_namespace: + raise AssertionError("include_namespace must be True for forward") + if g.view_copy is None: + raise AssertionError("view_copy must be non-None for forward") + api_name = ( + g.view.func.name.unambiguous_name() + if reapply_views + else g.view_copy.func.name.unambiguous_name() + ) + return f"at::_ops::{api_name}::call" + + +def reverse_name(f: NativeFunction, include_namespace: bool) -> str: + # for the reverse: we plumb the "reapply_views" flag into that function and support + # both copy and non-copy variants. (We could avoid doing that, but that would require + # writing out twice as many view inverse functions). + api_name = f.func.name.unambiguous_name() + # in the reverse case, we codegen both the call-sites (which need the full namespace) and the declarations (which don't) + if include_namespace: + return f"at::functionalization::FunctionalInverses::{api_name}_inverse" + else: + return f"{api_name}_inverse" + + +def returns_type(func: FunctionSchema) -> CType: + # Assertion: all view ops return tensor-like outputs + if len(func.returns) < 1: + raise AssertionError("Expected at least one return value") + for ret in func.returns: + if not ret.type.is_tensor_like(): + raise AssertionError(f"Expected tensor-like return type, got {ret.type}") + # However, the return type of the lambda is always an individual tensor. + # For multi-tensor outputs, each tensor needs to be tracked individually. + return BaseCType(tensorT) + + +# Checks whether `func` might return more than one value. +def is_multi_output(func: FunctionSchema) -> bool: + return len(func.returns) > 1 or ( + len(func.returns) == 1 and func.returns[0].type.is_list_like() is not None + ) + + +# `ViewMeta` specialization constructor parameters. +def base_ctor_arguments(func: FunctionSchema) -> list[Binding]: + # All specializations are parematerized by `has_symbolic_inputs` flag. + arguments = [has_symbolic_inputs_binding] + + # If `func` might return more than 1 value, we also parameterize this specialization + # with the output index. + if is_multi_output(func): + arguments.append(out_index_binding) + + return arguments + + +# `ViewMeta` specialized class' constructor arguments. +# +# Values needed specifically by this specialization, that the base class does not need. +# Same as the class' attributes, but non-owning. +def extra_ctor_arguments(func: FunctionSchema) -> list[Binding]: + return attributes(func, owning=False) + + +# `ViewMeta` specialized class' non-static member data. +# +# Essential data for calling the instance's `forward` and `reverse functions. You can +# think of them as values that should be captured from the functionalization kernel. +def attributes(func: FunctionSchema, owning: bool = True) -> list[Binding]: + args = func.arguments.flat_all + if args[0].type != BaseType(BaseTy.Tensor): + raise AssertionError(f"Expected first arg to be Tensor, got {args[0].type}") + return [ + reapply_views_binding, + inverse_return_mode_binding, + *[dispatcher.argument(a, remove_non_owning_ref_types=owning) for a in args[1:]], + ] + + +def op_arguments(func: FunctionSchema, is_reverse: bool) -> list[Binding]: + args = func.arguments.flat_all + if args[0].type != BaseType(BaseTy.Tensor): + raise AssertionError(f"Expected first arg to be Tensor, got {args[0].type}") + non_self_args = args[1:] + # The forward lambda calls the at::_ops API, while the reverse lambda calls the view inverse API. + # Both of these follow the dispatcher API. + non_self_bindings = [dispatcher.argument(a) for a in non_self_args] + if not is_reverse: + # the forward lambda swaps out the original tensor argument with the lambd arg "base" + return [base_binding] + non_self_bindings + else: + # the reverse lambda does the same, but with an additional "mutated_view" arg + # additionally, we have a calling convention: for view ops that return multiple tensor outputs + # their corresponding view_inverse function takes in an additional index argument. + if is_multi_output(func): + return [ + base_binding, + mutated_view_binding, + inverse_return_mode_binding, + out_index_binding, + ] + non_self_bindings + else: + return [ + base_binding, + mutated_view_binding, + inverse_return_mode_binding, + ] + non_self_bindings diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/lazy.py b/.venv/lib/python3.12/site-packages/torchgen/api/lazy.py new file mode 100644 index 0000000000000000000000000000000000000000..eff973ae11de99dfe2dea98bcfa7a85d25c99682 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/lazy.py @@ -0,0 +1,470 @@ +from __future__ import annotations + +from typing import Any + +from torchgen.api.types import ( + BaseCppType, + BaseCType, + boolT, + CType, + deviceT, + doubleT, + generatorT, + layoutT, + ListCType, + longT, + memoryFormatT, + NamedCType, + OptionalCType, + scalarT, + scalarTypeT, + stringT, + SymIntT, + VectorCType, +) +from torchgen.model import ( + Argument, + BaseTy, + BaseType, + FunctionSchema, + ListType, + OperatorName, + OptionalType, + Return, + TensorOptionsArguments, + Type, +) + + +_valueT: BaseCppType | None = None + + +# A ValueT is an IR type which represents the computation of a Tensor. In other +# words, a PyTorch user will do operations on lazy tensors, and each output lazy +# tensor internally tracks a ValueT representing the IR node that would have +# actually produced the value of this tensor for real. +# +# This is configurable because different lazy tensor backends (LTC vs XLA) will +# have different IR representations. (Though, arguably, after unification they +# shouldn't!) +def getValueT() -> BaseCppType: + global _valueT + if not _valueT: + raise NotImplementedError( + "The value type needs to be set with setValueT() in run_gen_lazy_tensor()" + ) + + return _valueT + + +def setValueT(val: BaseCppType) -> None: + global _valueT + _valueT = val + + +# this is a bad hack. I need to refactor the data model to represent each arg in the schema as an object, +# making it easier to represent special properties of an arg. +tensorListValueT = BaseCppType("torch::lazy", "Value") + + +def process_ir_type( + typ: Type, properties: LazyIrProperties, *, symint: bool +) -> BaseCType | VectorCType | OptionalCType | ListCType: + """ + This function takes a type from NativeFunctions and converts it for use with + lazy tensor codegen. + + Type conversion for lazy currently consists of + (1) changing at::Tensors into lazy::Values + (2) wrapping everything in a BaseCType + (3) making cpp-reference types into cpp-value types (e.g. vector instead of IntArrayRef) + + (1) converts at::Tensors to lazy::Values (which wrap lazy::Nodes, with which Lazy IR represents tensors.) + There is special handling for Optional[Tensor] or list[Tensor], etc- hence 'tensor-like' + + This is incomplete- there are assertions in places that it's expected to need to add + more types as the codegen is used with more operators. + """ + if isinstance(typ, BaseType): + if typ.name == BaseTy.Tensor: + return BaseCType(getValueT()) + elif typ.name == BaseTy.Scalar: + if properties.TreatScalarsAsConstants: + return BaseCType(scalarT) + # at::scalar has special handling, + # and is wrapped in an lazy::Value just like at::tensor + return BaseCType(getValueT()) + elif typ.name == BaseTy.ScalarType: + return BaseCType(scalarTypeT) + elif typ.name == BaseTy.int: + return BaseCType(longT) + elif typ.name == BaseTy.SymInt: + if symint: + return BaseCType(getValueT()) + else: + return BaseCType(longT) + elif typ.name == BaseTy.bool: + return BaseCType(boolT) + elif typ.name == BaseTy.float: + return BaseCType(doubleT) + elif typ.name == BaseTy.str: + return BaseCType(stringT) + elif typ.name == BaseTy.Device: + return BaseCType(deviceT) + elif typ.name == BaseTy.Generator: + return BaseCType(generatorT) + elif typ.name == BaseTy.Layout: + return BaseCType(layoutT) + elif typ.name == BaseTy.MemoryFormat: + return BaseCType(memoryFormatT) + else: + raise AssertionError(f"TODO add support for type {repr(typ)}") + elif isinstance(typ, OptionalType): + return OptionalCType(process_ir_type(typ.elem, properties, symint=symint)) + elif isinstance(typ, ListType): + if str(typ.elem) == "Tensor?": + # TODO(whc) is this actually correct? or should it use a Vector like above + return ListCType(OptionalCType(BaseCType(getValueT()))) + elif str(typ.elem) == "Tensor": + # this is a TensorList which comes in from GetTensorList as a Value + return BaseCType(tensorListValueT) + elif typ.elem == BaseType(BaseTy.SymInt): + # TODO: return a value type. The problem here is analogous to + # the problem with tensorListValueT: if you have SymInt[] you + # cannot conveniently save the list of Value directly, as nodes + # expect to save values as a vector for ALL arguments. So you + # need a separate IR node that represents all of the size nodes + # assembled into a list. I'm not an LTC dev so I don't want to + # figure it out right now. Y'all figure it out... + return VectorCType(BaseCType(longT)) + + else: + return VectorCType(process_ir_type(typ.elem, properties, symint=symint)) + else: + raise AssertionError(f"unrecognized type {repr(typ)}") + + +# TODO: Determining this based off of CType is bad; this should be computed +# from Type directly; then the same logic as process_ir_type can be used +# +# Invariant: passed typ should be an *owning* CType (e.g., we will report +# that ArrayRef is NOT a value type) +def isValueType(typ: CType, properties: LazyIrProperties | None = None) -> bool: + """ + Given a type, determine if it is a Value-like type. This is equivalent to + being Tensor-like, but assumes the type has already been transformed. + """ + if isinstance(typ, BaseCType): + # I am regretting my naming conventions, but now we are wrapping at::scalar in + # lazy value, while preserving other 'scalar' types as scalars in the IR + treat_scalars_as_constants = properties and properties.TreatScalarsAsConstants + return ( + typ.type == getValueT() + or (typ.type == scalarT and not treat_scalars_as_constants) + or typ.type == SymIntT + ) + elif typ == VectorCType(BaseCType(SymIntT)): + # TODO: report True for this + return False + elif isinstance(typ, (OptionalCType, ListCType, VectorCType)): + return isValueType(typ.elem, properties) + return False + + +def isSymIntType(typ: Type) -> bool: + return isinstance(typ, BaseType) and typ.name == BaseTy.SymInt + + +def isWrappedScalarType(typ: Type) -> bool: + """ + Given a type, determine if it is a c10::scalar which we will wrap in a lazy Value. + Since we literally change the type from scalarT to valueT, information is lost. + This function helps build a list of wrapped scalars to save that information + """ + if isinstance(typ, BaseType): + # I am regretting my naming conventions, but now we are wrapping at::scalar in + # lazy value, while preserving other 'scalar' types as scalars in the IR + return typ.name == BaseTy.Scalar + elif isinstance(typ, (OptionalType, ListType)): + return isWrappedScalarType(typ.elem) + return False + + +# TODO: dedupe with Type.is_generator_like +def isGeneratorType(typ: Type) -> bool: + if isinstance(typ, BaseType): + return typ.name == BaseTy.Generator + elif isinstance(typ, (OptionalType)): + return isGeneratorType(typ.elem) + return False + + +# This class caches a few derived properties computed from an Argument +# and LazyIrProperties +class LazyArgument: + name: str + orig_type: Type + lazy_type_: CType | None + is_wrapped_scalar: bool + is_generator: bool + # TODO: this is lies, it is false for symint list + is_symint_or_list: bool + + # Whether or not we are treating this as symint or not + symint: bool + + # true if this argument is or contains a lazy IR value + is_lazy_value: bool + + def __init__( + self, arg: Argument, properties: LazyIrProperties, *, symint: bool + ) -> None: + self.name = arg.name + self.orig_type = arg.type + self.symint = symint + self.is_optional = isinstance(arg.type, OptionalType) + self.is_generator = isGeneratorType(arg.type) + self.lazy_type_ = process_ir_type(arg.type, properties, symint=symint) + self.is_wrapped_scalar = isWrappedScalarType(arg.type) + self.is_symint_or_list = symint and ( + isSymIntType(arg.type) + or (isinstance(arg.type, OptionalType) and isSymIntType(arg.type.elem)) + # TODO: lists of symints are not currently treated as value types + # or (isinstance(arg.type, ListType) and isSymIntType(arg.type.elem)) + ) + + self.is_lazy_value = isValueType(self.lazy_type, properties) + + @property + def lazy_type(self) -> CType: + if self.lazy_type_ is None: + raise AssertionError( + f"Attempted to access lazy_type for invalid argument {self.name}" + ) + return self.lazy_type_ + + +class LazyIrProperties: + """Collection of properties for an IR node + + The property groups are listed below. Each group is mutually + exclusive, meaning that only one property from each group can be True + at any one time. The properties can be accessed as if they were normal + attributes. The mutual exclusivity is automatically handled. + """ + + Properties: tuple[tuple[str, ...], ...] = ( + ( + "ShapePrecompute", # Assume shape has been precomputed + "ShapeCompute", # Need to compute the shape on construction + "ShapeCache", # Utilize the shape cache to defer computation + ), + ( + "Lower", # Codegen full lower function + "LowerDeclOnly", # Codegen only lower function declaration + ), + ( + "CanBeReused", # Codegen full reuse function + "CanBeReusedDeclOnly", # Codegen only reuse function declaration + ), + ( + "CreateFn", # Codegen full create function + "CreateFnDeclOnly", # Codegen only create function declaration + ), + ( + "TreatScalarsAsConstants", # Treat Scalars as constants instead of handling like values + ), + ) + + def __init__(self, *default_properties: str) -> None: + properties: dict[tuple[str, ...], str | None] = dict.fromkeys( + LazyIrProperties.Properties + ) + self.__dict__["properties"] = properties + for p in default_properties: + setattr(self, p, True) + + def __getattr__(self, key: str) -> Any: + properties = self.__dict__["properties"] + for values in LazyIrProperties.Properties: + if key in values: + return properties[values] == key + + return self.__getattribute__(key) + + def __setattr__(self, key: str, value: Any) -> Any: + properties = self.__dict__["properties"] + for values in LazyIrProperties.Properties: + if key in values: + properties[values] = key if value else None + return value + + raise KeyError(f"Invalid property: {key}") + + +# Inspired by a FunctionSchema object, a LazyIrSchema holds the schema of a Lazy IR node. +# Unlike a FunctionSchema, it has no round-trippable string form (relating to the YAML), +# but carries type information from a native FunctionSchema modified for use with IR nodes, +# and preserving original argument names. +# +# TODO: This is not idiomatic with how other torchgen APIs transform on schema. +class LazyIrSchema: + # The name of the operator this function schema describes. + name: OperatorName + + positional_args: tuple[LazyArgument, ...] + keyword_args: tuple[LazyArgument, ...] + + # TODO: Need to handle collisions with argument names at some point + returns: tuple[Return, ...] + + # if this schema has a Generator arg, list its orig ctype/name but don't + # build a LazyArgument since lazy IR doesn't support it + generator_arg: NamedCType | None = None + + # original function schema + func: FunctionSchema + + # Whether or not we are code-genning for SymInt or not + symint: bool + + properties: LazyIrProperties = LazyIrProperties( + # default properties + "ShapePrecompute", + "Lower", + "CanBeReused", + ) + opkind: str | None = None + + def __init__( + self, + func: FunctionSchema, + properties: LazyIrProperties | None = None, + *, + symint: bool, + ) -> None: + if properties: + self.properties = properties + + self.func = func + self.symint = symint + positional_args: list[LazyArgument] = [] + for arg_field in ["pre_self_positional", "self_arg", "post_self_positional"]: + if arg_field == "self_arg" and func.arguments.self_arg is not None: + arg = func.arguments.self_arg.argument + positional_args.append( + LazyArgument(arg, self.properties, symint=symint) + ) + elif getattr(func.arguments, arg_field) is not None: + positional_args.extend( + LazyArgument(arg, self.properties, symint=symint) + for arg in getattr(func.arguments, arg_field) + ) + self.positional_args = tuple(positional_args) + + keyword_args: list[LazyArgument] = [] + for arg_field in [ + "pre_tensor_options_kwarg_only", + "tensor_options", + "post_tensor_options_kwarg_only", + "out", + ]: + curr_args = getattr(func.arguments, arg_field) + if curr_args is not None: + if isinstance(curr_args, TensorOptionsArguments): + curr_args = curr_args.all() + for arg in curr_args: + if isGeneratorType(arg.type): + if self.generator_arg is not None: + raise AssertionError( + "We expect there is only one generator arg" + ) + self.generator_arg = NamedCType( + arg.name, + arg.type, # type:ignore[arg-type] + ) + keyword_args.extend( + LazyArgument(arg, self.properties, symint=symint) + for arg in curr_args + ) + self.keyword_args = tuple(keyword_args) + self.name = func.name + self.returns = func.returns + + @property + def node_name(self) -> str: + """ + Return camel-case version of op in node. + + Note: This function also appends any `overload_name` in the operation. + For example, if the op is `bitwise_and.Tensor`, the returned name + will be `BitwiseAndTensor`. + """ + op_name = f"{self.name.name}_{self.name.overload_name}".lower() + return "".join(word.capitalize() or "" for word in op_name.split("_")) + + @property + def aten_name(self) -> str: + return str(self.name.name) + + @property + def base_name(self) -> str: + return f"{self.name.name.base}" + + def filtered_args( + self, + positional: bool = True, + keyword: bool = True, + values: bool = True, + scalars: bool = True, + generator: bool = True, + ) -> list[LazyArgument]: + # This function maintains the sorted order of arguments but provides different filtered views. + # Some parts of the code care about kwargs vs args (TS lowerings), + # other parts care about whether they need to wrap the arg in a lazy value or leave it alone. + # Generators are special cased, as they are needed for fallback/shape-inference but not supported + # in TS lowerings and therefore also omitted from lazy IR. + args: list[LazyArgument] = [] + if positional: + args.extend(self.positional_args) + if keyword: + args.extend(self.keyword_args) + + if values and scalars and generator: + return args + elif values and scalars: + return [a for a in args if not a.is_generator] + elif values: + return [a for a in args if a.is_lazy_value] + elif scalars: + return [ + a + for a in args + if not a.is_lazy_value and (generator or not a.is_generator) + ] + + return [] + + @property + def positional_values(self) -> list[LazyArgument]: + return self.filtered_args( + positional=True, keyword=False, values=True, scalars=False + ) + + @property + def positional_scalars(self) -> list[LazyArgument]: + return self.filtered_args( + positional=True, keyword=False, values=False, scalars=True + ) + + @property + def keyword_values(self) -> list[LazyArgument]: + return self.filtered_args( + positional=False, keyword=True, values=True, scalars=False + ) + + @property + def keyword_scalars(self) -> list[LazyArgument]: + return self.filtered_args( + positional=False, keyword=True, values=False, scalars=True + ) diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/meta.py b/.venv/lib/python3.12/site-packages/torchgen/api/meta.py new file mode 100644 index 0000000000000000000000000000000000000000..2e99d151faeaccea7ca47f372fd26f9985ce7249 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/meta.py @@ -0,0 +1,13 @@ +from torchgen.model import NativeFunctionsGroup + + +# Follows dispatcher calling convention, but: +# - Mutable arguments not allowed. Meta functions are always +# written in functional form. Look at FunctionSchema.signature() +# - No tensor returns; instead we return a TensorMeta describing +# the tensor in question + + +def name(g: NativeFunctionsGroup) -> str: + # use the overload name from the functional version + return str(g.functional.func.name).replace(".", "_") diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/native.py b/.venv/lib/python3.12/site-packages/torchgen/api/native.py new file mode 100644 index 0000000000000000000000000000000000000000..632216704d2d47606b977d487335ca196e2e1842 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/native.py @@ -0,0 +1,159 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING +from typing_extensions import assert_never + +from torchgen import local +from torchgen.api import cpp +from torchgen.api.types import ( + ArgName, + BaseCType, + Binding, + boolT, + ConstRefCType, + CType, + deviceT, + layoutT, + ListCType, + MutRefCType, + NamedCType, + OptionalCType, + scalarT, + scalarTypeT, + tensorT, +) +from torchgen.model import ( + Argument, + FunctionSchema, + Return, + SelfArgument, + TensorOptionsArguments, + Type, +) + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +# This file describes the translation of JIT schema to the native functions API. +# This looks a lot like the C++ API (which makes historical sense, because the +# idea was you wrote native functions to implement functions in the C++ API), +# but over time we have evolved the C++ API without actually changing our +# native:: kernels. The intention is to make native API and dispatcher API +# line up as closely as possible, since this results in the least overhead +# (no translation is needed from dispatcher API to native API). +# +# NB: this is symint aware, you will get the non-SymInt variant for some +# dispatch entries and SymInt for others. + + +def name(func: FunctionSchema) -> str: + name = str(func.name.name) + # TODO: delete this! + if func.is_out_fn(): + name += "_out" + if func.name.overload_name: + name += f"_{func.name.overload_name}" + return name + + +def argumenttype_type( + t: Type, *, mutable: bool, binds: ArgName, symint: bool +) -> NamedCType: + if str(t) == "Tensor?": + tensor_type: OptionalCType = OptionalCType(BaseCType(tensorT)) + if mutable and not local.use_const_ref_for_mutable_tensors(): + return NamedCType(binds, MutRefCType(tensor_type)) + else: + return NamedCType(binds, ConstRefCType(tensor_type)) + elif str(t) == "Tensor?[]": + return NamedCType( + binds, ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT)))) + ) + elif str(t) == "Scalar": + return NamedCType(binds, ConstRefCType(BaseCType(scalarT))) + elif str(t) == "Scalar?": + return NamedCType(binds, ConstRefCType(OptionalCType(BaseCType(scalarT)))) + return cpp.argumenttype_type(t, mutable=mutable, binds=binds, symint=symint) + + +def returns_type(rs: Sequence[Return], *, symint: bool) -> CType: + return cpp.returns_type(rs, symint=symint) + + +def argument_type(a: Argument, *, binds: ArgName, symint: bool) -> NamedCType: + return argumenttype_type(a.type, mutable=a.is_write, binds=binds, symint=symint) + + +def argument( + a: Argument | SelfArgument | TensorOptionsArguments, + *, + is_out: bool, + symint: bool, +) -> list[Binding]: + # Ideally, we NEVER default native functions. However, there are a number + # of functions that call native:: directly and rely on the defaulting + # existing. So for BC, we generate defaults for non-out variants (but not + # for out variants, where it is impossible to generate an appropriate + # default) + should_default = not is_out + if isinstance(a, Argument): + default: str | None = None + if should_default and a.default is not None: + default = cpp.default_expr(a.default, a.type, symint=symint) + return [ + Binding( + nctype=argument_type(a, binds=a.name, symint=symint), + name=a.name, + default=default, + argument=a, + ) + ] + elif isinstance(a, SelfArgument): + # Erase SelfArgument from the distinction + return argument(a.argument, is_out=is_out, symint=symint) + elif isinstance(a, TensorOptionsArguments): + default = None + if should_default: + default = "{}" + # TODO: Not sure why the arguments assigned here are for + # TensorOptionsArguments and not the constituent pieces. It seems + # to matter + return [ + Binding( + nctype=NamedCType("dtype", OptionalCType(BaseCType(scalarTypeT))), + name="dtype", + default=default, + argument=a, + ), + Binding( + nctype=NamedCType("layout", OptionalCType(BaseCType(layoutT))), + name="layout", + default=default, + argument=a, + ), + Binding( + nctype=NamedCType("device", OptionalCType(BaseCType(deviceT))), + name="device", + default=default, + argument=a, + ), + Binding( + nctype=NamedCType("pin_memory", OptionalCType(BaseCType(boolT))), + name="pin_memory", + default=default, + argument=a, + ), + ] + else: + assert_never(a) + + +def arguments(func: FunctionSchema, *, symint: bool) -> list[Binding]: + args: list[Argument | TensorOptionsArguments | SelfArgument] = [] + args.extend(func.arguments.non_out) + args.extend(func.arguments.out) + return [ + r for arg in args for r in argument(arg, symint=symint, is_out=func.is_out_fn()) + ] diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/python.py b/.venv/lib/python3.12/site-packages/torchgen/api/python.py new file mode 100644 index 0000000000000000000000000000000000000000..545cd1489d34eea9ccc1f75e72d596cf2cb2baab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/python.py @@ -0,0 +1,1525 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from torchgen.api import cpp +from torchgen.api.types import Binding, CppSignature, CppSignatureGroup +from torchgen.gen import pythonify_default +from torchgen.model import ( + Argument, + BaseTy, + BaseType, + FunctionSchema, + ListType, + NativeFunction, + OptionalType, + Return, + Type, + Variant, +) + + +if TYPE_CHECKING: + from collections.abc import Iterable, Sequence + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Data Models +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# [Notes] python binding codegen +# +# The Python binding codegen produces code that takes the input list of +# PyObjects, finds the matching ATen C++ function using PythonArgParser, +# converts the PyObjects into C++ types and calls the ATen C++ function: +# +# +--------+ parsing +------------------------+ binding +-----------------------+ +# | PyObjs | ---------> | PythonArgParser Output | ---------> | Cpp Function Dispatch | +# +--------+ +------------------------+ +-----------------------+ +# +# The following examples demonstrate the data models the Python binding +# codegen needs to deal with and the tasks it needs to accomplish. It +# helps understand the purpose of the new data types we introduced below. +# +# - Function Schema (source of truth) +# +# aten::zeros(int[] size, *, ScalarType? dtype=None, Layout? layout=None, +# Device? device=None, bool? pin_memory=None) -> Tensor +# +# - Python Signature +# +# It's used to generate input schema string for PythonArgParser. +# Note: TensorOptions fields are reordered and the additional +# 'requires_grad' field is added: +# +# zeros(IntArrayRef size, *, ScalarType dtype=None, +# Layout layout=torch.strided, Device device=None, +# bool pin_memory=False, bool requires_grad=False) +# +# - C++ Signature +# +# It's used to generate C++ lambda formals & dispatch call. +# Note: the scattered TensorOptions fields are packed into 'options'. +# +# auto dispatch_zeros = +# [](IntArrayRef size, const TensorOptions & options) -> Tensor { +# pybind11::gil_scoped_release no_gil; +# return torch::zeros(size, options); +# }; +# +# - Binding between Python Arguments and C++ Arguments +# +# Given a set of Python Arguments in scope, we need produce the +# binding expressions that translate the Python API into C++ API: +# +# Python Args Cpp Args Binding Exprs +# ----------------------------------------------------------------- +# 0: size size '_r.intlist(0)' +# 1: dtype -----+ +# 2: layout +--> options 'options' [special packing] +# 3: device / +# 4: pin_memory / +# 5: requires_grad -+ +# +# So the full dispatch expression would look like: +# +# dispatch_zeros(_r.intlist(0), options) +# +# Where does 'options' come from? It involves special local init +# for TensorOptions. Note that Python side has the additional +# 'requires_grad' field: +# +# const auto options = TensorOptions() +# .dtype(_r.scalartype(1)) +# .device(_r.device(3)) +# .layout(_r.layoutOptional(2)) +# .requires_grad(_r.toBool(5)) +# .pinned_memory(_r.toBool(4)); +# +# In some other cases one Python Argument can map to multiple C++ +# Arguments. For example: +# +# aten::max.dim(Tensor self, int dim, bool keepdim=False) +# -> (Tensor values, Tensor indices) +# +# Python Args Cpp Args Binding Exprs +# --------------------------------------------------------------------- +# +----> max 'out[0]' +# /-----> max_values 'out[1] +# 0: input / self '_r.tensor(0)' +# 1: dim / dim '_r.toInt64(1)' +# 2: keepdim / keepdim '_r.toBool(2)' +# 3: out -----+ [local init] out '_r.tensorlist_n<2>(3)' +# +# As demonstrated above, the binding can involve reordering, +# packing, unpacking and special local inits. +# +# +# Let's look at a concrete example: +# +# static PythonArgParser parser({ +# "abs(Tensor input, *, Tensor out=None)", +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# ^ +# +--- Python Schema, represented by PythonSignature and PythonArgument +# +# }, /*traceable=*/true); +# +# ParsedArgs<2> parsed_args; +# auto _r = parser.parse(nullptr, args, kwargs, parsed_args); +# +# ... +# +# if (_r.isNone(1)) { +# ~~~~~~~~~~~~ <--- Scattered PythonArgParser output (arg name = 'out') +# represented by PythonArgParserOutputExpr +# +# // aten::abs(Tensor self) -> Tensor +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# ^ +# +--- NativeFunction schema, base version +# +# auto dispatch_abs = [](const Tensor & self) -> Tensor { +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# ^ +# +--- dispatch_lambda_args / dispatch_lambda_return_str +# generated from NativeFunction / CppSignature +# (deprecated PythonSignature is special) +# arguments are represented by DispatchLambdaArgument +# +# pybind11::gil_scoped_release no_gil; +# return self.abs(); +# ~~~~~~~~~~~ <--- cpp_dispatch_target / cpp_dispatch_exprs +# generated from NativeFunction / CppSignature +# }; +# return wrap(dispatch_abs(_r.tensor(0))); +# ~~~~~~~~~~~~~ +# ^ +# +--- dispatch_lambda_exprs +# binding PythonArgParserOutputExpr (python args) +# and DispatchLambdaArgument (c++ args) +# +# } else { +# // aten::abs.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# ^ +# +--- NativeFunction schema, out-variant +# +# auto dispatch_abs_out = [](Tensor out, const Tensor & self) -> Tensor { +# pybind11::gil_scoped_release no_gil; +# return at::abs_out(out, self); +# }; +# return wrap(dispatch_abs_out(_r.tensor(1), _r.tensor(0))); +# } +# +# +# [Notes] python interface codegen +# The python dataclasses below are used used to generate both python binding code +# and pyi type hint signatures. +# In theory these two should look very similar, but there are number of differences +# in how pyi signatures vs. python_arg_parser signatures are generated. +# These differences have been encapsulated in signature_str() vs. signature_str_pyi() +# to display the full signatures, and argument_str() vs argument_str_pyi() to display arguments. +# For examples, only pyi signatures include return types. + + +def format_function_signature( + name: str, arguments: Iterable[str] = (), return_type: str | None = None +) -> str: + if not isinstance(arguments, (list, tuple)): + arguments = tuple(arguments) + return_type = f" -> {return_type}" if return_type is not None else "" + + sig = f"def {name}({', '.join(arguments)}){return_type}: ..." + if len(sig) <= 80 or len(arguments) == 0 or tuple(arguments) == ("self",): + return sig + + lines = [ + f"def {name}(", + *(f" {arg}," for arg in arguments), + f"){return_type}: ...", + ] + sig = "\n".join(lines) + if all(len(line) <= 80 for line in lines): + return sig + # ruff format bug for compound statements: https://github.com/astral-sh/ruff/issues/18658 + # use `skip` instead of `on` + `off` + return sig.removesuffix(" ...") + " # fmt: skip\n ..." + + +@dataclass(frozen=True) +class PythonReturns: + returns: tuple[Return, ...] + + +@dataclass(frozen=True) +class PythonArgument: + name: str + type: Type + default: str | None + + # Used to generate the default init expr for some PythonArgParser outputs, e.g.: + # + # _r.layoutWithDefault(3, layout_from_backend(self.options().backend()))) + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # ^ + # +--- default_init str + default_init: str | None + + # Compute argument formal for python argument parsing. + # Needs to be consistent with torch/csrc/utils/python_arg_parser.h. + def argument_str(self, *, method: bool = False, symint: bool = True) -> str: + type_str = ( + argument_type_str(self.type, symint=symint) + .replace("const ", "") + .replace(" &", "") + ) + + name = self.name + # s/self/input/ outside method bindings + # [old codegen] TODO: remove this? doesn't rename in codegen, it's just + # for the parse string + if name == "self" and type_str in ["Tensor", "Number"] and not method: + name = "input" + + # add default + if self.default is not None: + default = { + "nullptr": "None", + "::std::nullopt": "None", + "std::nullopt": "None", + "{}": "None", + }.get(self.default, self.default) + return f"{type_str} {name}={default}" + else: + return f"{type_str} {name}" + + def argument_str_pyi( + self, *, method: bool = False, deprecated: bool = False + ) -> str: + type_str = argument_type_str_pyi(self.type) + + name = self.name + # s/self/input/ outside method bindings + # [old codegen] TODO: remove this? doesn't rename in codegen, it's just + # for the parse string + if name == "self" and type_str == "Tensor" and not method and not deprecated: + name = "input" + + if name == "from": # from is a Python keyword... + name += "_" + + # pyi merges the _out and functional variants into the same signature, with an optional out arg + if name == "out" and not deprecated: + type_str = _append_optional_pyi(type_str) + + # pyi deprecated signatures don't get defaults for their out arg + treat_as_no_default = ( + deprecated + and isinstance(self, PythonOutArgument) + and self.default == "None" + ) + + # add default + if self.default is not None and not treat_as_no_default: + if ( + isinstance(self.type, ListType) + and self.type.elem == BaseType(BaseTy.int) + and self.default.startswith("{") + and self.default.endswith("}") + ): + default = ( + "(" + ", ".join(map(str.strip, self.default[1:-1].split(","))) + ")" + ) + else: + default = { + "nullptr": "None", + "::std::nullopt": "None", + "std::nullopt": "None", + "{}": "None", + "c10::MemoryFormat::Contiguous": "contiguous_format", + "QScheme::PER_TENSOR_AFFINE": "per_tensor_affine", + }.get(self.default, self.default) + return f"{name}: {type_str} = {default}" + else: + return f"{name}: {type_str}" + + +@dataclass(frozen=True) +class PythonOutArgument(PythonArgument): + # In Python signature multiple output fields are packed into one 'out' argument. + # When binding to C++, it's first binded to a local 'out' variable: + # 'auto out = _r.tensorlist_n<2>(2);', + # then binded to scattered C++ output arguments as 'out[0]', 'out[1]', and etc. + # TODO: maybe don't need keep scattered out fields for python signature? + outputs: tuple[PythonArgument, ...] + + @staticmethod + def from_outputs(outputs: tuple[PythonArgument, ...]) -> PythonOutArgument | None: + if not outputs: + return None + + size = len(outputs) + if size == 1: + return PythonOutArgument( + name=outputs[0].name, + type=outputs[0].type, + default="None", + default_init=None, + outputs=outputs, + ) + elif size > 1: + if any(not a.type.is_tensor_like() for a in outputs): + raise RuntimeError(f"Unsupported output type: {outputs}") + return PythonOutArgument( + name="out", + # TODO: shouldn't this be OptionalType[ListType[...]], since it defaults to None? + type=ListType(BaseType(BaseTy.Tensor), size), + default="None", + default_init=None, + outputs=outputs, + ) + raise AssertionError(r"Unexpected PythonOutArgument size") + + +@dataclass(frozen=True) +class PythonSignature: + # Base operator name, without inplace/outplace suffix. + name: str + + # Positional arguments. + # TODO: create a dedicated SelfArgument type for 'self'? + input_args: tuple[PythonArgument, ...] + + # Keyword arguments excluding the 'out' argument and scattered kwargs belonging + # to TensorOptions (dtype, layout, device, pin_memory, requires_grad, etc). + input_kwargs: tuple[PythonArgument, ...] + + output_args: PythonOutArgument | None + + # Return types, which are only used by pyi + returns: PythonReturns + + # These are scattered kwargs arguments belonging to TensorOptions. + # When binding to C++, they are packed into a TensorOptions object 'options'. + # It's possible that the C++ signature doesn't take TensorOptions object (e.g. + # for out variant), in which case they will be used as scattered fields without + # being packed into 'options'. + # TODO: maybe create a PythonTensorOptionsArgument? + tensor_options_args: tuple[PythonArgument, ...] + + # method or function signature? + method: bool + + @property + def deprecated(self) -> bool: + return False + + def arguments( + self, *, skip_outputs: bool = False, skip_tensor_options: bool = False + ) -> tuple[PythonArgument | PythonOutArgument, ...]: + result: list[PythonArgument | PythonOutArgument] = [] + result.extend(self.input_args) + result.extend(self.input_kwargs) + if self.output_args is not None and not skip_outputs: + result.append(self.output_args) + if not skip_tensor_options: + result.extend(self.tensor_options_args) + return tuple(result) + + def arguments_count(self) -> int: + return len(self.arguments()) + + def output_idx(self) -> int: + return len(self.input_args) + len(self.input_kwargs) + + # [old codegen] Compute the Python function signature for argument parsing, + # as specified in torch/csrc/utils/python_arg_parser.h. WARNING: + # this is NOT the same type signature as specified by PEP 484 + # as understood by mypy; our format was independently developed + # and has some quirks to make it more suitable specifically + # for error parsing. + # + # For a translation to mypy-valid type signatures, see + # signature_str_pyi(). + def signature_str(self, *, skip_outputs: bool = False, symint: bool = True) -> str: + args = self.arguments(skip_outputs=skip_outputs) + schema_formals: list[str] = [ + a.argument_str(method=self.method, symint=symint) for a in args + ] + positional_argc = len(self.input_args) + if len(schema_formals) > positional_argc: + schema_formals.insert(positional_argc, "*") + + return f"{self.name}({', '.join(schema_formals)})" + + def signature_str_pyi(self, *, skip_outputs: bool = False) -> str: + args = self.arguments(skip_outputs=skip_outputs) + schema_formals: list[str] = [ + a.argument_str_pyi(method=self.method) for a in args + ] + positional_argc = len(self.input_args) + if len(schema_formals) > positional_argc: + schema_formals.insert(positional_argc, "*") + + # only pyi signatures include returns + returns_str = returns_str_pyi(self) + # pyi also includes self (with no typing/defaults) for methods + if self.method: + schema_formals.insert(0, "self") + return format_function_signature(self.name, schema_formals, returns_str) + + def signature_str_pyi_vararg(self, *, skip_outputs: bool = False) -> str | None: + # only pyi uses vararg signatures + args = self.arguments(skip_outputs=skip_outputs) + schema_formals: list[str] = [ + a.argument_str_pyi(method=self.method) for a in args + ] + # vararg only applies to pyi signatures. vararg variants are not generated for all signatures + num_args = self.arguments_count() + if num_args == 0: + return None + + num_positionalargs = len(self.input_args) + + vararg_type = args[0].type + if not ( + isinstance(vararg_type, ListType) + and str(vararg_type.elem) in ["int", "SymInt"] + and num_positionalargs == 1 + ): + return None + + # Below are the major changes in vararg vs. regular pyi signatures + # vararg signatures also omit the asterix + schema_formals[0] = ( + "*" + args[0].name + ": " + argument_type_str_pyi(vararg_type.elem) + ) + + returns_str = returns_str_pyi(self) + # pyi also includes self (with no typing/defaults) for methods + if self.method: + schema_formals.insert(0, "self") + return format_function_signature(self.name, schema_formals, returns_str) + + +# The deprecated python signature involves some special logic, so create a +# dedicated data model to store these extra properties. +@dataclass(frozen=True) +class PythonSignatureDeprecated(PythonSignature): + # Schema for the deprecated function + deprecated_schema: FunctionSchema + + # The deprecated signature might miss some arguments that the corresponding + # C++ signature expects. We need store the constant default values to pass in. + # For example: + # [deprecate signature]: addmm(Scalar beta, Tensor self, Tensor mat1, Tensor mat2) + # [func schema]: aten::addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + # [func call]: self.addmm(mat1, mat2, beta, 1) + # We store ['self', 'mat1', 'mat2', 'beta', '1'] in this case. + deprecated_args_exprs: tuple[str, ...] + + @property + def deprecated(self) -> bool: + return True + + def signature_str(self, *, skip_outputs: bool = False, symint: bool = True) -> str: + return ( + PythonSignature.signature_str( + self, skip_outputs=skip_outputs, symint=symint + ) + + "|deprecated" + ) + + def signature_str_pyi(self, *, skip_outputs: bool = False) -> str: + args = self.arguments(skip_outputs=skip_outputs) + schema_formals: list[str] = [ + a.argument_str_pyi(method=self.method, deprecated=True) for a in args + ] + positional_argc = len(self.input_args) + if len(schema_formals) > positional_argc: + schema_formals.insert(positional_argc, "*") + + returns_str = returns_str_pyi(self) + return format_function_signature(self.name, schema_formals, returns_str) + + def signature_str_pyi_vararg(self, *, skip_outputs: bool = False) -> str | None: + # the codegen doesn't include vararg variants for deprecated signatures + return None + + +# This struct is used to hold the PythonSignature and its corresponding +# NativeFunction BEFORE grouping base and out-variant functions. +# Why not store NativeFunction in PythonSignature or construct PythonSignature +# from NativeFunction? Because they are not 1-1 mapped. +# One native function could have both deprecated and non-deprecated python +# signatures - NativeFunction doesn't contain information to construct the +# deprecated python signature. +# One python signature is used to handle both the base and the out-variant +# function - see 'PythonSignatureGroup'. +@dataclass(frozen=True) +class PythonSignatureNativeFunctionPair: + signature: PythonSignature + function: NativeFunction + + +# We merge pairs of functions with signatures that are equivalent mod +# output arguments, and use a single entry in the python_arg_parser sig +# list for both (output arguments become optional). +@dataclass(frozen=True) +class PythonSignatureGroup: + # The signature used for Python argument parsing. The outplace signature + # is preferred if exists, because it can be used to parse inputs for both + # the out-place variant and the base version (with output omitted). + signature: PythonSignature + + # The regular ATen declaration (e.g. conv2d) + base: NativeFunction + + # The out variant (e.g. conv2d_out) + outplace: NativeFunction | None + + @classmethod + def from_pairs( + cls, + functional: PythonSignatureNativeFunctionPair, + out: PythonSignatureNativeFunctionPair | None, + ) -> PythonSignatureGroup: + if out is None: + return PythonSignatureGroup( + signature=functional.signature, + base=functional.function, + outplace=None, + ) + + # prefer the signature with optional out=... arguments because it's the + # superset that can be used to parse input for both base and outplace. + signature_kwargs = out.signature.__dict__.copy() + + # Out overloads in C++ don't have TensorOptions arguments, + # so take these from the functional variant + signature_kwargs["tensor_options_args"] = ( + functional.signature.tensor_options_args + ) + + return PythonSignatureGroup( + signature=type(out.signature)(**signature_kwargs), + base=functional.function, + outplace=out.function, + ) + + +# C++ function dispatch is wrapped in a lambda function. The lambda function +# has almost the same signature as the C++ function, only with some small +# variants - see details below. +# This data model is used to represent arguments of the lambda function +# signature. +@dataclass(frozen=True) +class DispatchLambdaArgument: + name: str + type_str: str + is_out_arg: bool + + +# To pass PyObjects arguments to C++ function (via the lambda wrapper), +# we need first convert PyObjects into simple C++ objects. This work +# is done by PythonArgParser. +# This data model is used to represent the output of PythonArgParser. +# It has 1-1 mapping with PythonArgument in PythonSignature. +@dataclass(frozen=True) +class PythonArgParserOutputExpr: + # argument name + name: str + + # RHS expression to reference PythonArgParser output. + expr: str + + # In some special cases we need create different expr, e.g.: + # '_r.isNone(1)' instead of '_r.tensor(1)'. + index: int + + # The python argument it maps to. + argument: PythonArgument + + @property + def is_none_expr(self) -> str: + return f"_r.isNone({self.index})" + + +# To pass PythonArgParser output to the lambda wrapper, we need bind +# PythonArgParserOutputExpr to DispatchLambdaArgument. +# They are not always 1-1 mapped, e.g. scattered TensorOptions fields +# need be packed into a TensorOptions object, which is the argument +# that the lambda function wrapper takes. +@dataclass(frozen=True) +class DispatchLambdaArgumentExprs: + # The exprs that provide the binding for lambda arguments, e.g.: + # + # 'self' -> '_r.tensor(0)' + # 'min' -> 'out[0]' / 'min_indices' -> 'out[1]' + # 'options' -> 'options' + # + # It has 1-1 mapping with DispatchLambdaArgument. + exprs: Sequence[str] + + # Special local inits, which might introduce new variables that + # the 'exprs' above reference, e.g.: + # + # 'auto out = _r.tensorlist_n<2>(2);' + # + inits: Sequence[str] + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Helper Functions +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def _cpp_signature(f: NativeFunction, *, method: bool = False) -> CppSignature: + return CppSignatureGroup.from_native_function(f, method=method).signature + + +def has_tensor_options(f: NativeFunction) -> bool: + return f.func.arguments.tensor_options is not None + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Python Signature +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +# 'simple_type' was introduced by the old codegen, which is slightly +# different from the python schema type, e.g.: doesn't have '?' suffix +# for optional Tensor/TensorList; doesn't have '[size]' suffix for list type. +def argument_type_str( + t: Type, *, simple_type: bool = False, symint: bool = True +) -> str: + if isinstance(t, BaseType): + if t.name == BaseTy.int: + return "int64_t" + elif t.name == BaseTy.float: + return "double" + elif t.name == BaseTy.str: + return "c10::string_view" + elif t.name in [ + BaseTy.Tensor, + BaseTy.bool, + BaseTy.QScheme, + BaseTy.Scalar, + BaseTy.ScalarType, + BaseTy.Generator, + BaseTy.Storage, + BaseTy.Layout, + BaseTy.Device, + BaseTy.DeviceIndex, + BaseTy.MemoryFormat, + BaseTy.Stream, + BaseTy.SymInt, + ]: + # These python schema type names line up with their function schema names + return t.name.name + + elif isinstance(t, OptionalType): + elem = argument_type_str(t.elem, simple_type=simple_type, symint=symint) + return f"{elem}?" + elif isinstance(t, ListType): + size = t.size if not simple_type else None + if str(t.elem) == "bool": + if t.size is None: + raise AssertionError("bool ListType must have a size") + return f"::std::array" + elif str(t.elem) == "int": + return f"IntArrayRef[{size}]" if size is not None else "IntArrayRef" + elif str(t.elem) == "SymInt": + if symint: + return ( + f"SymIntArrayRef[{size}]" if size is not None else "SymIntArrayRef" + ) + else: + return f"IntArrayRef[{size}]" if size is not None else "IntArrayRef" + elif str(t.elem) == "Tensor": + return f"TensorList[{size}]" if size is not None else "TensorList" + elif str(t.elem) == "Scalar": + return f"ScalarList[{size}]" if size is not None else "ScalarList" + elif str(t.elem) == "Tensor?": + if simple_type: + return "c10::List<::std::optional>" + else: + return "const c10::List<::std::optional> &" + elem = argument_type_str(t.elem, simple_type=simple_type, symint=symint) + return f"ArrayRef<{elem}>" + + raise RuntimeError(f"unrecognized type {repr(t)}") + + +def argument_type_size(t: Type) -> int | None: + l = t.is_list_like() + if l is not None and str(l.elem) != "bool": + return l.size + else: + return None + + +def argument(a: Argument) -> PythonArgument: + return PythonArgument( + name=a.name, + type=a.type, + # TODO: directly translate a.default to python default + default=( + str(pythonify_default(cpp.default_expr(a.default, a.type, symint=False))) + if a.default is not None + else None + ), + default_init=None, + ) + + +# Generates a PythonSignature that can be used for either .pyi or PythonArgParser codegen +def signature( + f: NativeFunction, *, method: bool = False, pyi: bool = False +) -> PythonSignature: + return signature_from_schema( + f.func, category_override=f.category_override, method=method, pyi=pyi + ) + + +def signature_from_schema( + func: FunctionSchema, + *, + category_override: str | None, + method: bool = False, + pyi: bool = False, +) -> PythonSignature: + args: list[Argument] = [] + args.extend(func.arguments.pre_self_positional) + # Skip SelfArgument if this is method. + if not method and func.arguments.self_arg is not None: + args.append(func.arguments.self_arg.argument) + args.extend(func.arguments.post_self_positional) + args.extend(func.arguments.pre_tensor_options_kwarg_only) + # Skip TensorOptionsArguments. Python side TensorOptions + # arguments are created based on different rules - see below. + args.extend(func.arguments.post_tensor_options_kwarg_only) + args.extend(func.arguments.out) + + input_arg_set = {a.name for a in func.arguments.flat_positional} + kwarg_only_set = {a.name for a in func.arguments.flat_kwarg_only} + out_arg_set = {a.name for a in func.arguments.out} + + input_args = tuple(map(argument, filter(lambda a: a.name in input_arg_set, args))) + input_kwargs = tuple( + map(argument, filter(lambda a: a.name in kwarg_only_set, args)) + ) + outputs = tuple(map(argument, filter(lambda a: a.name in out_arg_set, args))) + + # Reintroduce the scattered fields of TensorOptions for Python. + # Compared to the cpp counterpart, the python arguments have new property + # (default_init) and a new argument 'requires_grad', which require some + # special handlings. + # [old codegen] TODO: because these aren't guaranteed to be 100% faithful + # to the original versions in the yaml, this recreation is a potential + # source of drift between eager and JIT. Pull this logic out to a shared place. + + has_tensor_input_arg = any( + a.type.is_tensor_like() for a in func.arguments.flat_non_out + ) + if any(a.name == "requires_grad" for a in func.schema_order_arguments()): + raise ValueError( + "argument named requires_grad is reserved, should not explicitly add it in the schema" + ) + + # [old codegen] this probably won't work if one of the returns is not a tensor, + # but it will produce a compile-time error that is obvious. + has_tensor_return = any(r.type.is_tensor_like() for r in func.returns) + + name: str = cpp.name(func) + is_factory_function = category_override == "factory" or ( + has_tensor_return and not has_tensor_input_arg + ) + is_like_or_new_function = ( + category_override in ("new", "like") + or name.startswith("new_") + or name.endswith("_like") + ) + is_dummy_function = category_override == "dummy" + + tensor_options_args: list[PythonArgument] = [] + if (is_factory_function or is_like_or_new_function) and not is_dummy_function: + + def topt_default_init(name: str) -> str | None: + topt_args = func.arguments.tensor_options + if topt_args is None: + return None + a = getattr(topt_args, name) + if a.default is None or a.default == "None": + return None + return cpp.default_expr(a.default, a.type, symint=False) + + tensor_options_args.append( + PythonArgument( + name="dtype", + type=OptionalType(BaseType(BaseTy.ScalarType)), + default="None", + default_init=( + None if is_like_or_new_function else topt_default_init("dtype") + ), + ) + ) + tensor_options_args.append( + PythonArgument( + name="layout", + type=OptionalType(BaseType(BaseTy.Layout)), + default="None", + default_init=( + None if is_like_or_new_function else topt_default_init("layout") + ), + ) + ) + tensor_options_args.append( + PythonArgument( + name="device", + type=OptionalType(BaseType(BaseTy.Device)), + default="None", + default_init=( + None + if is_like_or_new_function + else ( + topt_default_init("device") + or "torch::tensors::get_default_device()" + ) + ), + ) + ) + tensor_options_args.append( + PythonArgument( + name="pin_memory", + type=OptionalType(BaseType(BaseTy.bool)), + default="False", + default_init=None, + ) + ) + tensor_options_args.append( + PythonArgument( + name="requires_grad", + type=OptionalType(BaseType(BaseTy.bool)), + default="False", + default_init=None, + ) + ) + + returns = PythonReturns(returns=func.returns) + + return PythonSignature( + name=str(func.name.name), + input_args=input_args, + input_kwargs=input_kwargs, + output_args=PythonOutArgument.from_outputs(outputs), + tensor_options_args=tuple(tensor_options_args), + returns=returns, + method=method, + ) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Python Interface +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def structseq_fieldnames(returns: tuple[Return, ...]) -> list[str]: + if len(returns) <= 1 or all(r.name is None for r in returns): + return [] + else: + if any(r.name is None for r in returns): + # When building on Windows, `PyStructSequence_UnnamedField` could not be + # resolved by the linker for some reason, which cause error in building: + # + # python_nn_functions.cpp.obj : error LNK2001: unresolved external symbol + # PyStructSequence_UnnamedField + # + # Thus, at this point in time, we do not support unnamed + # fields in structseq; you must either name all fields, + # or none of them. + raise ValueError("Unnamed field is not supported by codegen") + + return [str(r.name) for r in returns] + + +def _append_optional_pyi(type_str: str) -> str: + # Append `| None`, avoiding a doubled `| None` if the type is already optional. + return f"{type_str} | None".replace(" | None | None", " | None") + + +def argument_type_str_pyi(t: Type) -> str: + add_optional = False + if isinstance(t, OptionalType): + t = t.elem + add_optional = True + + ret = "" + if isinstance(t, BaseType): + if t.name in [BaseTy.int, BaseTy.DeviceIndex]: + ret = "_int" + if t.name == BaseTy.SymInt: + ret = "_int | SymInt" + elif t.name == BaseTy.float: + ret = "_float" + elif t.name == BaseTy.str: + ret = "str" + elif t.name == BaseTy.Scalar: + ret = "Number | _complex | PySymType" + elif t.name == BaseTy.ScalarType: + ret = "_dtype" + elif t.name == BaseTy.bool: + ret = "_bool" + elif t.name == BaseTy.QScheme: + ret = "_qscheme" + elif t.name == BaseTy.Layout: + ret = "_layout" + elif t.name == BaseTy.Device: + ret = "DeviceLikeType | None" + elif t.name == BaseTy.MemoryFormat: + ret = "memory_format" + elif t.name == BaseTy.Storage: + ret = "Storage | UntypedStorage" + elif t.name in [BaseTy.Tensor, BaseTy.Generator, BaseTy.Stream]: + # These python schema type names line up with their function schema names + ret = t.name.name + + elif isinstance(t, ListType): + if str(t.elem) == "int": + ret = "_int | _size" if t.size is not None else "_size" + elif t.is_tensor_like(): + # Tensor?[] translates to tuple[Tensor | None, ...] | list[Tensor | None] | None + # Tensor[] translates to tuple[Tensor, ...] | list[Tensor] + if isinstance(t.elem, OptionalType): + add_optional = True + elem_str = "Tensor | None" + else: + elem_str = "Tensor" + ret = ( + f"Tensor | tuple[{elem_str}, ...] | list[{elem_str}]" + if t.size is not None + else f"tuple[{elem_str}, ...] | list[{elem_str}]" + ) + elif str(t.elem) == "float": + ret = "Sequence[_float]" + elif str(t.elem) == "SymInt" and t.size is not None: + elem = argument_type_str_pyi(t.elem) + ret = f"{elem} | Sequence[{elem}]" + else: + elem = argument_type_str_pyi(t.elem) + ret = f"Sequence[{elem}]" + + else: + raise RuntimeError(f"unrecognized type {repr(t)}") + + if add_optional: + ret = _append_optional_pyi(ret) + + return ret + + +def return_type_str_pyi(t: Type) -> str: + # Where arguments are open to accepting Union, return types should return + # concrete types + + if isinstance(t, OptionalType): + inner = return_type_str_pyi(t.elem) + return _append_optional_pyi(inner) + + if isinstance(t, BaseType): + if t.name == BaseTy.Device: + return "_device" + else: + return argument_type_str_pyi(t) + + if isinstance(t, ListType): + inner = return_type_str_pyi(t.elem) + return f"tuple[{inner}, ...]" + + return argument_type_str_pyi(t) + + +def returns_structseq_pyi(signature: PythonSignature) -> tuple[str, str] | None: + python_returns = [return_type_str_pyi(r.type) for r in signature.returns.returns] + structseq_name = signature.name + field_names = structseq_fieldnames(signature.returns.returns) + if field_names: + # These types are structseq objects which act like named NamedTuples, but + # the constructor acts like the constructor of tuple. Using typing.NamedTuple + # does not allow us to override __init__. + seq_type = f"tuple[{', '.join(python_returns)}]" + structseq_def_lines = [ + f"class {structseq_name}({seq_type}): # fmt: skip", + ] + for name, ret_type in zip(field_names, python_returns): + structseq_def_lines.extend( + [ + " @property", + f" def {name}(self) -> {ret_type}: ...", + ] + ) + structseq_def_lines.extend( + [ + " def __new__(", + " cls,", + f" sequence: {seq_type},", + " ) -> Self: # fmt: skip", + " ...", + f" n_fields: Final[_int] = {len(field_names)}", + f" n_sequence_fields: Final[_int] = {len(field_names)}", + " n_unnamed_fields: Final[_int] = 0", + " def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing", + "", # add an extra newline + ] + ) + structseq_def = "\n".join(structseq_def_lines) + # Example: + # structseq_def = ( + # "class max(tuple[Tensor, Tensor]): # fmt: skip\n" + # " @property\n" + # " def values(self) -> Tensor: ...\n" + # " @property\n" + # " def indices(self) -> Tensor: ...\n" + # " def __new__(\n" + # " cls,\n" + # " sequence: tuple[Tensor, Tensor],\n" + # " ) -> Self: # fmt: skip\n" + # " ...\n" + # " n_fields: Final[_int] = 2", + # " n_sequence_fields: Final[_int] = 2", + # " n_unnamed_fields: Final[_int] = 0", + # " def __init_subclass__(cls) -> NoReturn: ... # prohibit subclassing", + # ) + return structseq_name, structseq_def + return None + + +def returns_str_pyi(signature: PythonSignature) -> str: + field_names = structseq_fieldnames(signature.returns.returns) + if field_names: + return f"torch.return_types.{signature.name}" + + python_returns = [return_type_str_pyi(r.type) for r in signature.returns.returns] + if len(python_returns) > 1: + return "tuple[" + ", ".join(python_returns) + "]" + if len(python_returns) == 1: + return python_returns[0] + return "None" + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# C++ Function Dispatch +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# This section provides APIs to generate the code that does C++ function +# dispatch. The C++ function call is wrapped by a lambda function. +# For example: +# +# // aten::selu_(Tensor(a!) self) -> Tensor(a!) +# auto dispatch_selu_ = [](Tensor self) -> Tensor { +# pybind11::gil_scoped_release no_gil; +# return at::selu_(self); +# }; +# +# The lambda function's signature follows the C++ signature in common +# cases, e.g.: +# +# // aten::add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor +# [](const Tensor & self, const Tensor & other, Scalar alpha) -> Tensor +# +# For out variant the 'out' argument's type is changed from 'Tensor &' +# to 'Tensor'. It's because when calling the lambda it passes in the +# PythonArgParser output '_r.tensor(3)', which is stack allocated object +# and needs to pass by value. Also see comments in 'dispatch_lambda_return_str()'. +# +# // aten::add.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) +# [](Tensor out, const Tensor & self, const Tensor & other, Scalar alpha) -> Tensor +# +# For multi-output case it can keep using reference type because the +# PythonArgParser output has been unpacked to local variables, e.g.: +# +# // aten::max.dim_max(Tensor self, int dim, bool keepdim=False, *, +# // Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices) +# [](Tensor & max, Tensor & max_values, const Tensor & self, int64_t dim, bool keepdim) -> std::tuple +# +# For deprecated python signature, it should follow deprecated python arg order. +# TODO: This is to keep same byte-for-byte result as the old codegen - maybe unnecessary? + + +def dispatch_lambda_args( + ps: PythonSignature, f: NativeFunction, symint: bool = True +) -> tuple[DispatchLambdaArgument, ...]: + if isinstance(ps, PythonSignatureDeprecated): + schema = ps.deprecated_schema + else: + schema = f.func + + # Start with cpp arguments - dispatch lambda signature always include 'self' + cpp_args = cpp.arguments( + arguments=schema.arguments, + faithful=False, + symint=symint, + method=False, + cpp_no_default_args=f.cpp_no_default_args, + ) + out_args: set[str] = {a.name for a in schema.arguments.out} + + # Convert from cpp argument to lambda argument + def dispatch_lambda_arg(cpp_arg: Binding) -> DispatchLambdaArgument: + type_str = cpp_arg.type + is_out_arg = cpp_arg.name in out_args + if ps.method and cpp_arg.name == "self": + # For method's 'self', we can use 'const Tensor &' and simply ignore mutability! + type_str = "const at::Tensor &" + else: + # For other cases we need prevent dangling refs to temps (unless it's + # unpacked scattered output) + # The reason is explained in the comments above and in 'dispatch_lambda_return_str()'. + # TODO: avoid this special handling? + ensure_temp_safe = len(out_args) <= 1 or not is_out_arg + if ensure_temp_safe: + type_str = { + "at::Tensor &": "at::Tensor", + }.get(type_str, type_str) + return DispatchLambdaArgument( + name=cpp_arg.name, + type_str=type_str, + is_out_arg=is_out_arg, + ) + + return tuple(map(dispatch_lambda_arg, cpp_args)) + + +# [old codegen] XXX: if you got here because of an assertion failure, it doesn't mean +# it's enough to just extend the list here. Before you do this, make sure +# to add an appropriate wrap() overload in torch/csrc/autograd/utils/wrap_outputs.h. +SUPPORTED_RETURN_TYPES = { + "at::Tensor", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple", + "::std::tuple>", + "::std::vector", + # Needed for flash attention forw/backward + "::std::tuple", + "at::Scalar", + "bool", + "int64_t", + "void*", + "void", + "at::QScheme", + "double", + "at::IntArrayRef", + "at::ScalarType", + "at::Stream", +} + + +def dispatch_lambda_return_str(f: NativeFunction) -> str: + # [old codegen] Remove type annotation (e.g. 'Tensor' rather than 'Tensor &') + # because the dispatch lambdas take mutable arguments *by value*, not + # by reference. If you then return a reference to such an argument, you + # will now have a pointer to a dangling stack entry. Not good. + # + # You want: + # + # auto dispatch_selu_ = [](Tensor self) -> Tensor { ...; return at::selu_(self); }; + # ^^^^^^ + # + # *not* + # + # auto dispatch_selu_ = [](Tensor self) -> Tensor& { ...; return at::selu_(self); }; + # ^^^^^^^ + # + # (NB: We can't make dispatch_selu_ take Tensor&, because the enclosing + # codegen looks like dispatch_selu_(_r.tensor(0)), and you can't take a + # mutable reference to temporary. Maybe we could assign it to a + # variable itself.) + returns_without_annotation = tuple( + Return(r.name, r.type, None) for r in f.func.returns + ) + return_str = cpp.returns_type(returns_without_annotation, symint=True).cpp_type() + if return_str not in SUPPORTED_RETURN_TYPES: + raise RuntimeError(f"{f.func.name} returns unsupported type {return_str}") + return return_str + + +def cpp_dispatch_target(f: NativeFunction) -> str: + symint = f.func.has_symint() + name = cpp.name(f.func, symint_overload=symint) + if Variant.method in f.variants: + return f"self.{name}" + if Variant.function in f.variants: + if has_tensor_options(f) or f.func.name.name.base.endswith("_like"): + namespace = "torch" + else: + namespace = "at" + return f"{namespace}::{name}" + raise RuntimeError(f"could not dispatch, neither function nor method: {f.func}") + + +def cpp_dispatch_exprs( + f: NativeFunction, + *, + python_signature: PythonSignature | None = None, +) -> tuple[str, ...]: + cpp_args: Sequence[Binding] = _cpp_signature(f, method=False).arguments() + + exprs: tuple[str, ...] = () + if not isinstance(python_signature, PythonSignatureDeprecated): + # By default the exprs are consistent with the C++ signature. + exprs = tuple(a.name for a in cpp_args) + else: + # For deprecated python signature we may need fill in some constants. + exprs = tuple( + filter( + lambda n: n != "out" or f.func.is_out_fn(), + python_signature.deprecated_args_exprs, + ) + ) + + if Variant.method in f.variants: + exprs = tuple(filter("self".__ne__, exprs)) + + return exprs + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Python / C++ Args Binding +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +# We explicitly enumerate the PythonArgParser unpacking methods for all +# supported types. This might be more verbose than necessary, partially +# because of the irregularity of unpacking method naming, partially +# because we want to mimic the old codegen behavior - to reject +# unexpected and/or unsupported cases which the old codegen rejects. +# For certain cases it is intentionally more restrictive than necessary, +# e.g.: it doesn't accepts doublelist with definite size. +def arg_parser_unpack_method( + t: Type, default: str | None, default_init: str | None, *, symint: bool = True +) -> str: + has_default_init = default_init is not None + if has_default_init and str(t) not in ( + "ScalarType?", + "ScalarType", + "Device", + "Device?", + "Layout", + "Layout?", + "bool", + "bool?", + ): + raise RuntimeError(f"type '{t}' does not supported unpacking with default") + + if isinstance(t, BaseType): + if t.name in [ + BaseTy.Tensor, + BaseTy.Stream, + BaseTy.Storage, + BaseTy.Scalar, + ]: + # These unpack methods line up with their schema names + return t.name.name.lower() + elif t.name == BaseTy.ScalarType: + return "scalartypeWithDefault" if has_default_init else "scalartype" + elif t.name == BaseTy.Device: + return "deviceWithDefault" if has_default_init else "device" + elif t.name == BaseTy.DeviceIndex: + return "toInt64" + elif t.name == BaseTy.int: + return "toInt64" + elif t.name == BaseTy.SymInt: + return "toSymInt" if symint else "toInt64" + elif t.name == BaseTy.bool: + return "toBoolWithDefault" if has_default_init else "toBool" + elif t.name == BaseTy.float: + return "toDouble" + elif t.name == BaseTy.str: + return "stringView" + elif t.name == BaseTy.Layout: + return "layoutWithDefault" if has_default_init else "layout" + elif t.name == BaseTy.MemoryFormat: + return "memoryformat" + + elif isinstance(t, OptionalType): + if str(t.elem) == "Tensor": + return "optionalTensor" + elif str(t.elem) == "Generator": + return "generator" + elif not has_default_init and default in ( + None, + "None", + "::std::nullopt", + "std::nullopt", + ): + # If default is None: append 'Optional' to elem's unpacking method + return ( + arg_parser_unpack_method(t.elem, None, None, symint=symint) + "Optional" + ) + else: + # Otherwise, load as underlying type with default + return arg_parser_unpack_method( + t.elem, default, default_init, symint=symint + ) + + elif isinstance(t, ListType): + if str(t.elem) == "Tensor": + # accept and use definite size + return f"tensorlist_n<{t.size}>" if t.size is not None else "tensorlist" + elif str(t.elem) == "Tensor?": + return "list_of_optional_tensors" + elif str(t.elem) == "int": + # accept definite size + return "intlist" + elif str(t.elem) == "float": + return "doublelist" + elif str(t.elem) == "SymInt": + # accept definite size + return "symintlist" if symint else "intlist" + elif str(t.elem) == "Scalar": + return "scalarlist" + raise RuntimeError(f"type '{t}' is not supported by PythonArgParser") + + +# Return RHS expression for python argument using PythonArgParser output. +# e.g. for arg name 'foo', arg type 'bool', arg_index = 2, returns '_r.toBool(2)' +def arg_parser_output_expr( + arg_index: int, a: PythonArgument, *, symint: bool = True +) -> PythonArgParserOutputExpr: + has_default = a.default_init is not None + unpack_method = arg_parser_unpack_method( + t=a.type, default=a.default, default_init=a.default_init, symint=symint + ) + default = f", {a.default_init}" if has_default else "" + expr = f"_r.{unpack_method}({arg_index}{default})" + + return PythonArgParserOutputExpr( + name=a.name, + expr=expr, + index=arg_index, + argument=a, + ) + + +# Returns a map with key = arg_name and value = PythonArgParserOutputExpr. +def arg_parser_output_exprs( + ps: PythonSignature, f: NativeFunction, *, symint: bool = True +) -> dict[str, PythonArgParserOutputExpr]: + return { + e.name: e + for i, a in enumerate(ps.arguments()) + for e in (arg_parser_output_expr(i, a, symint=symint),) + } + + +# argument name to type for scattered tensor options fields +TENSOR_OPTIONS_FIELDS = { + "dtype": "ScalarType?", + "device": "Device?", + "layout": "Layout?", + "pin_memory": "bool?", + "requires_grad": "bool?", +} + + +# bind arg parser outputs (python args) with dispatch lambda arguments (c++ args). +def dispatch_lambda_exprs( + ps: PythonSignature, f: NativeFunction, *, symint: bool = True +) -> DispatchLambdaArgumentExprs: + # This method is to bind 'arg_parser_outputs' and 'lambda_args' by producing + # 'inits' and 'lambda_args_exprs' for each lambda argument using arg parser + # outputs. + arg_parser_outputs = arg_parser_output_exprs(ps, f, symint=symint) + lambda_args = dispatch_lambda_args(ps, f, symint=symint) + inits: list[str] = [] + lambda_args_exprs: dict[str, str] = {} + + has_toptions = has_tensor_options(f) + + # 1. special inits/unpacking to provide binding exprs for lambda arguments. + for a in ps.arguments(skip_tensor_options=True): + name = a.name + arg_parser_expr = arg_parser_outputs[a.name].expr + + if has_toptions and name == "self": + # TODO: why this needs to be special case? + inits.extend( + [ + f"auto self = {arg_parser_expr};", + ] + ) + lambda_args_exprs[name] = name + elif ( + isinstance(a, PythonOutArgument) + and len(a.outputs) > 1 + and f.func.is_out_fn() + ): + inits.extend( + [ + f"auto out = {arg_parser_expr};", + ] + ) + for i, out_arg in enumerate(a.outputs): + lambda_args_exprs[out_arg.name] = f"out[{i}]" + else: + # default case - directly using PythonArgParser output expr + lambda_args_exprs[name] = arg_parser_expr + + # method's self is passed directly to python binding, rather than parsed + if ps.method: + lambda_args_exprs["self"] = "self" + + # 2. special packing/checking for TensorOptions. + tensor_options_args_names = [a.name for a in ps.tensor_options_args] + if has_toptions: + if f.func.is_out_fn(): + raise RuntimeError(f"{f.func}: tensor options with output arg") + for a in ps.tensor_options_args: + if a.name not in TENSOR_OPTIONS_FIELDS: + raise RuntimeError( + f"{f.func}: unrecognized tensor options field '{a.name}' in python binding arguments" + ) + if str(a.type) != TENSOR_OPTIONS_FIELDS.get(a.name): + raise RuntimeError( + f"{f.func}: unrecognized type '{str(a.type)}' for tensor options field '{a.name}'" + ) + if not all(a in tensor_options_args_names for a in TENSOR_OPTIONS_FIELDS): + raise RuntimeError( + f"{f.func}: incomplete tensor options args: {tensor_options_args_names}" + ) + + maybe_initialize_device = ( + """\ +if (!at::impl::tensor_has_dispatch(self)) { + torch::utils::maybe_initialize_device(options); +} +""" + if ps.method + else "torch::utils::maybe_initialize_device(options);\n" + ) + + inits.append( + f"""\ +const auto options = TensorOptions() + .dtype({arg_parser_outputs["dtype"].expr}) + .device({arg_parser_outputs["device"].expr}) + .layout({arg_parser_outputs["layout"].expr}) + .requires_grad({arg_parser_outputs["requires_grad"].expr}) + .pinned_memory({arg_parser_outputs["pin_memory"].expr}); +{maybe_initialize_device}\ +""" + ) + lambda_args_exprs["options"] = "options" + + # 3. special case - access scattered TensorOptions fields without packing + # TODO: maybe move to the generator side as it's not related to binding. + if not has_toptions and tensor_options_args_names: + if "dtype" in tensor_options_args_names: + # we're an output-arg variant, check these args against output tensor + if not f.func.is_out_fn(): + raise RuntimeError( + f"{f.func}: dtype in tensor_options_args without output arg, {ps} {ps.arguments}" + ) + if not all(a in tensor_options_args_names for a in ("layout", "device")): + raise RuntimeError( + f"{f.func}: incomplete tensor options for output check" + ) + + inits.append( + f"""\ +check_out_type_matches({arg_parser_outputs["out"].expr}, {arg_parser_outputs["dtype"].expr}, + {arg_parser_outputs["dtype"].is_none_expr}, {arg_parser_outputs["layout"].expr}, + {arg_parser_outputs["device"].expr}, {arg_parser_outputs["device"].is_none_expr}); +""" + ) + # we'll set requires_grad on outgoing tensor + if "requires_grad" not in tensor_options_args_names: + raise RuntimeError( + f'{f.func}: expected "requires_grad" in tensor_options_args absent, but found [{tensor_options_args_names}]' + ) + + return DispatchLambdaArgumentExprs( + exprs=tuple(lambda_args_exprs[a.name] for a in lambda_args), + inits=inits, + ) diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/structured.py b/.venv/lib/python3.12/site-packages/torchgen/api/structured.py new file mode 100644 index 0000000000000000000000000000000000000000..828827a1f295fb693bfba522a9d9c39ff88c9a3a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/structured.py @@ -0,0 +1,155 @@ +from __future__ import annotations + +from typing_extensions import assert_never + +from torchgen.api import cpp +from torchgen.api.types import ( + ArgName, + ArrayRefCType, + BaseCType, + Binding, + ConstRefCType, + intArrayRefT, + iOptTensorListRefT, + iTensorListRefT, + NamedCType, + OptionalCType, + optionalIntArrayRefT, + optionalScalarRefT, + optionalTensorRefT, + scalarT, + tensorT, +) +from torchgen.model import ( + Argument, + BaseTy, + BaseType, + ListType, + NativeFunctionsGroup, + OptionalType, + SelfArgument, + TensorOptionsArguments, + Type, +) + + +# This file describes the translation of JIT schema to the structured functions API. +# This is similar to native API, but a number of historical problems with native +# API have been fixed. + + +# Translation of types occurring in JIT arguments to a C++ argument type. +# NB: For now, mutable doesn't do anything; but it could if we make +# some more nominal types +def argumenttype_type(t: Type, *, mutable: bool, binds: ArgName) -> NamedCType: + # If it's a value type, do the value type translation + # NB: structured kernels ALWAYS have symint off, since they involve actual + # kernels that require real ints. The one exception is the + # CompositeExplicitAutograd and the meta function (which could + # hypothetically be SymInt), but for simplicity we plan for these to just + # be handled in Python + r = cpp.valuetype_type(t, symint=False, binds=binds, mutable=mutable) + if r is not None: + return r + + if isinstance(t, BaseType): + if t.name == BaseTy.Tensor: + return NamedCType(binds, ConstRefCType(BaseCType(tensorT))) + elif t.name == BaseTy.Scalar: + return NamedCType(binds, ConstRefCType(BaseCType(scalarT))) + else: + raise AssertionError(f"base type should have been value type {t}") + elif isinstance(t, OptionalType): + if t.elem == BaseType(BaseTy.Tensor): + return NamedCType(binds, BaseCType(optionalTensorRefT)) + elif t.elem == BaseType(BaseTy.Scalar): + return NamedCType(binds, BaseCType(optionalScalarRefT)) + elif isinstance(t.elem, ListType) and str(t.elem.elem) == "int": + return NamedCType(binds, BaseCType(optionalIntArrayRefT)) + elem = argumenttype_type(t.elem, mutable=mutable, binds=binds) + return NamedCType(binds, OptionalCType(elem.type)) + elif isinstance(t, ListType): + if t.elem == BaseType(BaseTy.Tensor): + return NamedCType(binds, ConstRefCType(BaseCType(iTensorListRefT))) + elif t.elem == OptionalType(BaseType(BaseTy.Tensor)): + return NamedCType(binds, BaseCType(iOptTensorListRefT)) + # TODO: delete these special cases; see torchgen.api.cpp--these + # must be changed in tandem, but there are problems; see + # https://github.com/pytorch/pytorch/pull/51485 + elif str(t.elem) == "int": + return NamedCType(binds, BaseCType(intArrayRefT)) + elem = argumenttype_type(t.elem, mutable=mutable, binds=binds) + return NamedCType(binds, ArrayRefCType(elem.type)) + else: + raise AssertionError(f"unrecognized type {repr(t)}") + + +def argument_type(a: Argument, *, binds: ArgName) -> NamedCType: + return argumenttype_type(a.type, mutable=a.is_write, binds=binds) + + +# returns_type intentionally omitted, because structured kernels never "return"; +# instead, they always indirectly report their outputs (in the case of a meta +# function, by calling set_output; in the case of an impl function, by writing +# directly into the provided out argument). + + +# Structured kernels are never defaulted +def argument(a: Argument | SelfArgument | TensorOptionsArguments) -> list[Binding]: + if isinstance(a, Argument): + return [ + Binding( + nctype=argument_type(a, binds=a.name), + name=a.name, + default=None, + argument=a, + ) + ] + elif isinstance(a, SelfArgument): + return argument(a.argument) + elif isinstance(a, TensorOptionsArguments): + raise AssertionError("structured kernels don't support TensorOptions yet") + else: + assert_never(a) + + +def impl_arguments(g: NativeFunctionsGroup) -> list[Binding]: + args: list[Argument | TensorOptionsArguments | SelfArgument] = [] + + if g.out.precomputed: + # A list of parameters for the impl function with + # certain parameters replaced with precomputed counterparts + # as specified in native_functions.yaml. + non_out_args_replaced: list[ + Argument | TensorOptionsArguments | SelfArgument + ] = [] + for a in g.out.func.arguments.non_out: + if isinstance(a, Argument) and a.name in g.out.precomputed.replace: + # If a is in precompute.replace, append the parameters + # that should replace it onto non_out_args_replaced. + non_out_args_replaced.extend(g.out.precomputed.replace[a.name]) + else: + # If not, push a as it is. + non_out_args_replaced.append(a) + + args.extend(non_out_args_replaced) + # g.out.precomputed.add is the list of parameters that are added + # without replacement after the non out args and just before the out args + args.extend(g.out.precomputed.add) + else: + args.extend(g.out.func.arguments.non_out) + + args.extend(g.out.func.arguments.out) + return [r for arg in args for r in argument(arg)] + + +def meta_arguments(g: NativeFunctionsGroup) -> list[Binding]: + args: list[Argument | TensorOptionsArguments | SelfArgument] = [] + args.extend(g.functional.func.arguments.non_out) + return [r for arg in args for r in argument(arg)] + + +def out_arguments(g: NativeFunctionsGroup) -> list[Binding]: + args: list[Argument | TensorOptionsArguments | SelfArgument] = [] + args.extend(g.out.func.arguments.out) + return [r for arg in args for r in argument(arg)] diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/translate.py b/.venv/lib/python3.12/site-packages/torchgen/api/translate.py new file mode 100644 index 0000000000000000000000000000000000000000..9de2f0dbda476ac8af639cdba67f90c4be36f07b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/translate.py @@ -0,0 +1,447 @@ +from __future__ import annotations + +from typing import NoReturn, TYPE_CHECKING + +from torchgen.api.types import ( + ArrayRefCType, + BaseCType, + Binding, + boolT, + ConstRefCType, + deviceT, + Expr, + intArrayRefT, + iOptTensorListRefT, + layoutT, + ListCType, + longT, + memoryFormatT, + MutRefCType, + NamedCType, + opmath_t, + OptionalCType, + optionalIntArrayRefT, + optionalScalarRefT, + optionalSymIntArrayRefT, + optionalTensorRefT, + scalar_t, + scalarT, + scalarTypeT, + SpecialArgName, + symIntArrayRefT, + SymIntT, + tensorOptionsT, + tensorT, + VectorCType, +) + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +# This file implements a small program synthesis engine that implements +# conversions between one API to another. +# +# The key data type in this file in NamedCType, short for Named C++ semantic type. A NamedCType +# represents a C++ type, plus semantic information about what it represents. +# For example, consider the argument "bool pin_memory"; its normal C++ type is +# "bool", but its C++ semantic type also keeps track that this represents a +# "pin_memory"; you can't just use a random other boolean in a context where you +# need a "pin_memory"! +# +# The translator takes a list of needed NamedCTypes, and then figures out how +# to construct expressions with these NamedCTypes from the given bindings. Many +# of these expressions are trivial (I need a Tensor other; there's a Tensor +# other scope); others are more nontrivial and may require packing/unpacking. +# Some examples of non-trivial action: +# +# - Need the "dtype" binding? Well, maybe "dtype" isn't available +# in the context, instead, "options" is, and you need to extract +# it from there. (Gather) +# +# - Need the "context" binding? Well, maybe "context" isn't available +# in the context, and you need to construct it from "dtype", "device", +# etc. (Scatter) +# +# - Need the "memory_format" binding? Well, actually, it's available +# from both "memory_format" and "options", so you had better make sure +# they are consistent. (Join) + +options_ctype = NamedCType("options", ConstRefCType(BaseCType(tensorOptionsT))) + +out_tensor_ctype = NamedCType("out", ConstRefCType(BaseCType(tensorT))) + +longVec_ctype = VectorCType(BaseCType(longT)) +longSymVec_ctype = VectorCType(BaseCType(SymIntT)) +optionalLongVec_ctype = OptionalCType(VectorCType(BaseCType(longT))) +optionalScalar_ctype = OptionalCType(BaseCType(scalarT)) +optionalTensor_ctype = OptionalCType(BaseCType(tensorT)) + + +class UnsatError(RuntimeError): + pass + + +# Given a set of in-scope bindings and a set of target bindings, synthesize +# a list of expressions that uses only the in-scope bindings (bindings) that +# have all of the types of goals. You may want to use this function if +# you're generating code for a function like: +# +# void f({args}) { +# g({exprs}); // g is a different API +# } +# +# and you need to generate "exprs". +# +# Typically, a list of Bindings is convenient to get (you usually call something +# like arguments() to get them); but technically you only need less information: +# for 'bindings' an (un-ordered) list of Exprs is sufficient; similarly, for +# 'goals', an (ordered) list of NamedCType goals is sufficient. If you are doing +# something more complicated, e.g., tracking the set of bindings in a context, +# you may find using these smaller types more convenient. +def translate( + bindings: Sequence[Expr | Binding], + goals: Sequence[NamedCType | Binding], + *, + method: bool = False, + allow_expensive_conversions: bool = False, +) -> list[Expr]: + binding_exprs: list[Expr] = [] + for b in bindings: + if isinstance(b, Binding): + binding_exprs.append( + Expr( + expr=b.name, + type=b.nctype, + ) + ) + else: + binding_exprs.append(b) + + goal_ctypes: list[NamedCType] = [] + for g in goals: + if isinstance(g, Binding): + goal_ctypes.append(g.nctype) + else: + goal_ctypes.append(g) + + # Add all the bindings to the context + ctx: dict[NamedCType, str] = {} + for b in binding_exprs: + ctx[b.type] = b.expr + + # While we're at it, do some simple forward inference, looking through + # constructors. + # + # NB: When should you do forward inference versus backward inference? + # The general idea: + # + # - Backward inference WHEN the goal gets smaller + # - Forward inference WHEN the hypothesis gets smaller + # + # This helps ensure termination: backward inference starts with a goal + # and tries to make it simpler and simpler until it's trivial; if the + # goal can grow in size, we blow up to a really huge goal size. + # Similarly, with forward inference we take hypotheses and decompose + # them into simpler hypotheses; if hypotheses could expand in size, + # we also have potential nontermination. (In the code below, forward + # inference is only ever carried out at a single step, but you could + # imagine repeated application of forward inference being profitable.) + # + # A good starting point in the literature for exploring more about proof + # search are these lecture notes + # https://www.cs.cmu.edu/~fp/courses/oregon-m10/04-focusing.pdf + # + # TODO: My kingdom for a pattern matcher + # https://www.python.org/dev/peps/pep-0634/ + # + # TODO: This could get us in recomputation trouble if b.expr is nontrivial. + # Fix this by implementing some sort of sharing so that if multiple + # goals share the same expression, we only compute it once. This seems + # to matter in practice as compiler is often unwilling to CSE nontrivial + # expressions like scalar.to() + t = b.type + if ( + isinstance(t, ConstRefCType) + and isinstance(t.elem, OptionalCType) + and isinstance(t.elem.elem, BaseCType) + and str(t.elem.elem.type) == "at::Tensor" + ): + ctx[NamedCType(t.elem.elem.name, ConstRefCType(BaseCType(tensorT)))] = ( + f"({b.expr}.has_value() ? *{b.expr} : at::Tensor())" + ) + + if t.type == ConstRefCType(OptionalCType(BaseCType(tensorT))): + ctx[NamedCType(t.name, BaseCType(optionalTensorRefT))] = ( + f"(({b.expr}.has_value() && (*{b.expr}).defined()) ? at::OptionalTensorRef(*{b.expr}) : at::OptionalTensorRef())" + ) + + if t.type == ConstRefCType(BaseCType(scalarT)): + ctx[NamedCType(t.name, BaseCType(opmath_t))] = f"({b.expr}).to()" + + if t.type == ConstRefCType(OptionalCType(BaseCType(scalarT))): + ctx[NamedCType(t.name, BaseCType(optionalScalarRefT))] = ( + f"({b.expr}.has_value() ? at::OptionalScalarRef(&({b.expr}.value())) : at::OptionalScalarRef())" + ) + + if t.type == BaseCType(scalar_t): + ctx[NamedCType(t.name, BaseCType(opmath_t))] = ( + f"static_cast({b.expr})" + ) + + # [Note: IOptTensorListRef] + if t.type == ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT)))): + ctx[NamedCType(t.name, BaseCType(iOptTensorListRefT))] = ( + f"at::IOptTensorListRef({b.expr})" + ) + + # Add implicit bindings if the generated code is inside a Tensor method + if method: + ctx[NamedCType("self", MutRefCType(BaseCType(tensorT)))] = ( + "const_cast(*this)" + ) + ctx[NamedCType("self", ConstRefCType(BaseCType(tensorT)))] = ( + "const_cast(*this)" + ) + # This is better! Byte-for-byte compat + # ctx[NamedCType("self", ConstRefCType(BaseCType(tensorT)))] = "*this" + + def unsat(goal: NamedCType) -> NoReturn: + ctx_desc = "\n".join( + f" {t.cpp_type()} {t.name}; // {e}" for t, e in ctx.items() + ) + raise UnsatError( + f""" +Failed to synthesize the expression "{goal.cpp_type()} {goal.name}". +When I failed, the following bindings were available in the context: + +{ctx_desc} + +This probably means there is a missing rule in the rules of torchgen.api.translate. +Check this module for more information. +""" + ) + + # A shitty backtracking search implementation. It's shitty because it + # does backtracking via stack (bad idea!) and for the most part tries to + # avoid backtracking. In particular, if + # direct=True, we won't try to do any fancy synthesis, just trivial + # conversions (e.g., "T a" is OK for "const T& a"). So all of the + # existing rules in this function simply try to solve immediately, + # and bail if things don't work out. + def solve(goal: NamedCType, *, direct: bool) -> str: + def direct_solve(goal: NamedCType) -> str: + return solve(goal, direct=True) + + if goal in ctx: + # Trivial + return ctx[goal] + + # const & is satisfied with mutable & + if isinstance(goal.type, ConstRefCType): + try: + # WARNING: not strictly decreasing; be careful not + # to add a direct conversion that goes satisfies + # mutable& with const& + return solve( + NamedCType(goal.name, MutRefCType(goal.type.elem)), direct=direct + ) + except UnsatError: + pass + + # mutable & is satisfied with value + if isinstance(goal.type, MutRefCType): + try: + return solve(NamedCType(goal.name, goal.type.elem), direct=direct) + except UnsatError: + pass + + # TODO: These are referentially equal, shouldn't have to do this; + # ensuring we don't use type synonym IntArrayRef in codegen would + # help + if goal.type == ArrayRefCType(BaseCType(longT)): + return solve(NamedCType(goal.name, BaseCType(intArrayRefT)), direct=direct) + + if direct: + unsat(goal) + + # For now, all of these rules are mutually exclusive. + if goal == NamedCType("memory_format", OptionalCType(BaseCType(memoryFormatT))): + memory_format = direct_solve( + NamedCType( + SpecialArgName.possibly_redundant_memory_format, + OptionalCType(BaseCType(memoryFormatT)), + ) + ) + # No need to join "memory_format" and "options" if the target API takes "options" directly. + # Otherwise it will cause the redundant memory_format error. + if options_ctype in goal_ctypes: + return memory_format + try: + options = direct_solve(options_ctype) + return f"c10::impl::check_tensor_options_and_extract_memory_format({options}, {memory_format})" + except UnsatError: + return memory_format + elif goal == NamedCType("options", BaseCType(tensorOptionsT)): + dtype = direct_solve( + NamedCType("dtype", OptionalCType(BaseCType(scalarTypeT))) + ) + pin_memory = direct_solve( + NamedCType("pin_memory", OptionalCType(BaseCType(boolT))) + ) + device = direct_solve( + NamedCType("device", OptionalCType(BaseCType(deviceT))) + ) + layout = direct_solve( + NamedCType("layout", OptionalCType(BaseCType(layoutT))) + ) + return f"TensorOptions().dtype({dtype}).layout({layout}).device({device}).pinned_memory({pin_memory})" + + elif goal == NamedCType("dtype", OptionalCType(BaseCType(scalarTypeT))): + try: + options = direct_solve(options_ctype) + return f"c10::optTypeMetaToScalarType({options}.dtype_opt())" + except UnsatError: + out_tensor = direct_solve(out_tensor_ctype) + return f"{out_tensor}.scalar_type()" + + elif goal == NamedCType("layout", OptionalCType(BaseCType(layoutT))): + try: + options = direct_solve(options_ctype) + return f"{options}.layout_opt()" + except UnsatError: + out_tensor = direct_solve(out_tensor_ctype) + return f"{out_tensor}.layout()" + + elif goal == NamedCType("device", OptionalCType(BaseCType(deviceT))): + try: + options = direct_solve(options_ctype) + return f"{options}.device_opt()" + except UnsatError: + out_tensor = direct_solve(out_tensor_ctype) + return f"{out_tensor}.device()" + + elif goal == NamedCType("pin_memory", OptionalCType(BaseCType(boolT))): + try: + options = direct_solve(options_ctype) + return f"{options}.pinned_memory_opt()" + except UnsatError: + # If we're calling a factory op from its out= variant, + # We don't actually care about the value of pin_memory. + out_tensor = direct_solve(out_tensor_ctype) + return "::std::nullopt" + + # We can always do translations from value types to reference types, like vector -> IntArrayRef + elif goal.type == BaseCType(intArrayRefT): + try: + return direct_solve(NamedCType(goal.name, longVec_ctype)) + except UnsatError: + # We can also go SymIntArrayRef -> IntArrayRef + symIntArrayRef_type = direct_solve( + NamedCType(goal.name, BaseCType(symIntArrayRefT)) + ) + return f"C10_AS_INTARRAYREF_SLOW({symIntArrayRef_type})" + elif goal.type == BaseCType(symIntArrayRefT): + try: + r = direct_solve(NamedCType(goal.name, BaseCType(intArrayRefT))) + return f"c10::fromIntArrayRefSlow({r})" + except UnsatError: + return direct_solve(NamedCType(goal.name, longSymVec_ctype)) + elif goal.type == BaseCType(SymIntT): + return direct_solve(NamedCType(goal.name, BaseCType(longT))) + elif goal.type == OptionalCType(BaseCType(SymIntT)): + argname = direct_solve( + NamedCType(goal.name, OptionalCType(BaseCType(longT))) + ) + return f"{argname}.has_value() ? ::std::make_optional(c10::SymInt(*{argname})) : ::std::nullopt" + elif goal.type == BaseCType(longT): + symInt_type = direct_solve(NamedCType(goal.name, BaseCType(SymIntT))) + return f"{symInt_type}.guard_int(__FILE__, __LINE__)" + elif goal.type == OptionalCType(BaseCType(longT)): + argname = direct_solve( + NamedCType(goal.name, OptionalCType(BaseCType(SymIntT))) + ) + return f"{argname}.has_value() ? ::std::make_optional({argname}->guard_int(__FILE__, __LINE__)) : ::std::nullopt" + elif goal.type == BaseCType(optionalIntArrayRefT): + try: + return direct_solve(NamedCType(goal.name, optionalLongVec_ctype)) + except UnsatError: + argname = direct_solve( + NamedCType(goal.name, BaseCType(optionalSymIntArrayRefT)) + ) + return f"{argname}.has_value() ? ::std::make_optional(C10_AS_INTARRAYREF_SLOW(*{argname})) : ::std::nullopt" + elif goal.type == BaseCType(optionalSymIntArrayRefT): + # TODO: You might also want to solve this from longSymVec_ctype or + # an optional version of it + argname = direct_solve( + NamedCType(goal.name, BaseCType(optionalIntArrayRefT)) + ) + return f"{argname}.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*{argname})) : ::std::nullopt" + elif goal.type == BaseCType(optionalScalarRefT): + return direct_solve(NamedCType(goal.name, optionalScalar_ctype)) + elif goal.type == BaseCType(optionalTensorRefT): + return direct_solve(NamedCType(goal.name, optionalTensor_ctype)) + + # Note [translation from C++ reference to value types] + # The below cases are all for when we have an argument with a reference type, + # and a corresponding goal with a value type. + # These are needed when we populate the inputs to a lambda capture and we need + # to guarantee the lifetime of each captured argument. + # We guard it with an explicit kwarg because converting to a value type is expensive + # (O(n)) to convert from IntArrayRef to vector), + # so the caller of translate() should be explicit that they need it. + if allow_expensive_conversions: + if goal.type == VectorCType(BaseCType(longT)): + intArrayRef_ctype = NamedCType(goal.name, BaseCType(intArrayRefT)) + argname = direct_solve(intArrayRef_ctype) + return f"{argname}.vec()" + if goal.type == VectorCType(BaseCType(SymIntT)): + symIntArrayRef_ctype = NamedCType(goal.name, BaseCType(symIntArrayRefT)) + argname = direct_solve(symIntArrayRef_ctype) + return f"{argname}.vec()" + if goal.type == BaseCType(tensorT): + const_ref_tensor_ctype = NamedCType( + goal.name, ConstRefCType(BaseCType(tensorT)) + ) + return direct_solve(const_ref_tensor_ctype) + if goal.type == OptionalCType(BaseCType(tensorT)): + const_ref_optional_tensor_ctype = NamedCType( + goal.name, ConstRefCType(OptionalCType(BaseCType(tensorT))) + ) + return direct_solve(const_ref_optional_tensor_ctype) + elif goal.type == OptionalCType(VectorCType(BaseCType(longT))): + optionalIntArrayRef_ctype = NamedCType( + goal.name, BaseCType(optionalIntArrayRefT) + ) + argname = direct_solve(optionalIntArrayRef_ctype) + return f"{argname}.has_value() ? ::std::make_optional({argname}->vec()) : ::std::nullopt" + elif goal.type == OptionalCType(BaseCType(scalarT)): + optionalScalarRef_ctype = NamedCType( + goal.name, BaseCType(optionalScalarRefT) + ) + argname = direct_solve(optionalScalarRef_ctype) + return f"{argname}.has_value() ? ::std::make_optional({argname}) : ::std::nullopt" + elif goal.type == OptionalCType(BaseCType(tensorT)): + optionalTensorRef_ctype = NamedCType( + goal.name, BaseCType(optionalTensorRefT) + ) + argname = direct_solve(optionalTensorRef_ctype) + return f"{argname}.has_value() ? ::std::make_optional({argname}) : ::std::nullopt" + # Technically, we also need to handle cases of C++ containers holding reference types. + # But there currently aren't any ops that require lambda capture codegen + # With arguments like ::std::vector. + # If that changes, we'll have to add the translation here. + + # We allow const casting on tensors, since const-correctness is a bit broken for at::Tensor. + # We could probably generalize this to non-tensor types too. + if goal.type == MutRefCType(BaseCType(tensorT)): + const_ref_tensor_ctype = NamedCType( + goal.name, ConstRefCType(BaseCType(tensorT)) + ) + argname = direct_solve(const_ref_tensor_ctype) + return f"const_cast({argname})" + + unsat(goal) + + return [Expr(solve(g, direct=False), g) for g in goal_ctypes] diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/types/__init__.py b/.venv/lib/python3.12/site-packages/torchgen/api/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e98bb8df493f2375b514e6c6aeb897cebe8ec7d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/types/__init__.py @@ -0,0 +1,5 @@ +from torchgen.api.types.types import * +from torchgen.api.types.types_base import * + + +from torchgen.api.types.signatures import * # usort: skip diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8167e696c516ba21b8712b3c3d18f07e0257986 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/signatures.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/signatures.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5304b08e785b720cc8385b50a36e1c9e3b25640 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/signatures.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/types.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b0f7e22b0a5c1a330148fe82a6088d9aacae8b1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/types.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/types_base.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/types_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e07401674c4b779bc7452f432158a889b55f0c3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/api/types/__pycache__/types_base.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/types/signatures.py b/.venv/lib/python3.12/site-packages/torchgen/api/types/signatures.py new file mode 100644 index 0000000000000000000000000000000000000000..2eb6e926fc3a327287b73793e223b6d6f0b8d39c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/types/signatures.py @@ -0,0 +1,358 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from torchgen.api.types.types_base import Binding, CType, Expr + + +if TYPE_CHECKING: + from collections.abc import Iterator, Sequence + + from torchgen.model import ( + BackendIndex, + FunctionSchema, + NativeFunction, + NativeFunctionsGroup, + NativeFunctionsViewGroup, + ) + + +@dataclass(frozen=True) +class CppSignature: + """ + A CppSignature represents a single overload in the C++ API. For + any given function schema, there may be multiple CppSignatures + corresponding to it, based on how we desugar to C++. See also + CppSignatureGroup. + """ + + # The schema this signature is derived from + func: FunctionSchema + + # Is this a C++ signature for a method, i.e. Tensor::my_op(...)? + method: bool + + # Is this a faithful C++ signature (i.e. following the JIT schema) or a convenience API + # (i.e. with a potential TensorOptions argument and out arguments in the front) + faithful: bool + + # Is this a symint C++ signature. For BC reasons, functions that take + # SymInts still present as int64_t in C++, and the SymInt variant is + # offered at a different overload name + # + # NB: If a function RETURNS a SymInt, this is ALWAYS false + symint: bool + + # The set of C++ arguments which should not have defaults applied to them + cpp_no_default_args: set[str] + + # Is this a fallback C++ binding? Fallback bindings are enabled by + # manual_cpp_binding: True and are alternate, non-public API that + # lets manual C++ binding implementers access the binding that would + # have been automatically generated + fallback_binding: bool = False + + # Return the unpacked argument structure of this signature, + # discarding information about which arguments are semantically + # related to each other. + def arguments(self) -> Sequence[Binding]: + return cpp.arguments( + self.func.arguments, + faithful=self.faithful, + symint=self.symint, + method=self.method, + cpp_no_default_args=self.cpp_no_default_args, + ) + + def name(self, *, suppress_symint_suffix: bool = False) -> str: + n = cpp.name( + self.func, + faithful_name_for_out_overloads=self.faithful, + symint_overload=False if suppress_symint_suffix else self.symint, + ) + if self.fallback_binding: + n = f"__dispatch_{n}" + return n + + # Render the C++ declaration for this signature + def decl( + self, + *, + name: str | None = None, + prefix: str = "", + is_redispatching_fn: bool = False, + suppress_symint_suffix: bool = False, + ) -> str: + returns_type = cpp.returns_type( + self.func.returns, symint=self.symint + ).cpp_type() + cpp_args = [a.decl() for a in self.arguments()] + if is_redispatching_fn: + cpp_args = ["c10::DispatchKeySet dispatchKeySet"] + cpp_args + cpp_args_str = ", ".join(cpp_args) + if name is None: + name = prefix + self.name(suppress_symint_suffix=suppress_symint_suffix) + return f"{returns_type} {name}({cpp_args_str})" + + # Render the C++ definition for this signature, not including + # the body (with curly braces) + def defn( + self, + *, + name: str | None = None, + prefix: str = "", + is_redispatching_fn: bool = False, + ) -> str: + returns_type = cpp.returns_type( + self.func.returns, symint=self.symint + ).cpp_type() + cpp_args = [a.defn() for a in self.arguments()] + if is_redispatching_fn: + cpp_args = ["c10::DispatchKeySet dispatchKeySet"] + cpp_args + cpp_args_str = ", ".join(cpp_args) + if name is None: + name = prefix + self.name() + return f"{returns_type} {name}({cpp_args_str})" + + def ptr_type(self) -> str: + args_types_str = ", ".join(a.type for a in self.arguments()) + return f"{cpp.returns_type(self.func.returns, symint=self.symint).cpp_type()} (*)({args_types_str})" + + # Return the C++ function type, e.g., something like int(bool) + def type(self) -> str: + args_types_str = ", ".join(a.type for a in self.arguments()) + return f"{cpp.returns_type(self.func.returns, symint=self.symint).cpp_type()} ({args_types_str})" + + +# Represents group of all CppSignatures associated with a +# FunctionSchema. Right now, that's the regular, user-visible +# signature, as well as a "faithful" signature which doesn't +# have grouping. +@dataclass(frozen=True) +class CppSignatureGroup: + func: FunctionSchema + signature: CppSignature + faithful_signature: CppSignature | None + symint_signature: CppSignature | None + symint_faithful_signature: CppSignature | None + + def most_faithful_signature(self) -> CppSignature: + if self.faithful_signature: + return self.faithful_signature + else: + return self.signature + + def signatures(self, *, symint: bool = True) -> Iterator[CppSignature]: + yield self.signature + if self.faithful_signature: + yield self.faithful_signature + if symint: + if self.symint_signature: + yield self.symint_signature + if self.symint_faithful_signature: + yield self.symint_faithful_signature + + @staticmethod + def from_native_function( + f: NativeFunction, *, method: bool, fallback_binding: bool = False + ) -> CppSignatureGroup: + func = f.func + + def make_sig(*, faithful: bool, symint: bool) -> CppSignature: + return CppSignature( + func=func, + faithful=faithful, + symint=symint, + method=method, + fallback_binding=fallback_binding, + cpp_no_default_args=f.cpp_no_default_args, + ) + + def make_sigs(*, symint: bool) -> tuple[CppSignature, CppSignature | None]: + faithful_signature: CppSignature | None = None + if func.arguments.tensor_options is not None or len(func.arguments.out) > 0: + faithful_signature = make_sig(faithful=True, symint=symint) + signature = make_sig(faithful=False, symint=symint) + return signature, faithful_signature + + signature, faithful_signature = make_sigs(symint=False) + symint_signature: CppSignature | None = None + symint_faithful_signature: CppSignature | None = None + if func.has_symint(): + symint_signature, symint_faithful_signature = make_sigs(symint=True) + + return CppSignatureGroup( + func=func, + signature=signature, + faithful_signature=faithful_signature, + symint_signature=symint_signature, + symint_faithful_signature=symint_faithful_signature, + ) + + +@dataclass(frozen=True) +class DispatcherSignature: + # The schema this signature is derived from + func: FunctionSchema + + # Allows you to prepend an arbitrary prefix to the signature name. + # This is useful for parts of the codegen that generate wrappers around kernels, + # and need to avoid naming collisions. + prefix: str = "" + + symint: bool = True + + def arguments(self) -> list[Binding]: + return dispatcher.arguments(self.func, symint=self.symint) + + def name(self) -> str: + return self.prefix + dispatcher.name(self.func) + + def decl(self, name: str | None = None) -> str: + args_str = ", ".join(a.decl() for a in self.arguments()) + if name is None: + name = self.name() + return f"{self.returns_type().cpp_type()} {name}({args_str})" + + def defn( + self, name: str | None = None, *, is_redispatching_fn: bool = False + ) -> str: + args = [a.defn() for a in self.arguments()] + if is_redispatching_fn: + args = ["c10::DispatchKeySet dispatchKeySet"] + args + args_str = ", ".join(args) + if name is None: + name = self.name() + return f"{self.returns_type().cpp_type()} {name}({args_str})" + + def exprs(self) -> list[Expr]: + return [Expr(a.name, a.nctype) for a in self.arguments()] + + def returns_type(self) -> CType: + return dispatcher.returns_type(self.func.returns, symint=self.symint) + + def ptr_type(self) -> str: + dispatcher_args_types_str = ", ".join(a.type for a in self.arguments()) + return f"{self.returns_type().cpp_type()} (*)({dispatcher_args_types_str})" + + # Return the C++ function type, e.g., something like int(bool) + def type(self) -> str: + dispatcher_args_types_str = ", ".join(a.type for a in self.arguments()) + return f"{self.returns_type().cpp_type()} ({dispatcher_args_types_str})" + + @staticmethod + def from_schema( + func: FunctionSchema, *, prefix: str = "", symint: bool = True + ) -> DispatcherSignature: + return DispatcherSignature(func, prefix, symint) + + +@dataclass(frozen=True) +class NativeSignature: + # The schema this signature is derived from + func: FunctionSchema + + symint: bool + + prefix: str = "" + + def name(self) -> str: + return self.prefix + native.name(self.func) + + def decl(self, name: str | None = None) -> str: + args_str = ", ".join(a.decl() for a in self.arguments()) + if name is None: + name = self.name() + return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} {name}({args_str})" + + def defn(self, name: str | None = None) -> str: + args_str = ", ".join(a.defn() for a in self.arguments()) + if name is None: + name = self.name() + return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} {name}({args_str})" + + def ptr_type(self) -> str: + # don't include defaults in type signature! + args_str = ", ".join(a.defn() for a in self.arguments()) + return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} (*)({args_str})" + + def arguments(self) -> list[Binding]: + return native.arguments(self.func, symint=self.symint) + + def returns_type(self) -> CType: + return native.returns_type(self.func.returns, symint=self.symint) + + def dispatcher_exprs(self) -> list[Expr]: + return translate.translate( + self.arguments(), dispatcher.arguments(self.func), method=False + ) + + +@dataclass(frozen=True) +class ViewInverseSignature: + g: NativeFunctionsViewGroup + + def name(self) -> str: + return functionalization.reverse_name(self.g.view, include_namespace=False) + + def decl(self) -> str: + return_type = functionalization.returns_type(self.g.view.func) + decls = [ + a.decl() + for a in functionalization.op_arguments(self.g.view.func, is_reverse=True) + ] + return f"static {return_type.cpp_type()} {self.name()}({', '.join(decls)});" + + +@dataclass(frozen=True) +class StructuredImplSignature: + g: NativeFunctionsGroup + name: str + + def defn(self, name: str | None = None) -> str: + args_str = ", ".join(a.defn() for a in self.arguments()) + return f"TORCH_IMPL_FUNC({self.name})({args_str})" + + def arguments(self) -> list[Binding]: + return structured.impl_arguments(self.g) + + +# Helper functions + + +def kernel_signature( + f: NativeFunction, backend_index: BackendIndex, *, prefix: str = "" +) -> NativeSignature | DispatcherSignature: + # Note [External Backends Follow Dispatcher API] + # Kernel signatures for in-tree backends follow the "native" API, + # while kernels for out-of-tree backends follow the dispatcher API. + # See the comments in `native.py` for details, but historically there have been + # some small differences in schema convention between them and the Dispatcher API. + # Any differences that require translating between the two will results in a runtime cost, + # so we'd like to keep the differences as small as possible. + # With external backends, we'd like to enforce that they write their kernels with schemas + # that match the Dispatcher API directly, if they can. + meta = backend_index.get_kernel(f) + symint = meta is not None and meta.supports_symint() + if symint: + if not f.func.has_symint(): + raise AssertionError( + f"attempted to define symint kernel for {backend_index.dispatch_key} " + "without SymInt in schema" + ) + if backend_index.external: + return DispatcherSignature.from_schema(f.func, prefix=prefix, symint=symint) + else: + return NativeSignature(f.func, prefix=prefix, symint=symint) + + +# Functions only, no types +from torchgen.api import ( + cpp, + dispatcher, + functionalization, + native, + structured, + translate, +) diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/types/types.py b/.venv/lib/python3.12/site-packages/torchgen/api/types/types.py new file mode 100644 index 0000000000000000000000000000000000000000..4a49efe87785d0e2a2a30e7a07617c9dc9e12169 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/types/types.py @@ -0,0 +1,180 @@ +""" +Where should I add a new type? `types_base.py` vs `types.py` + +This file defines data model classes for torchgen typing system, as well as some base types such as int32_t. + +`types.py` defines ATen Tensor type and some c10 types, along with signatures that use these types. + +The difference between these two files, is `types_base.py` should be implementation-agnostic, meaning it shouldn't +contain any type definition that is tight to a specific C++ library (e.g., ATen), so that it can be easily reused +if we want to generate code for another C++ library. + +Add new types to `types.py` if these types are ATen/c10 related. +Add new types to `types_base.py` if they are basic and not attached to ATen/c10. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from torchgen.api.types.types_base import ( + BaseCppType, + BaseCType, + boolT, + byteT, + charT, + CType, + doubleT, + floatT, + int32T, + longT, + shortT, +) +from torchgen.model import BaseTy, ScalarType + + +TENSOR_LIST_LIKE_CTYPES = [ + "at::TensorList", + "const c10::List<::std::optional> &", + "const at::ITensorListRef &", +] + + +halfT = BaseCppType("at", "Half") +complexHalfT = BaseCppType( + "c10", "complex" +) # stuffing template param here is an abuse +complexFloatT = BaseCppType("c10", "complex") +complexDoubleT = BaseCppType("c10", "complex") +bfloat16T = BaseCppType("at", "BFloat16") +float8_e5m2T = BaseCppType("at", "Float8_e5m2") +float8_e5m2fnuzT = BaseCppType("at", "Float8_e5m2fnuz") +float8_e4m3fnT = BaseCppType("at", "Float8_e4m3fn") +float8_e4m3fnuzT = BaseCppType("at", "Float8_e4m3fnuz") +float8_e8m0fnuT = BaseCppType("at", "Float8_e8m0fnu") +stringT = BaseCppType("c10", "string_view") +generatorT = BaseCppType("at", "Generator") +scalarTypeT = BaseCppType("at", "ScalarType") +tensorT = BaseCppType("at", "Tensor") +optionalTensorRefT = BaseCppType("at", "OptionalTensorRef") +tensorListT = BaseCppType("at", "TensorList") +iTensorListRefT = BaseCppType("at", "ITensorListRef") +iOptTensorListRefT = BaseCppType("at", "IOptTensorListRef") +dimVectorT = BaseCppType("at", "DimVector") +layoutT = BaseCppType("at", "Layout") +deviceT = BaseCppType("at", "Device") +deviceIndexT = BaseCppType("at", "DeviceIndex") +scalarT = BaseCppType("at", "Scalar") +optionalScalarRefT = BaseCppType("at", "OptionalScalarRef") +memoryFormatT = BaseCppType("at", "MemoryFormat") +qschemeT = BaseCppType("at", "QScheme") +storageT = BaseCppType("at", "Storage") +streamT = BaseCppType("at", "Stream") +intArrayRefT = BaseCppType("at", "IntArrayRef") +optionalIntArrayRefT = BaseCppType("at", "OptionalIntArrayRef") +optionalSymIntArrayRefT = BaseCppType("at", "OptionalSymIntArrayRef") +tensorOptionsT = BaseCppType("at", "TensorOptions") +typeAndSizeT = BaseCppType("torch::autograd::generated", "TypeAndSize") +tensorGeometryT = BaseCppType("at", "TensorGeometry") +SymIntT = BaseCppType("c10", "SymInt") +SymBoolT = BaseCppType("c10", "SymBool") +symIntArrayRefT = BaseCppType("c10", "SymIntArrayRef") + +# Types representing template parameters. Technically, we probably shouldn't +# represent them this way in codegen, but it was pretty convenient. +scalar_t = BaseCppType("", "scalar_t") +opmath_t = BaseCppType("", "opmath_t") + +ScalarTypeToCppMapping: dict[ScalarType, BaseCppType] = { + ScalarType.Byte: byteT, + ScalarType.Char: charT, + ScalarType.Short: shortT, + ScalarType.Int: int32T, + ScalarType.Long: longT, + ScalarType.Half: halfT, + ScalarType.Float: floatT, + ScalarType.Double: doubleT, + ScalarType.ComplexHalf: complexHalfT, + ScalarType.ComplexFloat: complexFloatT, + ScalarType.ComplexDouble: complexDoubleT, + ScalarType.Bool: boolT, + ScalarType.Float8_e5m2: float8_e5m2T, + ScalarType.Float8_e5m2fnuz: float8_e5m2fnuzT, + ScalarType.Float8_e4m3fn: float8_e4m3fnT, + ScalarType.Float8_e4m3fnuz: float8_e4m3fnuzT, + ScalarType.Float8_e8m0fnu: float8_e8m0fnuT, +} + +BaseTypeToCppMapping: dict[BaseTy, BaseCppType] = { + BaseTy.int: longT, + BaseTy.float: doubleT, + BaseTy.bool: boolT, + BaseTy.str: stringT, + BaseTy.Generator: generatorT, + BaseTy.ScalarType: scalarTypeT, + BaseTy.Tensor: tensorT, + BaseTy.DimVector: dimVectorT, + BaseTy.Layout: layoutT, + BaseTy.Device: deviceT, + BaseTy.DeviceIndex: deviceIndexT, + BaseTy.Scalar: scalarT, + BaseTy.MemoryFormat: memoryFormatT, + BaseTy.QScheme: qschemeT, + BaseTy.Storage: storageT, + BaseTy.Stream: streamT, + BaseTy.SymInt: SymIntT, + BaseTy.SymBool: SymBoolT, +} + +# CTypes encode C++ type structure as needed for translation. + + +@dataclass(frozen=True) +class OptionalCType(CType): + elem: CType + + def cpp_type(self, *, strip_ref: bool = False) -> str: + # Do not pass `strip_ref` recursively. + return f"::std::optional<{self.elem.cpp_type()}>" + + def remove_const_ref(self) -> CType: + return OptionalCType(self.elem.remove_const_ref()) + + +@dataclass(frozen=True) +class ListCType(CType): + elem: CType + + def cpp_type(self, *, strip_ref: bool = False) -> str: + # Do not pass `strip_ref` recursively. + return f"c10::List<{self.elem.cpp_type()}>" + + def remove_const_ref(self) -> CType: + return ListCType(self.elem.remove_const_ref()) + + +@dataclass(frozen=True) +class ArrayRefCType(CType): + elem: CType + + def cpp_type(self, *, strip_ref: bool = False) -> str: + # Do not pass `strip_ref` recursively. + return f"at::ArrayRef<{self.elem.cpp_type()}>" + + def remove_const_ref(self) -> CType: + return ArrayRefCType(self.elem.remove_const_ref()) + + +@dataclass(frozen=True) +class VectorizedCType(CType): + # This template is explicitly specialized, so the only valid + # elems are those we have specializations for (e.g., float, double, ...) + # scalar_t is also a common argument here (when we are codegen in + # a templated context) + elem: BaseCType + + def cpp_type(self, *, strip_ref: bool = False) -> str: + return f"at::vec::Vectorized<{self.elem.cpp_type()}>" + + def remove_const_ref(self) -> CType: + return self diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/types/types_base.py b/.venv/lib/python3.12/site-packages/torchgen/api/types/types_base.py new file mode 100644 index 0000000000000000000000000000000000000000..322ae1c39c1ede4a5080b93dbf01ed30589b427c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/types/types_base.py @@ -0,0 +1,238 @@ +""" +Where should I add a new type? `types_base.py` vs `types.py` + +This file defines data model classes for torchgen typing system, as well as some base types such as int32_t. + +`types.py` defines ATen Tensor type and some c10 types, along with signatures that use these types. + +The difference between these two files, is `types_base.py` should be implementation-agnostic, meaning it shouldn't +contain any type definition that is tight to a specific C++ library (e.g., ATen), so that it can be easily reused +if we want to generate code for another C++ library. + +Add new types to `types.py` if these types are ATen/c10 related. +Add new types to `types_base.py` if they are basic and not attached to ATen/c10. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass +from enum import auto, Enum +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from torchgen.model import Argument, SelfArgument, TensorOptionsArguments + + +# An ArgName is just the str name of the argument in schema; +# but in some special circumstances, we may add a little extra +# context. The Enum SpecialArgName covers all of these cases; +# grep for their construction sites to see when they can occur. + + +class SpecialArgName(Enum): + possibly_redundant_memory_format = auto() + + +ArgName = str | SpecialArgName + + +# This class shouldn't be created directly; instead, use/create one of the singletons below. +@dataclass(frozen=True) +class BaseCppType: + ns: str | None + name: str + + def __str__(self) -> str: + if self.ns is None or self.ns == "": + return self.name + return f"{self.ns}::{self.name}" + + +# The set of all non-templated, valid, fully-qualified names of C++ types that are used in the codegen. +# Templated types get their own dataclass, mainly to make namespace parsing easier. +byteT = BaseCppType("", "uint8_t") +charT = BaseCppType("", "int8_t") +shortT = BaseCppType("", "int16_t") +# It would be more symmetric for this to be called intT, but it easy to mix +# this up with JIT int (which is int64_t in C++), so we intentionally don't +# define intT to make it obvious when you've stuffed it up +int32T = BaseCppType("", "int32_t") +longT = BaseCppType("", "int64_t") +doubleT = BaseCppType("", "double") +floatT = BaseCppType("", "float") +boolT = BaseCppType("", "bool") +voidT = BaseCppType("", "void") + + +class CType(ABC): + @abstractmethod + def cpp_type(self, *, strip_ref: bool = False) -> str: + raise NotImplementedError + + @abstractmethod + def remove_const_ref(self) -> CType: + return self + + +@dataclass(frozen=True) +class BaseCType(CType): + type: BaseCppType + + def cpp_type(self, *, strip_ref: bool = False) -> str: + return str(self.type) + + def remove_const_ref(self) -> CType: + return self + + +@dataclass(frozen=True) +class ConstRefCType(CType): + elem: CType + + def cpp_type(self, *, strip_ref: bool = False) -> str: + if strip_ref: + return self.elem.cpp_type(strip_ref=strip_ref) + return f"const {self.elem.cpp_type()} &" + + def remove_const_ref(self) -> CType: + return self.elem.remove_const_ref() + + +@dataclass(frozen=True) +class VectorCType(CType): + elem: CType + + def cpp_type(self, *, strip_ref: bool = False) -> str: + # Do not pass `strip_ref` recursively. + return f"::std::vector<{self.elem.cpp_type()}>" + + def remove_const_ref(self) -> CType: + return VectorCType(self.elem.remove_const_ref()) + + +@dataclass(frozen=True) +class ArrayCType(CType): + elem: CType + size: int + + def cpp_type(self, *, strip_ref: bool = False) -> str: + # Do not pass `strip_ref` recursively. + return f"::std::array<{self.elem.cpp_type()},{self.size}>" + + def remove_const_ref(self) -> CType: + return ArrayCType(self.elem.remove_const_ref(), self.size) + + +@dataclass(frozen=True) +class TupleCType(CType): + elems: list[CType] + + def cpp_type(self, *, strip_ref: bool = False) -> str: + # Do not pass `strip_ref` recursively. + return f"::std::tuple<{','.join([e.cpp_type() for e in self.elems])}>" + + def remove_const_ref(self) -> CType: + return TupleCType([e.remove_const_ref() for e in self.elems]) + + +@dataclass(frozen=True) +class MutRefCType(CType): + elem: CType + + def cpp_type(self, *, strip_ref: bool = False) -> str: + if strip_ref: + return self.elem.cpp_type(strip_ref=strip_ref) + return f"{self.elem.cpp_type()} &" + + def remove_const_ref(self) -> CType: + return self.elem.remove_const_ref() + + +# A NamedCType is short for Named C++ semantic type. A NamedCType represents a C++ type, plus +# semantic information about what it represents. For example, consider the +# argument "bool pin_memory"; its normal C++ type is "bool", but its C++ +# semantic type also keeps track that this represents a "pin_memory"; you can't +# just use a random other boolean in a context where you need a "pin_memory"! +# + + +@dataclass(frozen=True) +class NamedCType: + name: ArgName + type: CType + + def cpp_type(self, *, strip_ref: bool = False) -> str: + return self.type.cpp_type(strip_ref=strip_ref) + + def remove_const_ref(self) -> NamedCType: + return NamedCType(self.name, self.type.remove_const_ref()) + + def with_name(self, name: str) -> NamedCType: + return NamedCType(name, self.type) + + +# A binding represents any C++ binding site for a formal parameter. +# We don't distinguish between binding sites for different APIs; +# instead, all of the important distinctions are encoded in CType, +# which you can use to figure out if a given Binding is appropriate +# for use in another context. (See torchgen.api.translate) + + +@dataclass(frozen=True) +class Binding: + name: str + nctype: NamedCType + argument: Argument | TensorOptionsArguments | SelfArgument + # TODO: maybe don't represent default here + default: str | None = None + + def rename(self, name: str) -> Binding: + return Binding( + name=name, + nctype=self.nctype, + argument=self.argument, + default=self.default, + ) + + @property + def type(self) -> str: + return self.nctype.cpp_type() + + def no_default(self) -> Binding: + return Binding( + name=self.name, + nctype=self.nctype, + default=None, + argument=self.argument, + ) + + def decl(self, *, func_ptr_cast: bool = False) -> str: + mb_default = "" + if self.default is not None: + mb_default = f"={self.default}" + + # casting only needs to know the type + if func_ptr_cast: + return f"{self.type}" + else: + return f"{self.type} {self.name}{mb_default}" + + def defn(self) -> str: + return f"{self.type} {self.name}" + + def with_name(self, name: str) -> Binding: + return Binding( + name=name, nctype=self.nctype, argument=self.argument, default=self.default + ) + + +# An Expr is a C++ expression. It has a C++ string representing its syntax, +# as well as a CType saying what it provides. + + +@dataclass(frozen=True) +class Expr: + expr: str + type: NamedCType diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/ufunc.py b/.venv/lib/python3.12/site-packages/torchgen/api/ufunc.py new file mode 100644 index 0000000000000000000000000000000000000000..0ced02fc6d11a5923ef6d0e0086142c34ee31b17 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/ufunc.py @@ -0,0 +1,211 @@ +from __future__ import annotations + +from dataclasses import dataclass + +import torchgen.api.types as api_types +from torchgen.api import cpp, structured +from torchgen.api.types import ( + ArgName, + BaseCppType, + BaseCType, + Binding, + ConstRefCType, + CType, + NamedCType, + scalarT, +) +from torchgen.model import ( + Argument, + BaseTy, + BaseType, + DispatchKey, + FunctionSchema, + NativeFunctionsGroup, + Type, +) + + +def schema_kernel_name(func: FunctionSchema, dispatch_key: DispatchKey) -> str: + if not func.is_out_fn(): + raise AssertionError("ufunc.kernel_name should only be invoked on out schemas") + return f"ufunc_{func.name.name}_{dispatch_key}" + + +def kernel_name(g: NativeFunctionsGroup, dispatch_key: DispatchKey) -> str: + return schema_kernel_name(g.out.func, dispatch_key) + + +# Tensors are omitted (as they are stored in TensorIterator), everything else is +# passed along (technically, we can pass tensors along too, it just wastes +# argument registers) +# +# NB: used for CPU only +def dispatchstub_type(t: Type, *, binds: ArgName) -> NamedCType | None: + # Dispatch stubs are always plain ints + r = cpp.valuetype_type(t, binds=binds, symint=False) + if r is not None: + return r + + if t == BaseType(BaseTy.Scalar): + return NamedCType(binds, ConstRefCType(BaseCType(scalarT))) + elif t == BaseType(BaseTy.Tensor): + return None + else: + raise AssertionError(f"unrecognized type {repr(t)}") + + +def opmath_type(scalar_t: BaseCppType) -> BaseCppType: + if scalar_t == api_types.scalar_t: + return api_types.opmath_t + raise NotImplementedError + + +# NB: Tensors in constructor are stored in opmath_t, not scalar_t +# because Tensor in constructor = its a scalar tensor partially applied = +# it can be higher precision and we want to compute in that higher precision +# +# NB: CUDA only +def ufunctor_ctor_type(t: Type, *, binds: ArgName, scalar_t: BaseCppType) -> NamedCType: + r = cpp.valuetype_type(t, binds=binds, symint=False) + if r is not None: + return r + + if t == BaseType(BaseTy.Scalar): + return NamedCType(binds, BaseCType(opmath_type(scalar_t))) + elif t == BaseType(BaseTy.Tensor): + return NamedCType(binds, BaseCType(opmath_type(scalar_t))) + else: + raise AssertionError(f"unrecognized type {repr(t)}") + + +# Only Tensors ever get passed directly to operator() +# +# NB: CUDA only +# (Actually, this works for CPU too) +def ufunctor_apply_type( + t: Type, *, binds: ArgName, scalar_t: BaseCppType +) -> NamedCType: + if t == BaseType(BaseTy.Tensor): + return NamedCType(binds, BaseCType(scalar_t)) + else: + raise AssertionError(f"unrecognized type {repr(t)}") + + +# The actual ufunc template function the user writes. Everything here +# is done in the computation type. compute_t is opmath_t in CUDA and scalar_t +# in CPU +def ufunc_type(t: Type, *, binds: ArgName, compute_t: CType) -> NamedCType: + r = cpp.valuetype_type(t, binds=binds, symint=False) + if r is not None: + return r + + if t == BaseType(BaseTy.Scalar): + return NamedCType(binds, compute_t) + elif t == BaseType(BaseTy.Tensor): + return NamedCType(binds, compute_t) + else: + raise AssertionError(f"unrecognized type {repr(t)}") + + +def ufunctor_ctor_argument(a: Argument, scalar_t: BaseCppType) -> Binding: + return Binding( + nctype=ufunctor_ctor_type(a.type, binds=a.name, scalar_t=scalar_t), + name=a.name, + default=None, + argument=a, + ) + + +def ufunctor_apply_argument(a: Argument, scalar_t: BaseCppType) -> Binding: + return Binding( + nctype=ufunctor_apply_type(a.type, binds=a.name, scalar_t=scalar_t), + name=a.name, + default=None, + argument=a, + ) + + +def ufunc_argument(a: Argument, compute_t: CType) -> Binding: + return Binding( + nctype=ufunc_type(a.type, binds=a.name, compute_t=compute_t), + name=a.name, + default=None, + argument=a, + ) + + +@dataclass(frozen=True) +class UfunctorBindings: + ctor: list[Binding] + apply: list[Binding] + + +# ufunctors are a CUDA-only concept representing functors that take some of +# their arguments on a host-side constructor, and the rest in the device-side +# apply. E.g., +# +# template +# struct CUDAFunctorOnSelf_add { +# using opmath_t = at::opmath_type; +# opmath_t other_; +# opmath_t alpha_; +# CUDAFunctorOnSelf_add(opmath_t other, opmath_t alpha) : other_(other), alpha_(alpha) {} +# __device__ scalar_t operator()(scalar_t self) { +# return ufunc::add(static_cast(self), other_, alpha_); +# } +# }; +# +# The ctor refers to the constructor CUDAFunctorOnSelf_add, while apply refers +# to the operator() definition +def ufunctor_arguments( + g: NativeFunctionsGroup, *, scalar_tensor_idx: int | None, scalar_t: BaseCppType +) -> UfunctorBindings: + ctor = [] + apply = [] + for a in g.functional.func.arguments.flat_non_out: + if a.type.is_tensor_like(): + if scalar_tensor_idx == 0: + # put it in the ctor anyway + ctor.append(ufunctor_ctor_argument(a, scalar_t=scalar_t)) + scalar_tensor_idx = None + else: + if scalar_tensor_idx is not None: + scalar_tensor_idx -= 1 + apply.append(ufunctor_apply_argument(a, scalar_t=scalar_t)) + else: + ctor.append(ufunctor_ctor_argument(a, scalar_t=scalar_t)) + if scalar_tensor_idx is not None: + raise AssertionError("scalar_tensor_idx should be None at end of processing") + return UfunctorBindings(ctor=ctor, apply=apply) + + +# ufuncs are the inner loop template functions that you wrote in ufunc/add.h +# which do the actual computation in question. E.g., +# +# template +# C10_HOST_DEVICE T add(T self, T other, T alpha) __ubsan_ignore_undefined__ { +# return self + alpha * other; +# } +# +# In this file, we refer to T as compute_t which is bound by caller +def ufunc_arguments(g: NativeFunctionsGroup, *, compute_t: CType) -> list[Binding]: + return [ + ufunc_argument(a, compute_t=compute_t) + for a in g.functional.func.arguments.flat_non_out + ] + + +# Stubs are the DispatchStub trampolines that CPU kernels use to get to their +# vectorized versions. E.g., +# +# using structured_binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha); +# DECLARE_DISPATCH(structured_binary_fn_alpha, add_stub); +def stub_arguments(g: NativeFunctionsGroup) -> list[Binding]: + # stubs drop all tensor arguments (they are implicit in the TensorIterator + # argument and keep everything else) + return [ + r + for a in g.out.func.arguments.flat_non_out + if not a.type.is_tensor_like() + for r in structured.argument(a) + ] diff --git a/.venv/lib/python3.12/site-packages/torchgen/api/unboxing.py b/.venv/lib/python3.12/site-packages/torchgen/api/unboxing.py new file mode 100644 index 0000000000000000000000000000000000000000..3c3b115e1e5e9b22a0ecfcd2aa6c375ff6b56cfd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/api/unboxing.py @@ -0,0 +1,217 @@ +from __future__ import annotations + +from torchgen.api import cpp +from torchgen.api.types import Binding, CppSignatureGroup, CType +from torchgen.model import ( + Argument, + BaseTy, + BaseType, + ListType, + NativeFunction, + OptionalType, + Type, +) + + +# This file generates the code for unboxing wrappers, i.e., the glue logic to unbox a boxed operator and convert the +# ivalues from stack to correct arguments to the unboxed kernel, based on corresponding JIT schema. This codegen is +# an alternative way to generate unboxing wrappers similar to the existing C++ metaprogramming approach but gets the +# job done statically. These generated unboxing wrappers will be useful under the scenario where we need to register +# a fixed set of operators known at compile time and thus can save some time in runtime initialization phase. +# +# Here's an example on how the codegen works: +# +# - Function Schema (source of truth) +# +# aten::zeros(int[] size, *, ScalarType? dtype=None, Layout? layout=None, +# Device? device=None, bool? pin_memory=None) -> Tensor +# +# - Argument Conversion +# Generates C++ code to convert an ivalue (from stack) to its underlying C++ type. +# - int[] size +# ```cpp +# const c10::List size_list_in = (std::move(peek(stack, 0, 5))).toList(); +# +# std::vector size_vec; +# for (c10::IValue size_elem: size_list_in) { +# int64_t size_base = size_elem.to(); +# size_vec.push_back(size_base); +# } +# at::ArrayRef size_list_out(size_vec); +# ~~~~~~~~~~~~~ <-- The converted argument from ivalues in the stack. +# Will be passed to unboxed kernel. +# ``` +# - ScalarType? dtype +# ```cpp +# ::std::optional dtype_opt = (std::move(peek(stack, 1, 5))).toOptional(); +# ::std::optional dtype_opt_out; +# if (dtype_opt.has_value()) { +# ~~~~~~~~~~~ <-- Unwrapping optional shell +# const c10::IValue dtype_opt_in = dtype_opt.value(); +# at::ScalarType dtype_base = dtype_opt_in.to(); +# ~~~~~~~~~~~~~~~~~~~~ <-- For base types, convert ivalue to it +# directly using ".to()" API. +# dtype_opt_out = ::std::optional(dtype_base); +# } else { +# dtype_opt_out = ::std::optional(); +# } +# ``` +# +# - Unboxed Kernel Call +# ```cpp +# auto result_ = torch::zeros( +# size_list_out, +# options +# ); +# ``` +# +# - Push Result Back to Stack +# ```cpp +# drop(stack, 5); +# pack(stack, std::move(result_)); +# ``` +connector = "\n\t" + + +# Return unboxing function name for a NativeFunction +def name(f: NativeFunction) -> str: + return f.func.name.unambiguous_name() + + +# Convert all the arguments in a NativeFunction to C++ code +def convert_arguments(f: NativeFunction) -> tuple[list[Binding], list[str]]: + # we need the 'self' argument so method needs to be False + args = ( + CppSignatureGroup.from_native_function(f, method=False) + .most_faithful_signature() + .arguments() + ) + code_list = [ + f"c10::IValue {args[i].name} = std::move(peek(stack, {i}, {len(args)}));" + for i in range(len(args)) + ] + [""] + binding_list = [] + for arg in args: + # expecting only Argument + if not isinstance(arg.argument, Argument): + raise Exception( # noqa: TRY002 + f"Unexpected argument type, expecting `Argument` but got {arg}" + ) + argument: Argument = arg.argument + unboxed_name, _, code, decl = argumenttype_ivalue_convert( + argument.type, + argument.name, + mutable=argument.is_write, + ) + code_list.extend(decl) + code_list.extend(code) + binding_list.append(arg.with_name(unboxed_name)) + return binding_list, code_list + + +# Takes in the type, name and mutability corresponding to an argument, and generates a tuple of: +# (1) the C++ code necessary to unbox the argument +# (2) A Binding corresponding to the newly created unboxed variable, including variable name and its CType +def argumenttype_ivalue_convert( + t: Type, arg_name: str, *, mutable: bool = False +) -> tuple[str, CType, list[str], list[str]]: + # Unboxing is for mobile, which doesn't care about SymInts + ctype = cpp.argumenttype_type( + t=t, mutable=mutable, binds=arg_name, symint=False + ).type + + if isinstance(t, BaseType): + out_name = f"{arg_name}_base" + code, decl = _gen_code_base_type( + arg_name=arg_name, out_name=out_name, ctype=ctype + ) + elif isinstance(t, OptionalType): + out_name = f"{arg_name}_opt_out" + code, decl = _gen_code_optional_type( + arg_name=arg_name, + out_name=out_name, + t=t, + ctype=ctype, + ) + elif isinstance(t, ListType): + out_name = f"{arg_name}_list_out" + code, decl = _gen_code_list_type( + arg_name=arg_name, + out_name=out_name, + t=t, + ctype=ctype, + ) + else: + raise Exception(f"Cannot handle type {t}. arg_name: {arg_name}") # noqa: TRY002 + return out_name, ctype, code, decl + + +def _gen_code_base_type( + arg_name: str, out_name: str, ctype: CType +) -> tuple[list[str], list[str]]: + return [ + f"{ctype.cpp_type(strip_ref=True)} {out_name} = {arg_name}.to<{ctype.cpp_type(strip_ref=True)}>();" + ], [] + + +def _gen_code_optional_type( + arg_name: str, out_name: str, t: OptionalType, ctype: CType +) -> tuple[list[str], list[str]]: + in_name = f"{arg_name}_opt_in" + res_name, _, res_code, decl = argumenttype_ivalue_convert(t.elem, in_name) + return ( + f""" +auto {arg_name}_opt = {arg_name}.toOptional(); +{ctype.cpp_type(strip_ref=True)} {out_name}; +if ({arg_name}_opt.has_value()) {{ + const c10::IValue {in_name} = {arg_name}_opt.value(); + {connector.join(res_code)} + {out_name} = {ctype.cpp_type(strip_ref=True)}({res_name}); +}} else {{ + {out_name} = {ctype.cpp_type(strip_ref=True)}(); +}} + """.split("\n"), + decl, + ) + + +def _gen_code_list_type( + arg_name: str, out_name: str, t: ListType, ctype: CType +) -> tuple[list[str], list[str]]: + in_name = f"{arg_name}_list_in" + elem_name = f"{arg_name}_elem" + code = [f"const c10::List {in_name} = {arg_name}.toList();"] + res_name, res_ctype, res_code, decl = argumenttype_ivalue_convert(t.elem, elem_name) + # handle list type with size, e.g., bool[4] + if isinstance(t.elem, BaseType) and t.elem.name == BaseTy.bool and t.size: + code.extend( + f""" +{ctype.cpp_type(strip_ref=True)} {out_name} = as_array<{res_ctype.cpp_type(strip_ref=True)}, {t.size}>({in_name}); + """.split("\n") + ) + # we have to use c10::List for optional element. e.g., Tensor?[] -> c10::List<::std::optional> + elif isinstance(t.elem, OptionalType): + code.extend( + f""" +{ctype.cpp_type(strip_ref=True)} {out_name}; +for (c10::IValue {elem_name}: {in_name}) {{ + {connector.join(res_code)} + {out_name}.push_back({res_name}); +}} + """.split("\n") + ) + else: + # use ArrayRef as default. + vec_name = arg_name + "_vec" + # need to bring vector instantiation out of scope so that ArrayRef has valid data + decl.append(f"std::vector<{res_ctype.cpp_type(strip_ref=True)}> {vec_name};") + code.extend( + f""" +for (c10::IValue {elem_name}: {in_name}) {{ + {connector.join(res_code)} + {vec_name}.push_back({res_name}); +}} +{ctype.cpp_type(strip_ref=True)} {out_name}({vec_name}); + """.split("\n") + ) + return code, decl diff --git a/.venv/lib/python3.12/site-packages/torchgen/code_template.py b/.venv/lib/python3.12/site-packages/torchgen/code_template.py new file mode 100644 index 0000000000000000000000000000000000000000..8fcae32c79f53a2c4536987f7236cae00d87312e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/code_template.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +import itertools +import re +import textwrap +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + + +# match $identifier or ${identifier} and replace with value in env +# If this identifier is at the beginning of whitespace on a line +# and its value is a list then it is treated as +# block substitution by indenting to that depth and putting each element +# of the list on its own line +# if the identifier is on a line starting with non-whitespace and a list +# then it is comma separated ${,foo} will insert a comma before the list +# if this list is not empty and ${foo,} will insert one after. + + +class CodeTemplate: + substitution_str = r"(^[^\n\S]*)?\$([^\d\W]\w*|\{,?[^\d\W]\w*\,?})" + substitution = re.compile(substitution_str, re.MULTILINE) + + pattern: str + filename: str + + @staticmethod + def from_file(filename: str) -> CodeTemplate: + with open(filename) as f: + return CodeTemplate(f.read(), filename) + + def __init__(self, pattern: str, filename: str = "") -> None: + self.pattern = pattern + self.filename = filename + + def substitute( + self, env: Mapping[str, object] | None = None, **kwargs: object + ) -> str: + if env is None: + env = {} + + def lookup(v: str) -> object: + if env is None: + raise AssertionError("env must be non-None") + return kwargs[v] if v in kwargs else env[v] + + def indent_lines(indent: str, v: Sequence[object]) -> str: + content = "\n".join( + itertools.chain.from_iterable(str(e).splitlines() for e in v) + ) + content = textwrap.indent(content, prefix=indent) + # Remove trailing whitespace on each line + return "\n".join(map(str.rstrip, content.splitlines())).rstrip() + + def replace(match: re.Match[str]) -> str: + indent = match.group(1) + key = match.group(2) + comma_before = "" + comma_after = "" + if key[0] == "{": + key = key[1:-1] + if key[0] == ",": + comma_before = ", " + key = key[1:] + if key[-1] == ",": + comma_after = ", " + key = key[:-1] + v = lookup(key) + if indent is not None: + if not isinstance(v, list): + v = [v] + return indent_lines(indent, v) + elif isinstance(v, list): + middle = ", ".join([str(x) for x in v]) + if len(v) == 0: + return middle + return comma_before + middle + comma_after + else: + return str(v) + + return self.substitution.sub(replace, self.pattern) + + +if __name__ == "__main__": + c = CodeTemplate( + """\ + int foo($args) { + + $bar + $bar + $a+$b + } + int commatest(int a${,stuff}) + int notest(int a${,empty,}) + """ + ) + print( + c.substitute( + args=["hi", 8], + bar=["what", 7], + a=3, + b=4, + stuff=["things...", "others"], + empty=[], + ) + ) diff --git a/.venv/lib/python3.12/site-packages/torchgen/context.py b/.venv/lib/python3.12/site-packages/torchgen/context.py new file mode 100644 index 0000000000000000000000000000000000000000..a99d7119c656f27fabe4accdd2096d997416f4b6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/context.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +import contextlib +import functools +from typing import Any, TYPE_CHECKING, TypeVar + +import torchgen.local as local +from torchgen.model import ( + BackendIndex, + DispatchKey, + NativeFunction, + NativeFunctionsGroup, + NativeFunctionsViewGroup, +) +from torchgen.utils import context, S, T + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + + +# Helper functions for defining generators on things in the model + +F = TypeVar( + "F", + NativeFunction, + NativeFunctionsGroup, + NativeFunctionsViewGroup, + NativeFunction | NativeFunctionsGroup, + NativeFunction | NativeFunctionsViewGroup, +) + +F2 = TypeVar( + "F2", + NativeFunction, + NativeFunctionsGroup, + NativeFunction | None, + bool, + str, +) + +F3 = TypeVar("F3", tuple[NativeFunction, Any], list[NativeFunction]) + + +@contextlib.contextmanager +def native_function_manager( + g: NativeFunctionsGroup | NativeFunctionsViewGroup | NativeFunction, +) -> Iterator[None]: + if isinstance(g, NativeFunctionsGroup): + # By default, we associate all errors with structured native functions + # with the out variant. In some cases, it might be better to have + # a more specific place to hang things; if so, use + # native_function_manager again on the inside + f = g.out + elif isinstance(g, NativeFunctionsViewGroup): + # We associate errors with the view operator + f = g.view + else: + f = g + with context(lambda: f"in native_functions.yaml line {f.loc}:\n {f.func}"): + with local.parametrize( + use_const_ref_for_mutable_tensors=f.use_const_ref_for_mutable_tensors, + use_ilistref_for_tensor_lists=f.part_of_structured_group, + ): + yield + + +# Given a function that operates on NativeFunction, wrap it into a new function +# that sets some appropriate context managers for that native function. +# YOU MUST WRAP FUNCTIONS IN THIS for calls to api modules to be sound +# (you will get an error if we try to access the local variables without having +# set them). +def with_native_function(func: Callable[[F], T]) -> Callable[[F], T]: + @functools.wraps(func) + def wrapper(f: F) -> T: + with native_function_manager(f): + return func(f) + + return wrapper + + +def with_native_function_and(func: Callable[[F, F2], T]) -> Callable[[F, F2], T]: + @functools.wraps(func) + def wrapper(f: F, f2: F2) -> T: + # The first native_function is assumed to be the one with the appropriate context. + with native_function_manager(f): + return func(f, f2) + + return wrapper + + +def method_with_native_function(func: Callable[[S, F], T]) -> Callable[[S, F], T]: + @functools.wraps(func) + def wrapper(slf: S, f: F) -> T: + with native_function_manager(f): + return func(slf, f) + + return wrapper + + +def method_with_nested_native_function( + func: Callable[[S, F3], T], +) -> Callable[[S, F3], T]: + @functools.wraps(func) + def wrapper(slf: S, f: F3) -> T: + with native_function_manager(f[0]): + return func(slf, f) + + return wrapper + + +# Convenience decorator for functions that explicitly take in a BackendIndex, +# instead of indirectly taking one in as a closure +def with_native_function_and_index( + func: Callable[[F, BackendIndex], T], +) -> Callable[[F, BackendIndex], T]: + @functools.wraps(func) + def wrapper(f: F, backend_index: BackendIndex) -> T: + with native_function_manager(f): + return func(f, backend_index) + + return wrapper + + +# Convenience decorator for functions that explicitly take in a Dict of BackendIndices +def with_native_function_and_indices( + func: Callable[[F, dict[DispatchKey, BackendIndex]], T], +) -> Callable[[F, dict[DispatchKey, BackendIndex]], T]: + @functools.wraps(func) + def wrapper(f: F, backend_indices: dict[DispatchKey, BackendIndex]) -> T: + with native_function_manager(f): + return func(f, backend_indices) + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/torchgen/dest/__init__.py b/.venv/lib/python3.12/site-packages/torchgen/dest/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f08a743ae2dc766530fd8f93be9ebb8b7733f21 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/dest/__init__.py @@ -0,0 +1,19 @@ +from torchgen.dest.lazy_ir import ( + generate_non_native_lazy_ir_nodes as generate_non_native_lazy_ir_nodes, + GenLazyIR as GenLazyIR, + GenLazyNativeFuncDefinition as GenLazyNativeFuncDefinition, + GenLazyShapeInferenceDefinition as GenLazyShapeInferenceDefinition, +) +from torchgen.dest.native_functions import ( + compute_native_function_declaration as compute_native_function_declaration, +) +from torchgen.dest.register_dispatch_key import ( + gen_registration_headers as gen_registration_headers, + gen_registration_helpers as gen_registration_helpers, + RegisterDispatchKey as RegisterDispatchKey, +) +from torchgen.dest.ufunc import ( + compute_ufunc_cpu as compute_ufunc_cpu, + compute_ufunc_cpu_kernel as compute_ufunc_cpu_kernel, + compute_ufunc_cuda as compute_ufunc_cuda, +) diff --git a/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dc07d459db01964dc36b15e90d482ca8e3ef813 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/lazy_ir.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/lazy_ir.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73589db57a0c51291d13f0a8fe5cd493dd1de40c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/lazy_ir.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/lazy_ts_lowering.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/lazy_ts_lowering.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f17cd51ba6f3b4e305b876701e4912209172ce0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/lazy_ts_lowering.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/native_functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/native_functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbd634bd77a4329f685110dd370ff0d2f6df75ea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/native_functions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/register_dispatch_key.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/register_dispatch_key.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1b45b97eafa7787b37e4e2c9de1990dd3fc1a5b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/register_dispatch_key.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/ufunc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/ufunc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07947c2ce82fbc46c5e47af24ba302a79f4130a6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/dest/__pycache__/ufunc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/dest/lazy_ir.py b/.venv/lib/python3.12/site-packages/torchgen/dest/lazy_ir.py new file mode 100644 index 0000000000000000000000000000000000000000..f98184cb44a3ec2a60889cbbcd6ed44c2b7e9437 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/dest/lazy_ir.py @@ -0,0 +1,718 @@ +from __future__ import annotations + +import itertools +from abc import ABC +from dataclasses import dataclass +from typing import Any + +import torchgen.api.dispatcher as dispatcher +from torchgen.api.lazy import ( + getValueT, + isValueType, + LazyArgument, + LazyIrProperties, + LazyIrSchema, + tensorListValueT, +) +from torchgen.api.translate import translate +from torchgen.api.types import ( + BaseCType, + Binding, + deviceT, + DispatcherSignature, + kernel_signature, + NativeSignature, + OptionalCType, + VectorCType, +) +from torchgen.context import method_with_native_function +from torchgen.dest.lazy_ts_lowering import ts_lowering_body +from torchgen.model import ( + Argument, + BackendIndex, + BackendMetadata, + BaseTy, + BaseType, + FunctionSchema, + ListType, + NativeFunction, + NativeFunctionsGroup, +) + + +def node_ctor_arg_rvalue_string(arg: LazyArgument) -> str: + """ + Given a LazyArgument, + generate a c++ string for materializing an rvalue of that arg for passing into + a lazy Node constructor. + """ + + # TODO: Matching on CType seems wrong; should be matching on Type + if isValueType(arg.lazy_type): + if isinstance(arg.lazy_type, BaseCType): + if arg.is_wrapped_scalar: + return f"node_{arg.name}" + elif arg.lazy_type.type is tensorListValueT: + return f"lazy_{arg.name}_tensorlist" + elif arg.is_symint_or_list: + return f"GetSymIntValue({arg.name})" + return f"lazy_{arg.name}->GetIrValue()" + elif isinstance(arg.lazy_type, OptionalCType): + if arg.is_symint_or_list: + # TODO: I don't understand when you should put lazy_ in the name + # or not + return f"{arg.name} ? std::make_optional(GetSymIntValue(*{arg.name})) : ::std::nullopt" + elif arg.is_wrapped_scalar: + return f"node_{arg.name}" + return ( + f"lazy_{arg.name} ? " + f"std::make_optional(lazy_{arg.name}->GetIrValue()) : " + "::std::nullopt" + ) + else: + raise AssertionError( + f"TODO not sure if there are other valid types to handle here ({arg.lazy_type})" + ) + else: + # NB: this is here because right now we aren't treating SymInt[] as a + # value type; when we do this needs to move above + # NB: we cannot test arg.lazy_type as we've already specified it is an + # int64_t and so we cannot distinguish between SymInt and int64_t + if isinstance(arg.orig_type, ListType) and arg.orig_type.elem == BaseType( + BaseTy.SymInt + ): + if arg.symint: + return f"GetSymIntArrayRefValue({arg.name})" + else: + return f"std::vector({arg.name}.begin(), {arg.name}.end())" + elif isinstance(arg.lazy_type, VectorCType) and isinstance( + arg.lazy_type.elem, BaseCType + ): + return f"std::vector<{arg.lazy_type.elem.type}>({arg.name}.begin(), {arg.name}.end())" + elif ( + isinstance(arg.lazy_type, OptionalCType) + and isinstance(arg.lazy_type.elem, VectorCType) + and isinstance(arg.lazy_type.elem.elem, BaseCType) + ): + return f"torch::lazy::ToOptionalVector<{arg.lazy_type.elem.elem.type}>({arg.name})" + else: + return f"{arg.name}" + + +def node_ctor_inputs(schema: LazyIrSchema) -> str: + """ + Produce a formatted string with the arguments as passed into the constructor of a node class. + """ + node_ctor_values = [ + node_ctor_arg_rvalue_string(arg) for arg in schema.filtered_args() + ] + return ", ".join(node_ctor_values) + + +def gen_fallback_code( + schema: LazyIrSchema, + sig: DispatcherSignature | NativeSignature, + overload_name: str, +) -> str: + """ + Generate code that falls back to eager conditioned on a predicate + """ + dispatcher_sig = DispatcherSignature.from_schema(schema.func) + exprs = translate(sig.arguments(), dispatcher_sig.arguments()) + fallback_args = ",\n ".join([a.expr for a in exprs]) + if len(overload_name): + aten_op_str = f"ATEN_OP2({schema.aten_name}, {overload_name})" + else: + aten_op_str = f"ATEN_OP({schema.aten_name})" + return f""" + if (force_eager_fallback({aten_symbol(schema)})) {{ + return at::native::call_fallback_fn_symint<<c_eager_fallback, {aten_op_str}>::call( + {fallback_args} + ); + }} +""" + + +def aten_symbol(schema: LazyIrSchema) -> str: + missing_interned_strings = { + "sigmoid_backward", + } + if schema.aten_name in missing_interned_strings: + return f'c10::Symbol::fromQualString("aten::{schema.aten_name}")' + + if not schema.aten_name.startswith("at::"): + return f"at::aten::{schema.aten_name}" + else: + return schema.aten_name + + +# converts all tensor-like arguments to meta tensors. Returns: +# (1) a string containing all of the logic that does the conversions. +# (2) a context, to be used by translate(), with all of the relevant bindings. +def convert_to_meta_tensors(sig: DispatcherSignature) -> tuple[str, list[Binding]]: + context: list[Binding] = [] + unwrapped_tensor_args: list[str] = [] + for arg in sig.arguments(): + if isinstance(arg.argument, Argument) and arg.argument.type.is_tensor_like(): + unwrapped_name = f"{arg.name}_meta" + unwrapped_tensor_args.append( + f"auto {unwrapped_name} = to_meta({arg.name});" + ) + context.append(arg.with_name(unwrapped_name)) + else: + context.append(arg) + unwrap_tensor_args_str = "\n ".join(unwrapped_tensor_args) + return unwrap_tensor_args_str, context + + +@dataclass(frozen=True) +class GenLazyIR(ABC): + backend_index: BackendIndex + backend_name: str + node_base: str + use_lazy_shape: bool + + @method_with_native_function + def __call__(self, f: NativeFunctionsGroup | NativeFunction) -> list[str]: + func = f.functional.func if isinstance(f, NativeFunctionsGroup) else f.func + metadata = self.backend_index.get_kernel( + f.functional if isinstance(f, NativeFunctionsGroup) else f + ) + schema = LazyIrSchema( + func, symint=metadata is not None and metadata.supports_symint() + ) + return self.gen(schema) + + # there is no lowering functionality generated unless this IR base class is subclassed and + # implemented as a backend-specific node + def lowering_function(self, schema: LazyIrSchema) -> str: + return "" + + def create_function(self, schema: LazyIrSchema, node_ctor_args: str) -> str: + return "" + + def can_be_reused_function(self, schema: LazyIrSchema, node_ctor_args: str) -> str: + return f"""bool CanBeReused({node_ctor_args}) const {{ + return false; + }}""" + + def node_base_ctor_call(self, schema: LazyIrSchema) -> str: + value_args = schema.filtered_args(values=True, scalars=False) + # backends can customize the way the node base class constructor is called, + # as long as all of its arguments can be generated from information available from the schema + base_ctor_value_args_list = [] + for arg in value_args: + if isinstance(arg.lazy_type, (BaseCType, VectorCType)): + base_ctor_value_args_list.append(f"{arg.name}") + elif isinstance(arg.lazy_type, OptionalCType): + base_ctor_value_args_list.append(f"{arg.name}.value_or(kNullValue)") + else: + raise AssertionError( + f"Unsupported type ({arg.lazy_type}) - add support if necessary" + ) + base_ctor_value_args = ", ".join(base_ctor_value_args_list) + + scalar_args = schema.filtered_args(values=False, scalars=True) + + # Shape construction. + # Conditionally build shape depending on specified shape property + if schema.properties.ShapePrecompute: + shape_ctor_arg = "std::move(shapes)," + elif schema.properties.ShapeCompute: + shape_args = [a.name for a in value_args] + shape_args.extend(a.name for a in scalar_args) + shape_ctor_arg = f"compute_shape_{schema.name}({', '.join(shape_args)})," + elif schema.properties.ShapeCache: + shape_args = [f"operand({i})" for i in range(len(value_args))] + shape_args.extend(a.name for a in scalar_args) + shape_ctor_arg = f"[&](){{ return compute_shape_{schema.name}({', '.join(shape_args)})[0]; }}," + else: + shape_ctor_arg = "" + + scalar_hashes = ", ".join(f"{a.name}" for a in scalar_args) + + return f"""{self.node_base}( + {schema.node_name}::ClassOpKind(), + OpList{{{base_ctor_value_args}}}, + {shape_ctor_arg} + /* num_outputs */ {len(schema.returns)}, + torch::lazy::MHash({scalar_hashes}))""" + + def gen(self, schema: LazyIrSchema) -> list[str]: + opkind = schema.opkind or aten_symbol(schema) + + # for now, we just want one IR class decl and soon after also the method defs + # and we use the functional version not out/inplace. + all_args = schema.filtered_args() + scalar_args = schema.filtered_args(values=False, scalars=True) + + ctor_args = [f"const {i.lazy_type.cpp_type()}& {i.name}" for i in all_args] + reuse_ctor_args = ", ".join(ctor_args) + if self.use_lazy_shape and schema.properties.ShapePrecompute: + ctor_args.append("std::vector&& shapes") + node_ctor_args = ", ".join(ctor_args) + + scalar_initializers = ",\n ".join( + [ + # This code is just special casing the mapping from string_view -> strings + f"{a.name}({a.name}.has_value() ? ::std::make_optional(std::string(*{a.name})) : ::std::nullopt)" + if a.lazy_type.cpp_type() == "::std::optional" + else f"{a.name}({a.name})" + for a in scalar_args + ] + ) + if len(scalar_initializers): + scalar_initializers = f",\n {scalar_initializers}" + scalar_decls = "\n ".join( + [ + f"std::string {a.name};" + if a.lazy_type.cpp_type() == "c10::string_view" + else f"::std::optional {a.name};" + if a.lazy_type.cpp_type() == "::std::optional" + else f"{a.lazy_type.cpp_type()} {a.name};" + for a in scalar_args + ] + ) + optional_values = [ + arg.name + for arg in schema.filtered_args(values=True, scalars=False) + if isinstance(arg.lazy_type, OptionalCType) + ] + has_optional_decls = "\n ".join( + [f"bool has_{value}: 1;" for value in optional_values] + ) + has_optional_defs = "\n ".join( + [f"has_{value} = !!{value};" for value in optional_values] + ) + members_to_string = [] + for arg in scalar_args: + if isinstance(arg.lazy_type, OptionalCType): + value = f"{arg.name}.value()" + if arg.is_generator: + value = '"torch.Generator()"' + members_to_string.append( + f"""if ({arg.name}.has_value()) {{ + ss << ", {arg.name}=" << {value}; + }} else {{ + ss << ", {arg.name}=null"; + }}""" + ) + else: + members_to_string.append(f'ss << ", {arg.name}=" << {arg.name};') + members_to_string_str = "\n ".join(members_to_string) + + return [ + f"""\ +class {schema.node_name} : public {self.node_base} {{ + public: + static torch::lazy::OpKind ClassOpKind() {{ + return torch::lazy::OpKind({opkind}); + }} + + {schema.node_name}({node_ctor_args}) + : {self.node_base_ctor_call(schema)}{scalar_initializers} + {{ + {has_optional_defs} + }} + + std::string ToString() const override {{ + std::stringstream ss; + ss << {self.node_base}::ToString(); + {members_to_string_str} + return std::move(ss).str(); + }} + + {self.create_function(schema, reuse_ctor_args)} + + {self.can_be_reused_function(schema, reuse_ctor_args)} + + {self.lowering_function(schema)} + + {scalar_decls} + {has_optional_decls} + +}}; + +""", + ] + + +@dataclass(frozen=True) +class GenTSLazyIR(GenLazyIR): + def lowering_function(self, schema: LazyIrSchema) -> str: + signature = """ + torch::lazy::TSOpVector Lower( + std::shared_ptr function, + torch::lazy::TSLoweringContext* loctx) const override""" + + if schema.properties.LowerDeclOnly: + return f"{signature};" + elif schema.properties.Lower: + return f"""{signature} {{ + {ts_lowering_body(schema)} + }} + """ + else: + return "" + + def create_function(self, schema: LazyIrSchema, node_ctor_args: str) -> str: + signature = f"static NodePtr Create({node_ctor_args})" + if schema.properties.CreateFnDeclOnly: + return f"{signature};" + elif not schema.properties.CreateFn: + return "" + return f"""{signature} {{ + return ReuseOrMakeNode<{schema.node_name}>(data); + }}""" + + def can_be_reused_function(self, schema: LazyIrSchema, node_ctor_args: str) -> str: + signature = f"bool CanBeReused({node_ctor_args}) const" + if schema.properties.CanBeReusedDeclOnly: + return f"{signature};" + elif not schema.properties.CanBeReused: + return "" + value_comparison = [] + for arg in itertools.chain(schema.positional_values, schema.keyword_values): + if isinstance(arg.lazy_type, OptionalCType): + value_comparison.append( + f"nullable_operand(i++) == {arg.name}.value_or(kNullValue)" + ) + else: + value_comparison.append(f"operand(i++) == {arg.name}") + for arg in itertools.chain(schema.positional_scalars, schema.keyword_scalars): + if isinstance(arg.lazy_type, OptionalCType): + value_comparison.append( + f"((!this->{arg.name}&&!{arg.name}) || (this->{arg.name}&&{arg.name} && *(this->{arg.name}) == *{arg.name}))" + ) + else: + value_comparison.append(f"this->{arg.name} == {arg.name}") + value_comparison_str = " &&\n ".join(value_comparison) + + return f"""{signature} {{ + size_t i = 0; + return ({value_comparison_str}); + }}""" + + +@dataclass(frozen=True) +class GenLazyNativeFuncDefinition: + class_method_name: str + backend_index: BackendIndex + tensor_class: str + gen_forced_fallback_code: bool + backend_namespace: str + get_tensorlist: str + get_tensor_or_wrap_number: str + try_get_tensor: str + metrics_counter: str + create_tensor: str + create_from_first_tensor: bool + create_aten_from_ltc_tensor: str + tuple_aten_from_ltc_tensors: str + lazy_tensor_ptr: str + get_device_fn: str + + def lazy_tensor_decls(self, func: NativeFunction, schema: LazyIrSchema) -> str: + value_args = schema.filtered_args(values=True, scalars=False) + # Generates lazy_{name} variables for LazyTensors wrapping input tensors + lazy_tensor_decls: list[str] = [] + for arg in value_args: + if arg.is_wrapped_scalar: + if isinstance(arg.lazy_type, OptionalCType): + lazy_tensor_decls.append( + f"""auto node_{arg.name} = {arg.name} ? + std::make_optional(torch::lazy::LazyGraphExecutor::Get()-> + GetIrValueForScalarFromCodegen(*{arg.name}, *common_device)): + ::std::nullopt;""" + ) + else: + lazy_tensor_decls.append( + f"""auto node_{arg.name} = torch::lazy::LazyGraphExecutor::Get()-> + GetIrValueForScalarFromCodegen({arg.name}, *common_device);""" + ) + elif arg.is_symint_or_list: + continue # values are extracted in isValueType + elif isinstance(arg.lazy_type, BaseCType): + if arg.lazy_type.type is tensorListValueT: + lazy_tensor_decls.append( + f"auto lazy_{arg.name}_tensorlist = " + f"{self.backend_namespace}::{self.get_tensorlist}({arg.name});" + ) + else: + lazy_tensor_decls.append( + f"{self.lazy_tensor_ptr} lazy_{arg.name} = " + f"{self.backend_namespace}::{self.get_tensor_or_wrap_number}({arg.name}, *common_device);" + ) + elif isinstance(arg.lazy_type, OptionalCType): + if arg.lazy_type.elem != BaseCType(getValueT()): + raise AssertionError( + f"Expected OptionalCType elem to be {BaseCType(getValueT())}, " + f"got {arg.lazy_type.elem}" + ) + # TODO(alanwaketan): Maybe we want to apply GetLtcTensorOrCreateForWrappedNumber here, but hold it + # until we encounter a real world example. + lazy_tensor_decls.append( + f"{self.lazy_tensor_ptr} lazy_{arg.name} = " + f"{self.backend_namespace}::{self.try_get_tensor}({arg.name}.value_or(at::Tensor()));" + ) + else: + raise AssertionError( + f"TODO not sure if there are other valid types to handle here ({arg.lazy_type})" + ) + return ("\n ").join(lazy_tensor_decls) + + def force_eager_fallback( + self, + func: NativeFunction, + schema: LazyIrSchema, + metadata: BackendMetadata, + sig: DispatcherSignature | NativeSignature, + ) -> str: + if self.gen_forced_fallback_code: + return gen_fallback_code( + schema, sig, overload_name=func.func.name.overload_name + ) + return "" + + def metrics(self, func: NativeFunction, schema: LazyIrSchema) -> str: + return f"{self.metrics_counter};" + + def get_device(self, func: NativeFunction, schema: LazyIrSchema) -> str: + value_args = schema.filtered_args(values=True, scalars=False) + scalar_args = schema.filtered_args(values=False, scalars=True) + value_types_names = [f"{a.name}" for a in value_args if not a.is_wrapped_scalar] + optional_device = OptionalCType(BaseCType(deviceT)) + optional_devices = [ + a.name for a in scalar_args if a.lazy_type == optional_device + ] + if len(value_types_names) == 0 and len(optional_devices) == 0: + raise AssertionError("Expected at least one Value or Device type") + get_device_str = ( + f"{self.get_device_fn}({', '.join(value_types_names + optional_devices)})" + ) + return f"""auto common_device = {get_device_str}; + TORCH_INTERNAL_ASSERT(common_device); + """ + + def shape_inference(self, func: NativeFunction, schema: LazyIrSchema) -> str: + metadata = self.backend_index.get_kernel(func) + if metadata is None: + raise AssertionError(f"No kernel metadata found for {func.func.name}") + all_args = schema.filtered_args() + returns_length = len(schema.returns) + # call the meta kernel if it exists, to compute output shape/dtype for our IR + # Note [Generated LTC Shape Functions] + # LTC uses meta tensors from core to do shape inference when possible, and otherwise + # we generate a shape function declaration that needs to be manually implemented. + # How do we detect which ops are eligible to use meta tensors? + # In general we should be able to use meta tensors not just on structured operators, + # but also on composite operators that are implemented in terms of structured kernels. + # We don't currently have a way of knowing at codegen time which ops are implemented that way. + # This is the case for all view and view_copy operators however, so we're going to + # use them specifically for all of the view_copy ops (instead of manually writing shape rules for all of them). + is_view_copy_op = "view_copy" in func.tags + is_structured = func.structured or func.structured_delegate is not None + if is_structured or is_view_copy_op: + meta_out = """ +std::vector shapes{torch::lazy::Shape(out_meta.scalar_type(), out_meta.sizes().vec())};""" + if returns_length > 1: + + def this_shape(i: int) -> str: + return f"torch::lazy::Shape(std::get<{i}>(out_meta).scalar_type(), std::get<{i}>(out_meta).sizes().vec())" + + shapes_str = ",".join([this_shape(i) for i in range(returns_length)]) + meta_out = "std::vector shapes{" + shapes_str + "};" + + # Convert tensor args to the meta device and call it. + # (We can't pass in the input tensors directly, because they are "functional wrappers". + # If any of the meta kernels call a tensor op and redispatch, we don't want to hit the functionalize kernels.) + # Even at::meta:: functions might redispatch, e.g. if they call into view ops. + dispatcher_sig = DispatcherSignature.from_schema(func.func) + meta_conversion_str, meta_call_ctx = convert_to_meta_tensors(dispatcher_sig) + meta_call_args = [ + e.expr + for e in translate( + meta_call_ctx, dispatcher_sig.arguments(), method=False + ) + ] + if is_view_copy_op: + # view_copy ops always have a CompositeExplicitAutogradNonFunctional kernel + if not func.has_composite_explicit_autograd_non_functional_kernel: + raise AssertionError( + f"view_copy op {func.func.name} must have " + "CompositeExplicitAutogradNonFunctional kernel" + ) + dispatch_ns = "compositeexplicitautogradnonfunctional" + else: + dispatch_ns = "meta" + aten_name = schema.aten_name + # TODO: this is trolling + if func.func.has_symint() and metadata.supports_symint(): + aten_name += "_symint" + shape_str = f"""\ + {meta_conversion_str} + auto out_meta = at::{dispatch_ns}::{aten_name}({", ".join(meta_call_args)}); + {meta_out}""" + else: + shape_sig = ComputeShapeSignature( + metadata.kernel, func, symint=metadata.supports_symint() + ) + shape_str = f""" + auto shapes = {shape_sig.shape_call};""" + + shape_str += f""" + TORCH_INTERNAL_ASSERT(shapes.size() == {returns_length});""" + + # Calculating which dimensions are symbolic + func_schema_str = "aten::" + str(func.func) + shape_str += f""" + if(torch::lazy::symbolicShapeEnabled()){{ + std::vector inputs = {{ {", ".join(str(a.name) for a in all_args)} }}; + const char* schema_str = "{func_schema_str}"; + applySymbolicShapesOnLT(schema_str, inputs, shapes); + }} + """ + return shape_str + + def build_ir_node(self, func: NativeFunction, schema: LazyIrSchema) -> str: + node_ctor_input_str = node_ctor_inputs(schema) + return f"""torch::lazy::NodePtr node = torch::lazy::ReuseNode<{schema.node_name}>({node_ctor_input_str}); + if (!node) {{ + {self.shape_inference(func, schema)} + node = torch::lazy::MakeNode<{schema.node_name}>({node_ctor_input_str}, std::move(shapes)); + CacheNode(node); + }} + """ + + def create_lazy_tensor(self, first_tensor_name: str | None = None) -> str: + # xla uses an instance method for tensor creation, for the time being + if self.create_from_first_tensor: + # TODO(whc) remove this if XLA switches to using static method for creation + if first_tensor_name is None: + raise AssertionError("Requires first tensor to create lazy tensor") + return f"{first_tensor_name}.{self.create_tensor}" + return f"{self.backend_namespace}::{self.create_tensor}" + + def return_aten_tensor(self, func: NativeFunction, schema: LazyIrSchema) -> str: + returns_length = len(schema.returns) + value_args = schema.filtered_args(values=True, scalars=False) + value_types_names = [f"{a.name}" for a in value_args if not a.is_wrapped_scalar] + first_tensor_name = value_types_names[0] if len(value_types_names) > 0 else None + bridge_str = f"""auto result = {self.create_aten_from_ltc_tensor}( + {self.create_lazy_tensor(first_tensor_name)}(std::move(node), *common_device));""" + + if returns_length > 1: + if len(value_types_names) == 0: + raise AssertionError( + "Code below assumes there is at least one tensor arg" + ) + bridge_str = f"""std::vector<{self.lazy_tensor_ptr}> lazy_tensors; + for (int i = 0; i < {returns_length}; i++) {{ + lazy_tensors.push_back({self.create_lazy_tensor(first_tensor_name)}({getValueT()}(node, i), *common_device)); + }} + auto result = {self.tuple_aten_from_ltc_tensors}<{returns_length}>(lazy_tensors);""" + + if schema.name.name.inplace or func.func.is_out_fn(): + if returns_length != 1: + raise AssertionError( + "We assumed there was no such case where an op is an in-place variant " + f"and has tuple outputs, but got tuple of len {returns_length}." + ) + bridge_str = f"""lazy_{first_tensor_name}->SetInPlaceIrValue(node); + auto& result = {first_tensor_name};""" + + bridge_str += """ + return result;""" + return bridge_str + + @method_with_native_function + def __call__(self, func: NativeFunction) -> list[str]: + sig = kernel_signature(func, self.backend_index) + metadata = self.backend_index.get_kernel(func) + if metadata is None: + raise AssertionError(f"No kernel metadata found for {func.func.name}") + schema = LazyIrSchema(func.func, symint=metadata.supports_symint()) + return [ + f"""\ + {sig.decl(name=f"{self.class_method_name}::{metadata.kernel}")} {{ + {self.force_eager_fallback(func, schema, metadata, sig)} + {self.metrics(func, schema)} + {self.get_device(func, schema)} + {self.lazy_tensor_decls(func, schema)} + {self.build_ir_node(func, schema)} + {self.return_aten_tensor(func, schema)} + }}\n + """ + ] + + +class ComputeShapeSignature: + """ + Here we use the base name as the suffix of the signature to avoid generating for in-place variants. + """ + + def __init__(self, kernel_name: str, f: NativeFunction, *, symint: bool) -> None: + self.__schema = LazyIrSchema(f.func, symint=symint) + self.__dispatch_args = ", ".join( + [a.decl() for a in dispatcher.arguments(f.func, symint=symint)] + ) + self.__call_args = ", ".join( + [f"{arg.name}" for arg in self.__schema.filtered_args(generator=True)] + ) + self.__kernel_name = kernel_name + + def __decl_suffix(self) -> str: + return f"{self.__kernel_name}({self.__dispatch_args})" + + def __call_suffix(self) -> str: + return f"{self.__kernel_name}({self.__call_args})" + + @property + def shape_decl(self) -> str: + return f"TORCH_API std::vector compute_shape_{self.__decl_suffix()}" + + @property + def shape_call(self) -> str: + return f"torch::lazy::compute_shape_{self.__call_suffix()}" + + +@dataclass(frozen=True) +class GenLazyShapeInferenceDefinition: + backend_index: BackendIndex + tensor_class: str + + @method_with_native_function + def __call__(self, f: NativeFunction) -> list[str]: + metadata = self.backend_index.get_kernel(f) + if metadata is None: + raise AssertionError(f"No kernel metadata found for {f.func.name}") + + # See Note [Generated LTC Shape Functions] + is_view_copy_op = "view_copy" in f.tags + is_structured = f.structured or f.structured_delegate is not None + if is_structured or is_view_copy_op: + return [] + else: + shape_sig = ComputeShapeSignature( + metadata.kernel, f, symint=metadata.supports_symint() + ) + return ["\n".join([f"{shape_sig.shape_decl};"])] + + +def generate_non_native_lazy_ir_nodes( + non_native: list[dict[str, Any]], gen_lazy_ir: GenLazyIR +) -> list[str]: + """Generate the non-native lazy IR node classes""" + nodes = [] + for op in non_native: + # Set default properties for Non-Native IRs + properties = LazyIrProperties("ShapeCache", "CanBeReused", "LowerDeclOnly") + for p in op.get("properties", []): + setattr(properties, p, True) + + # non-native is assumed to want symint bindings if you wrote symint + schema = LazyIrSchema(FunctionSchema.parse(op["func"]), properties, symint=True) + schema.opkind = op.get("opkind") + nodes.append(gen_lazy_ir.gen(schema)[0]) + + return nodes diff --git a/.venv/lib/python3.12/site-packages/torchgen/dest/lazy_ts_lowering.py b/.venv/lib/python3.12/site-packages/torchgen/dest/lazy_ts_lowering.py new file mode 100644 index 0000000000000000000000000000000000000000..70161216d8e7c95e194b0d89b345e0da886ef989 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/dest/lazy_ts_lowering.py @@ -0,0 +1,48 @@ +from torchgen.api.lazy import LazyArgument, LazyIrSchema +from torchgen.api.types import OptionalCType + + +def ts_lowering_body(schema: LazyIrSchema) -> str: + # for now, we just want one IR class decl and soon after also the method defs + # and we use the functional version not out/inplace. + emplace_arguments = [] + + def get_value(arg: LazyArgument) -> str: + if isinstance(arg.lazy_type, OptionalCType): + return f"has_{arg.name} ? loctx->GetOutputOp(operand(i++)) : nullptr" + return "loctx->GetOutputOp(operand(i++))" + + for arg in schema.positional_args: + if arg.is_lazy_value: + emplace_arguments.append(get_value(arg)) + continue + emplace_arguments.append(f'"{arg.name}", {arg.name}') + + emplace_arguments_str = "\n ".join( + [f"arguments.emplace_back({a});" for a in emplace_arguments] + ) + emplace_kwarg_values = [ + f'"{arg.name}", {get_value(arg)}' for arg in schema.keyword_values + ] + emplace_kwarg_scalars = [ + f'"{arg.name}", {arg.name}' for arg in schema.keyword_scalars + ] + emplace_kwarguments = "\n ".join( + [ + f"kwarguments.emplace_back({a});" + for a in emplace_kwarg_values + emplace_kwarg_scalars + ] + ) + return f"""\ + std::vector arguments; + std::vector kwarguments; + arguments.reserve({len(emplace_arguments)}); + kwarguments.reserve({len(emplace_kwarg_values + emplace_kwarg_scalars)}); + size_t i = 0; + {emplace_arguments_str} + {emplace_kwarguments} + torch::lazy::TSOpVector {schema.aten_name}_out = torch::lazy::LowerTSBuiltin(function, op().op, arguments, kwarguments); + TORCH_CHECK_EQ({schema.aten_name}_out.size(), {len(schema.returns)}); + + return {schema.aten_name}_out; +""" diff --git a/.venv/lib/python3.12/site-packages/torchgen/dest/native_functions.py b/.venv/lib/python3.12/site-packages/torchgen/dest/native_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..52f2db366e6a4246517539620629232b8bd32f62 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/dest/native_functions.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import torchgen.api.meta as meta +import torchgen.api.structured as structured +from torchgen.api.types import kernel_signature +from torchgen.context import with_native_function_and_index +from torchgen.model import BackendIndex, NativeFunction, NativeFunctionsGroup +from torchgen.utils import mapMaybe + + +@with_native_function_and_index +def gen_unstructured(f: NativeFunction, backend_index: BackendIndex) -> str | None: + sig = kernel_signature(f, backend_index) + metadata = backend_index.get_kernel(f) + if metadata is None: + return None + if "legacy::" in metadata.kernel: + return None + else: + prefix = "static" if backend_index.external else "TORCH_API" + return f"{prefix} {sig.decl(name=metadata.kernel)};" + + +@with_native_function_and_index +def gen_structured(g: NativeFunctionsGroup, backend_index: BackendIndex) -> list[str]: + meta_name = meta.name(g) + out_args = structured.impl_arguments(g) + metadata = backend_index.get_kernel(g) + if metadata is None: + return [] + prefix = "" if backend_index.external else "TORCH_API " + return [ + f"""\ +struct {prefix}structured_{metadata.kernel} : public at::meta::structured_{meta_name} {{ +void impl({", ".join(a.decl() for a in out_args)}); +}}; +""" + ] + + +# Generates NativeFunctions.h, a list of forward declarations of all +# actual kernel definitions we keep in aten/src/ATen/native/ +@with_native_function_and_index +def compute_native_function_declaration( + g: NativeFunctionsGroup | NativeFunction, backend_index: BackendIndex +) -> list[str]: + metadata = backend_index.get_kernel(g) + if isinstance(g, NativeFunctionsGroup): + if metadata is not None and metadata.structured: + if backend_index.external: + # Structured hasn't been tested with external backends yet. + raise AssertionError( + "Structured external backend functions are not implemented yet." + ) + else: + return gen_structured(g, backend_index) + else: + return list( + mapMaybe(lambda f: gen_unstructured(f, backend_index), g.functions()) + ) + else: + x = gen_unstructured(g, backend_index) + return [] if x is None else [x] diff --git a/.venv/lib/python3.12/site-packages/torchgen/dest/register_dispatch_key.py b/.venv/lib/python3.12/site-packages/torchgen/dest/register_dispatch_key.py new file mode 100644 index 0000000000000000000000000000000000000000..1e9da890228383c56e47b57b422e0dfd4fb61a88 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/dest/register_dispatch_key.py @@ -0,0 +1,1026 @@ +from __future__ import annotations + +import itertools +import textwrap +from dataclasses import dataclass +from typing import Literal, TYPE_CHECKING +from typing_extensions import assert_never + +import torchgen.api.cpp as cpp +import torchgen.api.meta as meta +import torchgen.api.structured as structured +from torchgen.api.translate import translate +from torchgen.api.types import ( + BaseCType, + Binding, + ConstRefCType, + CppSignature, + CppSignatureGroup, + DispatcherSignature, + Expr, + kernel_signature, + MutRefCType, + NamedCType, + NativeSignature, + tensorT, +) +from torchgen.context import method_with_native_function, native_function_manager +from torchgen.model import ( + Argument, + BackendIndex, + DeviceCheckType, + DispatchKey, + gets_generated_out_inplace_wrapper, + is_cuda_dispatch_key, + NativeFunction, + NativeFunctionsGroup, + SchemaKind, + TensorOptionsArguments, +) +from torchgen.utils import mapMaybe, Target + + +if TYPE_CHECKING: + from torchgen.selective_build.selector import SelectiveBuilder + + +def gen_registration_headers( + backend_index: BackendIndex, + per_operator_headers: bool, + rocm: bool, +) -> list[str]: + if per_operator_headers: + headers = ["#include "] + else: + headers = ["#include "] + + if backend_index.dispatch_key in (DispatchKey.CPU, DispatchKey.Meta): + headers.append("#include ") + elif backend_index.dispatch_key == DispatchKey.CUDA: + if rocm: + headers.append("#include ") + else: + headers.append("#include ") + elif backend_index.dispatch_key == DispatchKey.MPS: + headers.append("#include ") + elif backend_index.dispatch_key == DispatchKey.XPU: + # XPU specific, this header resides in third_party/torch-xpu-ops + headers.append("#include ") + elif backend_index.dispatch_key == DispatchKey.MTIA: + headers.append("#include ") + elif per_operator_headers: + headers += [ + "#include ", + "#include ", + "#include ", + "#include ", + ] + else: + headers.append("#include ") + + headers.append("#include ") + return headers + + +def gen_empty_impl_names( + backend_index: BackendIndex, +) -> tuple[str | None, str | None]: + empty_impl = None + empty_strided_impl = None + + if backend_index.dispatch_key in ( + DispatchKey.Meta, + DispatchKey.CPU, + DispatchKey.CUDA, + DispatchKey.MPS, + DispatchKey.XPU, + DispatchKey.MTIA, + ): + dispatch = str(backend_index.dispatch_key).lower() + empty_impl = f"at::detail::empty_{dispatch}" + empty_strided_impl = f"at::detail::empty_strided_{dispatch}" + elif backend_index.dispatch_key in ( + DispatchKey.CompositeExplicitAutogradNonFunctional, + DispatchKey.QuantizedCPU, + DispatchKey.QuantizedCUDA, + ): + empty_impl = "at::empty" + empty_strided_impl = "at::empty_strided" + + return empty_impl, empty_strided_impl + + +def gen_create_out_helper(backend_index: BackendIndex) -> list[str]: + if backend_index.dispatch_key == DispatchKey.Meta: + empty_options = "options.device(at::kMeta)" + else: + empty_options = "options" + + empty_impl, empty_strided_impl = gen_empty_impl_names(backend_index) + if empty_impl is None: + return [] + + return [ + f""" +Tensor create_out(IntArrayRef sizes, IntArrayRef strides, const TensorOptions &options) {{ + if (strides.empty()) {{ + return {empty_impl}(sizes, {empty_options}); + }} else {{ + return {empty_strided_impl}(sizes, strides, {empty_options}); + }} +}} +""" + ] + + +def gen_maybe_create_proxy_helper(backend_index: BackendIndex) -> list[str]: + _, empty_strided_impl = gen_empty_impl_names(backend_index) + return ( + [] + if empty_strided_impl is None + else [ + f""" +std::optional maybe_create_proxy(const Tensor &out, IntArrayRef sizes, IntArrayRef strides, const TensorOptions &options) {{ + if (out.strides() != strides) {{ + return {empty_strided_impl}(sizes, strides, options); + }} + return std::nullopt; +}} +""" + ] + ) + + +def gen_resize_out_helper(backend_index: BackendIndex) -> list[str]: + if backend_index.dispatch_key == DispatchKey.CompositeExplicitAutogradNonFunctional: + # The function isn't used by this key (since only functional ops have a kernel for this key), + # so we need to not include it to avoid a defined-but-not-used error. + return [] + return [ + """ +void resize_out(const Tensor &out, IntArrayRef sizes, IntArrayRef strides, const TensorOptions &options) { + TORCH_CHECK(options.dtype() == out.dtype(), + "Expected out tensor to have dtype ", options.dtype(), ", but got ", out.dtype(), " instead"); + TORCH_CHECK(options.device() == out.device(), + "Expected out tensor to have device ", options.device(), ", but got ", out.device(), " instead"); + const bool resized = at::native::resize_output(out, sizes); + // Only restride if a resize occurred; otherwise we ignore the (advisory) + // strides from the meta function and directly use the output tensor's + // preexisting strides + if (resized) { + if (!strides.empty()) { + TORCH_INTERNAL_ASSERT(!options.memory_format_opt().has_value()); + // TODO: avoid the redispatch here + out.as_strided_(sizes, strides); + } else if (options.memory_format_opt().has_value()) { + out.unsafeGetTensorImpl()->empty_tensor_restride(*options.memory_format_opt()); + } + } +} +""" + ] + + +def gen_check_inplace_helper(backend_index: BackendIndex) -> list[str]: + return [ + """ +void check_inplace(const Tensor &self, IntArrayRef sizes, const TensorOptions &options) { + // These checks are needed on those operators that: + // 1) don't use 'TensorIterator' (e.g. 'addmm' and 'baddbmm') + // 2) have particular typing rules (e.g. 'cumsum' and 'cumprod') + // For other operators (e.g. 'add'), 'TensorIterator' already checks + // these things separately. + TORCH_CHECK(options.dtype() == self.dtype(), + "Bad in-place call: ", + "input tensor dtype ", self.dtype(), " and output tensor dtype ", options.dtype(), " should match"); + TORCH_CHECK(options.device() == self.device(), + "Bad in-place call: ", + "input tensor device ", self.device(), " and output tensor device ", options.device(), " should match"); + TORCH_CHECK(sizes == self.sizes(), + "Bad in-place call: ", + "input tensor size ", self.sizes(), " and output tensor size ", sizes, " should match"); +} +""" + ] + + +def gen_registration_helpers(backend_index: BackendIndex) -> list[str]: + return [ + 'C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-function")', + *gen_create_out_helper(backend_index), + *gen_resize_out_helper(backend_index), + *gen_check_inplace_helper(backend_index), + *gen_maybe_create_proxy_helper(backend_index), + "C10_DIAGNOSTIC_POP()", + ] + + +# Generates Register{dispatch}.cpp (e.g., RegisterCPU.cpp). +# +# - The primary function of this file is to register all of the +# implementations for the given dispatch key to the dispatcher, +# so they are available for use in PyTorch. If dispatch is +# None, we generate schema (def) registrations and catchall +# registrations. +# - The secondary function of this file is to generate a wrapper +# around functions. In CPUType these wrappers do nothing +# (and should be removed), but in other cases they handle +# DeviceGuard. A small extra benefit of wrappers is they +# are not overloaded, so they can be used in the registration +# API without having to disambiguate which overload you want +# (as would be the case if you directly registered native:: +# functions). +# - The tertiary function of this file is to generate *static* +# cpp API bindings which can be used to bypass dispatcher +# directly to kernels, but with user-friendly cpp-style API +@dataclass(frozen=True) +class RegisterDispatchKey: + backend_index: BackendIndex + + target: Literal[ + Target.ANONYMOUS_DEFINITION, + Target.NAMESPACED_DEFINITION, + Target.NAMESPACED_DECLARATION, + Target.REGISTRATION, + ] + + # Selector object to determine which operators to generate + # registration code for. + selector: SelectiveBuilder + + # Whether or not we are actually code-genning for ROCm + rocm: bool + + # Whether or not to generate symint registrations or not. External users + # of codegen who don't care about symints can set this to false to get + # non-SymInt codegen + symint: bool + + # The class that all unstructured native functions live under. This is used to improve + # compiler error messages when a kernel writer adds a native function with the wrong signature. + # This is only used in unstructured kernels, since structured kernels already live in a class. + # Finally, this field is currently Optional because it is only used by external backends. + # It would be nice if we can add the same logic to in-tree kernels too, but that requires updating + # all of the existing kernel signatures scattered across aten/src/ATen/native. + class_method_name: str | None + + # Only set to true in lightweight dispatch. If lightweight dispatch is enabled we are registering + # operators into JIT op registry, thus we need to avoid generating code to register into the dispatcher. + skip_dispatcher_op_registration: bool + + @staticmethod + def gen_device_check( + type: DeviceCheckType, args: list[Argument], method_name: str + ) -> str: + if type == DeviceCheckType.NoCheck: + return " // No device check\n" + + device_check = "std::optional common_device = std::nullopt;\n" + device_check += "(void)common_device; // Suppress unused variable warning\n" + for arg in args: + # Only tensor like arguments are eligible + if arg.type.is_tensor_like(): + device_check += f""" + c10::impl::check_and_update_common_device(common_device, {arg.name}, "{method_name}", "{arg.name}");""" + return device_check + + @method_with_native_function + def __call__(self, f: NativeFunctionsGroup | NativeFunction) -> list[str]: + if isinstance(f, NativeFunctionsGroup): + g: NativeFunctionsGroup = f + # Note: We call gen_structured() if the operator is marked structured, regardless of the backend. + # gen_structured() has special logic to handle auto-generated kernels. + if g.structured: + return self.gen_structured(g) + else: + return list( + mapMaybe(lambda f: self.gen_unstructured(f, g), g.functions()) + ) + elif isinstance(f, NativeFunction): + r = self.gen_unstructured(f) + return [] if r is None else [r] + else: + assert_never(f) + + def wrapper_kernel_sig( + self, f: NativeFunction + ) -> NativeSignature | DispatcherSignature: + # The prefix is just to ensure uniqueness. The Dispatcher API doesn't guarantee unique kernel names. + return DispatcherSignature.from_schema( + f.func, + prefix=f"wrapper_{self.backend_index.dispatch_key}_{f.func.name.overload_name}_", + symint=self.symint, + ) + + def gen_out_inplace_wrapper( + self, f: NativeFunction, g: NativeFunctionsGroup | None + ) -> str | None: + if g is None: + return None + k = f.func.kind() + if k is SchemaKind.inplace: + copy_op = "at::_copy_from" + elif k is SchemaKind.out: + copy_op = "at::_copy_from_and_resize" + else: + raise AssertionError("gen_out_inplace_wrapper called on a functional op") + + sig = self.wrapper_kernel_sig(f) + name = sig.name() + + func_res = f"{name}_tmp" + return_names = cpp.return_names(f) + if len(return_names) > 1: + updates = "\n ".join( + f"{copy_op}(std::get<{i}>({func_res}), {ret_name});" + for i, ret_name in enumerate(return_names) + ) + returns = f"{sig.returns_type().cpp_type()}({', '.join(return_names)})" + elif len(return_names) == 1: + ret_name = return_names[0] + updates = f"{copy_op}({func_res}, {ret_name});" + returns = ret_name + else: + if len(f.func.arguments.out) != 1: + raise AssertionError( + f"Expected exactly 1 out argument, got {len(f.func.arguments.out)}" + ) + returns = "" + out_arg = f.func.arguments.out[0] + if out_arg.type.is_list_like(): + updates = f"""\ + for (int64_t i = 0; i < {func_res}.size(); ++i) {{ + {copy_op}({func_res}[i], {out_arg.name}[i]); + }}""" + else: + updates = f"{copy_op}({func_res}, {out_arg.name});" + + functional_sig = self.wrapper_kernel_sig(g.functional) + + return f"""\ +{sig.defn(name=name)} {{ + auto {func_res} = {functional_sig.name()}({", ".join(e.expr for e in translate(sig.arguments(), functional_sig.arguments()))}); + {updates} + return {returns}; +}} +""" + + def gen_structured(self, g: NativeFunctionsGroup) -> list[str]: + metadata = self.backend_index.get_kernel(g) + if self.backend_index.dispatch_key == DispatchKey.Meta: + if self.backend_index.has_kernel(g.out): + raise AssertionError( + "Do not explicitly specify Meta dispatch key on structured " + "functions, they will be automatically generated for you" + ) + elif ( + self.backend_index.dispatch_key + == DispatchKey.CompositeExplicitAutogradNonFunctional + ): + if self.backend_index.has_kernel(g.out): + raise AssertionError( + "Do not explicitly specify CompositeExplicitAutograd dispatch key on " + "structured functions, they will be automatically generated for you" + ) + elif metadata is None or not metadata.structured: + return list(mapMaybe(lambda f: self.gen_unstructured(f, g), g.functions())) + structured_gen = StructuredRegisterDispatchKey( + self.backend_index, + self.target, + self.selector, + self.rocm, + self.symint, + self.class_method_name, + self.skip_dispatcher_op_registration, + g, + ) + return list(mapMaybe(structured_gen.gen_one, g.functions())) + + def gen_unstructured( + self, f: NativeFunction, g: NativeFunctionsGroup | None = None + ) -> str | None: + with native_function_manager(f): + inplace_meta = False + gets_out_inplace_wrapper = False + if not self.backend_index.has_kernel(f): + if ( + self.backend_index.dispatch_key == DispatchKey.Meta + and f.func.kind() is SchemaKind.inplace + and + # Defer to composites for meta implementation + not f.has_composite_kernel + and + # Inplace list operations are not supported + len(f.func.returns) == 1 + ): + inplace_meta = True + elif ( + not self.backend_index.use_out_as_primary + and g is not None + and gets_generated_out_inplace_wrapper(f, g, self.backend_index) + ): + # We want to generate inplace/out wrappers, that don't have a kernel for the backend. + gets_out_inplace_wrapper = True + else: + return None + if f.manual_kernel_registration: + return None + + if ( + self.target is Target.REGISTRATION + and not self.selector.is_native_function_selected(f) + ): + return None + + sig = self.wrapper_kernel_sig(f) + + name = sig.name() + returns_type = sig.returns_type().cpp_type() + args = sig.arguments() + args_str = ", ".join(a.defn() for a in args) + + # See Note [Direct dispatch bindings] + cpp_sig_group = CppSignatureGroup.from_native_function( + f, method=False, fallback_binding=False + ) + + # TODO: dedupe this with the structured codegen + if self.target is Target.NAMESPACED_DECLARATION: + result = "" + for cpp_sig in cpp_sig_group.signatures(symint=self.symint): + result += f"TORCH_API {cpp_sig.decl()};\n" + return result + elif self.target is Target.NAMESPACED_DEFINITION: + + def generate_defn(cpp_sig: CppSignature) -> str: + return f""" +{cpp_sig.defn()} {{ +return {sig.name()}({", ".join(e.expr for e in translate(cpp_sig.arguments(), sig.arguments()))}); +}} +""" + + result = "" + for cpp_sig in cpp_sig_group.signatures(symint=self.symint): + result += generate_defn(cpp_sig) + return result + + elif self.target is Target.ANONYMOUS_DEFINITION: + # short circuit for inplace_meta + if inplace_meta: + if f.func.arguments.self_arg is None: + raise AssertionError( + "Expected self_arg to be non-None for inplace_meta" + ) + self_arg_name = f.func.arguments.self_arg.argument.name + # TODO: handle in place on tensor list + return f""" +{returns_type} {name}({args_str}) {{ + TORCH_CHECK_NOT_IMPLEMENTED({self_arg_name}.is_meta(), + "Cannot inplace into non-meta tensor with meta tensor argument"); + return {self_arg_name}; +}} +""" + + # short circuit for generated inplace/out wrappers + if gets_out_inplace_wrapper: + return self.gen_out_inplace_wrapper(f, g) + + metadata = self.backend_index.get_kernel(f) + if metadata is None: + return None + if self.class_method_name is None: + impl_name = f"{metadata.cpp_namespace}::{metadata.kernel}" + else: + impl_name = f"{metadata.cpp_namespace}::{self.class_method_name}::{metadata.kernel}" + + kernel_sig = kernel_signature(f, self.backend_index) + + args_exprs_str = ", ".join( + e.expr + for e in translate( + sig.arguments(), kernel_sig.arguments(), method=False + ) + ) + + device_check = " // No device check\n" + # Backends that require device guards presumably also require device checks. + if self.backend_index.device_guard: + device_check_args = itertools.chain( + f.func.arguments.out, f.func.arguments.flat_positional + ) + device_check = RegisterDispatchKey.gen_device_check( + f.device_check, list(device_check_args), name + ) + + device_guard = "// DeviceGuard omitted" # default + if f.device_guard and self.backend_index.device_guard: + has_tensor_options = any( + isinstance(a, TensorOptionsArguments) + for a in f.func.arguments.non_out + ) + if has_tensor_options: + # kernel is creating a tensor + device_guard = """ + const DeviceGuard device_guard(device_or_default(device));""" + + # CUDA requires special handling + if is_cuda_dispatch_key(self.backend_index.dispatch_key): + device_guard = f"globalContext().lazyInitDevice(c10::DeviceType::CUDA);\n{device_guard}" + else: + # kernel is operating on existing tensors + + # There is precedence for which argument we use to do + # device guard. This describes the precedence order. + self_arg = ( + [f.func.arguments.self_arg.argument] + if f.func.arguments.self_arg is not None + else [] + ) + candidate_args = itertools.chain( + self_arg, + f.func.arguments.out, + f.func.arguments.flat_positional, + ) + + # Only tensor like arguments are eligible + device_of = next( + ( + f"{a.name}" + for a in candidate_args + if a.type.is_tensor_like() + ), + None, + ) + if device_of is not None: + device_guard = f"const OptionalDeviceGuard device_guard(device_of({device_of}));" + + return f"""\ +namespace {{ + +{returns_type} {name}({args_str}) {{ + {device_check} + + {device_guard} + return {impl_name}({args_exprs_str}); +}} + +}} // anonymous namespace +""" + + elif self.target is Target.REGISTRATION: + if f.manual_kernel_registration or self.skip_dispatcher_op_registration: + return None + else: + payload = f"TORCH_FN({name})" + return f'm.impl("{f.func.name}",\n{payload});\n' + else: + assert_never(self.target) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# STRUCTURED +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +@dataclass(frozen=True) +class StructuredRegisterDispatchKey(RegisterDispatchKey): + g: NativeFunctionsGroup + + def gen_class_set_output_functions( + self, k: SchemaKind, parent_class: str, generate_super: bool + ) -> str: + if generate_super: + set_output_super = f"{parent_class}::set_output_raw_strided(output_idx, sizes, strides, options);" + else: + set_output_super = "" + + def gen_set_output_function(name: str, maybe_create_proxy: bool) -> str: + return f""" +void set_output_{name}( + int64_t output_idx, IntArrayRef sizes, IntArrayRef strides, + TensorOptions options +) override {{ +{textwrap.indent(self.gen_class_set_output_body(k, maybe_create_proxy), " ")} + // super must happen after, so that downstream can use maybe_get_output + // to retrieve the output +{textwrap.indent(set_output_super, " ")} +}} +""" + + return f""" +{gen_set_output_function("strided", maybe_create_proxy=True)} +{gen_set_output_function("raw_strided", maybe_create_proxy=False)} +""" + + def gen_class_set_output_body(self, k: SchemaKind, maybe_create_proxy: bool) -> str: + if self.backend_index.dispatch_key in [ + DispatchKey.CUDA, + DispatchKey.MPS, + DispatchKey.XPU, + DispatchKey.CompositeExplicitAutogradNonFunctional, + ]: + maybe_set_guard = """ +auto current_device = guard_.current_device(); +if (C10_UNLIKELY(current_device.has_value())) { + TORCH_INTERNAL_ASSERT(*current_device == options.device(), + "structured kernels don't support multi-device outputs"); +} else { + guard_.reset_device(options.device()); +} +""" + maybe_set_guard_line = maybe_set_guard + "\n" + else: + maybe_set_guard_line = maybe_set_guard = "" + + if maybe_create_proxy: + create_proxy = """ +auto maybe_proxy = maybe_create_proxy(out, sizes, strides, options); +if (C10_UNLIKELY(maybe_proxy.has_value())) { + proxy_outputs_[output_idx] = std::move(maybe_proxy).value(); +} +""" + else: + create_proxy = "" + + if k is SchemaKind.functional: + if self.backend_index.dispatch_key not in ( + DispatchKey.Meta, + DispatchKey.CPU, + DispatchKey.CUDA, + DispatchKey.MPS, + DispatchKey.XPU, + DispatchKey.MTIA, + DispatchKey.CompositeExplicitAutogradNonFunctional, + ): + raise AssertionError( + f"Unexpected dispatch key {self.backend_index.dispatch_key} " + "for functional schema" + ) + return f"""{maybe_set_guard_line} +outputs_[output_idx] = create_out(sizes, strides, options);""" + elif k is SchemaKind.inplace: + return f"""{maybe_set_guard_line} +const auto& out = outputs_[output_idx].get(); +check_inplace(out, sizes, options); +{create_proxy}""" + elif k is SchemaKind.out: + return f"""{maybe_set_guard_line} +const auto& out = outputs_[output_idx].get(); +resize_out(out, sizes, strides, options); +{create_proxy}""" + elif k is SchemaKind.mutable or k is SchemaKind.scratch: + raise AssertionError( + f"{k} structured operators are currently not supported" + ) + else: + assert_never(k) + + # returns the definition of a ctor, as well as how to construct + # this class to a variable named op + def gen_class_ctor(self, k: SchemaKind, class_name: str, returns: int) -> str: + if k is SchemaKind.functional: + return "" + elif k is SchemaKind.inplace: + # TODO: Make sure out argument is guaranteed to be self + return f"{class_name}(Tensor& self) : outputs_{{std::ref(self)}} {{}}" + elif k is SchemaKind.out: + out_args = ", ".join(f"Tensor& out{i}" for i in range(returns)) + out_refs = ", ".join(f"std::ref(out{i})" for i in range(returns)) + return f"{class_name}({out_args}) : outputs_{{ {out_refs} }} {{}}" + elif k is SchemaKind.mutable or k is SchemaKind.scratch: + raise AssertionError( + f"{k} structured operators are currently not supported" + ) + else: + assert_never(k) + + def gen_class( + self, + f: NativeFunction, + k: SchemaKind, + *, + class_name: str, + parent_class: str, + generate_super: bool, + ) -> str: + if k is SchemaKind.functional: + output_type = "Tensor" + output_value = "outputs_[output_idx]" + proxy_field = "" + elif k is SchemaKind.inplace or k is SchemaKind.out: + output_type = "std::reference_wrapper" + output_value = "proxy_outputs_[output_idx].has_value() ? *proxy_outputs_[output_idx] : outputs_[output_idx].get()" + proxy_field = f"std::array<::std::optional, {len(f.func.returns)}> proxy_outputs_;" + else: + raise RuntimeError(f"Unsupported SchemaKind {k}") + + if self.backend_index.dispatch_key == DispatchKey.CUDA: + guard_field = "c10::cuda::OptionalCUDAGuard guard_;" + elif ( + self.backend_index.dispatch_key + == DispatchKey.CompositeExplicitAutogradNonFunctional + ): + guard_field = "c10::OptionalDeviceGuard guard_;" + elif self.backend_index.dispatch_key == DispatchKey.MPS: + # TODO: Move to OptionalMPSGuard. + guard_field = "c10::OptionalDeviceGuard guard_;" + elif self.backend_index.dispatch_key == DispatchKey.XPU: + guard_field = "c10::OptionalDeviceGuard guard_;" + elif self.backend_index.dispatch_key == DispatchKey.MTIA: + guard_field = "c10::OptionalDeviceGuard guard_;" + else: + guard_field = "" + + indent = " " * 4 + class_ctor_str = self.gen_class_ctor(k, class_name, len(f.func.returns)) + lines = ( + f"struct {class_name} final : public {parent_class} {{", + f"{textwrap.indent(class_ctor_str, indent)}", + f"{textwrap.indent(self.gen_class_set_output_functions(k, parent_class, generate_super), indent)}", + " const Tensor& maybe_get_output(int64_t output_idx) override {", + f" return {output_value};\n", # type: ignore[possibly-undefined] # TODO: audit + " }", + # type: ignore[possibly-undefined] # TODO: audit + f" std::array<{output_type}, {len(f.func.returns)}> outputs_;", + f"{textwrap.indent(proxy_field, indent)}", # type: ignore[possibly-undefined] # TODO: audit + f"{textwrap.indent(guard_field, indent)}", + "};", + ) + return "\n".join(line for line in lines if line) + + @method_with_native_function + def gen_one(self, f: NativeFunction) -> str | None: + if f.manual_kernel_registration: + raise AssertionError( + f"Function {f.func.name} has manual_kernel_registration=True" + ) + + if ( + self.target is Target.REGISTRATION + and not self.selector.is_native_function_selected(f) + ): + return None + + # TODO: Now, there is something interesting going on here. In the code below, + # we generate CompositeExplicitAutogradNonFunctional implementations of functional and inplace + # based on the out implementation. But in fact, out is definable by + # functional too (just not very efficiently), and this is honestly the + # MORE likely situation for a backend implementer. How do we pick? + # Well, taking a page from Haskell type classes and default methods, + # we could conceivably register a circular definition (out in terms + # of functional, and functional in terms of out) and just require + # someone to implement one or the other. We'd have to do a little bit + # of work to not register one of these "weak" definitions unless there + # is a strong definition somewhere in the DAG! So it's not implemented yet. + if ( + self.backend_index.dispatch_key + == DispatchKey.CompositeExplicitAutogradNonFunctional + and f.func.kind() is SchemaKind.out + ): + # Never generate a default implementation for out, that's what you + # have to define as a backend implementer + return None + + # Note [Direct dispatch bindings] + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # Signature of the non-dispatched function we'll expose in a header + # (e.g., at::cpu::add). We don't generate methods (TODO: do this + # when CPUTensor class is a thing); nor do we generate fallback + # bindings for manual_cpp_binding functions. + cpp_sig_group = CppSignatureGroup.from_native_function( + f, method=False, fallback_binding=False + ) + + # Signature of the wrapper function we'll register to the dispatcher + kern = self.backend_index.get_kernel(f) + sig = NativeSignature( + f.func, + prefix=f"wrapper_{self.backend_index.dispatch_key}_", + symint=kern is not None and kern.supports_symint(), + ) + + if self.target is Target.NAMESPACED_DECLARATION: + result = "" + for cpp_sig in cpp_sig_group.signatures(symint=self.symint): + result += f"TORCH_API {cpp_sig.decl()};\n" + return result + + elif self.target is Target.NAMESPACED_DEFINITION: + + def generate_defn(cpp_sig: CppSignature) -> str: + return f""" +{cpp_sig.defn()} {{ +return {sig.name()}({", ".join(e.expr for e in translate(cpp_sig.arguments(), sig.arguments()))}); +}} +""" + + result = "" + for cpp_sig in cpp_sig_group.signatures(symint=self.symint): + result += generate_defn(cpp_sig) + return result + + elif self.target is Target.ANONYMOUS_DEFINITION: + k = f.func.kind() + + # Construct the body of the wrapper function with signature sig + sig_body = [] + # We'll use context to keep track of any variables we've brought + # into scope while generating code + context: list[Binding | Expr] = list(sig.arguments()) + + # Initialize the class corresponding to this structured + # operator; feeding it the output argument(s) if it is known + if self.backend_index.dispatch_key is DispatchKey.Meta: + class_name = f"structured_{meta.name(self.g)}_meta_{k.name}" + parent_class = f"at::meta::structured_{meta.name(self.g)}" + elif ( + self.backend_index.dispatch_key + is DispatchKey.CompositeExplicitAutogradNonFunctional + ): + # TODO: dedup this branch + class_name = f"structured_{meta.name(self.g)}_default_backend_{k.name}" + parent_class = f"at::meta::structured_{meta.name(self.g)}" + else: + metadata = self.backend_index.get_kernel(self.g) + if metadata is None: + raise AssertionError( + f"No kernel metadata found for {self.g.functional.func.name}" + ) + class_name = f"structured_{metadata.kernel}_{k.name}" + parent_class = f"{metadata.cpp_namespace}::structured_{metadata.kernel}" + + if self.backend_index.device_guard: + device_check_args = itertools.chain( + f.func.arguments.out, f.func.arguments.flat_positional + ) + sig_body.append( + RegisterDispatchKey.gen_device_check( + f.device_check, list(device_check_args), sig.name() + ) + ) + + if k is SchemaKind.functional: + sig_body.append(f"{class_name} op;") + elif k is SchemaKind.inplace: + sig_body.append(f"{class_name} op(self);") + elif k is SchemaKind.out: + out_args_str = ", ".join(a.name for a in f.func.arguments.out) + sig_body.append(f"{class_name} op({out_args_str});") + + # Translate the input native arguments into structured + # arguments for the meta call + meta_exprs = ", ".join( + e.expr + for e in translate( + context, structured.meta_arguments(self.g), method=False + ) + ) + + if self.g.out.precomputed: + # If this function group has precomputed elements, the meta function + # returns a struct containing them which must be saved so that it + # can be unpacked when generating code to call the impl. + sig_body.append(f"auto precompute = op.meta({meta_exprs});") + + # Put all of the contents of the precompute struct into the context + # so that translate will be able to return the correct args for the + # call to the impl. + precomputed_values = [ + *self.g.out.precomputed.replace.values(), + self.g.out.precomputed.add, + ] + for precomputed_elems in precomputed_values: + context.extend( + Expr( + expr=f"precompute.{arg.name}", + type=structured.argument_type(arg, binds=arg.name), + ) + for arg in precomputed_elems + ) + + # Add a use of the precompute struct so FB internal compilers don't + # complain that there is an unused variable. + sig_body.append("(void)precompute;") + else: + sig_body.append(f"op.meta({meta_exprs});") + + # After running meta, op.outputs_ is guaranteed to be valid; + # add it to the context + out_args = structured.out_arguments(self.g) + for i, out_arg in enumerate(out_args): + if ConstRefCType(BaseCType(tensorT)) != out_arg.nctype.type: + raise AssertionError( + f"Expected out_arg type to be ConstRefCType(BaseCType(tensorT)), " + f"got {out_arg.nctype.type}" + ) + + if k is SchemaKind.out: + expr = f"op.maybe_get_output({i})" + else: + expr = f"op.outputs_[{i}]" + + context.append( + Expr( + expr=expr, + # TODO: Stop hardcoding that the output type is a Tensor. Note + # that for the codegen here this is fine because outputs_ is + # hardcoded to be tensor already + type=NamedCType( + out_arg.nctype.name, MutRefCType(BaseCType(tensorT)) + ), + ) + ) + + # With the expanded context, do the impl call (if not a meta + # function) + if ( + self.backend_index.dispatch_key + == DispatchKey.CompositeExplicitAutogradNonFunctional + ): + # TODO: https://github.com/pytorch/pytorch/issues/53023 + out_sig_group = CppSignatureGroup.from_native_function( + self.g.out, method=False, fallback_binding=f.manual_cpp_binding + ) + out_sig = out_sig_group.most_faithful_signature() + api_name = out_sig.name() + out_exprs = ", ".join( + e.expr + for e in translate(context, out_sig.arguments(), method=False) + ) + # TODO: I think this means structured won't work with method + # only functions (but maybe you're saved by faithful? iunno.) + # NB: Originally I wrote this as an at::redispatch call, but + # I got in trouble because that meant I needed a DispatchKeySet + # in the wrapper function, which meant I needed a DispatchKeySet + # in the DispatchKeyFunctions declarations, but the defined API + # there does NOT permit a dispatch key set. I think you can + # probably unwind this by calling some function to do the TLS + # fetch and get the DispatchKeySet when you don't have it, but + # I didn't do it for this version + sig_body.append(f"at::{api_name}({out_exprs});") + elif self.backend_index.dispatch_key != DispatchKey.Meta: + impl_exprs = ", ".join( + e.expr + for e in translate( + context, structured.impl_arguments(self.g), method=False + ) + ) + sig_body.append(f"op.impl({impl_exprs});") + + # Go over each output, and check if there is a proxy created for it. + # If so, copy it over to the original output. + if k is SchemaKind.out or k is SchemaKind.inplace: + for i in range(len(f.func.returns)): + sig_body.append( + f"if (op.proxy_outputs_[{i}].has_value()) op.outputs_[{i}].get().copy_(*op.proxy_outputs_[{i}]);" + ) + + # Destructively return the final tensors + # TODO: Do this in translate instead + if k is SchemaKind.functional: + if len(f.func.returns) == 1: + ret_expr = "std::move(op.outputs_[0])" # small optimization + else: + moved = ", ".join( + f"std::move(op.outputs_[{i}])" + for i in range(len(f.func.returns)) + ) + ret_expr = f"std::make_tuple({moved})" + elif k is SchemaKind.inplace: + ret_expr = "self" + elif k is SchemaKind.out: + if len(f.func.returns) == 1: + ret_expr = f.func.arguments.out[0].name + else: + refs = ", ".join(a.name for a in f.func.arguments.out) + ret_expr = f"std::forward_as_tuple({refs})" + sig_body.append(f"return {ret_expr};") # type: ignore[possibly-undefined] # TODO: audit + + sig_body_str = "\n".join(sig_body) + + # For an overview of what this template code looks like, see + # https://github.com/pytorch/rfcs/pull/9 + return f"""\ +{ + self.gen_class( + f, + k, + class_name=class_name, + parent_class=parent_class, + generate_super=self.g.out.structured_inherits is not None, + ) + } + +{sig.defn()} {{ +{sig_body_str} +}} +""" + + elif self.target is Target.REGISTRATION: + return f'm.impl("{f.func.name}", TORCH_FN({sig.name()}));' + else: + assert_never(self.target) + # Silence mypy's "Missing return statement" error + return None diff --git a/.venv/lib/python3.12/site-packages/torchgen/dest/ufunc.py b/.venv/lib/python3.12/site-packages/torchgen/dest/ufunc.py new file mode 100644 index 0000000000000000000000000000000000000000..82ba5352e586d509cd8a26fc6c63ed249e5e35c8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/dest/ufunc.py @@ -0,0 +1,561 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import torchgen.api.ufunc as ufunc +from torchgen.api.translate import translate +from torchgen.api.types import ( + BaseCType, + Binding, + CType, + Expr, + NamedCType, + opmath_t, + scalar_t, + StructuredImplSignature, + VectorizedCType, +) +from torchgen.context import with_native_function +from torchgen.model import ( + Argument, + BaseTy, + BaseType, + DispatchKey, + NativeFunctionsGroup, + ScalarType, + UfuncKey, +) +from torchgen.utils import OrderedSet + + +if TYPE_CHECKING: + from collections.abc import Sequence + + from torchgen.api.ufunc import UfunctorBindings + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# CUDA STUFF +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + +# NB: not bothering to generate dispatch stub forward declaration in header, +# we can just paste it wherever necessary + +# TODO: use BackendIndex +# dispatch_key: DispatchKey # only CPU/CUDA right now + + +# Represents functors for implementing CUDA ufuncs. +# Functors are templated by scalar_t because when USERS instantiate functors +# they are templated. A functor looks something like this: +# +# template +# struct CUDAFunctorOnSelf_add { +# using opmath_t = at::opmath_type; +# opmath_t other_; +# opmath_t alpha_; +# CUDAFunctorOnSelf_add(opmath_t other, opmath_t alpha) +# : other_(other), alpha_(alpha) {} +# __device__ scalar_t operator()(scalar_t self) { +# return ufunc::add(static_cast(self), other_, alpha_); +# } +# }; +# +@dataclass(frozen=True) +class UfunctorSignature: + g: NativeFunctionsGroup + scalar_tensor_idx: int | None + name: str + + def arguments(self) -> UfunctorBindings: + return ufunc.ufunctor_arguments( + self.g, scalar_tensor_idx=self.scalar_tensor_idx, scalar_t=scalar_t + ) + + def fields(self) -> list[Binding]: + # fields are renamed to have a trailing underscore, as is conventional + return [b.rename(f"{b.name}_") for b in self.arguments().ctor] + + def returns_type(self) -> CType: + # TODO: don't hardcode; return type will be inferred based on tags on + # the native function + return BaseCType(scalar_t) + + def decl_fields(self) -> str: + return "\n".join(f"{f.type} {f.name};" for f in self.fields()) + + def inline_defn_ctor(self) -> str: + args_str = ", ".join(a.decl() for a in self.arguments().ctor) + # NB: hypothetically could do this with translate but the + # transition here is very regular + init_str = ", ".join(f"{a.name}_({a.name})" for a in self.arguments().ctor) + return f"{self.name}({args_str}) : {init_str} {{}}" + + def decl_apply(self) -> str: + args_str = ", ".join(a.decl() for a in self.arguments().apply) + return f"{self.returns_type().cpp_type()} operator()({args_str}) const" + + +@dataclass(frozen=True) +class UfuncSignature: + g: NativeFunctionsGroup + name: str + compute_t: CType + + def arguments(self) -> list[Binding]: + return ufunc.ufunc_arguments(self.g, compute_t=self.compute_t) + + def call(self, ctx: Sequence[Binding | Expr]) -> str: + return f"{self.name}({', '.join(a.expr for a in translate(ctx, self.arguments()))})" + + +# steps: +# 1. take the functional signature +# 2. use api.ufunc to convert it to template signature. this establishes +# the type of the template function +# 3. use api.ufunc (II) to generate a split struct / operator() signature. +# this establish context in which we call the template signature +# +# StructuredImplSignature context +# ~> functor constructor sig +# +# Functor constructor context +# ~> functor fields sig +# +# Functor apply context (functor fields + functor apply sig) +# ~> template sig +# + + +def eligible_for_binary_scalar_specialization(g: NativeFunctionsGroup) -> bool: + num_tensors = sum( + 1 for a in g.functional.func.arguments.flat_non_out if a.type.is_tensor_like() + ) + return num_tensors == 2 + + +def compute_ufunc_cuda_functors( + g: NativeFunctionsGroup, +) -> tuple[dict[ScalarType, dict[UfuncKey, UfunctorSignature]], str]: + # First, build the functors. + ufunctor_sigs: dict[ScalarType, dict[UfuncKey, UfunctorSignature]] = {} + ufunctors: list[str] = [] + loops = g.out.ufunc_inner_loop + scalar_tensor_idx_lookup = { + UfuncKey.CUDAFunctorOnSelf: 1, + UfuncKey.CUDAFunctorOnOther: 0, + UfuncKey.CUDAFunctor: None, + } + if eligible_for_binary_scalar_specialization(g): + keys = [ + UfuncKey.CUDAFunctorOnSelf, + UfuncKey.CUDAFunctorOnOther, + UfuncKey.CUDAFunctor, + ] + else: + keys = [UfuncKey.CUDAFunctor] + for k in [UfuncKey.CUDAFunctorOnSelf, UfuncKey.CUDAFunctorOnOther]: + if k in loops: + raise AssertionError(f"cannot use {k} on non-binary function") + for k in keys: + # If the key was directly defined, skip functor codegen; we assume the + # user already done it for us + if k in loops: + ufunctor_sig = UfunctorSignature( + g, scalar_tensor_idx=scalar_tensor_idx_lookup[k], name=loops[k].name + ) + for dtype in loops[k].supported_dtypes: + ufunctor_sigs.setdefault(dtype, {})[k] = ufunctor_sig + continue + + # Note [ScalarOnly and Generic must match names for CUDA] + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # Otherwise, look in ANY of the generic entries. For simplicity of + # codegen, both ScalarOnly and Generic are defined, the ufunc name + # must match (if they didn't match, we'd have to generate distinct + # functors per dtype, which is awful, so we're not going to do it unless + # someone really forces us to) + ufunc_name = None + supported_dtypes: OrderedSet[ScalarType] = OrderedSet() + for lk in [UfuncKey.ScalarOnly, UfuncKey.Generic]: + if lk not in loops: + continue + if ufunc_name is None: + ufunc_name = loops[lk].name + else: + # See Note [ScalarOnly and Generic must match names for CUDA] + if ufunc_name != loops[lk].name: + raise AssertionError( + "ScalarOnly and Generic must have same ufunc name" + ) + supported_dtypes |= loops[lk].supported_dtypes + if ufunc_name is None: + raise AssertionError("ufunc_name must be non-None") + + name = f"{k}_{ufunc_name}" + ufunctor_sig = UfunctorSignature( + g, scalar_tensor_idx=scalar_tensor_idx_lookup[k], name=name + ) + for dtype in supported_dtypes: + ufunctor_sigs.setdefault(dtype, {})[k] = ufunctor_sig + + ufunc_sig = UfuncSignature( + g, name=f"ufunc::{ufunc_name}", compute_t=BaseCType(opmath_t) + ) + apply_ctx = ufunctor_sig.fields() + ufunctor_sig.arguments().apply + ufunctors.append( + f""" +template +struct {ufunctor_sig.name} {{ + using opmath_t = at::opmath_type; + {ufunctor_sig.decl_fields()} + {ufunctor_sig.inline_defn_ctor()} + __device__ {ufunctor_sig.decl_apply()} {{ + return {ufunc_sig.call(apply_ctx)}; + }} +}}; +""" + ) + + return ufunctor_sigs, "\n".join(ufunctors) + + +@dataclass(frozen=True) +class BinaryScalarSpecializationConfig: + scalar_idx: int + ctor_tensor: str + ufunc_key: UfuncKey + + +BinaryScalarSpecializationConfigs = [ + BinaryScalarSpecializationConfig( + scalar_idx=0, + ctor_tensor="self", + ufunc_key=UfuncKey.CUDAFunctorOnOther, + ), + BinaryScalarSpecializationConfig( + scalar_idx=1, + ctor_tensor="other", + ufunc_key=UfuncKey.CUDAFunctorOnSelf, + ), +] + + +def compute_ufunc_cuda_dtype_body( + g: NativeFunctionsGroup, + dtype: ScalarType, + inner_loops: dict[UfuncKey, UfunctorSignature], + parent_ctx: Sequence[Binding], +) -> str: + body = "using opmath_t = at::opmath_type;" + body += "if (false) {}\n" # for ease of codegen + for config in BinaryScalarSpecializationConfigs: + if config.ufunc_key not in inner_loops: + continue + ufunctor_sig = inner_loops[config.ufunc_key] + scalar_idx = config.scalar_idx + 1 + # Make a copy and at the same time widen the type (not permissible + # without copy; we don't want to mutate the input argument anyway) + ctx: list[Expr | Binding] = list(parent_ctx) + ctx.append( + Expr( + expr=f"iter.scalar_value({scalar_idx})", + type=NamedCType(config.ctor_tensor, BaseCType(opmath_t)), + ) + ) + ufunctor_ctor_exprs_str = ", ".join( + a.expr for a in translate(ctx, ufunctor_sig.arguments().ctor) + ) + + # NB: ufunctor must be allocated before iter.remove_operand is called, + # as it relies on iter + body += f"""\ +else if (iter.is_cpu_scalar({scalar_idx})) {{ + {ufunctor_sig.name} ufunctor({ufunctor_ctor_exprs_str}); + iter.remove_operand({scalar_idx}); + gpu_kernel(iter, ufunctor); +}}""" + + ufunctor_sig = inner_loops[UfuncKey.CUDAFunctor] + ufunctor_ctor_exprs_str = ", ".join( + a.expr for a in translate(parent_ctx, ufunctor_sig.arguments().ctor) + ) + body += f""" +else {{ + gpu_kernel(iter, {ufunctor_sig.name}({ufunctor_ctor_exprs_str})); +}} + """ + return body + + +@with_native_function +def compute_ufunc_cuda(g: NativeFunctionsGroup) -> str: + # First, build the functors, indexing them by dtype + ufunctor_sigs, ufunctors = compute_ufunc_cuda_functors(g) + + # Next, build the conditionals + sig = StructuredImplSignature(g, ufunc.kernel_name(g, DispatchKey.CUDA)) + dtype_cases = [] + for dtype, inner_ufunc_sigs in ufunctor_sigs.items(): + dtype_cases.append( + f""" +AT_DISPATCH_CASE(at::ScalarType::{dtype}, + [&]() {{ + {compute_ufunc_cuda_dtype_body(g, dtype, inner_ufunc_sigs, sig.arguments())} + }} +) +""" + ) + + dtype_cases_str = "\n".join(dtype_cases) + + stub_sig = StubSignature(g) + + return f""" +{ufunctors} + +{stub_sig.type_defn()}; +{stub_sig.dispatch_decl()} + +{stub_sig.kernel_defn()} {{ + AT_DISPATCH_SWITCH(iter.common_dtype(), "{sig.name}", + {dtype_cases_str} + ); +}} +REGISTER_DISPATCH({stub_sig.name}, &{stub_sig.kernel_name}) + +{sig.defn()} {{ + {stub_sig.direct_call(sig.arguments())}; +}} +""" + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# CPU STUFF +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +@dataclass(frozen=True) +class StubSignature: + g: NativeFunctionsGroup + + @property + def name(self) -> str: + return f"{str(self.g.functional.func.name.name)}_stub" + + @property + def kernel_name(self) -> str: + return f"{str(self.g.functional.func.name.name)}_kernel" + + @property + def type_name(self) -> str: + return f"{str(self.g.functional.func.name.name)}_fn" + + def arguments(self) -> list[Binding]: + return ufunc.stub_arguments(self.g) + + def type(self) -> str: + cpp_args = self.arguments() + return f"void(*)(TensorIteratorBase&, {', '.join(a.type for a in cpp_args)})" + + def dispatch_decl(self) -> str: + return f"DECLARE_DISPATCH({self.type_name}, {self.name})" + + def dispatch_defn(self) -> str: + return f"DEFINE_DISPATCH({self.name})" + + def kernel_defn(self) -> str: + return f"void {self.kernel_name}(TensorIteratorBase& iter, {', '.join(a.defn() for a in self.arguments())})" + + def type_defn(self) -> str: + return f"using {self.type_name} = {self.type()}" + + # must be called from context where this is TensorIteratorBase* + def call(self, ctx: Sequence[Binding]) -> str: + return f"{self.name}(device_type(), *this, {', '.join(a.expr for a in translate(ctx, self.arguments()))})" + + # used in CUDA to skip the unnecessary dynamic dispatch + def direct_call(self, ctx: Sequence[Binding]) -> str: + return f"{self.kernel_name}(*this, {', '.join(a.expr for a in translate(ctx, self.arguments()))})" + + +@with_native_function +def compute_ufunc_cpu(g: NativeFunctionsGroup) -> str: + stub_sig = StubSignature(g) + sig = StructuredImplSignature(g, ufunc.kernel_name(g, DispatchKey.CPU)) + + return f""" +{stub_sig.type_defn()}; +{stub_sig.dispatch_decl()} +{stub_sig.dispatch_defn()}; + +{sig.defn()} {{ + {stub_sig.call(sig.arguments())}; +}} +""" + + +def compute_ufunc_cpu_dtype_body( + g: NativeFunctionsGroup, + dtype: ScalarType, + inner_loops: dict[UfuncKey, UfuncSignature], + parent_ctx: Sequence[Binding], +) -> str: + if UfuncKey.CPUScalar not in inner_loops: + raise AssertionError(f"{dtype}, {inner_loops.keys()}") + if not inner_loops.keys() <= {UfuncKey.CPUScalar, UfuncKey.CPUVector}: + raise AssertionError( + f"inner_loops keys must be subset of CPUScalar/CPUVector, got {inner_loops.keys()}" + ) + scalar_loop = inner_loops[UfuncKey.CPUScalar] + vec_loop = None + if UfuncKey.CPUVector in inner_loops: + vec_loop = inner_loops[UfuncKey.CPUVector] + + # NB: We DON'T use translate here, because translate is + # incapable of CSE'ing the scalar accesses in case it is also + # used by Vectorized; also, the unpacking here is very simple + # and only affects Scalar; everything else is implicitly captured + # by the lambda + + # Setup scalar in scope + body = [] + ctx = [] + for b in parent_ctx: + if isinstance(b.argument, Argument) and b.argument.type != BaseType( + BaseTy.Scalar + ): + continue + body.append(f"auto _s_{b.name} = {b.name}.to();") + ctx.append(Expr(f"_s_{b.name}", NamedCType(b.nctype.name, BaseCType(scalar_t)))) + if vec_loop is not None: + for b in parent_ctx: + if isinstance(b.argument, Argument) and b.argument.type != BaseType( + BaseTy.Scalar + ): + continue + body.append( + f"auto _v_{b.name} = at::vec::Vectorized(_s_{b.name});" + ) + ctx.append( + Expr( + f"_v_{b.name}", + NamedCType(b.nctype.name, VectorizedCType(BaseCType(scalar_t))), + ) + ) + + # Setup lambda signature + # NB: simplified version of ufunctor_arguments + scalar_bindings = [] + vec_bindings = [] + for a in g.functional.func.arguments.flat_non_out: + if not a.type.is_tensor_like(): + continue + if a.type != BaseType(BaseTy.Tensor): + raise AssertionError(f"Expected Tensor type, got {a.type}") + scalar_bindings.append( + Binding( + name=a.name, + nctype=NamedCType(a.name, BaseCType(scalar_t)), + argument=a, + ) + ) + if vec_loop is not None: + vec_bindings.append( + Binding( + name=a.name, + nctype=NamedCType(a.name, VectorizedCType(BaseCType(scalar_t))), + argument=a, + ) + ) + + def with_ctx(b: Sequence[Binding]) -> list[Expr | Binding]: + r: list[Expr | Binding] = [] + r.extend(ctx) + r.extend(b) + return r + + body_str = "\n".join(body) + if vec_loop is not None: + return f""" +{body_str} +cpu_kernel_vec(iter, + [=]({", ".join(b.decl() for b in scalar_bindings)}) {{ return {scalar_loop.call(with_ctx(scalar_bindings))}; }}, + [=]({", ".join(b.decl() for b in vec_bindings)}) {{ return {vec_loop.call(with_ctx(vec_bindings))}; }} +); +""" + else: + return f""" +{body_str} +cpu_kernel(iter, + [=]({", ".join(b.decl() for b in scalar_bindings)}) {{ return {scalar_loop.call(with_ctx(scalar_bindings))}; }} +); +""" + + +@with_native_function +def compute_ufunc_cpu_kernel(g: NativeFunctionsGroup) -> str: + stub_sig = StubSignature(g) + + # Reindex the ufunc by dtypes; processing generic/scalaronly as well + loops = g.out.ufunc_inner_loop + ufunc_sigs: dict[ScalarType, dict[UfuncKey, UfuncSignature]] = {} + for k in [UfuncKey.CPUScalar, UfuncKey.CPUVector]: + lks = [] + # ORDER MATTERS: this specifies overriding precedence + if k in loops: # should happen rarely + lks.append(k) + if UfuncKey.ScalarOnly in loops and k is UfuncKey.CPUScalar: + lks.append(UfuncKey.ScalarOnly) + if UfuncKey.Generic in loops: + lks.append(UfuncKey.Generic) + # TODO: don't hardcode ufunc:: namespace here, should be centralized smh + for lk in lks: + for dtype in loops[lk].supported_dtypes: + compute_t: CType + if k is UfuncKey.CPUScalar: + compute_t = BaseCType(scalar_t) + elif k is UfuncKey.CPUVector: + compute_t = VectorizedCType(BaseCType(scalar_t)) + else: + raise AssertionError + inner_ufunc_sigs = ufunc_sigs.setdefault(dtype, {}) + if k not in inner_ufunc_sigs: + inner_ufunc_sigs[k] = UfuncSignature( + g, name=f"ufunc::{loops[lk].name}", compute_t=compute_t + ) + + # Build the conditionals + dtype_cases = [] + for dtype, inner_ufunc_sigs in ufunc_sigs.items(): + dtype_cases.append( + f""" +AT_DISPATCH_CASE(at::ScalarType::{dtype}, + [&]() {{ + {compute_ufunc_cpu_dtype_body(g, dtype, inner_ufunc_sigs, stub_sig.arguments())} + }} +) +""" + ) + + dtype_cases_str = "\n".join(dtype_cases) + return f""" +namespace {{ + +{stub_sig.kernel_defn()} {{ + AT_DISPATCH_SWITCH(iter.common_dtype(), "{stub_sig.name}", + {dtype_cases_str} + ); +}} + +}} // anonymous namespace + +{stub_sig.type_defn()}; +{stub_sig.dispatch_decl()} +REGISTER_DISPATCH({stub_sig.name}, &{stub_sig.kernel_name}) +""" diff --git a/.venv/lib/python3.12/site-packages/torchgen/gen.py b/.venv/lib/python3.12/site-packages/torchgen/gen.py new file mode 100644 index 0000000000000000000000000000000000000000..2832fd3a1f990a25c90d045964e34fab7ed56f1c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/gen.py @@ -0,0 +1,3092 @@ +from __future__ import annotations + +import argparse +import functools +import json +import keyword +import os +from collections import defaultdict, namedtuple, OrderedDict +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal, TYPE_CHECKING, TypeVar +from typing_extensions import assert_never + +import yaml + +import torchgen.api.dispatcher as dispatcher +import torchgen.api.meta as meta +import torchgen.api.native as native +import torchgen.api.structured as structured +import torchgen.dest as dest +from torchgen.api import cpp +from torchgen.api.translate import translate +from torchgen.api.types import ( + Binding, + CppSignature, + CppSignatureGroup, + DispatcherSignature, + NamedCType, + NativeSignature, + SpecialArgName, +) +from torchgen.context import ( + method_with_native_function, + native_function_manager, + with_native_function, + with_native_function_and_indices, +) +from torchgen.gen_aoti_c_shim import ( + gen_aoti_c_shim_files, + gen_static_dispatch_backend_call_signature, +) +from torchgen.gen_functionalization_type import ( + gen_functionalization_definition, + gen_functionalization_registration, + gen_functionalization_view_inverse_declaration, + gen_functionalization_view_meta_classes_decl, + gen_functionalization_view_meta_classes_impl, + GenCompositeViewCopyKernel, +) +from torchgen.gen_vmap_plumbing import gen_all_vmap_plumbing +from torchgen.model import ( + Argument, + BackendIndex, + BackendMetadata, + BaseOperatorName, + DEFAULT_KERNEL_NAMESPACE, + dispatch_device_map, + DispatchKey, + FRAGMENT_NAMESPACES, + FunctionSchema, + is_cuda_dispatch_key, + is_generic_dispatch_key, + is_ufunc_dispatch_key, + is_xpu_dispatch_key, + Location, + NativeFunction, + NativeFunctionsGroup, + NativeFunctionsViewGroup, + OperatorName, + OptionalType, + SchemaKind, + SelfArgument, + STRUCTURED_DISPATCH_KEYS, + TensorOptionsArguments, + Type, + Variant, + ViewSchemaKind, +) +from torchgen.native_function_generation import ( + add_generated_native_functions, + gen_composite_functional_kernel, + gen_composite_out_kernel, + pre_group_native_functions, +) +from torchgen.selective_build.selector import SelectiveBuilder +from torchgen.utils import ( + concatMap, + context, + FileManager, + make_file_manager, + mapMaybe, + NamespaceHelper, + Target, +) +from torchgen.yaml_utils import YamlDumper, YamlLoader + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + +T = TypeVar("T") + +# Welcome to the ATen code generator v2! The ATen code generator is +# responsible for parsing native_functions.yaml and then generating +# various generated files (e.g., TypeDefault.cpp) based on the operators +# defined in this file. This means that the code generator knows how to +# parse function schema, and then translate this into various C++ types +# and boilerplate code. +# +# Some things to know about this file when you modify it: +# +# - This file has STRICT mypy typechecking. Typecheck it with +# `mypy --config mypy-strict.ini` in the root source directory +# +# - Most of the heavy lifting lives in external modules: +# - 'model' has the data model for native_functions.yaml. The classes +# in those file represent what you see when you look at +# a native_functions.yaml +# - 'api' has conversions for how to translate JIT schema into +# the various C++ APIs that the codegen interacts with. There +# are in fact THREE different C++ APIs: the public C++ API, +# the dispatcher API, and the legacy dispatcher API. See each +# of these respective files for more information + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# HELPER FUNCTIONS +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +# A custom loader for YAML to let us also keep track of line numbers +# of each entry in the YAML file +class LineLoader(YamlLoader): + def construct_mapping(self, node, deep=False): # type: ignore[no-untyped-def] + mapping = super().construct_mapping(node, deep=deep) # type: ignore[no-untyped-call] + # Add 1 so line numbering starts at 1 + mapping["__line__"] = node.start_mark.line + 1 + return mapping + + +# Parse native_functions.yaml into a sequence of NativeFunctions and Backend Indices. +ParsedYaml = namedtuple("ParsedYaml", ["native_functions", "backend_indices"]) + + +_GLOBAL_PARSE_NATIVE_YAML_CACHE: dict[str, ParsedYaml] = {} +_GLOBAL_PARSE_TAGS_YAML_CACHE: dict[str, set[str]] = {} + + +def file_manager_from_dispatch_key( + dispatch_key: DispatchKey, + device_fms: dict[str, FileManager], + default_fm: FileManager, +) -> FileManager: + fm = device_fms.get( + next( + ( + device + for check, device in dispatch_device_map.items() + if check(dispatch_key) + ), + "", + ), + default_fm, + ) + return fm + + +def parse_native_yaml_struct( + es: object, + valid_tags: set[str], + ignore_keys: set[DispatchKey] | None = None, + path: str = "", + skip_native_fns_gen: bool = False, +) -> ParsedYaml: + if not isinstance(es, list): + raise AssertionError(f"Expected 'es' to be a list, but got {type(es)}") + rs: list[NativeFunction] = [] + bs: dict[DispatchKey, dict[OperatorName, BackendMetadata]] = defaultdict(dict) + for e in es: + if not isinstance(e, dict): + raise AssertionError(f"Expected to be dict: {e}") + if not isinstance(e.get("__line__"), int): + raise AssertionError(f"Expected '__line__' to be int: {e}") + loc = Location(path, e["__line__"]) + funcs = e.get("func") + if funcs is None: + raise AssertionError(f"Missed 'func' in {e}") + with context(lambda: f"in {loc}:\n {funcs}"): + func, m = NativeFunction.from_yaml(e, loc, valid_tags, ignore_keys) + rs.append(func) + BackendIndex.grow_index(bs, m) + error_check_native_functions(rs) + # Default dict is to prevent the codegen from barfing when we have a dispatch key that has no kernels yet. + indices: dict[DispatchKey, BackendIndex] = defaultdict( + lambda: BackendIndex( + dispatch_key=DispatchKey.Undefined, + use_out_as_primary=True, + external=False, + device_guard=False, + # I'm actually not sure about this; undefined could be hit on + # empty TensorList, hypothetically that could have sizes in it + index={}, + ) + ) + if not skip_native_fns_gen: + add_generated_native_functions(rs, bs) + for k, v in bs.items(): + # All structured in-tree operators are implemented in terms of their out operator. + indices[k] = BackendIndex( + dispatch_key=k, + use_out_as_primary=True, + external=False, + # Only cuda-like devices in tree require device guards + device_guard=is_cuda_dispatch_key(k) or is_xpu_dispatch_key(k), + index=v, + ) + return ParsedYaml(rs, indices) + + +def parse_tags_yaml_struct(es: object, path: str = "") -> set[str]: + if not isinstance(es, list): + raise AssertionError(f"Expected 'es' to be a list, but got {type(es)}") + rs: set[str] = set() + for e in es: + if not isinstance(e.get("__line__"), int): + raise AssertionError(f"Expected '__line__' to be int: {e}") + loc = Location(path, e["__line__"]) + tags = e.get("tag") + with context(lambda: f"in {loc}:\n {tags}"): + e_i = e.copy() + name = e_i.pop("tag") + desc = e_i.pop("desc", "") + # ensure that each tag has a non-empty description + if desc == "": + raise AssertionError(f"Tag '{name}' must have a non-empty description") + rs.add(name) + return rs + + +@functools.cache +def parse_tags_yaml(path: str) -> set[str]: + global _GLOBAL_PARSE_TAGS_YAML_CACHE + if path not in _GLOBAL_PARSE_TAGS_YAML_CACHE: + with open(path) as f: + es = yaml.load(f, Loader=LineLoader) + _GLOBAL_PARSE_TAGS_YAML_CACHE[path] = parse_tags_yaml_struct(es, path=path) + + return _GLOBAL_PARSE_TAGS_YAML_CACHE[path] + + +def parse_native_yaml( + path: str, + tags_yaml_path: str, + ignore_keys: set[DispatchKey] | None = None, + *, + skip_native_fns_gen: bool = False, + loaded_yaml: object | None = None, +) -> ParsedYaml: + global _GLOBAL_PARSE_NATIVE_YAML_CACHE + if path not in _GLOBAL_PARSE_NATIVE_YAML_CACHE: + valid_tags = parse_tags_yaml(tags_yaml_path) + + # if a loaded yaml is provided, use that instead of reading from path + if loaded_yaml is None: + with open(path) as f: + es = yaml.load(f, Loader=LineLoader) + else: + es = loaded_yaml + + _GLOBAL_PARSE_NATIVE_YAML_CACHE[path] = parse_native_yaml_struct( + es, + valid_tags, + ignore_keys, + path=path, + skip_native_fns_gen=skip_native_fns_gen, + ) + + return _GLOBAL_PARSE_NATIVE_YAML_CACHE[path] + + +# Some assertions are already performed during parsing, but those are only within a single NativeFunction. +# Assertions here are meant to be performed across NativeFunctions. +def error_check_native_functions(funcs: Sequence[NativeFunction]) -> None: + func_map: dict[OperatorName, NativeFunction] = {} + base_func_map: dict[BaseOperatorName, list[NativeFunction]] = defaultdict(list) + for f in funcs: + func_map[f.func.name] = f + base_func_map[f.func.name.name].append(f) + for f in funcs: + if f.structured_delegate is not None: + delegate_func = func_map.get(f.structured_delegate) + if delegate_func is None: + raise AssertionError( + f"{f.func.name} is marked as a structured_delegate pointing to " + f"{f.structured_delegate}, but {f.structured_delegate} is missing." + ) + if not delegate_func.structured: + raise AssertionError( + f"{f.func.name} is marked as a structured_delegate pointing to " + f"{f.structured_delegate}, but {f.structured_delegate} is not marked as structured. " + f"Consider adding 'structured=True' to the delegated operator" + ) + + # Check for reserved Python keywords + PYTHON_RESERVED_KEYWORDS = set(keyword.kwlist) + # List of pre-existing operators that are known to have reserved keywords + # Exclusion list is used to suppress the assertion for these operators + EXCLUSION_LIST = { + ("_has_compatible_shallow_copy_type", "from"), + ("random_.from", "from"), + ("uniform_", "from"), + } + + for arg in f.func.arguments.flat_all: + if arg.name in PYTHON_RESERVED_KEYWORDS: + if (str(f.func.name), arg.name) not in EXCLUSION_LIST: + raise AssertionError( + f"Argument name '{arg.name}' in function '{f.func.name}' is a reserved Python keyword." + ) + # See Note [resize_ in Functionalization] + # resize_() is technically an inplace view op (and therefore needs the tag), + # but it would be overkill to add a true "view" variant of resize. + # Instead, resize_() gets special treatment in functionalization, + # and we have a resize() op that is non-aliasing + functional. + if ( + "inplace_view" in f.tags + and str(f.func.name) != "resize_" + and str(f.func.name) != "resize_as_" + and str(f.func.name.name) != "set_" + ): + base_name = f.func.name.name + if not base_name.inplace: + raise AssertionError( + f"{f.func.name} is marked with tag: inplace_view, but it doesn't follow the naming " + "convention for inplace ops - the codegen expects the base name to have a trailing underscore." + ) + out_of_place_base_name = BaseOperatorName( + base_name.base, False, base_name.dunder_method + ) + if len(base_func_map[out_of_place_base_name]) == 0: + raise AssertionError( + f"{f.func.name} is marked with tag: inplace_view. The codegen expects there to be a corresponding " + f"out-of-place view op with the name '{base_name}' and matching schema, but it didn't find one." + ) + + +def cpp_string(s: str) -> str: + """Convert a python string into a c++ string literal""" + s = s.replace("\\", "\\\\") + s = s.replace('"', '\\"') + s = s.replace("\a", "\\a") + s = s.replace("\b", "\\b") + s = s.replace("\f", "\\f") + s = s.replace("\n", "\\n") + s = s.replace("\v", "\\v") + s = s.replace("\t", "\\t") + return f'"{s}"' + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# C++ CODE GENERATION +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + +# Most functions in this section are curried: they consist of a function +# that takes some parameters (e.g., what is to be generated) which itself +# returns a function that actually maps NativeFunction to the code +# to be generated. This pattern makes it convenient to use map, concatMap +# and similar functional combinators. + + +def static_dispatch_keys(backends: list[BackendIndex]) -> list[DispatchKey]: + if len(backends) == 0: + return [] + else: + return [backend.dispatch_key for backend in backends] + [ + DispatchKey.CompositeImplicitAutograd, + DispatchKey.CompositeImplicitAutogradNestedTensor, + DispatchKey.CompositeExplicitAutograd, + DispatchKey.CompositeExplicitAutogradNonFunctional, + ] + + +def get_static_dispatch_backend( + f: NativeFunction, backend_index: BackendIndex +) -> DispatchKey | None: + if f.structured_delegate is not None or backend_index.has_kernel(f): + # TODO: for ops with structured_delegate it should check the dispatch table of + # the out variant instead. For now, these structured ops all have CPU/CUDA kernels + # so we always dispatch to the `backend`, but this could be wrong when we + # migrate math/default_backend ops to use structured delegate. + return backend_index.dispatch_key + elif f.has_composite_explicit_autograd_kernel: + return DispatchKey.CompositeExplicitAutograd + elif f.has_composite_explicit_autograd_non_functional_kernel: + return DispatchKey.CompositeExplicitAutogradNonFunctional + elif f.has_composite_implicit_autograd_kernel: + return DispatchKey.CompositeImplicitAutograd + elif f.has_composite_implicit_autograd_nested_tensor_kernel: + return DispatchKey.CompositeImplicitAutogradNestedTensor + return None + + +def static_dispatch_ops_header( + f: NativeFunction, backend_index: list[BackendIndex] +) -> str | None: + if backend_index is None or f.manual_kernel_registration: + return None + + output = [] + for index in backend_index: + dispatch_key = get_static_dispatch_backend(f, index) + if dispatch_key is not None: + output.append( + f"#include " + ) + return "\n".join(output) + + +def static_dispatch_extra_headers(backends: list[BackendIndex]) -> list[str]: + return [ + f"#include " + for dispatch_key in static_dispatch_keys(backends) + ] + + +# Translates arguments of `sig` to CppSignature bindings. +# Note that we have a special case for `memory_format` argument and this case is not covered by +# tools.codegen.api.translate() yet as its application is limited to static dispatch. +def translate_args( + sig: CppSignature | DispatcherSignature, + cpp_sig: CppSignature, +) -> str: + # Adds SpecialArgName.possibly_redundant_memory_format NamedCType for memory_format bindings + def add_spl_memory_format_binding(input_bindings: list[Binding]) -> list[Binding]: + output_bindings: list[Binding] = [] + for binding in input_bindings: + if binding.name == "memory_format": + spl_mem_format_binding = Binding( + nctype=NamedCType( + SpecialArgName.possibly_redundant_memory_format, + binding.nctype.type, + ), + name=binding.name, + default=binding.default, + argument=binding.argument, + ) + output_bindings.append(spl_mem_format_binding) + else: + output_bindings.append(binding) + return output_bindings + + src_bindings = list(sig.arguments()) + goal_bindings = list(cpp_sig.arguments()) + # When last argument of CPP signature has SpecialArgName.possibly_redundant_memory_format NCType, + # get memory_format bindings of dispatcher signature to have the same NCType as well + for arg in goal_bindings: + if arg.nctype.name == SpecialArgName.possibly_redundant_memory_format: + src_bindings = add_spl_memory_format_binding(src_bindings) + break + exprs = translate(src_bindings, goal_bindings) + return ", ".join(a.expr for a in exprs) + + +def generate_static_dispatch_backend_call( + sig: CppSignature | DispatcherSignature, + f: NativeFunction, + backend_index: BackendIndex, +) -> str: + cpp_sig = gen_static_dispatch_backend_call_signature(f) + name = cpp_sig.name() + exprs = translate_args(sig, cpp_sig) + backend_metadata = backend_index.get_kernel(f) + kernel_ns = ( + backend_metadata.cpp_namespace + if backend_metadata and backend_metadata.cpp_namespace + else DEFAULT_KERNEL_NAMESPACE + ) + ns = kernel_ns.replace("::native", "") + return f"return {ns}::{backend_index.dispatch_key.lower()}::{name}({exprs});" + + +def generate_static_dispatch_fallback_call( + sig: CppSignature | DispatcherSignature, + f: NativeFunction, + backend_indices: list[BackendIndex], +) -> str: + cpp_sigs = CppSignatureGroup.from_native_function( + f, method=False, fallback_binding=False + ) + if sig.symint and f.func.has_symint(): + cpp_sig = cpp_sigs.symint_signature + else: + cpp_sig = cpp_sigs.signature + if cpp_sig is None: + raise AssertionError("Expected cpp_sig to be non-None") + name = cpp_sig.name() + exprs = translate_args(sig, cpp_sig) + ns = DEFAULT_KERNEL_NAMESPACE.replace("::native", "") + if f.has_composite_explicit_autograd_kernel: + return f"return {ns}::{DispatchKey.CompositeExplicitAutograd.lower()}::{name}({exprs});" + elif f.has_composite_explicit_autograd_non_functional_kernel: + return f"return {ns}::{DispatchKey.CompositeExplicitAutogradNonFunctional.lower()}::{name}({exprs});" + elif f.has_composite_implicit_autograd_kernel: + return f"return {ns}::{DispatchKey.CompositeImplicitAutograd.lower()}::{name}({exprs});" + elif f.has_composite_implicit_autograd_nested_tensor_kernel: + return f"return {ns}::{DispatchKey.CompositeImplicitAutogradNestedTensor.lower()}::{name}({exprs});" + else: + return f"""TORCH_CHECK(false, "Static dispatch does not support {name} for\ +{", ".join([str(index.dispatch_key) for index in backend_indices])} ");""" + + +def static_dispatch( + sig: CppSignature | DispatcherSignature, + f: NativeFunction, + backend_indices: list[BackendIndex], +) -> str: + """ + For a given `NativeFunction`, find out the corresponding backend and dispatch to it. If more than one + backends exist, fallback to static dispatch by determining dispatch key from inputs. + Arguments: + sig: A CppSignature or DispatcherSignature for this native function we want to use. + f: NativeFunction to generate static dispatch. + backend_indices: All available backends. + Return: + C++ code to call backend-specific functions, e.g., "return at::cpu::add(self, other, scale);" + """ + if len(backend_indices) == 0 or f.manual_kernel_registration: + return "" + + keys = [ + b + for b in backend_indices + if b.has_kernel(f) + or ( + f.structured_delegate is not None + and b.dispatch_key in STRUCTURED_DISPATCH_KEYS + ) + ] + if len(keys) == 1: + return generate_static_dispatch_backend_call(sig, f, keys[0]) + elif len(keys) == 0: + return generate_static_dispatch_fallback_call(sig, f, backend_indices) + + native_tensor_args = [ + a.name + for a in sig.arguments() + if isinstance(a.argument, SelfArgument) + or isinstance(a.argument, Argument) + and a.argument.type.is_tensor_like() + ] + tensor_args = ", ".join(native_tensor_args) + tensor_opts = f.func.arguments.tensor_options + + stmts = [] + subexprs: list[str] = [] + if tensor_opts is not None: + subexprs.append( + "DispatchKeySet(c10::computeDispatchKey(dtype, layout, device))" + ) + if tensor_args != "": + subexprs.append(f"c10::detail::multi_dispatch_key_set({tensor_args})") + stmts.append(f"""DispatchKeySet _dk_set = {" | ".join(subexprs)};""") + stmts.append("DispatchKey _dk = c10::highestPriorityBackendTypeId(_dk_set);") + + dispatch_code = [] + for index in keys: + dispatch_code.append(f"""case DispatchKey::{index.dispatch_key}:""") + dispatch_code.append( + f"""\t{generate_static_dispatch_backend_call(sig, f, index)};""" + ) + + fallback = generate_static_dispatch_fallback_call(sig, f, backend_indices) + connector = "\n\t\t" + + return f""" + {connector.join(stmts)} + switch (_dk) {{ + {connector.join(dispatch_code)} + default: + {fallback} + }} + """ + + +# Generates RegisterSchema.cpp. Depending on the selector, either +# all schemas are registered, or only some are (in the case of +# selective build) +@dataclass(frozen=True) +class RegisterSchema: + selector: SelectiveBuilder + known_tags: dict[str, int] = field(default_factory=dict) + + @method_with_native_function + def __call__(self, f: NativeFunction) -> str | None: + if not self.selector.is_native_function_selected(f): + return None + tags = "{" + ", ".join(f"at::Tag::{tag}" for tag in sorted(f.tags)) + "}" + if tags == "{}": + return f"m.def({cpp_string(str(f.func))}, {{}});\n" + maybe_tags = "" + if tags not in self.known_tags: + idx = len(self.known_tags) + self.known_tags[tags] = idx + maybe_tags = f"const std::vector tags_{idx} = {tags};\n" + return f"{maybe_tags}m.def({cpp_string(str(f.func))}, tags_{self.known_tags[tags]});\n" + + +# Generates Operators.h and Operators.cpp. +# These provide macros that, given an operator and overload name, allow users +# to access an "un-overloaded" function version of the operator. This +# is useful for extension writers who want to (1) want to decltype the operator +# and (2) don't want to worry about method-only operators. +@dataclass(frozen=True) +class ComputeOperators: + target: Literal[Target.DECLARATION, Target.DEFINITION] + static_dispatch_backend_indices: list[BackendIndex] + + @method_with_native_function + def __call__(self, f: NativeFunction) -> str: + sig = DispatcherSignature.from_schema(f.func) + name = f.func.name.unambiguous_name() + + if self.target is Target.DECLARATION: + # Note [The ATen Operators API] + # The ATen Operators API lives in the at::_ops namespace, and contains compile-time + # metadata about each operator + entry points into the Dispatcher. + # The C++ function, method, and redispatch API's are all implemented as wrappers + # into various bits of the structs defined here. + # + # Important characteristics about the Operators API: + # (1) It follows the Dispatcher API. + # This is kind of necessary to avoid overhead. + # For example: if it followed the C++ API, then all of the faithful C++ factory functions + # would need to wrap their arguments into TensorOptions only to unwrap them again. + # (2) Overload names are disambiguated. + # This is helpful for pytorch extenders who would like to decltype() an aten operator, + # that has overloads, e.g. decltype(at::_ops::mul_Tensor::call) + # (3) No argument defaulting is allowed. + # This is more of an implementation detail to avoid #include cycles, + # since TensorBody.h (which defines the Tensor class) needs to include this file. + # (4) manual_cpp_bindings and faithful names are not included in the API. + # This applies to stuff like __dispatch__is_complex(), and add_outf(). + # These aren't "real aten ops", they're just additional functions provided by the C++ API. + # They're implemented as wrappers in Functions.h that call into the actual operators + # defined here, i.e. at::_ops::is_complex::call() and at::_ops::add_out::call(). + # This means that ATEN_OP(is_complex) will not fastpath, and will go through the dispatcher. + return f""" +struct TORCH_API {name} {{ + using schema = {sig.type()}; + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + static constexpr const char* name = "aten::{f.func.name.name}"; + static constexpr const char* overload_name = "{f.func.name.overload_name}"; + static constexpr const char* schema_str = {cpp_string(str(f.func))}; + static {sig.defn(name="call", is_redispatching_fn=False)}; + static {sig.defn(name="redispatch", is_redispatching_fn=True)}; +}};""" + + elif self.target is Target.DEFINITION: + defns = f""" +// aten::{f.func} +static C10_NOINLINE c10::TypedOperatorHandle<{name}::schema> create_{name}_typed_handle() {{ + return c10::Dispatcher::singleton() + .findSchemaOrThrow({name}::name, {name}::overload_name) + .typed<{name}::schema>(); +}} +""" + for is_redispatching_fn in [False, True]: + if is_redispatching_fn: + dispatcher_exprs_str = ", ".join( + ["dispatchKeySet"] + [a.name for a in sig.arguments()] + ) + method_base = "redispatch" + else: + dispatcher_exprs_str = ", ".join([a.name for a in sig.arguments()]) + method_base = "call" + + dispatcher_call = method_base + method_name = f"{name}::{method_base}" + + fn_body = f""" + static auto op = create_{name}_typed_handle(); + return op.{dispatcher_call}({dispatcher_exprs_str});""" + + if ( + not is_redispatching_fn + and len(self.static_dispatch_backend_indices) > 0 + ): + # call() should go through static dispatch + fn_body = static_dispatch( + sig, f, backend_indices=self.static_dispatch_backend_indices + ) + defns += f""" +// aten::{f.func} +{sig.defn(name=method_name, is_redispatching_fn=is_redispatching_fn)} {{ + {fn_body} +}} +""" + return defns + else: + assert_never(self.target) + + +# Generates Functions.h, which provides the functional public C++ API, +# and the scaffolding to call into the dispatcher from these functions. +@dataclass(frozen=True) +class ComputeFunction: + @method_with_native_function + def __call__(self, f: NativeFunction) -> str | None: + sig_group = CppSignatureGroup.from_native_function( + f, method=False, fallback_binding=f.manual_cpp_binding + ) + has_symint = f.func.has_symint() + + result = "" + for sig in sig_group.signatures(): + # See Note [The ATen Operators API] + target_sig = DispatcherSignature.from_schema(f.func) + exprs = translate(sig.arguments(), target_sig.arguments()) + exprs_str = ", ".join([e.expr for e in exprs]) + + if sig.symint: + intlike_t = "c10::SymInt" + else: + intlike_t = "int64_t" + + if Variant.function in f.variants: + result += f""" +// aten::{f.func} +inline {sig.decl()} {{ + return at::_ops::{f.func.name.unambiguous_name()}::call({exprs_str}); +}}""" + + # The template function can be used from template situations + # where you want to switch between the symint or not version + # depending on a template argument + # + # NB: we ALWAYS generate this even for methods. But we put it in + # this header so it can take advantage of per-op headers + if has_symint: + result += f""" +namespace symint {{ + template >> + {sig.decl(suppress_symint_suffix=True)} {{ + return at::_ops::{f.func.name.unambiguous_name()}::call({exprs_str}); + }} +}} +""" + return result + + +# Generates TensorBody.h. This file provides the object-oriented (method-based) +# public C++ API, and the scaffolding to call into the dispatcher from these functions. +@dataclass(frozen=True) +class ComputeTensorMethod: + target: Literal[Target.DECLARATION, Target.DEFINITION] + static_dispatch_backend_indices: list[BackendIndex] + + @method_with_native_function + def __call__(self, f: NativeFunction) -> str | None: + if Variant.method not in f.variants: + return None + + if f.func.is_out_fn(): + raise AssertionError(f"Method variant cannot be an out function: {f.func}") + if f.func.arguments.self_arg is None: + raise AssertionError(f"Method variant must have self_arg: {f.func}") + + sig_group = CppSignatureGroup.from_native_function( + f, method=True, fallback_binding=f.manual_cpp_binding + ) + + if self.target is Target.DECLARATION: + result = "" + for sig in sig_group.signatures(): + result += f"{sig.decl()} const;\n" + return result + + if self.target is not Target.DEFINITION: + assert_never(self.target) + + result = "" + + for sig in sig_group.signatures(): + target_sig = DispatcherSignature.from_schema(f.func) + exprs = translate(sig.arguments(), target_sig.arguments(), method=True) + exprs_str = ", ".join([e.expr for e in exprs]) + + result += f""" +// aten::{f.func} +inline {sig.defn(prefix="Tensor::")} const {{ + return at::_ops::{f.func.name.unambiguous_name()}::call({exprs_str}); +}} +""" + + return result + + +# Generates RedispatchFunctions.h. +# This is similar to the C++ API defined in Functions.h, but provides access +# to the dispatcher's redispatch API. +@dataclass(frozen=True) +class ComputeRedispatchFunction: + @method_with_native_function + def __call__(self, f: NativeFunction) -> str | None: + # We unconditionally generate function variants of the redispatch API. + # This is mainly because we can namespace functions separately, but not methods, + sig_group = CppSignatureGroup.from_native_function( + f, method=False, fallback_binding=f.manual_cpp_binding + ) + + result = "" + for sig in sig_group.signatures(): + target_sig = DispatcherSignature.from_schema(f.func) + exprs = translate(sig.arguments(), target_sig.arguments()) + exprs_str = ", ".join(["dispatchKeySet"] + [a.expr for a in exprs]) + + result += f""" +// aten::{f.func} +inline {sig.decl(is_redispatching_fn=True)} {{ + return at::_ops::{f.func.name.unambiguous_name()}::redispatch({exprs_str}); +}} +""" + + return result + + +# Generates ATenOpList.cpp, a runtime accessible list of all aten +# operators. +# TODO: This was historically used to help some JIT interop code +# figure out whether or not to treat aten namespace'd operators +# one way or another, we should reevaluate if this is actually needed. +@with_native_function +def compute_aten_op(f: NativeFunction) -> str: + return f'{{"aten::{f.func.name.name}", "{f.func.name.overload_name}"}},' + + +# Generates MetaFunctions.h +def compute_meta_function_declaration(g: NativeFunctionsGroup) -> str | None: + if not g.structured: + return None + with native_function_manager(g.out): + name = meta.name(g) + args = structured.meta_arguments(g) + args_str = ", ".join(a.decl() for a in args) + parent_class = g.out.structured_inherits + if parent_class is None: + parent_class = "at::impl::MetaBase" + meta_return = "void" + precomputed = g.out.precomputed if g.structured else None + + if precomputed: + # Generate the template declaration with one bool parameter for each + # precomputed element. Each parameter is true if the corresponding (in + # terms of position) precomputed element has been set. + precomputed_values = [*precomputed.replace.values(), precomputed.add] + precomputed_elements = [ + elem for replace_list in precomputed_values for elem in replace_list + ] + precomputed_template_parameters = [ + elem.name.upper() for elem in precomputed_elements + ] + precomputed_template_params_str = ", ".join( + f"bool {param} = false" for param in precomputed_template_parameters + ) + precompute_template_decl = f"template <{precomputed_template_params_str}>" + + # Generate a string containing declarations of all precomputed elements. + precomputed_elements_with_cpp_types = [ + structured.argument_type(elem, binds=elem.name) + for elem in precomputed_elements + ] + + precomputed_elements_decl = ";\n".join( + f"{elem.cpp_type(strip_ref=True)} {elem.name}" + for elem in precomputed_elements_with_cpp_types + ) + + # Generate "setter" methods for each precomputed element. Each method will return + # a new instance of precompute_out with the template parameter that corresponds to + # the member set by the method to true (to indicate that it has been set). + setter_methods = [] + for i, elem in enumerate(precomputed_elements): + # Generate the signature. The return type will be the same + # as the type of `this` but with the template parameter + # corresponding to the element set by this method set to true. + # The assert generated below will ensure that this template + # parameter is false on the type of `this`. + return_ty_templates = ", ".join( + precomputed_template_parameters[:i] + + ["true"] + + precomputed_template_parameters[i + 1 :] + ) + return_ty = f"precompute_out<{return_ty_templates}>" + elem_cpp_ty = precomputed_elements_with_cpp_types[i].cpp_type( + strip_ref=True + ) + signature = f"{return_ty} set_{elem.name}({elem_cpp_ty} value)" + + # Generate an assert which checks that the + # template parameter corresponding to the precomputed + # element that is set by this method is false on the + # class corresponding to the object that `this` points to. + # This ensures that each element can be set only once. + assert_msg = f'"{elem.name} already set"' + assert_stmt = f"static_assert({precomputed_template_parameters[i]} == false, {assert_msg});" + + # Generate the new object construction block. All state + # except the element that this method sets is copied from the + # object that `this` points to. The value for the element that + # the method sets is taken from a method parameter. + construction_stmts = [] + construction_stmts.append(f"{return_ty} ret;") + + for j, elem in enumerate(precomputed_elements): + if i == j: + construction_stmts.append(f"ret.{elem.name} = value;") + else: + construction_stmts.append( + f"ret.{elem.name} = this->{elem.name};" + ) + + construction_stmts.append("return ret;") + construction_block = "\n".join(construction_stmts) + + setter_methods.append( + f""" + {signature} {{ + {assert_stmt} + {construction_block} + }} + """ + ) + setter_methods_decl = "\n".join(setter_methods) + + # Meta should return an instance of the struct containing the precomputed elements. + meta_return_template_params = ", ".join( + ["true"] * len(precomputed_template_parameters) + ) + # This typedef (actually a using statement) is needed so that TORCH_META_FUNC can reuse the return + # type (which has a variable number of template parameters). + meta_return_typedef = f"using meta_return_ty = precompute_out <{meta_return_template_params}>;" + meta_return = "meta_return_ty" + precomputed_decl = f""" + {precompute_template_decl} + struct TORCH_API precompute_out {{ + {setter_methods_decl} + {precomputed_elements_decl}; + }};""" + else: + meta_return_typedef = "" + precomputed_decl = "" + + return f"""\ +struct TORCH_API structured_{name} : public {parent_class} {{ + {precomputed_decl} + {meta_return_typedef} + {meta_return} meta({args_str}); +}}; +""" + + +def needs_backend_select(f: NativeFunction, selector: SelectiveBuilder) -> bool: + name = str(f.func.name.name) + if name.endswith("_like") or name.startswith("new_"): + return False + if f.func.arguments.tensor_options is None: + return False + return selector.is_native_function_selected(f) + + +# Generates RegisterBackendSelect.cpp, a series of kernels which provide +# specialized computation of dispatch key for operator signatures which cannot +# be easily done automatically using templating. +@dataclass(frozen=True) +class ComputeBackendSelect: + target: Literal[Target.DEFINITION, Target.REGISTRATION] + + # Selector object to determine which operators to generate + # registration code for. + selector: SelectiveBuilder + + @method_with_native_function + def __call__(self, f: NativeFunction) -> str | None: + if not needs_backend_select(f, self.selector): + return None + + name = native.name(f.func) + # BackendSelect can go to Meta, so it must preserve symints + native_sig = NativeSignature(f.func, symint=True) + + native_tensor_args = [ + a + for a in native_sig.arguments() + if isinstance(a.argument, Argument) and a.argument.type.is_tensor_like() + ] + + dispatcher_sig = DispatcherSignature.from_schema(f.func) + + sig: NativeSignature | DispatcherSignature + sig = dispatcher_sig + dispatcher_exprs = dispatcher_sig.exprs() + dispatch_key = "c10::computeDispatchKey(dtype, layout, device)" + + if self.target is Target.DEFINITION: + # I don't think there's actually a good reason to generate + # these two cases differently + # The first case could probably be improved though- it calls computeDispatchKeySet(), + # which looks at TLS dispatch keys- there should not be any by the time we reach backend select. + if native_tensor_args: + if not f.func.arguments.has_tensor_arg(): + raise AssertionError( + f"Expected function to have tensor args: {f.func}" + ) + tensor_args = ", ".join(a.name for a in native_tensor_args) + compute_dk = f"""\ +DispatchKeySet _dk_set = c10::DispatchKeySet({dispatch_key}) | c10::detail::multi_dispatch_key_set({tensor_args}); +DispatchKeySet _dk_mask = c10::DispatchKeySet(DispatchKeySet::FULL_AFTER, DispatchKey::BackendSelect); +DispatchKeySet _dk = c10::impl::computeDispatchKeySet(_dk_set, _dk_mask);""" + else: + if f.func.arguments.has_tensor_arg(): + raise AssertionError( + f"Expected function to not have tensor args: {f.func}" + ) + compute_dk = ( + f"DispatchKeySet _dk = c10::DispatchKeySet({dispatch_key});" + ) + return f"""\ +// aten::{f.func} +C10_ALWAYS_INLINE +{sig.defn(name)} {{ + {compute_dk} + return at::_ops::{f.func.name.unambiguous_name()}::redispatch( + _dk, {", ".join(a.expr for a in dispatcher_exprs)}); +}} +""" + elif self.target is Target.REGISTRATION: + return f"""m.impl("aten::{f.func.name}", TORCH_FN({name}));""" + else: + assert_never(self.target) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# YAML CODE GENERATION +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def format_yaml(data: object) -> str: + # Ignore alias in Dumper + YamlDumper.ignore_aliases = lambda self, data: True # type: ignore[assignment] + + # Support serializing OrderedDict + def dict_representer(dumper: Any, data: Any) -> Any: + return dumper.represent_dict(data.items()) + + YamlDumper.add_representer(OrderedDict, dict_representer) # type: ignore[no-untyped-call] + # Some yaml parsers (e.g. Haskell's) don't understand line breaks. + # width=1e9 turns off optional line breaks and improves + # the portability of the outputted yaml. + return yaml.dump(data, default_flow_style=False, Dumper=YamlDumper, width=1e9) # type: ignore[no-any-return, call-overload] + + +# For some reason, some defaults we write to YAML are written as native +# YAML objects, rather than doing them uniformly as strings. This +# function detects those cases and converts them into native Python +# objects. +def pythonify_default(s: str) -> object: + if s == "true": + return True + elif s == "false": + return False + + try: + return int(s) + except ValueError: + try: + return float(s) + except ValueError: + return s + + +# What is a dynamic type? Over time, the semantic meaning of +# dynamic type has degraded to meaninglessness (in the old days, +# it captured dtype-ness of types, but that has gone away with +# the removal of TH). These days, it's mostly the same thing as +# the C++ API argument type, except that Tensor and Tensor? +# arguments simply present as Tensor. +# +# TODO: Get rid of dynamic_type, after getting tools/autograd +# to use the new codegen framework +def dynamic_type(t: Type) -> str: + if isinstance(t, OptionalType): + return dynamic_type(t.elem) + # Note we don't use t.is_tensor_like() here because it would + # also include Tensor[] + if str(t) == "Tensor": + return "at::Tensor" + # This is a legacy concept, so never report SymInt + return cpp.argumenttype_type( + t, mutable=False, binds="__placeholder__", symint=False + ).cpp_type() + + +def compute_method_of_yaml(variants: set[Variant]) -> list[str]: + # This is written out explicitly to ensure that Tensor and + # namespace are put into the list in the right order + method_of = ["Type"] + if Variant.method in variants: + method_of.append("Tensor") + if Variant.function in variants: + method_of.append("namespace") + return method_of + + +def compute_returns_yaml( + f: NativeFunction, +) -> tuple[list[dict[str, str]], dict[str, str]]: + # Note [name and field_name] + # ~~~~~~~~~~~~~~~~~~~~~~~~~~ + # To understand name_to_field_name, we must first talk about this + # schema: + # + # lstsq.X(Tensor self, Tensor A, *, Tensor(a!) X, Tensor(b!) qr) -> (Tensor(a!) solution, Tensor(b!) QR) + # + # There is something very odd about this schema: it is an out + # variant of the function (that is to say, it will convert into + # at::lstsq_out() in the C++ API), but the names of the output + # return arguments don't match the keyword argument names of + # the inputs. It TURNS OUT that in this situation, the historical + # Declarations.yaml we want to output is this (abbreviated to + # only show relevant fields): + # + # arguments: + # ... + # - field_name: solution + # name: X + # - field_name: QR + # name: qr + # ... + # + # returns: + # - field_name: solution + # name: X + # - field_name: QR + # name: qr + # + # The name of the return fields is stored in 'field_name', and the + # name of the arguments is stored in 'name'. So when we process + # arguments, we need a way to get at the corresponding return. At + # the moment, this is most conveniently done by constructing a + # mapping from name (the argument concept) to field_name (the + # return concept) while processing return arguments, since we don't + # directly maintain this correspondence in the modeling of function + # schema itself. + # + # See also https://github.com/pytorch/pytorch/issues/43114 + name_to_field_name: dict[str, str] = {} + + # Compute the returns field of the YAML entry + names = cpp.return_names(f) + returns = [] + for i, (r, name) in enumerate(zip(f.func.returns, names)): + ret = { + "dynamic_type": dynamic_type(r.type), + "name": name, + # legacy, report ints + "type": cpp.return_type(r, symint=False).cpp_type(), + } + + if r.name: + # See Note [name and field_name] + ret["field_name"] = r.name + if f.func.is_out_fn(): + name_to_field_name[f.func.arguments.out[i].name] = r.name + + returns.append(ret) + + return returns, name_to_field_name + + +# arguments in yaml roughly corresponds to the public C++ API +def compute_cpp_argument_yaml( + cpp_a: Binding, + *, + schema_order: bool, + kwarg_only_set: set[str], + out_arg_set: set[str], + name_to_field_name: dict[str, str], +) -> object: + if isinstance(cpp_a.argument, TensorOptionsArguments): + arg: dict[str, object] = { + "annotation": None, + "dynamic_type": "at::TensorOptions", + "is_nullable": False, + "name": cpp_a.name, + "type": cpp_a.type, + "kwarg_only": True, + } + if cpp_a.default is not None: + arg["default"] = cpp_a.default + return arg + elif isinstance(cpp_a.argument, SelfArgument): + raise AssertionError + elif isinstance(cpp_a.argument, Argument): + return compute_argument_yaml( + cpp_a.argument, + schema_order=schema_order, + kwarg_only_set=kwarg_only_set, + out_arg_set=out_arg_set, + name_to_field_name=name_to_field_name, + ) + + +def compute_argument_yaml( + a: Argument, + *, + schema_order: bool, + kwarg_only_set: set[str], + out_arg_set: set[str], + name_to_field_name: dict[str, str], +) -> object: + arg: dict[str, object] = { + "annotation": str(a.annotation) if a.annotation else None, + "dynamic_type": dynamic_type(a.type), + "is_nullable": a.type.is_nullable(), + "name": a.name, + # legacy, report ints + "type": cpp.argument_type(a, binds="__placeholder__", symint=False).cpp_type(), + } + if a.default is not None: + arg["default"] = pythonify_default( + cpp.default_expr(a.default, a.type, symint=False) + ) + if a.name in kwarg_only_set: + arg["kwarg_only"] = True + if a.name in out_arg_set: + arg["output"] = True + arg["allocate"] = True + # See Note [name and field_name] + if a.name in name_to_field_name: + arg["field_name"] = name_to_field_name[a.name] + # Historically, booleans don't get their size recorded, because it + # is already built into the cpp type (e.g., std::array) + l = a.type.is_list_like() + if l is not None and l.size is not None and str(l.elem) != "bool": + arg["size"] = l.size + return arg + + +@with_native_function +def compute_declaration_yaml(f: NativeFunction) -> object: + returns, name_to_field_name = compute_returns_yaml(f) + + # These sets are used to conveniently test if an argument is a + # kwarg-only or out argument + kwarg_only_set = {a.name for a in f.func.arguments.flat_kwarg_only} + out_arg_set = {a.name for a in f.func.arguments.out} + + sig_group = CppSignatureGroup.from_native_function( + f, method=False, fallback_binding=False + ) + cpp_args = sig_group.signature.arguments() + arguments = [ + compute_cpp_argument_yaml( + cpp_a, + schema_order=False, + kwarg_only_set=kwarg_only_set, + out_arg_set=out_arg_set, + name_to_field_name=name_to_field_name, + ) + for cpp_a in cpp_args + ] + + schema_order_jit_arguments = list(f.func.schema_order_arguments()) + + schema_order_arguments = [ + compute_argument_yaml( + a, + schema_order=True, + kwarg_only_set=kwarg_only_set, + out_arg_set=out_arg_set, + name_to_field_name=name_to_field_name, + ) + for a in schema_order_jit_arguments + ] + + cpp_schema_order_types = [ + # NB: method here doesn't matter + r.type + for a in schema_order_jit_arguments + for r in cpp.argument( + a, + method=False, + cpp_no_default_args=set(), + faithful=False, + symint=False, + has_tensor_options=False, + ) + ] + + # legacy, report ints + cpp_returns = cpp.returns_type(f.func.returns, symint=False).cpp_type() + schema_order_cpp_signature = f"{cpp_returns} ({', '.join(cpp_schema_order_types)})" + + is_factory_method = ( + any(isinstance(a.argument, TensorOptionsArguments) for a in cpp_args) + and Variant.method not in f.variants + ) + + return OrderedDict( + [ + ("name", cpp.name(f.func)), + ("operator_name", str(f.func.name.name)), + ("overload_name", str(f.func.name.overload_name)), + ("manual_kernel_registration", f.manual_kernel_registration), + ( + "category_override", + f.category_override if f.category_override is not None else "", + ), + ("schema_string", f"aten::{f.func}"), + ("arguments", arguments), + ("schema_order_cpp_signature", schema_order_cpp_signature), + ("schema_order_arguments", schema_order_arguments), + ("method_of", compute_method_of_yaml(f.variants)), + ("mode", "native"), + ("python_module", "" if f.python_module is None else f.python_module), + ("returns", returns), + ("inplace", f.func.name.name.inplace), + ("is_factory_method", is_factory_method), + ("abstract", f.is_abstract), + ("device_guard", f.device_guard), + ("with_gil", False), + ("deprecated", False), + ("has_math_kernel", f.has_composite_implicit_autograd_kernel), + ] + ) + + +# See Note [Auto generated composite kernels] +def has_autogenerated_composite_kernel(f: NativeFunction) -> bool: + return (f.structured or f.structured_delegate is not None) and ( + f.func.kind() == SchemaKind.functional or f.func.kind() == SchemaKind.inplace + ) + + +@with_native_function_and_indices +def compute_registration_declarations( + f: NativeFunction, backend_indices: dict[DispatchKey, BackendIndex] +) -> str: + name = dispatcher.name(f.func) + returns_type = dispatcher.returns_type(f.func.returns).cpp_type() + args = dispatcher.arguments(f.func) + args_str = ", ".join(a.no_default().decl() for a in args) + comment_data: dict[str, str] = { + "schema": f"aten::{f.func}", + # TODO: What exactly is the semantics of the 'dispatch' field? + "dispatch": str( + {k for k, v in backend_indices.items() if v.has_kernel(f)} + != {DispatchKey.CompositeImplicitAutograd} + and {k for k, v in backend_indices.items() if v.has_kernel(f)} + != { + DispatchKey.CompositeImplicitAutograd, + DispatchKey.CompositeImplicitAutogradNestedTensor, + } + ), + "default": str(f.has_composite_kernel or has_autogenerated_composite_kernel(f)), + } + return f"""{returns_type} {name}({args_str}); // {json.dumps(comment_data)} +""" + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# RUN IT ALL +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def get_custom_build_selector( + provided_op_registration_allowlist: list[str] | None, + op_selection_yaml_path: str | None, +) -> SelectiveBuilder: + if ( + provided_op_registration_allowlist is not None + and op_selection_yaml_path is not None + ): + raise AssertionError( + "Both provided_op_registration_allowlist and op_selection_yaml_path " + "can NOT be provided at the same time." + ) + + op_registration_allowlist: set[str] | None = None + if provided_op_registration_allowlist is not None: + op_registration_allowlist = set(provided_op_registration_allowlist) + + if op_registration_allowlist is not None: + selector = SelectiveBuilder.from_legacy_op_registration_allow_list( + op_registration_allowlist, + True, + False, + ) + elif op_selection_yaml_path is not None: + selector = SelectiveBuilder.from_yaml_path(op_selection_yaml_path) + else: + selector = SelectiveBuilder.get_nop_selector() + + return selector + + +def get_grouped_by_view_native_functions( + native_functions: Sequence[NativeFunction], +) -> Sequence[NativeFunction | NativeFunctionsViewGroup]: + def maybe_create_view_group( + d: dict[ViewSchemaKind | SchemaKind, NativeFunction], + ) -> list[NativeFunction | NativeFunctionsViewGroup]: + funcs: list[NativeFunction | NativeFunctionsViewGroup] = [] + if ViewSchemaKind.aliasing in d: + view = d.pop(ViewSchemaKind.aliasing) + view_inplace = d.pop(ViewSchemaKind.aliasing_inplace, None) + view_copy = d.pop(SchemaKind.functional, None) + + funcs.append( + NativeFunctionsViewGroup( + view=view, + view_copy=view_copy, + view_inplace=view_inplace, + ) + ) + # Take the remaining functions that weren't part of the view group + # and emit them separately + funcs.extend(d.values()) + return funcs + + grouped_by_views: dict[ + FunctionSchema, dict[SchemaKind | ViewSchemaKind, NativeFunction] + ] = defaultdict(dict) + for f in native_functions: + schema = f.func.view_signature() + view_kind: ViewSchemaKind = f.view_schema_kind + # We need to group up ops relevant to the same "view", consisting of: + # view op (ViewSchemaKind.aliasing) + # view_inplace op (ViewSchemaKind.aliasing_inplace) + # view_copy op (SchemaKind.functional) + if view_kind == ViewSchemaKind.non_aliasing: + kind = f.func.kind() + if kind in grouped_by_views[schema]: + raise AssertionError( + f"Duplicate schema kind {kind} in {grouped_by_views[schema].keys()}" + ) + grouped_by_views[schema][kind] = f + else: + if view_kind in grouped_by_views[schema]: + raise AssertionError( + f"{view_kind} already in {grouped_by_views[schema].keys()}" + ) + grouped_by_views[schema][view_kind] = f + + return list(concatMap(maybe_create_view_group, grouped_by_views.values())) + + +def get_grouped_native_functions( + native_functions: Sequence[NativeFunction], +) -> Sequence[NativeFunction | NativeFunctionsGroup]: + def flatten_pre_group( + d: dict[SchemaKind, NativeFunction], + ) -> Sequence[NativeFunction | NativeFunctionsGroup]: + r = NativeFunctionsGroup.from_dict(d) + if r is None: + # Invariant: any NativeFunctions that are code-generated + # should have been grouped into NativeFunctionsGroup objects + if any("generated" in f.tags for f in d.values()): + raise AssertionError( + "Generated NativeFunctions should have been grouped into " + f"NativeFunctionsGroup objects: {list(d.values())}" + ) + return list(d.values()) + else: + return [r] + + # TODO: how come ValuesView isn't a Sequence lol + pre_grouped_native_functions = pre_group_native_functions(native_functions) + return list( + concatMap(flatten_pre_group, list(pre_grouped_native_functions.values())) + ) + + +def get_ns_grouped_kernels( + *, + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + backend_indices: dict[DispatchKey, BackendIndex], + native_function_decl_gen: Callable[ + [NativeFunctionsGroup | NativeFunction, BackendIndex], list[str] + ] = dest.compute_native_function_declaration, +) -> dict[str, list[str]]: + ns_grouped_kernels: dict[str, list[str]] = defaultdict(list) + for f in grouped_native_functions: + native_function_namespaces = set() + dispatch_keys = set() + for dispatch_key, backend_idx in backend_indices.items(): + backend_metadata = backend_idx.get_kernel(f) + if backend_metadata: + namespace = backend_metadata.cpp_namespace + dispatch_keys.add(dispatch_key) + native_function_namespaces.add(namespace) + else: + namespace = DEFAULT_KERNEL_NAMESPACE + if len(native_function_namespaces) > 1: + raise AssertionError( + f"Codegen only supports one namespace per operator, " + f"got {native_function_namespaces} from {dispatch_keys}" + ) + ns_grouped_kernels[namespace].extend( + native_function_decl_gen(f, backend_idx) + ) + return ns_grouped_kernels + + +def get_native_function_declarations_from_ns_grouped_kernels( + *, + ns_grouped_kernels: dict[str, list[str]], +) -> list[str]: + declarations: list[str] = [] + newline = "\n" + for namespace, kernels in ns_grouped_kernels.items(): + ns_helper = NamespaceHelper( + namespace_str=namespace, + entity_name="", + max_level=4, + ) + # Convert to a set first to remove duplicate kernel names. Backends are + # allowed to repeat kernel names; only generate the declaration once! + ordered_kernels = list(OrderedDict.fromkeys(kernels)) + declarations.extend( + f""" +{ns_helper.prologue} +{newline.join(ordered_kernels)} +{ns_helper.epilogue} + """.split(newline) + ) + return declarations + + +# Return native function declarations grouped by their namespaces. +def get_native_function_declarations( + *, + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + backend_indices: dict[DispatchKey, BackendIndex], + native_function_decl_gen: Callable[ + [NativeFunctionsGroup | NativeFunction, BackendIndex], list[str] + ] = dest.compute_native_function_declaration, +) -> list[str]: + """ + Generate kernel declarations, in `NativeFunction(s).h`. + :param grouped_native_functions: a sequence of `NativeFunction` or `NativeFunctionGroup`. + :param backend_indices: kernel collections grouped by dispatch key. + :param native_function_decl_gen: callable to generate kernel declaration for each `NativeFunction`. + :return: a list of string, from the string with all declarations, grouped by namespaces, split by newline. + """ + + ns_grouped_kernels = get_ns_grouped_kernels( + grouped_native_functions=grouped_native_functions, + backend_indices=backend_indices, + native_function_decl_gen=native_function_decl_gen, + ) + return get_native_function_declarations_from_ns_grouped_kernels( + ns_grouped_kernels=ns_grouped_kernels + ) + + +def get_kernel_namespace( + *, f: NativeFunction | NativeFunctionsGroup, backend_idx: BackendIndex +) -> str: + backend_metadata = backend_idx.get_kernel(f) + if backend_metadata and "::native" not in backend_metadata.cpp_namespace: + func_name = ( + f.func.name if isinstance(f, NativeFunction) else f.functional.func.name + ) + raise AssertionError( + f"The kernel for function {func_name} " + f"with dispatch key {backend_idx.dispatch_key} " + f"has a namespace {backend_metadata.cpp_namespace} and it's not ending with '::native'." + ) + return ( + backend_metadata.cpp_namespace if backend_metadata else DEFAULT_KERNEL_NAMESPACE + ) + + +# Return native function definitions grouped by dispatch key and custom namespace. +# Used in RegisterDispatchKey.cpp and etc. +def get_native_function_definitions( + *, + fm: FileManager, + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + dispatch_key: DispatchKey, + backend_idx: BackendIndex, + selector: SelectiveBuilder, + rocm: bool, + symint: bool, + skip_dispatcher_op_registration: bool, + gen_dispatch_helpers: bool, +) -> list[str]: + definitions: list[str] = [] + ns_definitions: dict[str, list[str]] = defaultdict(list) + anonymous_definitions: dict[str, list[str]] = defaultdict(list) + registrations: dict[str, dict[str, list[str]]] = defaultdict(dict) + newline = "\n" + ns_gen = dest.RegisterDispatchKey( + backend_idx, + Target.NAMESPACED_DEFINITION, + selector, + rocm=rocm, + symint=symint, + class_method_name=None, + skip_dispatcher_op_registration=skip_dispatcher_op_registration, + ) + anonymous_gen = dest.RegisterDispatchKey( + backend_idx, + Target.ANONYMOUS_DEFINITION, + selector, + rocm=rocm, + symint=symint, + class_method_name=None, + skip_dispatcher_op_registration=skip_dispatcher_op_registration, + ) + reg_gen = dest.RegisterDispatchKey( + backend_idx, + Target.REGISTRATION, + selector, + rocm=rocm, + symint=symint, + class_method_name=None, + skip_dispatcher_op_registration=skip_dispatcher_op_registration, + ) + for f in grouped_native_functions: + kernel_namespace = get_kernel_namespace(f=f, backend_idx=backend_idx).replace( + "::native", "" + ) + + ns_definitions[kernel_namespace].extend( + ns_gen(f), + ) + anonymous_definitions[kernel_namespace].extend( + anonymous_gen(f), + ) + namespace = ( + f.namespace if isinstance(f, NativeFunction) else f.functional.namespace + ) + if namespace not in registrations[kernel_namespace]: + registrations[kernel_namespace] = defaultdict(list) + registrations[kernel_namespace][namespace].extend( + reg_gen(f), + ) + + for kernel_namespace in ns_definitions: + if len(ns_definitions[kernel_namespace]) == 0: + continue + ns_helper = NamespaceHelper(namespace_str=kernel_namespace) + registration_body = "" + for namespace in registrations[kernel_namespace]: + if not registrations[kernel_namespace][namespace]: + continue + registration_body += f""" +TORCH_LIBRARY_IMPL({namespace}, {dispatch_key}, m) {{ + {newline.join(registrations[kernel_namespace][namespace])} +}}""" + definitions.extend( + fm.substitute_with_template( + "RegisterDispatchDefinitions.ini", + lambda: { + "ns_prologue": ns_helper.prologue, + "ns_epilogue": ns_helper.epilogue, + "dispatch_anonymous_definitions": anonymous_definitions[ + kernel_namespace + ], + "static_init_dispatch_registrations": "" + if skip_dispatcher_op_registration + else registration_body, + "deferred_dispatch_registrations": "", + "dispatch_namespace": dispatch_key.lower(), + "dispatch_namespaced_definitions": ns_definitions[kernel_namespace], + }, + ).split(newline) + ) + + return definitions + + +# Return native function declarations grouped by dispatch key and custom namespace. +# Used in CPUFunctions_inl.h and etc. +def get_namespaced_declaration( + *, + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + dispatch_key: DispatchKey, + backend_idx: BackendIndex, + selector: SelectiveBuilder, + rocm: bool, + symint: bool, +) -> list[str]: + declarations: list[str] = [] + ns_grouped_kernels: dict[str, list[str]] = defaultdict(list) + newline = "\n" + func = dest.RegisterDispatchKey( + backend_idx, + Target.NAMESPACED_DECLARATION, + selector, + rocm=rocm, + class_method_name=None, + skip_dispatcher_op_registration=False, + symint=symint, + ) + for f in grouped_native_functions: + namespace = get_kernel_namespace(f=f, backend_idx=backend_idx).replace( + "native", dispatch_key.lower() + ) + + ns_grouped_kernels[namespace].extend( + func(f), + ) + + for namespace, kernels in ns_grouped_kernels.items(): + if len(kernels) == 0: + continue + ns_helper = NamespaceHelper( + namespace_str=namespace, entity_name="", max_level=3 + ) + ordered_kernels = list(OrderedDict.fromkeys(kernels)) + declarations.extend( + f""" +{ns_helper.prologue} +{newline.join(ordered_kernels)} +{ns_helper.epilogue} + """.split(newline) + ) + return declarations + + +# Return native function schema registration code for aten and other namespaces. +def get_native_function_schema_registrations( + *, + native_functions: Sequence[NativeFunction], + schema_selector: SelectiveBuilder, +) -> tuple[list[str], str]: + ns_native_functions: dict[str, list[NativeFunction]] = defaultdict(list) + for native_function in native_functions: + ns_native_functions[native_function.namespace].append(native_function) + schema_registrations = "" + aten_schema_registrations = [] + custom_namespace = None + for namespace, funcs in ns_native_functions.items(): + schema_registrations_body = list( + mapMaybe(RegisterSchema(schema_selector), funcs) + ) + # NB: we have to separate aten namespace registration from other namespaces, + # because in the template we hardcoded an operator for ATen already. + if namespace == "aten": + aten_schema_registrations = schema_registrations_body + else: + custom_namespace = namespace + tab = "\t" + # if the namespace is predefined, we should use define a library fragment + # instead of a new library + torch_library_macro = ( + "TORCH_LIBRARY_FRAGMENT" + if namespace in FRAGMENT_NAMESPACES + else "TORCH_LIBRARY" + ) + schema_registrations += f""" +{torch_library_macro}({custom_namespace}, m) {{ + {tab.join(schema_registrations_body)} +}};""" + return (aten_schema_registrations, schema_registrations) + + +def gen_aggregated_headers( + *, + native_functions: Sequence[NativeFunction], + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + structured_native_functions: Sequence[NativeFunctionsGroup], + static_dispatch_idx: list[BackendIndex], + selector: SelectiveBuilder, + backend_indices: dict[DispatchKey, BackendIndex], + cpu_fm: FileManager, + device_fms: dict[str, FileManager], + functions_keys: set[DispatchKey], + dispatch_keys: Sequence[DispatchKey], + rocm: bool, +) -> None: + # Buck doesn't support dynamic output files, so we aggregate all operator + # headers into a single file + cpu_fm.write( + "NativeMetaFunctions.h", + lambda: { + "NativeMetaFunctions_includes": [], + "NativeMetaFunctions_declarations": list( + mapMaybe(compute_meta_function_declaration, structured_native_functions) + ), + }, + ) + method_native_functions = [ + fn for fn in native_functions if Variant.method in fn.variants + ] + non_method_native_functions = [ + fn for fn in native_functions if fn not in method_native_functions + ] + cpu_fm.write( + "MethodOperators.h", + lambda: { + "MethodOperators_includes": [], + "MethodOperators_declarations": list( + mapMaybe( + ComputeOperators( + Target.DECLARATION, + static_dispatch_backend_indices=static_dispatch_idx, + ), + method_native_functions, + ) + ), + }, + ) + cpu_fm.write( + "Operators.h", + lambda: { + "Operators_includes": ["#include "], + "Operators_declarations": list( + mapMaybe( + ComputeOperators( + Target.DECLARATION, + static_dispatch_backend_indices=static_dispatch_idx, + ), + non_method_native_functions, + ) + ), + }, + ) + cpu_fm.write( + "Functions.h", + lambda: { + "static_dispatch_extra_headers": static_dispatch_extra_headers( + static_dispatch_idx + ), + "Functions_includes": ["#include "], + "Functions_declarations": list( + mapMaybe( + ComputeFunction(), + native_functions, + ) + ), + }, + ) + declarations = get_native_function_declarations( + grouped_native_functions=grouped_native_functions, + backend_indices=backend_indices, + ) + cpu_fm.write( + "NativeFunctions.h", + lambda: { + "NativeFunctions_includes": ["#include "], + "NativeFunctions_declarations": declarations, + }, + ) + + for dispatch_key in dispatch_keys: + fm = file_manager_from_dispatch_key(dispatch_key, device_fms, cpu_fm) + if dispatch_key in functions_keys: + inl_headers = f"#include " + + fm.write_with_template( + f"{dispatch_key}Functions.h", + "DispatchKeyFunctions.h", + lambda: { + "dispatch_key": str(dispatch_key), + "inline_headers": inl_headers, + }, + ) + fm.write_with_template( + f"{dispatch_key}Functions_inl.h", + "DispatchKeyFunctions_inl.h", + lambda: { + "DispatchKeyFunctions_inl_includes": [], + "dispatch_namespace": dispatch_key.lower(), + "dispatch_namespaced_declarations": get_namespaced_declaration( + grouped_native_functions=grouped_native_functions, + dispatch_key=dispatch_key, + backend_idx=backend_indices[dispatch_key], + selector=selector, + rocm=rocm, + symint=True, + ), + }, + ) + + del fm + + +def gen_per_operator_headers( + *, + native_functions: Sequence[NativeFunction], + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + static_dispatch_idx: list[BackendIndex], + selector: SelectiveBuilder, + backend_indices: dict[DispatchKey, BackendIndex], + cpu_fm: FileManager, + device_fms: dict[str, FileManager], + ops_fm: FileManager, + functions_keys: set[DispatchKey], + dispatch_keys: Sequence[DispatchKey], + rocm: bool, +) -> None: + # For CMake builds, split operator declarations into separate headers in + # the ATen/ops folder to split up header dependencies + functions_by_root_name: dict[str, list[NativeFunction]] = defaultdict(list) + for fn in native_functions: + functions_by_root_name[fn.root_name].append(fn) + + grouped_functions_by_root_name: dict[ + str, list[NativeFunction | NativeFunctionsGroup] + ] = defaultdict(list) + for group in grouped_native_functions: + name = group.root_name + grouped_functions_by_root_name[name].append(group) + + for name, functions in functions_by_root_name.items(): + ops_fm.write_with_template( + f"{name}_ops.h", + "Operator.h", + lambda: { + "declarations": list( + mapMaybe( + ComputeOperators( + Target.DECLARATION, + static_dispatch_backend_indices=static_dispatch_idx, + ), + functions, + ) + ), + }, + ) + + ops_fm.write_with_template( + f"{name}.h", + "Function.h", + lambda: { + "static_dispatch_ops_headers": list( + mapMaybe( + lambda fn: static_dispatch_ops_header( + fn, backend_index=static_dispatch_idx + ), + functions, + ) + ), + "operator_includes": f"#include ", + "function_definitions": list( + mapMaybe( + ComputeFunction(), + functions, + ) + ), + }, + ) + + grouped_functions = grouped_functions_by_root_name.get(name, []) + structured_functions = [ + fn + for fn in grouped_functions + if isinstance(fn, NativeFunctionsGroup) and fn.structured + ] + is_structured = len(structured_functions) > 0 + + if is_structured: + ops_fm.write_with_template( + f"{name}_meta.h", + "NativeMetaFunction.h", + lambda: { + "meta_function_declarations": list( + mapMaybe( + compute_meta_function_declaration, structured_functions + ) + ), + }, + ) + declarations = get_native_function_declarations( + grouped_native_functions=grouped_functions, + backend_indices=backend_indices, + native_function_decl_gen=dest.compute_native_function_declaration, + ) + ops_fm.write_with_template( + f"{name}_native.h", + "NativeFunction.h", + lambda: { + "extra_includes": ( + f"#include " if is_structured else [] + ), + "native_function_declarations": declarations, + }, + ) + + for category, suffix in [ + ("Functions", ""), + ("Operators", "_ops"), + ("NativeMetaFunctions", "_meta"), + ("NativeFunctions", "_native"), + ]: + cpu_fm.write( + f"{category}.h", + lambda: { + f"{category}_includes": [ + f"#include " + for name in sorted(functions_by_root_name.keys()) + ], + f"{category}_declarations": [], + }, + ) + + for dispatch_key in dispatch_keys: + if dispatch_key not in functions_keys: + continue + + dispatch_namespace = dispatch_key.lower() + dispatch_names = [] + + for name, functions in functions_by_root_name.items(): + grouped_functions = grouped_functions_by_root_name.get(name, []) + declarations = list( + concatMap( + dest.RegisterDispatchKey( + backend_indices[dispatch_key], + Target.NAMESPACED_DECLARATION, + selector, + rocm=rocm, + symint=True, + class_method_name=None, + skip_dispatcher_op_registration=False, + ), + grouped_functions, + ) + ) + + if len(declarations) == 0: + continue + + dispatch_names.append(name) + ops_fm.write_with_template( + f"{name}_{dispatch_namespace}_dispatch.h", + "DispatchKeyFunction.h", + lambda: { + "dispatch_namespace": dispatch_namespace, + "dispatch_namespaced_declarations": declarations, + }, + ) + + fm = file_manager_from_dispatch_key(dispatch_key, device_fms, cpu_fm) + inl_headers = f"#include " + + fm.write_with_template( + f"{dispatch_key}Functions.h", + "DispatchKeyFunctions.h", + lambda: { + "dispatch_key": str(dispatch_key), + "inline_headers": inl_headers, + }, + ) + fm.write_with_template( + f"{dispatch_key}Functions_inl.h", + "DispatchKeyFunctions_inl.h", + lambda: { + "dispatch_namespace": dispatch_namespace, + "DispatchKeyFunctions_inl_includes": [ + f"#include " + for name in sorted(dispatch_names) + ], + "dispatch_namespaced_declarations": [], + }, + ) + del fm + + cpu_fm.write( + "MethodOperators.h", + lambda: { + "MethodOperators_includes": sorted( + f"#include " + for name, functions in functions_by_root_name.items() + if any(Variant.method in fn.variants for fn in functions) + ), + "MethodOperators_declarations": [], + }, + ) + + +def gen_headers( + *, + native_functions: Sequence[NativeFunction], + valid_tags: set[str], + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + structured_native_functions: Sequence[NativeFunctionsGroup], + static_dispatch_idx: list[BackendIndex], + selector: SelectiveBuilder, + backend_indices: dict[DispatchKey, BackendIndex], + headeronly_fm: FileManager, + core_fm: FileManager, + cpu_fm: FileManager, + device_fms: dict[str, FileManager], + ops_fm: FileManager, + dispatch_keys: Sequence[DispatchKey], + functions_keys: set[DispatchKey], + rocm: bool, + per_operator_headers: bool, +) -> None: + if per_operator_headers: + gen_per_operator_headers( + native_functions=native_functions, + grouped_native_functions=grouped_native_functions, + static_dispatch_idx=static_dispatch_idx, + selector=selector, + backend_indices=backend_indices, + cpu_fm=cpu_fm, + device_fms=device_fms, + ops_fm=ops_fm, + dispatch_keys=dispatch_keys, + functions_keys=functions_keys, + rocm=rocm, + ) + else: + gen_aggregated_headers( + native_functions=native_functions, + grouped_native_functions=grouped_native_functions, + structured_native_functions=structured_native_functions, + static_dispatch_idx=static_dispatch_idx, + selector=selector, + backend_indices=backend_indices, + cpu_fm=cpu_fm, + device_fms=device_fms, + dispatch_keys=dispatch_keys, + functions_keys=functions_keys, + rocm=rocm, + ) + + core_fm.write( + "TensorBody.h", + lambda: { + "tensor_method_declarations": list( + mapMaybe( + ComputeTensorMethod( + target=Target.DECLARATION, + static_dispatch_backend_indices=static_dispatch_idx, + ), + native_functions, + ) + ), + "tensor_method_definitions": list( + mapMaybe( + ComputeTensorMethod( + target=Target.DEFINITION, + static_dispatch_backend_indices=static_dispatch_idx, + ), + native_functions, + ) + ), + }, + ) + + cpu_fm.write( + "RedispatchFunctions.h", + lambda: { + "function_redispatch_definitions": list( + mapMaybe(ComputeRedispatchFunction(), native_functions) + ), + }, + ) + + cpu_fm.write( + "RegistrationDeclarations.h", + lambda: { + "registration_declarations": [ + compute_registration_declarations(f, backend_indices) + for f in native_functions + ], + }, + ) + + cpu_fm.write( + "VmapGeneratedPlumbing.h", lambda: gen_all_vmap_plumbing(native_functions) + ) + + def gen_aten_interned_strings() -> dict[str, str]: + attrs: set[str] = set() # All function argument names + names = set() # All ATen function names + for func in native_functions: + names.add(str(func.func.name.name)) + # Some operators don't have a functional variant but we still create a + # symbol without the underscore + names.add(func.func.name.name.base) + + attrs.update(arg.name for arg in func.func.schema_order_arguments()) + + # These are keywords in C++, so aren't valid symbol names + # https://en.cppreference.com/w/cpp/language/operator_alternative + names -= { + "and", + "and_eq", + "bitand", + "bitor", + "compl", + "not", + "not_eq", + "or", + "or_eq", + "xor", + "xor_eq", + } + + return { + "aten_symbols": " \\\n".join( + [f"_(aten, {name})" for name in sorted(names)] + ), + "attr_symbols": " \\\n".join( + [f"_(attr, {name})" for name in sorted(attrs)] + ), + } + + core_fm.write("aten_interned_strings.h", gen_aten_interned_strings) + + def gen_tags_enum() -> dict[str, str]: + return {"enum_of_valid_tags": (",\n".join(sorted(valid_tags)))} + + headeronly_fm.write("enum_tag.h", gen_tags_enum) + + +def gen_source_files( + *, + native_functions: Sequence[NativeFunction], + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + structured_native_functions: Sequence[NativeFunctionsGroup], + view_groups: Sequence[NativeFunctionsViewGroup], + selector: SelectiveBuilder, + static_dispatch_idx: list[BackendIndex], + backend_indices: dict[DispatchKey, BackendIndex], + aoti_fm: FileManager, + core_fm: FileManager, + cpu_vec_fm: FileManager, + cpu_fm: FileManager, + device_fms: dict[str, FileManager], + dispatch_keys: Sequence[DispatchKey], + functions_keys: set[DispatchKey], + rocm: bool, + force_schema_registration: bool, + per_operator_headers: bool, + skip_dispatcher_op_registration: bool, + update_aoti_c_shim: bool, + aoti_backends: set[DispatchKey | None], + extend_aoti_c_shim: bool, +) -> None: + extra_cuda_headers = """\ +#include +#include +#include +#include """ + if rocm: + extra_cuda_headers = """\ +#include +#include +#include +#include """ + + for dispatch_key in dispatch_keys: + fm = file_manager_from_dispatch_key(dispatch_key, device_fms, cpu_fm) + if per_operator_headers: + + def operator_headers() -> list[str]: + headers = [] + for g in grouped_native_functions: + is_registered = False + if backend_index.has_kernel(g): + is_registered = True + # The above has_kernel test on a group will only test for + # the existence of out dispatch, because that's how + # structured kernels work. But sometimes functions can be + # grouped but not be structured, and then you need to check + # each individual piece, as they may have manual dispatch + # entries. + elif isinstance(g, NativeFunctionsGroup) and any( + backend_index.has_kernel(fn) for fn in g.functions() + ): + is_registered = True + # TODO: this condition is a bit questionable + # (It has to do with the fact that structured kernels get generated kernels + # to the Meta + CompositeExplicitAutogradNonFunctional keys). + elif g.structured and dispatch_key in ( + DispatchKey.Meta, + DispatchKey.CompositeExplicitAutogradNonFunctional, + ): + is_registered = True + if not is_registered: + continue + + headers.append(f"#include ") + if ( + dispatch_key + == DispatchKey.CompositeExplicitAutogradNonFunctional + ): + headers.append(f"#include ") + if dispatch_key in functions_keys: + headers.append( + f"#include " + ) + + return sorted(set(headers)) + + else: + + def operator_headers() -> list[str]: + headers = ["#include "] + if dispatch_key == DispatchKey.CompositeExplicitAutogradNonFunctional: + headers.append("#include ") + if dispatch_key in functions_keys: + headers.append(f"#include ") + return headers + + backend_index = backend_indices[dispatch_key] + ns_grouped_native_functions = defaultdict(list) + for grouped_native_function in grouped_native_functions: + namespace = ( + grouped_native_function.namespace + if isinstance(grouped_native_function, NativeFunction) + else grouped_native_function.functional.namespace + ) + ns_grouped_native_functions[namespace].append(grouped_native_function) + + dispatch_namespace = str(dispatch_key).lower() + + # CompositeImplicitAutogradNestdTensor does not currently user the helpers generated + # compilation will fail when `-Werror=unused-function` flag is set + gen_dispatch_helpers: bool = ( + dispatch_key != DispatchKey.CompositeImplicitAutogradNestedTensor + ) + + register_dispatch_key_base_env = { + "extra_cuda_headers": extra_cuda_headers + if is_cuda_dispatch_key(dispatch_key) + else "", + "external_backend_headers": "", + "dispatch_headers": dest.gen_registration_headers( + backend_index, per_operator_headers, rocm + ), + # ops_headers *could* be sharded, but doesn't seem necessary? + "ops_headers": operator_headers(), + "dispatch_helpers": ( + dest.gen_registration_helpers(backend_index) + if gen_dispatch_helpers + else [] + ), + } + + def register_dispatch_key_env_callable( + gnf: NativeFunction | NativeFunctionsGroup, + ) -> dict[str, list[str]]: + return { + "dispatch_definitions": get_native_function_definitions( + fm=fm, # noqa: F821 + grouped_native_functions=[gnf], + dispatch_key=dispatch_key, + backend_idx=backend_index, + selector=selector, + rocm=rocm, + symint=True, + skip_dispatcher_op_registration=skip_dispatcher_op_registration, + gen_dispatch_helpers=gen_dispatch_helpers, + ) + } + + fm.write_sharded_with_template( + f"Register{dispatch_key}.cpp", + "RegisterDispatchKey.cpp", + grouped_native_functions, + key_fn=lambda x: x.root_name, + env_callable=register_dispatch_key_env_callable, + num_shards=4 if dispatch_key == DispatchKey.CPU else 1, + base_env=register_dispatch_key_base_env, + sharded_keys={"dispatch_definitions"}, + ) + + for g in structured_native_functions: + if not g.out.ufunc_inner_loop or not is_ufunc_dispatch_key(dispatch_key): + continue + name = g.functional.func.name.name + if dispatch_key is DispatchKey.CPU: + if fm is not cpu_fm: + raise AssertionError("Expected fm to be cpu_fm for DispatchKey.CPU") + fm.write_with_template( + f"UfuncCPU_{name}.cpp", + "UfuncCPU.cpp", + lambda: { + "meta_declaration": compute_meta_function_declaration(g), + "native_declaration": dest.compute_native_function_declaration( + g, backend_indices[dispatch_key] + ), + "native_definitions": dest.compute_ufunc_cpu(g), + }, + ) + cpu_vec_fm.write_with_template( + f"UfuncCPUKernel_{name}.cpp", + "UfuncCPUKernel.cpp", + lambda: { + "name": name, + "native_definitions": dest.compute_ufunc_cpu_kernel(g), + }, + ) + elif dispatch_key is DispatchKey.CUDA: + cuda_headers = "#include " + if rocm: + cuda_headers = "#include " + fm.write_with_template( + f"UfuncCUDA_{name}.cu", + "UfuncCUDA.cu", + lambda: { + "name": name, + "cuda_headers": cuda_headers, + "meta_declaration": compute_meta_function_declaration(g), + "native_declaration": dest.compute_native_function_declaration( + g, backend_indices[dispatch_key] + ), + "native_definitions": dest.compute_ufunc_cuda(g), + }, + ) + else: + raise AssertionError(f"unrecognized {dispatch_key} for ufunc") + + del fm + + gen_aoti_c_shim_files( + aoti_fm=aoti_fm, + aoti_backends=aoti_backends, + native_functions=native_functions, + backend_indices=backend_indices, + structured_native_functions=structured_native_functions, + extra_cuda_headers=extra_cuda_headers, + update_aoti_c_shim=update_aoti_c_shim, + extend_aoti_c_shim=extend_aoti_c_shim, + ) + + # BackendSelect is generated specially + def gen_backend_select() -> dict[str, list[str]]: + relevant_fns = [ + fn for fn in native_functions if needs_backend_select(fn, selector) + ] + return { + "ops_headers": [ + f"#include " for fn in relevant_fns + ], + "backend_select_method_definitions": list( + mapMaybe( + ComputeBackendSelect(Target.DEFINITION, selector), relevant_fns + ) + ), + "backend_select_function_registrations": list( + mapMaybe( + ComputeBackendSelect(Target.REGISTRATION, selector), relevant_fns + ) + ), + } + + cpu_fm.write("RegisterBackendSelect.cpp", gen_backend_select) + + schema_selector = selector + if force_schema_registration: + schema_selector = SelectiveBuilder.get_nop_selector() + + ( + aten_schema_registrations, + schema_registrations, + ) = get_native_function_schema_registrations( + native_functions=native_functions, schema_selector=schema_selector + ) + cpu_fm.write( + "RegisterSchema.cpp", + lambda: { + "aten_schema_registrations": [] + if skip_dispatcher_op_registration + else aten_schema_registrations, + "schema_registrations": [] + if skip_dispatcher_op_registration + else schema_registrations, + }, + ) + + def key_func( + fn: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup, + ) -> str: + return fn.root_name + + cpu_fm.write_sharded( + "Operators.cpp", + native_functions, + key_fn=key_func, + env_callable=lambda fn: { + "operator_headers": [f"#include "], + "definitions": [ + ComputeOperators( + Target.DEFINITION, + static_dispatch_backend_indices=static_dispatch_idx, + )(fn) + ], + }, + base_env={ + "static_dispatch_extra_headers": static_dispatch_extra_headers( + static_dispatch_idx + ), + }, + num_shards=5, + sharded_keys={ + "operator_headers", + "definitions", + "static_dispatch_extra_headers", + }, + ) + + cpu_fm.write("Functions.cpp", dict) + + core_fm.write("TensorMethods.cpp", dict) + + core_fm.write( + "ATenOpList.cpp", + lambda: { + "aten_ops": list(mapMaybe(compute_aten_op, native_functions)), + }, + ) + + def gen_op_headers( + g: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup, + ) -> list[str]: + if isinstance(g, NativeFunctionsViewGroup): + # view ops always get a functionalization kernel + headers = [ + f"#include ", + f"#include ", + ] + if g.view_copy is not None: + headers += [ + f"#include ", + f"#include ", + ] + return headers + elif isinstance(g, NativeFunctionsGroup): + headers = [ + f"#include ", + f"#include ", + f"#include ", + f"#include ", + ] + if g.inplace is not None: + headers += [ + f"#include ", + f"#include ", + ] + if g.mutable is not None: + headers += [ + f"#include ", + f"#include ", + ] + return headers + else: + return [ + f"#include ", + f"#include ", + ] + + def functionalization_env_callable( + g: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup, + ) -> dict[str, list[str]]: + return { + "ops_headers": gen_op_headers(g), + "func_definitions": gen_functionalization_definition( + selector, + g, + ), + "func_registrations": gen_functionalization_registration( + selector, + g, + backend_indices[DispatchKey.CompositeImplicitAutograd], + ), + } + + all_groups: list[ + NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup + ] = list(structured_native_functions) + list( + view_groups # type: ignore[assignment, arg-type, operator] + ) + # Note: all operators that functionalization needs to handle (mutable and aliasing ops) should be grouped properly. + # The only reason we really need to deal with direct NativeFunctions here (instead of the groups) is because: + # (1) We can provide better error checking (error out if someone introduces a mutable op that doesn't obey the grouping logic) + # (2) functionalization needs to manually register CompositeImplicitAutograd kernels, which might not be grouped. + # Although this could go away long-term if we add a dedicated dispatch key for decompositions. + structured_map: dict[OperatorName, NativeFunction] = { + f.func.name: f + for f in concatMap(lambda g: list(g.functions()), structured_native_functions) + } + view_map: dict[OperatorName, NativeFunction] = { + f.func.name: f for f in concatMap(lambda g: list(g.functions()), view_groups) + } + all_groups.extend( + f + for f in native_functions + if f.func.name not in structured_map and f.func.name not in view_map + ) + + cpu_fm.write_sharded( + "RegisterFunctionalization.cpp", + all_groups, + key_fn=key_func, + env_callable=functionalization_env_callable, + num_shards=4, + sharded_keys={ + "ops_headers", + "func_definitions", + "func_registrations", + "func_add_back_views_definitions", + "func_add_back_views_registrations", + }, + ) + + cpu_fm.write( + "FunctionalInverses.h", + lambda: { + "view_inverse_declarations": list( + mapMaybe( + lambda g: gen_functionalization_view_inverse_declaration( + selector, g + ), + view_groups, + ) + ) + }, + ) + + cpu_fm.write( + "ViewMetaClasses.h", + lambda: { + "view_meta_declarations": list( + concatMap( + lambda g: gen_functionalization_view_meta_classes_decl(selector, g), + view_groups, + ) + ) + }, + ) + + cpu_fm.write( + "ViewMetaClasses.cpp", + lambda: { + "view_meta_implementations": list( + concatMap( + lambda g: gen_functionalization_view_meta_classes_impl(selector, g), + view_groups, + ) + ), + "op_headers": list(concatMap(gen_op_headers, view_groups)), + }, + ) + + # Note [view_copy NativeFunctions] + # Every view operator in native_functions.yaml that is not CompositeImplicitAutograd + # needs to have a corresponding non-aliasing {view}_copy variant. + # Backends that use functionalization and don't know how to handle aliasing ops + # are expected to implement kernels for these {view}_copy kernels instead. + # The code for {view}_copy operators in core is pretty boilerplate-heavy however, + # so we codegen the following: + # (1) A CompositeExplicitAutogradNonFunctional kernel for every {view}_copy operator. + # These are never explicitly invoked by the functionalization pass, + # but they could theoretically be called from user code (I added these kernels for completeness, + # since the ops are part of the public API). + # (2) A derivative formula for every {view}_copy operator + # {view}_copy operators can reuse the same derivative formulas as their {view} op counterparts, + # so rather than stamping all of the entries out in derivatives.yaml, + # we codegen them in. + # This is similar to how autograd codegen doesn't require inplace ops to have a derivatives.yaml entry. + cpu_fm.write( + "CompositeViewCopyKernels.cpp", + lambda: { + "ops_headers": [ + "\n".join( + f"#include \n" + # NB: this include is important as it ensures we + # set the visibility on generated view_copy kernels + # correctly + f"#include " + for f in ( + [g.view] if g.view_copy is None else [g.view, g.view_copy] + ) + ) + for g in view_groups + ] + + [ + "\n".join( + f"#include \n" + # NB: this include is also important for correct visibility + f"#include " + for f in [g.inplace, g.mutable, g.functional] + if f is not None and "generated" not in f.tags + ) + for g in structured_native_functions + ], + "CompositeViewCopyKernel_Definitions": list( + mapMaybe( + GenCompositeViewCopyKernel( + backend_indices[ + DispatchKey.CompositeExplicitAutogradNonFunctional + ] + ), + view_groups, + ) + ), + "GeneratedCompositeFunctional_Definitions": list( + mapMaybe( + gen_composite_functional_kernel, + structured_native_functions, + ) + ), + "GeneratedCompositeOut_Definitions": list( + mapMaybe( + gen_composite_out_kernel, + structured_native_functions, + ) + ), + }, + ) + + +def gen_declarations_yaml( + cpu_fm: FileManager, native_functions: Sequence[NativeFunction] +) -> None: + cpu_fm.write( + "Declarations.yaml", + lambda: format_yaml([compute_declaration_yaml(f) for f in native_functions]), + ) + + +def get_torchgen_root() -> Path: + """ + If you're depending on torchgen out-of-tree, you can use the root to figure + out the path to native_functions.yaml + """ + return Path(__file__).parent.resolve() + + +def main() -> None: + parser = argparse.ArgumentParser(description="Generate ATen source files") + parser.add_argument( + "-s", + "--source-path", + help="path to source directory for ATen", + default="aten/src/ATen", + ) + parser.add_argument( + "-o", + "--output-dependencies", + help="output a list of dependencies into the given file and exit", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="run without writing any files (still updates outputs)", + ) + parser.add_argument( + "--per-operator-headers", + action="store_true", + help="generate separate headers per operator in ATen/ops", + ) + parser.add_argument( + "-d", + "--install-dir", + "--install_dir", + help="output directory", + default="build/aten/src/ATen", + ) + parser.add_argument( + "--aoti-install-dir", + "--aoti_install_dir", + help="output directory for AOTInductor shim", + default="torch/csrc/inductor/aoti_torch/generated", + ) + parser.add_argument( + "--headeronly-install-dir", + "--headeronly_install_dir", + help="output directory for header-only generated files (e.g. enum_tag.h). " + "Defaults to `/core` when --install-dir is set, otherwise " + "`build/torch/headeronly/core`.", + default=None, + ) + parser.add_argument( + "--rocm", + action="store_true", + help="reinterpret CUDA as ROCm/HIP and adjust filepaths accordingly", + ) + parser.add_argument( + "--mps", + action="store_true", + help="Generate MPS registration code when set", + ) + parser.add_argument( + "--xpu", + action="store_true", + help="Generate XPU registration code when set", + ) + parser.add_argument( + "--mtia", + action="store_true", + help="Generate MTIA registration code when set", + ) + + # TODO: --op-registration-whitelist will be removed when all call-sites + # for gen.py are moved over to using the operator YAML file for mobile + # custom build. + parser.add_argument( + "--op-registration-whitelist", + "--op_registration_whitelist", + nargs="*", + help="filter op registrations by the whitelist (if set); " + "each item is `namespace`::`operator name` without overload name; " + "e.g.: aten::empty aten::conv2d ...", + ) + parser.add_argument( + "--op-selection-yaml-path", + "--op_selection_yaml_path", + help="Provide a path to the operator selection (for custom build) YAML " + "that contains the information about the set of selected operators " + "and their categories (training, ...). Each operator is either a " + "full operator name with overload or just a bare operator name. " + "The operator names also contain the namespace prefix (e.g. aten::)", + ) + parser.add_argument( + "--backend-whitelist", + "--backend_whitelist", + nargs="*", + help="filter dispatch backend by the whitelist (if set), " + "e.g.: CPU CUDA QuantizedCPU ...", + ) + parser.add_argument( + "--static-dispatch-backend", + "--static_dispatch_backend", + nargs="*", + help="generate static dispatch code for the specific backend (if set)", + ) + parser.add_argument( + "--skip-dispatcher-op-registration", + "--skip_dispatcher_op_registration", + action="store_true", + help="Avoid registering operators into the dispatcher.", + ) + parser.add_argument( + "--force-schema-registration", + "--force_schema_registration", + action="store_true", + help="force it to generate schema-only registrations for all ops, including" + "those that are not listed on --op-registration-whitelist", + ) + parser.add_argument( + "--generate", + type=str, + nargs="*", + choices=["headers", "sources", "declarations_yaml"], + default=["headers", "sources", "declarations_yaml"], + help="Generate only a subset of files", + ) + parser.add_argument( + "--update-aoti-c-shim", + action="store_true", + help="Update AOTInductor C shim after adding an entry to inductor_fallback_ops in torchgen/aoti/fallback_ops.py. " + "WARNING: Do not use this unless you are sure what you are doing!!!", + ) + parser.add_argument( + "--extend-aoti-c-shim", + action="store_true", + help="This Flag indicates the generation of c shims for out-of-tree ATen ops," + "which is an extension to the In-tree ATen op c shims. This flag needs to be combined with" + "---source-path=" + "--aoti-install-dir=/extend" + " default is torch/csrc/inductor/aoti_torch/generated/extend" + "WARNING: Do not use this unless you are sure what you are doing!!!", + ) + + options = parser.parse_args() + + selector = get_custom_build_selector( + options.op_registration_whitelist, + options.op_selection_yaml_path, + ) + + native_yaml_path = os.path.join(options.source_path, "native/native_functions.yaml") + tags_yaml_path = os.path.join(options.source_path, "native/tags.yaml") + + from torchgen.model import dispatch_keys + + # Only a limited set of dispatch keys get CPUFunctions.h headers generated + # for them; this is the set + functions_keys = { + DispatchKey.CPU, + DispatchKey.CUDA, + DispatchKey.CompositeImplicitAutograd, + DispatchKey.CompositeImplicitAutogradNestedTensor, + DispatchKey.CompositeExplicitAutograd, + DispatchKey.CompositeExplicitAutogradNonFunctional, + DispatchKey.Meta, + DispatchKey.MTIA, + } + + aoti_backends = { + DispatchKey.CPU, + DispatchKey.CUDA, + # None will generate the aten shim based on aten_shimified_ops + # which does not bypass the dispatcher + None, + } + + # TODO: stop generating CUDA kernels for non-CUDA builds + ignore_keys = set() + + MPS_KEYS = {DispatchKey.MPS, DispatchKey.SparseMPS, DispatchKey.SparseCsrMPS} + if options.mps or options.update_aoti_c_shim: + functions_keys.update(MPS_KEYS) + aoti_backends.add(DispatchKey.MPS) + else: + ignore_keys.update(MPS_KEYS) + dispatch_keys[:] = [k for k in dispatch_keys if k not in MPS_KEYS] + + XPU_KEYS = { + DispatchKey.XPU, + DispatchKey.SparseXPU, + DispatchKey.SparseCsrXPU, + DispatchKey.NestedTensorXPU, + } + if options.xpu or options.update_aoti_c_shim: + functions_keys.add(DispatchKey.XPU) + aoti_backends.add(DispatchKey.XPU) + else: + ignore_keys.update(XPU_KEYS) + dispatch_keys[:] = [k for k in dispatch_keys if k not in XPU_KEYS] + + if not options.mtia: + ignore_keys.add(DispatchKey.MTIA) + + if DispatchKey.MTIA in dispatch_keys: + del dispatch_keys[dispatch_keys.index(DispatchKey.MTIA)] + + if options.backend_whitelist: + dispatch_keys = [ + k + for k in dispatch_keys + if is_generic_dispatch_key(k) or str(k) in options.backend_whitelist + ] + + parsed_yaml = parse_native_yaml(native_yaml_path, tags_yaml_path, ignore_keys) + valid_tags = _GLOBAL_PARSE_TAGS_YAML_CACHE[tags_yaml_path] + native_functions, backend_indices = ( + parsed_yaml.native_functions, + parsed_yaml.backend_indices, + ) + + grouped_native_functions = get_grouped_native_functions(native_functions) + + structured_native_functions = [ + g for g in grouped_native_functions if isinstance(g, NativeFunctionsGroup) + ] + native_functions_with_view_groups = get_grouped_by_view_native_functions( + native_functions + ) + view_groups = [ + g + for g in native_functions_with_view_groups + if isinstance(g, NativeFunctionsViewGroup) + ] + + # NB: It is mandatory to NOT use os.path.join here, as the install directory + # will eventually be ingested by cmake, which does not respect Windows style + # path slashes. If you switch this to use os.path.join, you'll get an error + # like: + # + # Syntax error in cmake code when parsing string + # + # C:/Jenkins/workspace/pytorch-builds/pytorch-win-ws2016-cuda9-cudnn7-py3-build/build/aten/src/ATen\core/TensorMethods.h + # + # Invalid character escape '\c'. + core_install_dir = f"{options.install_dir}/core" + Path(core_install_dir).mkdir(parents=True, exist_ok=True) + ops_install_dir = f"{options.install_dir}/ops" + Path(ops_install_dir).mkdir(parents=True, exist_ok=True) + + aoti_install_dir = f"{options.aoti_install_dir}" + Path(aoti_install_dir).mkdir(parents=True, exist_ok=True) + + if options.headeronly_install_dir is not None: + headeronly_install_dir = options.headeronly_install_dir + elif options.install_dir is not None: + headeronly_install_dir = f"{options.install_dir}/core" + else: + headeronly_install_dir = "build/torch/headeronly/core" + Path(headeronly_install_dir).mkdir(parents=True, exist_ok=True) + + core_fm = make_file_manager(options=options, install_dir=core_install_dir) + cpu_fm = make_file_manager(options=options) + cpu_vec_fm = make_file_manager(options=options) + cuda_fm = make_file_manager(options=options) + ops_fm = make_file_manager(options=options, install_dir=ops_install_dir) + aoti_fm = make_file_manager(options=options, install_dir=aoti_install_dir) + headeronly_fm = make_file_manager( + options=options, install_dir=headeronly_install_dir + ) + device_fms = {"cuda": cuda_fm} + if options.xpu: + device_fms["xpu"] = make_file_manager(options=options) + + static_dispatch_idx: list[BackendIndex] = [] + if options.static_dispatch_backend: + static_dispatch_idx = [ + backend_indices[DispatchKey.parse(key)] + for key in options.static_dispatch_backend + ] + for key in options.static_dispatch_backend: + dp_key = DispatchKey.parse(key) + if dp_key not in functions_keys: + functions_keys.add(dp_key) + + if "sources" in options.generate: + gen_source_files( + native_functions=native_functions, + grouped_native_functions=grouped_native_functions, + structured_native_functions=structured_native_functions, + view_groups=view_groups, + selector=selector, + static_dispatch_idx=static_dispatch_idx, + backend_indices=backend_indices, + aoti_fm=aoti_fm, + core_fm=core_fm, + cpu_vec_fm=cpu_vec_fm, + cpu_fm=cpu_fm, + device_fms=device_fms, + dispatch_keys=dispatch_keys, + functions_keys=functions_keys, + rocm=options.rocm, + force_schema_registration=options.force_schema_registration, + per_operator_headers=options.per_operator_headers, + skip_dispatcher_op_registration=options.skip_dispatcher_op_registration, + update_aoti_c_shim=options.update_aoti_c_shim, + aoti_backends=aoti_backends, + extend_aoti_c_shim=options.extend_aoti_c_shim, + ) + + if "headers" in options.generate: + gen_headers( + native_functions=native_functions, + valid_tags=valid_tags, + grouped_native_functions=grouped_native_functions, + structured_native_functions=structured_native_functions, + static_dispatch_idx=static_dispatch_idx, + selector=selector, + backend_indices=backend_indices, + headeronly_fm=headeronly_fm, + core_fm=core_fm, + cpu_fm=cpu_fm, + device_fms=device_fms, + ops_fm=ops_fm, + dispatch_keys=dispatch_keys, + functions_keys=functions_keys, + rocm=options.rocm, + per_operator_headers=options.per_operator_headers, + ) + + if "declarations_yaml" in options.generate: + gen_declarations_yaml(native_functions=native_functions, cpu_fm=cpu_fm) + + if options.output_dependencies: + depfile_path = Path(options.output_dependencies).resolve() + depfile_name = depfile_path.name + depfile_stem = depfile_path.stem + + for fm, prefix in [ + (cpu_fm, ""), + (cpu_vec_fm, "cpu_vec_"), + (core_fm, "core_"), + (ops_fm, "ops_"), + ] + [(device_fm, f"{device}_") for device, device_fm in device_fms.items()]: + varname = prefix + depfile_stem + path = depfile_path.parent / (prefix + depfile_name) + fm.write_outputs(varname, str(path)) + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torchgen/gen_aoti_c_shim.py b/.venv/lib/python3.12/site-packages/torchgen/gen_aoti_c_shim.py new file mode 100644 index 0000000000000000000000000000000000000000..314229f9c03eae428427c243e6b63f43f3114fc7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/gen_aoti_c_shim.py @@ -0,0 +1,835 @@ +from __future__ import annotations + +import difflib +import os +import re +import textwrap +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from torchgen.aoti.fallback_ops import aten_shimified_ops, inductor_fallback_ops +from torchgen.api.types import DispatcherSignature +from torchgen.api.types.signatures import CppSignature, CppSignatureGroup +from torchgen.context import method_with_native_function +from torchgen.model import ( + Argument, + BackendIndex, + BaseTy, + BaseType, + DispatchKey, + FunctionSchema, + is_cuda_dispatch_key, + ListType, + NativeFunction, + NativeFunctionsGroup, + OperatorName, + OptionalType, + Type, + Variant, +) +from torchgen.utils import FileManager, mapMaybe + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +base_type_to_c_type = { + BaseTy.Tensor: "AtenTensorHandle", + BaseTy.bool: "int32_t", # Use int to pass bool + BaseTy.int: "int64_t", + BaseTy.SymInt: "int64_t", # Inductor-generated code won't see a SymInt + BaseTy.Scalar: "double", # Use double to pass both integer and floating point + BaseTy.float: "double", # TODO: how about other floating point types? + BaseTy.str: "const char*", + BaseTy.DeviceIndex: "int32_t", + BaseTy.Layout: "int32_t", # Represent enum as int + BaseTy.MemoryFormat: "int32_t", # Represent enum as int + BaseTy.ScalarType: "int32_t", # Represent enum as int + BaseTy.Generator: "AtenGeneratorHandle", +} + +base_type_to_aten_type = { + BaseTy.Tensor: "at::Tensor", + BaseTy.bool: "bool", + BaseTy.int: "int64_t", + BaseTy.SymInt: "c10::SymInt", + BaseTy.Scalar: "c10::Scalar", + BaseTy.float: "double", + BaseTy.str: "::std::string_view", + BaseTy.DeviceIndex: "c10::DeviceIndex", + BaseTy.Layout: "c10::Layout", + BaseTy.MemoryFormat: "c10::MemoryFormat", + BaseTy.ScalarType: "c10::ScalarType", + BaseTy.Generator: "at::Generator", +} + +base_type_to_callsite_expr = { + BaseTy.Tensor: "resolve_tensor_dispatch_flags", + BaseTy.bool: "", + BaseTy.int: "", + BaseTy.SymInt: "", + BaseTy.Scalar: "", + BaseTy.float: "", + BaseTy.str: "", + BaseTy.DeviceIndex: "static_cast", + BaseTy.Layout: "static_cast", + BaseTy.MemoryFormat: "static_cast", + BaseTy.ScalarType: "static_cast", + BaseTy.Generator: "*generator_handle_to_generator_pointer", +} + + +# convert args to C types, names in declarations, and expressions in function bodies +def convert_arg_type_and_name( + typ: Type, + name: str, + is_write: bool = False, +) -> tuple[list[str], list[str], list[str], list[str]]: + if isinstance(typ, BaseType): + if typ.name in base_type_to_c_type: + if typ.name == BaseTy.Tensor and is_write: + # For output tensors, our normal call to resolve_tensor_dispatch_flags + # results in an rvalue tensor, which can't be passed to at::Tensor&. + # Override this case specifically. + callsite_expr = [f"*tensor_handle_to_tensor_pointer({name})"] + else: + callsite_expr = [ + f"{base_type_to_callsite_expr[typ.name]}({name})" + if base_type_to_callsite_expr[typ.name] + else name + ] + + return ( + [base_type_to_c_type[typ.name]], + [name], + [base_type_to_aten_type[typ.name]], + callsite_expr, + ) + elif typ.name == BaseTy.Device: + return ( + ["int32_t", "int32_t"], + [name, name + "_index_"], + ["c10::Device"], + [ + f"c10::Device(static_cast({name}), static_cast({name}_index_))" + ], + ) + else: + raise NotImplementedError(f"TODO: add support for arg type {repr(typ)}") + elif isinstance(typ, OptionalType): + c_types, names, aten_types, callsite_exprs = convert_arg_type_and_name( + typ.elem, name + ) + j = 0 # index for names + new_aten_types = [] + new_callsite_exprs = [] + for aten_type in aten_types: + # Use pointer to denote optional type + c_types[j] = c_types[j] + "*" + if aten_type.startswith("c10::ArrayRef<"): + # ArrayRef is passed as pointer + size, but no need to add "*" to the size argument + new_aten_types.append(f"::std::optional<{aten_type}>") + base_type = aten_type[len("c10::ArrayRef<") : -1] + new_callsite_exprs.append( + f"pointer_to_optional_list<{base_type}>({names[j]}, {names[j + 1]})" + ) + j += 2 + elif aten_type == "c10::Device": + # Device is passed as device_type + device_index + new_aten_types.append("::std::optional") + new_callsite_exprs.append( + f"pointer_to_optional_device({names[j]}, {names[j + 1]})" + ) + j += 2 + elif aten_type == "at::Tensor": + new_aten_types.append(f"::std::optional<{aten_type}>") + new_callsite_exprs.append(f"resolve_tensor_dispatch_flags({names[j]})") + j += 1 + else: + new_aten_types.append(f"::std::optional<{aten_type}>") + new_callsite_exprs.append( + f"pointer_to_optional<{aten_type}>({names[j]})" + ) + j += 1 + + return ( + c_types, + names, + new_aten_types, + new_callsite_exprs, + ) + elif isinstance(typ, ListType): + # Need to explicitly pass the list as pointer + length + c_types, names, aten_types, _ = convert_arg_type_and_name(typ.elem, name) + if len(c_types) != 1: + raise AssertionError(f"ListType with unsupported element type {repr(typ)}") + + # The list content should never be modified + c_types[0] = f"const {c_types[0]}*" + c_types.append("int64_t") + name = names[0] + names.append(name + "_len_") + + atype = aten_types[0] + callsite_exprs = [] + if atype == "bool": + # no converter from std::vector to c10::ArrayRef + # construct std::array instead + if typ.size is None: + raise AssertionError("bool ListType must have a size") + callsite_exprs.append(f"pointer_to_list<{typ.size}>({name})") + elif atype == "at::Tensor" and not is_write: + callsite_exprs.append( + f"resolve_tensor_list_dispatch_flags({name}, {name}_len_)" + ) + elif atype == "::std::optional": + # convert from std::vector<::std::optional> to c10::List<::std::optional> + callsite_exprs.append( + f"c10::List<{atype}>(c10::ArrayRef<{atype}>(resolve_tensor_list_dispatch_flags({name}, {name}_len_)))" + ) + else: + callsite_exprs.append(f"pointer_to_list<{atype}>({name}, {name}_len_)") + + aten_types = [f"c10::ArrayRef<{t}>" for t in aten_types] + return ( + c_types, + names, + aten_types, + callsite_exprs, + ) + raise NotImplementedError(f"Argument type {repr(typ)} not supported!") + + +def zip_type_and_name(types: list[str], names: list[str]) -> list[str]: + return [typ + " " + name for typ, name in zip(types, names)] + + +# Generate argument declarations and callsite expressions +def gen_arguments( + flat_arguments: Sequence[Argument], skipped_args: set[str] +) -> tuple[list[str], list[str]]: + types: list[str] = [] + new_names: list[str] = [] + callsite_exprs: list[str] = [] + for arg in flat_arguments: + if arg.name in skipped_args: + # Pass the arg's schema default when available (e.g. "false" for + # a bool arg with default=False), so non-optional args with defaults + # can be versioned too. Fall back to std::nullopt for optional args + # with no default (matches historical behavior). + if arg.default is not None: + from torchgen.api.cpp import default_expr + + callsite_exprs.append(default_expr(arg.default, arg.type, symint=False)) + else: + callsite_exprs.append("std::nullopt") + continue + new_types, names, _, new_callsite_exprs = convert_arg_type_and_name( + arg.type, arg.name, arg.is_write + ) + types.extend(new_types) + new_names.extend(names) + callsite_exprs.extend(new_callsite_exprs) + return zip_type_and_name(types, new_names), callsite_exprs + + +# Return values are passed out as pointer arguments because all the C shim functions +# are expected to return AOTITorchError. +# Generate returns as declarations and callsite expressions +def gen_returns(schema: FunctionSchema) -> tuple[list[str], list[str]]: + types = [] + names = [] + for idx, ret in enumerate(schema.returns): + names.append(f"ret{idx}") + if isinstance(ret.type, BaseType) and ret.type.name in base_type_to_c_type: + types.append(base_type_to_c_type[ret.type.name] + "*") + else: + raise NotImplementedError( + f"TODO: add support for return type {repr(ret.type)}" + ) + + def convert_return(typ: BaseType, val: str) -> str: + if typ.name == BaseTy.Tensor: + return f"new_tensor_handle(std::move({val}))" + elif typ.name == BaseTy.SymInt: + return f"{val}.expect_int()" + elif typ.name == BaseTy.Scalar: + return f"{val}.toDouble()" + else: + return val + + ret_pointer_can_be_null = False + unambiguous_name = schema.name.unambiguous_name() + for name in ( + "_functional_sym_constrain_range", + "_scaled_dot_product_cudnn_attention", + "_scaled_dot_product_efficient_attention_backward", + "_scaled_dot_product_efficient_attention", + "_scaled_dot_product_flash_attention", + "_scaled_dot_product_fused_attention_overrideable", + "_thhn_fused_lstm_cell_backward_impl", + "convolution_backward", + "grid_sampler_2d_backward", + "grid_sampler_3d_backward", + "linear_backward", + ): + if name in unambiguous_name: + ret_pointer_can_be_null = True + break + + callsite_exprs: list[str] = [] + for idx, ret in enumerate(schema.returns): + tmp = "tmp_result" if len(names) == 1 else f"std::get<{idx}>(tmp_result)" + if not isinstance(ret.type, BaseType): + raise AssertionError(f"Expected BaseType for return, got {type(ret.type)}") + rval = convert_return(ret.type, tmp) + if ret_pointer_can_be_null: + callsite_exprs.append(f"if ({names[idx]}) {{ *{names[idx]} = {rval}; }}") + else: + callsite_exprs.append(f"*{names[idx]} = {rval};") + + return zip_type_and_name(types, names), callsite_exprs + + +# gen.py generates header first and then src, so caching the result here to avoid duplicate work +declaration_definition_cache: dict[tuple[str, str, str], tuple[str, str]] = {} + + +_TORCH_VERSION_PATTERN = re.compile(r"^TORCH_VERSION_\d+_\d+_\d+$") + + +def _get_earliest_torch_version_for_op_variant( + op_metadata: dict[str, str | dict[str, list[str] | str]], + op_version: int, +) -> str | None: + """ + Return the TORCH_VERSION_X_Y_Z macro string at which the given op variant became + available, or None if the variant is ungated. + + op_metadata contains the entry for an op in a dictionary like aten_shimified_ops + in torchgen/aoti/fallback_ops.py + + op_version is the integer extracted from a "vN" key in `op_metadata`. The base op + has op_version == 1 and reads from a top-level "since" key; later variants read + "since" from their own dict-form entry {"new_args": [...], "since": "..."}. + """ + if op_version == 1: + since = op_metadata.get("since") + else: + variant = op_metadata.get(f"v{op_version}") + since = variant.get("since") if isinstance(variant, dict) else None + if since is None: + return None + if not isinstance(since, str) or not _TORCH_VERSION_PATTERN.match(since): + raise AssertionError( + f"`since` value {since!r} is not of the form TORCH_VERSION_X_Y_Z" + ) + return since + + +def gen_declaration_and_definition( + schema: FunctionSchema, + device: str, + backend_call: str, + op_metadata: dict[str, str | dict[str, list[str] | str]], +) -> tuple[str, str]: + base_name = schema.name.unambiguous_name() + + global declaration_definition_cache + if (base_name, device, backend_call) in declaration_definition_cache: + return declaration_definition_cache[(base_name, device, backend_call)] + + # Check the validity of op_metadata. Each "vN" entry is a dict + # {"new_args": [...], "since": "TORCH_VERSION_X_Y_Z"} where "since" is optional; + # op_metadata may also carry a top-level "since" key that would version-gate v1. + indexed_op_metadata: dict[int, list[str]] = {1: []} + for ver_str, payload in sorted(op_metadata.items()): + # since will get processed later per op + if ver_str == "since": + continue + if not ver_str.startswith("v"): + raise AssertionError( + f"Version number for {base_name} is {ver_str}, not starting with 'v'" + ) + try: + ver_id = int(ver_str[1:]) + except ValueError as e: + raise AssertionError( + f"Version number for {base_name} is {ver_str}, not a valid integer after 'v'" + ) from e + if ver_id in indexed_op_metadata: + raise AssertionError(f"{ver_str} for {base_name} has already been defined") + if not isinstance(payload, dict): + raise AssertionError( + f"Variant {ver_str} for {base_name} must be a dict of the form " + "{'new_args': [...], 'since': 'TORCH_VERSION_X_Y_Z'}" + ) + new_args = payload.get("new_args", []) + if not isinstance(new_args, list): + raise AssertionError( + f"Variant {ver_str} for {base_name} has non-list 'new_args' field when a " + "list of arg names differing from prev versions is expected." + ) + indexed_op_metadata[ver_id] = new_args + + declarations: list[str] = [] + definitions: list[str] = [] + skipped_args: set[str] = set() + + for ver_id, new_args in sorted(indexed_op_metadata.items(), reverse=True): + # Iterate in the reverse order, so the latest version of an op will get generated first + # with all the arguments included, while a set of to-be-trimmed args is carried down + # to generate earlier version of the op. + func_name = base_name if ver_id == 1 else f"{base_name}_v{ver_id}" + if schema.is_out_fn(): + # out_variant has out arguments in the front, and it's ok to ignore return values + # because C shim functions only return AOTITorchError + args, callsite_exprs = gen_arguments( + [*schema.arguments.out, *schema.arguments.flat_non_out], skipped_args + ) + ret_assignments: list[str] = [] + else: + args, callsite_exprs = gen_arguments( + schema.arguments.flat_all, skipped_args + ) + # ignore return values for inplace ops + ret_declarations, ret_assignments = ( + ([], []) if schema.name.name.inplace else gen_returns(schema) + ) + args.extend(ret_declarations) + + declaration = textwrap.dedent( + f"AOTITorchError aoti_torch_{device}_{func_name}({', '.join(args)})" + ) + + tmp_result = "auto tmp_result = " if ret_assignments else "" + indent = "\t\t" + ret_assignments_str = ( + "\n".join(indent + r for r in ret_assignments) if ret_assignments else "" + ) + definition = ( + textwrap.dedent(f""" + {declaration} {{ + AOTI_TORCH_CONVERT_EXCEPTION_TO_ERROR_CODE({{ + {tmp_result}{backend_call}( + {", ".join(callsite_exprs)} + ); + """) + + ret_assignments_str + + textwrap.dedent(""" + }); + } + """) + ) + skipped_args.update(new_args) + decl = f"AOTI_TORCH_EXPORT {declaration};" + since = _get_earliest_torch_version_for_op_variant(op_metadata, ver_id) + if since is not None: + decl = ( + f"#if TORCH_FEATURE_VERSION >= {since}\n" + f"{decl}\n" + f"#endif // TORCH_FEATURE_VERSION >= {since}" + ) + declarations.append(decl) + definitions.append(definition) + + declaration_definition_cache[(base_name, device, backend_call)] = ( + "\n".join(declarations), + "\n".join(definitions), + ) + return declaration_definition_cache[(base_name, device, backend_call)] + + +def gen_static_dispatch_backend_call_signature(f: NativeFunction) -> CppSignature: + sig = DispatcherSignature.from_schema(f.func) + cpp_sigs = CppSignatureGroup.from_native_function( + f, method=False, fallback_binding=False + ) + if sig.symint and f.func.has_symint(): + cpp_sig = cpp_sigs.symint_signature + else: + cpp_sig = cpp_sigs.signature + if cpp_sig is None: + raise AssertionError(f"No cpp signature found for {f.func.name}") + return cpp_sig + + +def gen_static_dispatch_backend_call( + f: NativeFunction, + backend_index: BackendIndex | None = None, +) -> str: + sig = DispatcherSignature.from_schema(f.func) + cpp_sig = gen_static_dispatch_backend_call_signature(f) + + if backend_index is None: + # Check if this is a symint function and if the function only has method variants + if sig.symint and f.func.has_symint(): + has_function_variant = Variant.function in f.variants + + if not has_function_variant: + # Functions with both function and method variants can use the at::{*}_symint version + # (e.g., narrow -> at::narrow_symint), BUT + # Method-only functions with symint parameters should use at::symint:: namespace + # Remove the _symint suffix since at::symint:: namespace uses the base name + # (e.g., new_empty -> at::symint::new_empty) + base_name = cpp_sig.name() + base_name = base_name.removesuffix("_symint") # Remove "_symint" suffix + return f"at::symint::{base_name}" + + return f"at::{cpp_sig.name()}" + else: + return f"at::{backend_index.dispatch_key.lower()}::{cpp_sig.name()}" + + +def get_backend_index_for_aoti( + func: NativeFunction, + func_group_mapping: dict[OperatorName, NativeFunctionsGroup], + dispatch_key: DispatchKey | None, + backend_indices: dict[DispatchKey, BackendIndex], + extend_aoti_c_shim: bool, +) -> BackendIndex | None: + backend_index = None + + if dispatch_key is None: + return backend_index + + if backend_indices[dispatch_key].has_kernel(func) or ( + func.structured_delegate is not None + and func.structured_delegate in func_group_mapping + and backend_indices[dispatch_key].has_kernel( + func_group_mapping[func.structured_delegate] + ) + ): + backend_index = backend_indices[dispatch_key] + else: + # for the extend out-of-tree kernels, we don't need to + # duplicatly create C shim wrappers for other dispatch keys + if extend_aoti_c_shim: + return backend_index + + elif backend_indices[DispatchKey.CompositeExplicitAutograd].has_kernel(func): + # We need to create C shim wrappers for CompositeExplicitAutograd kernels + backend_index = backend_indices[DispatchKey.CompositeExplicitAutograd] + elif backend_indices[ + DispatchKey.CompositeExplicitAutogradNonFunctional + ].has_kernel(func): + # We need to create C shim wrappers for CompositeExplicitAutogradNonFunctional kernels + backend_index = backend_indices[ + DispatchKey.CompositeExplicitAutogradNonFunctional + ] + elif backend_indices[DispatchKey.CompositeImplicitAutograd].has_kernel(func): + backend_index = backend_indices[DispatchKey.CompositeImplicitAutograd] + + return backend_index + + +def get_header_for_aoti( + func: NativeFunction, + func_group_mapping: dict[OperatorName, NativeFunctionsGroup], + dispatch_key: DispatchKey | None, + backend_indices: dict[DispatchKey, BackendIndex], + extend_aoti_c_shim: bool, +) -> str | None: + backend_index = get_backend_index_for_aoti( + func, func_group_mapping, dispatch_key, backend_indices, extend_aoti_c_shim + ) + if backend_index is None: + if dispatch_key is None: + return f"#include " + return None + + return f"#include " + + +def get_fallback_op_name(func: NativeFunction) -> str: + return ( + f"{func.namespace}.{func.func.name.name}.{func.func.name.overload_name}" + if func.func.name.overload_name + else f"{func.namespace}.{func.func.name.name}.default" + ) + + +def gen_c_shim( + func: NativeFunction, + version_info: dict[str, str | dict[str, list[str] | str]], + func_group_mapping: dict[OperatorName, NativeFunctionsGroup], + dispatch_key: DispatchKey | None, + backend_indices: dict[DispatchKey, BackendIndex], + header: bool, + extend_aoti_c_shim: bool, +) -> str | None: + backend_index = get_backend_index_for_aoti( + func, func_group_mapping, dispatch_key, backend_indices, extend_aoti_c_shim + ) + if backend_index is None and dispatch_key is not None: + return None + + schema = func.func + device = "aten" if dispatch_key is None else dispatch_key.lower() + backend_call = gen_static_dispatch_backend_call( + func, + backend_index, + ) + + try: + if header: + declaration, _ = gen_declaration_and_definition( + schema, device, backend_call, version_info + ) + return declaration + else: + _, definition = gen_declaration_and_definition( + schema, device, backend_call, version_info + ) + return definition + + except NotImplementedError: + return None + + +@dataclass(frozen=True) +class ShimGenerator: + inductor_fallback_ops: dict[str, dict[str, str | dict[str, list[str] | str]]] + func_group_mapping: dict[OperatorName, NativeFunctionsGroup] + dispatch_key: DispatchKey | None + backend_indices: dict[DispatchKey, BackendIndex] + header: bool # True to generate .h and False to generate .cpp + extend_aoti_c_shim: bool + + @method_with_native_function + def __call__( + self, + func: NativeFunction, + ) -> str | None: + version_info = self.inductor_fallback_ops[get_fallback_op_name(func)] + result = gen_c_shim( + func, + version_info, + self.func_group_mapping, + self.dispatch_key, + self.backend_indices, + self.header, + self.extend_aoti_c_shim, + ) + return result + + +def gen_aoti_c_shim( + native_functions: Sequence[NativeFunction], + inductor_fallback_ops: dict[str, dict[str, str | dict[str, list[str] | str]]], + func_group_mapping: dict[OperatorName, NativeFunctionsGroup], + dispatch_key: DispatchKey | None, + backend_indices: dict[DispatchKey, BackendIndex], + header: bool, + extend_aoti_c_shim: bool, + includes: str = "", +) -> str: + body = "\n".join( + list( + mapMaybe( + ShimGenerator( + inductor_fallback_ops, + func_group_mapping, + dispatch_key, + backend_indices, + header, + extend_aoti_c_shim, + ), + native_functions, + ) + ) + ) + device = "aten" if dispatch_key is None else dispatch_key.lower() + include_device_functions = ( + "#include " + if dispatch_key is None + else f"#include " + ) + aten_warning = ( + ( + "\n\n// This file corresponds to the aten_shimified_ops list in torchgen/aoti/fallback_ops.py\n" + ) + if dispatch_key is None + else "" + ) + warning = """ + +// WARNING: THIS FILE IS AUTOGENERATED BY torchgen. DO NOT MODIFY BY HAND. +// See https://github.com/pytorch/pytorch/blob/7e86a7c0155295539996e0cf422883571126073e/torchgen/gen.py#L2424-L2436 for details""" + + if header: + return ( + warning + + aten_warning + + textwrap.dedent(""" + + #pragma once + + #include + + #ifdef __cplusplus + extern "C" { + #endif + + """) + + body + + textwrap.dedent(""" + + #ifdef __cplusplus + } // extern "C" + #endif + """) + ) + else: + return ( + warning + + aten_warning + + textwrap.dedent(f""" + + #include + #include + + #ifndef AT_PER_OPERATOR_HEADERS + {include_device_functions} + #include + #include + #include + #else + """) + + includes + + textwrap.dedent(""" + #endif // AT_PER_OPERATOR_HEADERS + + using namespace torch::aot_inductor; + + """) + + body + ) + + +def gen_aoti_c_shim_files( + aoti_fm: FileManager, + aoti_backends: set[DispatchKey | None], + native_functions: Sequence[NativeFunction], + backend_indices: dict[DispatchKey, BackendIndex], + structured_native_functions: Sequence[NativeFunctionsGroup], + extra_cuda_headers: str, + extend_aoti_c_shim: bool, + update_aoti_c_shim: bool, +) -> None: + structured_func_group_dict = {} + for func_group in structured_native_functions: + for func in func_group.functions(): + if func.structured_delegate is not None: + structured_func_group_dict[func.structured_delegate] = func_group + break + + for dispatch_key in aoti_backends: + # Use aten_shimified_ops for the aten backend, inductor_fallback_ops for others + fallback_ops_dict = ( + aten_shimified_ops if dispatch_key is None else inductor_fallback_ops + ) + fallbacks = {} + for func in native_functions: + op_name = get_fallback_op_name(func) + if op_name in fallback_ops_dict: + fallbacks[op_name] = func + fallback_native_functions = tuple( + value for _, value in sorted(fallbacks.items()) + ) + + # Use "aten" as the device name when dispatch_key is Generic + device_name = "aten" if dispatch_key is None else dispatch_key.lower() + + # header files were checked in for ABI-compatibility checking + header_file_name = f"c_shim_{device_name}.h" + new_header = gen_aoti_c_shim( + fallback_native_functions, + fallback_ops_dict, + structured_func_group_dict, + dispatch_key, + backend_indices, + header=True, + extend_aoti_c_shim=extend_aoti_c_shim, + includes="", + ) + if update_aoti_c_shim: + aoti_fm.write( + header_file_name, + lambda: new_header, + ) + else: + try: + with open( + os.path.join(aoti_fm.install_dir, header_file_name) + ) as old_file: + old_header = old_file.read() + + if old_header != new_header: + diff = "\n".join( + difflib.unified_diff( + old_header.splitlines(), + new_header.splitlines(), + fromfile="expected", + tofile="actual", + lineterm="", + ) + ) + + raise RuntimeError(f""" +The generated AOTInductor C shim header files have unexpectedly changed. This +indicates an AOTInductor fallback operator ABI backward compatibility breakage!!! +Only in a limited number of situations, this is allowed: + +1. You added a fallback op to the inductor_fallback_ops list in torchgen/aoti/fallback_ops.py. +If that's the case, run `python torchgen/gen.py --update-aoti-c-shim` to add a new entry to +existing C shim header files. + +2. You added a new default argument to an existing fallback op. This is clearly a BC breaking +change in the AOTInductor land. You need to annotate the new default argument in +torchgen/aoti/fallback_ops.py, and then run `python torchgen/gen.py --update-aoti-c-shim` to +update the C shim header files by creating different versions of the fallback op. See +https://github.com/pytorch/pytorch/pull/154848 as an example. + +{diff} + """) + except FileNotFoundError: + print( + f"{os.path.join(aoti_fm.install_dir, header_file_name)} not found" + ) + + # cpp files are always generated on-the-fly + def headers_for_aoti() -> str: + headers = [] + for func in fallback_native_functions: + header = get_header_for_aoti( + func, + structured_func_group_dict, + dispatch_key, + backend_indices, + extend_aoti_c_shim=extend_aoti_c_shim, + ) + if header is not None: + headers.append(header) + return "\n".join(sorted(set(headers))) + + extra_headers = ( + extra_cuda_headers + if dispatch_key is not None and is_cuda_dispatch_key(dispatch_key) + else "" + ) + + aoti_fm.write( + f"c_shim_{device_name}.cpp", + lambda: gen_aoti_c_shim( + fallback_native_functions, + fallback_ops_dict, + structured_func_group_dict, + dispatch_key, + backend_indices, + header=False, + extend_aoti_c_shim=extend_aoti_c_shim, + includes=headers_for_aoti() + "\n" + extra_headers, + ), + ) diff --git a/.venv/lib/python3.12/site-packages/torchgen/gen_backend_stubs.py b/.venv/lib/python3.12/site-packages/torchgen/gen_backend_stubs.py new file mode 100644 index 0000000000000000000000000000000000000000..efe63a80249eb4226001a686c65e59e47740c1aa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/gen_backend_stubs.py @@ -0,0 +1,635 @@ +from __future__ import annotations + +import argparse +import os +import re +from collections import Counter, defaultdict, namedtuple +from pathlib import Path +from typing import TYPE_CHECKING + +import yaml + +import torchgen.api.dispatcher as dispatcher +import torchgen.dest as dest +from torchgen.api.types import DispatcherSignature +from torchgen.code_template import CodeTemplate +from torchgen.context import native_function_manager +from torchgen.gen import get_grouped_native_functions, parse_native_yaml +from torchgen.model import ( + BackendIndex, + BackendMetadata, + DispatchKey, + NativeFunction, + NativeFunctionsGroup, + OperatorName, +) +from torchgen.selective_build.selector import SelectiveBuilder +from torchgen.utils import concatMap, context, FileManager, NamespaceHelper, Target +from torchgen.yaml_utils import YamlLoader + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +# Parses the external backend's yaml, and adds a new BackendIndex for the backend's dispatch key. +# Returns a Tuple of (backend_key, autograd_key, cpp_namespace, updated BackendIndex mapping) +ParsedExternalYaml = namedtuple( + "ParsedExternalYaml", + ["backend_key", "autograd_key", "class_name", "cpp_namespace", "backend_indices"], +) + + +def parse_backend_yaml( + backend_yaml_path: str, + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + backend_indices: dict[DispatchKey, BackendIndex], +) -> ParsedExternalYaml: + native_functions_map: dict[OperatorName, NativeFunction] = { + f.func.name: f + for f in concatMap( + lambda f: [f] if isinstance(f, NativeFunction) else list(f.functions()), + grouped_native_functions, + ) + } + + with open(backend_yaml_path) as f: + yaml_values = yaml.load(f, Loader=YamlLoader) + if not isinstance(yaml_values, dict): + raise AssertionError( + f"Expected yaml_values to be a dict, got {type(yaml_values)}" + ) + + valid_keys = [ + "backend", + "class_name", + "cpp_namespace", + "extra_headers", + "supported", + "autograd", + "full_codegen", + "non_native", + "ir_gen", + "symint", + ] + + backend = yaml_values.pop("backend", None) + if backend is None: + raise AssertionError('You must provide a value for "backend"') + + class_name = yaml_values.pop("class_name", None) + + cpp_namespace = yaml_values.pop("cpp_namespace", None) + if cpp_namespace is None: + raise AssertionError('You must provide a value for "cpp_namespace"') + + # Mostly just defaulting to false to stick with LazyTensor convention. + use_out_as_primary = yaml_values.pop("use_out_as_primary", False) + if not isinstance(use_out_as_primary, bool): + raise AssertionError( + f"You must provide either True or False for use_out_as_primary. Provided: {use_out_as_primary}" + ) + + use_device_guard = yaml_values.pop("device_guard", False) + if not isinstance(use_device_guard, bool): + raise AssertionError( + f"You must provide either True or False for device_guard. Provided: {use_device_guard}" + ) + + supported = yaml_values.pop("supported", []) + if supported is None: + supported = [] # Allow an empty list of supported ops + if not isinstance(supported, list): + raise AssertionError( + f'expected "supported" to be a list, but got: {supported} (of type {type(supported)})' + ) + + symint = yaml_values.pop("symint", []) + if symint is None: + symint = [] # Allow an empty list of symint ops + if not isinstance(symint, list): + raise AssertionError( + f'expected "symint" to be a list, but got: {symint} (of type {type(symint)})' + ) + symint_set = set(symint) + + supported_autograd = yaml_values.pop("autograd", []) + if not isinstance(supported_autograd, list): + raise AssertionError( + f'expected "autograd" to be a list, but got: {supported_autograd}' + ) + + # full_codegen is ignored by parse_backend_yaml, and re-parsed in gen_lazy_tensor.py + full_codegen = yaml_values.pop("full_codegen", []) + supported.extend(full_codegen) + + # non_native is ignored by parse_backend_yaml, and re-parsed in gen_lazy_tensor.py + yaml_values.pop("non_native", {}) + + # ir_gen is ignored by parse_backend_yaml, and re-parsed in gen_lazy_tensor.py + yaml_values.pop("ir_gen", {}) + + if len(yaml_values.keys()) != 0: + raise AssertionError( + f"{backend_yaml_path} contains unexpected keys: {', '.join(yaml_values.keys())}. " + f"Only the following keys are supported: {', '.join(valid_keys)}" + ) + + def create_backend_index( + backend_ops: list[str], + symint_ops: set[str], + dispatch_key: DispatchKey, + *, + use_out_as_primary: bool, + use_device_guard: bool, + ) -> BackendIndex: + metadata: dict[OperatorName, BackendMetadata] = {} + for op in backend_ops: + op_name = OperatorName.parse(op) + if op_name not in native_functions_map: + raise AssertionError(f"Found an invalid operator name: {op_name}") + # See Note [External Backends Follow Dispatcher API] + kernel_name = dispatcher.name(native_functions_map[op_name].func) + if op in symint_ops: + kernel_name += "_symint" + # TODO: allow structured external backends later. + m = BackendMetadata( + kernel=kernel_name, structured=False, cpp_namespace=cpp_namespace + ) + metadata[op_name] = m + return BackendIndex( + dispatch_key=dispatch_key, + use_out_as_primary=use_out_as_primary, + external=True, + device_guard=use_device_guard, + index=metadata, + ) + + backend_key: DispatchKey | None = None + if len(supported) > 0: + with context( + lambda: f'The provided value for "backend" must be a valid DispatchKey, but got {backend}.' + ): + backend_key = DispatchKey.parse(backend) + + backend_idx = create_backend_index( + supported, + symint_set, + backend_key, + use_out_as_primary=use_out_as_primary, + use_device_guard=use_device_guard, + ) + if backend_key in backend_indices: + raise AssertionError(f"Duplicate backend key: {backend_key}") + backend_indices[backend_key] = backend_idx + + autograd_key: DispatchKey | None = None + if len(supported_autograd) > 0: + with context( + lambda: f'The "autograd" key was specified, which indicates that you would like to override \ +the behavior of autograd for some operators on your backend. However "Autograd{backend}" is not a valid DispatchKey.' + ): + autograd_key = DispatchKey.parse(f"Autograd{backend}") + + autograd_idx = create_backend_index( + supported_autograd, + symint_set, + autograd_key, + use_out_as_primary=use_out_as_primary, + use_device_guard=use_device_guard, + ) + if autograd_key in backend_indices: + raise AssertionError(f"Duplicate autograd key: {autograd_key}") + backend_indices[autograd_key] = autograd_idx + + for g in grouped_native_functions: + if isinstance(g, NativeFunction): + forward_kernels = ( + [] + if backend_key is None + else [ + m + for m in [backend_indices[backend_key].get_kernel(g)] + if m is not None + ] + ) + backward_kernels = ( + [] + if autograd_key is None + else [ + m + for m in [backend_indices[autograd_key].get_kernel(g)] + if m is not None + ] + ) + else: + forward_kernels = ( + [] + if backend_key is None + else [ + m + for m in [ + backend_indices[backend_key].get_kernel(f) + for f in g.functions() + ] + if m is not None + ] + ) + backward_kernels = ( + [] + if autograd_key is None + else [ + m + for m in [ + backend_indices[autograd_key].get_kernel(f) + for f in g.functions() + ] + if m is not None + ] + ) + + forward_kernels = [f for f in forward_kernels if f is not None] + backward_kernels = [f for f in backward_kernels if f is not None] + if not (len(forward_kernels) == 0 or len(backward_kernels) == 0): + raise AssertionError( + f"Currently, all variants of an op must either be registered to a backend key, " + f"or to a backend's autograd key. They cannot be mix and matched. " + f"If this is something you need, feel free to create an issue! " + f'{forward_kernels[0].kernel} is listed under "supported", ' + f'but {backward_kernels[0].kernel} is listed under "autograd".' + ) + + return ParsedExternalYaml( + backend_key, autograd_key, class_name, cpp_namespace, backend_indices + ) + + +def error_on_missing_kernels( + native_functions: Sequence[NativeFunction], + backend_indices: dict[DispatchKey, BackendIndex], + backend_key: DispatchKey, + autograd_key: DispatchKey | None, + class_name: str, + kernel_defn_file_path: str, + full_codegen: list[OperatorName] | None = None, +) -> None: + try: + with open(kernel_defn_file_path) as f: + backend_defns = f.read() + except OSError as e: + raise AssertionError( + f"Unable to read from the specified impl_path file: {kernel_defn_file_path}" + ) from e + + if full_codegen is None: + full_codegen = [] + + indices = [backend_indices[backend_key].index] + ( + [] if autograd_key is None else [backend_indices[autograd_key].index] + ) + # Quick mapping from each OperatorName used by the external backend + # to its backend kernel name + expected_backend_op_names: dict[OperatorName, str] = dict( + list( + concatMap( + lambda index: [ + (op_name, metadata.kernel) for op_name, metadata in index.items() + ], + indices, + ) + ) + ) + expected_backend_native_funcs: list[NativeFunction] = [ + f + for f in native_functions + if f.func.name in expected_backend_op_names and f.func.name not in full_codegen + ] + expected_backend_kernel_name_counts: dict[str, list[NativeFunction]] = defaultdict( + list + ) + for native_f in expected_backend_native_funcs: + expected_backend_kernel_name_counts[ + expected_backend_op_names[native_f.func.name] + ].append(native_f) + + # This just looks for lines containing "foo(", and assumes that the kernel foo has been implemented. + # It might cause false negatives (we won't catch all cases), but that's ok - if we catch a missing kernel + # here, then we get a nicer error message. If we miss it, you get a linker error. + kernel_defn_regex = rf"(.*){class_name}::\s*([\w\d]*)\(" + actual_backend_kernel_name_counts = Counter( + # A bit unwieldy (this could probably be moved into regex), + # but we don't want to include kernel names that come from function calls, + # like "return torch_xla::XLANativeFunctions::empty_strided_symint(...)". + # Easy check is to ignore any lines with colons before the class name. + [ + y + for (x, y) in re.findall(kernel_defn_regex, backend_defns) + if not x.endswith(":") + ] + ) + + missing_kernels_err_msg = "" + for expected_name, funcs in expected_backend_kernel_name_counts.items(): + expected_overload_count = len(funcs) + actual_overload_count = actual_backend_kernel_name_counts[expected_name] + if expected_overload_count != actual_overload_count: + + def create_decl(f: NativeFunction) -> str: + with native_function_manager(f): + return DispatcherSignature.from_schema(f.func).decl() + + expected_schemas_str = "\n".join([create_decl(f) for f in funcs]) + missing_kernels_err_msg += f""" +{class_name} is missing a kernel definition for {expected_name}. We found {actual_overload_count} kernel(s) with that name, +but expected {expected_overload_count} kernel(s). The expected function schemas for the missing operator are: +{expected_schemas_str} + +""" + if missing_kernels_err_msg != "": + raise AssertionError(missing_kernels_err_msg) + + +def main() -> None: + parser = argparse.ArgumentParser(description="Generate backend stub files") + parser.add_argument( + "-s", + "--source-yaml", + "--source_yaml", + help="path to source yaml file containing operator external definitions", + ) + parser.add_argument("-o", "--output-dir", "--output_dir", help="output directory") + parser.add_argument( + "--dry-run", "--dry_run", type=bool, default=False, help="output directory" + ) + parser.add_argument( + "--impl-path", + "--impl_path", + type=str, + default=None, + help="path to the source C++ file containing kernel definitions", + ) + options = parser.parse_args() + + run(options.source_yaml, options.output_dir, options.dry_run, options.impl_path) + + +def gen_dispatchkey_nativefunc_headers( + fm: FileManager, + class_name: str, + cpp_namespace: str, + backend_indices: dict[DispatchKey, BackendIndex], + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + backend_dispatch_key: DispatchKey, + autograd_dispatch_key: DispatchKey | None, + backend_name: str = "", +) -> None: + if class_name is None: + raise AssertionError("class_name must not be None") + generated_comment = ( + "Autogenerated file by gen_backend_stubs.py. Do not edit directly!" + ) + + # Convert to a set first to remove duplicate kernel names. + # Backends are allowed to repeat kernel names; only generate the declaration once! + # Sort for deterministic output. + backend_declarations = sorted( + set( + concatMap( + lambda f: dest.compute_native_function_declaration( + f, backend_indices[backend_dispatch_key] + ), + grouped_native_functions, + ) + ) + ) + autograd_declarations = sorted( + set( + concatMap( + lambda f: [] + if autograd_dispatch_key is None + else dest.compute_native_function_declaration( + f, backend_indices[autograd_dispatch_key] + ), + grouped_native_functions, + ) + ) + ) + + ns_helper = NamespaceHelper(cpp_namespace) + fm.write_with_template( + f"{backend_dispatch_key}NativeFunctions.h", + "DispatchKeyNativeFunctions.h", + lambda: { + "generated_comment": generated_comment, + "namespace_prologue": ns_helper.prologue, + "class_name": class_name, + "namespace_epilogue": ns_helper.epilogue, + "dispatch_declarations": backend_declarations + autograd_declarations, + "BackendName": backend_name, + "DispatchKey": backend_dispatch_key, + }, + ) + + +def gen_dispatcher_registrations( + fm: FileManager, + output_dir: str, + class_name: str, + backend_indices: dict[DispatchKey, BackendIndex], + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], + backend_dispatch_key: DispatchKey, + dispatch_key: DispatchKey, + selector: SelectiveBuilder, + # build_in_tree is true for lazy TS backend and affects include paths, not used for external backends + build_in_tree: bool = False, + per_operator_headers: bool = False, + backend_name: str = "", + eager_registration: bool = True, +) -> None: + headers = [ + f"{output_dir}/{backend_dispatch_key}NativeFunctions.h", + ] + if build_in_tree: + external_backend_headers_str = "\n".join(f"#include <{h}>" for h in headers) + else: + external_backend_headers_str = "\n".join(f'#include "{h}"' for h in headers) + + if class_name is None: + raise AssertionError("class_name must not be None") + backend_index = backend_indices[dispatch_key] + + dispatch_registrations_body = list( + concatMap( + dest.RegisterDispatchKey( + backend_index, + Target.REGISTRATION, + selector, + rocm=False, + symint=True, + class_method_name=f"{class_name}", + skip_dispatcher_op_registration=False, + ), + grouped_native_functions, + ) + ) + newline = "\n" + ns_helper = NamespaceHelper(namespace_str="at") + deferred_dispatch_registrations = "" + static_init_dispatch_registrations = "" + if eager_registration: + static_template = CodeTemplate( + """\ +TORCH_LIBRARY_IMPL(aten, $dispatch_key, m) { + $dispatch_registrations_body +}""" + ) + static_init_dispatch_registrations = static_template.substitute( + dispatch_key=dispatch_key, + dispatch_registrations_body=dispatch_registrations_body, + ) + else: + deferred_template = CodeTemplate( + """\ +TORCH_API void Register${backend_name}${dispatch_key}NativeFunctions(); +TORCH_API void Register${backend_name}${dispatch_key}NativeFunctions() { + static auto m = MAKE_TORCH_LIBRARY_IMPL(aten, $dispatch_key); + $dispatch_registrations_body +}""" + ) + deferred_dispatch_registrations = deferred_template.substitute( + backend_name=backend_name, + dispatch_key=dispatch_key, + dispatch_registrations_body=dispatch_registrations_body, + ) + + fm.write_with_template( + f"Register{dispatch_key}.cpp", + "RegisterDispatchKey.cpp", + lambda: { + "extra_cuda_headers": "", + "external_backend_headers": external_backend_headers_str, + "ops_headers": "#include " + if not per_operator_headers + else "", + "DispatchKey": dispatch_key, + "dispatch_namespace": dispatch_key.lower(), + "dispatch_headers": dest.gen_registration_headers( + backend_index, per_operator_headers=per_operator_headers, rocm=False + ), + "dispatch_helpers": dest.gen_registration_helpers(backend_index), + "dispatch_definitions": fm.substitute_with_template( + "RegisterDispatchDefinitions.ini", + lambda: { + "ns_prologue": ns_helper.prologue, + "ns_epilogue": ns_helper.epilogue, + "static_init_dispatch_registrations": static_init_dispatch_registrations, + "deferred_dispatch_registrations": deferred_dispatch_registrations, + "dispatch_namespace": dispatch_key.lower(), + "dispatch_namespaced_definitions": "", + "dispatch_anonymous_definitions": list( + concatMap( + dest.RegisterDispatchKey( + backend_index, + Target.ANONYMOUS_DEFINITION, + selector, + rocm=False, + symint=True, + class_method_name=f"{class_name}", + skip_dispatcher_op_registration=False, + ), + grouped_native_functions, + ) + ), + }, + ).split(newline), + }, + ) + + +def run( + source_yaml: str, output_dir: str, dry_run: bool, impl_path: str | None = None +) -> None: + # Assumes that this file lives at torchgen/gen_backend_stubs.py + root = Path(__file__).absolute().parent.parent + common_dir = os.path.join(root, "aten/src") # Assumes root is pytorch_root + if not os.path.exists(common_dir): # This file is out-of-tree. + common_dir = os.path.join(root, "torchgen/packaged") + + template_dir = os.path.join(common_dir, "ATen/templates") + + def make_file_manager(install_dir: str) -> FileManager: + return FileManager( + install_dir=install_dir, template_dir=template_dir, dry_run=dry_run + ) + + fm = make_file_manager(output_dir) + + native_yaml_path = os.path.join(common_dir, "ATen/native/native_functions.yaml") + tags_yaml_path = os.path.join(common_dir, "ATen/native/tags.yaml") + parsed_yaml = parse_native_yaml(native_yaml_path, tags_yaml_path) + native_functions, backend_indices = ( + parsed_yaml.native_functions, + parsed_yaml.backend_indices, + ) + grouped_native_functions = get_grouped_native_functions(native_functions) + parsed_backend_yaml = parse_backend_yaml( + source_yaml, grouped_native_functions, backend_indices + ) + backend_key = parsed_backend_yaml.backend_key + autograd_key = parsed_backend_yaml.autograd_key + cpp_namespace = parsed_backend_yaml.cpp_namespace + class_name = parsed_backend_yaml.class_name + backend_indices = parsed_backend_yaml.backend_indices + + selector = SelectiveBuilder.get_nop_selector() + + if backend_key is None: + # This could be useful if a backend wants to quickly set up a noop yaml file but doesn't have any kernels ready yet. + return + + if class_name is None: + # class_name is an optional argument to backend yaml file. + # if specified it allows an external backend to override + # the name of the class that all generated kernel definitions live under. + # if not specified, its value is given as native_function_class_name. + class_name = backend_indices[backend_key].native_function_class_name() + if class_name is None: + raise AssertionError("class_name must not be None") + + if impl_path is not None: + error_on_missing_kernels( + native_functions, + backend_indices, + backend_key, + autograd_key, + class_name, + impl_path, + ) + + gen_dispatchkey_nativefunc_headers( + fm, + class_name, + cpp_namespace, + backend_indices, + grouped_native_functions, + backend_key, + autograd_key, + ) + + for dispatch_key in ( + [backend_key] if autograd_key is None else [backend_key, autograd_key] + ): + gen_dispatcher_registrations( + fm, + output_dir, + class_name, + backend_indices, + grouped_native_functions, + backend_key, + dispatch_key, + selector, + ) + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torchgen/gen_functionalization_type.py b/.venv/lib/python3.12/site-packages/torchgen/gen_functionalization_type.py new file mode 100644 index 0000000000000000000000000000000000000000..800ec6aa1703d9faa429794e842e14d064fb3d33 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/gen_functionalization_type.py @@ -0,0 +1,1219 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from torchgen.api import cpp, dispatcher, functionalization +from torchgen.api.translate import translate +from torchgen.api.types import ( + BaseCType, + Binding, + CType, + DispatcherSignature, + iTensorListRefT, + NativeSignature, + OptionalCType, + optionalSymIntArrayRefT, + symIntArrayRefT, + SymIntT, + tensorListT, + tensorT, + VectorCType, + ViewInverseSignature, +) +from torchgen.context import ( + method_with_native_function, + native_function_manager, + with_native_function, + with_native_function_and, +) +from torchgen.model import ( + Argument, + BackendIndex, + BaseTy, + BaseType, + FunctionSchema, + ListType, + NativeFunction, + NativeFunctionsGroup, + NativeFunctionsViewGroup, + OperatorName, + Return, + SchemaKind, + SelfArgument, + TensorOptionsArguments, +) +from torchgen.native_function_generation import ( + INPLACE_OPS_THAT_DONT_GET_GROUPED_PROPERLY, + MUTABLE_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT, + OUT_OPS_THAT_DONT_GET_GROUPED_PROPERLY, +) +from torchgen.utils import concatMap, dataclass_repr, FileManager + + +if TYPE_CHECKING: + from collections.abc import Callable + + from torchgen.selective_build.selector import SelectiveBuilder + + +# Note: [Mutable Ops Not Using Functionalization] +# Ops in this list currently do not work with functionalization and should be fixed. +MUTABLE_OPS_NOT_USING_FUNCTIONALIZATION = ( + OUT_OPS_THAT_DONT_GET_GROUPED_PROPERLY + + MUTABLE_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT + + INPLACE_OPS_THAT_DONT_GET_GROUPED_PROPERLY + + [ + # It will be BC-breaking, but we should fix their schemas. + # should be inplace? + "record_stream", + # See Note [resize_ in Functionalization] + "resize_", + "resize_as_", + # This function is used as for testing purposes only. + "_fill_mem_eff_dropout_mask_", + # Inference-only op called behind a custom op graph break. + "_flash_attention_forward_no_dropout_inplace", + ] +) + +# Eager cumulative out variants compute in the out dtype when dtype is omitted. +# Functionalization normally lowers mutable ops through their functional variants, +# so these need to thread the out dtype explicitly to preserve eager semantics. +CUMULATIVE_OUT_OPS_PRESERVING_OUT_DTYPE = { + OperatorName.parse("cumsum.out"), + OperatorName.parse("cumprod.out"), +} + +# This file contains codegen that relates to the functionalization pass. +# It includes: +# - gen_functionalization_definition +# Generates dispatcher kernel definitions for the functionalization pass. +# - gen_functionalization_registration +# Generates dispatcher kernel registrations for the functionalization pass. +# - gen_functionalization_view_inverse_declaration +# Generates a declaration for an "inverse view", for every view op +# that is needed in functionalization. We manually implement their definitions. +# - gen_composite_view_copy_kernel +# Generates view_copy() composite kernels for all view_copy operators. + + +# Generates the body of the default composite C++ kernel for a {view}_copy NativeFunction +# See Note [view_copy NativeFunctions] +@dataclass(frozen=True) +class GenCompositeViewCopyKernel: + backend_index: BackendIndex + + @method_with_native_function + def __call__(self, g: NativeFunctionsViewGroup) -> str | None: + if g.view_copy is None: + return None + elif g.view_copy.func.name.name.base != f"{g.view.func.name.name}_copy": + # If the view_copy doesn't match the standard naming scheme of _copy, + # assume it already exists and doesn't need to be generated. + # Example: slice_inverse() with the copy variant named slice_scatter() + # instead of slice_inverse_copy() + return None + + metadata = self.backend_index.get_kernel(g.view_copy) + if metadata is None: + raise AssertionError( + f"Expected metadata for view_copy kernel: {g.view_copy}" + ) + + # We can make view_copy work in more cases by using reshape() + # when a normal view call would ordinarily fail. + # This also makes LTC more efficient, because they don't need to include + # clone() calls in their graph (which is normally needed by reshape). + if str(g.view_copy.func.name) == "view_copy": + if metadata.kernel != "view_copy_symint": + raise AssertionError( + f"Expected kernel 'view_copy_symint', got '{metadata.kernel}'" + ) + return """\ +at::Tensor view_copy_symint(const at::Tensor & self, at::SymIntArrayRef size) { + c10::SymDimVector shape = infer_size_dv(size, self.sym_numel()); + if (!at::detail::computeStride(self.sym_sizes(), self.sym_strides(), shape).has_value()) { + return self.reshape_symint(size); + } else { + auto output = at::_ops::view::call(self, size); + return output.clone(/*memory_format=*/at::MemoryFormat::Contiguous); + } +} +""" + # view_copy is a native signature, since we're generating an at::native:: kernel + # Functionalization always operates on symints though + view_copy_sig = NativeSignature( + g.view_copy.func, symint=metadata.supports_symint() + ) + + # view is a dispatcher signature, since we're calling into the at::_ops API + view_sig = DispatcherSignature(g.view.func) + + view_api_name = g.view.func.name.unambiguous_name() + exprs = ", ".join( + [e.expr for e in translate(view_copy_sig.arguments(), view_sig.arguments())] + ) + + # view ops today always return either a Tensor or a list of Tensors + if len(g.view.func.returns) != 1: + raise AssertionError(f"Expected 1 return, got {len(g.view.func.returns)}") + if not ( + g.view.func.returns[0].type == BaseType(BaseTy.Tensor) + or g.view.func.returns[0].type == ListType(BaseType(BaseTy.Tensor), None) + ): + raise AssertionError( + f"Expected Tensor or Tensor[] return type, got {g.view.func.returns[0].type}" + ) + + if g.view.func.returns[0].type == BaseType(BaseTy.Tensor): + return_cloned_output = """\ + return output.clone(/*memory_format=*/at::MemoryFormat::Contiguous);""" + else: + # If the return type is a list, we need to clone each tensor in the list. + return_cloned_output = f"""\ + {view_copy_sig.returns_type().cpp_type()} out_clone; + for (const auto i : c10::irange(output.size())) {{ + out_clone.push_back(output[i].clone(/*memory_format=*/at::MemoryFormat::Contiguous)); + }} + return out_clone;""" + + # The default generated composite kernel for {view}_copy() operators just clones + # the input tensor, and runs the underlying view on the clone. + return f""" +{view_copy_sig.defn(name=metadata.kernel)} {{ + auto output = at::_ops::{view_api_name}::call({exprs}); + {return_cloned_output} +}} +""" + + +def return_str(rets: tuple[Return, ...], names: list[str]) -> str: + if len(rets) != len(names): + raise AssertionError(f"Expected {len(rets)} names, got {len(names)}") + if len(rets) == 0: + return "" + elif len(rets) == 1: + return f"return {names[0]};" + else: + return f"return {dispatcher.returns_type(rets).cpp_type()}({', '.join(names)});" + + +def modifies_arguments(f: NativeFunction) -> bool: + return any( + a.annotation is not None and a.annotation.is_write + for a in f.func.arguments.flat_all + ) + + +def wrapper_name(func: FunctionSchema) -> str: + if func.name.overload_name: + return f"{cpp.name(func)}_{func.name.overload_name}" + else: + return cpp.name(func) + + +def is_tensor_like(a: Argument | TensorOptionsArguments | SelfArgument) -> bool: + return isinstance(a, SelfArgument) or ( + isinstance(a, Argument) and a.type.is_tensor_like() + ) + + +# We need to wrap / unwrap various arguments from the op in the functionalization kernels. +# Some op schemas include non-owning types though (like TensorList), +# and when we unwrap them we expect to get out an owning type!. +# We also return a lambda that tells you how to convert the non-owning type argument into the owning type. +def get_owning_type(t: CType) -> tuple[CType, Callable[[str], str]]: + if t == BaseCType(tensorListT): + return VectorCType(BaseCType(tensorT)), lambda x: f"{x}.vec()" + if t == BaseCType(iTensorListRefT): + return VectorCType(BaseCType(tensorT)), lambda x: f"{{{x}.begin(), {x}.end()}}" + # There are technically other non-owning types out there (like IntArrayRef), + # but functionalization only actually cares about the ones involving tensors. + return t, lambda x: x + + +# unwraps all tensor-like arguments, returning: +# (1) a string containing all of the logic that does the unwrapping +# (2) a context, to be used by translate(), with all of the relevant bindings. +def unwrap_tensor_args( + sig: DispatcherSignature, *, is_view_op: bool +) -> tuple[str, list[Binding]]: + context: list[Binding] = [] + unwrapped_tensor_args: list[str] = [] + for arg in sig.arguments(): + if is_tensor_like(arg.argument): + # for tensor inputs, we want to unwrap them before passing them into the redispatch calls. + unwrapped_name = f"{arg.name}_" + # For most ops, the functionalization needs to sync any pending updates on the input tensors + # before calling the operator, since otherwise the operator will act on stale data. + # For view ops though, we can continue to defer syncing until the tensor is used by + # a non-view operator. + maybe_sync_input = ( + "" if is_view_op else f"at::functionalization::impl::sync({arg.name});" + ) + unwrapped_type, conversion_fn = get_owning_type( + arg.nctype.remove_const_ref().type + ) + unwrapped_tensor_args.append( + f""" + {unwrapped_type.cpp_type()} {unwrapped_name}; + if (at::functionalization::impl::isFunctionalTensor({arg.name})) {{ + {maybe_sync_input} + {unwrapped_name} = at::functionalization::impl::from_functional_tensor({arg.name}); + }} else {{ + {unwrapped_name} = {conversion_fn(arg.name)}; + }}""" + ) + context.append(arg.with_name(unwrapped_name)) + else: + # for non-tensor inputs, we want to pass them directly into the redispatch calls. + context.append(arg) + unwrap_tensor_args_str = "\n ".join(unwrapped_tensor_args) + return unwrap_tensor_args_str, context + + +# converts all tensor-like arguments to meta tensors, which are used to compute stride info. Returns: +# (1) a string containing all of the logic that does the conversions. +# (2) a context, to be used by translate(), with all of the relevant bindings. +def convert_to_meta_tensors(sig: DispatcherSignature) -> tuple[str, list[Binding]]: + context: list[Binding] = [] + unwrapped_tensor_args: list[str] = [] + for arg in sig.arguments(): + if is_tensor_like(arg.argument): + # for tensor inputs, we want to unwrap them before passing them into the redispatch calls. + a_ = arg.name + unwrapped_name = f"{arg.name}_meta" + unwrapped_tensor_args.append(f"auto {unwrapped_name} = to_meta({a_});") + context.append(arg.with_name(unwrapped_name)) + else: + # for non-tensor inputs, we want to pass them directly into the redispatch calls. + context.append(arg) + unwrap_tensor_args_str = "\n ".join(unwrapped_tensor_args) + return unwrap_tensor_args_str, context + + +# The functionalization codegen currently expects view op schemas to have this form: +# foo(Tensor(a), ...) -> Tensor(a) (e.g. transpose) +# foo(Tensor(a!), ...) -> Tensor(a!) (e.g. transpose_) +def assert_view_op_properties(func: FunctionSchema) -> None: + def is_alias(a: Argument) -> bool: + return a.annotation is not None + + args = func.arguments.flat_non_out + # The first argument is a tensor with an alias semantics (annotations) + if not (len(args) > 0 and args[0].type == BaseType(BaseTy.Tensor)): + raise AssertionError( + f"In the functionalization codegen, we expect the first argument of every view operator to be a tensor, " + f"but found an argument of type {str(args[0].type)} for operator: {str(func.name)}." + ) + # No other arguments have aliasing semantics + if not (is_alias(args[0]) and not any(is_alias(a) for a in args[1:])): + raise AssertionError( + "In the functionalization codegen, we expect the first argument of every view " + "operator to alias the output. View operators with multiple aliasing inputs " + "aren't supported yet. Found an operator that doesn't satisfy this constraint" + ) + + +# One-liner expression for checking if an expression expr of type type has any +# symbolic values. +def emit_expr_has_symbolic_values(expr: str, type: CType) -> str: + if type == BaseCType(SymIntT): + return f"{expr}.is_symbolic()" + + if isinstance(type, OptionalCType): + innerexpr = f"(*{expr})" + return f"{expr}.has_value() ? {emit_expr_has_symbolic_values(innerexpr, type.elem)} : false" + + if type == BaseCType(optionalSymIntArrayRefT): + return emit_expr_has_symbolic_values( + expr, OptionalCType(BaseCType(symIntArrayRefT)) + ) + + if type in (BaseCType(symIntArrayRefT), VectorCType(BaseCType(SymIntT))): + argname = "arg" + lambda_check = emit_expr_has_symbolic_values(argname, BaseCType(SymIntT)) + return ( + "std::any_of(" + f"{expr}.begin(), {expr}.end(), " + f"[=](auto& {argname}) {{ return {lambda_check}; }})" + ) + + raise ValueError( + "unsupported type for has_symbolic_values check. " + "It should be a SymInt or a collection of those. " + f"Got: {type.cpp_type()}" + ) + + +# Detects whether any of the SymInt arguments are, in fact, symbolic values. +# This is used in the constructor of ViewMeta. +def emit_has_symbolic_inputs(sig: DispatcherSignature) -> str: + name = "has_symbolic_inputs" + statements = [ + f"{name} = {name} | ({emit_expr_has_symbolic_values(binding.name, binding.nctype.type)});" + for binding in sig.arguments() + if ( + isinstance(binding.argument, Argument) + and binding.argument.type.is_symint_like() + ) + ] + body = "\n ".join(statements) + return f""" + bool {name} = false; + {body}""" + + +# Generates the Functionalization kernel for: +# - ops that create aliases (e.g. transpose()) +# - ops that are views AND mutations (e.g. transpose_()) +def emit_view_functionalization_body( + g: NativeFunctionsViewGroup, *, view_inplace: bool +) -> str: + if view_inplace: + # This op is both an inplace op AND a view op. + # See Note [Functionalization Pass - Inplace View Ops] for details. + # I currently have the view meta call into the out-of-place variant of the view, to avoid + # having to define an extra ~20 inplace {view}_inverse_ functions. + # Most view ops don't have NativeFunctionGroup's both, because we don't define out= variants for view ops. + # I'm assuming that every inplace-view op has a corresponding out-of-place view op, + # with the same name but the trailing underscore removed. + # This is currently asserted at parse time in gen.py (see error_check_native_functions). + if g.view_inplace is None: + raise AssertionError( + "Expected view_inplace to be non-None for inplace view" + ) + f = g.view_inplace + else: + f = g.view + + if g.view_copy is None: + raise AssertionError("Expected view_copy to be non-None") + with native_function_manager(f): + call_sig = DispatcherSignature.from_schema(g.view_copy.func) + + spec = ViewMetaSpecialization(g, f=f) + + # the "view_copy" op name that the functionalization kernels need to call + api_name = g.view_copy.func.name.unambiguous_name() + # Sometimes the functionalization pass needs to no-op (e.g. if it was passed non-functional tensors) + # "no-op"ing in this context is just redispatching to the original op. + noop_api_name = f.func.name.unambiguous_name() + + dispatcher_sig = DispatcherSignature.from_schema(f.func) + assert_view_op_properties(f.func) + view_tensor_name = dispatcher_sig.arguments()[0].name + + return_type = dispatcher_sig.returns_type().remove_const_ref().cpp_type() + + unwrap_tensor_args_str, unwrapped_args_ctx = unwrap_tensor_args( + dispatcher_sig, is_view_op=True + ) + view_redispatch_args = [ + e.expr + for e in translate(unwrapped_args_ctx, call_sig.arguments(), method=False) + ] + + # The meta API call should use the same arguments, but convert all tensors to meta tensors first. + meta_conversion_str, meta_call_ctx = convert_to_meta_tensors(dispatcher_sig) + meta_call_args = [ + e.expr for e in translate(meta_call_ctx, call_sig.arguments(), method=False) + ] + + symbolic_inputs_check = emit_has_symbolic_inputs(call_sig) + + if "inplace_view" in f.tags: + # See Note [Functionalization Pass - Inplace View Ops] for more details + return f""" + {dispatcher_sig.defn(name=wrapper_name(f.func), is_redispatching_fn=True)} {{ + if (!at::functionalization::impl::isFunctionalTensor({view_tensor_name})) {{ + // functionalization is re-entrant, but will no-op if it wasn't passed a FunctionalTensorWrapper. + {unwrap_tensor_args_str} + at::AutoDispatchSkipFunctionalize guard; + return at::_ops::{noop_api_name}::call({", ".join(view_redispatch_args)}); + }} + auto reapply_views = at::functionalization::impl::getFunctionalizationReapplyViewsTLS(); + auto inverse_return_mode = ( + reapply_views ? at::functionalization::InverseReturnMode::ViewOrScatterInverse + : at::functionalization::InverseReturnMode::NeverView + ); + {symbolic_inputs_check} + auto view_meta = {spec.new()}; + auto compute_reference_meta = + {view_tensor_name}.key_set().has_backend(c10::BackendComponent::XLABit) || + {view_tensor_name}.key_set().has_backend(c10::BackendComponent::LazyBit); + {return_type} reference_tensor_output; + if (compute_reference_meta && !disable_meta_reference()) {{ + {meta_conversion_str} + at::AutoDispatchSkipFunctionalize func_guard; + c10::impl::ExcludeDispatchKeyGuard guard(exclude_keys_for_meta_dispatch); + reference_tensor_output = at::_ops::{noop_api_name}::call({", ".join(meta_call_args)}); + }} + // This function adds the above view meta to the current tensor and replays them off the base, + // mutating the size/stride info of the current FunctionalTensorWrapper. + // Because of this, we need to make sure to run the reference shape function above, + // BEFORE doing this (otherwise we'll end up running the reference function using the wrong sizes/strides) + at::functionalization::impl::mutate_view_meta({view_tensor_name}, view_meta); + // See Note [Propagating strides in the functionalization pass] + // XLA/LTC don't implement the logic to propagate strides correctly, so we need to rely + // on a reference implementation here (instead of relying on the output from the forward lambda + // having the correct stride info) + if (compute_reference_meta && !disable_meta_reference()) {{ + at::functionalization::impl::set_sizes_strides_offset({view_tensor_name}, reference_tensor_output); + }} + return {view_tensor_name}; + }} +""" + + else: + return f""" + {dispatcher_sig.defn(name=wrapper_name(f.func), is_redispatching_fn=True)} {{ + {unwrap_tensor_args_str} + if (!at::functionalization::impl::isFunctionalTensor({view_tensor_name})) {{ + // functionalization is re-entrant, but will no-op if it wasn't passed a FunctionalTensorWrapper. + at::AutoDispatchSkipFunctionalize guard; + return at::_ops::{noop_api_name}::call({", ".join(view_redispatch_args)}); + }} + auto reapply_views = at::functionalization::impl::getFunctionalizationReapplyViewsTLS(); + auto inverse_return_mode = ( + reapply_views ? at::functionalization::InverseReturnMode::ViewOrScatterInverse + : at::functionalization::InverseReturnMode::NeverView + ); + auto compute_reference_meta = + {view_tensor_name}.key_set().has_backend(c10::BackendComponent::XLABit) || + {view_tensor_name}.key_set().has_backend(c10::BackendComponent::LazyBit); + {return_type} reference_tensor_output; + if (compute_reference_meta && !disable_meta_reference()) {{ + {meta_conversion_str} + at::AutoDispatchSkipFunctionalize func_guard; + c10::impl::ExcludeDispatchKeyGuard guard(exclude_keys_for_meta_dispatch); + reference_tensor_output = at::_ops::{noop_api_name}::call({", ".join(meta_call_args)}); + }} + {return_type} tmp_output; + {{ + at::AutoDispatchSkipFunctionalize guard; + if (reapply_views) {{ + tmp_output = at::_ops::{noop_api_name}::call({", ".join(view_redispatch_args)}); + }} else {{ + tmp_output = at::_ops::{api_name}::call({", ".join(view_redispatch_args)}); + }} + }} + {symbolic_inputs_check} + auto view_meta = {spec.new()}; + auto out = at::functionalization::impl::create_functional_tensor_with_view_meta(tmp_output, {view_tensor_name}, view_meta); + // See Note [Propagating strides in the functionalization pass] + if (compute_reference_meta && !disable_meta_reference()) {{ + at::functionalization::impl::set_sizes_strides_offset(out, reference_tensor_output); + }} + return out; + }} +""" + + +def maybe_create_output(f: NativeFunction, var_name: str) -> str: + if len(f.func.returns) == 0: + return "" + return_type = dispatcher.returns_type(f.func.returns).remove_const_ref().cpp_type() + return f"{return_type} {var_name} = " + + +# Given a NativeFunction, and a variable name corresponding to the output of redispatching on the function, +# this returns two lists of names, consisting of: +# - the names of returns corresponding to the original (mutable) inputs of the outer function +# - the names of returns corresponding to the (immutable) outputs of the inner redispatched function +def get_mutable_redispatch_return_names( + f: NativeFunction, inner_return_var: str +) -> tuple[list[str], list[str]]: + aliased_returns = [] + non_aliased_returns = [] + for i, name in enumerate(f.func.aliased_return_names()): + if name is not None: + aliased_returns.append(name) + else: + non_aliased_returns.append( + inner_return_var + if len(f.func.returns) == 1 + else f"std::get<{i}>({inner_return_var})" + ) + return aliased_returns, non_aliased_returns + + +# When functionalization "no-op's" and redispatches on a mutable operator, we need to take care so that: +# - For fresh outputs, we return the result of the redispatch (without wrapping outputs) +# - For outputs that were aliased to inputs, we return the inputs directly (since some of them might have been wrapped) +def return_from_mutable_noop_redispatch( + f: NativeFunction, inner_return_var: str +) -> str: + aliased, non_aliased = get_mutable_redispatch_return_names(f, inner_return_var) + # Just get all of the return names, and immediately return them + return return_str(f.func.returns, aliased + non_aliased) + + +def wrap_propagate_mutations_and_return( + f: NativeFunction, functional_op: NativeFunction, inner_return_var: str +) -> str: + mutable_arg_names = f.func.arguments.mutable_arg_names() + ( + aliased_outer_rets, + non_aliased_outer_rets, + ) = get_mutable_redispatch_return_names(f, inner_return_var) + _, non_aliased_inner_rets = get_mutable_redispatch_return_names( + functional_op, inner_return_var + ) + # The outer function may have a mix of aliased and non-aliased outputs, + # But the inner functional op that we're transforming to should only have non-aliased outputs + if len(mutable_arg_names) + len(non_aliased_outer_rets) != len( + non_aliased_inner_rets + ): + raise AssertionError( + f"Expected {len(mutable_arg_names)} + {len(non_aliased_outer_rets)} == {len(non_aliased_inner_rets)}" + ) + + # First, take all of the newly created outputs from the inner call and wrap them into functional tensors + updates = [] + non_aliased_wrapped_ret_names = [] + for i, inner_ret in enumerate( + non_aliased_inner_rets[: len(non_aliased_outer_rets)] + ): + ret_name = f"output_{i}" + updates.append( + f"""\ + auto output_{i} = at::functionalization::impl::to_functional_tensor({inner_ret});""" + ) + non_aliased_wrapped_ret_names.append(ret_name) + + # Next, take all of the mutated outputs from the inner call corresponding to mutated inputs, + # and propagate the mutations + for outer_arg, inner_ret in zip( + mutable_arg_names, non_aliased_inner_rets[len(non_aliased_outer_rets) :] + ): + updates.append( + f"""\ + auto {outer_arg}_inner = at::functionalization::impl::from_functional_tensor({outer_arg}); + at::functionalization::impl::replace_({outer_arg}, {inner_ret}); + at::functionalization::impl::commit_update({outer_arg}); + at::functionalization::impl::sync({outer_arg}); + auto {outer_arg}_inner_updated = at::functionalization::impl::from_functional_tensor({outer_arg}); + at::functionalization::impl::propagate_xla_data_direct({outer_arg}_inner, {outer_arg}_inner_updated);""" + ) + + # Finally, we return: + # - Any mutable arguments that also returns + # - Any immutable returns that were created wrapping the output from the inner call + returns_str = return_str( + f.func.returns, aliased_outer_rets + non_aliased_wrapped_ret_names + ) + updates_str = "\n".join(updates) + return f"""\ +{updates_str} + {returns_str}""" + + +def maybe_replace_cumulative_out_dtype_exprs( + f: NativeFunction, + functional_sig: DispatcherSignature, + functional_exprs: list[str], +) -> list[str]: + if ( + f.func.kind() != SchemaKind.out + or f.func.name not in CUMULATIVE_OUT_OPS_PRESERVING_OUT_DTYPE + ): + return functional_exprs + + if len(f.func.arguments.out) != 1: + raise AssertionError( + f"Expected a single out argument for cumulative out op: {f.func.name}" + ) + + dtype_arg_idx = next( + (i for i, arg in enumerate(functional_sig.arguments()) if arg.name == "dtype"), + None, + ) + if dtype_arg_idx is None: + raise AssertionError( + f"Expected dtype argument for cumulative out op: {f.func.name}" + ) + + adjusted_exprs = functional_exprs.copy() + dtype_expr = adjusted_exprs[dtype_arg_idx] + adjusted_exprs[dtype_arg_idx] = ( + f"{dtype_expr}.has_value() ? {dtype_expr} : " + f"std::optional({f.func.arguments.out[0].name}_.scalar_type())" + ) + return adjusted_exprs + + +# Generates the Functionalization kernel for: +# - mutation ops (inplace and out= ops) +@with_native_function_and +def emit_inplace_functionalization_body( + f: NativeFunction, g: NativeFunctionsGroup +) -> str: + # mutation case + if not modifies_arguments(f): + raise AssertionError(f"Expected function to modify arguments: {f.func}") + + dispatcher_sig = DispatcherSignature.from_schema(f.func) + + unwrap_tensor_args_str, unwrapped_args_ctx = unwrap_tensor_args( + dispatcher_sig, is_view_op=False + ) + + mutated_names = [ + a.name + for a in f.func.arguments.flat_all + if a.type.is_tensor_like() and a.annotation is not None + ] + non_mutated_names = [ + a.name + for a in f.func.arguments.flat_all + if a.type.is_tensor_like() and a.annotation is None + ] + non_mutated_tensor_names = [ + a.name + for a in f.func.arguments.flat_all + if a.type == BaseType(BaseTy.Tensor) and a.annotation is None + ] + # all mutable inputs must be functional tensors in order to participate in functionalization + check_all_mutated_args_are_functional = " && ".join( + ["true"] + + [ + f"at::functionalization::impl::isFunctionalTensor({a})" + for a in mutated_names + ] + ) + check_any_non_mutated_args_are_functional = " || ".join( + ["false"] + + [ + f"at::functionalization::impl::isFunctionalTensor({a})" + for a in non_mutated_names + ] + ) + + check_any_non_mutated_tensors_are_xla = " || ".join( + ["false"] + + [ + f"{a}.device().type() == c10::DeviceType::XLA" + for a in non_mutated_tensor_names + ] + ) + # These are used in the cases where we don't functionalize and redispatch to the inplace op + # case 1: we hit an inplace op that doesn't have an out-of-place equivalent + # case 2: we hit an inplace ops but our inputs are not functional tensors (in which case our kernel just no-ops) + inplace_exprs = [ + e.expr + for e in translate(unwrapped_args_ctx, dispatcher_sig.arguments(), method=False) + ] + + # call the out-of-place variant of the op + return_type = ( + dispatcher.returns_type(g.functional.func.returns).remove_const_ref().cpp_type() + ) + functional_sig = DispatcherSignature.from_schema(g.functional.func) + functional_exprs = [ + e.expr + for e in translate(unwrapped_args_ctx, functional_sig.arguments(), method=False) + ] + functional_exprs = maybe_replace_cumulative_out_dtype_exprs( + f, functional_sig, functional_exprs + ) + + meta_conversion_str, meta_call_ctx = convert_to_meta_tensors(dispatcher_sig) + # We don't want to run the inplace meta func for ops like .set_(), because: + # (1) they're unnecessary: inplace meta checks are only useful for ops like add_(), + # where broadcasting will work for the out-of-place case but should fail on the inplace call + # (2) They'll also fail without adding extra infra: we'd need to convert the input storage argument + # into a meta storage + any_storage_args = any( + a.type == BaseType(BaseTy.Storage) for a in f.func.arguments.flat_all + ) + + return f""" + {dispatcher_sig.defn(name=wrapper_name(f.func), is_redispatching_fn=True)} {{ + if ({str(not any_storage_args and f.func.kind() == SchemaKind.inplace).lower()} && !disable_meta_reference()) {{ + // Before converting the mutable op to its functional variant, run meta tensors through the original op. + // This will help us catch shape errors that apply to inplace ops that wouldn't apply to their functional variants. + // (We can only do this for inplace ops today though, because they technically all support meta tensors). + {meta_conversion_str} + at::AutoDispatchSkipFunctionalize func_guard; + c10::impl::ExcludeDispatchKeyGuard guard(exclude_keys_for_meta_dispatch); + at::_ops::{f.func.name.unambiguous_name()}::call({", ".join(a.name for a in meta_call_ctx)}); + }} + {unwrap_tensor_args_str} + if (!({check_all_mutated_args_are_functional})) {{ + // We want to disable this check if there are any XLA tensors. + // cpu_tensor.copy_(xla_tensor) is valid code. + if (!({check_any_non_mutated_tensors_are_xla}) && ({check_any_non_mutated_args_are_functional})) {{ + // case 1: trying to mutate a non functional tensor with a functional tensor is an error + TORCH_INTERNAL_ASSERT(false, + "mutating a non-functional tensor with a functional tensor is not allowed.", + " Please ensure that all of your inputs are wrapped inside of a functionalize() call."); + }} else {{ + // case 2: arguments are not functional tensors, so we no-op and redispatch. + at::AutoDispatchSkipFunctionalize guard; + {maybe_create_output(f, "tmp_output")}at::_ops::{f.func.name.unambiguous_name()}::call({", ".join(inplace_exprs)}); + {return_from_mutable_noop_redispatch(f, "tmp_output")} + }} + }} else {{ + {return_type} tmp_output; + {{ + at::AutoDispatchSkipFunctionalize guard; + tmp_output = at::_ops::{g.functional.func.name.unambiguous_name()}::call({", ".join(functional_exprs)}); + }} + {wrap_propagate_mutations_and_return(f, g.functional, "tmp_output")} + }} + }}""" + + +# The below functions generate RegisterFunctionalization.cpp +# These files provide the kernels that run the functionalization pass, which can be opted into +# per backend (e.g. XLA or Vulkan), or as a composable transform (functionalize() in functorch). + + +# See Note [Functionalization Pass: View Inverses]. +def gen_functionalization_view_inverse_declaration( + selector: SelectiveBuilder, g: NativeFunctionsViewGroup +) -> str | None: + # For every (non-composite) view op, we need a corresponding "inverse view" function. + # This generates the declarations so we get a good compiler error when someone adds a new view. + @with_native_function + def emit_decl_helper(g: NativeFunctionsViewGroup) -> str | None: + if g.view.has_composite_implicit_autograd_kernel: + return None + view_inverse_sig = ViewInverseSignature(g) + return view_inverse_sig.decl() + + return emit_decl_helper(g) + + +# Helper class for generating `ViewMeta` specializations. +@dataclass +class ViewMetaSpecialization: + g: NativeFunctionsViewGroup + f: NativeFunction + + @property + def is_multi_output(self) -> bool: + return functionalization.is_multi_output(self.f.func) + + @property + def is_as_strided(self) -> bool: + return str(self.f.func.name) == "as_strided" + + @property + def out_index(self) -> str: + if self.is_multi_output: + return functionalization.out_index_binding.name + return "0" + + @property + def classname(self) -> str: + return functionalization.classname(self.f.func) + + def decl(self) -> list[str]: + base_ctor_arguments = functionalization.base_ctor_arguments(self.f.func) + extra_ctor_arguments = functionalization.extra_ctor_arguments(self.f.func) + attributes = functionalization.attributes(self.f.func) + + # List of types for declaring the `SerializableTuple` type. + serializable_tuple_args = ",\n".join( + f" {binding.type} /* {binding.name} */" + for binding in (base_ctor_arguments + attributes) + ) + + # Arguments used for forwarding the tuple elements to the constructor. + destructure_tuple_args = ", ".join( + f"std::get<{i}>(tpl)" + for i in range(len(base_ctor_arguments) + len(extra_ctor_arguments)) + ) + + # List of constructor parameters + ctor_parameters = ", ".join( + binding.decl() for binding in (base_ctor_arguments + extra_ctor_arguments) + ) + + # Call the base class `ViewMeta` constructor. + # + # Both of `is_multi_output` and `is_as_strided` are known values, given the + # operation schema. + is_multi_output_str = str(self.is_multi_output).lower() + is_as_strided_str = str(self.is_as_strided).lower() + + base_ctor_bindings = ", ".join( + [ + # `has_symbolic_inputs` is always taken as parameter. + functionalization.has_symbolic_inputs_binding.name, + f"/*is_multi_output=*/{is_multi_output_str}", + f"/*is_as_strided=*/{is_as_strided_str}", + # `out_index` is know if the operation returns only one value. Otherwise, + # we also take it as parameter. + f"/*out_index=*/{self.out_index}", + ] + ) + + # Assignments of `extra_ctor_arguments` to their corresponding fields. + # These are extra fields to-be-declared in this specialization. + # + # We need to set `allow_expensive_conversions`, since we are storing owned versions + # of the non-owning arguments. + ctor_assignments = ",\n".join( + f" {e.type.name}({e.expr})" + for e in translate( + extra_ctor_arguments, + attributes, + method=False, + allow_expensive_conversions=True, + ) + ) + + # List of arguments for constructing the `SerializableTuple` from an instance. + tuple_arguments = ", ".join( + binding.name for binding in (base_ctor_arguments + attributes) + ) + + # List of field declarations. + attr_declarations = "\n".join(f" {binding.decl()};" for binding in attributes) + + # Override `to_out_index` if this operation returns more than 1 value. + to_out_index_decl = "" + if self.is_multi_output: + to_out_index_decl = ( + " std::shared_ptr to_out_index(int64_t out_idx) override;" + ) + + return [ + f""" +struct TORCH_API {self.classname} : public ViewMeta {{ + FUNCTIONALIZATION_VIEWMETA_NAME({self.classname}) + FUNCTIONALIZATION_VIEWMETA_SERIALIZABLE_TUPLE(\n{serializable_tuple_args}); + + {self.classname}(const SerializableTuple& tpl) + : {self.classname}({destructure_tuple_args}) {{}} + + {self.classname}({ctor_parameters}) + : at::functionalization::ViewMeta({base_ctor_bindings}), +{ctor_assignments} {{}} + + Tensor forward(const Tensor& base) override; + Tensor reverse(const Tensor& base, const Tensor& mutated_view) override; +{to_out_index_decl} + + SerializableTuple to_serializable_tuple() {{ + return std::make_tuple({tuple_arguments}); + }} + +{attr_declarations} +}}; +""" + ] + + # Generate a call to the actual operation. + def opcall(self, is_reverse: bool, reapply_views: bool) -> str: + opname = functionalization.name( + self.g, + is_reverse=is_reverse, + include_namespace=True, + reapply_views=reapply_views, + ) + + # Expected arguments for the operation. + if self.g.view_copy is None: + raise AssertionError("Expected view_copy to be non-None") + op_arguments = functionalization.op_arguments(self.g.view_copy.func, is_reverse) + + # The context is composed by the constructor arguments (which are also + # the field variables stored in the instance), and the `base` tensor. + context = [functionalization.base_binding] + context += functionalization.base_ctor_arguments(self.f.func) + context += functionalization.attributes(self.f.func) + + # If we are generating the call for the reverse function, we also have + # access to `mutated_view` argument. + if is_reverse: + context.append(functionalization.mutated_view_binding) + + arguments = ", ".join( + [e.expr for e in translate(context, op_arguments, method=False)] + ) + + # Index the result if this operation returns multiple values. + maybe_index = "" + if not is_reverse and self.is_multi_output: + maybe_index = f"[{self.out_index}]" + + return f"{opname}({arguments}){maybe_index}" + + def impl(self) -> list[str]: + functions = [ + f""" +at::Tensor {self.classname}::forward(const at::Tensor& base) {{ + if (reapply_views) {{ + return {self.opcall(is_reverse=False, reapply_views=True)}; + }} else {{ + return {self.opcall(is_reverse=False, reapply_views=False)}; + }} +}}""", + f""" +at::Tensor {self.classname}::reverse(const at::Tensor& base, const Tensor& mutated_view) {{ + return {self.opcall(is_reverse=True, reapply_views=True)}; +}}""", + ] + + # If this operation returns multiple values, also generate a `to_out_index` + # implementation. + if self.is_multi_output: + functions.append(f""" +std::shared_ptr {self.classname}::to_out_index(int64_t out_index) {{ + return {self.new("out_index")}; +}} +""") + + return functions + + # Create the Python binding for this specialized class. + def binding(self) -> list[str]: + name = functionalization.classname(self.f.func, with_namespace=True) + return [f" create_binding_with_pickle<{name}>(functionalization);"] + + # Generate an instantiation of this specialized class. + def new(self, out_index: str = "0") -> str: + name = functionalization.classname(self.f.func, with_namespace=True) + ctor_arguments = functionalization.base_ctor_arguments( + self.f.func + ) + functionalization.extra_ctor_arguments(self.f.func) + # Replace the `out_index` parameter with the given `out_index`. + arguments = ", ".join( + binding.name if binding.name != "out_index" else out_index + for binding in ctor_arguments + ) + return f"std::make_shared<{name}>({arguments})" + + # Run the function `run` for both: `view` and `view_inplace` functions. + @staticmethod + def map( + g: NativeFunctionsViewGroup, run: Callable[[ViewMetaSpecialization], list[str]] + ) -> list[str]: + def maybe_run(f: NativeFunction | None) -> list[str]: + if f is None: + return [] + with native_function_manager(f): + return run(ViewMetaSpecialization(g, f)) + + return list(concatMap(maybe_run, (g.view, g.view_inplace))) + + +def gen_functionalization_view_meta_classes_base( + selector: SelectiveBuilder, + g: NativeFunctionsViewGroup, + run: Callable[[ViewMetaSpecialization], list[str]], +) -> list[str]: + if not selector.include_all_operators: + return [] + + if g.composite: + return [] + + return ViewMetaSpecialization.map(g, run) + + +def gen_functionalization_view_meta_classes_decl( + selector: SelectiveBuilder, g: NativeFunctionsViewGroup +) -> list[str]: + return gen_functionalization_view_meta_classes_base( + selector, g, ViewMetaSpecialization.decl + ) + + +def gen_functionalization_view_meta_classes_impl( + selector: SelectiveBuilder, g: NativeFunctionsViewGroup +) -> list[str]: + return gen_functionalization_view_meta_classes_base( + selector, g, ViewMetaSpecialization.impl + ) + + +def gen_functionalization_view_meta_classes_binding( + selector: SelectiveBuilder, g: NativeFunctionsViewGroup +) -> list[str]: + return gen_functionalization_view_meta_classes_base( + selector, g, ViewMetaSpecialization.binding + ) + + +# Generates the Python bindings for the `ViewMeta` specialized classes. +def gen_functionalization_view_meta_classes( + native_functions_path: str, + tags_path: str, + selector: SelectiveBuilder, + install_dir: str, + template_dir: str, +) -> None: + from torchgen.gen import get_grouped_by_view_native_functions, parse_native_yaml + + # Parse the native_functions.yaml. + # Then, group them into `NativeFunctionsViewGroup`. + # + # This is the same steps we do in gen.py (ATen codegen). + native_functions = parse_native_yaml( + native_functions_path, tags_path + ).native_functions + native_functions_with_view_groups = get_grouped_by_view_native_functions( + native_functions + ) + view_groups = [ + g + for g in native_functions_with_view_groups + if isinstance(g, NativeFunctionsViewGroup) + ] + + fm = FileManager(install_dir=install_dir, template_dir=template_dir, dry_run=False) + fm.write( + "ViewMetaClassesPythonBinding.cpp", + lambda: { + "view_meta_bindings": list( + concatMap( + lambda g: gen_functionalization_view_meta_classes_binding( + selector, g + ), + view_groups, + ) + ), + }, + ) + + +def gen_functionalization_registration( + selector: SelectiveBuilder, + g: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup, + composite_implicit_autograd_index: BackendIndex, +) -> list[str]: + @with_native_function + def emit_registration_helper(f: NativeFunction) -> str: + if f.has_composite_implicit_autograd_kernel: + metadata = composite_implicit_autograd_index.get_kernel(f) + if metadata is None: + raise AssertionError( + f"Expected metadata for composite implicit autograd kernel: {f.func}" + ) + native_api_name = metadata.kernel + sig = NativeSignature(f.func, symint=metadata.supports_symint()) + # Note [Composite view ops in the functionalization pass] + # We don't need to worry about implemententing functionalization kernels for views with + # CompositeImplicitAutograd kernels, because we can just decompose them into their base operators. + # We can't just opt the entire Functionalization dispatch key into the composite keyset though, + # because we don't want to decompose non-view ops that are composite, like `at::ones`. + registration_str = ( + f"static_cast<{sig.ptr_type()}>(at::native::{native_api_name})" + ) + else: + # non-composite view ops (and inplace ops) get a normal registration. + registration_str = f"TORCH_FN(functionalization::{wrapper_name(f.func)})" + return f'm.impl("{f.func.name}", {registration_str});' + + # Don't generate kernels in mobile build + if not selector.include_all_operators: + return [] + + if isinstance(g, NativeFunctionsViewGroup): + # functionalization needs to register kernels for view + view_inplace ops + # See Note [Functionalization <> torch.Tensor constructor] + if str(g.view.func.name) == "lift_fresh": + return [] + view_str = [] + view_str.append(emit_registration_helper(g.view)) + if g.view_inplace is not None: + if not g.view_inplace.is_view_op: + raise AssertionError( + f"Expected view_inplace to be a view op: {g.view_inplace.func}" + ) + view_str.append(emit_registration_helper(g.view_inplace)) + return view_str + + elif isinstance(g, NativeFunctionsGroup): + # Gets a hand-written functionalization kernel + if g.inplace is not None and str(g.inplace.func.name) == "set_.source_Tensor": + fns = [] + else: + fns = list(g.functions()) + else: + if str(g.func.name) in MUTABLE_OPS_NOT_USING_FUNCTIONALIZATION: + return [] + fns = [g] + + registrations = [] + for f in fns: + if f.has_composite_implicit_autograd_kernel: + continue + if str(f.func.name) == "lift": + # See Note [Functionalization <> torch.Tensor constructor] + return [] + if str(f.func.name) == "resize_": + # See Note [resize_ in Functionalization] + return [] + if str(f.func.name.name) != "set_": + if f.is_view_op: + raise AssertionError(f"Unexpected view op: {f.func}") + # functionalization needs to generate and register kernels for inplace ops. + # We *also* need to directly register CompositeImplicitAUtograd kernels + # so that they decompose properly before functioanlization. + if modifies_arguments(f): + registrations.append(emit_registration_helper(f)) + return registrations + + +def gen_functionalization_definition( + selector: SelectiveBuilder, + # Note: Ideally this code should never have to look at NativeFunction + # (and instead only need to operate on grouped NativeFunctions). + # The only reason currently is because we need to emit direct dispatch registrations + # For CompositeImplicitAutograd operators, which are potentially ungrouped. + g: NativeFunction | NativeFunctionsGroup | NativeFunctionsViewGroup, +) -> list[str]: + # Don't generate kernels in mobile build + if not selector.include_all_operators: + return [] + + if isinstance(g, NativeFunctionsViewGroup): + # Case 1: emit view -> view_copy kernels for the functionalization pass + view_defs = [] + if not g.composite: + # invariant: NativeFunctionsViewGroup's always have a view_copy operator + # if the view is not composite (implicit autograd) + if g.view_copy is None: + raise AssertionError( + f"Expected view_copy to be non-None: {dataclass_repr(g, indent=1)}" + ) + view_defs.append(emit_view_functionalization_body(g, view_inplace=False)) + if g.view_inplace is not None: + view_defs.append(emit_view_functionalization_body(g, view_inplace=True)) + return view_defs + elif isinstance(g, NativeFunction): + # Invariant: all mutable operators that we need to handle in functionalization + # should have been properly grouped up. + # TODO: The below ops all have "problematic" schemas that prevent them from + # getting functionalized. Instead of bending over backwards to get things to work, + # I think we should either: + # (1) fix their schemas (BC-breaking) + # (2) hand-write their functionalization kernels + if ( + str(g.func.name) not in MUTABLE_OPS_NOT_USING_FUNCTIONALIZATION + and str(g.func.name.name) not in MUTABLE_OPS_NOT_USING_FUNCTIONALIZATION + ): + if not ( + g.has_composite_implicit_autograd_kernel or not modifies_arguments(g) + ): + raise AssertionError( + f"Expected composite implicit autograd kernel or non-modifying function: {g.func}" + ) + return [] + else: + # Case 2: emit inplace -> out-of-place kernels for the functionalization pass + mutation_defs = [] + mutation_defs.append(emit_inplace_functionalization_body(g.out, g)) + if g.inplace is not None: + mutation_defs.append(emit_inplace_functionalization_body(g.inplace, g)) + if g.mutable is not None: + mutation_defs.append(emit_inplace_functionalization_body(g.mutable, g)) + return mutation_defs + return [] diff --git a/.venv/lib/python3.12/site-packages/torchgen/gen_lazy_tensor.py b/.venv/lib/python3.12/site-packages/torchgen/gen_lazy_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..5cacf4002dba9036023795ebe88c417fdb60e4fd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/gen_lazy_tensor.py @@ -0,0 +1,593 @@ +from __future__ import annotations + +import argparse +import os +from collections import namedtuple +from pathlib import Path +from typing import Any, TYPE_CHECKING + +import yaml + +import torchgen.dest as dest +from torchgen.api.lazy import setValueT +from torchgen.api.types import BaseCppType +from torchgen.dest.lazy_ir import GenLazyIR, GenLazyNativeFuncDefinition, GenTSLazyIR +from torchgen.gen import get_grouped_native_functions, parse_native_yaml +from torchgen.gen_backend_stubs import ( + error_on_missing_kernels, + gen_dispatcher_registrations, + gen_dispatchkey_nativefunc_headers, + parse_backend_yaml, +) +from torchgen.model import NativeFunction, NativeFunctionsGroup, OperatorName +from torchgen.selective_build.selector import SelectiveBuilder +from torchgen.utils import FileManager, NamespaceHelper +from torchgen.yaml_utils import YamlLoader + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Iterator, Sequence + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Lazy Tensor Codegen +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# Overview +# ~~~~~~~~ +# +# This codegen script builds on existing data models and helpers used +# by all ATen backends, and adds new functionality specific to lazy +# tensor backends. +# +# Inputs: +# - _native_functions.yaml: controls which operators are +# supported by the backend. +# +# Outputs: +# (for all backends) +# Ir.h defines Lazy IR classes to be constructed during tracing +# - opt-in: also generate 'lowering' methods for the TorchScript backend only +# NativeFunctions.cpp defines implementations of native functions which perform lazy tracing +# - opt-in: 'full_codegen' section of backend yaml; 'supported' section omits these implementations +# NativeFunctions.h declares implementations of native functions for both 'supported' and 'full_codegen' +# ops +# +# Register.cpp registers all op implementations with the dispatcher +# RegisterAutograd.cpp registers all autograd implementations with the dispatcher +# +# Validation Helpers: +# - Shape Inference: errs if any ops in backend yaml require shape inference not provided by meta kernels or +# implementations in torch/csrc/lazy/core/shape_inference.* +# - native function impls: errs if any 'supported' ops do not have an implementation defined in the backend +# (non-codegen) implementation file +# +# +# About the Data Model +# ~~~~~~~~~~~~~~~~~~~~ +# +# Modeled after ATen codegen, the first step is to parse yaml and build a data model for the operators +# we care about. In this case, the _native_functions yaml defines a subset of the core operators +# (defined in more detail in the main native_functions.yaml), which will be supported by your backend. +# Backends can list ops in two categories: +# - `supported` ops require hand-implementations but still get codegenned declarations and registrations +# - `full_codegen` ops get implementations (and IR classes) generated too +# +# Each native function is modeled as an object with a schema, and each schema has objects representing their +# arguments. Much of the codegen is manipulation of the arguments and their types. For example, lazy tensor +# backends need to transform 'at::Tensor' arguments into 'lazy::Value' objects, as well as replacing reference +# types (stringref) with actual string objects, and this is done by manipulating the data model objects. +# - see api/lazy.py for the lazy data model +# +# Once the data model is set up, the rest of this script processes a number of templates for output CPP file +# and fills in the template values using helpers in `dest/lazy_ir.py` and `dest/lazy_ts_lowering.py`. These +# helpers mostly iterate over functions and their arguments, outputting different c++ snippets. +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +# Parses the external backend's yaml, and adds a new BackendIndex for the backend's dispatch key. +# Returns a Tuple of (backend_key, autograd_key, cpp_namespace, updated BackendIndex mapping, full_codegen) +ParsedExternalYaml = namedtuple( + "ParsedExternalYaml", + ["backend_key", "autograd_key", "cpp_namespace", "backend_indices", "full_codegen"], +) + + +def parse_native_functions_keys( + backend_yaml_path: str, + grouped_native_functions: Sequence[NativeFunction | NativeFunctionsGroup], +) -> tuple[list[OperatorName], list[Any], list[OperatorName]]: + with open(backend_yaml_path) as f: + yaml_values = yaml.load(f, Loader=YamlLoader) + if not isinstance(yaml_values, dict): + raise AssertionError(f"Expected dict from YAML, got {type(yaml_values)}") + + full_codegen = yaml_values.pop("full_codegen", []) + non_native = yaml_values.pop("non_native", []) + ir_gen = yaml_values.pop("ir_gen", []) + if not isinstance(full_codegen, list): + raise AssertionError( + f"Expected full_codegen to be list, got {type(full_codegen)}" + ) + if not isinstance(non_native, list): + raise AssertionError(f"Expected non_native to be list, got {type(non_native)}") + if not isinstance(ir_gen, list): + raise AssertionError(f"Expected ir_gen to be list, got {type(ir_gen)}") + full_codegen_opnames = [OperatorName.parse(name) for name in full_codegen] + ir_gen_opnames = [OperatorName.parse(name) for name in ir_gen] + return full_codegen_opnames, non_native, ir_gen_opnames + + +def validate_shape_inference_header( + shape_inference_hdr: str, expected_shape_infr_decls: list[str] +) -> None: + try: + with open(shape_inference_hdr) as f: + shape_infr_decls = f.read() + shape_infr_decl_lines = set(shape_infr_decls.split("\n")) + except OSError as e: + raise AssertionError( + f"Unable to read from the specified shape_inference_hdr file: {shape_inference_hdr}" + ) from e + + # TODO(whc) add a check for shape inference functions that have meta kernels implement and should be retired. + + missing_decls = [ + decl for decl in expected_shape_infr_decls if decl not in shape_infr_decl_lines + ] + if missing_decls: + raise Exception( # noqa: TRY002 + f"""Missing shape inference function.\n +Please add declare this function in {shape_inference_hdr}:\n +and implement it in the corresponding shape_inference.cpp file.\n +{os.linesep.join(missing_decls)}""" + ) + + +# Some helper functions for the codegen. +def get_ltc_helper_fns() -> str: + return """\ +at::Tensor to_meta(const at::Tensor& tensor) { + // undefined tensors can't be converted to the meta device, since they don't have sizes/strides + if (!tensor.defined()) return tensor; + auto out = at::native::empty_strided_meta_symint(tensor.sym_sizes(), tensor.sym_strides(), \ +/*dtype=*/tensor.scalar_type(), /*layout=*/tensor.layout(), \ +/*device=*/c10::Device(c10::kMeta), /*pin_memory=*/std::nullopt); + // needs to handle wrapped numbers, so dtype promotion works properly. + if (tensor.unsafeGetTensorImpl()->is_wrapped_number()) { + out.unsafeGetTensorImpl()->set_wrapped_number(true); + } + return out; +} +std::optional to_meta(const std::optional& tensor) { + if (tensor.has_value()) { + return to_meta(*tensor); + } + return std::nullopt; +} + +std::vector to_meta(at::ITensorListRef t_list) { + std::vector outs; + outs.reserve(t_list.size()); + for (const auto& tensor : t_list) { + outs.push_back(to_meta(tensor)); + } + return outs; +} +""" + + +class default_args: + node_base: str = "Node" + node_base_hdr: str | None = None + shape_inference_hdr: str = "torch/csrc/lazy/core/shape_inference.h" + tensor_class: str = "torch::lazy::LazyTensor" + tensor_class_hdr: str = "torch/csrc/lazy/core/tensor.h" + lazy_ir_generator: type[GenLazyIR] = GenLazyIR + native_func_definition_generator: type[GenLazyNativeFuncDefinition] = ( + GenLazyNativeFuncDefinition + ) + backend_name: str = "TorchScript" + + +def main() -> None: + parser = argparse.ArgumentParser(description="Generate Lazy Tensor backend files") + parser.add_argument( + "-s", + "--source-yaml", + "--source_yaml", + help="path to source yaml file containing operator external definitions", + ) + parser.add_argument("-o", "--output-dir", "--output_dir", help="output directory") + parser.add_argument( + "--dry-run", "--dry_run", type=bool, default=False, help="output directory" + ) + parser.add_argument( + "--impl-path", + "--impl_path", + type=str, + default=None, + help="path to the source C++ file containing kernel definitions", + ) + parser.add_argument( + "--gen-ts-lowerings", + "--gen_ts_lowerings", + action="store_true", + help="Generate TorchScript lowerings in addition to Lazy IR and NativeFunctions", + ) + parser.add_argument( + "--node-base", + "--node_base", + type=str, + default=default_args.node_base, + help="Name of backend specific custom Lazy IR Node base class", + ) + parser.add_argument( + "--node-base-hdr", + "--node_base_hdr", + type=str, + default=default_args.node_base_hdr, + help="Path to header file defining custom Lazy IR Node base class", + ) + parser.add_argument( + "--shape-inference-hdr", + "--shape_inference_hdr", + type=str, + default=default_args.shape_inference_hdr, + help="Path to header file defining custom Lazy shape inference functions", + ) + parser.add_argument( + "--tensor-class", + "--tensor_class", + type=str, + default=default_args.tensor_class, + help="Name of backend specific custom Lazy Tensor class", + ) + parser.add_argument( + "--tensor-class-hdr", + "--tensor_class_hdr", + type=str, + default=default_args.tensor_class_hdr, + help="Path to header file defining custom Lazy Tensor class", + ) + parser.add_argument( + "--backend-name", + "--backend_name", + type=str, + default=default_args.backend_name, + help="Name of the backend to generate", + ) + options = parser.parse_args() + + # Assumes that this file lives at PYTORCH_ROOT/torchgen/gen_backend_stubs.py + torch_root = Path(__file__).absolute().parents[2] + aten_path = str(torch_root / "aten" / "src" / "ATen") + lazy_ir_generator: type[GenLazyIR] = default_args.lazy_ir_generator + if options.gen_ts_lowerings: + lazy_ir_generator = GenTSLazyIR + native_func_definition_generator: type[GenLazyNativeFuncDefinition] = ( + default_args.native_func_definition_generator + ) + + run_gen_lazy_tensor( + aten_path, + options.source_yaml, + options.output_dir, + options.dry_run, + options.impl_path, + options.node_base, + options.node_base_hdr, + options.tensor_class, + options.tensor_class_hdr, + options.shape_inference_hdr, + lazy_ir_generator, + native_func_definition_generator, + options.backend_name, + ) + + +def run_gen_lazy_tensor( + aten_path: str, + source_yaml: str, + output_dir: str, + dry_run: bool, + impl_path: str | None, + node_base: str = default_args.node_base, + node_base_hdr: str | None = default_args.node_base_hdr, + tensor_class: str = default_args.tensor_class, + tensor_class_hdr: str = default_args.tensor_class_hdr, + shape_inference_hdr: str = default_args.shape_inference_hdr, + lazy_ir_generator: type[GenLazyIR] = default_args.lazy_ir_generator, + native_func_definition_generator: type[ + GenLazyNativeFuncDefinition + ] = default_args.native_func_definition_generator, + # build_in_tree is true for TS backend and affects include paths + build_in_tree: bool = False, + # per_operator_headers changes whether ATen/Functions.h or individual operator headers are used + # it must match how ATen was built + per_operator_headers: bool = False, + backend_name: str = default_args.backend_name, + gen_forced_fallback_code: bool = False, + use_lazy_shape: bool = True, + # the following arguments are temporary customization points for xla backend migration. + # do not rely on them otherwise, they should be removed once migration is complete + backend_namespace: str = "torch::lazy", + get_tensorlist: str = "GetTensorList", + get_tensor_or_wrap_number: str = "GetLtcTensorOrCreateForWrappedNumber", + try_get_tensor: str = "TryGetLtcTensor", + metrics_counter: str = 'TORCH_LAZY_FN_COUNTER("lazy::")', + create_tensor: str = "LazyTensor::Create", + create_from_first_tensor: bool = False, + create_aten_from_ltc_tensor: str = "torch::lazy::CreateAtenFromLtcTensor", + tuple_aten_from_ltc_tensors: str = "torch::lazy::TupleAtenFromLtcTensors", + lazy_value_class: str = "torch::lazy::Value", + lazy_tensor_ptr: str = "LazyTensorPtr", + get_device_fn: str = "torch::lazy::GetBackendDevice", +) -> None: + lv_tokens = lazy_value_class.split("::") + lv_class = lv_tokens[-1] + lv_ns = "::".join(lv_tokens[:-1]) + setValueT(BaseCppType(lv_ns, lv_class)) + template_dir = os.path.join(aten_path, "templates") + + def make_file_manager(install_dir: str) -> FileManager: + return FileManager( + install_dir=install_dir, template_dir=template_dir, dry_run=dry_run + ) + + fm = make_file_manager(output_dir) + + native_yaml_path = os.path.join(aten_path, "native/native_functions.yaml") + tags_yaml_path = os.path.join(aten_path, "native/tags.yaml") + parsed_yaml = parse_native_yaml(native_yaml_path, tags_yaml_path) + native_functions, backend_indices = ( + parsed_yaml.native_functions, + parsed_yaml.backend_indices, + ) + grouped_native_functions = get_grouped_native_functions(native_functions) + + def sort_native_function(f: NativeFunctionsGroup | NativeFunction) -> str: + """ + We sort the native function because of the note in concat_map_codegen. + TODO(alanwaketan): Remove this sorting hack once all ops are grouped properly. + """ + func = f.functional.func if isinstance(f, NativeFunctionsGroup) else f.func + return str(func.name.name) + + grouped_native_functions = sorted( + grouped_native_functions, key=sort_native_function + ) + + parsed_backend_yaml = parse_backend_yaml( + source_yaml, grouped_native_functions, backend_indices + ) + backend_key = parsed_backend_yaml.backend_key + autograd_key = parsed_backend_yaml.autograd_key + cpp_namespace = parsed_backend_yaml.cpp_namespace + backend_indices = parsed_backend_yaml.backend_indices + # the following 3 keys are all processed differently + # for full_codegen, we generate IR, kernels, etc + # for ir_gen, we generate only IR + # non_native is used to register kernels not declared in + # native_functions.yaml + full_codegen, non_native, ir_gen = parse_native_functions_keys( + source_yaml, grouped_native_functions + ) + + def concat_map_codegen( + func: Callable[[NativeFunction], Sequence[str]], + xs: Iterable[NativeFunctionsGroup | NativeFunction], + ops_list: list[OperatorName] = full_codegen, + ) -> Iterator[str]: + """ + We code-gen for the functional variant, which is all we need for IR classes/lowerings/shape inferences, but we + only code-gen additional entries for the inplace variant for the native functions. + """ + + for x in xs: + fs = list(x.functions()) if isinstance(x, NativeFunctionsGroup) else [x] + for f in fs: + if f.func.name in ops_list: + yield from func(f) + + selector = SelectiveBuilder.get_nop_selector() + + if backend_key is None: + raise AssertionError("backend_key must be non-None") + class_name = backend_indices[backend_key].native_function_class_name() + + if impl_path is not None: + error_on_missing_kernels( + native_functions, + backend_indices, + backend_key, + autograd_key, + class_name, + impl_path, + full_codegen, + ) + + """ Validate Shape Inference Definitions + + Generated lazy native functions all perform shape inference, by first using a meta:: kernel + if available for that op, and otherwise using a 'compute_shape_{op}' function instead. The generator + knows the call signature for compute_shape_{op} because it matches the nativefunction (and meta::) signature, + so it just has to check whether the op is structured and generate a call for one or the other. It's up to the dev + to supply the missing compute_shape_{op} function, but the codegen at least warns you about this and provides + the expected signature which can be copy-pasted into shape_inference.h. + + compute_shape_{op} functions are handwritten and should be replaced over time as ops get ported + to structured kernels. + + See torch/csrc/lazy/core/shape_inference.cpp #READ THIS! for more information. + """ + if shape_inference_hdr is not None: + expected_shape_infr_decls = list( + concat_map_codegen( + dest.GenLazyShapeInferenceDefinition( + backend_indices[backend_key], tensor_class + ), + grouped_native_functions, + ) + ) + + validate_shape_inference_header(shape_inference_hdr, expected_shape_infr_decls) + if class_name is None: + raise AssertionError("class_name must be non-None") + + # Generate nativefunction declarations + # Note, eager registrations is set to False for the lazy TS backend as another LTC backend + # may want to register their own lazy kernels instead of registering the TS ones. + # The registration will lazily happen when init_ts_backend is called. + gen_dispatchkey_nativefunc_headers( + fm, + class_name, + cpp_namespace, + backend_indices, + grouped_native_functions, + backend_key, + autograd_key, + backend_name, + ) + + # Generate Dispatcher registrations which hook up the nativefunctions + for dispatch_key in ( + [backend_key] if autograd_key is None else [backend_key, autograd_key] + ): + gen_dispatcher_registrations( + fm, + output_dir, + class_name, + backend_indices, + grouped_native_functions, + backend_key, + dispatch_key, + selector, + build_in_tree=build_in_tree, + per_operator_headers=per_operator_headers, + backend_name=backend_name, + eager_registration=False, + ) + + # Generate native function impls that build IR nodes + ns_helper = NamespaceHelper(cpp_namespace) + fm.write_with_template( + f"{backend_key}NativeFunctions.cpp", + "DispatchKeyNativeFunctions.cpp", + lambda: { + "includes": [ + f"#include <{path}>" + for path in [ + tensor_class_hdr, + shape_inference_hdr, + "ATen/Functions.h", + "ATen/native/TensorConversions.h", + "ATen/NativeFunctions.h", + "ATen/CompositeExplicitAutogradNonFunctionalFunctions.h", + "ATen/MetaFunctions.h", + "ATen/Operators.h", + "ATen/native/CPUFallback.h", + "torch/csrc/lazy/core/ir_builder.h", + "torch/csrc/lazy/core/lazy_graph_executor.h", + "torch/csrc/lazy/core/metrics.h", + "torch/csrc/lazy/core/shape.h", + f"{output_dir}/{backend_key}NativeFunctions.h", + f"{output_dir}/LazyIr.h", + ] + + ( + ["torch/csrc/lazy/ts_backend/ts_eager_fallback.h"] + if gen_forced_fallback_code + else [] + ) + ], + "helper_fns": get_ltc_helper_fns(), + "native_functions_include": "", + "namespace_prologue": ns_helper.prologue, + "namespace_epilogue": ns_helper.epilogue, + "native_function_definitions": list( + concat_map_codegen( + native_func_definition_generator( + f"{backend_key}NativeFunctions", + backend_indices[backend_key], + tensor_class, + gen_forced_fallback_code, + backend_namespace, + get_tensorlist, + get_tensor_or_wrap_number, + try_get_tensor, + metrics_counter, + create_tensor, + create_from_first_tensor, + create_aten_from_ltc_tensor, + tuple_aten_from_ltc_tensors, + lazy_tensor_ptr, + get_device_fn, + ), + grouped_native_functions, + ) + ), + }, + ) + # Generate IR node classes + lazy_ir_obj = lazy_ir_generator( + backend_indices[backend_key], backend_name, node_base, use_lazy_shape + ) + + fm.write_with_template( + "LazyIr.h", + "LazyIr.h", + lambda: { + "lazy_ir_sysinc": [ + f"#include <{path}>" + for path in [ + "ATen/core/Formatting.h", + "c10/core/ScalarType.h", + "torch/csrc/lazy/core/hash.h", + "torch/csrc/lazy/core/ir.h", + "torch/csrc/lazy/core/shape.h", + "optional", + "vector", + ] + ], + "lazy_ir_inc": [f'#include "{node_base_hdr}"'] + if node_base_hdr is not None + else [], + "ir_declarations": list( + concat_map_codegen( + lazy_ir_obj, grouped_native_functions, full_codegen + ir_gen + ) + ), + "namespace_prologue": ns_helper.prologue, + "namespace_epilogue": ns_helper.epilogue, + }, + ) + + # Generate Non Native IR Node classes + fm.write_with_template( + "LazyNonNativeIr.h", + "LazyNonNativeIr.h", + lambda: { + "lazy_non_native_ir_inc": [ + f"#include <{path}>" + for path in [ + "torch/csrc/lazy/core/ir.h", + "torch/csrc/lazy/core/ir_builder.h", + "torch/csrc/lazy/core/internal_ops/ltc_ops.h", + "torch/csrc/lazy/core/shape_inference.h", + ] + + ([node_base_hdr] if node_base_hdr else []) + if path + ], + "non_native_ir_nodes": dest.generate_non_native_lazy_ir_nodes( + non_native, lazy_ir_obj + ), + "namespace_prologue": ns_helper.prologue, + "namespace_epilogue": ns_helper.epilogue, + }, + ) + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torchgen/gen_schema_utils.py b/.venv/lib/python3.12/site-packages/torchgen/gen_schema_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..45ffffba2e07b8f6eaf6d6a549c05bcf4bce2da0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/gen_schema_utils.py @@ -0,0 +1,98 @@ +from typing import Any + +from torchgen.model import ( + Annotation, + Argument, + Arguments, + BaseOperatorName, + BaseTy, + BaseType, + CustomClassType, + FunctionSchema, + ListType, + OperatorName, + Return, +) + + +# Note: These aren't actually used in torchgen, they're some utilities for generating a schema +# from real arguments. For example, this is used to generate HigherOrderOperators' schema since +# their schemas can vary for different instances of the same HOP. + + +class TypeGen: + convert_to_base_ty = { + int: BaseTy.int, + float: BaseTy.float, + str: BaseTy.str, + bool: BaseTy.bool, + } + + @staticmethod + def from_example(obj: Any) -> BaseType | ListType | CustomClassType: + import torch + + if isinstance(obj, torch.fx.GraphModule): + return BaseType(BaseTy.GraphModule) + elif isinstance(obj, torch.Tensor): + return BaseType(BaseTy.Tensor) + elif isinstance(obj, torch.SymInt): + return BaseType(BaseTy.SymInt) + elif isinstance(obj, torch.SymBool): + return BaseType(BaseTy.SymBool) + elif isinstance(obj, torch.ScriptObject): + return CustomClassType(obj._type().name()) # type: ignore[attr-defined] + elif isinstance(obj, (list, tuple)): + if len(obj) == 0: + raise AssertionError("list/tuple must be non-empty") + all_base_tys = [TypeGen.from_example(x) for x in obj] + if len(set(all_base_tys)) > 1: + raise RuntimeError( + f"Cannot generate schema for a sequence of args of heterogeneous types: {all_base_tys}. " + "Consider unpacking the argument and give proper names to them if possible " + "instead of using *args." + ) + return ListType(all_base_tys[0], len(obj)) + tp = type(obj) + if tp not in TypeGen.convert_to_base_ty: + raise RuntimeError(f"unsupported type {tp}") + return BaseType(TypeGen.convert_to_base_ty[tp]) + + +class ReturnGen: + @staticmethod + def from_example( + name: str | None, obj: Any, annotation: Annotation | None + ) -> Return: + return Return(name, TypeGen.from_example(obj), annotation) + + +class ArgumentGen: + @staticmethod + def from_example( + name: str, obj: Any, default: str | None, annotation: Annotation | None + ) -> Argument: + return Argument( + name, TypeGen.from_example(obj), default=default, annotation=annotation + ) + + +class FunctionSchemaGen: + @staticmethod + def from_example( + op_name: str, + example_inputs: tuple[tuple[str, Any], ...], + example_outputs: tuple[Any, ...], + ) -> FunctionSchema: + args = [] + for name, inp in example_inputs: + args.append(ArgumentGen.from_example(name, inp, None, None)) + # ignore the annotations and other attributes for now, we could add more when needed. + arguments = Arguments( + tuple(), None, tuple(args), tuple(), None, tuple(), tuple() + ) + returns = tuple( + ReturnGen.from_example(None, out, None) for out in example_outputs + ) + op_name = OperatorName(BaseOperatorName(op_name, False, False, False), "") + return FunctionSchema(op_name, arguments, returns) diff --git a/.venv/lib/python3.12/site-packages/torchgen/gen_vmap_plumbing.py b/.venv/lib/python3.12/site-packages/torchgen/gen_vmap_plumbing.py new file mode 100644 index 0000000000000000000000000000000000000000..16582db2db877dd264b4beeb2da45621becdea2c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/gen_vmap_plumbing.py @@ -0,0 +1,277 @@ +from __future__ import annotations + +import textwrap +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from torchgen.api.translate import translate +from torchgen.api.types import DispatcherSignature +from torchgen.context import method_with_native_function +from torchgen.model import ( + Argument, + BaseTy, + BaseType, + FunctionSchema, + ListType, + NativeFunction, + OptionalType, + Return, + SchemaKind, + Type, +) +from torchgen.utils import mapMaybe + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +def is_tensor(typ: Type) -> bool: + return isinstance(typ, BaseType) and typ.name == BaseTy.Tensor + + +def is_optional_tensor(typ: Type) -> bool: + return isinstance(typ, OptionalType) and is_tensor(typ.elem) + + +def is_tensor_list(typ: Type) -> bool: + return isinstance(typ, ListType) and is_tensor(typ.elem) + + +def unwrap_tensor(name: str, cur_level_var: str) -> list[str]: + result = f"""\ + auto [{name}_value, {name}_bdim] = unwrapTensorAtLevel({name}, {cur_level_var});""" + return textwrap.dedent(result).split("\n") + + +def unwrap_optional_tensor(name: str, cur_level_var: str) -> list[str]: + result = f"""\ + std::optional {name}_value; + std::optional {name}_bdim; + if ({name}) {{ + std::tie({name}_value, {name}_bdim) = unwrapTensorAtLevel({name}.value(), {cur_level_var}); + }}""" + return textwrap.dedent(result).split("\n") + + +def gen_unwraps( + flat_arguments: Sequence[Argument], cur_level_var: str +) -> tuple[str, list[str]]: + arg_names = [a.name for a in flat_arguments] + arg_types = [a.type for a in flat_arguments] + + tensors = [name for typ, name in zip(arg_types, arg_names) if is_tensor(typ)] + optional_tensors = [ + name for typ, name in zip(arg_types, arg_names) if is_optional_tensor(typ) + ] + + unwraps = [] + for tensor in tensors: + unwraps += unwrap_tensor(tensor, cur_level_var) + + for opt_tensor in optional_tensors: + unwraps += unwrap_optional_tensor(opt_tensor, cur_level_var) + unwrap_code = "\n".join(unwraps) + + unwrapped_arg_list = [] + for arg in arg_names: + if arg in tensors or arg in optional_tensors: + unwrapped_arg_list += [f"{arg}_value", f"{arg}_bdim"] + else: + unwrapped_arg_list.append(arg) + return unwrap_code, unwrapped_arg_list + + +def gen_case_where_all_bdims_are_none( + outer_sig: DispatcherSignature, schema: FunctionSchema, cur_level_var: str +) -> str: + conditions = [] + flat_args = schema.arguments.flat_all + for arg in flat_args: + if not arg.type.is_tensor_like(): + continue + conditions.append(f"!isBatchedAtLevel({arg.name}, {cur_level_var})") + + sig = DispatcherSignature.from_schema(schema) + translated_args = ", ".join( + e.expr for e in translate(outer_sig.arguments(), sig.arguments()) + ) + return f"""\ +if ({" && ".join(conditions)}) {{ + return at::_ops::{sig.func.name.unambiguous_name()}::call({translated_args}); +}}""" + + +def gen_returns( + returns: tuple[Return, ...], cur_level_var: str, results_var: str +) -> str: + idx = 0 + wrapped_returns = [] + for ret in returns: + if is_tensor(ret.type): + wrapped_returns.append( + f"makeBatched(std::get<{idx}>({results_var}), std::get<{idx + 1}>({results_var}), {cur_level_var})" + ) + idx += 2 + elif is_tensor_list(ret.type): + wrapped_returns.append( + f"makeBatchedVector(std::get<{idx}>({results_var}), std::get<{idx + 1}>({results_var}), {cur_level_var})" + ) + idx += 2 + else: + wrapped_returns.append(f"std::get<{idx}>({results_var})") + idx += 1 + if len(wrapped_returns) == 1: + result = f"return {wrapped_returns[0]};" + else: + result = f"return std::make_tuple({', '.join(wrapped_returns)});" + return result + + +def accepts_at_least_one_tensor_input(schema: FunctionSchema) -> bool: + return any(a.type.is_tensor_like() for a in schema.arguments.flat_all) + + +def is_mutated_arg(argument: Argument) -> bool: + return argument.annotation is not None and argument.annotation.is_write + + +def gen_vmap_inplace_plumbing(native_function: NativeFunction) -> str | None: + # Assumptions: + # - only one argument is being modified in-place + # - the argument that is being modified in-place is the first argument + # - all returns are either Tensor, tuple of Tensor, or TensorList + schema = native_function.func + sig = DispatcherSignature.from_schema(schema) + returns = schema.returns + + # Check assumptions. If these are invalid we return None + # and punt the work to handle them to the future. + if schema.kind() != SchemaKind.inplace: + raise AssertionError(f"Expected inplace schema, got {schema.kind()}") + if not is_mutated_arg(schema.arguments.flat_all[0]): + return None + if len([arg for arg in schema.arguments.flat_all if is_mutated_arg(arg)]) != 1: + return None + + # Only support cases where all returns are Tensors or vector + if len(returns) == 0: + return None + if not all(is_tensor(ret.type) or is_tensor_list(ret.type) for ret in returns): + return None + if not accepts_at_least_one_tensor_input(schema): + return None + + cur_level_var = "cur_level" + + unwraps, unwrapped_arg_list = gen_unwraps(schema.arguments.flat_all, cur_level_var) + bdims_all_none_case = gen_case_where_all_bdims_are_none(sig, schema, cur_level_var) + + return f"""\ +template +{sig.decl(name=schema.name.unambiguous_name() + "_generated_plumbing")} {{ + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "gen_vmap_inplace_plumbing"); + int64_t {cur_level_var} = maybe_layer->layerId(); +{textwrap.indent(bdims_all_none_case, " ")} +{textwrap.indent(unwraps, " ")} + batch_rule({", ".join(unwrapped_arg_list)}); + return {schema.arguments.flat_all[0].name}; +}}""" + + +def gen_vmap_plumbing_no_returns(native_function: NativeFunction) -> str: + schema = native_function.func + sig = DispatcherSignature.from_schema(schema) + cur_level_var = "cur_level" + + unwraps, unwrapped_arg_list = gen_unwraps(schema.arguments.flat_all, cur_level_var) + bdims_all_none_case = gen_case_where_all_bdims_are_none(sig, schema, cur_level_var) + + return f"""\ +template +{sig.decl(name=schema.name.unambiguous_name() + "_generated_plumbing")} {{ + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "gen_vmap_plumbing_no_returns"); + int64_t {cur_level_var} = maybe_layer->layerId(); +{textwrap.indent(bdims_all_none_case, " ")} +{textwrap.indent(unwraps, " ")} + batch_rule({", ".join(unwrapped_arg_list)}); +}}""" + + +def gen_vmap_plumbing(native_function: NativeFunction) -> str | None: + schema = native_function.func + sig = DispatcherSignature.from_schema(schema) + returns = schema.returns + + # Only support cases where all returns are Tensors or vector + if not accepts_at_least_one_tensor_input(schema): + return None + if len(returns) == 0: + return gen_vmap_plumbing_no_returns(native_function) + return_symint_overrides = [ + "_scaled_dot_product_flash_attention", + "_scaled_dot_product_cudnn_attention", + "_scaled_dot_product_flash_attention_quantized", + ] + if ( + not all(ret.type.is_tensor_like() for ret in returns) + and schema.name.unambiguous_name() not in return_symint_overrides + ): + return None + # in-place views need special handling + if "inplace_view" in native_function.tags: + return None + + if schema.kind() == SchemaKind.inplace: + return gen_vmap_inplace_plumbing(native_function) + + # Don't support these (mutable, out, scratch) + if schema.kind() != SchemaKind.functional: + return None + + results_var = "results" + cur_level_var = "cur_level" + + unwraps, unwrapped_arg_list = gen_unwraps(schema.arguments.flat_all, cur_level_var) + bdims_all_none_case = gen_case_where_all_bdims_are_none(sig, schema, cur_level_var) + + wrapped_returns = gen_returns(returns, cur_level_var, results_var) + return f"""\ +template +{sig.decl(name=schema.name.unambiguous_name() + "_generated_plumbing")} {{ + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "gen_vmap_plumbing"); + int64_t {cur_level_var} = maybe_layer->layerId(); +{textwrap.indent(bdims_all_none_case, " ")} +{textwrap.indent(unwraps, " ")} + auto {results_var} = batch_rule({", ".join(unwrapped_arg_list)}); + {wrapped_returns} +}}""" + + +@dataclass(frozen=True) +class ComputeBatchRulePlumbing: + @method_with_native_function + def __call__(self, f: NativeFunction) -> str | None: + result = gen_vmap_plumbing(f) + return result + + +def gen_all_vmap_plumbing(native_functions: Sequence[NativeFunction]) -> str: + body = "\n".join(list(mapMaybe(ComputeBatchRulePlumbing(), native_functions))) + return f""" +#pragma once +#include +#include + +namespace at {{ namespace functorch {{ + +{body} + +}}}} // namespace at::functorch +""" diff --git a/.venv/lib/python3.12/site-packages/torchgen/local.py b/.venv/lib/python3.12/site-packages/torchgen/local.py new file mode 100644 index 0000000000000000000000000000000000000000..d2f9965970009b10977bdb69849dea20d483b007 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/local.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +import threading +from contextlib import contextmanager +from typing import TYPE_CHECKING + + +if TYPE_CHECKING: + from collections.abc import Iterator + + +# Simple dynamic scoping implementation. The name "parametrize" comes +# from Racket. +# +# WARNING WARNING: LOOKING TO EDIT THIS FILE? Think carefully about +# why you need to add a toggle to the global behavior of code +# generation. The parameters here should really only be used +# for "temporary" situations, where we need to temporarily change +# the codegen in some cases because we cannot conveniently update +# all call sites, and are slated to be eliminated once all call +# sites are eliminated. If you don't have a plan for how to get there, +# DON'T add a new entry here. + + +class Locals(threading.local): + use_const_ref_for_mutable_tensors: bool | None = None + use_ilistref_for_tensor_lists: bool | None = None + + +_locals = Locals() + + +def use_const_ref_for_mutable_tensors() -> bool: + if _locals.use_const_ref_for_mutable_tensors is None: + raise AssertionError( + "need to initialize local.use_const_ref_for_mutable_tensors with " + "local.parametrize" + ) + return _locals.use_const_ref_for_mutable_tensors + + +def use_ilistref_for_tensor_lists() -> bool: + if _locals.use_ilistref_for_tensor_lists is None: + raise AssertionError( + "need to initialize local.use_ilistref_for_tensor_lists with local.parametrize" + ) + return _locals.use_ilistref_for_tensor_lists + + +@contextmanager +def parametrize( + *, use_const_ref_for_mutable_tensors: bool, use_ilistref_for_tensor_lists: bool +) -> Iterator[None]: + old_use_const_ref_for_mutable_tensors = _locals.use_const_ref_for_mutable_tensors + old_use_ilistref_for_tensor_lists = _locals.use_ilistref_for_tensor_lists + try: + _locals.use_const_ref_for_mutable_tensors = use_const_ref_for_mutable_tensors + _locals.use_ilistref_for_tensor_lists = use_ilistref_for_tensor_lists + yield + finally: + _locals.use_const_ref_for_mutable_tensors = ( + old_use_const_ref_for_mutable_tensors + ) + _locals.use_ilistref_for_tensor_lists = old_use_ilistref_for_tensor_lists diff --git a/.venv/lib/python3.12/site-packages/torchgen/model.py b/.venv/lib/python3.12/site-packages/torchgen/model.py new file mode 100644 index 0000000000000000000000000000000000000000..decf1a493dbca20a77d9733f5877ab1ff8dca615 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/model.py @@ -0,0 +1,3094 @@ +from __future__ import annotations + +import dataclasses +import itertools +import re +from dataclasses import dataclass +from enum import auto, Enum +from typing import TYPE_CHECKING +from typing_extensions import assert_never + +from torchgen.utils import NamespaceHelper, OrderedSet + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator, Sequence + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# DATA MODEL +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Some general principles for our data model. +# +# - Stop using C++ data types as the internal data representation +# format. Instead, the internal data structures are centered +# around JIT schema representation. This avoid a big problem +# with the old codegen where we read in all the types from +# native_functions.yaml and then immediately had to retranslate +# them into C++ types. +# +# - More semantic data representation. Instead of representing +# everything as dicts and strings, we define dataclasses for +# every interesting entity the code generation has to deal with. +# These dataclasses have strong semantic invariants: for example, +# we generally require them to roundtrip losslessly into the +# form they were parsed from. These structures are immutable +# and you're expected to populate information once during +# construction. + + +# Represent a source location; used for better error reporting +@dataclass(frozen=True) +class Location: + file: str + line: int + + def __str__(self) -> str: + return f"{self.file}:{self.line}" + + +# Valid values of the 'variants' field in native_functions.yaml +class Variant(Enum): + function = auto() + method = auto() + + +# Default kernel namespace +DEFAULT_KERNEL_NAMESPACE = "at::native" + +# NOTE: Keep the list in sync with `DispatchKey` in c10/core/DispatchKey.h +BACKEND_COMPONENTS = [ + "CPU", + "CUDA", + "HIP", + "XLA", + "MTIA", + "MPS", + "IPU", + "XPU", + "HPU", + "VE", + "Lazy", + "Meta", + "PrivateUse1", + "PrivateUse2", + "PrivateUse3", +] +FUNCTIONALITY_KEYS = [ + "", + "Quantized", + "Sparse", + "SparseCsr", + "NestedTensor", + "Autograd", +] + +# This list guards dispatches that can be used in derivatives.yaml +# For now we omit AutogradFunctionality and AutogradOther +AUTOGRAD_KEYS = ["AutogradNestedTensor"] + [ + "Autograd" + component for component in BACKEND_COMPONENTS +] + +FRAGMENT_NAMESPACES = {"quantized", "quantized_decomposed"} + + +# This doesn't have to be in sync with the header, it only needs to contain +# entries that we actually use in the codegen or want pyi entries for +class DispatchKey(Enum): + Undefined = 0 + CatchAll = Undefined + + FPGA = auto() + MAIA = auto() + Vulkan = auto() + Metal = auto() + MKLDNN = auto() + OpenGL = auto() + OpenCL = auto() + IDEEP = auto() + CustomRNGKeyId = auto() + MkldnnCPU = auto() + Sparse = auto() + SparseCsr = auto() + NestedTensor = auto() + Dense = auto() + + PythonTLSSnapshot = auto() + PreDispatch = auto() + PythonDispatcher = auto() + Python = auto() + FuncTorchDynamicLayerBackMode = auto() + ZeroTensor = auto() + Conjugate = auto() + Negative = auto() + BackendSelect = auto() + Named = auto() + AutogradOther = auto() + AutogradFunctionality = auto() + AutogradNestedTensor = auto() + Tracer = auto() + Autocast = auto() + AutocastCPU = auto() + AutocastCUDA = auto() + AutocastXPU = auto() + Batched = auto() + VmapMode = auto() + FuncTorchGradWrapper = auto() + FuncTorchBatched = auto() + BatchedNestedTensor = auto() + FuncTorchVmapMode = auto() + FuncTorchDynamicLayerFrontMode = auto() + Functionalize = auto() + TESTING_ONLY_GenericWrapper = auto() + TESTING_ONLY_GenericMode = auto() + + ADInplaceOrView = auto() + Autograd = auto() + CompositeImplicitAutograd = auto() + CompositeImplicitAutogradNestedTensor = auto() + CompositeExplicitAutograd = auto() + CompositeExplicitAutogradNonFunctional = auto() + FuncTorchBatchedDecomposition = auto() + + # BEGIN autogenerated + CPU = auto() + CUDA = auto() + HIP = auto() + XLA = auto() + MTIA = auto() + MPS = auto() + IPU = auto() + XPU = auto() + HPU = auto() + VE = auto() + Lazy = auto() + Meta = auto() + PrivateUse1 = auto() + PrivateUse2 = auto() + PrivateUse3 = auto() + QuantizedCPU = auto() + QuantizedCUDA = auto() + QuantizedHIP = auto() + QuantizedXLA = auto() + QuantizedMTIA = auto() + QuantizedMPS = auto() + QuantizedIPU = auto() + QuantizedXPU = auto() + QuantizedHPU = auto() + QuantizedVE = auto() + QuantizedLazy = auto() + QuantizedMeta = auto() + QuantizedPrivateUse1 = auto() + QuantizedPrivateUse2 = auto() + QuantizedPrivateUse3 = auto() + SparseCPU = auto() + SparseCUDA = auto() + SparseHIP = auto() + SparseXLA = auto() + SparseMTIA = auto() + SparseMPS = auto() + SparseIPU = auto() + SparseXPU = auto() + SparseHPU = auto() + SparseVE = auto() + SparseLazy = auto() + SparseMeta = auto() + SparsePrivateUse1 = auto() + SparsePrivateUse2 = auto() + SparsePrivateUse3 = auto() + SparseCsrCPU = auto() + SparseCsrCUDA = auto() + SparseCsrHIP = auto() + SparseCsrXLA = auto() + SparseCsrMTIA = auto() + SparseCsrMPS = auto() + SparseCsrIPU = auto() + SparseCsrXPU = auto() + SparseCsrHPU = auto() + SparseCsrVE = auto() + SparseCsrLazy = auto() + SparseCsrMeta = auto() + SparseCsrPrivateUse1 = auto() + SparseCsrPrivateUse2 = auto() + SparseCsrPrivateUse3 = auto() + NestedTensorCPU = auto() + NestedTensorCUDA = auto() + NestedTensorHIP = auto() + NestedTensorXLA = auto() + NestedTensorMTIA = auto() + NestedTensorMPS = auto() + NestedTensorIPU = auto() + NestedTensorXPU = auto() + NestedTensorHPU = auto() + NestedTensorVE = auto() + NestedTensorLazy = auto() + NestedTensorMeta = auto() + NestedTensorPrivateUse1 = auto() + NestedTensorPrivateUse2 = auto() + NestedTensorPrivateUse3 = auto() + AutogradCPU = auto() + AutogradCUDA = auto() + AutogradHIP = auto() + AutogradXLA = auto() + AutogradMTIA = auto() + AutogradMPS = auto() + AutogradIPU = auto() + AutogradXPU = auto() + AutogradHPU = auto() + AutogradVE = auto() + AutogradLazy = auto() + AutogradMeta = auto() + AutogradPrivateUse1 = auto() + AutogradPrivateUse2 = auto() + AutogradPrivateUse3 = auto() + # END autogenerated + + def __str__(self) -> str: + return self.name + + def lower(self) -> str: + return str(self).lower() + + @staticmethod + def parse(value: str) -> DispatchKey: + for k, v in DispatchKey.__members__.items(): + if k == value: + return v + raise AssertionError(f"unknown dispatch key {value}") + + +class _TorchDispatchModeKey(Enum): + FAKE = auto() + PROXY = auto() + FUNCTIONAL = auto() + + +def codegen_per_backend_entries() -> str: + r: list[str] = [] + for fk in FUNCTIONALITY_KEYS: + r.extend(f" {fk}{bc} = auto()" for bc in BACKEND_COMPONENTS) + return "\n".join(r) + + +for fk in FUNCTIONALITY_KEYS: + for bc in BACKEND_COMPONENTS: + if not hasattr(DispatchKey, fk + bc): + r = codegen_per_backend_entries() + print(r) + raise RuntimeError( + f"Missing {fk}{bc} from DispatchKey enum. Here is the autogenerated list we expect to have:\n\n{r}" + ) + + +STRUCTURED_DISPATCH_KEYS = { + DispatchKey.MPS, + DispatchKey.CUDA, + DispatchKey.CPU, + DispatchKey.XPU, + DispatchKey.MTIA, +} +UFUNC_DISPATCH_KEYS = {DispatchKey.CUDA, DispatchKey.CPU} + +# Set of supported dispatch keys +dispatch_keys = [ + DispatchKey.CPU, + DispatchKey.SparseCPU, + DispatchKey.SparseCsrCPU, + DispatchKey.MkldnnCPU, + DispatchKey.CUDA, + DispatchKey.MPS, + DispatchKey.XPU, + DispatchKey.SparseXPU, + DispatchKey.SparseCsrXPU, + DispatchKey.SparseCUDA, + DispatchKey.SparseCsrCUDA, + DispatchKey.SparseMPS, + DispatchKey.SparseCsrMPS, + DispatchKey.QuantizedCPU, + DispatchKey.QuantizedCUDA, + DispatchKey.CompositeImplicitAutograd, + DispatchKey.CompositeImplicitAutogradNestedTensor, + DispatchKey.CompositeExplicitAutograd, + DispatchKey.CompositeExplicitAutogradNonFunctional, + DispatchKey.NestedTensorCPU, + DispatchKey.NestedTensorCUDA, + DispatchKey.NestedTensorXPU, + DispatchKey.NestedTensorHPU, + # Meta is a magic key: it is automatically generated for structured + # kernels + DispatchKey.Meta, + DispatchKey.SparseMeta, + DispatchKey.SparseCsrMeta, + DispatchKey.QuantizedMeta, + DispatchKey.NestedTensorMeta, + DispatchKey.ZeroTensor, + DispatchKey.MTIA, +] + + +# Dispatch keys that "support all backends". These codegen slightly differently +# then backend specific keys. +def is_generic_dispatch_key(dk: DispatchKey) -> bool: + return dk in { + DispatchKey.CompositeExplicitAutograd, + DispatchKey.CompositeExplicitAutogradNonFunctional, + DispatchKey.CompositeImplicitAutograd, + DispatchKey.CompositeImplicitAutogradNestedTensor, + } + + +# CUDA specific dispatch keys +def is_cuda_dispatch_key(dk: DispatchKey) -> bool: + return dk in { + DispatchKey.CUDA, + DispatchKey.QuantizedCUDA, + DispatchKey.SparseCUDA, + DispatchKey.SparseCsrCUDA, + DispatchKey.NestedTensorCUDA, + DispatchKey.AutogradCUDA, + } + + +# XPU specific dispatcy keys +def is_xpu_dispatch_key(dk: DispatchKey) -> bool: + return dk in { + DispatchKey.XPU, + DispatchKey.QuantizedXPU, + DispatchKey.SparseXPU, + DispatchKey.SparseCsrXPU, + DispatchKey.NestedTensorXPU, + DispatchKey.AutogradXPU, + } + + +# Structured kernel generation is only supported for certain key types; +# otherwise use old-style +def is_structured_dispatch_key(dk: DispatchKey) -> bool: + return dk in STRUCTURED_DISPATCH_KEYS + + +def is_ufunc_dispatch_key(dk: DispatchKey) -> bool: + # For now, ufunc dispatch keys coincide with structured keys + return dk in UFUNC_DISPATCH_KEYS + + +dispatch_device_map = {is_cuda_dispatch_key: "cuda", is_xpu_dispatch_key: "xpu"} + + +# This is oddly named ScalarType and not DType for symmetry with C++ +class ScalarType(Enum): + Byte = auto() + Char = auto() + Short = auto() + Int = auto() + Long = auto() + Half = auto() + Float = auto() + Double = auto() + ComplexHalf = auto() + ComplexFloat = auto() + ComplexDouble = auto() + Bool = auto() + BFloat16 = auto() + Float8_e5m2 = auto() + Float8_e5m2fnuz = auto() + Float8_e4m3fn = auto() + Float8_e4m3fnuz = auto() + Float8_e8m0fnu = auto() + + def __str__(self) -> str: + return self.name + + @staticmethod + def maybe_parse(value: str) -> ScalarType | None: + for k, v in ScalarType.__members__.items(): + if k == value: + return v + return None + + @staticmethod + def parse(value: str) -> ScalarType: + mb_r = ScalarType.maybe_parse(value) + if mb_r is None: + raise AssertionError(f"unknown dtype {value}") + return mb_r + + @staticmethod + def parse_set(values: str) -> OrderedSet[ScalarType]: + dtypes: OrderedSet[ScalarType] = OrderedSet() + for value in values.split(", "): + if value in DTYPE_CLASSES: + dtypes.update(DTYPE_CLASSES[value]) + else: + dtypes.add(ScalarType.parse(value)) + return dtypes + + +DTYPE_CLASSES: dict[str, OrderedSet[ScalarType]] = {} +# NB: Integral doesn't include boolean +DTYPE_CLASSES["Integral"] = OrderedSet( + [ + ScalarType.Byte, + ScalarType.Char, + ScalarType.Int, + ScalarType.Long, + ScalarType.Short, + ] +) +# NB: Floating doesn't include low precision types +DTYPE_CLASSES["Floating"] = OrderedSet([ScalarType.Float, ScalarType.Double]) +DTYPE_CLASSES["Complex"] = OrderedSet( + [ScalarType.ComplexFloat, ScalarType.ComplexDouble] +) +DTYPE_CLASSES["All"] = DTYPE_CLASSES["Integral"] | DTYPE_CLASSES["Floating"] +DTYPE_CLASSES["AllAndComplex"] = DTYPE_CLASSES["All"] | DTYPE_CLASSES["Complex"] +DTYPE_CLASSES["FloatingAndComplex"] = ( + DTYPE_CLASSES["Floating"] | DTYPE_CLASSES["Complex"] +) + + +# Represents the valid entries for ufunc_inner_loop in native_functions.yaml. +# NB: if you add a new UfuncKey, you will teach torchgen.dest.ufunc how +# to process it. Most logic will ignore keys they don't understand, so your +# new key will get silently ignored until you hook in logic to deal with it. +class UfuncKey(Enum): + # These are low level keys that represent exactly one particular + # instantiation of the kernel produced by codegen + CUDAFunctor = auto() + CUDAFunctorOnOther = auto() + CUDAFunctorOnSelf = auto() + + CPUScalar = auto() + CPUVector = auto() + + # These are the ones users will usually specify, and + # implicitly "fill in" the low level keys + ScalarOnly = auto() # CUDA*, CPUScalar + Generic = auto() # CUDA*, CPU* + + def __str__(self) -> str: + return self.name + + @staticmethod + def parse(value: str) -> UfuncKey: + for k, v in UfuncKey.__members__.items(): + if k == value: + return v + raise AssertionError(f"unknown ufunc key {value}") + + +class DeviceCheckType(Enum): + NoCheck = 0 + ExactSame = 1 + + +class ViewSchemaKind(Enum): + aliasing = auto() + aliasing_inplace = auto() + non_aliasing = auto() + + +# The basic input to the code generation is native_functions.yaml. +# The name "native", BTW, comes from the distinction between native +# functions and legacy TH functions. The legacy TH functions are gone, +# but the "native" descriptor has stuck. +# +# NativeFunction models a single entry in native_functions.yaml. Its +# fields roughly correspond to what you would see in the YAML itself, +# but after canonicalization and parsing has occurred. +# +# You can see some of the overall design patterns for how we setup +# dataclasses in this class, but we will defer a complete discussion +# of this at FunctionSchema. +@dataclass(frozen=True) +class NativeFunction: + # The namespace for this operator. For example, if we have "at::add" + # then the namespace would be "at". This enables ops to be registered + # through the same DSL with a custom namespace. If not specified, the + # default namespace would be "at". + namespace: str + + # The function schema of the operator in question. This schema + # has been parsed; see FunctionSchema for more about its structure. + # (This type is quoted as we are forward referencing a type + # defined later in the file. I opted for this ordering of the + # classes for expository clarity.) + func: FunctionSchema + + # Whether or not to generate mutable tensor arguments like regular + # ones + use_const_ref_for_mutable_tensors: bool + + # Whether or not to omit automatic generation of a DeviceGuard + device_guard: bool + + # How to emit automatic generation of device check + device_check: DeviceCheckType + + # What python module to put the function in + python_module: str | None + + # TODO: figure out what this does + category_override: str | None + + # If no variants are specified in native_functions.yaml, this is + # assumed to be {'function'}. + variants: set[Variant] + + # Whether or not we should skip generating registrations for + # this kernel. This is a bit of a double-edged sword, as manual + # registrations don't participate in codegen-based selective build! + manual_kernel_registration: bool + + # Whether or not to skip generating TensorMethod/Functions bindings + # for this kernel. Technically, this doesn't actually skip generating + # the binding; instead, the binding gets generated to __dispatch_{funcname} + # so you can make use of the normal binding if you need it. + manual_cpp_binding: bool + + # The location in the YAML file were this native function entry was + # defined. This is for conveniently reporting error messages! + loc: Location + + # A list of operators that are expected to be auto-generated for this NativeFunction. + # Note: This list isn't actually directly used by the codegen to generate anything. + # Instead, the codegen figures out what operators to generate purely based off of + # function schema, and uses the autogen declarations to error check. + # We expect every NativeFunction that gets auto-generated be explicitly called out + # in native_functions.yaml + autogen: list[OperatorName] + + # If non-empty, this kernel is subject to ufunc codegen. + # Sorted by ufunc_key + ufunc_inner_loop: dict[UfuncKey, UfuncInnerLoop] + + # Whether or not this out functions is a "structured kernel". Structured + # kernels are defined a little differently from normal kernels; in + # particular, their shape checking logic is defined separately from + # the kernel. Only out functions can be structured; other functions + # delegate to the out function using the structured_delegate keyword. + # Every structured kernel must have at least an out and a functional + # variant. + structured: bool + + # Whether or not this non-out function is a structured kernel, defined + # in terms of the out kernel referenced by the string here. + structured_delegate: OperatorName | None + + # Only valid for structured kernels. Specifies alternative of what + # to inherit from when defining the meta class for the structured + # operator. This will usually be TensorIteratorBase. This also + # changes the semantics of set_output to call the parent class. + structured_inherits: str | None + + # Structured kernels can declare elements as "precomputed". These elements + # are returned by the meta function in one struct and passed to the impl + # function in lieu of certain kernel arguments that these precomputed + # elements supersede. Information about the names and types of these + # precomputed elements and how they correspond to kernel arguments is stored + # in this member, if applicable. + precomputed: Precompute | None + + # Argument names whose default should be excluded from the C++ interface. + # Intended for resolving overload ambiguities between signatures. + cpp_no_default_args: set[str] + + # Note [Abstract ATen methods] + # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + # An abstract ATen method is one whose dispatch differs between + # types. These are implemented in derived types (with a + # standard (throwing) definition in Type). A concrete ATen + # method is one which has the same dispatch for all types; + # we just implement it in the base Type. This is exposed + # in Declarations.yaml via a field named 'abstract'. + is_abstract: bool + + # Whether or not the NativeFunction contains a backend-agnostic kernel + has_composite_implicit_autograd_kernel: bool + has_composite_implicit_autograd_nested_tensor_kernel: bool + has_composite_explicit_autograd_kernel: bool + has_composite_explicit_autograd_non_functional_kernel: bool + + # Tags are used to describe semantic information about (groups of) operators, + # That aren't easily inferable directly from the operator's schema. + tags: set[str] + + # NB: The benefit of defining a dataclass is that we automatically get + # a constructor defined for all the fields we specify. No need + # to explicitly write it out. + + # We parse both the NativeFunction + backend-specific information about it, which it stored in a corresponding BackendIndex. + @staticmethod + def from_yaml( + ei: dict[str, object], + loc: Location, + valid_tags: set[str], + ignore_keys: set[DispatchKey] | None = None, + ) -> tuple[NativeFunction, dict[DispatchKey, dict[OperatorName, BackendMetadata]]]: + """ + Parse a NativeFunction from a dictionary as directly parsed + from native_functions.yaml + """ + e = ei.copy() + + funcs = e.pop("func") + if not isinstance(funcs, str): + raise AssertionError(f"not a str: {funcs}") + # only support one level of namespace. E.g., aten::add + namespace_helper = NamespaceHelper.from_namespaced_entity( + namespaced_entity=funcs, max_level=1 + ) + namespace = namespace_helper.get_cpp_namespace(default="aten") + func = FunctionSchema.parse(namespace_helper.entity_name) + + cpp_no_default_args_list = e.pop("cpp_no_default_args", []) + if not isinstance(cpp_no_default_args_list, list): + raise AssertionError( + f"cpp_no_default_args is not a list: {cpp_no_default_args_list}" + ) + cpp_no_default_args = set(cpp_no_default_args_list) + + use_const_ref_for_mutable_tensors = e.pop( + "use_const_ref_for_mutable_tensors", False + ) + if not isinstance(use_const_ref_for_mutable_tensors, bool): + raise AssertionError( + f"use_const_ref_for_mutable_tensors is not a bool: {use_const_ref_for_mutable_tensors}" + ) + + if use_const_ref_for_mutable_tensors: + if func.arguments.out: + raise AssertionError( + "see https://github.com/pytorch/pytorch/issues/145522" + ) + + variants_s = e.pop("variants", "function") + if not isinstance(variants_s, str): + raise AssertionError(f"variants is not a str: {variants_s}") + variants: set[Variant] = set() + for v in variants_s.split(", "): + if v == "function": + variants.add(Variant.function) + elif v == "method": + variants.add(Variant.method) + else: + raise AssertionError(f"illegal variant {v}") + + manual_kernel_registration = e.pop("manual_kernel_registration", False) + if not isinstance(manual_kernel_registration, bool): + raise AssertionError(f"not a bool: {manual_kernel_registration}") + + manual_cpp_binding = e.pop("manual_cpp_binding", False) + if not isinstance(manual_cpp_binding, bool): + raise AssertionError(f"not a bool: {manual_cpp_binding}") + + device_guard = e.pop("device_guard", True) + if not isinstance(device_guard, bool): + raise AssertionError(f"not a bool: {device_guard}") + + device_check_s = e.pop("device_check", None) + if not (device_check_s is None or isinstance(device_check_s, str)): + raise AssertionError(f"not a str: {device_check_s}") + if not ( + device_check_s is None or device_check_s in DeviceCheckType.__members__ + ): + raise AssertionError(f"illegal device_check: {device_check_s}") + device_check: DeviceCheckType + if device_check_s is None: + device_check = DeviceCheckType.ExactSame + else: + device_check = DeviceCheckType[device_check_s] + + structured = e.pop("structured", False) + if not isinstance(structured, bool): + raise AssertionError(f"not a bool: {structured}") + + structured_delegate_s = e.pop("structured_delegate", None) + if not ( + structured_delegate_s is None or isinstance(structured_delegate_s, str) + ): + raise AssertionError(f"not a str: {structured_delegate_s}") + if structured_delegate_s is not None and "::" in structured_delegate_s: + raise AssertionError( + "namespace is not supported in structured delegate," + " using the same namespace as the native function" + ) + structured_delegate: OperatorName | None = None + if structured_delegate_s is not None: + structured_delegate = OperatorName.parse(structured_delegate_s) + + structured_inherits = e.pop("structured_inherits", None) + if not (structured_inherits is None or isinstance(structured_inherits, str)): + raise AssertionError(f"not a str: {structured_inherits}") + if structured_inherits is not None and "::" in structured_inherits: + raise AssertionError( + "namespace is not supported in structured inherits," + " using the same namespace as the native function" + ) + + python_module = e.pop("python_module", None) + if not (python_module is None or isinstance(python_module, str)): + raise AssertionError(f"not a str: {python_module}") + if python_module is not None and Variant.method in variants: + raise AssertionError("functions in modules cannot be methods") + + category_override = e.pop("category_override", None) + if not (category_override is None or isinstance(category_override, str)): + raise AssertionError(f"not a str: {category_override}") + + precomputed_dict = e.pop("precomputed", None) + if precomputed_dict is not None and structured is not True: + raise AssertionError( + f"precomputed requires structured=True, got structured={structured}" + ) + precomputed = Precompute.parse(precomputed_dict) if precomputed_dict else None + + tags_inp = e.pop("tags", []) + if isinstance(tags_inp, str): + tags_inp = [tags_inp] + if not isinstance(tags_inp, list): + raise AssertionError(f"tags is not a list: {tags_inp}") + + # All aten ops generated by torchgen receive the pt2_compliant tag. + if namespace == "aten" and "pt2_compliant_tag" in valid_tags: + tags_inp.append("pt2_compliant_tag") + + # All out= ops receive the "out" tag. + if func.is_out_fn() and "out" in valid_tags: + tags_inp.append("out") + + # All inplace ops receive the "inplace" tag. + if func.name.name.inplace and "inplace" in valid_tags: + tags_inp.append("inplace") + + tags: set[str] = set() + for t in tags_inp: + if len(valid_tags) == 0: + raise AssertionError("valid_tags is empty") + # TODO: verify that the tag is valid and has an entry in tags.yaml + if t in valid_tags: + tags.add(t) + else: + raise AssertionError(f"illegal tag {t}") + + from torchgen.api import cpp + + raw_dispatch = e.pop("dispatch", None) + if not (raw_dispatch is None or isinstance(raw_dispatch, dict)): + raise AssertionError(f"dispatch is not a dict: {e}") + dispatch: dict[DispatchKey, BackendMetadata] = {} + num_dispatch_keys: int = 0 + if raw_dispatch is not None: + if manual_kernel_registration: + raise AssertionError( + "cannot specify both manual_kernel_registration and dispatch; with " + "manual registration, dispatch has no effect!" + ) + redundant_composite_implicit_autograd = False + for ks, v in raw_dispatch.items(): + if ks == "__line__": + continue # not worth tracking line numbers for dispatch entries + if not isinstance(ks, str): + raise AssertionError( + f"illegal dispatch key '{ks}' in {raw_dispatch}" + ) + if not isinstance(v, str): + raise AssertionError( + f"illegal dispatch value '{v}' in {raw_dispatch}" + ) + for k in ks.split(","): + dispatch_key = DispatchKey.parse(k.strip()) + num_dispatch_keys += 1 + + if ignore_keys and dispatch_key in ignore_keys: + continue + if dispatch_key not in dispatch_keys: + raise AssertionError( + f"Dispatch key {dispatch_key} of kernel {v} " + "is not a supported dispatch key." + ) + # We only allow at most 3 levels of namespace for kernels. + # We will append "native" to a custom kernel namespace. + namespace_helper = NamespaceHelper.from_namespaced_entity( + v, max_level=3 + ) + kernel_namespace = namespace_helper.get_cpp_namespace(default="at") + # Why is 'structured' included? External backends (e.g. + # XLA) opt into which ops are structured independently + # of which in-tree ops are structured + dispatch[dispatch_key] = BackendMetadata( + kernel=namespace_helper.entity_name, + structured=structured + and is_structured_dispatch_key(dispatch_key), + cpp_namespace=(kernel_namespace + "::native"), + ) + if ( + dispatch_key is DispatchKey.CompositeImplicitAutograd + and v == cpp.name(func) + ): + redundant_composite_implicit_autograd = True + + # We count the number of dispatch keys which have not been ignored to prevent a dispatch table + # in which all backend keys are ignored but necessarily kept, remaining compositeimplicit, + # from being treated as redundant. + if num_dispatch_keys == 1 and redundant_composite_implicit_autograd: + raise AssertionError( + "unnecessary dispatch table for this function; just delete the dispatch " + "key entirely" + ) + # if a function is a structured delegate, deleting the dispatch + # table is NOT semantics preserving + if not ( + structured_delegate + or dispatch.keys() != {DispatchKey.CompositeImplicitAutograd} + or dispatch[DispatchKey.CompositeImplicitAutograd].supports_symint() + or num_dispatch_keys != 1 + ): + raise AssertionError( + f"unexpected name for singleton CompositeImplicitAutograd dispatch entry: expected {cpp.name(func)} " + f"but got {dispatch[DispatchKey.CompositeImplicitAutograd]}. Rename your implementation to the expected " + "name, then delete the dispatch table" + ) + elif not structured and structured_delegate is None: + name = str(func.name.name) + if ( + name.startswith("new_") + or name.endswith("_like") + # TODO: maybe it's better to test the return + or ( + func.arguments.tensor_options + and not func.arguments.has_tensor_arg() + ) + ): + raise AssertionError( + f"expected {name} to have a CompositeExplicitAutograd " + "dispatch entry, but there was no dispatch table. Factory functions " + "should not have implicit dispatch as they should not be decomposed " + "for __torch_dispatch__" + ) + dispatch[DispatchKey.CompositeImplicitAutograd] = BackendMetadata( + cpp.name(func), structured=False, cpp_namespace=DEFAULT_KERNEL_NAMESPACE + ) + + composites_in_dispatch = [ + d + for d in dispatch + if d == DispatchKey.CompositeExplicitAutograd + or d == DispatchKey.CompositeExplicitAutogradNonFunctional + or d == DispatchKey.CompositeImplicitAutograd + or d == DispatchKey.CompositeImplicitAutogradNestedTensor + ] + + if not ( + len(composites_in_dispatch) <= 1 + or ( + len(composites_in_dispatch) == 2 + and ( + DispatchKey.CompositeExplicitAutogradNonFunctional + not in composites_in_dispatch + ) + and ( + DispatchKey.CompositeImplicitAutogradNestedTensor + in composites_in_dispatch + ) + ) + ): + raise AssertionError( + "cannot specify more than one of CompositeExplicitAutograd, CompositeExplicitAutogradNonFunctional, " + "or CompositeImplicitAutograd on a single kernel; each " + "strictly subsumes the other. If you wanted to provide an explicit autograd " + "implementation, specify CompositeExplicitAutograd; otherwise specify CompositeImplicitAutograd only" + ) + + autogen_str = e.pop("autogen", "") + if not isinstance(autogen_str, str): + raise AssertionError(f"autogen is not a str: {autogen_str}") + autogen = ( + [] + if autogen_str == "" + else [OperatorName.parse(x) for x in autogen_str.split(", ")] + ) + + raw_ufunc_inner_loop = e.pop("ufunc_inner_loop", {}) + ufunc_inner_loop = {} + if isinstance(raw_ufunc_inner_loop, str): + ufunc_inner_loop[UfuncKey.Generic] = UfuncInnerLoop.parse( + raw_ufunc_inner_loop, UfuncKey.Generic + ) + elif isinstance(raw_ufunc_inner_loop, dict): + for k, vo in raw_ufunc_inner_loop.items(): + if k == "__line__": + continue + if not isinstance(k, str): + raise AssertionError(f"ufunc_inner_loop key is not a str: {k}") + if not isinstance(vo, str): + raise AssertionError(f"ufunc_inner_loop value is not a str: {vo}") + ufunc_key = UfuncKey.parse(k) + ufunc_inner_loop[ufunc_key] = UfuncInnerLoop.parse(vo, ufunc_key) + else: + raise AssertionError( + f"ufunc_inner_loop not str or dict: {raw_ufunc_inner_loop}" + ) + # Program the BackendIndex for the implicit dispatch entry from ufunc + if ufunc_inner_loop: + if not structured: + raise AssertionError("ufunc must be structured") + + # Delay import ufunc here to avoid circular import issue + # See: https://github.com/pytorch/pytorch/issues/81294 + import torchgen.api.ufunc as ufunc + + for dispatch_key in UFUNC_DISPATCH_KEYS: + if dispatch_key in dispatch: + raise AssertionError( + f"ufunc should not have explicit dispatch entry for {dispatch_key}" + ) + dispatch[dispatch_key] = BackendMetadata( + kernel=ufunc.schema_kernel_name(func, dispatch_key), + structured=True, + cpp_namespace=DEFAULT_KERNEL_NAMESPACE, + ) + + if structured_delegate: + # Structured functions MUST have a dispatch table + is_abstract = True + else: + is_abstract = ( + dispatch.keys() != {DispatchKey.CompositeImplicitAutograd} + and dispatch.keys() + != {DispatchKey.CompositeImplicitAutogradNestedTensor} + and dispatch.keys() + != { + DispatchKey.CompositeImplicitAutograd, + DispatchKey.CompositeImplicitAutogradNestedTensor, + } + ) + + has_composite_implicit_autograd_kernel = ( + DispatchKey.CompositeImplicitAutograd in dispatch + ) + has_composite_implicit_autograd_nested_tensor_kernel = ( + DispatchKey.CompositeImplicitAutogradNestedTensor in dispatch + ) + has_composite_explicit_autograd_kernel = ( + DispatchKey.CompositeExplicitAutograd in dispatch + ) + has_composite_explicit_autograd_non_functional_kernel = ( + DispatchKey.CompositeExplicitAutogradNonFunctional in dispatch + ) + + # We aren't going to store dispatch metadata inline in NativeFunctions; + # instead it is separately indexed by backend (so other backends can + # add more dispatch entries after the fact). Reindex the individual + # metadata by OperatorName! + backend_metadata = {k: {func.name: v} for k, v in dispatch.items()} + + # don't care if it exists or not; make it easier to use this function + # with other yaml parsers that aren't setting __line__ in the dict + e.pop("__line__", None) + if e: + raise AssertionError(f"leftover entries: {e}") + + # Asserts that we can't do in post_init, because they rely on backend-specific info + if structured_delegate is not None: + for key in STRUCTURED_DISPATCH_KEYS: + if key in dispatch: + raise AssertionError( + f"if structured_delegate, then must not have {key} in dispatch dictionary " + "(it is delegated!)" + ) + + return ( + NativeFunction( + func=func, + use_const_ref_for_mutable_tensors=use_const_ref_for_mutable_tensors, + variants=variants, + structured=structured, + structured_delegate=structured_delegate, + structured_inherits=structured_inherits, + precomputed=precomputed, + autogen=autogen, + ufunc_inner_loop=ufunc_inner_loop, + manual_kernel_registration=manual_kernel_registration, + manual_cpp_binding=manual_cpp_binding, + python_module=python_module, + category_override=category_override, + device_guard=device_guard, + device_check=device_check, + loc=loc, + cpp_no_default_args=cpp_no_default_args, + is_abstract=is_abstract, + has_composite_implicit_autograd_kernel=has_composite_implicit_autograd_kernel, + has_composite_implicit_autograd_nested_tensor_kernel=has_composite_implicit_autograd_nested_tensor_kernel, + has_composite_explicit_autograd_kernel=has_composite_explicit_autograd_kernel, + has_composite_explicit_autograd_non_functional_kernel=has_composite_explicit_autograd_non_functional_kernel, + tags=tags, + namespace=namespace, + ), + backend_metadata, + ) + + def validate_unstructured(self) -> None: + # TODO: probably better to accumulate these errors and report them all + # at once + if self.structured: + raise AssertionError( + "This function is structured, but there was " + "no valid functional variant of it." + ) + if not self.structured_delegate: + raise AssertionError( + "This function delegates to another structured out function, " + "but no valid function was found (the delegate may not exist, or it has the wrong type)" + ) + + # __post_init__ functions in dataclasses can be used to do extra + # validation after construction. + # + # Notice that we don't do any type validation here. In fact, we + # rely exclusively on mypy to check if you've done types correctly! + # Validation is for nontrivial invariants that cannot be (conveniently) + # encoded in the type system. + def __post_init__(self) -> None: + if self.func.arguments.out: + if self.variants != {Variant.function}: + raise AssertionError( + "Native functions with out arguments MUST " + "be declared with only function variant; e.g., variants: function; " + "otherwise you will tickle a Python argument binding bug " + "(which usually manifests itself as the result variable being undefined.)" + ) + if self.structured: + if self.func.kind() != SchemaKind.out: + raise AssertionError( + "Put structured field on the out= " + "variant of a function; did you mean structured_delegate?" + ) + if not self.device_guard: + raise AssertionError( + "device_guard: False is not respected by structured kernels" + ) + if self.structured_delegate: + if self.func.kind() == SchemaKind.out: + raise AssertionError( + "structured_delegate field not allowed " + "on out= functions; did you mean structured?" + ) + if not self.device_guard: + raise AssertionError( + "device_guard: False is not respected by structured kernels" + ) + # Technically, with the asserts above, this assert is impossible to + # happen + if self.structured and self.structured_delegate: + raise AssertionError( + "Cannot have both structured and structured_delegate on function" + ) + defaulted_arguments = { + a.name for a in self.func.schema_order_arguments() if a.default is not None + } + invalid_args = set.difference(self.cpp_no_default_args, defaulted_arguments) + if len(invalid_args) != 0: + raise AssertionError(f"Invalid cpp_no_default_args: {invalid_args}") + if self.structured_inherits is not None: + if not self.structured: + raise AssertionError( + "structured_inherits must also imply structured: True" + ) + if str(self.func.name).startswith("_foreach"): + if self.device_check != DeviceCheckType.NoCheck: + raise AssertionError( + "foreach kernels fall back to slow path when tensor are on different devices, " + "device_check not allowed to be enabled" + ) + + # NB: if your function accidentally has rand/dropout/... in its name + # but is not actually random, feel free to amend this to special case + if ( + "rand" in str(self.func.name) + or ( + ( + "dropout" in str(self.func.name) + or any( + "dropout" in arg.name for arg in self.func.arguments.flat_all + ) + ) + # Backwards of dropout is typically deterministic + and "backward" not in str(self.func.name) + and str(self.func.name.name) != "_cudnn_init_dropout_state" + ) + or self.func.arguments.has_generator_arg() + ): + if "nondeterministic_seeded" not in self.tags: + raise AssertionError( + f"nondeterministic_seeded tag missing for {self.func.name}" + ) + + @property + def has_composite_kernel(self) -> bool: + return ( + self.has_composite_implicit_autograd_kernel + or self.has_composite_explicit_autograd_kernel + or self.has_composite_explicit_autograd_non_functional_kernel + ) or ( + self.has_composite_implicit_autograd_kernel + and self.has_composite_implicit_autograd_nested_tensor_kernel + ) + + @property + def is_view_op(self) -> bool: + rets = self.func.returns + is_non_mutating_view = len(rets) > 0 and any( + r.annotation is not None and not r.annotation.is_write for r in rets + ) + # See Note [resize_ in Functionalization] for more dtails + is_inplace_view = ( + "inplace_view" in self.tags + and str(self.func.name) != "resize_" + and str(self.func.name) != "resize_as_" + ) + is_wildcard_view = any( + inp.annotation is not None and "*" in inp.annotation.alias_set_after + for inp in self.func.schema_order_arguments() + ) + return is_non_mutating_view or is_inplace_view or is_wildcard_view + + @property + def view_schema_kind(self) -> ViewSchemaKind: + if self.is_view_op and self.func.name.name.inplace: + if "inplace_view" not in self.tags: + raise AssertionError(f"inplace_view tag missing for {self.func.name}") + return ViewSchemaKind.aliasing_inplace + if self.is_view_op: + return ViewSchemaKind.aliasing + else: + return ViewSchemaKind.non_aliasing + + @property + def root_name(self) -> str: + return self.func.name.name.base + + @property + def part_of_structured_group(self) -> bool: + return self.structured or self.structured_delegate is not None + + +class SchemaKind(Enum): + functional = auto() + inplace = auto() + out = auto() + mutable = auto() + scratch = auto() + + +# A structured kernel is guaranteed to have a functional and out variant, and +# optionally an inplace variant. +# +# NB: we create NativeFunctionsGroup *even if* the function is not +# actually annotated structured. Test the structured boolean to see if it +# actually is structured or not. +@dataclass(frozen=True) +class NativeFunctionsGroup: + functional: NativeFunction + inplace: NativeFunction | None + mutable: NativeFunction | None + out: NativeFunction + + @property + def structured(self) -> bool: + # Whether or not the operator has a meta() function. This information is backend-agnostic. + return self.out.structured + + def __post_init__(self) -> None: + test_sig: FunctionSchema = self.functional.func.signature() + for f in self.functions(): + if test_sig != f.func.signature(): + raise AssertionError( + "NativeFunctionsGroup constructed from two NativeFunctions " + f"that don't have matching signatures: {test_sig} != {f.func.signature()}" + ) + + if self.structured != f.part_of_structured_group: + raise AssertionError( + "NativeFunctionsGroup constructed from structured and unstructured " + f"functions: {self.out.func.name} and {f.func.name}" + ) + if self.functional.func.kind() != SchemaKind.functional: + raise AssertionError( + f"functional.func.kind() is {self.functional.func.kind()}, expected SchemaKind.functional" + ) + if self.out.func.kind() != SchemaKind.out: + raise AssertionError( + f"out.func.kind() is {self.out.func.kind()}, expected SchemaKind.out" + ) + if self.functional.namespace != self.out.namespace: + raise AssertionError( + f"functional.namespace ({self.functional.namespace}) != out.namespace ({self.out.namespace})" + ) + if self.inplace is not None: + if self.inplace.func.kind() != SchemaKind.inplace: + raise AssertionError( + f"inplace.func.kind() is {self.inplace.func.kind()}, expected SchemaKind.inplace" + ) + if self.inplace.namespace != self.functional.namespace: + raise AssertionError( + f"inplace.namespace ({self.inplace.namespace}) != functional.namespace ({self.functional.namespace})" + ) + + if self.mutable is not None: + if self.mutable.func.kind() != SchemaKind.mutable: + raise AssertionError( + f"mutable.func.kind() is {self.mutable.func.kind()}, expected SchemaKind.mutable" + ) + if self.mutable.namespace != self.functional.namespace: + raise AssertionError( + f"mutable.namespace ({self.mutable.namespace}) != functional.namespace ({self.functional.namespace})" + ) + # See Note [Overload Ambiguity With Functional Variants] + if not self.functional.func.name.name.functional_overload: + raise AssertionError( + "functional.func.name.name.functional_overload must be True when mutable is not None" + ) + + if self.structured: + # For now, structured composite kernels are not supported (need some + # design work to figure out how to make the composite case work) + if ( + self.out.has_composite_implicit_autograd_kernel + or self.out.has_composite_implicit_autograd_nested_tensor_kernel + ): + raise AssertionError("structured composite kernels are not supported") + + if self.functional.structured_delegate != self.out.func.name: + raise AssertionError( + f"{self.functional.func.name} delegates to {self.functional.structured_delegate} " + f"but its actual delegate is {self.out.func.name}" + ) + if self.inplace is not None: + if self.inplace.structured_delegate != self.out.func.name: + raise AssertionError( + f"{self.inplace.func.name} delegates to {self.inplace.structured_delegate} " + f"but its actual delegate is {self.out.func.name}" + ) + + generated_fns = sorted( + [str(f.func.name) for f in self.functions() if "generated" in f.tags] + ) + generated_fns_str = ", ".join(str(x) for x in generated_fns) + expected_generated_fns: set[str] = set() + for f in self.functions(): + expected_generated_fns.update(str(op) for op in f.autogen) + expected_generated_fns_str = ", ".join( + str(x) for x in sorted(expected_generated_fns) + ) + if len(expected_generated_fns) == 0 and len(generated_fns) > 0: + raise RuntimeError( + f"The codegen expects to be able to generate '{generated_fns_str}'." + " In order to generate them however, we expect them to be called out explicitly in the yaml." + f" Please add an 'autogen: {generated_fns_str}' line to the entry for {str(f.func.name)}" + ) + if expected_generated_fns_str != generated_fns_str: + raise RuntimeError( + f"The codegen expects to be able to generate '{generated_fns_str}'." + f" To do so, it expects a line: 'autogen: {generated_fns_str}'." + f" Instead, it found 'autogen: {expected_generated_fns_str}'" + ) + + def signature(self) -> FunctionSchema: + return self.out.func.signature() + + def functions(self) -> Iterator[NativeFunction]: + yield self.functional + yield self.out + if self.inplace is not None: + yield self.inplace + if self.mutable is not None: + yield self.mutable + + @property + def root_name(self) -> str: + return self.functional.root_name + + @staticmethod + def from_dict(d: dict[SchemaKind, NativeFunction]) -> NativeFunctionsGroup | None: + if not d: + raise AssertionError("from_dict called with empty dict") + if len(d) == 1: + return None + d = dict(d) # non-destructive updates please + functional = d.pop(SchemaKind.functional, None) + inplace = d.pop(SchemaKind.inplace, None) + mutable = d.pop(SchemaKind.mutable, None) + out = d.pop(SchemaKind.out, None) + if d: + raise AssertionError(f"unexpected keys in dict: {d}") + if functional is None: + raise AssertionError("functional variant is required") + # There are a few operators which only have functional/inplace variants; + # these don't count as structured for our purposes here + if out is None: + return None + # assuming all variants have the same namespace + return NativeFunctionsGroup( + functional=functional, + inplace=inplace, + mutable=mutable, + out=out, + ) + + +@dataclass(frozen=True) +class BackendMetadata: + # The name of the backend kernel, for a given operator + # for in-tree backends. These names come directly from the 'dispatch" field + # in native_functions.yaml. The dispatch entry is optional; in that + # case, that is equivalent to having written: + # + # dispatch: + # CompositeImplicitAutograd: $operator_name + kernel: str + # Whether or not the operator has a structured kernel implemented, for this particular backend. + # For in-tree backends, they all have the same value for structured- this is listed + # in native_functions.yaml. + # However, external backends like XLA can indendently toggle which ops are structured. + structured: bool + + # The namespace for kernels, default value: DEFAULT_KERNEL_NAMESPACE + cpp_namespace: str + + def supports_symint(self) -> bool: + return "_symint" in self.kernel + + +@dataclass(frozen=True) +class UfuncInnerLoop: + name: str + supported_dtypes: OrderedSet[ScalarType] + # key is stored here because it affects the semantics of name, + # so its helpful to have them together for further processing + ufunc_key: UfuncKey + + @staticmethod + def parse(value: str, ufunc_key: UfuncKey) -> UfuncInnerLoop: + name, supported_dtypes_str = value.split(" ", 1) + if supported_dtypes_str[0] != "(": + raise AssertionError( + f"expected '(' at start of supported_dtypes, got: {supported_dtypes_str}" + ) + if supported_dtypes_str[-1] != ")": + raise AssertionError( + f"expected ')' at end of supported_dtypes, got: {supported_dtypes_str}" + ) + supported_dtypes: OrderedSet[ScalarType] = OrderedSet() + for k in supported_dtypes_str[1:-1].split(", "): + supported_dtypes |= ScalarType.parse_set(k) + return UfuncInnerLoop( + name=name, supported_dtypes=supported_dtypes, ufunc_key=ufunc_key + ) + + +# BackendIndex represents a backend. +# The BackendIndex encodes per-operator information that is potentially different +# for each backend. The most obvious example is the name of the kernel +# (the 'dispatch' entry in native_functions.yaml). +# However, there can be other examples of different backends having different information. +# External backends can choose to opt their kernels to be structured independently from in-tree backends, +# which means that this information isn't inherently tied to a NativeFunction- it's different per backend. +@dataclass(frozen=True) +class BackendIndex: + dispatch_key: DispatchKey + # Mainly important for structured kernels, this determines which variant in the operator group is used to implement the others. + # All in-tree ops use out kernels, while XLA uses functional kernels. + use_out_as_primary: bool + # Whether the backend requires a device guard, and device checks. + # For in-tree backends, this is currently just CUDA/HIP + # For out-of-tree backends, this is currently just Intel XPU + device_guard: bool + # Whether the backend is in-tree (CPU/CUDA) or out-of-tree (XLA) + external: bool + # Other backend-specific information that is on a per-operator basis + index: dict[OperatorName, BackendMetadata] + + @staticmethod + def grow_index( + parent_index: dict[DispatchKey, dict[OperatorName, BackendMetadata]], + child_index: dict[DispatchKey, dict[OperatorName, BackendMetadata]], + ) -> None: + for k, v in child_index.items(): + for op_name, metadata in v.items(): + if op_name in parent_index[k]: + raise AssertionError( + f"duplicate operator {op_name} for dispatch key {k}" + ) + parent_index[k][op_name] = metadata + + def primary(self, g: NativeFunctionsGroup) -> NativeFunction: + if self.use_out_as_primary: + return g.out + else: + return g.functional + + def has_kernel(self, g: NativeFunction | NativeFunctionsGroup) -> bool: + m = self.get_kernel(g) + return m is not None + + def get_kernel( + self, g: NativeFunction | NativeFunctionsGroup + ) -> BackendMetadata | None: + if isinstance(g, NativeFunction): + f = g + elif isinstance(g, NativeFunctionsGroup): + f = self.primary(g) + else: + assert_never(g) + if f.func.name not in self.index: + return None + return self.index[f.func.name] + + def native_function_class_name(self) -> str | None: + if self.external: + return f"{str(self.dispatch_key)}NativeFunctions" + else: + # TODO: This discrepancy isn't required; we could also generated + # a class for in-tree kernels. It'll just require carefully + # updating every kernel definition + callsite of every in-tree aten kernel. + return None + + +# The function schema is undoubtedly the most important data structure +# in all of the codegen, as it defines the type signature for operators, +# and most of the code generation we do is type directed (e.g., look at +# the types, decide what to do. Think about how we code generate +# C++ function stubs!) +# +# We will also see in this class the general structure for how we model +# data in this code generation. A few notable properties to point out +# ahead of time: +# +# - These dataclasses are a *lossless* representation of the strings +# they are parsed from. In fact, we assert that given the +# information stored in the dataclass, we can exactly reconstruct +# the string we parsed from (and assert this inside the parse +# definition). There are a few reasons for this: +# +# - If you find that it is difficult to reconstruct the string +# given a dataclass, that is a clue that you are data +# representation is wrong. +# +# - It helps ensure that all relevant information is present +# in the dataclass, so that downstream users aren't tempted +# to reparse the original string to get some information +# that was omitted. +# +# - It forces you to represent the data in-memory in the same way +# it is recorded textually, which makes the dataclasses easier +# to understand for someone who is familiar with the +# textual format. (As a tradeoff, it means you have to model +# the syntax, even when it is inconvenient. But maybe that means +# the syntax is bad!) If you don't understand the internal +# representation, go look at the printing code to see how +# it maps onto the surface syntax! +# +# - It makes it easy to test the parsing code, as parsing code +# that is inconsistent with the string code will fail early +# and loudly. (As a tradeoff, it makes the parsing code a bit +# brittle (in particular, with trivial whitespace changes you +# are likely to trigger an assert error). +# +# In general, try to make the __str__ code as simple as possible +# (even at the cost of more complex parsing logic.) Additionally, +# try to minimize redundancy in data representation. (Precomputed +# fields are OK though: they are defined as a simple function on +# the canonical representation in question.) +# +# - These dataclasses are all frozen; once constructed their +# values never change. This makes it easy to tell where any +# given data came from: just look to the constructor. As a +# tradeoff, you can't easily "decorate" a schema with extra +# information from a post-facto analysis. We impose this +# restriction to make these structures more understandable. +# +@dataclass(frozen=True) +class FunctionSchema: + # The name of the operator this function schema describes. + name: OperatorName + + arguments: Arguments + + # TODO: Need to handle collisions with argument names at some point + returns: tuple[Return, ...] + + @property + def is_mutable(self) -> bool: + def is_write(arg: Argument) -> bool: + if arg.annotation is None: + return False + return arg.annotation.is_write + + # Corresponds to torch._C._FunctionSchema.is_mutable + # See aten/src/ATen/core/function_schema.h (keep these in sync) + return any(is_write(a) for a in self.arguments.flat_all) + + def schema_order_arguments(self) -> Iterator[Argument]: + return itertools.chain( + self.arguments.flat_positional, + self.arguments.flat_kwarg_only, + self.arguments.out, + ) + + decl_re = re.compile(r"(?P[^\(]+)\((?P.*)\) -> (?P.*)") + + @staticmethod + def parse(func: str) -> FunctionSchema: + # We should probably get a proper parser here + decls = FunctionSchema.decl_re.findall(func) + if len(decls) != 1: + raise AssertionError(f"Invalid function schema: {func}") + ops, args, return_decl = decls[0] + name = OperatorName.parse(ops) + arguments = Arguments.parse(args) + returns = parse_returns(return_decl) + r = FunctionSchema(name=name, arguments=arguments, returns=returns) + if str(r) != func: + raise AssertionError(f"{str(r)} != {func}") + return r + + def returns_are_aliased(self) -> bool: + # We assert earlier that schemas can't have a mix of aliased and non-aliased returns + return any( + r + for r in self.returns + if r.annotation is not None and r.annotation.is_write + ) + + def __post_init__(self) -> None: + for arg, ret in zip(self.arguments.out, self.returns): + if arg.annotation != ret.annotation: + raise AssertionError( + "Out arguments must have matching return Tensor; furthermore, " + f"the ith-argument needs to correspond to the ith return. " + f"arg.annotation={arg.annotation}, ret.annotation={ret.annotation}" + ) + # We also enforce that if you have any mutable, positional args, then they are not returned. + # This makes it easier to group these functions properly with their functional/out= counterparts. + for a in self.arguments.post_self_positional_mutable: + if any(a.annotation == r.annotation for r in self.returns): + raise AssertionError( + f"If you have a schema with mutable positional args, we expect them to not be returned. schema: {str(self)}" + ) + # Invariant: we expect out arguments to appear as keyword arguments in the schema. + # This means that all mutable returns should be aliased to a keyword argument + # (except for "self", which we explicitly don't treat as an out argument because of its use in methods) + # See Note [is_out_fn] + out_and_self = list(self.arguments.out) + [ + arg for arg in self.arguments.flat_positional if arg.name == "self" + ] + mutable_returns = [ + ret + for ret in self.returns + if ret.annotation is not None and ret.annotation.is_write + ] + immutable_returns = [ + ret + for ret in self.returns + if ret.annotation is None or not ret.annotation.is_write + ] + # Some assertions: We don't want any functions with a return type of "-> (Tensor(a!), Tensor)", + # because: + # (1) It's more annoying to handle properly + # (2) It's unnecessary - you can't method-chain on the first (mutated) output because it's part of a tuple. + # Instead, we expect the (a!) argument to not be returned. + if not (len(mutable_returns) == 0 or len(immutable_returns) == 0): + raise AssertionError( + f"NativeFunctions must have either only mutable returns, or only immutable returns. Found: {str(self)}" + ) + for ret in mutable_returns: + if not any(ret.annotation == arg.annotation for arg in out_and_self): + raise AssertionError( + 'All mutable returns must be aliased either to a keyword argument, or to "self". ' + "Did you forget to mark an out argument as keyword-only?" + ) + if self.arguments.out: + # out= ops that return their mutable inputs are only really useful for method chaining. + # And method chaining is only really useful if the thing you're returning is a plain Tensor. + # So ideally, we'd enforce that out= ops with a single plain mutable tensor should return the tensor, + # and all other types of out= op schemas should return void. + # There are a bunch of existing out= ops that return tuples of tensors though, so we're stuck with allowing that. + if any(a.type != BaseType(BaseTy.Tensor) for a in self.arguments.out): + if len(self.returns) != 0: + raise AssertionError( + "out= ops that accept tensor lists as out arguments " + "are expected to have no return type (since you can't do method chaining on them)" + ) + else: + # mutable keyword arguments whose name has _scratch_ prefix are + # scratch tensors for memory planning and should not be returned + non_scratch_out_args = len( + [ + arg + for arg in self.arguments.out + if not arg.name.startswith("_scratch_") + ] + ) + if non_scratch_out_args != len(self.returns): + raise AssertionError( + f"Must return as many arguments as there are out arguments, or no return at all. " + f"Got {non_scratch_out_args} non-scratch out args and {len(self.returns)} returns" + ) + + if self.name.name.inplace: + self_a = self.arguments.self_arg + if not ( + self_a + and self_a.argument.annotation + and self_a.argument.annotation.is_write + ): + raise AssertionError( + f"Inplace op {self.name} must have a self argument with a mutable annotation" + ) + if self_a.argument.type == BaseType(BaseTy.Tensor): + # All inplace ops with an ordinary `Tensor self` argument should return self, + # to allow for method chaining. + if not ( + len(self.returns) == 1 + and self.returns[0].annotation == self_a.argument.annotation + ): + raise AssertionError( + f"Inplace op {self.name} with Tensor self must return self" + ) + else: + # You can't method chain on non-tensor self arguments though (like a list[Tensor]) + # so in all other cases we expect the return type to be none. + if len(self.returns) != 0: + raise AssertionError( + f"Inplace op {self.name} with non-Tensor self must have no returns" + ) + + if self.arguments.tensor_options is not None: + if self.kind() != SchemaKind.functional: + raise AssertionError( + "Found an operator that is not functional or out variant, but has tensor options arguments." + "This is not allowed- tensor options arguments are only allowed for factory functions." + f"schema: {str(self)}" + ) + if self.is_functional_fn(): + if self.kind() != SchemaKind.functional: + raise AssertionError( + "Found an operator that is not functional, but its overload contains the string 'functional'." + "This is a special keyword in the codegen, please use a different overload name." + f"schema: {str(self)}" + ) + + def is_functional_fn(self) -> bool: + return "functional" in self.name.overload_name + + def is_out_fn(self) -> bool: + # Note [is_out_fn] + # + # out functions are the variants which take an explicit out= argument + # to populate into. We need to know if a schema corresponds to an + # out function for several reasons: + # + # - They codegen differently in C++ API + # - codegen to at::add_out rather than at::add + # - out argument is moved to front of C++ argument list + # + # out functions are DEFINED to be any function with a keyword-only + # argument that is mutable. In principle, this could lead to a + # false positive if you define a function that mutates a + # kwarg only argument, but this isn't the "true" output of this + # function. A more robust definition that would work in this + # case would also look at: + # + # - The output types. Out functions take in the arguments + # they mutate and then return them again; this is sort + # of "definitionally" what makes something an out function. + # Historically, we DO check this for consistency. + # - Correspondence with pure variant. An out function + # should have a signature equivalent to its pure variant, + # but just with extra kwargs for the output elements. This + # is difficult to actually check for and historically + # we only do this check in tools/ + return bool(self.arguments.out) + + def kind(self) -> SchemaKind: + """ + What kind of schema is this? A functional schema is one + that returns a newly allocated output; an inplace schema + modifies the self argument inplace; an out schema writes + the result into an explicitly provided out argument. + """ + is_out = bool(self.arguments.out) + is_scratch = bool( + [arg for arg in self.arguments.out if arg.name.startswith("_scratch_")] + ) + is_inplace = self.name.name.inplace + is_mutable = any( + a.annotation is not None and a.annotation.is_write + for a in self.arguments.post_self_positional + ) + if is_out and is_inplace: + raise AssertionError("A schema cannot be both out= and inplace") + # out= and inplace schemas can also have post_self_positional mutable args, + # but we give precedence to out= and inplace when deciding the schema kind. + # Tradeoff: we probably don't want to have to teach codegen that looks at inplace ops + # to also worry about mutable post_self_positional arguments, + # but it seems like a much bigger lift to classify them has having a new schema kind. + # The number of ops that fit in this strange category is small enough that + # we can probably manually write code for them instead of forcing the codegen to handle them. + if is_inplace: + return SchemaKind.inplace + elif is_scratch: + if not is_out: + raise AssertionError( + "invariant: all scratch operators are expected to be out= operators too" + ) + return SchemaKind.scratch + elif is_out: + if is_scratch: + raise AssertionError( + "We should not categorize a scratch op as an out variant. Check if the order of if statements are expected!" + ) + return SchemaKind.out + elif is_mutable: + return SchemaKind.mutable + else: + return SchemaKind.functional + + # For every return: + # - If the return aliases an input, we return the input name + # - Otherwise, we return None. + # If return names were enforced to be consistent with aliasing information, then we wouldn't need this. + def aliased_return_names(self) -> list[str | None]: + outs: list[str | None] = [] + for r in self.returns: + aliased_args = [ + a + for a in self.arguments.flat_all + if a.annotation is not None and a.annotation == r.annotation + ] + if len(aliased_args) == 0: + outs.append(None) + elif len(aliased_args) == 1: + outs.append(aliased_args[0].name) + else: + aliased_names = ", ".join(a.name for a in aliased_args) + raise AssertionError( + f"Found a return ({r.name})that aliases multiple inputs ({aliased_names})" + ) + return outs + + def signature( + self, + *, + strip_default: bool = False, + strip_view_copy_name: bool = False, + keep_return_names: bool = False, + ) -> FunctionSchema: + """ + Certain schemas are 'related', in that they are simply + inplace/out/functional versions of the same function. This method + factors these schemas into the "core" functional signature which + is equal across all versions. + + Here is what normalization happens to the schema to convert + it to a signature: + - The overload name is stripped (name is retained, since + it expresses semantic content about what the function does) + - Inplace is set False + - Out arguments are stripped + - Mutable post_self_positional args are converted to returns + - Mutability annotations are stripped (this is sound + because you cannot overload on mutability annotation) + - Return names are stripped since they are not overloadable and + some variants have return names but some not + - TensorOptions are dropped + because out= variants of factory functions don't include them + (and we want to be able to pair up factory functions with their out variants) + + Finally, we want to be able to pair up related "view" and their + corresponding "view_copy" operators. We do this by optionally + stripping the trailing "_copy" from the base name. + + Example of a mutable op before and after: + + f.func (Mutable operator): + _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask) # noqa: B950 + + f.func (Corresponding functional operator): + _fused_moving_avg_obs_fq_helper.functional(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor running_min, Tensor running_max, Tensor scale, Tensor zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask, Tensor running_min_out, Tensor running_max_out, Tensor scale_out, Tensor zero_point_out) # noqa: B950 + + f.func.signature() output: + _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor running_min, Tensor running_max, Tensor scale, Tensor zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor) # noqa: B950 + """ + + def strip_ret_annotation(r: Return) -> Return: + return Return( + name=r.name if keep_return_names else None, + type=r.type, + annotation=None, + ) + + base_name = self.name.name.base + if strip_view_copy_name: + if base_name.endswith("_copy"): + base_name = base_name.replace("_copy", "") + elif base_name.endswith("_scatter"): + base_name = base_name.replace("scatter", "inverse") + + # find mutable inputs that are not originally returned, and convert them to returns + returns_from_mutable_inputs = tuple( + # When we're grouping functions we strip the return names, + # but when we're generating the actual functional variants then we follow + # a convention for what to name the returns + Return( + name=f"{a.name}_out" if keep_return_names else None, + type=a.type, + annotation=None, + ) + for a in itertools.chain( + # Order is important here (otherwise e.g. inplace with mutable args + # and out= with mutable args won't have the same signature) + ( + [self.arguments.self_arg.argument] + if self.arguments.self_arg is not None + else [] + ), + self.arguments.out, + self.arguments.post_self_positional, + ) + if a.annotation is not None + and a.annotation.is_write + and not any(a.annotation == r.annotation for r in self.returns) + ) + original_returns = tuple(map(strip_ret_annotation, self.returns)) + # Ordering is important here. We expect the "mutable input" returns to come last. + returns = original_returns + returns_from_mutable_inputs + + args_sig = self.arguments.signature(strip_default=strip_default) + # See Note [bernoulli.p schema] + if str(self.name) == "bernoulli.p": + args_sig = Arguments.parse(str(args_sig).replace("float p", "float p=0.5")) + + return FunctionSchema( + name=OperatorName( + name=BaseOperatorName( + base=base_name, + inplace=False, + dunder_method=self.name.name.dunder_method, + ), + overload_name="", # stripped + ), + arguments=args_sig, + returns=returns, + ) + + def view_signature(self) -> FunctionSchema: + return self.signature(strip_view_copy_name=True) + + def with_name(self, name: OperatorName) -> FunctionSchema: + return FunctionSchema( + name=name, + arguments=self.arguments, + returns=self.returns, + ) + + @property + def modifies_arguments(self) -> bool: + return self.kind() in [SchemaKind.inplace, SchemaKind.out, SchemaKind.mutable] + + def has_symint(self) -> bool: + return self.arguments.has_symint_arg() + + def __str__(self) -> str: + all_arguments_str = str(self.arguments) + if len(self.returns) == 1: + returns = str(self.returns[0]) # omit parentheses + else: + returns = "(" + ", ".join(map(str, self.returns)) + ")" + return f"{self.name}({all_arguments_str}) -> {returns}" + + +# Here is the rest of the data model, described more briefly. + + +# Simplified version for what actually shows up in built-ins. +# Look at alias_info.h for expanded syntax. If you need the structure, +# you also need to make this structure recursive so it can be lined +# up with the type components too. For primitives this isn't really +# necessary +@dataclass(frozen=True) +class Annotation: + # Typically only has one element. Not actually a set so + # we can conveniently assume it is canonically ordered + alias_set: tuple[str, ...] + is_write: bool + alias_set_after: tuple[str, ...] + + @staticmethod + def parse(ann: str) -> Annotation: + # TODO: implement a proper parser if this gets more ugly + # Regex Explanation: + # Example: "a! -> a|b" + # Group #1: alias before optional '|', required. Matches the first + # character 'a' in the example + # Group #2: optional alias set after optional '|', matches empty string + # in the example + # Group #3: optional "is write" flag, matches '!' in the example. + # Group #4: optional section containing arrow, matches " -> a|b" in the + # example. + # Group #5: optional alias after set, supports wildcard, matches "a|b" + # in the example. + # Group #6: optional sub-section of alias after set, matches "|b" in the + # example. + m = re.match(r"^([a-z])(\|[a-z])*(!?)( -> (\*|[a-z](\|[a-z])*))?$", ann) + + if m is None: + raise AssertionError(f"unrecognized alias annotation {ann}") + before_alias = m.group(1) + (m.group(2) if m.group(2) else "") + alias_set = tuple(before_alias.split("|")) + is_write = m.group(3) == "!" + if is_write and len(alias_set) > 1: + raise AssertionError( + f"alias set larger than 1 is not mutable, got {ann} instead." + ) + after_set = tuple(m.group(5).split("|")) if m.group(5) else () + if len(before_alias) > 1 and len(after_set) > 1: + raise AssertionError( + f"before alias set and after alias set cannot be larger than 1 at the same time, got {ann} instead." + ) + r = Annotation( + alias_set=alias_set, is_write=is_write, alias_set_after=after_set + ) + if str(r) != ann: + raise AssertionError(f"{r} != {ann}") + return r + + def __str__(self) -> str: + alias_set = "|".join(self.alias_set) + if self.is_write: + alias_set = f"{alias_set}!" + alias_set_after = "|".join(self.alias_set_after) + if alias_set_after: + alias_set = f"{alias_set} -> {alias_set_after}" + return alias_set + + +# The base class for the type system. This is also loosely modeled +# off of jit_type.h, but we've simplified the hierarchy to focus +# in on the aspects of the type system that matter for code generation +# (for example, there's no SingleElementType subclass anymore). +# You never actually construct a Type; usually it's going to be one +# of the subclasses. If Python had ADTs this would be one! +@dataclass(frozen=True) +class Type: + @staticmethod + def parse(t: str) -> Type: + r = Type._parse(t) + if str(r) != t: + raise AssertionError(f"{r} != {t}") + return r + + @staticmethod + def _parse(t: str) -> Type: + m = re.match(r"^(.+)\?$", t) + if m is not None: + return OptionalType(Type.parse(m.group(1))) + m = re.match(r"^(.+)\[([0-9]+)?\]$", t) + if m is not None: + size = int(m.group(2)) if m.group(2) is not None else None + return ListType(elem=Type.parse(m.group(1)), size=size) + + # '__torch__.torch.classes.' is the prefix for custom class + m = re.match(r"^__torch__\.torch\.classes\.([a-zA-Z0-9_.]+)$", t) + if m is not None: + return CustomClassType(m.group(1)) + try: + return BaseType(BaseTy[t]) + except KeyError as e: + raise RuntimeError(f"unrecognized type {t}") from e + + def __str__(self) -> str: + raise NotImplementedError + + # WARNING: These concepts are not very well-defined. For example, + # is "int?" nullable? How about "int?[]". They are defined + # so we can conveniently generate legacy Declarations.yaml but + # really we should probably just remove these at some point + + def is_base_ty_like(self, base_ty: BaseTy) -> bool: + raise NotImplementedError + + def is_tensor_like(self) -> bool: + return self.is_base_ty_like(BaseTy.Tensor) + + def is_generator_like(self) -> bool: + return self.is_base_ty_like(BaseTy.Generator) + + def is_symint_like(self) -> bool: + return self.is_base_ty_like(BaseTy.SymInt) + + def is_nullable(self) -> bool: + raise NotImplementedError + + def is_list_like(self) -> ListType | None: + raise NotImplementedError + + +# Base types are simple, atomic types with no further structure +class BaseTy(Enum): + Generator = auto() + ScalarType = auto() + Tensor = auto() + int = auto() + DimVector = auto() + float = auto() + str = auto() + bool = auto() + Layout = auto() + Device = auto() + DeviceIndex = auto() + Scalar = auto() + MemoryFormat = auto() + QScheme = auto() + Storage = auto() + Stream = auto() + SymInt = auto() + SymBool = auto() + GraphModule = auto() + + +@dataclass(frozen=True) +class BaseType(Type): + name: BaseTy + + def __str__(self) -> str: + return f"{self.name.name}" + + def is_base_ty_like(self, base_ty: BaseTy) -> bool: + return self.name == base_ty + + def is_nullable(self) -> bool: + return False + + def is_list_like(self) -> ListType | None: + return None + + def is_symint_like(self) -> bool: + return self.name == BaseTy.SymInt + + +# Optional types may be specified, or may also be validly given None +@dataclass(frozen=True) +class OptionalType(Type): + elem: Type + + def __str__(self) -> str: + return f"{self.elem}?" + + def is_base_ty_like(self, base_ty: BaseTy) -> bool: + return self.elem.is_base_ty_like(base_ty) + + def is_symint_like(self) -> bool: + return self.elem.is_symint_like() + + def is_nullable(self) -> bool: + return True + + def is_list_like(self) -> ListType | None: + return self.elem.is_list_like() + + +# A type representing a PyTorch custom class +@dataclass(frozen=True) +class CustomClassType(Type): + class_name: str + + def __str__(self) -> str: + """ + Return the class name will prefix __torch__.torch.classes + """ + return f"__torch__.torch.classes.{self.class_name}" + + def is_base_ty_like(self, base_ty: BaseTy) -> bool: + return False + + def is_symint_like(self) -> bool: + return False + + def is_nullable(self) -> bool: + """ + Assume a custom class is not nullable. + """ + return False + + def is_list_like(self) -> ListType | None: + return None + + +# List types specify that we may have multiples of an element. We +# also support explicit sizes on list types, but these have +# some nontrivial semantics! (However, for C++ API purposes, explicit +# sizes are mostly erased from the type system.) +# +# DANGER WILL ROBINSON: C++ elaboration depends on elem type; e.g., +# int[] elaborates differently than bool[3]! +@dataclass(frozen=True) +class ListType(Type): + elem: Type + size: int | None + + def __str__(self) -> str: + size = f"{self.size}" if self.size else "" + return f"{self.elem}[{size}]" + + def is_base_ty_like(self, base_ty: BaseTy) -> bool: + return self.elem.is_base_ty_like(base_ty) + + def is_symint_like(self) -> bool: + return self.elem.is_symint_like() + + def is_nullable(self) -> bool: + return self.elem.is_nullable() + + def is_list_like(self) -> ListType | None: + return self + + +@dataclass(frozen=True) +class Argument: + # NB: I didn't put kwarg_only as a boolean field here, unlike + # c10::Argument, so that printing works correctly + + name: str + type: Type + default: str | None + + # The semantics of the annotation field are a little strange. + # + # Alias annotations parametrize Tensors (since Tensors are the only things + # that can alias.) This motivates why I write Tensor(a!)? (and not, for + # example, Tensor?(a!)), because the (a!) describes aliasing on the tensor, + # which may be optional (i.e., the alias annotation should bind first to + # Tensor, before the optional postfix annotation). + # + # However, despite being a property of Tensor, we (and c10::Argument) + # store the annotation at the top level of the Argument, rather than + # inside the embedded Tensor type. In the C++ version of this + # class, we then go through great lengths to mimic the type + # structure in the annotation structure so we can correlate + # annotations with types. + # + # Now, it turns out, in all applications in code generation, the + # structure of annotated types is very simple. So we just hard + # code it here. But if we ever do get anything more complex, this + # model will have to change! + annotation: Annotation | None + + @property + def alias_info(self) -> Annotation | None: + return self.annotation + + @staticmethod + def parse(arg: str) -> Argument: + name: str + default: str | None + if " " not in arg: + raise AssertionError(f"illegal argument '{arg}'") + if "=" in arg: + if arg.count("=") != 1: + raise AssertionError(f"illegal argument with default value: '{arg}'") + type_and_annot_and_name, default = arg.split("=") + type_and_annot, name = type_and_annot_and_name.rsplit(" ", 1) + name_and_default = f"{name}={default}" + else: + type_and_annot, name_and_default = arg.rsplit(" ", 1) + name = name_and_default + default = None + # TODO: deduplicate annotation matching with Return + match = re.match(r"Tensor\((.+)\)(.*)", type_and_annot) + annotation: Annotation | None + if match: + # If you update this, make sure the __str__ still works too + if match.group(2) not in ["", "?", "[]"]: + raise AssertionError( + f"unrecognized alias analysis form with Tensor: {match.group(2)}" + ) + type_s = "Tensor" + match.group(2) + annotation = Annotation.parse(match.group(1)) + else: + type_s = type_and_annot + annotation = None + type = Type.parse(type_s) + r = Argument( + name=name, + type=type, + default=default, + annotation=annotation, + ) + if str(r) != arg: + raise AssertionError(f"{str(r)} != {arg}") + return r + + @property + def is_write(self) -> bool: + return self.annotation is not None and self.annotation.is_write + + def __str__(self) -> str: + type = f"{self.type}" + if self.annotation: + if type not in ["Tensor", "Tensor?", "Tensor[]"]: + raise AssertionError(f"annotation on non-Tensor type: {type}") + type = type.replace("Tensor", f"Tensor({self.annotation})") + if self.name is None: + return type + else: + mb_default = "" + if self.default: + mb_default = f"={self.default}" + return f"{type} {self.name}{mb_default}" + + +@dataclass(frozen=True) +class Return: + name: str | None + type: Type + annotation: Annotation | None + + @property + def alias_info(self) -> Annotation | None: + return self.annotation + + @staticmethod + def parse(arg: str) -> Return: + name: str | None + if " " in arg: + type_and_annot, name = arg.rsplit(" ", 1) + else: + type_and_annot = arg + name = None + match = re.match(r"Tensor\((.+)\)(.*)", type_and_annot) + annotation: Annotation | None + if match: + # If you update this, make sure the __str__ still works too + if match.group(2) not in ["", "?", "[]"]: + raise AssertionError( + f"unrecognized alias analysis form with Tensor: {match.group(2)}" + ) + type_s = "Tensor" + match.group(2) + annotation = Annotation.parse(match.group(1)) + else: + type_s = type_and_annot + annotation = None + type = Type.parse(type_s) + r = Return( + name=name, + type=type, + annotation=annotation, + ) + if str(r) != arg: + raise AssertionError(f"{str(r)} != {arg}") + return r + + @property + def is_write(self) -> bool: + return self.annotation is not None and self.annotation.is_write + + def __str__(self) -> str: + type = f"{self.type}" + if self.annotation: + if type not in ["Tensor", "Tensor?", "Tensor[]"]: + raise AssertionError(f"annotation on non-Tensor type: {type}") + type = type.replace("Tensor", f"Tensor({self.annotation})") + if self.name is None: + return type + else: + return f"{type} {self.name}" + + +# Represents the self argument for functions that may be methods +@dataclass(frozen=True) +class SelfArgument: + argument: Argument + + +# Bundle of arguments that represent a TensorOptions. This is mostly +# relevant for the public C++ API but we bake it into the core data +# model because other APIs often have to interact with it +@dataclass(frozen=True) +class TensorOptionsArguments: + dtype: Argument + layout: Argument + device: Argument + pin_memory: Argument + + def all(self) -> Sequence[Argument]: + return [self.dtype, self.layout, self.device, self.pin_memory] + + +@dataclass(frozen=True) +class Arguments: + # pre_self_positional is usually empty, but is notably non-empty + # for where.self, where the condition argument comes before the + # self argument + pre_self_positional: tuple[Argument, ...] + self_arg: SelfArgument | None + post_self_positional: tuple[Argument, ...] + + pre_tensor_options_kwarg_only: tuple[Argument, ...] + tensor_options: TensorOptionsArguments | None + # post_tensor_options is typically memory format, which should be + # part of tensor options but isn't right now, and is usually + # placed after the tensor options arguments + post_tensor_options_kwarg_only: tuple[Argument, ...] + + # Unlike in the previous codegen, we have factored out 'out' arguments + # in the canonical representation, removing them from kwarg + # arguments. This choice is justified by numerous downstream + # transformations which treat out arguments specially; additionally, + # you can see that canonicity is not violated! + out: tuple[Argument, ...] # these are also kwarg-only + + @property + def flat_non_out(self) -> Sequence[Argument]: + ret: list[Argument] = [] + ret.extend(self.flat_positional) + ret.extend(self.flat_kwarg_only) + return ret + + @property + def flat_positional(self) -> Sequence[Argument]: + ret: list[Argument] = [] + ret.extend(self.pre_self_positional) + if self.self_arg is not None: + ret.append(self.self_arg.argument) + ret.extend(self.post_self_positional) + return ret + + @property + def post_self_positional_mutable(self) -> Sequence[Argument]: + return [a for a in self.post_self_positional if a.is_write] + + # NB: doesn't contain out arguments + @property + def flat_kwarg_only(self) -> Sequence[Argument]: + ret: list[Argument] = [] + ret.extend(self.pre_tensor_options_kwarg_only) + if self.tensor_options is not None: + ret.extend(self.tensor_options.all()) + ret.extend(self.post_tensor_options_kwarg_only) + return ret + + @property + def flat_all(self) -> Sequence[Argument]: + ret: list[Argument] = [] + ret.extend(self.flat_positional) + ret.extend(self.flat_kwarg_only) + ret.extend(self.out) + return ret + + @property + def non_out( + self, + ) -> Sequence[Argument | SelfArgument | TensorOptionsArguments]: + ret: list[Argument | SelfArgument | TensorOptionsArguments] = [] + ret.extend(self.positional) + ret.extend(self.kwarg_only) + return ret + + @property + def positional(self) -> Sequence[Argument | SelfArgument]: + ret: list[Argument | SelfArgument] = [] + ret.extend(self.pre_self_positional) + if self.self_arg is not None: + ret.append(self.self_arg) + ret.extend(self.post_self_positional) + return ret + + @property + def kwarg_only(self) -> Sequence[Argument | TensorOptionsArguments]: + ret: list[Argument | TensorOptionsArguments] = [] + ret.extend(self.pre_tensor_options_kwarg_only) + if self.tensor_options is not None: + ret.append(self.tensor_options) + ret.extend(self.post_tensor_options_kwarg_only) + return ret + + @property + def all(self) -> Sequence[Argument | SelfArgument | TensorOptionsArguments]: + ret: list[Argument | SelfArgument | TensorOptionsArguments] = [] + ret.extend(self.positional) + ret.extend(self.kwarg_only) + ret.extend(self.out) + return ret + + def mutable_arg_names(self) -> list[str]: + return [ + a.name + for a in self.flat_all + if a.annotation is not None and a.annotation.is_write + ] + + def has_tensor_arg(self) -> bool: + return any(a.type.is_tensor_like() for a in self.flat_non_out) + + def has_symint_arg(self) -> bool: + return any(a.type.is_symint_like() for a in self.flat_non_out) + + def has_generator_arg(self) -> bool: + return any(a.type.is_generator_like() for a in self.flat_non_out) + + def signature(self, *, strip_default: bool = False) -> Arguments: + # dataclasses.replace could be used here, but it is less + # type safe so for now I've opted to type everything out + def strip_arg_annotation(a: Argument) -> Argument: + return Argument( + name=a.name, + type=a.type, + default=a.default if not strip_default else None, + annotation=None, + ) + + return Arguments( + pre_self_positional=tuple( + map(strip_arg_annotation, self.pre_self_positional) + ), + self_arg=( + SelfArgument(strip_arg_annotation(self.self_arg.argument)) + if self.self_arg is not None + else None + ), + post_self_positional=tuple( + map(strip_arg_annotation, self.post_self_positional) + ), + # Since TensorOptions are dropped, the post_tensor_options_kwargs are + # converted to pre_tensor_options_kwargs + pre_tensor_options_kwarg_only=tuple( + map(strip_arg_annotation, self.pre_tensor_options_kwarg_only) + ) + + tuple(map(strip_arg_annotation, self.post_tensor_options_kwarg_only)), + # TensorOptions are dropped in signature, + # so we can pair factory functions with their out= variants. + tensor_options=None, + post_tensor_options_kwarg_only=(), + # out arguments are dropped in signature + out=(), + ) + + def remove_self_annotation(self) -> Arguments: + if self.self_arg is None: + raise AssertionError("remove_self_annotation called but self_arg is None") + return dataclasses.replace( + self, + self_arg=SelfArgument( + dataclasses.replace(self.self_arg.argument, annotation=None) + ), + ) + + def with_out_args(self, outs: list[Argument]) -> Arguments: + if len(self.out) != 0: + raise AssertionError( + f"with_out_args called but self.out is not empty: {self.out}" + ) + return dataclasses.replace( + self, + out=tuple(outs), + ) + + @staticmethod + def _preparse(args: str) -> tuple[list[Argument], list[Argument], list[Argument]]: + positional: list[Argument] = [] + kwarg_only: list[Argument] = [] + out: list[Argument] = [] + arguments_acc = positional + + # TODO: Use a real parser here; this will get bamboozled + # by signatures that contain things like std::array (note the space) + for arg in args.split(", "): + if not arg: + continue + if arg == "*": + if arguments_acc is not positional: + raise AssertionError( + "invalid syntax: kwarg-only specifier * can only occur once" + ) + arguments_acc = kwarg_only + continue + parg = Argument.parse(arg) + # Currently, we rely directly on the invariant that there are NO + # kwarg-only mutating arguments. If you want to relax this, + # we will need a more semantic way of matching that takes + # into account return arguments. In that case, you will have + # to manage out computation a level up, in FunctionSchema. See Note + # [is_out_fn] + if parg.annotation is not None and parg.annotation.is_write: + if arguments_acc is positional: + pass # do nothing + elif arguments_acc is kwarg_only: + arguments_acc = out + else: + if arguments_acc is out: + raise AssertionError( + f"non-mutable argument '{parg.name}' cannot follow mutable out arguments" + ) + arguments_acc.append(parg) + + return positional, kwarg_only, out + + @staticmethod + def parse(args: str) -> Arguments: + """ + Input: 'int x, int y, int z' + """ + + # We do this in two phases. First we parse into three + # main categories: positional, kwarg_only, out. + # Then, we reparse positional and kwarg_only to separate + # out the self argument and tensor options arguments. + + positional, kwarg_only, out = Arguments._preparse(args) + + # Split self argument + self_ix = None + for i, a in enumerate(positional): + if a.name == "self": + self_ix = i + break + pre_self_positional: list[Argument] + self_arg: SelfArgument | None + post_self_positional: list[Argument] + if self_ix is not None: + pre_self_positional = positional[:self_ix] + self_arg = SelfArgument(positional[self_ix]) + post_self_positional = positional[self_ix + 1 :] + else: + pre_self_positional = [] + self_arg = None + post_self_positional = positional + + # Group tensor options arguments + pre_tensor_options_kwarg_only: list[Argument] = [] + tensor_options: TensorOptionsArguments | None = None + post_tensor_options_kwarg_only: list[Argument] = [] + kwarg_only_acc = pre_tensor_options_kwarg_only + + def pred(name: str, ty: Type) -> Callable[[Argument], bool]: + return lambda a: a.name == name and a.type in [ty, OptionalType(ty)] + + predicates = [ # order matters + pred("dtype", Type.parse("ScalarType")), + pred("layout", Type.parse("Layout")), + pred("device", Type.parse("Device")), + pred("pin_memory", Type.parse("bool")), + ] + + i = 0 + while i < len(kwarg_only): + # If there is enough space... + if i <= len(kwarg_only) - len(predicates): + # And the next len(predicates) arguments look like TensorOptions arguments + if all( + p(a) + for p, a in zip(predicates, kwarg_only[i : i + len(predicates)]) + ): + if kwarg_only_acc is not pre_tensor_options_kwarg_only: + raise AssertionError( + "tensor options arguments can only appear once" + ) + # Group them together as one argument + tensor_options = TensorOptionsArguments( + dtype=kwarg_only[i], + layout=kwarg_only[i + 1], + device=kwarg_only[i + 2], + pin_memory=kwarg_only[i + 3], + ) + i += len(predicates) + kwarg_only_acc = post_tensor_options_kwarg_only + continue + kwarg_only_acc.append(kwarg_only[i]) + i += 1 + + return Arguments( + pre_self_positional=tuple(pre_self_positional), + self_arg=self_arg, + post_self_positional=tuple(post_self_positional), + pre_tensor_options_kwarg_only=tuple(pre_tensor_options_kwarg_only), + tensor_options=tensor_options, + post_tensor_options_kwarg_only=tuple(post_tensor_options_kwarg_only), + out=tuple(out), + ) + + def __str__(self) -> str: + all_arguments: list[str] = [] + all_arguments.extend(map(str, self.flat_positional)) + if self.flat_kwarg_only or self.out: + all_arguments.append("*") + all_arguments.extend(map(str, self.flat_kwarg_only)) + all_arguments.extend(map(str, self.out)) + return ", ".join(all_arguments) + + def __post_init__(self) -> None: + # TODO: These invariants are weirdly asymmetric? + # TODO: Fancier types? + if self.self_arg is None: + if self.pre_self_positional: + raise AssertionError( + "pre_self_positional is non-empty but self_arg is None" + ) + if self.tensor_options is None: + if self.post_tensor_options_kwarg_only: + raise AssertionError( + "post_tensor_options_kwarg_only is non-empty but tensor_options is None" + ) + + # We don't allow any of the following to have argument annotations, + # to keep things simple. + mutable_pre_self_positionals = [ + a + for a in self.pre_self_positional + if a.annotation is not None and a.annotation.is_write + ] + if len(mutable_pre_self_positionals) != 0: + raise AssertionError( + f"mutable pre_self_positional arguments are not currently supported in the schema: {mutable_pre_self_positionals}" + ) + + +# Names that validly are __iXXX__ indicating inplace operations. +# Taken from https://www.python.org/dev/peps/pep-0203/#new-methods +# NB: PyTorch hasn't actually implemented all of these +AUGMENTED_ASSIGNMENT_NAMES = [ + "add", + "sub", + "mul", + "div", + "mod", + "pow", + "lshift", + "rshift", + "and", + "xor", + "or", +] + + +# A BaseOperatorName is what we think of the operator name, without +# the overload name. Unusually, we don't represent this as just a +# string; instead, we directly represent a few important semantic +# bits of information we derive from the string: namely whether +# or not it's inplace (add_) and whether or not it's a double-underscore +# method (__add__) +@dataclass(frozen=True) +class BaseOperatorName: + base: str + inplace: bool + dunder_method: bool + # Note [Overload Ambiguity With Functional Variants] + # A handful of operators have both a "mutable" and a "functional" variant. + # (native_batch_norm is a good example, although this isn't the case today). + # For those operators, the mutable and functional variant take in the same set of + # arguments, but have different alias annotations. + # this makes it ambiguous when you try to resolve an OverloadPacket into an overload, + # given a set of input arguments. + # + # So instead of making the "functional" variant in this case a real overload, e.g: + # native_batch_norm (mutable variant) + # native_batch_norm.functional (functional variant) + # we make it a new base operator, + # native_batch_norm_functional (functional variant) + # + # In an ideal world, we would probably invert this so the operators were: + # native_batch_norm.mutable (mutable variant) + # native_batch_norm (functional variant) + # + # Doing that is BC-breaking though, so we're stuck with the above modeling. + functional_overload: bool = False + + # NB: We don't officially support namespace in FunctionSchema, we treat this prefix + # as part of the base operator name, for __str__() to consume. + # The canonical input (from the rest of the infra) will not contain namespace, but + # we have a usecase in ExecuTorch where we want to support BaseOperatorName with namespace. + namespace: str | None = None + + @staticmethod + def parse(op: str) -> BaseOperatorName: + if op == "": + raise AssertionError("operator name cannot be empty") + if op.endswith("_out"): + raise AssertionError( + "_out suffix is reserved and not permitted for operator names; " + "did you mean to specify an out overload name instead?" + ) + # Extract namespace out. Base operator name may or may not contain namespace. + # E.g., aten::__lshift__ is a valid base operator name, __lshift__ is also valid. + # We want to split the namespace out from the base operator name. + match = re.match(r"^(?:(.*)::)?(.*)$", op) + namespace = match.group(1) if match else "" + op_without_ns = match.group(2) if match else op + m = re.match(r"^__([^_]+)__$", op_without_ns) + if m is not None: + dunder_method = True + base = m.group(1) + if any(base == f"i{n}" for n in AUGMENTED_ASSIGNMENT_NAMES): + inplace = True + base = base[1:] + else: + inplace = False + # temporary, this is not intrinsically true but + # has been historically true for dunder methods + # we support (but, if we ever got, say, __int__, this would + # be wrong!) + if base[0] == "i": + raise AssertionError( + f"unexpected dunder method starting with 'i': {op}" + ) + else: + dunder_method = False + base = op_without_ns + if base[-1] == "_": + inplace = True + base = base[:-1] + else: + inplace = False + + # See Note [Overload Ambiguity With Functional Variants] + functional_suffix = "_functional" + if base.endswith(functional_suffix): + functional_overload = True + base = base[: -len(functional_suffix)] + # This seems complicated and unnecessary, so banning dunder methods + # for now on ops that have a functional + mutable variant (like native_batch_norm). + if dunder_method or inplace: + raise AssertionError( + f"functional overload cannot be a dunder method or inplace: {op}" + ) + else: + functional_overload = False + + r = BaseOperatorName( + base=base, + inplace=inplace, + dunder_method=dunder_method, + functional_overload=functional_overload, + namespace=namespace, + ) + if str(r) != op: + raise AssertionError(f"{str(r)} != {op}") + return r + + def __str__(self) -> str: + namespace_prefix = f"{self.namespace}::" if self.namespace else "" + if self.dunder_method: + i = "i" if self.inplace else "" + return f"{namespace_prefix}__{i}{self.base}__" + else: + i = ( + "_" + if self.inplace + else "_functional" + if self.functional_overload + else "" + ) + return f"{namespace_prefix}{self.base}{i}" + + +# Operator name is the base operator name along with the (typically not +# user visible) overload string. +@dataclass(frozen=True) +class OperatorName: + name: BaseOperatorName + overload_name: str + + @staticmethod + def parse(op_name: str) -> OperatorName: + if "." in op_name: + name, overload_name = op_name.split(".", 1) + else: + name = op_name + overload_name = "" + r = OperatorName(name=BaseOperatorName.parse(name), overload_name=overload_name) + if str(r) != op_name: + raise AssertionError(f"{str(r)} != {op_name}") + return r + + def __str__(self) -> str: + if self.overload_name: + return f"{self.name}.{self.overload_name}" + else: + return f"{self.name}" + + # NB: This must be synchronized with the naming scheme in + # aten/src/ATen/templates/Operators.h + # Given a function schema "aten::op.overload(...)", + # If there is no overload name, this returns f"{op}" + # If there is an overload name, this returns f"{op}_{overload}" + def unambiguous_name(self) -> str: + if self.overload_name: + return f"{self.name}_{self.overload_name}" + else: + return f"{self.name}" + + def remove_inplace(self) -> OperatorName: + return OperatorName( + name=BaseOperatorName( + base=self.name.base, + inplace=False, + dunder_method=self.name.dunder_method, + ), + overload_name=self.overload_name, + ) + + def with_overload(self, overload: str) -> OperatorName: + return OperatorName( + name=BaseOperatorName( + base=self.name.base, + inplace=False, + dunder_method=self.name.dunder_method, + ), + overload_name=overload, + ) + + +def gets_generated_out_inplace_wrapper( + f: NativeFunction, g: NativeFunctionsGroup, b: BackendIndex +) -> bool: + return ( + f.func.kind() is not SchemaKind.functional + and not b.has_kernel(f) + and b.has_kernel(g.functional) + ) + + +# NativeFunction objects that are views (f.is_view_op returns True) +# are added into a `NativeFunctionsViewGroup`, which we can use to +# easily access the generated (optional) view_copy NativeFunction. +# It's convenient to group them together, so we pair them up in NativeFunctionsViewGroup. +# See Note [Codegen'd {view}_copy Operators] +# +# One property of this representation is that in order for a view-like op to be part of +# a NativeFunctionsViewGroup, the "aliasing" version of that view op must exist. +# There's one case where that doesn't happen: we have a non-aliasing `narrow_copy.out` op, +# but don't have corresponding aliasing `narrow.out` op. +# This means that `narrow_copy.out` won't appear as a NativeFunctionsViewGroup. +@dataclass(frozen=True) +class NativeFunctionsViewGroup: + view: NativeFunction + # Note: the {view}_copy operator is optional because we currently don't generate copy variants + # for all view ops. Notably, we don't generate them for CompositeImplicitAutograd views + # (we already get them "for free" through decomposition) + view_copy: NativeFunction | None + # view_inplace ops are also optional, but every view_inplace op should have out-of-place variant. + view_inplace: NativeFunction | None + + def __post_init__(self) -> None: + if not self.view.is_view_op: + raise AssertionError(f"view is not a view op: {self.view.func.name}") + if self.view_copy is None: + if gets_generated_view_copy(self.view): + raise AssertionError( + f"{str(self.view.func.name)} appears to be a new operator that aliases its inputs." + " The codegen expects you to add a corresponding operator to native_functions.yaml:" + f" {get_view_copy_name(self.view)!s}." + " See Note [view_copy NativeFunctions] for details." + ) + else: + if not self.view_copy.func.name.name.base.endswith(("_copy", "_scatter")): + raise AssertionError( + f"view_copy name must end with '_copy' or '_scatter': {self.view_copy.func.name}" + ) + if self.view.func.signature() != self.view_copy.func.signature( + strip_view_copy_name=True, + ): + view_sig = self.view.func.signature() + view_copy_sig = self.view_copy.func.signature(strip_view_copy_name=True) + raise AssertionError( + f"view and view_copy signatures don't match: {view_sig} != {view_copy_sig}" + ) + if "view_copy" not in self.view_copy.tags: + raise AssertionError( + f"{str(self.view_copy.func.name), str(self.view.tags)} appears to be a view_copy operator. The codegen expects" + " view_copy operators to be annotated with the 'view_copy' tag in native_functions.yaml." + " See Note [view_copy NativeFunction] for details." + ) + if self.view_inplace is not None: + if self.view.func.signature() != self.view_inplace.func.signature(): + view_sig = self.view.func.signature() + view_inplace_sig = self.view_inplace.func.signature() + raise AssertionError( + f"view and view_inplace signatures don't match: {view_sig} != {view_inplace_sig}" + ) + + if self.view.has_composite_implicit_autograd_kernel: + if self.view_inplace is not None: + if not self.view_inplace.has_composite_implicit_autograd_kernel: + raise AssertionError( + f"{str(self.view.func.name)} and {str(self.view_inplace.func.name)} must either" + " both have CompositeImplicitAutograd kernels, or both not have composite kernels." + ) + if self.view.has_composite_implicit_autograd_nested_tensor_kernel: + if self.view_inplace is not None: + if not self.view_inplace.has_composite_implicit_autograd_nested_tensor_kernel: + raise AssertionError( + f"{str(self.view.func.name)} and {str(self.view_inplace.func.name)} must either" + " both have CompositeImplicitAutogradNestedTensor kernels, or both not have composite kernels." + ) + + def functions(self, *, include_copy: bool = True) -> Iterator[NativeFunction]: + yield self.view + if self.view_inplace is not None: + yield self.view_inplace + if self.view_copy is not None and include_copy: + yield self.view_copy + + @property + def root_name(self) -> str: + return self.view.root_name + + @property + def composite(self) -> bool: + # We currently assert that the "group" is consistent. + # If the view op is composite, then its view_inplace op is too. + return self.view.has_composite_implicit_autograd_kernel + + +def gets_generated_view_copy(f: NativeFunction) -> bool: + # Only aliasing (view) operators get a copy variant. + if not f.is_view_op: + return False + # We don't need to bother generating copy variants for CompositeImplicitAutograd ops, + # because we can let them decompose into base view ops. + if f.has_composite_implicit_autograd_kernel: + return False + # We also don't need to generate copy variants for inplace views. + if "inplace_view" in f.tags: + return False + # Assume ops ending in _inverse have manually-defined copy variants + # (e.g. slice_inverse() has the copy variant slice_scatter()). + # We -could- probably generate these as well, but the codegen will be + # slightly different, and hand-writing these few kernels keeps codegen + # complexity lower. + if f.func.name.name.base.endswith("_inverse"): + return False + return True + + +# Given a NativeFunction that corresponds to a view op, +# returns the OperatorName of the corresponding "copy" variant of the op. +def get_view_copy_name(f: NativeFunction) -> OperatorName: + # Right now, when asking for a view op's corresponding "view_copy" name + # we assert for sanity that the op is allowed to have a generated view_copy variant. + # (We can do this because "gets_generated_view_copy()" tell us which ops get a generated view_copy op). + # However, narrow_copy() already exists as an op directly in native_functions.yaml. + # I'm hardcoding narrow_copy here for now to maintain the assert, + # But we could also just get rid of the assert. + list_of_ops_with_explicit_view_copy_operators = ["narrow"] + if str(f.func.name) not in list_of_ops_with_explicit_view_copy_operators: + if not gets_generated_view_copy(f): + raise AssertionError( + f"{f.func.name} does not have a generated view_copy variant" + ) + + base_name = f"{f.func.name.name.base}_copy" + view_copy_name = OperatorName( + name=BaseOperatorName( + base=base_name, inplace=False, dunder_method=f.func.name.name.dunder_method + ), + overload_name=f.func.name.overload_name, + ) + return view_copy_name + + +# Helper functions for parsing argument lists (both inputs and returns) + + +def parse_returns(return_decl: str) -> tuple[Return, ...]: + """ + Input: '()' + Output: [] + """ + if return_decl == "()": + return () + if return_decl[0] == "(" and return_decl[-1] == ")": + return_decl = return_decl[1:-1] + return tuple(Return.parse(arg) for arg in return_decl.split(", ")) + + +# A Precompute instance consists of a map from kernel argument name +# to the list of Argument instances that should replace that +# kernel argument in the impl function. +@dataclass(frozen=True) +class Precompute: + # A map from kernel argument name -> a list of precomputed + # elements that replaces/supersedes it. + replace: dict[str, list[Argument]] + # List of precomputed args added without replacement + add: list[Argument] + + @staticmethod + def parse(src: object) -> Precompute: + if not isinstance(src, list): + raise AssertionError(f"precomputed must be a list, got {type(src)}") + + # src is a list of strings of the format: + # {kernel param name} -> {replacement decl}[, {replacement decl}, ...] + # [{add decl}[, {add decl}, ...]] + # The last line is optional and contains the precomputed parameters that are + # added without replacement. + # The other lines are parsed to get the names of which precomputed elements + # should replace which kernel arguments. + add_args = [] + if " -> " not in src[-1]: + add_list = src[-1].split(",") + add_args = [Argument.parse(name.strip()) for name in add_list] + src = src[:-1] + + replace = {} + for raw_replace_item in src: + if not isinstance(raw_replace_item, str): + raise AssertionError( + f"precomputed item must be a str, got {type(raw_replace_item)}" + ) + if " -> " not in raw_replace_item: + raise AssertionError( + f"precomputed parameters without replacement are allowed only in the last line, got: {raw_replace_item}" + ) + + arg, with_list_raw = raw_replace_item.split(" -> ") + if " " in arg: + raise AssertionError( + f"illegal kernel param name '{arg}' in precomputed parameters" + ) + with_list = with_list_raw.split(",") + with_list_args = [Argument.parse(name.strip()) for name in with_list] + replace[arg] = with_list_args + + r = Precompute(replace=replace, add=add_args) + if r.to_list() != src: + raise AssertionError(f"r.to_list() != src: {r.to_list()} != {src}") + return r + + def __post_init__(self) -> None: + # the template parameters are upper so if these are the + # same then it is ambiguous + for a in self.add: + if a.name.upper() == a.name: + raise AssertionError( + f"precomputed argument name must not be all uppercase: {a.name}" + ) + for args in self.replace.values(): + for a in args: + if a.name.upper() == a.name: + raise AssertionError( + f"precomputed argument name must not be all uppercase: {a.name}" + ) + + def to_list(self) -> list[str]: + replace_list = [] + for kernel_param, replacement_params in self.replace.items(): + replacements = ", ".join(str(param) for param in replacement_params) + replace_list.append(f"{kernel_param} -> {replacements}") + + return replace_list diff --git a/.venv/lib/python3.12/site-packages/torchgen/native_function_generation.py b/.venv/lib/python3.12/site-packages/torchgen/native_function_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..d4efcf714f7d76308e0daf3b6e12eb8fb0391eef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/native_function_generation.py @@ -0,0 +1,666 @@ +from __future__ import annotations + +import string +from collections import defaultdict +from typing import TYPE_CHECKING + +import torchgen.api.dispatcher as dispatcher +from torchgen.api.translate import translate +from torchgen.api.types import Binding, DispatcherSignature, Expr +from torchgen.context import with_native_function +from torchgen.model import ( + Annotation, + Argument, + BackendIndex, + BackendMetadata, + BaseOperatorName, + BaseTy, + BaseType, + DEFAULT_KERNEL_NAMESPACE, + DeviceCheckType, + DispatchKey, + FunctionSchema, + NativeFunction, + NativeFunctionsGroup, + OperatorName, + Return, + SchemaKind, + Variant, +) +from torchgen.utils import concatMap + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +# See Note: [Out ops with functional variants that don't get grouped properly] +OUT_OPS_THAT_DONT_GET_GROUPED_PROPERLY = [ + # This has a functional variant, but it's currently marked private. + # This function should be marked private as well (*_backward ops aren't exposed to python anyway). + "adaptive_avg_pool3d_backward.grad_input", + # There's a functional variant, _slow_conv2d_backward.output_mask, that isn't grouped properly. + # Maybe we can kill this operator in favor of convolution_backward? + "_slow_conv2d_backward.grad_input", +] + + +# See Note: [Mutable ops that cannot get an out variant] +MUTABLE_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT = [ + # should be out=? + "_cummax_helper", + # should be out=? + "_cummin_helper", +] + +# All of these operators don't have any tensor like returns +FUNCTIONAL_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT = [ + "_assert_async", # no return + "_assert_async.msg", # no return + "_assert_tensor_metadata", # no return + "_cslt_sparse_mm_search", # returns an int + "_assert_scalar", # no return + "_dimI", # returns an int + "_dimV", # returns an int + "_has_same_storage_numel", # returns a boolean + "_linalg_check_errors", # no return + "_local_scalar_dense", # returns a Scalar + "_nested_tensor_from_mask_left_aligned", # returns a boolean + "_nnz", # returns an int + "_use_cudnn_ctc_loss", # returns a boolean + "_use_cudnn_ctc_loss.Tensor", # returns a boolean + "_use_miopen_ctc_loss", # returns a boolean + "_use_miopen_ctc_loss.Tensor", # returns a boolean + "_validate_compressed_sparse_indices", # no return + "allclose", # returns a boolean + "dense_dim", # returns an int + "equal", # returns a boolean + "is_coalesced", # returns an boolean + "is_pinned", # returns a boolean + "is_same_size", # returns a boolean + "is_set_to", # returns a boolean + "q_per_channel_axis", # returns an int + "q_scale", # returns a float + "q_zero_point", # returns an int + "qscheme", # returns a QScheme + "record_stream", # no return + "sparse_dim", # returns an int + "sym_constrain_range", # no return + "sym_constrain_range_for_size", # no return + "_nested_tensor_storage_offsets", # returns a vector of ints + "_chunk_grad_outputs_efficient_attention", # returns a bool + "_fused_sdp_choice", # returns an int + "_print", # no return + "_sink_tokens", # no return + "_nested_get_ragged_idx", # returns an int +] + +INPLACE_OPS_THAT_DONT_GET_GROUPED_PROPERLY = [ + # polygamma and polygamma.out both exist, but have a + # pre-self arg (while polygamma_ does not) + # We should either fix this schema so it can be grouped properly, + # or allow the codegen to generate new functional/out= NativeFunctions for this op + # (which would require changing its overload name to prevent overload ambiguity). + "polygamma_" +] + + +# Groups "similar" NativeFunctions together +# example add.Tensor, add_.Tensor, add.out +# "similar" NativeFunctions are all expected to have an identical `signature()`, +# But have differing SchemaKinds. +def pre_group_native_functions( + native_functions: Sequence[NativeFunction], +) -> dict[FunctionSchema, dict[SchemaKind, NativeFunction]]: + pre_grouped_native_functions: dict[ + FunctionSchema, dict[SchemaKind, NativeFunction] + ] = defaultdict(dict) + for f in native_functions: + d = pre_grouped_native_functions[f.func.signature()] + if f.func.kind() in d: + raise AssertionError(f"Duplicate schema kind {f.func.kind()} for {f.func}") + d[f.func.kind()] = f + return pre_grouped_native_functions + + +# Returns the out variant overload name given a base function overload name +def get_expected_out_variant_overload_name(overload_name: str | None) -> str: + return "out" if not overload_name else f"{overload_name}_out" + + +# Helper function: given an inplace FunctionSchema, generate its corresponding out= variant +# Example before: +# _add_relu_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!) +# Example after: +# _add_relu.Scalar_out(Tensor self, Scalar other, Scalar alpha=1, *, Tensor(a!) out) +def self_to_out_signature(func: FunctionSchema) -> FunctionSchema: + # Generating an out= schema from an inplace schema. + if func.kind() != SchemaKind.inplace: + raise AssertionError(f"Expected inplace schema, got {func.kind()}") + if func.arguments.self_arg is None: + raise AssertionError("Expected self_arg to be non-None") + # The new out= schema has: + # - a new out argument with the same type as "func" (but with a mutable annotation) + # - The returns (if any) now alias the out= argument instead of "func" + # - an "out" overload name + return FunctionSchema( + name=func.name.remove_inplace().with_overload( + get_expected_out_variant_overload_name(func.name.overload_name) + ), + arguments=func.arguments.remove_self_annotation().with_out_args( + [ + Argument( + name="out", + type=func.arguments.self_arg.argument.type, + default=None, + annotation=func.arguments.self_arg.argument.annotation, + ) + ] + ), + returns=func.returns, + ) + + +# Helper function: given a functional FunctionSchema, generate its corresponding out= variant +# Example before: +# _to_copy(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, +# bool? pin_memory=None, bool non_blocking=False, MemoryFormat? memory_format=None) -> Tensor +# Example after: +# _to_copy._out(Tensor self, *, bool non_blocking=False, MemoryFormat? memory_format=None, +# Tensor(a!) out) -> Tensor(a!) +def functional_to_out_signature(func: FunctionSchema) -> FunctionSchema: + # Generating an out= schema from a functional schema. + if func.kind() != SchemaKind.functional: + raise AssertionError(f"Expected functional schema, got {func.kind()}") + + new_returns, new_out_args = generate_out_args_from_schema(func) + # The new out= schema has: + # - one or more new out argument(s) with the same type as returns (but with a mutable annotation) + # - The returns now alias the out= arguments + # - an "_out" overload name + return FunctionSchema( + name=func.name.with_overload( + get_expected_out_variant_overload_name(func.name.overload_name) + ), + arguments=func.arguments.signature().with_out_args( + new_out_args, + ), + returns=tuple(new_returns), + ) + + +# Helper function: given a function schema, generate corresponding out arguments, also the updated return annotations. +def generate_out_args_from_schema( + func: FunctionSchema, +) -> tuple[list[Return], list[Argument]]: + # More of a sanity check - our existing restrictions on schemas should enforce that + # mutable schema kinds never return their mutable arguments. + if any(r.annotation is not None and r.annotation.is_write for r in func.returns): + raise AssertionError("Mutable schema kinds should not return mutable arguments") + + tensorlike_rets = [r for r in func.returns if r.type.is_tensor_like()] + if len(tensorlike_rets) == 0: + raise AssertionError("Expected at least one tensor-like return") + + used_annotations = concatMap( + lambda a: [] if a.annotation is None else a.annotation.alias_set, + func.arguments.flat_all, + ) + valid_annotations = [x for x in string.ascii_lowercase if x not in used_annotations] + + all_rets_are_tensors = all(r.type == BaseType(BaseTy.Tensor) for r in func.returns) + + new_out_args: list[Argument] = [] + # The end result of new_returns is that: + # - If every return is a plain tensor, then the new returns == the old returns, but with the out= alias annotations added. + # - Otherwise, none of the out arguments show up in the returns (and we're only left with non-tensor-like returns, if any). + new_returns: list[Return] = [] + for i, r in enumerate(func.returns): + if r.type.is_tensor_like(): + new_out = Argument( + name="out" if len(func.returns) == 1 else f"out{i}", + type=r.type, + default=None, + annotation=Annotation.parse(f"{valid_annotations[i]}!"), + ) + new_out_args.append(new_out) + if all_rets_are_tensors: + # The convention for out= schemas is that they only return their out arguments + # if the return is a plain Tensor (or if it's a tuple of plain Tensors) + new_ret = Return( + name=None, type=new_out.type, annotation=new_out.annotation + ) + new_returns.append(new_ret) + else: + new_returns.append(r) + return new_returns, new_out_args + + +# Helper function: given a mutable FunctionSchema, generate its corresponding out= variant +# Example before: +# _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask) +# Example after: +# _fused_moving_avg_obs_fq_helper._out(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False, *, Tensor(e!) out0, Tensor(f!) out1) -> (Tensor(e!), Tensor(f!)) +def mutable_to_out_signature(func: FunctionSchema) -> FunctionSchema: + # Generating an out= schema from a mutable schema. + if func.kind() != SchemaKind.mutable: + raise AssertionError(f"Expected mutable schema, got {func.kind()}") + # The new out= schema has: + # - Any non-aliased tensor-like returns are converted to mutable, aliased out= arguments + # (if the argument is a tensor then we also return it for method chaining, + # otherwise we return nothing) + # - an "out" overload name + # + # Note that: + # (1) This also means that we can *only* generate an out= variant from a mutable schema + # if the mutable schema has at least one tensor-like non-aliasing return. + # (2) The generated out= variant still has mutable positional arguments, + # but if necessary we could probably add another out= variant that also + # functionalizes the mutable arguments (a functional_out variant) + + new_returns, new_out_args = generate_out_args_from_schema(func) + + return FunctionSchema( + name=func.name.remove_inplace().with_overload( + get_expected_out_variant_overload_name(func.name.overload_name) + ), + arguments=func.arguments.with_out_args(new_out_args), + returns=tuple(new_returns), + ) + + +# This function, given function of one SchemaKind, as well as a target SchemaKind, +# generates a new NativeFunction with the same properties, but using the target SchemaKind. +# We only actually generate functions for either functional or out= SchemaKinds. +# This function returns a tuple, with: +# - The generated NativeFunction +# - a dictionary of `BackendIndex` objects, describing which dispatch keys +# we will generate kernels for, for the new NativeFunction. +# Details are in the function, but we only generate composite kernels (in some cases) today. +def generate_function( + f: NativeFunction, k: SchemaKind +) -> tuple[NativeFunction, dict[DispatchKey, dict[OperatorName, BackendMetadata]]]: + from torchgen.api import cpp + + if k == SchemaKind.functional: + if f.func.kind() == SchemaKind.functional: + raise AssertionError("Cannot generate functional from functional schema") + # The new "functional" NativeFunction has: + # - any mutable arguments have been converted into (immutable) returns. + # (if a mutable argument was not also a return, it gets converted to one) + # - "_functional" appended to the base name, ONLY IF this op has a mutable variant. + # See Note [Overload Ambiguity With Functional Variants] + # The default grouping logic in signature() actually already does this, + # so we can piggy-back off it (but we still want return names) + func = f.func.signature(keep_return_names=True).with_name( + OperatorName( + name=BaseOperatorName( + base=f.func.name.name.base, + inplace=False, + dunder_method=f.func.name.name.dunder_method, + # See Note [Overload Ambiguity With Functional Variants] + functional_overload=f.func.kind() == SchemaKind.mutable, + ), + overload_name=f.func.name.overload_name, + ) + ) + elif k == SchemaKind.out: + # We generate out= ops mostly just so that we can pair up NativeFunctions into groups easily, + # but at least today, there is no good reason to actually use them. + # we'll generate a dispatcher entry for them, but won't actually register any kernels for them. + if f.func.kind() == SchemaKind.inplace: + func = self_to_out_signature(f.func) + elif f.func.kind() == SchemaKind.mutable: + func = mutable_to_out_signature(f.func) + elif f.func.kind() == SchemaKind.functional: + func = functional_to_out_signature(f.func) + else: + raise AssertionError( + "We only bother generating out= functions from either inplace or mutable or functional variants" + ) + else: + raise AssertionError( + "We currently only generate either functional or out= NativeFunctions" + ) + + # Generated kernel naming convention for out: _. The reason for this is to + # disambiguate operator with the same name but different overload name, e.g., `randn.names_out` and + # `randn.generator_with_names_out`. + kernel_name = ( + func.name.unambiguous_name() + if func.kind() == SchemaKind.out + else cpp.name(func) + ) + if f.func.has_symint(): + kernel_name += "_symint" + backend_metadata = { + DispatchKey.CompositeExplicitAutograd: { + func.name: BackendMetadata( + kernel=kernel_name, + structured=False, + cpp_namespace=DEFAULT_KERNEL_NAMESPACE, + ) + } + } + tags = {"generated"} | set( + f.tags & {"nondeterministic_seeded", "view_copy", "pt2_compliant_tag"} + ) + if func.is_out_fn(): + tags.add("out") + if func.name.name.inplace: + tags.add("inplace") + + return ( + NativeFunction( + func=func, + use_const_ref_for_mutable_tensors=f.use_const_ref_for_mutable_tensors, + # These generated fn's aren't meant to be user friendly- don't generate methods. + variants={Variant.function}, + structured=False, + structured_delegate=None, + structured_inherits=None, + precomputed=None, + autogen=[], + ufunc_inner_loop={}, + manual_kernel_registration=False, + manual_cpp_binding=False, + python_module=None, + category_override=None, + device_guard=False, + device_check=DeviceCheckType.NoCheck, + loc=f.loc, + cpp_no_default_args=set(), + is_abstract=f.is_abstract, + has_composite_implicit_autograd_kernel=False, + has_composite_implicit_autograd_nested_tensor_kernel=False, + has_composite_explicit_autograd_kernel=True, + has_composite_explicit_autograd_non_functional_kernel=False, + # Every generated NativeFunction gets a "generated" tag, so it's easy to tell + # which NativeFunction objects did not come directly from native_functions.yaml. + tags=tags, + namespace=f.namespace, + ), + backend_metadata, + ) + + +# This function is responsible for adding generated NativeFunctions which don't appear +# explicitly in the codegen. +# You can inspect the full list of NativeFunctions yourself with the torchgen package, by running +# torchgen.parse_native_yaml("aten/src/ATen/native/native_functions.yaml", "aten/src/ATen/native/tags.yaml") +# (Maybe we should make a friendly API for this) +# +# Note: this function *mutates* its two inputs, +# adding the new NativeFunctions / BackendMetadata to them +def add_generated_native_functions( + rs: list[NativeFunction], + indices: dict[DispatchKey, dict[OperatorName, BackendMetadata]], +) -> None: + # The main code for generating new NativeFunctions + # First we group of NativeFunctions by schema kind, + # then we detect which ones are missing and generate them. + pre_grouped_native_functions = pre_group_native_functions(rs) + for d in pre_grouped_native_functions.values(): + has_functional = SchemaKind.functional in d + has_inplace = SchemaKind.inplace in d + has_mutable = SchemaKind.mutable in d + has_out = SchemaKind.out in d + is_core = any("core" in variant.tags for variant in d.values()) + + # We automatically generate a few native functions that don't exist in the yaml, for a few reasons: + # (1) If an operator has an inplace/out= variant but no functional variant, we can generate + # a simple functional variant that the functionalization pass can consume. + # (2) If an operator has an inplace or functional but no out= variant, we generate an out= + # variant, mostly so we can easily pair up functions into NativeFunctionsGroup, + # while maintaining the constraint that the out= variant is "required". + if has_mutable or has_inplace or has_out or has_functional: + # Don't bother generating functions trio's for native functions that bypass the dispatcher. + are_manual = all(f.manual_cpp_binding for f in d.values()) + # Don't bother generating functional + out= variants for view operators + # set_ is technically an inplace_view, but for now it is treated + # as a normal inplace op in the codegen + has_view_ops = any( + f.is_view_op and str(f.func.name.name) != "set_" for f in d.values() + ) + # Don't generate the other variants for non-core CompositeImplicitAutograd operators. + # We could probably do this, but the main benefit of generating the function triplets + # is for transforms that need them, and transforms don't need to act directly + # on CompositeImplicitAutograd operators (since we let them decompose). + are_composite_implicit = all( + f.has_composite_implicit_autograd_kernel for f in d.values() + ) + if are_manual or has_view_ops or are_composite_implicit and not is_core: + continue + if has_out and len(d.values()) == 1: + # Note: [Out ops with functional variants that don't get grouped properly] + # In theory we could validly have an out= operator in native_functions.yaml + # that has no other variants. + # But today, all of the operators where that's the case actually do have + # functional variants, that we are just unable to pair up properly. + # I think banning this all together is probably safer + # (you can always add a functional variant yourself if you want to add a new out= operator). + # + # We should probably fix the existing cases; this check is to prevent us from adding more over time. + if ( + str(d[SchemaKind.out].func.name) + not in OUT_OPS_THAT_DONT_GET_GROUPED_PROPERLY + ): + raise AssertionError( + f"Found an out= operator that we could not find any other variants of: {str(d[SchemaKind.out].func)}" + ) + continue + + # Some inplace ops that have problematic schemas (that we should fix), which prevent us + # from generating out= and functional variants + if ( + has_inplace + and str(d[SchemaKind.inplace].func.name) + in INPLACE_OPS_THAT_DONT_GET_GROUPED_PROPERLY + ): + continue + + base_fn = ( + d[SchemaKind.mutable] + if has_mutable + else d[SchemaKind.inplace] + if has_inplace + else d[SchemaKind.out] + if has_out + else d[SchemaKind.functional] + ) + + # Note: [Mutable ops that cannot get an out variant] + # We can only generate an out= variant if either: + # - the original function has tensor-like returns (since we can convert them to out kwargs) + # - or it's inplace (since we can convert `self` to an out kwarg) + # There are only two functions that don't fit this criteria today though, + # and they both look like they should be fixed to be out= variants, + # so if feels safer to ban this schema all-together + base_fn_valid = base_fn.func.kind() == SchemaKind.inplace or any( + r.type.is_tensor_like() for r in base_fn.func.returns + ) + # Note: [Loosen the assertion that all functional should have out variant] + # By design all functional operators should have our variants. The needs_out check + # is loosening this requirement, changing it to only generate out variant if there's + # an `autogen` block in the native function, in the long run it should be removed. + # FIXME: Remove this after figuring out CI job failures related to min, max, mean + needs_out = any("out" in str(op_name) for op_name in base_fn.autogen) + gets_out_variant = not has_out and base_fn_valid and needs_out + if not has_out and not base_fn_valid: + if ( + str(base_fn.func.name) + not in MUTABLE_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT + and str(base_fn.func.name) + not in FUNCTIONAL_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT + ): + raise AssertionError( + f"""Found an operator that we could not generate an out= variant for: {str(base_fn.func)}. +This type of operators don't have tensor-like return, making it difficult to generate a proper out= variant. If +out= variant is not needed, please add the function name into FUNCTIONAL_OPS_THAT_CANNOT_GET_AN_OUT_VARIANT list.""" + ) + + # Generate an out= variant + if gets_out_variant: + fn, metadata = generate_function(base_fn, SchemaKind.out) + d[SchemaKind.out] = fn + BackendIndex.grow_index(indices, metadata) + rs.append(fn) + + # Generate a functional variant, but only do it if the operator got an out= variant + # (Functional variants are only useful if we can group up the variants, + # which we can only do if they have an out= variant) + if not has_functional and (has_out or gets_out_variant): + fn, metadata = generate_function(base_fn, SchemaKind.functional) + d[SchemaKind.functional] = fn + BackendIndex.grow_index(indices, metadata) + rs.append(fn) + + +def return_str(rets: tuple[Return, ...], names: list[str]) -> str: + if len(rets) != len(names): + raise AssertionError( + f"Returns and names length mismatch: {len(rets)} vs {len(names)}" + ) + if len(rets) == 0: + return "" + elif len(rets) == 1: + return f"return {names[0]};" + else: + return f"return {dispatcher.returns_type(rets).cpp_type()}({', '.join(names)});" + + +# Given a function, and the name of a variable corresponding to the output of that function, +# gather up all of the individual returns that are not aliased +def gather_nonaliased_inner_rets(func: FunctionSchema, out_var: str) -> list[str]: + aliased_rets = func.aliased_return_names() + non_aliased_names = [] + is_out_var_a_tuple = len(func.returns) > 1 + for i, r in enumerate(aliased_rets): + if r is None: + non_aliased_names.append( + f"std::get<{i}>({out_var})" if is_out_var_a_tuple else out_var + ) + return non_aliased_names + + +# Generates functional kernels in terms of their inplace.mutable counterparts. +# We only do this for "generated" NativeFunctions +@with_native_function +def gen_composite_functional_kernel(g: NativeFunctionsGroup) -> str | None: + # We should only be generating these for code-generated NativeFunctions + if "generated" not in g.functional.tags: + return None + # And we always write the kernel for a generated op in terms of a non-generated op. + if g.inplace is not None and "generated" not in g.inplace.tags: + target_f = g.inplace + elif g.mutable is not None and "generated" not in g.mutable.tags: + target_f = g.mutable + else: + # We should be guaranteed to have a valid inplace/mutable variant to call into. + # See Note: [Mutable Ops Not Using Functionalization] + raise AssertionError(str(g.functional.func)) + + sig = DispatcherSignature(g.functional.func) + target_sig = DispatcherSignature(target_f.func) + + context: list[Binding | Expr] = [] + clone_mutable_inputs = [] + cloned_return_names = [] + # We can't just directly pass all of the arguments from the functional op into the mutating op. + # We need to check for which inputs to the mutating operator are mutable, + # and clone those inputs first. + for a_curr, a_tgt in zip( + dispatcher.jit_arguments(g.functional.func), + dispatcher.jit_arguments(target_f.func), + ): + if a_tgt.annotation is not None and a_tgt.annotation.is_write: + clone_mutable_inputs.append( + f"auto {a_curr.name}_clone = clone_arg({a_curr.name});" + ) + context.append( + Expr( + expr=f"{a_curr.name}_clone", + type=dispatcher.argument_type(a_curr, binds=a_curr.name), + ) + ) + # Invariant: mutable arguments on the inner mutable op are always returns on the functional op. + cloned_return_names.append(f"{a_curr.name}_clone") + else: + context.append(dispatcher.argument(a_curr)) + exprs = ", ".join([e.expr for e in translate(context, target_sig.arguments())]) + + out_name = "output" + maybe_assign = f"auto {out_name} = " if len(target_f.func.returns) > 0 else "" + inner_return_names = gather_nonaliased_inner_rets(target_f.func, out_name) + ret_str = return_str( + g.functional.func.returns, inner_return_names + cloned_return_names + ) + + clone_mutable_inputs_str = "\n".join(clone_mutable_inputs) + return f""" +{sig.defn(name=sig.name() + ("_symint" if g.out.func.has_symint() else ""))} {{ + {clone_mutable_inputs_str} + {maybe_assign}at::_ops::{target_f.func.name.unambiguous_name()}::call({exprs}); + {ret_str} +}} +""" + + +# Generates out= kernels in terms of their functional counterparts. +# We only do this for "generated" NativeFunctions +@with_native_function +def gen_composite_out_kernel(g: NativeFunctionsGroup) -> str | None: + # We should only be generating these for code-generated NativeFunctions + if "generated" not in g.out.tags: + return None + # And we always write the kernel for the out= op in terms of the functional. + # Note that the functional op might have also been generated, but we don't have to + # worry about cycles, because the generated functional kernels are always implemented + # in terms of non-generated kernels (see gen_composite_functional_kernel). + + sig = DispatcherSignature(g.out.func) + target_sig = DispatcherSignature(g.functional.func) + + exprs = ", ".join( + [e.expr for e in translate(sig.arguments(), target_sig.arguments())] + ) + + copy_outs = [] + out_name = "tmp_output" + for i, out_arg in enumerate(g.out.func.arguments.out): + functional_return_name = ( + out_name + if len(g.functional.func.returns) == 1 + else f"std::get<{i}>({out_name})" + ) + copy_outs.append( + f"""\ + resize_out_helper({out_arg.name}, {functional_return_name}); + copy_arg({out_arg.name}, {functional_return_name});""" + ) + + rets = [] + # For each return arg in the calling (out=) operator, + # If it corresponds to an aliased input, return the input. + # Otherwise, return the corresponding output from calling the functional operator. + for i, ret_name in enumerate(g.out.func.aliased_return_names()): + if ret_name is not None: + rets.append(ret_name) + else: + functional_return_name = ( + out_name + if len(g.functional.func.returns) == 1 + else f"std::get<{i}>({out_name})" + ) + rets.append(functional_return_name) + + copy_outs_str = "\n".join(copy_outs) + + # Kernel name needs to follow the naming convention defined in `generate_function()` + return f""" +{sig.defn(name=g.out.func.name.unambiguous_name() + ("_symint" if g.out.func.has_symint() else ""))} {{ + auto {out_name} = at::_ops::{g.functional.func.name.unambiguous_name()}::call({exprs}); + {copy_outs_str} + {return_str(g.out.func.returns, rets)} +}} +""" diff --git a/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__init__.py b/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..072438a5de3df0ae2e05297c1c52ef737d5ed58d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea7299a38b8ead28ec083539787968c71ace212e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders_constant.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders_constant.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20b9ee4c1f560db1079b5f91743a583cf4905a1c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/operator_versions/__pycache__/gen_mobile_upgraders_constant.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/operator_versions/gen_mobile_upgraders.py b/.venv/lib/python3.12/site-packages/torchgen/operator_versions/gen_mobile_upgraders.py new file mode 100644 index 0000000000000000000000000000000000000000..f5c42b4e22cadc0aade34c081dbeac6ce5633fb7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/operator_versions/gen_mobile_upgraders.py @@ -0,0 +1,390 @@ +#!/usr/bin/env python3 + +from __future__ import annotations + +import os +from enum import Enum +from operator import itemgetter +from pathlib import Path +from typing import Any + +import torch +from torch.jit.generate_bytecode import generate_upgraders_bytecode +from torchgen.code_template import CodeTemplate +from torchgen.operator_versions.gen_mobile_upgraders_constant import ( + MOBILE_UPGRADERS_HEADER_DESCRIPTION, +) + + +class ByteCode(Enum): + instructions = 1 + constants = 2 + types = 3 + operators = 4 + register_size = 5 + + +EXCLUDED_OP_SET = [ + "aten::full.names", + "aten::full.out", + "aten::full", +] + +EXCLUE_UPGRADER_SET = ["full_0_4", "full_out_0_4"] + +ONE_INSTRUCTION = CodeTemplate( + """ + Instruction{OpCode::${operator_name}, ${X}, ${N}},""" +) + +INSTRUCTION_LIST = CodeTemplate( + """std::vector({ + ${instruction_list} + }), // instructions list""" +) + +ONE_CONSTANT = CodeTemplate( + """ + c10::IValue(${constant}),""" +) + +CONSTANT_LIST = CodeTemplate( + """std::vector({ + ${constant_list} + }), // constants list""" +) + +CONSTANTS_LIST_EMPTY = """std::vector(), // constants list""" + +ONE_TYPE = CodeTemplate("""c10::parseType("${type_str}"),""") + +TYPE_LIST = CodeTemplate( + """std::vector({ + ${type_list} + }), // types list""" +) + +TYPE_LIST_EMPTY = """std::vector(), // types list""" + +ONE_OPERATOTR_STRING = CodeTemplate( + """ + OperatorString({"${operator_name}", "${overload_name}", ${num_of_args}}),""" +) + +OPERATOR_STRING_LIST = CodeTemplate( + """ + std::vector({ + ${operator_string_list} + }), // operators list""" +) + +ONE_UPGRADER_FUNCTION = CodeTemplate( + """ + mobile::Function::registerFunc( + "${upgrader_name}", + ${instruction_list}, + ${constant_list}, + ${type_list}, + ${register_size} + )""" +) + +ONE_UPGRADER_SRC = CodeTemplate( + """ + ByteCodeFunctionWithOperator({ + ${bytecode_function}, + ${operator_string_list} + }),""" +) + + +ONE_UPGRADER_IN_VERSION_MAP = CodeTemplate( + """Upgrader({${upgrader_min_version}, ${upgrader_max_version}, "${upgrader_name}", ${bytecode_func_index}})""" +) + +ONE_OPERATOR_IN_VERSION_MAP = CodeTemplate( + """ + {std::string("${operator_name}"), + std::vector({ + ${upgrader_list_in_version_map} + })},""" +) + + +OPERATOR_VERSION_MAP = CodeTemplate( + """ +const std::unordered_map> +getOperatorVersionMapForMobile() { + static std::unordered_map> + operatorVersionMapForMobile({ + ${operator_list_in_version_map} + }); + return operatorVersionMapForMobile; +} +""" +) + + +UPGRADER_CPP_SRC = CodeTemplate( + MOBILE_UPGRADERS_HEADER_DESCRIPTION + + """ +#include +#include +#include + +namespace torch { +namespace jit { + +// clang-format off + +// From operator_versions_map +${operator_version_map} + +const std::vector& getUpgraderBytecodeList() { + auto generate_upgrader_bytecode_list = []() { + std::vector upgrader_function_list({ + ${upgrader_bytecode} + }); + for (const auto& upgrader_function : upgrader_function_list) { + for (const auto& op : upgrader_function.operators) { + upgrader_function.function.append_operator( + op.name, + op.overload_name, + op.num_specified_args); + } + } + return upgrader_function_list; + }; + static std::vector upgraderBytecodeList = + generate_upgrader_bytecode_list(); + return upgraderBytecodeList; +} + +// clang-format on + +} // namespace jit +} // namespace torch +""" +) + +UPGRADER_MOBILE_FILE_NAME = "upgrader_mobile.cpp" + +UPGRADER_ELEMENT = CodeTemplate( + """\ +Upgrader({${min_version}, ${max_version}, ${operator_name}, ${index}}), +""" +) + +PER_OPERATOR_UPGRADER_LIST = CodeTemplate( + """\ +{ + std::string(${operator_name}), + std::vector({${upgrader_list}}); +} +""" +) + + +def construct_instruction(instruction_list_from_yaml: list[Any]) -> str: + instruction_list_part = [ + ONE_INSTRUCTION.substitute( + operator_name=instruction[0], + X=instruction[1], + N=instruction[2], + ) + for instruction in instruction_list_from_yaml + ] + return INSTRUCTION_LIST.substitute( + instruction_list="".join(instruction_list_part).lstrip("\n") + ) + + +def construct_constants(constants_list_from_yaml: list[Any]) -> str: + constants_list_part = [] + for constant_from_yaml in constants_list_from_yaml: + convert_constant = None + if isinstance(constant_from_yaml, str): + # Add quotes if it's string + convert_constant = f'"{constant_from_yaml}"' + elif isinstance(constant_from_yaml, bool): + convert_constant = "true" if constant_from_yaml else "false" + elif constant_from_yaml is None: + convert_constant = "" + elif isinstance(constant_from_yaml, int): + convert_constant = str(constant_from_yaml) + else: + raise ValueError( + f"The type of {constant_from_yaml} is {type(constant_from_yaml)}. " + "Please add change in construct_constants function in gen_mobile_upgraders.py." + ) + constants_list_part.append(ONE_CONSTANT.substitute(constant=convert_constant)) + if len(constants_list_part) == 0: + return CONSTANTS_LIST_EMPTY + return CONSTANT_LIST.substitute( + constant_list="".join(constants_list_part).lstrip("\n") + ) + + +def construct_operators(operator_list_from_yaml: list[Any]) -> str: + operator_list_part = [ + ONE_OPERATOTR_STRING.substitute( + operator_name=operator[0], + overload_name=operator[1], + num_of_args=operator[2], + ) + for operator in operator_list_from_yaml + ] + return OPERATOR_STRING_LIST.substitute( + operator_string_list="".join(operator_list_part).lstrip("\n") + ) + + +def construct_types(types_tr_list_from_yaml: list[Any]) -> str: + types_tr_list_part = [ + ONE_TYPE.substitute(type_str=types_tr) for types_tr in types_tr_list_from_yaml + ] + if len(types_tr_list_part) == 0: + return TYPE_LIST_EMPTY + return TYPE_LIST.substitute(type_list="".join(types_tr_list_part).lstrip("\n")) + + +def construct_register_size(register_size_from_yaml: int) -> str: + if not isinstance(register_size_from_yaml, int): + raise ValueError( + f"Input register size is {register_size_from_yaml} and" + "it's type is {type(register_size_from_yaml)}. An int type is expected." + ) + return str(register_size_from_yaml) + + +def construct_version_maps( + upgrader_bytecode_function_to_index_map: dict[str, Any], +) -> str: + version_map = torch._C._get_operator_version_map() + sorted_version_map_ = sorted(version_map.items(), key=itemgetter(0)) # type: ignore[no-any-return] + sorted_version_map = dict(sorted_version_map_) + + operator_list_in_version_map_part = [] + for op_name in sorted_version_map: + upgraders_in_version_map_part = [] + # TODO: remove the skip after these two operators schemas are fixed + if op_name in EXCLUDED_OP_SET: + continue + upgrader_ranges = torch._C._get_upgrader_ranges(op_name) + upgrader_entries = sorted_version_map[op_name] + if len(upgrader_ranges) != len(upgrader_entries): + raise AssertionError( + f"upgrader_ranges and upgrader_entries length mismatch for {op_name}: " + f"{len(upgrader_ranges)} != {len(upgrader_entries)}" + ) + for idx, upgrader_entry in enumerate(upgrader_entries): + upgrader_name = upgrader_entry.upgrader_name + bytecode_function_index = upgrader_bytecode_function_to_index_map[ + upgrader_name + ] + upgraders_in_version_map_part.append( + ONE_UPGRADER_IN_VERSION_MAP.substitute( + upgrader_min_version=upgrader_ranges[idx].min_version, + upgrader_max_version=upgrader_ranges[idx].max_version, + upgrader_name=upgrader_name, + bytecode_func_index=bytecode_function_index, + ) + ) + operator_list_in_version_map_part.append( + ONE_OPERATOR_IN_VERSION_MAP.substitute( + operator_name=op_name, + upgrader_list_in_version_map="".join(upgraders_in_version_map_part), + ) + ) + return OPERATOR_VERSION_MAP.substitute( + operator_list_in_version_map="".join(operator_list_in_version_map_part).lstrip( + "\n" + ) + ) + + +def get_upgrader_bytecode_function_to_index_map( + upgrader_dict: list[dict[str, Any]], +) -> dict[str, Any]: + upgrader_bytecode_function_to_index_map = {} + index = 0 + for upgrader_bytecode in upgrader_dict: + for upgrader_name in upgrader_bytecode: + if upgrader_name in EXCLUE_UPGRADER_SET: + continue + upgrader_bytecode_function_to_index_map[upgrader_name] = index + index += 1 + return upgrader_bytecode_function_to_index_map + + +def write_cpp(cpp_path: str, upgrader_dict: list[dict[str, Any]]) -> None: + upgrader_bytecode_function_to_index_map = ( + get_upgrader_bytecode_function_to_index_map(upgrader_dict) + ) + version_map_src = construct_version_maps(upgrader_bytecode_function_to_index_map) + all_upgrader_src_string = [] + for upgrader_bytecode in upgrader_dict: + for upgrader_name, bytecode in upgrader_bytecode.items(): + # TODO: remove the skip after these two operators schemas are fixed + if upgrader_name in EXCLUE_UPGRADER_SET: + continue + instruction_list_str = "" + constant_list_str = "" + type_list_str = "" + register_size_str = "" + operator_list_str = "" + for table_name, contents in bytecode.items(): + element = ByteCode[table_name] + if element is ByteCode.instructions: + instruction_list_str = construct_instruction(contents) + elif element is ByteCode.constants: + constant_list_str = construct_constants(contents) + elif element is ByteCode.operators: + operator_list_str = construct_operators(contents) + elif element is ByteCode.types: + type_list_str = construct_types(contents) + elif element is ByteCode.register_size: + register_size_str = construct_register_size(contents) + + one_upgrader_function_string = ONE_UPGRADER_FUNCTION.substitute( + upgrader_name=upgrader_name, + instruction_list=instruction_list_str, + constant_list=constant_list_str, + type_list=type_list_str, + register_size=register_size_str, + ) + one_upgrader_src_string = ONE_UPGRADER_SRC.substitute( + bytecode_function=one_upgrader_function_string.lstrip("\n"), + operator_string_list=operator_list_str.lstrip("\n"), + ) + all_upgrader_src_string.append(one_upgrader_src_string) + + upgrader_file_content = UPGRADER_CPP_SRC.substitute( + operator_version_map=version_map_src, + upgrader_bytecode="".join(all_upgrader_src_string).lstrip("\n"), + ) + print("writing file to : ", cpp_path + "/" + UPGRADER_MOBILE_FILE_NAME) + with open(os.path.join(cpp_path, UPGRADER_MOBILE_FILE_NAME), "wb") as out_file: + out_file.write(upgrader_file_content.encode("utf-8")) + + +def sort_upgrader(upgrader_list: list[dict[str, Any]]) -> list[dict[str, Any]]: + sorted_upgrader_list = sorted( + upgrader_list, key=lambda one_upgrader: next(iter(one_upgrader)) + ) + return sorted_upgrader_list + + +def main() -> None: + upgrader_list = generate_upgraders_bytecode() + sorted_upgrader_list = sort_upgrader(upgrader_list) + for up in sorted_upgrader_list: + print("after sort upgrader : ", next(iter(up))) + + pytorch_dir = Path(__file__).resolve().parents[2] + upgrader_path = pytorch_dir / "torch" / "csrc" / "jit" / "mobile" + write_cpp(str(upgrader_path), sorted_upgrader_list) + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torchgen/operator_versions/gen_mobile_upgraders_constant.py b/.venv/lib/python3.12/site-packages/torchgen/operator_versions/gen_mobile_upgraders_constant.py new file mode 100644 index 0000000000000000000000000000000000000000..04b5ad887e54153115eeca7b6686d7c2de8dfc06 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/operator_versions/gen_mobile_upgraders_constant.py @@ -0,0 +1,7 @@ +MOBILE_UPGRADERS_HEADER_DESCRIPTION = """/** + * @generated + * This is an auto-generated file. Please do not modify it by hand. + * To re-generate, please run: + * cd ~/pytorch && python torchgen/operator_versions/gen_mobile_upgraders.py + */ +""" diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/native/native_functions.yaml b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/native/native_functions.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ec0fefa69582b06496295be1b69c46e65d7bbdb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/native/native_functions.yaml @@ -0,0 +1,16239 @@ +# See README.md in this directory for more guidance + +# *********NB: _cast_* operators are DEPRECATED and will be removed +# eventually. These were previously used before TorchScript IR supported +# representing ScalarType's. They are now superseded by usage of +# `aten::to()`. The ops remain here for backward compatibility purposes. + +# DEPRECATED. DO NOT USE +- func: _cast_Byte(Tensor self, bool non_blocking=False) -> Tensor + variants: function + +# DEPRECATED. DO NOT USE +- func: _cast_Char(Tensor self, bool non_blocking=False) -> Tensor + variants: function + +# DEPRECATED. DO NOT USE +- func: _cast_Double(Tensor self, bool non_blocking=False) -> Tensor + variants: function + +# DEPRECATED. DO NOT USE +- func: _cast_Float(Tensor self, bool non_blocking=False) -> Tensor + variants: function + +# DEPRECATED. DO NOT USE +- func: _cast_Int(Tensor self, bool non_blocking=False) -> Tensor + variants: function + +# DEPRECATED. DO NOT USE +- func: _cast_Long(Tensor self, bool non_blocking=False) -> Tensor + variants: function + +# DEPRECATED. DO NOT USE +- func: _cast_Short(Tensor self, bool non_blocking=False) -> Tensor + variants: function + +# DEPRECATED. DO NOT USE +- func: _cast_Half(Tensor self, bool non_blocking=False) -> Tensor + variants: function + +# Computes the gradient of current tensor w.r.t. graph leaves. +- func: _backward(Tensor self, Tensor[] inputs, Tensor? gradient=None, bool? retain_graph=None, bool create_graph=False) -> () + manual_cpp_binding: True + variants: method + +# DEPRECATED. Sets the tensor data held by this `Variable` to be the same as +# `new_data`. It requires that `new_data` and `Variable` have compatible tensor +# type, by checking `_has_compatible_shallow_copy_type(this, new_data)`. +# +# This function is deprecated because it doesn't really make sense in a world +# where Variables *are* Tensors (as opposed to them containing tensors, which +# is what the previous interpretation was.) +- func: set_data(Tensor(a!) self, Tensor new_data) -> () + manual_cpp_binding: True + variants: method + +- func: data(Tensor self) -> Tensor + manual_cpp_binding: True + variants: method + +# True if this `Variable` is a leaf and thus does not have a `grad_fn`. +- func: is_leaf(Tensor self) -> bool + manual_cpp_binding: True + variants: method + +# Returns the output index of this variable from the forward operation that +# produced it. Conversely, it returns the input index of the gradient `Node` to +# which this `Variable` is connected (because in the gradient computation, +# inputs and outputs switch meaning). For example: +# +# y0, y1, y2 = f(x) +# assert y0.output_nr == 0 +# assert y1.output_nr == 1 +# assert y2.output_nr == 2 +# +- func: output_nr(Tensor self) -> int + manual_cpp_binding: True + variants: method + +- func: _version(Tensor self) -> int + manual_cpp_binding: True + variants: method + +- func: requires_grad_(Tensor(a!) self, bool requires_grad=True) -> Tensor(a!) + manual_cpp_binding: True + variants: method + +# Enables .grad attribute for non-leaf Tensors. +- func: retain_grad(Tensor(a!) self) -> () + manual_cpp_binding: True + variants: method + +- func: retains_grad(Tensor self) -> bool + manual_cpp_binding: True + variants: method + +- func: _fw_primal(Tensor(a) self, int level) -> Tensor(a) + variants: method + dispatch: + CompositeExplicitAutograd: _fw_primal + +- func: _make_dual(Tensor(a) primal, Tensor tangent, int level) -> Tensor(a) + variants: function + dispatch: + CompositeExplicitAutograd: _make_dual + +- func: _unpack_dual(Tensor(a) dual, int level) -> (Tensor(a) primal, Tensor tangent) + variants: function + +# NOTE: [_new_zeros_with_same_feature_meta] +# This function creates a new tensor with the layout and TensorOptions +# of `other` but also takes into account the batch dimensions of `self` +# +# This function has a couple extra constraints because it is also used for `jvp` +# in functorch. +# - is used for forward AD because there is the restriction +# that the primal and tangent must have the same layout +# - We cannot assume that `self` and `other` have the same sizes or even dim +# because in the inplace over view case, `other` is the base tensor, and +# `self` is the forward grad with respect to the view, which can have an +# entirely different shape +# - takes the number of batch dims for `self` because we also handle +# some batching logic. We handle that here instead of a batching rule because +# we'd like to avoid calling as_strided in the batching rule (as to enable +# nested vmap in functorch). +# - needs to be CompositeExplicitAutograd for jvp support in functorch. +# functorch currently relies on TensorWrapper which does not have storage +# CompositeExplicitAutograd makes sure the TensorWrapper is unwrapped. +# - this function may eventually take on another int argument to store the +# the number of batch dims for other once we support that use case +- func: _new_zeros_with_same_feature_meta(Tensor self, Tensor other, *, int self_num_batch_dims=0) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: _new_zeros_with_same_feature_meta + autogen: _new_zeros_with_same_feature_meta.out + +# This function compares the storage numel of self with that of other, where +# storage numel is computed as: `other.storage().nbytes() / other.itemsize()`. +# We create this function for composite compliance purposes. The batching rule +# always returns true because vmapped as_strided does not support accessing +# storage locations not indexable by the input tensor. +# See the note above for more information. +- func: _has_same_storage_numel(Tensor self, Tensor other) -> bool + variants: function + dispatch: + CompositeExplicitAutograd: _has_same_storage_numel + +# Not assert because it's a keyword; not Assert because FX already +# took that syntax +# TODO: need to specify this is side-effectful somehow +- func: _assert_async(Tensor self) -> () + dispatch: + CPU: _assert_async_cpu + CUDA: _assert_async_cuda + MPS: _assert_async_mps + XPU: _assert_async_xpu + +- func: _assert_async.msg(Tensor self, str assert_msg) -> () + dispatch: + CPU: _assert_async_msg_cpu + CUDA: _assert_async_msg_cuda + MPS: _assert_async_msg_mps + XPU: _assert_async_msg_xpu + +- func: _assert_scalar(Scalar self, str assert_msg) -> () + dispatch: + CompositeExplicitAutograd: _assert_scalar + +- func: _functional_assert_scalar(Scalar self, str assert_msg, Tensor dep_token) -> Tensor + dispatch: + CompositeExplicitAutograd: _functional_assert_scalar + +- func: _functional_assert_async.msg(Tensor self, str assert_msg, Tensor dep_token) -> Tensor + dispatch: + CPU: _functional_assert_async_msg_cpu + +- func: _assert_tensor_metadata(Tensor a, SymInt[]? size=None, SymInt[]? stride=None, ScalarType? dtype=None, *, Device? device=None, Layout? layout=None) -> () + dispatch: + CompositeExplicitAutograd: _assert_tensor_metadata + Meta: _assert_tensor_metadata_meta_symint + +- func: _print(str s) -> () + dispatch: + CompositeExplicitAutograd: _print + +- func: sym_constrain_range(Scalar size, *, int? min=None, int? max=None) -> () + dispatch: + CompositeExplicitAutograd: sym_constrain_range + +- func: sym_constrain_range_for_size(Scalar size, *, int? min=None, int? max=None) -> () + dispatch: + CompositeExplicitAutograd: sym_constrain_range_for_size + +- func: _functional_sym_constrain_range(Scalar size, int? min, int? max, Tensor dep_token) -> Tensor + dispatch: + CompositeExplicitAutograd: _functional_sym_constrain_range + +- func: _functional_sym_constrain_range_for_size(Scalar size, int? min, int? max, Tensor dep_token) -> Tensor + dispatch: + CompositeExplicitAutograd: _functional_sym_constrain_range_for_size + +- func: _make_dep_token(*, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + dispatch: + CPU: _make_dep_token_cpu + +- func: _use_cudnn_ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank) -> bool + device_check: NoCheck # Tensor arguments allowed to be on different devices, see also _cudnn_ctc_loss + dispatch: + CUDA: _use_cudnn_ctc_loss + +- func: _use_cudnn_ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank) -> bool + device_check: NoCheck # Tensor arguments allowed to be on different devices, see also _cudnn_ctc_loss + dispatch: + CUDA: _use_cudnn_ctc_loss_tensor + +- func: _cudnn_ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor) + device_check: NoCheck # log_probs is expected to be on CUDA while targets is expected to be on CPU + dispatch: + CUDA: _cudnn_ctc_loss + autogen: _cudnn_ctc_loss.out + +- func: _cudnn_ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor) + device_check: NoCheck # log_probs is expected to be on CUDA while targets is expected to be on CPU + dispatch: + CUDA: _cudnn_ctc_loss_tensor + +- func: _use_cudnn_rnn_flatten_weight() -> bool + +- func: _cudnn_rnn_flatten_weight(Tensor[] weight_arr, int weight_stride0, SymInt input_size, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, bool bidirectional) -> Tensor + dispatch: + CUDA: _cudnn_rnn_flatten_weight + autogen: _cudnn_rnn_flatten_weight.out + +- func: _cudnn_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor? weight_buf, Tensor hx, Tensor? cx, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor) + # rnn_tanh may or may not redispatch to _cudnn_rnn based on algorithm and build. Thus it might hit dispatch or kernel device check. + # Disable dispatch time device check for consistent behavior. + device_check: NoCheck + dispatch: + CUDA: _cudnn_rnn + autogen: _cudnn_rnn.out + tags: nondeterministic_seeded + +- func: _cudnn_rnn_backward(Tensor input, Tensor[] weight, int weight_stride0, Tensor weight_buf, Tensor hx, Tensor? cx, Tensor output, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state, Tensor reserve, bool[4] output_mask) -> (Tensor, Tensor, Tensor, Tensor[]) + dispatch: + CUDA: _cudnn_rnn_backward + autogen: _cudnn_rnn_backward.out + +- func: _cudnn_init_dropout_state(float dropout, bool train, int dropout_seed, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor + dispatch: + CUDA: _cudnn_init_dropout_state + autogen: _cudnn_init_dropout_state.out + tags: nondeterministic_seeded + +- func: _debug_has_internal_overlap(Tensor self) -> int + variants: function + +- func: _fused_dropout(Tensor self, float p, Generator? generator=None) -> (Tensor, Tensor) + variants: function + dispatch: + CUDA: fused_dropout_cuda + XPU: fused_dropout_xpu + tags: nondeterministic_seeded + autogen: _fused_dropout.out + +- func: _masked_scale(Tensor self, Tensor mask, float scale) -> Tensor + variants: function + dispatch: + CUDA: masked_scale_cuda + XPU: masked_scale_xpu + autogen: _masked_scale.out + +- func: native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor) + variants: function + dispatch: + CPU: native_dropout_cpu + CUDA: native_dropout_cuda + MPS: native_dropout_mps + XPU: native_dropout_xpu + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: native_dropout_nested + tags: [nondeterministic_seeded, core] + autogen: native_dropout.out + +- func: native_dropout_backward(Tensor grad_output, Tensor mask, float scale) -> Tensor + dispatch: + CPU, NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: native_dropout_backward + CUDA: native_dropout_backward_cuda + MPS: native_dropout_backward_mps + XPU: native_dropout_backward_xpu + autogen: native_dropout_backward.out + tags: pointwise + +- func: _sobol_engine_draw(Tensor quasi, int n, Tensor sobolstate, int dimension, int num_generated, ScalarType? dtype) -> (Tensor, Tensor) + +- func: _sobol_engine_ff_(Tensor(a!) self, int n, Tensor sobolstate, int dimension, int num_generated) -> Tensor(a!) + +- func: _sobol_engine_scramble_(Tensor(a!) self, Tensor ltm, int dimension) -> Tensor(a!) + +- func: _sobol_engine_initialize_state_(Tensor(a!) self, int dimension) -> Tensor(a!) + +- func: _reshape_from_tensor(Tensor self, Tensor shape) -> Tensor + +- func: _shape_as_tensor(Tensor self) -> Tensor + +- func: dropout(Tensor input, float p, bool train) -> Tensor + tags: [nondeterministic_seeded, maybe_aliasing_or_mutating] + +- func: dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!) + tags: nondeterministic_seeded + +- func: feature_dropout(Tensor input, float p, bool train) -> Tensor + tags: [nondeterministic_seeded, maybe_aliasing_or_mutating] + +- func: feature_dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!) + tags: nondeterministic_seeded + +- func: alpha_dropout(Tensor input, float p, bool train) -> Tensor + tags: [nondeterministic_seeded, maybe_aliasing_or_mutating] + +- func: alpha_dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!) + tags: nondeterministic_seeded + +- func: feature_alpha_dropout(Tensor input, float p, bool train) -> Tensor + tags: [nondeterministic_seeded, maybe_aliasing_or_mutating] + +- func: feature_alpha_dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!) + tags: nondeterministic_seeded + +- func: abs(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: abs + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: abs_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta, SparseCsrXPU: abs_sparse_csr + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_abs + tags: [core, pointwise] + +- func: abs_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: abs_ + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: abs_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta, SparseCsrXPU: abs_sparse_csr_ + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_abs_ + +- func: abs.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: abs_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: abs_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta, SparseCsrXPU: abs_sparse_csr_out + tags: pointwise + +# Note [Adding an alias] +# To add an alias do the following: +# +# 1) Copy the original functions native_functions.yaml entry, but replace the +# original function's name with their own and delete any dispatch +# keys for the aliases. Specifying a dispatch key will prevent +# autograd from recording the operations the alias performs, which +# will stop it from "inheriting" the original operation's autograd behavior. +# 2) Implement the corresponding functions and have them redispatch to the +# original function. +# 3) Add docstrings to the new function that reference the original function, +# and document the method as usual (if it exists.) +# (See torch/_torch_docs.py and docs/source/torch.rst if adding a function, +# torch/_tensor_docs.py and docs/source/tensors.rst if adding a method, +# or module-specific doc bindings (like torch/linalg/__init__.py) if +# adding an alias in a namespace.) +# 4) Update torch/overrides.py consistent with the original function. +# 5) Update the alias_map in torch/csrc/jit/passes/normalize_ops.cpp. +# 6) Add aliases argument to existing OpInfo/UnaryUfuncInfo or create new OpInfo/UnaryUfuncInfo entry +# in op_db list in torch/testing/_internal/common_methods_invocations.py +# +# See torch.absolute, an alias for torch.abs, as an example. +# Absolute, alias for abs + +- func: absolute(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + +- func: absolute_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + +- func: absolute.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + +- func: angle(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CPU, CUDA, MPS, XPU: angle + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: angle_sparse_csr + tags: pointwise + +- func: angle.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, XPU: angle_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: angle_sparse_csr_out + tags: pointwise + +- func: view_as_real(Tensor(a) self) -> Tensor(a) + variants: function + dispatch: + CPU, CUDA, MPS, Meta, XPU: view_as_real + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: view_as_real_sparse + +- func: view_as_complex(Tensor(a) self) -> Tensor(a) + variants: function + dispatch: + CPU, CUDA, MPS, Meta, XPU: view_as_complex + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: view_as_complex_sparse + +- func: sgn(Tensor self) -> Tensor + variants: function, method + structured_delegate: sgn.out + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sgn_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sgn_sparse_csr + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_sgn + tags: pointwise + +- func: sgn_(Tensor(a!) self) -> Tensor(a!) + variants: method + structured_delegate: sgn.out + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sgn_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sgn_sparse_csr_ + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_sgn_ + tags: pointwise + +- func: sgn.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, XPU: sgn_out + MPS: sgn_out_mps + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sgn_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sgn_sparse_csr_out + tags: pointwise + +- func: chalf(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor + variants: method + +- func: real(Tensor(a) self) -> Tensor(a) + device_check: NoCheck # TensorIterator + variants: function + +- func: imag(Tensor(a) self) -> Tensor(a) + device_check: NoCheck # TensorIterator + variants: function + +- func: _conj(Tensor(a) self) -> Tensor(a) + variants: function, method + dispatch: + CompositeExplicitAutograd: _conj + +- func: conj(Tensor(a) self) -> Tensor(a) + variants: function, method + manual_cpp_binding: True + +- func: _conj_physical(Tensor self) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: _conj_physical + SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta, SparseCsrXPU: conj_physical_sparse_csr + autogen: _conj_physical.out + tags: pointwise + +- func: conj_physical(Tensor self) -> Tensor + variants: function, method + tags: [pointwise, maybe_aliasing_or_mutating] + +- func: conj_physical.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, XPU: conj_physical_out + MPS: conj_physical_out_mps + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: conj_physical_out_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta, SparseCsrXPU: conj_physical_sparse_csr_out + tags: pointwise + +- func: conj_physical_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + dispatch: + CompositeExplicitAutograd: conj_physical_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: conj_physical_sparse_csr_ + tags: pointwise + +- func: resolve_conj(Tensor(a) self) -> Tensor(a) + variants: function, method + +- func: resolve_neg(Tensor(a) self) -> Tensor(a) + variants: function, method + +- func: _neg_view(Tensor(a) self) -> Tensor(a) + variants: function, method + dispatch: + CompositeExplicitAutograd: _neg_view + +- func: acos(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: acos.out + tags: [core, pointwise] + +- func: acos_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: acos.out + tags: pointwise + +- func: acos.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: acos_out + tags: pointwise + +# arccos, alias of acos +- func: arccos(Tensor self) -> Tensor + variants: function, method + +- func: arccos_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + +- func: arccos.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + +- func: avg_pool1d(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, bool ceil_mode=False, bool count_include_pad=True) -> Tensor + tags: core + autogen: avg_pool1d.out + +- func: adaptive_avg_pool1d(Tensor self, int[1] output_size) -> Tensor + tags: core + autogen: adaptive_avg_pool1d.out + +# Return: (Tensor output, Tensor indices) +- func: adaptive_max_pool1d(Tensor self, int[1] output_size) -> (Tensor, Tensor) + +- func: add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: add.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: add_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: add_sparse_csr + MkldnnCPU: mkldnn_add + ZeroTensor: add_zerotensor + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_add_Tensor + tags: [core, pointwise] + +- func: add_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: add.out + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: add_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: add_sparse_csr_ + MkldnnCPU: mkldnn_add_ + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_add__Tensor + tags: pointwise + +- func: add.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + ufunc_inner_loop: + Generic: add (AllAndComplex, BFloat16, Half, ComplexHalf) + ScalarOnly: add (Bool) + dispatch: + SparseCPU, SparseMeta: add_out_sparse_cpu + SparseCUDA: add_out_sparse_cuda + SparseMPS: add_out_sparse_mps + SparseXPU: add_out_sparse_xpu + SparseCsrCPU, SparseCsrMeta: add_out_sparse_compressed_cpu + SparseCsrCUDA: add_out_sparse_compressed_cuda + SparseCsrXPU: add_out_sparse_compressed_xpu + MkldnnCPU: mkldnn_add_out + MPS: add_out_mps + MTIA: add_out_mtia + XPU: add_out_xpu + tags: pointwise + +- func: _add_relu.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor + variants: function + dispatch: + CPU: add_relu + +- func: _add_relu_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!) + variants: function + dispatch: + CPU: add_relu_ + +- func: _add_relu.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + variants: function + dispatch: + CPU: add_relu_out + +- func: _add_relu.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor + variants: function + dispatch: + CPU: add_relu + +- func: _add_relu_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!) + variants: function + dispatch: + CPU: add_relu_ + autogen: _add_relu.Scalar_out + +# For C++ only, until we have conversion from C++ numbers to Tensor +- func: add.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: add + tags: [core, pointwise] + +- func: add_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: add_ + autogen: add.Scalar_out + tags: pointwise + +- func: addmv(Tensor self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1) -> Tensor + structured_delegate: addmv.out + variants: function, method + +- func: addmv_(Tensor(a!) self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) + structured_delegate: addmv.out + variants: function, method + +- func: addmv.out(Tensor self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU: addmv_out_cpu + CUDA: addmv_out_cuda + MPS: addmv_out_mps + XPU: addmv_out_xpu + SparseCsrCPU: addmv_out_sparse_compressed + SparseCsrCUDA: addmv_out_sparse_compressed_cuda + SparseCsrXPU: addmv_out_sparse_compressed_xpu + +- func: addr(Tensor self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + variants: function, method + dispatch: + CPU, CUDA, XPU: addr + MPS: addr_mps + CompositeExplicitAutograd: math_addr + +- func: addr_(Tensor(a!) self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) + variants: method + dispatch: + CompositeExplicitAutograd: addr_ + +- func: addr.out(Tensor self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, XPU: addr_out + MPS: addr_out_mps + CompositeExplicitAutograd: math_addr_out + +- func: affine_grid_generator(Tensor theta, SymInt[] size, bool align_corners) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: affine_grid_generator + autogen: affine_grid_generator.out + +- func: affine_grid_generator_backward(Tensor grad, SymInt[] size, bool align_corners) -> Tensor + variants: function + +- func: _is_all_true(Tensor self) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: _is_all_true + +- func: _is_any_true(Tensor self) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: _is_any_true + +# Note: this function is only for testing. +- func: _test_check_tensor(Tensor self) -> Tensor + variants: function + +# Note; this function is only for testing +- func: _test_functorch_fallback(Tensor self, Tensor other) -> Tensor + variants: function + dispatch: + CPU: _test_functorch_fallback + autogen: _test_functorch_fallback.out + +- func: all.dim(Tensor self, int dim, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: all.out + variants: function, method + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_all + tags: reduction + +- func: all.dims(Tensor self, int[]? dim=None, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: all.dims_out + variants: function, method + cpp_no_default_args: ['dim'] + dispatch: + CompositeExplicitAutograd: all_dims_default + tags: reduction + +- func: all.out(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + dispatch: + CPU, CUDA, MPS, XPU: all_out + MTIA: all_out_mtia + tags: reduction + +- func: all.dims_out(Tensor self, int[]? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + dispatch: + CPU, CUDA, XPU: all_dims_out + CompositeExplicitAutograd: all_dims_out_default + cpp_no_default_args: ['dim'] + tags: reduction + +- func: allclose(Tensor self, Tensor other, float rtol=1e-05, float atol=1e-08, bool equal_nan=False) -> bool + variants: function, method + tags: data_dependent_output + dispatch: + CompositeExplicitAutograd: allclose + +- func: any.dim(Tensor self, int dim, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: any.out + variants: function, method + tags: [core, reduction] + +- func: any.dims(Tensor self, int[]? dim=None, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: any.dims_out + variants: function, method + cpp_no_default_args: ['dim'] + tags: [core, reduction] + dispatch: + CompositeExplicitAutograd: any_dims_default + +- func: any.out(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + dispatch: + CPU, CUDA, MPS, XPU: any_out + tags: reduction + +- func: any.dims_out(Tensor self, int[]? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + dispatch: + CPU, CUDA, XPU: any_dims_out + CompositeExplicitAutograd: any_dims_out_default + cpp_no_default_args: ['dim'] + tags: reduction + +- func: arange(Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: arange + +- func: arange.start(Scalar start, Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: arange + +# This operator should be named `arange.start_out` if following the naming convention. However that +# name is already taken. Disabled because of CI job failures. +# FIXME: enable this +#- func: arange.start_out_(Scalar start, Scalar end, *, Tensor(a!) out) -> Tensor(a!) +# dispatch: +# CompositeExplicitAutograd: arange_start_out + +- func: arange.start_step(Scalar start, Scalar end, Scalar step=1, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: arange + cpp_no_default_args: ['step'] + tags: core + +- func: arange.out(Scalar end, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: arange_out + +- func: arange.start_out(Scalar start, Scalar end, Scalar step=1, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, Meta: arange_out + CUDA: arange_cuda_out + MPS: arange_mps_out + MTIA: arange_mtia_out + XPU: arange_xpu_out + cpp_no_default_args: ['step'] + +# This function is a temporary hack to allow tracing of arange like constructs with dynamic +# bounds on arange. Normal arange is not traceable because it does not take any tensor inputs; +# if the range you need is based on another tensor, calling this function directly will +# preserve tracing. Get rid of this when arange can directly take tensors for bounds +# (so that it can be traced directly). +- func: _dim_arange(Tensor like, int dim) -> Tensor + +- func: argmax(Tensor self, int? dim=None, bool keepdim=False) -> Tensor + structured_delegate: argmax.out + device_check: NoCheck # TensorIterator + variants: function, method + tags: [core, reduction] + +- func: argmax.out(Tensor self, int? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU, CUDA, XPU: argmax_out + MPS: argmax_out_mps + tags: reduction + +- func: argmin(Tensor self, int? dim=None, bool keepdim=False) -> Tensor + structured_delegate: argmin.out + device_check: NoCheck # TensorIterator + variants: function, method + tags: [core, reduction] + +- func: argmin.out(Tensor self, int? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU, CUDA, XPU: argmin_out + MPS: argmin_out_mps + tags: reduction + +- func: acosh(Tensor self) -> Tensor + variants: function, method + structured_delegate: acosh.out + tags: [core, pointwise] + +- func: acosh_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + structured_delegate: acosh.out + tags: pointwise + +- func: acosh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, XPU, MPS: acosh_out + tags: pointwise +# arccosh, alias for acosh + +- func: arccosh(Tensor self) -> Tensor + variants: function, method + +- func: arccosh_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + +- func: arccosh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + +- func: asinh(Tensor self) -> Tensor + variants: function, method + structured_delegate: asinh.out + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: asinh_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: asinh_sparse_csr + tags: [core, pointwise] + +- func: asinh_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + structured_delegate: asinh.out + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: asinh_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: asinh_sparse_csr_ + tags: pointwise + +- func: asinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, XPU, MPS: asinh_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: asinh_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: asinh_sparse_csr_out + tags: pointwise + +# arcsinh, alias for asinh +- func: arcsinh(Tensor self) -> Tensor + variants: function, method + +- func: arcsinh_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + +- func: arcsinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + +- func: atanh(Tensor self) -> Tensor + structured_delegate: atanh.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: atanh_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: atanh_sparse_csr + tags: [core, pointwise] + +- func: atanh_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: atanh.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: atanh_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: atanh_sparse_csr_ + tags: pointwise + +- func: atanh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, XPU, MPS: atanh_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: atanh_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: atanh_sparse_csr_out + tags: pointwise +# arctanh, alias for atanh + +- func: arctanh(Tensor self) -> Tensor + variants: function, method + +- func: arctanh_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + +- func: arctanh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + +- func: as_strided(Tensor(a) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a) + variants: function, method + dispatch: + ZeroTensor, CPU, CUDA, MTIA, MPS, XPU: as_strided_tensorimpl + Meta: as_strided_tensorimpl_meta_symint + QuantizedCPU, QuantizedCUDA: as_strided_qtensorimpl + device_check: NoCheck + device_guard: False + tags: core + +- func: as_strided_(Tensor(a!) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True + variants: function, method + device_check: NoCheck + device_guard: False + tags: inplace_view + dispatch: + CompositeExplicitAutogradNonFunctional: as_strided__symint + +- func: asin(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: asin.out + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: asin_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: asin_sparse_csr + tags: [core, pointwise] + +- func: asin_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: asin.out + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: asin_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: asin_sparse_csr_ + tags: pointwise + +- func: asin.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: asin_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: asin_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: asin_sparse_csr_out + tags: pointwise + +# arcsin, alias of asin +- func: arcsin(Tensor self) -> Tensor + variants: function, method + +- func: arcsin_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + +- func: arcsin.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + +- func: atan(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: atan.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: atan_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: atan_sparse_csr + tags: [core, pointwise] + +- func: atan_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: atan.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: atan_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: atan_sparse_csr_ + tags: pointwise + +- func: atan.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: atan_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: atan_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: atan_sparse_csr_out + tags: pointwise + +# arctan, alias of atan +- func: arctan(Tensor self) -> Tensor + variants: function, method + +- func: arctan_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + +- func: arctan.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + +- func: atleast_1d(Tensor self) -> Tensor + variants: function + tags: maybe_aliasing_or_mutating + +- func: atleast_1d.Sequence(Tensor[] tensors) -> Tensor[] + +- func: atleast_2d(Tensor self) -> Tensor + variants: function + tags: maybe_aliasing_or_mutating + +- func: atleast_2d.Sequence(Tensor[] tensors) -> Tensor[] + variants: function + +- func: atleast_3d(Tensor self) -> Tensor + variants: function + tags: maybe_aliasing_or_mutating + +- func: atleast_3d.Sequence(Tensor[] tensors) -> Tensor[] + variants: function + +- func: baddbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + variants: function, method + structured_delegate: baddbmm.out + +- func: baddbmm_(Tensor(a!) self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) + variants: method + structured_delegate: baddbmm.out + +- func: baddbmm.out(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CPU: baddbmm_out_cpu + CUDA: baddbmm_out_cuda + MPS: baddbmm_out_mps + MTIA: baddbmm_out_mtia + XPU: baddbmm_out_xpu + SparseCsrCUDA: baddbmm_out_sparse_csr_cuda + SparseCsrXPU: baddbmm_out_sparse_csr_xpu + +- func: baddbmm.dtype(Tensor self, Tensor batch1, Tensor batch2, ScalarType out_dtype, *, Scalar beta=1, Scalar alpha=1) -> Tensor + variants: function + dispatch: + CUDA: _baddbmm_dtype_cuda + XPU: _baddbmm_dtype_xpu + +- func: baddbmm.dtype_out(Tensor self, Tensor batch1, Tensor batch2, ScalarType out_dtype, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + variants: function + dispatch: + CUDA: _baddbmm_out_dtype_cuda + XPU: _baddbmm_out_dtype_xpu + +- func: bartlett_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: bartlett_window + autogen: bartlett_window.out + +- func: bartlett_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: bartlett_window + autogen: bartlett_window.periodic_out + +- func: batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> Tensor + tags: maybe_aliasing_or_mutating + +- func: quantized_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor var, float eps, float output_scale, int output_zero_point) -> Tensor + dispatch: + QuantizedCPU: quantized_batch_norm + autogen: quantized_batch_norm.out + +- func: _batch_norm_impl_index(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> (Tensor, Tensor, Tensor, Tensor, int) + tags: maybe_aliasing_or_mutating + +- func: _batch_norm_impl_index_backward(int impl_index, Tensor input, Tensor grad_output, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var_transform, bool train, float eps, bool[3] output_mask, Tensor reservedSpace) -> (Tensor, Tensor, Tensor) + +# Sample bernoulli with values in `self` as probability. +- func: bernoulli(Tensor self, *, Generator? generator=None) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: bernoulli + tags: nondeterministic_seeded + +- func: bernoulli.out(Tensor self, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function + tags: nondeterministic_seeded + dispatch: + CPU, CUDA, MPS, XPU: bernoulli_out + +- func: bernoulli_.Tensor(Tensor(a!) self, Tensor p, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + tags: nondeterministic_seeded + dispatch: + CPU, CUDA, MPS, XPU: bernoulli_ + autogen: bernoulli.Tensor, bernoulli.Tensor_out + +- func: bernoulli_.float(Tensor(a!) self, float p=0.5, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + tags: nondeterministic_seeded + dispatch: + CPU, CUDA, MPS, XPU: bernoulli_ + autogen: bernoulli.float_out + +# Note [bernoulli.p schema] +# We should probably just fix the overload ambiguity by appending a _functional to the C++ API name (BC breaking) +# This out-of-place version isn't used explicitly, but needed by jit. +# There is no default valid on `p` here because it would introduce ambiguity +# with `bernoulli(Tensor self, *, Generator? generator=None)` declaration. +- func: bernoulli.p(Tensor self, float p, *, Generator? generator=None) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutogradNonFunctional: bernoulli + +- func: bilinear(Tensor input1, Tensor input2, Tensor weight, Tensor? bias=None) -> Tensor + +- func: binary_cross_entropy(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor + device_check: NoCheck # TensorIterator + python_module: nn + variants: function + dispatch: + CPU: binary_cross_entropy_cpu + CUDA: binary_cross_entropy_cuda + MPS: binary_cross_entropy_mps + XPU: binary_cross_entropy_xpu + +- func: binary_cross_entropy.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: nn + variants: function + dispatch: + CPU: binary_cross_entropy_out_cpu + CUDA: binary_cross_entropy_out_cuda + MPS: binary_cross_entropy_out_mps + XPU: binary_cross_entropy_out_xpu + +- func: binary_cross_entropy_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor + python_module: nn + variants: function + dispatch: + CPU: binary_cross_entropy_backward_cpu + CUDA: binary_cross_entropy_backward_cuda + MPS: binary_cross_entropy_backward_mps + XPU: binary_cross_entropy_backward_xpu + +- func: binary_cross_entropy_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + variants: function + dispatch: + CPU: binary_cross_entropy_backward_out_cpu + CUDA: binary_cross_entropy_backward_out_cuda + MPS: binary_cross_entropy_backward_out_mps + XPU: binary_cross_entropy_backward_out_xpu + +- func: binary_cross_entropy_with_logits(Tensor self, Tensor target, Tensor? weight=None, Tensor? pos_weight=None, int reduction=Mean) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: binary_cross_entropy_with_logits + autogen: binary_cross_entropy_with_logits.out + +- func: bincount(Tensor self, Tensor? weights=None, SymInt minlength=0) -> Tensor + variants: function, method + dispatch: + CPU: _bincount_cpu + CUDA: _bincount_cuda + MPS: _bincount_mps + XPU: _bincount_xpu + tags: dynamic_output_shape + autogen: bincount.out + +- func: bitwise_not(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: bitwise_not.out + variants: function, method + tags: [core, pointwise] + +- func: bitwise_not_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: bitwise_not.out + variants: method + tags: pointwise + +- func: bitwise_not.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: bitwise_not_out + tags: pointwise + +- func: copysign.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: copysign_out + tags: pointwise + +- func: copysign.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: copysign.out + tags: pointwise + +- func: copysign_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: copysign.out + +- func: copysign.Scalar(Tensor self, Scalar other) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: copysign + tags: pointwise + +- func: copysign_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + variants: method + dispatch: + CompositeExplicitAutograd: copysign_ + +- func: copysign.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: copysign_out + tags: pointwise + +- func: _lazy_clone(Tensor self) -> Tensor + # Like clone, but the copy takes place lazily, only if either the + # input or the output are written. + variants: function, method + dispatch: + CompositeExplicitAutograd: _lazy_clone + +- func: logical_not(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: logical_not + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_logical_not + tags: [core, pointwise] + +- func: logical_not_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: logical_not_ + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_logical_not_ + tags: pointwise + +- func: logical_not.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: logical_not_out + tags: pointwise + +- func: logical_xor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: logical_xor + tags: [core, pointwise] + +- func: logical_xor_(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: logical_xor_ + tags: pointwise + +- func: logical_xor.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MTIA, XPU: logical_xor_out + MPS: logical_xor_out_mps + tags: pointwise + +- func: logical_and(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: logical_and + tags: [core, pointwise] + +- func: logical_and_(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: logical_and_ + tags: pointwise + +- func: logical_and.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MTIA, XPU: logical_and_out + MPS: logical_and_out_mps + tags: pointwise + +- func: logical_or(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: logical_or + tags: [core, pointwise] + +- func: logical_or_(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: logical_or_ + tags: pointwise + +- func: logical_or.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MTIA, XPU: logical_or_out + MPS: logical_or_out_mps + tags: pointwise + +- func: blackman_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: blackman_window + autogen: blackman_window.out + +- func: blackman_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: blackman_window + autogen: blackman_window.periodic_out + +- func: bmm(Tensor self, Tensor mat2) -> Tensor + structured_delegate: bmm.out + variants: function, method + dispatch: + SparseCPU: bmm_sparse_cpu + SparseCUDA: bmm_sparse_cuda + SparseMPS: bmm_sparse_mps + SparseXPU: bmm_sparse_xpu + NestedTensorCPU: bmm_nested + NestedTensorCUDA: bmm_nested_cuda + NestedTensorXPU: bmm_nested_xpu + tags: core + +- func: bmm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CPU: bmm_out_cpu + CUDA: bmm_out_cuda + MPS: bmm_out_mps + MTIA: bmm_out_mtia + XPU: bmm_out_xpu + SparseCPU: bmm_out_sparse_cpu + SparseCUDA: bmm_out_sparse_cuda + SparseMPS: bmm_out_sparse_mps + SparseXPU: bmm_out_sparse_xpu + SparseCsrCUDA: bmm_out_sparse_csr_cuda + SparseCsrXPU: bmm_out_sparse_csr_xpu + +- func: bmm.dtype(Tensor self, Tensor mat2, ScalarType out_dtype) -> Tensor + variants: function + dispatch: + CUDA: _bmm_dtype_cuda + XPU: _bmm_dtype_xpu + +- func: bmm.dtype_out(Tensor self, Tensor mat2, ScalarType out_dtype, *, Tensor(a!) out) -> Tensor(a!) + variants: function + dispatch: + CUDA: _bmm_out_dtype_cuda + XPU: _bmm_out_dtype_xpu + +- func: broadcast_tensors(Tensor[] tensors) -> Tensor[] + device_check: NoCheck + device_guard: False + +- func: broadcast_to(Tensor(a) self, SymInt[] size) -> Tensor(a) + variants: function, method + dispatch: + CompositeImplicitAutograd: broadcast_to_symint + +- func: _sparse_broadcast_to(Tensor(a) self, int[] size) -> Tensor(a) + variants: function + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sparse_broadcast_to + +- func: cat(Tensor[] tensors, int dim=0) -> Tensor + structured_delegate: cat.out + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: cat_sparse + QuantizedCPU: cat_quantized_cpu + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: cat_nested + tags: core + +- func: cat.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!) + structured: True + precomputed: + - dim -> int dim, int valid, bool all_contiguous, bool all_same_dtype, bool all_same_sizes_and_stride, MemoryFormat memory_format + dispatch: + CPU: cat_out_cpu + CUDA: cat_out_cuda + MPS: cat_out_mps + XPU: cat_out_xpu + QuantizedCPU: cat_out_quantized_cpu + +- func: concat(Tensor[] tensors, int dim=0) -> Tensor + +- func: concat.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!) + +- func: concatenate(Tensor[] tensors, int dim=0) -> Tensor + +- func: concatenate.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!) + +- func: block_diag(Tensor[] tensors) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: block_diag + autogen: block_diag.out + +- func: ceil(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: ceil.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: ceil_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: ceil_sparse_csr + tags: [core, pointwise] + +- func: ceil_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: ceil.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: ceil_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: ceil_sparse_csr_ + tags: pointwise + +- func: ceil.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: ceil_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: ceil_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: ceil_sparse_csr_out + tags: pointwise + +# alias for torch.linalg.multi_dot +- func: chain_matmul(Tensor[] matrices) -> Tensor + variants: function + +# alias for torch.linalg.multi_dot +- func: chain_matmul.out(Tensor[] matrices, *, Tensor(a!) out) -> Tensor(a!) + +- func: unsafe_chunk(Tensor self, int chunks, int dim=0) -> Tensor[] + variants: function, method + device_check: NoCheck + device_guard: False + tags: maybe_aliasing_or_mutating + +- func: chunk(Tensor(a -> *) self, int chunks, int dim=0) -> Tensor(a)[] + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeImplicitAutograd: chunk + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: chunk_nested_tensor + +- func: tensor_split.sections(Tensor(a -> *) self, SymInt sections, int dim=0) -> Tensor(a)[] + variants: function, method + dispatch: + CompositeImplicitAutograd: tensor_split_sections_symint + +- func: tensor_split.indices(Tensor(a -> *) self, SymInt[] indices, int dim=0) -> Tensor(a)[] + variants: function, method + dispatch: + CompositeImplicitAutograd: tensor_split_indices_symint + +- func: tensor_split.tensor_indices_or_sections(Tensor(a -> *) self, Tensor tensor_indices_or_sections, int dim=0) -> Tensor(a)[] + variants: function, method + +- func: clamp(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + cpp_no_default_args: ['min'] + structured_delegate: clamp.out + dispatch: + QuantizedCPU: clamp_quantized_cpu + tags: [core, pointwise] + +- func: clamp.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor + variants: function, method + structured_delegate: clamp.Tensor_out + tags: [core, pointwise] + +- func: clamp_(Tensor(a!) self, Scalar? min=None, Scalar? max=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + cpp_no_default_args: ['min'] + structured_delegate: clamp.out + tags: pointwise + +- func: clamp_.Tensor(Tensor(a!) self, Tensor? min=None, Tensor? max=None) -> Tensor(a!) + variants: function, method + structured_delegate: clamp.Tensor_out + tags: pointwise + +- func: clamp.out(Tensor self, Scalar? min=None, Scalar? max=None, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + cpp_no_default_args: ['min'] + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MTIA, MPS, XPU: clamp_out + tags: pointwise + +- func: clamp.Tensor_out(Tensor self, Tensor? min=None, Tensor? max=None, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: clamp_Tensor_out + tags: pointwise + +- func: clamp_max(Tensor self, Scalar max) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: clamp_max.out + tags: pointwise + +- func: clamp_max.Tensor(Tensor self, Tensor max) -> Tensor + variants: function, method + structured_delegate: clamp_max.Tensor_out + tags: pointwise + +- func: clamp_max_(Tensor(a!) self, Scalar max) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: clamp_max.out + tags: pointwise + +- func: clamp_max_.Tensor(Tensor(a!) self, Tensor max) -> Tensor(a!) + variants: function, method + structured_delegate: clamp_max.Tensor_out + tags: pointwise + +- func: clamp_max.out(Tensor self, Scalar max, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MTIA, MPS, XPU: clamp_max_out + tags: pointwise + +- func: clamp_max.Tensor_out(Tensor self, Tensor max, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: clamp_max_Tensor_out + tags: pointwise + +- func: clamp_min(Tensor self, Scalar min) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: clamp_min.out + tags: pointwise + +- func: clamp_min.Tensor(Tensor self, Tensor min) -> Tensor + variants: function, method + structured_delegate: clamp_min.Tensor_out + tags: pointwise + +- func: clamp_min_(Tensor(a!) self, Scalar min) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: clamp_min.out + tags: pointwise + +- func: clamp_min_.Tensor(Tensor(a!) self, Tensor min) -> Tensor(a!) + variants: function, method + structured_delegate: clamp_min.Tensor_out + tags: pointwise + +- func: clamp_min.out(Tensor self, Scalar min, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MTIA, MPS, XPU: clamp_min_out + tags: pointwise + +- func: clamp_min.Tensor_out(Tensor self, Tensor min, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: clamp_min_Tensor_out + tags: pointwise + +# clip is an alias for clamp +- func: clip(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor + cpp_no_default_args: ['min'] + variants: function, method + tags: pointwise + +- func: clip.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor + variants: function, method + tags: pointwise + +- func: clip_(Tensor(a!) self, Scalar? min=None, Scalar? max=None) -> Tensor(a!) + cpp_no_default_args: ['min'] + variants: function, method + tags: pointwise + +- func: clip_.Tensor(Tensor(a!) self, Tensor? min=None, Tensor? max=None) -> Tensor(a!) + variants: function, method + tags: pointwise + +- func: clip.out(Tensor self, Scalar? min=None, Scalar? max=None, *, Tensor(a!) out) -> Tensor(a!) + cpp_no_default_args: ['min'] + tags: pointwise + +- func: clip.Tensor_out(Tensor self, Tensor? min=None, Tensor? max=None, *, Tensor(a!) out) -> Tensor(a!) + +- func: cudnn_is_acceptable(Tensor self) -> bool + device_check: NoCheck + device_guard: False + +- func: complex(Tensor real, Tensor imag) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: complex + +- func: complex.out(Tensor real, Tensor imag, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: complex_out + +- func: polar(Tensor abs, Tensor angle) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: polar + +- func: polar.out(Tensor abs, Tensor angle, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: polar_out + +- func: constant_pad_nd(Tensor self, SymInt[] pad, Scalar value=0) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: constant_pad_nd + MPS: constant_pad_nd_mps + autogen: constant_pad_nd.out + tags: core + +- func: contiguous(Tensor(a) self, *, MemoryFormat memory_format=contiguous_format) -> Tensor(a) + variants: method + manual_cpp_binding: True + +- func: convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups) -> Tensor + dispatch: + CompositeExplicitAutograd: convolution + autogen: convolution.out + tags: core + +- func: convolution_backward(Tensor grad_output, Tensor input, Tensor weight, SymInt[]? bias_sizes, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) + dispatch: + CompositeExplicitAutograd, CUDA: convolution_backward + autogen: convolution_backward.out + tags: core + +- func: convolution_overrideable(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups) -> Tensor + dispatch: + CompositeExplicitAutograd: convolution_overrideable + autogen: convolution_overrideable.out + +- func: convolution_backward_overrideable(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias) + dispatch: + CompositeExplicitAutograd: convolution_backward_overrideable + autogen: convolution_backward_overrideable.out + +- func: _convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32) -> Tensor + dispatch: + CompositeExplicitAutograd: _convolution + autogen: _convolution.out + +- func: _convolution.deprecated(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, int[] output_padding, SymInt groups, bool benchmark, bool deterministic, bool cudnn_enabled) -> Tensor + +- func: _convolution_mode(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, str padding, SymInt[] dilation, SymInt groups) -> Tensor + dispatch: + CompositeImplicitAutograd: _convolution_mode_symint + +- func: _convolution_double_backward(Tensor? ggI, Tensor? ggW, Tensor? ggb, Tensor gO, Tensor weight, Tensor self, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) + +- func: conv1d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[1] stride=1, SymInt[1] padding=0, SymInt[1] dilation=1, SymInt groups=1) -> Tensor + dispatch: + CompositeImplicitAutograd: conv1d_symint + +- func: conv2d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] dilation=1, SymInt groups=1) -> Tensor + dispatch: + CompositeImplicitAutograd: conv2d_symint + +- func: conv3d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] dilation=1, SymInt groups=1) -> Tensor + dispatch: + CompositeImplicitAutograd: conv3d_symint + +- func: conv1d.padding(Tensor input, Tensor weight, Tensor? bias=None, SymInt[1] stride=1, str padding="valid", SymInt[1] dilation=1, SymInt groups=1) -> Tensor + cpp_no_default_args: ['bias', 'stride', 'padding'] + dispatch: + CompositeImplicitAutograd: conv1d_padding_symint + +- func: conv2d.padding(Tensor input, Tensor weight, Tensor? bias=None, SymInt[2] stride=1, str padding="valid", SymInt[2] dilation=1, SymInt groups=1) -> Tensor + cpp_no_default_args: ['bias', 'stride', 'padding'] + dispatch: + CompositeImplicitAutograd: conv2d_padding_symint + +- func: conv3d.padding(Tensor input, Tensor weight, Tensor? bias=None, SymInt[3] stride=1, str padding="valid", SymInt[3] dilation=1, SymInt groups=1) -> Tensor + cpp_no_default_args: ['bias', 'stride', 'padding'] + dispatch: + CompositeImplicitAutograd: conv3d_padding_symint + +- func: conv_tbc(Tensor self, Tensor weight, Tensor bias, int pad=0) -> Tensor + dispatch: + CompositeExplicitAutograd: conv_tbc + autogen: conv_tbc.out + +- func: conv_tbc_backward(Tensor self, Tensor input, Tensor weight, Tensor bias, int pad) -> (Tensor, Tensor, Tensor) + +# NB: we inherit the goofy argument order from PyTorch torch.nn.functional +- func: conv_transpose1d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[1] stride=1, SymInt[1] padding=0, SymInt[1] output_padding=0, SymInt groups=1, SymInt[1] dilation=1) -> Tensor + dispatch: + CompositeImplicitAutograd: conv_transpose1d_symint + +- func: conv_transpose2d.input(Tensor input, Tensor weight, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt groups=1, SymInt[2] dilation=1) -> Tensor + dispatch: + CompositeImplicitAutograd: conv_transpose2d_symint + +- func: conv_transpose3d.input(Tensor input, Tensor weight, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt groups=1, SymInt[3] dilation=1) -> Tensor + dispatch: + CompositeImplicitAutograd: conv_transpose3d_symint + +- func: copy(Tensor self, Tensor src, bool non_blocking=False) -> Tensor + variants: function + dispatch: + Meta: copy_meta + CompositeExplicitAutogradNonFunctional: copy + tags: core + +- func: copy_(Tensor(a!) self, Tensor src, bool non_blocking=False) -> Tensor(a!) + variants: method + device_check: NoCheck + device_guard: False + dispatch: + MkldnnCPU: copy_mkldnn_ + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: copy_sparse_wrapper_ + CompositeExplicitAutograd: copy_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: copy_sparse_compressed_ + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: copy_nested_ + autogen: copy.out + +- func: _copy_from(Tensor self, Tensor dst, bool non_blocking=False) -> Tensor + dispatch: + MPS: _copy_from_mps + autogen: _copy_from.out + +# We need this to be able to properly copy from a CPU to an XLA tensor with different sizes. +# See https://github.com/pytorch/xla/issues/2881 +- func: _copy_from_and_resize(Tensor self, Tensor dst) -> Tensor + dispatch: + MPS: _copy_from_and_resize_mps + autogen: _copy_from_and_resize.out + +- func: cos(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: cos.out + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_cos + tags: [core, pointwise] + +- func: cos_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: cos.out + tags: pointwise + +- func: cos.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: cos_out + tags: pointwise + +- func: cosh(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: cosh.out + tags: [core, pointwise] + +- func: cosh_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: cosh.out + tags: pointwise + +- func: cosh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: cosh_out + tags: pointwise + +- func: cosine_embedding_loss(Tensor input1, Tensor input2, Tensor target, float margin=0.0, int reduction=Mean) -> Tensor + +- func: count_nonzero.dim_IntList(Tensor self, int[] dim) -> Tensor + variants: function, method + dispatch: + CPU: count_nonzero_cpu + CUDA: count_nonzero_cuda + MPS: count_nonzero_mps + XPU: count_nonzero_xpu + autogen: count_nonzero.dim_IntList_out + tags: reduction + +- func: count_nonzero(Tensor self, int? dim=None) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: count_nonzero + autogen: count_nonzero.out + tags: reduction + +- func: cov(Tensor self, *, int correction=1, Tensor? fweights=None, Tensor? aweights=None) -> Tensor + variants: function, method + +- func: corrcoef(Tensor self) -> Tensor + variants: function, method + +- func: cudnn_affine_grid_generator(Tensor theta, int N, int C, int H, int W) -> Tensor grid + dispatch: + CUDA: cudnn_affine_grid_generator_forward + autogen: cudnn_affine_grid_generator.out + +# TODO: Why do I have to call this grad?! +- func: cudnn_affine_grid_generator_backward(Tensor grad, int N, int C, int H, int W) -> Tensor grad_theta + dispatch: + CUDA: cudnn_affine_grid_generator_backward + autogen: cudnn_affine_grid_generator_backward.out + +- func: cudnn_batch_norm(Tensor input, Tensor weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float exponential_average_factor, float epsilon) -> (Tensor, Tensor, Tensor, Tensor) + dispatch: + CUDA: cudnn_batch_norm + +- func: cudnn_batch_norm.out(Tensor input, Tensor weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float exponential_average_factor, float epsilon, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!)) + dispatch: + CUDA: cudnn_batch_norm_out + +# NB: You can only use this if you used cudnn_batch_norm training=True +- func: cudnn_batch_norm_backward(Tensor input, Tensor grad_output, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, float epsilon, Tensor reserveSpace) -> (Tensor, Tensor, Tensor) + dispatch: + CUDA: cudnn_batch_norm_backward + autogen: cudnn_batch_norm_backward.out + +- func: cudnn_convolution(Tensor self, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor + dispatch: + CUDA: cudnn_convolution + +- func: cudnn_convolution.out(Tensor self, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CUDA: cudnn_convolution_out + +- func: cudnn_convolution_transpose(Tensor self, Tensor weight, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor + dispatch: + CUDA: cudnn_convolution_transpose + autogen: cudnn_convolution_transpose.out + +- func: _mps_convolution_transpose(Tensor self, Tensor weight, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor + dispatch: + MPS: _mps_convolution_transpose + autogen: _mps_convolution_transpose.out + +- func: mps_convolution_transpose_backward(Tensor self, Tensor grad_output, Tensor weight, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool[2] output_mask) -> (Tensor, Tensor) + dispatch: + MPS: mps_convolution_transpose_backward + autogen: mps_convolution_transpose_backward.out + +- func: cudnn_convolution_relu(Tensor self, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor + dispatch: + CUDA: cudnn_convolution_relu + autogen: cudnn_convolution_relu.out + +- func: cudnn_convolution_add_relu(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor + dispatch: + CUDA: cudnn_convolution_add_relu + autogen: cudnn_convolution_add_relu.out + +# NB: input is special cased in a way I don't quite understand +- func: cudnn_grid_sampler(Tensor self, Tensor grid) -> Tensor output + dispatch: + CUDA: cudnn_grid_sampler_forward + autogen: cudnn_grid_sampler.out + +- func: cudnn_grid_sampler_backward(Tensor self, Tensor grid, Tensor grad_output) -> (Tensor grad_self, Tensor grad_grid) + dispatch: + CUDA: cudnn_grid_sampler_backward + autogen: cudnn_grid_sampler_backward.out + +- func: cummax(Tensor self, int dim) -> (Tensor values, Tensor indices) + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: cummax + +- func: cummax.out(Tensor self, int dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) + device_check: NoCheck # TensorIterator + dispatch: + CompositeExplicitAutograd: cummax_out + +- func: _cummax_helper(Tensor self, Tensor(a!) values, Tensor(b!) indices, int dim) -> () + variants: function + dispatch: + CPU: cummax_helper_cpu + CUDA: cummax_helper_cuda + MPS: cummax_helper_mps + XPU: cummax_helper_xpu + +- func: cummin(Tensor self, int dim) -> (Tensor values, Tensor indices) + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: cummin + +- func: cummin.out(Tensor self, int dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) + device_check: NoCheck # TensorIterator + dispatch: + CompositeExplicitAutograd: cummin_out + +- func: _cummin_helper(Tensor self, Tensor(a!) values, Tensor(b!) indices, int dim) -> () + variants: function + dispatch: + CPU: cummin_helper_cpu + CUDA: cummin_helper_cuda + MPS: cummin_helper_mps + XPU: cummin_helper_xpu + +- func: cummaxmin_backward(Tensor grad, Tensor input, Tensor indices, int dim) -> Tensor + variants: function + device_check: NoCheck + device_guard: False + +- func: cumprod(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor + structured_delegate: cumprod.out + device_check: NoCheck # TensorIterator + variants: function, method + +- func: cumprod_(Tensor(a!) self, int dim, *, ScalarType? dtype=None) -> Tensor(a!) + structured_delegate: cumprod.out + variants: method + +- func: cumprod.out(Tensor self, int dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + structured: True + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, XPU: cumprod_out + MPS: cumprod_out_mps + +- func: cumprod_backward(Tensor grad, Tensor input, int dim, Tensor output) -> Tensor + variants: function + device_check: NoCheck + device_guard: False + +- func: cumsum(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor + structured_delegate: cumsum.out + device_check: NoCheck # TensorIterator + variants: function, method + tags: core + +- func: cumsum_(Tensor(a!) self, int dim, *, ScalarType? dtype=None) -> Tensor(a!) + structured_delegate: cumsum.out + variants: method + +- func: cumsum.out(Tensor self, int dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + structured: True + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, XPU: cumsum_out + MPS: cumsum_out_mps + +- func: cumulative_trapezoid.x(Tensor y, Tensor x, *, int dim=-1) -> Tensor + +- func: cumulative_trapezoid.dx(Tensor y, *, Scalar dx=1, int dim=-1) -> Tensor + +- func: ctc_loss.IntList(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank=0, int reduction=Mean, bool zero_infinity=False) -> Tensor + +# convenience function that converts to intlists for you +- func: ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank=0, int reduction=Mean, bool zero_infinity=False) -> Tensor + +- func: _ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank=0, bool zero_infinity=False) -> (Tensor, Tensor) + dispatch: + CPU: ctc_loss_cpu + CUDA: ctc_loss_gpu + MPS: ctc_loss_mps + Meta: ctc_loss_meta + XPU: ctc_loss_xpu + autogen: _ctc_loss.out + tags: dynamic_output_shape # the shape of second output is data dependent + +- func: _ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank=0, bool zero_infinity=False) -> (Tensor, Tensor) + dispatch: + CPU, CUDA, XPU, MPS: ctc_loss_tensor + autogen: _ctc_loss.Tensor_out + tags: dynamic_output_shape # the shape of second output is data dependent + +- func: _ctc_loss_backward(Tensor grad, Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, Tensor neg_log_likelihood, Tensor log_alpha, int blank, bool zero_infinity=False) -> Tensor + dispatch: + CPU: ctc_loss_backward_cpu + CUDA: ctc_loss_backward_gpu + XPU: ctc_loss_backward_xpu + MPS: ctc_loss_backward_mps + autogen: _ctc_loss_backward.out + +- func: _ctc_loss_backward.Tensor(Tensor grad, Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, Tensor neg_log_likelihood, Tensor log_alpha, int blank, bool zero_infinity=False) -> Tensor + dispatch: + CPU, CUDA, XPU, MPS: ctc_loss_backward_tensor + +- func: diag_embed(Tensor self, int offset=0, int dim1=-2, int dim2=-1) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutogradNonFunctional: diag_embed + autogen: diag_embed.out + +- func: diagflat(Tensor self, int offset=0) -> Tensor + variants: function, method + +- func: diagonal(Tensor(a) self, int offset=0, int dim1=0, int dim2=1) -> Tensor(a) + variants: function, method + dispatch: + CompositeExplicitAutograd: diagonal + tags: core + +- func: linalg_diagonal(Tensor(a) A, *, int offset=0, int dim1=-2, int dim2=-1) -> Tensor(a) + python_module: linalg + variants: function + +- func: diagonal_backward(Tensor grad_output, SymInt[] input_sizes, int offset, int dim1, int dim2) -> Tensor + variants: function + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: diagonal_backward_symint + autogen: diagonal_backward.out + +- func: fill_diagonal_(Tensor(a!) self, Scalar fill_value, bool wrap=False) -> Tensor(a!) + variants: method + +- func: diff(Tensor self, int n=1, int dim=-1, Tensor? prepend=None, Tensor? append=None) -> Tensor + variants: function, method + +- func: diff.out(Tensor self, int n=1, int dim=-1, Tensor? prepend=None, Tensor? append=None, *, Tensor(a!) out) -> Tensor(a!) + variants: function + +- func: gradient.scalarint(Tensor self, *, Scalar? spacing=None, int? dim=None, int edge_order=1) -> Tensor[] + variants: function + +- func: gradient.scalararray(Tensor self, *, Scalar spacing, int[] dim, int edge_order=1) -> Tensor[] + variants: function + +- func: gradient.array(Tensor self, *, int[] dim, int edge_order=1) -> Tensor[] + variants: function + +- func: gradient.scalarrayint(Tensor self, *, Scalar[] spacing, int? dim=None, int edge_order=1) -> Tensor[] + variants: function + +- func: gradient.scalarrayarray(Tensor self, *, Scalar[] spacing, int[] dim, int edge_order=1) -> Tensor[] + variants: function + +- func: gradient.tensorarrayint(Tensor self, *, Tensor[] spacing, int? dim=None, int edge_order=1) -> Tensor[] + variants: function + +- func: gradient.tensorarray(Tensor self, *, Tensor[] spacing, int[] dim, int edge_order=1) -> Tensor[] + variants: function + +- func: div.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: div.out + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: div_sparse + ZeroTensor: div_zerotensor + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_div_Tensor + tags: [core, pointwise] + +- func: div_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: div.out + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: div_sparse_ + tags: pointwise + +- func: div.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: div_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: div_out_sparse_zerodim + tags: pointwise + +- func: div.Tensor_mode(Tensor self, Tensor other, *, str? rounding_mode) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: div.out_mode + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: div_sparse + tags: [core, pointwise] + +- func: div_.Tensor_mode(Tensor(a!) self, Tensor other, *, str? rounding_mode) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: div.out_mode + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: div_sparse_ + tags: pointwise + +- func: div.out_mode(Tensor self, Tensor other, *, str? rounding_mode, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: div_out_mode + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: div_out_sparse_zerodim + tags: pointwise + +# For C++ only, until we have conversion from C++ numbers to Tensor +- func: div.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: div + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_div_Scalar + tags: [core, pointwise] + +- func: div_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: div_ + autogen: div.Scalar_out + tags: pointwise + +- func: div.Scalar_mode(Tensor self, Scalar other, *, str? rounding_mode) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: div + tags: [core, pointwise] + +- func: div_.Scalar_mode(Tensor(a!) self, Scalar other, *, str? rounding_mode) -> Tensor(a!) + variants: method + dispatch: + CompositeExplicitAutograd: div_ + autogen: div.Scalar_mode_out + tags: pointwise + +# divide, alias for div +- func: divide.Tensor(Tensor self, Tensor other) -> Tensor + variants: function, method + +- func: divide_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + variants: method + +- func: divide.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + +- func: divide.Scalar(Tensor self, Scalar other) -> Tensor + variants: function, method + +- func: divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + variants: method + +- func: divide.Tensor_mode(Tensor self, Tensor other, *, str? rounding_mode) -> Tensor + variants: function, method + +- func: divide_.Tensor_mode(Tensor(a!) self, Tensor other, *, str? rounding_mode) -> Tensor(a!) + variants: method + +- func: divide.out_mode(Tensor self, Tensor other, *, str? rounding_mode, Tensor(a!) out) -> Tensor(a!) + +- func: divide.Scalar_mode(Tensor self, Scalar other, *, str? rounding_mode) -> Tensor + variants: function, method + +- func: divide_.Scalar_mode(Tensor(a!) self, Scalar other, *, str? rounding_mode) -> Tensor(a!) + variants: method + + # true_divide, an alias for div +- func: true_divide.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + tags: pointwise + +- func: true_divide_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + +- func: true_divide.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + +- func: true_divide.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + +- func: true_divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + +- func: dot(Tensor self, Tensor tensor) -> Tensor + variants: function, method + dispatch: + CPU: dot + CUDA: dot_cuda + MPS: dot_mps + XPU: dot_xpu + +- func: dot.out(Tensor self, Tensor tensor, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: dot_out + +- func: vdot(Tensor self, Tensor other) -> Tensor + variants: function, method + dispatch: + CPU: vdot + CUDA: vdot_cuda + MPS: vdot_mps + XPU: vdot_xpu + +- func: vdot.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: vdot_out + +- func: einsum(str equation, Tensor[] tensors, *, int[]? path=None) -> Tensor + +- func: embedding(Tensor weight, Tensor indices, SymInt padding_idx=-1, bool scale_grad_by_freq=False, bool sparse=False) -> Tensor + dispatch: + CompositeExplicitAutograd: embedding_symint + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_embedding + autogen: embedding.out + tags: core + +- func: embedding_backward(Tensor grad, Tensor indices, SymInt num_weights, SymInt padding_idx, bool scale_grad_by_freq, bool sparse) -> Tensor + dispatch: + CompositeImplicitAutograd: embedding_backward_symint + +- func: embedding_dense_backward(Tensor grad_output, Tensor indices, SymInt num_weights, SymInt padding_idx, bool scale_grad_by_freq) -> Tensor + dispatch: + CPU: embedding_dense_backward_cpu + CUDA: embedding_dense_backward_cuda + MPS: embedding_dense_backward_mps + XPU: embedding_dense_backward_xpu + autogen: embedding_dense_backward.out + tags: core + +- func: embedding_renorm_(Tensor(a!) self, Tensor indices, float max_norm, float norm_type) -> Tensor(a!) + dispatch: + CPU: embedding_renorm_cpu_ + CUDA: embedding_renorm_cuda_ + XPU: embedding_renorm_xpu_ + autogen: embedding_renorm, embedding_renorm.out + +- func: embedding_sparse_backward(Tensor grad, Tensor indices, int num_weights, int padding_idx, bool scale_grad_by_freq) -> Tensor + +# NOTE [ embedding_bag Native Functions ] +# The `_embedding_bag.*` variants assume that input tensors except for `weight`, +# e.g. `indices` and `offsets` (and `offset2bag`), are contiguous. +# We really only need to enforce this for `_embedding_bag` (the forward) because +# the backward inputs are the same as forward ones. +# The above `embedding_bag` wrapper is created to achieve this, e.g., +# applying indices = indices.contiguous(). +# The backward functions apply a check that these input tensors are contiguous. + +- func: _embedding_bag_forward_only(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1) -> (Tensor, Tensor, Tensor, Tensor) + dispatch: + CPU: _embedding_bag_forward_only_cpu + CUDA: _embedding_bag_forward_only_cuda + MPS: _embedding_bag_forward_only_mps + XPU: _embedding_bag_forward_only_xpu + autogen: _embedding_bag_forward_only.out + +- func: _rowwise_prune(Tensor weight, Tensor mask, ScalarType compressed_indices_dtype) -> (Tensor, Tensor) + +# row_stack is the alias of vstack +- func: row_stack(Tensor[] tensors) -> Tensor + +- func: row_stack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) + +- func: embedding_bag(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False) -> (Tensor, Tensor, Tensor, Tensor) + +# To keep backward and forward compatibility, and to avoid ambiguity with the +# original signature above, scale_grad_by_freq, mode, sparse, +# per_sample_weights, and include_last_offset parameters do not have default +# values. Once the original signature is removed, default values can be added. +- func: embedding_bag.padding_idx(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights, bool include_last_offset, int? padding_idx) -> (Tensor, Tensor, Tensor, Tensor) + +- func: _embedding_bag(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1) -> (Tensor, Tensor, Tensor, Tensor) + dispatch: + CPU: _embedding_bag_cpu + CUDA: _embedding_bag_cuda + MPS: _embedding_bag_mps + XPU: _embedding_bag_xpu + autogen: _embedding_bag.out + tags: core + +- func: _embedding_bag_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor + dispatch: + CPU, CUDA, MPS, XPU: _embedding_bag_backward_symint + +- func: _embedding_bag_sparse_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, SymInt num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor + dispatch: + CompositeImplicitAutograd: _embedding_bag_sparse_backward_symint + +- func: _embedding_bag_dense_backward(Tensor grad, Tensor indices, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor + dispatch: + CPU: _embedding_bag_dense_backward_cpu + CUDA: _embedding_bag_dense_backward_cuda + MPS: _embedding_bag_dense_backward_mps + XPU: _embedding_bag_dense_backward_xpu + autogen: _embedding_bag_dense_backward.out + +- func: _embedding_bag_per_sample_weights_backward(Tensor grad, Tensor weight, Tensor indices, Tensor offsets, Tensor offset2bag, int mode, int padding_idx=-1) -> Tensor + dispatch: + CPU: _embedding_bag_per_sample_weights_backward_cpu + CUDA: _embedding_bag_per_sample_weights_backward_cuda + MPS: _embedding_bag_per_sample_weights_backward_mps + XPU: _embedding_bag_per_sample_weights_backward_xpu + autogen: _embedding_bag_per_sample_weights_backward.out + +- func: empty.memory_format(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + dispatch: + CPU: empty_cpu + CUDA: empty_cuda + MPS: empty_mps + XPU: empty_xpu + Meta: empty_meta_symint + MkldnnCPU: empty_mkldnn + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: empty_sparse + SparseMeta: empty_sparse_symint + SparseCsrCPU, SparseCsrCUDA, SparseCsrXPU: empty_sparse_compressed + SparseCsrMeta: empty_sparse_compressed_symint + QuantizedCPU, QuantizedCUDA, QuantizedMeta: empty_unknown_quantized + tags: core + +- func: empty_permuted(SymInt[] size, int[] physical_layout, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: empty_permuted_symint + autogen: empty_permuted.out + +# We do not make new_empty a composite that calls into new_empty_strided, as the strided version +# is significantly more difficult to implement by different backends +- func: new_empty(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + variants: method + dispatch: + CompositeExplicitAutograd: new_empty_symint + autogen: new_empty.out + +- func: new_empty_strided(Tensor self, SymInt[] size, SymInt[] stride, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + variants: method + dispatch: + CompositeExplicitAutogradNonFunctional: new_empty_strided_symint + autogen: new_empty_strided.out + +- func: new_full(Tensor self, SymInt[] size, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + variants: method + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd: new_full + autogen: new_full.out + +- func: new_zeros(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + variants: method + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd: new_zeros + autogen: new_zeros.out + +- func: new_ones(Tensor self, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + variants: method + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd: new_ones + autogen: new_ones.out + +# other overrides are to provide a more helpful error message that dtype is required +- func: _empty_affine_quantized(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, float scale=1, int zero_point=0, MemoryFormat? memory_format=contiguous_format) -> Tensor + dispatch: + CPU: empty_affine_quantized_other_backends_stub + QuantizedCPU, QuantizedCUDA: empty_affine_quantized + autogen: _empty_affine_quantized.out + +# it's a factory function receiving a tensor argument, thus overriding explicitly +# other overrides are to provide a more helpful error message that dtype is required +- func: _empty_per_channel_affine_quantized(SymInt[] size, *, Tensor scales, Tensor zero_points, int axis, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=contiguous_format) -> Tensor + category_override: factory + dispatch: + CPU: empty_per_channel_affine_quantized_other_backends_stub + QuantizedCPU, QuantizedCUDA: empty_per_channel_affine_quantized + autogen: _empty_per_channel_affine_quantized.out + +- func: resize_(Tensor(a!) self, SymInt[] size, *, MemoryFormat? memory_format=None) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True + variants: method + device_check: NoCheck + device_guard: False + tags: [core, inplace_view] + dispatch: + Meta: resize__symint + CPU: resize_ + CUDA: resize_cuda_ + MPS: resize_mps_ + XPU: resize_xpu_ + QuantizedCPU: quantized_resize_cpu_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: resize_sparse_csr_ + autogen: resize, resize.out + +# This is a utility function to enable users to resize out tensor while registering kernels for out variants. +# Eventually, we can consider exposing `resize_output` as a public API to ship it with python op registration +# to make it easy to register out variants for ops. +- func: _resize_output_(Tensor(a!) self, SymInt[] size, Device device) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True + variants: function + dispatch: + Meta: _resize_output_ + autogen: _resize_output, _resize_output.out + +- func: empty_quantized(int[] size, Tensor qtensor, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + category_override: factory + variants: function + dispatch: + QuantizedCPU, QuantizedCUDA: empty_quantized + autogen: empty_quantized.out + +- func: empty.out(SymInt[] size, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + device_guard: False + +- func: empty_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: empty_like + QuantizedCPU, QuantizedCUDA: empty_like_quantized + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: empty_like_sparse_coo + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: empty_like_sparse_csr + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: empty_like_nested + autogen: empty_like.out + +- func: empty_strided(SymInt[] size, SymInt[] stride, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CPU: empty_strided_cpu + CUDA: empty_strided_cuda + MPS: empty_strided_mps + XPU: empty_strided_xpu + Meta: empty_strided_meta_symint + QuantizedCPU, QuantizedCUDA: empty_strided_unknown_quantized + autogen: empty_strided.out + tags: core + +- func: erf(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: erf.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: erf_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: erf_sparse_csr + tags: [core, pointwise] + +- func: erf_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: erf.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: erf_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: erf_sparse_csr_ + tags: pointwise + +- func: erf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: erf_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: erf_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: erf_sparse_csr_out + tags: pointwise + +- func: erfc(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: erfc.out + variants: function, method + tags: pointwise + +- func: erfc_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: erfc.out + variants: function, method + tags: pointwise + +- func: erfc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: erfc_out + tags: pointwise + +- func: exp(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: exp.out + variants: function, method + tags: [core, pointwise] + +- func: exp_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: exp.out + variants: function, method + tags: pointwise + +- func: exp.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: exp_out + tags: pointwise + +- func: exp2(Tensor self) -> Tensor + structured_delegate: exp2.out + variants: function, method + tags: pointwise + +- func: exp2_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: exp2.out + variants: function, method + tags: pointwise + +- func: exp2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: exp2_out + tags: pointwise + +- func: expm1(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: expm1.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: expm1_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: expm1_sparse_csr + tags: [core, pointwise] + +- func: expm1_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: expm1.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: expm1_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: expm1_sparse_csr_ + tags: pointwise + +- func: expm1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: expm1_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: expm1_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: expm1_sparse_csr_out + tags: pointwise + +- func: expand(Tensor(a) self, SymInt[] size, *, bool implicit=False) -> Tensor(a) + variants: method # This is method-only to match the previous tensor API. In the future we could make this a function too. + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: expand + tags: core + +- func: expand_as(Tensor(a) self, Tensor other) -> Tensor(a) + variants: method # This is method-only to match the previous tensor API. In the future we could make this a function too. + device_check: NoCheck + device_guard: False + +# decomposes to eye.m +- func: eye(SymInt n, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: eye + +- func: eye.m(SymInt n, SymInt m, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: eye + +- func: eye.out(SymInt n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, Meta: eye_out_cpu + CUDA: eye_out_cuda + MPS: eye_out_mps + XPU: eye_out_xpu + +- func: eye.m_out(SymInt n, SymInt m, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, Meta: eye_out_cpu + CUDA: eye_out_cuda + MPS: eye_out_mps + XPU: eye_out_xpu + +- func: flatten.using_ints(Tensor(a) self, int start_dim=0, int end_dim=-1) -> Tensor(a) + variants: function, method + +- func: unflatten.int(Tensor(a) self, int dim, SymInt[] sizes) -> Tensor(a) + variants: function, method + dispatch: + CompositeImplicitAutograd: unflatten_symint + +- func: fill.Scalar(Tensor self, Scalar value) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: fill + tags: core + +- func: fill.Tensor(Tensor self, Tensor value) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: fill + +- func: fill_.Scalar(Tensor(a!) self, Scalar value) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CPU, CUDA, MPS, XPU: fill_ + QuantizedCPU, QuantizedCUDA: fill_quantized_ + Meta: fill_meta_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: fill_sparse_csr_ + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: fill_nested_ + autogen: fill.Scalar_out + +- func: fill_.Tensor(Tensor(a!) self, Tensor value) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CPU, CUDA, MPS, XPU: fill_ + QuantizedCPU, QuantizedCUDA: fill_quantized_ + Meta: fill_meta_ + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: fill_nested_ + autogen: fill.Tensor_out + +- func: floor(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: floor.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: floor_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: floor_sparse_csr + tags: [core, pointwise] + +- func: floor_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: floor.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: floor_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: floor_sparse_csr_ + tags: pointwise + +- func: floor.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: floor_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: floor_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: floor_sparse_csr_out + tags: pointwise + +- func: floor_divide(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CPU, CUDA, MPS, MTIA, XPU: floor_divide + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: floor_divide_sparse + +- func: floor_divide_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CPU, CUDA, MPS, XPU: floor_divide_ + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: floor_divide_sparse_ + +- func: floor_divide.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: floor_divide_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: floor_divide_out_sparse_zerodim + +- func: floor_divide.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: floor_divide + +- func: floor_divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: floor_divide_ + autogen: floor_divide.Scalar_out + +- func: frac(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: frac.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: frac_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: frac_sparse_csr + tags: pointwise + +- func: frac_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: frac.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: frac_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: frac_sparse_csr_ + tags: pointwise + +- func: frac.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, XPU: frac_out + MPS: frac_out_mps + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: frac_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: frac_sparse_csr_out + tags: pointwise + +- func: full(SymInt[] size, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: full + tags: core + +- func: full.out(SymInt[] size, Scalar fill_value, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: full_out + +- func: full_like(Tensor self, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd: full_like + autogen: full_like.out + tags: core + +- func: from_file(str filename, bool? shared=None, int? size=0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CPU: from_file + autogen: from_file.out + +- func: gcd.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: gcd_out + tags: pointwise + +- func: gcd(Tensor self, Tensor other) -> Tensor + structured_delegate: gcd.out + variants: function, method + tags: pointwise + +- func: gcd_(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: gcd.out + variants: function, method + +- func: lcm.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: lcm_out + tags: pointwise + +- func: lcm(Tensor self, Tensor other) -> Tensor + structured_delegate: lcm.out + variants: function, method + tags: pointwise + +- func: lcm_(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: lcm.out + variants: function, method + +# NOTE [ grid_sampler Native Functions ] +# `grid_sampler` is _supposed to_ do all the shape checking and then dispatch to +# one of `cudnn_grid_sampler`, `grid_sampler_2d`, or `grid_sampler_3d`, each of +# which has the corresponding backward defined as native functions as well. +# However, we do shape checking everywhere for now since each of the mentioned +# functions can be called directly, which will lead to crashes otherwise. +# See https://github.com/pytorch/pytorch/issues/73187 for more information. +# +# There is also _grid_sampler_2d_backward_cpu_fallback which is an +# implementation detail of grid_sampler_2d and is only exposed here for testing +# purposes. +# +# Additionally, arguments `padding_mode` and `interpolation_mode` are cast to +# enums defined in `native/GridSampler.h`. `cudnn_grid_sampler` doesn't take in +# `interpolation_mode` because it only supports Bilinear interpolation mode. +# Nor does it take in `align_corners` because it only supports the mode +# `align_corners = True`. +- func: grid_sampler(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor + +- func: grid_sampler_2d(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor + dispatch: + CPU, QuantizedCPU: grid_sampler_2d_cpu + CUDA: grid_sampler_2d_cuda + MPS: grid_sampler_2d_mps + XPU: grid_sampler_2d_xpu + autogen: grid_sampler_2d.out + tags: core + +# `grid_sampler_2d_backward` takes in `output_mask` to optimize performance for +# the case where `input` doesn't require gradient. Gradient for `grid` is always +# computed (only `output_mask[0]` is checked by the implementations). +- func: grid_sampler_2d_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, bool[2] output_mask) -> (Tensor, Tensor) + dispatch: + CPU: grid_sampler_2d_backward_cpu + CUDA: grid_sampler_2d_backward_cuda + MPS: grid_sampler_2d_backward_mps + XPU: grid_sampler_2d_backward_xpu + autogen: grid_sampler_2d_backward.out + +# See NOTE [ grid_sample CPU fallback ] +- func: _grid_sampler_2d_cpu_fallback(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor + dispatch: + CompositeExplicitAutograd: _grid_sampler_2d_cpu_fallback + autogen: _grid_sampler_2d_cpu_fallback.out + +- func: _grid_sampler_2d_cpu_fallback_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> (Tensor, Tensor) + dispatch: + CompositeExplicitAutograd: _grid_sampler_2d_cpu_fallback_backward + +- func: grid_sampler_3d(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor + dispatch: + CPU: grid_sampler_3d_cpu + CUDA: grid_sampler_3d_cuda + MPS: grid_sampler_3d_mps + XPU: grid_sampler_3d_xpu + autogen: grid_sampler_3d.out + +# `grid_sampler_3d_backward` takes in `output_mask` to optimize performance for +# the case where `input` doesn't require gradient. Gradient for `grid` is always +# computed (only `output_mask[0]` is checked by the implementations). +- func: grid_sampler_3d_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, bool[2] output_mask) -> (Tensor, Tensor) + dispatch: + CPU: grid_sampler_3d_backward_cpu + CUDA: grid_sampler_3d_backward_cuda + MPS: grid_sampler_3d_backward_mps + XPU: grid_sampler_3d_backward_xpu + autogen: grid_sampler_3d_backward.out + +- func: hann_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: hann_window + autogen: hann_window.out + +- func: hann_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: hann_window + autogen: hann_window.periodic_out + +- func: hamming_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: hamming_window + autogen: hamming_window.out + +- func: hamming_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: hamming_window + autogen: hamming_window.periodic_out + +- func: hamming_window.periodic_alpha(int window_length, bool periodic, float alpha, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: hamming_window + autogen: hamming_window.periodic_alpha_out + +- func: hamming_window.periodic_alpha_beta(int window_length, bool periodic, float alpha, float beta, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: hamming_window + autogen: hamming_window.periodic_alpha_beta_out + +- func: kaiser_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: kaiser_window + autogen: kaiser_window.out + +- func: kaiser_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: kaiser_window + autogen: kaiser_window.periodic_out + +- func: kaiser_window.beta(int window_length, bool periodic, float beta, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: kaiser_window + autogen: kaiser_window.beta_out + +- func: hinge_embedding_loss(Tensor self, Tensor target, float margin=1.0, int reduction=Mean) -> Tensor + +- func: group_norm(Tensor input, int num_groups, Tensor? weight=None, Tensor? bias=None, float eps=1e-05, bool cudnn_enabled=True) -> Tensor + +- func: native_group_norm(Tensor input, Tensor? weight, Tensor? bias, SymInt N, SymInt C, SymInt HxW, int group, float eps) -> (Tensor, Tensor, Tensor) + dispatch: + CPU, CUDA, MPS, XPU: native_group_norm + CompositeExplicitAutograd: math_group_norm + autogen: native_group_norm.out + tags: core + +- func: native_group_norm_backward(Tensor grad_out, Tensor input, Tensor mean, Tensor rstd, Tensor? weight, SymInt N, SymInt C, SymInt HxW, int group, bool[3] output_mask) -> (Tensor, Tensor, Tensor) + dispatch: + CPU, CUDA, MPS, XPU: native_group_norm_backward + autogen: native_group_norm_backward.out + tags: core + +# Real to complex forward FFT +- func: _fft_r2c(Tensor self, int[] dim, int normalization, bool onesided) -> Tensor + variants: function + dispatch: + CPU: _fft_r2c_mkl + CUDA: _fft_r2c_cufft + MPS: _fft_r2c_mps + XPU: _fft_r2c_xpu + tags: core + +- func: _fft_r2c.out(Tensor self, int[] dim, int normalization, bool onesided, *, Tensor(a!) out) -> Tensor(a!) + variants: function + dispatch: + CPU: _fft_r2c_mkl_out + CUDA: _fft_r2c_cufft_out + MPS: _fft_r2c_mps_out + XPU: _fft_r2c_xpu_out + +# Complex to real inverse FFT +- func: _fft_c2r(Tensor self, int[] dim, int normalization, SymInt last_dim_size) -> Tensor + variants: function + dispatch: + CPU: _fft_c2r_mkl + CUDA: _fft_c2r_cufft + MPS: _fft_c2r_mps + XPU: _fft_c2r_xpu + tags: core + +- func: _fft_c2r.out(Tensor self, int[] dim, int normalization, SymInt last_dim_size, *, Tensor(a!) out) -> Tensor(a!) + variants: function + dispatch: + CPU: _fft_c2r_mkl_out + CUDA: _fft_c2r_cufft_out + MPS: _fft_c2r_mps_out + XPU: _fft_c2r_xpu_out + +# Standard complex to complex FFT (forward or backward) +- func: _fft_c2c(Tensor self, SymInt[] dim, int normalization, bool forward) -> Tensor + variants: function + dispatch: + CPU: _fft_c2c_mkl + CUDA: _fft_c2c_cufft + MPS: _fft_c2c_mps + XPU: _fft_c2c_xpu + +- func: _fft_c2c.out(Tensor self, SymInt[] dim, int normalization, bool forward, *, Tensor(a!) out) -> Tensor(a!) + variants: function + dispatch: + CPU: _fft_c2c_mkl_out + CUDA: _fft_c2c_cufft_out + MPS: _fft_c2c_mps_out + XPU: _fft_c2c_xpu_out + +- func: _validate_compressed_sparse_indices(bool is_crow, Tensor compressed_idx, Tensor plain_idx, int cdim, int dim, int nnz) -> () + device_check: NoCheck + variants: function + dispatch: + CPU: _validate_compressed_sparse_indices_cpu + CUDA: _validate_compressed_sparse_indices_cuda + +- func: _cufft_get_plan_cache_size(DeviceIndex device_index) -> int + +- func: _cufft_get_plan_cache_max_size(DeviceIndex device_index) -> int + +- func: _cufft_set_plan_cache_max_size(DeviceIndex device_index, int max_size) -> () + +- func: _cufft_clear_plan_cache(DeviceIndex device_index) -> () + +- func: index.Tensor(Tensor self, Tensor?[] indices) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: index.Tensor_out + variants: function, method + dispatch: + QuantizedCPU: quantized_index + tags: [core, dynamic_output_shape] + # NB: This function is special-cased in tools/autograd/gen_variable_type.py + # NB: The following functions are declared in aten/src/ATen/templates/TensorBody.h and defined in aten/src/ATen/TensorIndexing.cpp: + # - Tensor Tensor::index(ArrayRef indices) + # - Tensor Tensor::index(std::initializer_list indices) + +- func: index.Tensor_out(Tensor self, Tensor?[] indices, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + structured: True + structured_inherits: TensorIteratorBase + precomputed: + - indices -> DimVector sizes, DimVector strides + dispatch: + CPU, CUDA, MPS, XPU: index_out + +# Used by inductor to signal indexing without bounds checks +# Note that we don't support boolean indexing, to avoid dynamic output shapes +- func: _unsafe_index.Tensor(Tensor self, Tensor?[] indices) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: _unsafe_index + +# Used by inductor to generate masked loads +# Note that we don't support boolean indexing, to avoid dynamic output shapes +- func: _unsafe_masked_index(Tensor self, Tensor mask, Tensor?[] indices, Scalar fill) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: _unsafe_masked_index + +- func: _unsafe_masked_index_put_accumulate(Tensor self, Tensor mask, Tensor?[] indices, Tensor values) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: _unsafe_masked_index_put_accumulate + +- func: index_copy.out(Tensor self, int dim, Tensor index, Tensor source, *, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + precomputed: + - dim -> int dim + dispatch: + CPU, CUDA, XPU: index_copy_out + MPS: index_copy_out_mps + +- func: index_copy_(Tensor(a!) self, int dim, Tensor index, Tensor source) -> Tensor(a!) + variants: method + structured_delegate: index_copy.out + +- func: index_copy(Tensor self, int dim, Tensor index, Tensor source) -> Tensor + variants: function, method + structured_delegate: index_copy.out + +- func: index_put_(Tensor(a!) self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor(a!) + device_check: NoCheck # delegate to _index_put_impl_, which leverages TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: index_put_ + autogen: index_put.out + # NB: The following functions are declared in aten/src/ATen/templates/TensorBody.h and defined in aten/src/ATen/TensorIndexing.cpp: + # - Tensor & Tensor::index_put_(ArrayRef indices, Tensor const & rhs) + # - Tensor & Tensor::index_put_(ArrayRef indices, Scalar v) + # - Tensor & Tensor::index_put_(std::initializer_list indices, Tensor const & rhs) + # - Tensor & Tensor::index_put_(std::initializer_list indices, Scalar v) + +- func: index_put(Tensor self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor + device_check: NoCheck # delegate to _index_put_impl_ after clone, which leverages TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: index_put + tags: core + +- func: _unsafe_index_put(Tensor self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor + device_check: NoCheck # delegate to _index_put_impl_ after clone, which leverages TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: _unsafe_index_put + +- func: _index_put_impl_(Tensor(a!) self, Tensor?[] indices, Tensor values, bool accumulate=False, bool unsafe=False) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CPU, CUDA, MPS, XPU: _index_put_impl_ + QuantizedCPU: _index_put_impl_quantized_cpu_ + QuantizedCUDA: _index_put_impl_quantized_cuda_ + autogen: _index_put_impl, _index_put_impl.out + +- func: instance_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool use_input_stats, float momentum, float eps, bool cudnn_enabled) -> Tensor + variants: function + +- func: isclose(Tensor self, Tensor other, float rtol=1e-05, float atol=1e-08, bool equal_nan=False) -> Tensor + variants: function, method + +- func: isin.Tensor_Tensor_out(Tensor elements, Tensor test_elements, *, bool assume_unique=False, bool invert=False, Tensor(a!) out) -> Tensor(a!) + variants: function + structured: True + dispatch: + CPU, CUDA, XPU: isin_Tensor_Tensor_out + MPS: isin_Tensor_Tensor_out_mps + +- func: isin.Tensor_Tensor(Tensor elements, Tensor test_elements, *, bool assume_unique=False, bool invert=False) -> Tensor + variants: function + structured_delegate: isin.Tensor_Tensor_out + +- func: isin.Tensor_Scalar_out(Tensor elements, Scalar test_element, *, bool assume_unique=False, bool invert=False, Tensor(a!) out) -> Tensor(a!) + variants: function + structured: True + dispatch: + CPU, CUDA, MPS, XPU: isin_Tensor_Scalar_out + +- func: isin.Tensor_Scalar(Tensor elements, Scalar test_element, *, bool assume_unique=False, bool invert=False) -> Tensor + variants: function + structured_delegate: isin.Tensor_Scalar_out + +- func: isin.Scalar_Tensor_out(Scalar element, Tensor test_elements, *, bool assume_unique=False, bool invert=False, Tensor(a!) out) -> Tensor(a!) + variants: function + structured: True + dispatch: + CPU, CUDA, XPU: isin_Scalar_Tensor_out + MPS: isin_Scalar_Tensor_out_mps + +- func: isin.Scalar_Tensor(Scalar element, Tensor test_elements, *, bool assume_unique=False, bool invert=False) -> Tensor + variants: function + structured_delegate: isin.Scalar_Tensor_out + +- func: isnan(Tensor self) -> Tensor + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CPU, CUDA, MPS, MTIA, XPU: isnan + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_isnan + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: isnan_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: isnan_sparse_csr + autogen: isnan.out + tags: [core, pointwise] + +- func: is_distributed(Tensor self) -> bool + variants: function, method + device_check: NoCheck + device_guard: False + +- func: is_floating_point(Tensor self) -> bool + variants: function, method + device_check: NoCheck + device_guard: False + manual_cpp_binding: True + +- func: is_complex(Tensor self) -> bool + variants: function, method + device_check: NoCheck + device_guard: False + manual_cpp_binding: True + +- func: is_conj(Tensor self) -> bool + variants: function, method + device_guard: False + manual_cpp_binding: True + +- func: _is_zerotensor(Tensor self) -> bool + variants: function, method + device_guard: False + manual_cpp_binding: True + +- func: is_neg(Tensor self) -> bool + variants: function, method + device_guard: False + manual_cpp_binding: True + +- func: isreal(Tensor self) -> Tensor + variants: function, method + +- func: is_nonzero(Tensor self) -> bool + variants: function, method + device_check: NoCheck + device_guard: False + +- func: is_same_size(Tensor self, Tensor other) -> bool + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: nested_is_same_size + CompositeExplicitAutograd: is_same_size + +- func: is_signed(Tensor self) -> bool + variants: function, method + device_check: NoCheck + device_guard: False + manual_cpp_binding: True + +- func: is_inference(Tensor self) -> bool + variants: function, method + device_check: NoCheck + device_guard: False + manual_cpp_binding: True + +- func: numel(Tensor self) -> int + variants: method + device_check: NoCheck + device_guard: False + manual_cpp_binding: True + +- func: dim(Tensor self) -> int + variants: method + device_check: NoCheck + device_guard: False + manual_cpp_binding: True + +- func: get_device(Tensor self) -> int + variants: method + device_check: NoCheck + device_guard: False + manual_cpp_binding: True + +- func: storage_offset(Tensor self) -> int + variants: method + device_check: NoCheck + device_guard: False + manual_cpp_binding: True + +- func: is_contiguous(Tensor self) -> bool + variants: method + device_check: NoCheck + device_guard: False + manual_cpp_binding: True + +- func: is_contiguous.memory_format(Tensor self, MemoryFormat memory_format) -> bool + variants: method + device_check: NoCheck + device_guard: False + manual_cpp_binding: True + +- func: kl_div(Tensor self, Tensor target, int reduction=Mean, *, bool log_target=False) -> Tensor + +- func: kron(Tensor self, Tensor other) -> Tensor + variants: function, method + +- func: kron.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + +- func: kthvalue(Tensor self, SymInt k, int dim=-1, bool keepdim=False) -> (Tensor values, Tensor indices) + variants: function, method + dispatch: + CompositeExplicitAutograd: kthvalue + +- func: kthvalue.values(Tensor self, SymInt k, int dim=-1, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) + dispatch: + CPU: kthvalue_out_cpu + CUDA: kthvalue_out_cuda + MPS: kthvalue_out_mps + XPU: kthvalue_out_xpu + +- func: layer_norm(Tensor input, SymInt[] normalized_shape, Tensor? weight=None, Tensor? bias=None, float eps=1e-05, bool cudnn_enable=True) -> Tensor + dispatch: + CompositeImplicitAutograd: layer_norm_symint + +- func: native_layer_norm(Tensor input, SymInt[] normalized_shape, Tensor? weight, Tensor? bias, float eps) -> (Tensor, Tensor, Tensor) + dispatch: + CPU: layer_norm_cpu + CUDA: layer_norm_cuda + MPS: layer_norm_mps + XPU: layer_norm_xpu + CompositeExplicitAutograd: math_native_layer_norm + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: nested_layer_norm + autogen: native_layer_norm.out + tags: core + +- func: native_layer_norm_backward(Tensor grad_out, Tensor input, SymInt[] normalized_shape, Tensor mean, Tensor rstd, Tensor? weight, Tensor? bias, bool[3] output_mask) -> (Tensor, Tensor, Tensor) + dispatch: + CPU: layer_norm_backward_cpu + CUDA: layer_norm_backward_cuda + MPS: layer_norm_backward_mps + XPU: layer_norm_backward_xpu + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: layer_norm_backward_nested + autogen: native_layer_norm_backward.out + tags: core + +- func: rms_norm(Tensor input, SymInt[] normalized_shape, Tensor? weight=None, float? eps=None) -> Tensor + dispatch: + CompositeImplicitAutograd: rms_norm_symint + +- func: _fused_rms_norm(Tensor input, int[] normalized_shape, Tensor? weight, float? eps) -> (Tensor, Tensor) + dispatch: + CUDA: _fused_rms_norm_cuda + MPS: _fused_rms_norm_mps + XPU: _fused_rms_norm_xpu + CompositeImplicitAutograd: rms_norm_composite + +- func: _fused_rms_norm_backward(Tensor grad_out, Tensor input, int[] normalized_shape, Tensor rstd, Tensor? weight, bool[2] output_mask) -> (Tensor, Tensor) + dispatch: + CUDA: _fused_rms_norm_backward_cuda + XPU: _fused_rms_norm_backward_xpu + +- func: nan_to_num(Tensor self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: nan_to_num + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: nan_to_num_sparse + tags: pointwise + +- func: nan_to_num_(Tensor(a!) self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor(a!) + variants: function, method + dispatch: + CompositeExplicitAutograd: nan_to_num_ + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: nan_to_num_sparse_ + tags: pointwise + +- func: nan_to_num.out(Tensor self, float? nan=None, float? posinf=None, float? neginf=None, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MTIA, XPU, MPS: nan_to_num_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: nan_to_num_sparse_out + tags: pointwise + +- func: linear(Tensor input, Tensor weight, Tensor? bias=None) -> Tensor + python_module: nn + dispatch: + CompositeImplicitAutograd: linear + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: nested_linear + MPS: _mps_linear + +- func: linear_backward(Tensor self, Tensor grad_output, Tensor weight, bool[3] output_mask) -> (Tensor, Tensor, Tensor) + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: nested_linear_backward + MPS: mps_linear_backward + autogen: linear_backward.out + +- func: linear.out(Tensor input, Tensor weight, Tensor? bias=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + dispatch: + CompositeExplicitAutograd: linear_out + +- func: mkldnn_linear(Tensor self, Tensor weight, Tensor? bias=None) -> Tensor + python_module: nn + dispatch: + MkldnnCPU: mkldnn_linear + autogen: mkldnn_linear.out + +- func: mkldnn_linear_backward_input(int[] input_size, Tensor grad_output, Tensor weight) -> Tensor + dispatch: + MkldnnCPU: mkldnn_linear_backward_input + autogen: mkldnn_linear_backward_input.out + +- func: mkldnn_linear_backward_weights(Tensor grad_output, Tensor input, Tensor weight, bool bias_defined) -> (Tensor, Tensor) + dispatch: + MkldnnCPU: mkldnn_linear_backward_weights + autogen: mkldnn_linear_backward_weights.out + +- func: mkldnn_linear_backward(Tensor self, Tensor grad_output, Tensor weight, bool[3] output_mask) -> (Tensor, Tensor, Tensor) + dispatch: + MkldnnCPU: mkldnn_linear_backward + autogen: mkldnn_linear_backward.out + +- func: _cslt_compress(Tensor input) -> Tensor + dispatch: + CUDA: _cslt_compress + +- func: _cslt_sparse_mm(Tensor compressed_A, Tensor dense_B, Tensor? bias=None, Tensor? alpha=None, ScalarType? out_dtype=None, bool transpose_result=False, int alg_id=0, int split_k=1, int split_k_mode=-1) -> Tensor + dispatch: + CUDA: _cslt_sparse_mm + tags: needs_fixed_stride_order + +- func: _cslt_sparse_mm_search(Tensor compressed_A, Tensor dense_B, Tensor? bias=None, Tensor? alpha=None, ScalarType? out_dtype=None, bool transpose_result=False) -> int + dispatch: + CUDA: _cslt_sparse_mm_search + +- func: _sparse_semi_structured_tile(Tensor input, str algorithm="", bool use_cutlass=True) -> (Tensor, Tensor, Tensor, Tensor, Tensor) + dispatch: + CUDA: _sparse_semi_structured_tile + +- func: _sparse_semi_structured_apply(Tensor input, Tensor thread_masks) -> (Tensor, Tensor) + dispatch: + CUDA: _sparse_semi_structured_apply + +- func: _sparse_semi_structured_apply_dense(Tensor input, Tensor thread_masks) -> Tensor + dispatch: + CUDA: _sparse_semi_structured_apply_dense + +# DEPRECATED: Use torch.__sparse_semi_structured_mm/torch._sparse_semi_structured_addmm instead +- func: _sparse_semi_structured_linear(Tensor input, Tensor weight, Tensor meta, *, Tensor? bias=None, str? activation=None, ScalarType? out_dtype=None) -> Tensor + dispatch: + CUDA: _sparse_semi_structured_linear + +- func: _sparse_semi_structured_mm(Tensor mat1, Tensor mat1_meta, Tensor mat2, *, ScalarType? out_dtype=None) -> Tensor + dispatch: + CUDA: _sparse_semi_structured_mm + +- func: _sparse_semi_structured_addmm(Tensor input, Tensor mat1, Tensor mat1_meta, Tensor mat2, *, Scalar alpha=1, Scalar beta=1, ScalarType? out_dtype=None) -> Tensor + dispatch: + CUDA: _sparse_semi_structured_addmm + +- func: _mixed_dtypes_linear(Tensor input, Tensor weight, Tensor scale, *, Tensor? bias=None, str? activation=None) -> Tensor + dispatch: + CUDA: _mixed_dtypes_linear + +- func: fbgemm_linear_int8_weight_fp32_activation(Tensor input, Tensor weight, Tensor packed, Tensor col_offsets, Scalar weight_scale, Scalar weight_zero_point, Tensor bias) -> Tensor + +- func: fbgemm_linear_int8_weight(Tensor input, Tensor weight, Tensor packed, Tensor col_offsets, Scalar weight_scale, Scalar weight_zero_point, Tensor bias) -> Tensor + +- func: fbgemm_linear_quantize_weight(Tensor input) -> (Tensor, Tensor, float, int) + +- func: fbgemm_pack_gemm_matrix_fp16(Tensor input) -> Tensor + +- func: _wrapped_linear_prepack(Tensor weight, Tensor weight_scale, Tensor weight_zero_point, Tensor bias) -> Tensor + +- func: _wrapped_quantized_linear_prepacked(Tensor input, Tensor input_scale, Tensor input_zero_point, Tensor packed_weight, Tensor output_scale, Tensor output_zero_point, int out_channel) -> Tensor + +- func: fbgemm_linear_fp16_weight_fp32_activation(Tensor input, Tensor packed_weight, Tensor? bias) -> Tensor + +- func: fbgemm_linear_fp16_weight_fp32_activation.out(Tensor input, Tensor packed_weight, Tensor? bias, Tensor(a!) output) -> Tensor + +- func: fbgemm_linear_fp16_weight(Tensor input, Tensor packed_weight, Tensor bias) -> Tensor + +- func: fbgemm_linear_fp16_weight.out(Tensor input, Tensor packed_weight, Tensor bias, Tensor(a!) output) -> Tensor + +- func: fbgemm_pack_quantized_matrix(Tensor input) -> Tensor + +- func: fbgemm_pack_quantized_matrix.KN(Tensor input, int K, int N) -> Tensor + +- func: ldexp.Tensor(Tensor self, Tensor other) -> Tensor + variants: function, method + tags: pointwise + dispatch: + CompositeExplicitAutograd: ldexp + +- func: ldexp_(Tensor(a!) self, Tensor other) -> Tensor(a!) + variants: function, method + tags: pointwise + dispatch: + CompositeExplicitAutograd: ldexp_ + +- func: ldexp.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + tags: pointwise + dispatch: + CompositeExplicitAutograd: ldexp_out + +- func: linspace(Scalar start, Scalar end, int steps, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: linspace + +- func: linspace.Tensor_Tensor(Tensor start, Tensor end, int steps, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + category_override: factory + dispatch: + CompositeExplicitAutograd: linspace + +- func: linspace.Tensor_Scalar(Tensor start, Scalar end, int steps, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + category_override: factory + dispatch: + CompositeExplicitAutograd: linspace + +- func: linspace.Scalar_Tensor(Scalar start, Tensor end, int steps, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + category_override: factory + dispatch: + CompositeExplicitAutograd: linspace + +- func: linspace.out(Scalar start, Scalar end, int steps, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, Meta: linspace_out + CUDA: linspace_cuda_out + MPS: linspace_out_mps + XPU: linspace_xpu_out + +- func: linspace.Tensor_Tensor_out(Tensor start, Tensor end, int steps, *, Tensor(a!) out) -> Tensor(a!) + category_override: factory + dispatch: + CompositeExplicitAutograd: linspace_out + +- func: linspace.Tensor_Scalar_out(Tensor start, Scalar end, int steps, *, Tensor(a!) out) -> Tensor(a!) + category_override: factory + dispatch: + CompositeExplicitAutograd: linspace_out + +- func: linspace.Scalar_Tensor_out(Scalar start, Tensor end, int steps, *, Tensor(a!) out) -> Tensor(a!) + category_override: factory + dispatch: + CompositeExplicitAutograd: linspace_out + +- func: log(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: log.out + variants: function, method + tags: [core, pointwise] + +- func: log_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: log.out + variants: function, method + tags: pointwise + +- func: log.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: log_out + tags: pointwise + +- func: log10(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: log10.out + variants: function, method + tags: [core, pointwise] + +- func: log10_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: log10.out + variants: function, method + tags: pointwise + +- func: log10.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: log10_out + tags: pointwise + +- func: log1p(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: log1p.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: log1p_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: log1p_sparse_csr + tags: [core, pointwise] + +- func: log1p_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: log1p.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: log1p_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: log1p_sparse_csr_ + tags: pointwise + +- func: log1p.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: log1p_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: log1p_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: log1p_sparse_csr_out + tags: pointwise + +- func: log2(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: log2.out + variants: function, method + tags: [core, pointwise] + +- func: log2_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: log2.out + variants: function, method + tags: pointwise + +- func: log2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: log2_out + tags: pointwise + +- func: logaddexp.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: logaddexp_out + tags: pointwise + +- func: logaddexp(Tensor self, Tensor other) -> Tensor + variants: method, function + structured_delegate: logaddexp.out + tags: pointwise + +- func: logaddexp2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: logaddexp2_out + tags: pointwise + +- func: logaddexp2(Tensor self, Tensor other) -> Tensor + variants: method, function + structured_delegate: logaddexp2.out + tags: pointwise + +- func: xlogy.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: xlogy.OutTensor + variants: function, method + tags: pointwise + +- func: xlogy.Scalar_Self(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: xlogy + tags: pointwise + +- func: xlogy.Scalar_Other(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: xlogy + tags: pointwise + +# xlogy: inplace variant +- func: xlogy_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: xlogy.OutTensor + tags: pointwise + +- func: xlogy_.Scalar_Other(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: xlogy_ + +# xlogy: out variant +- func: xlogy.OutTensor(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + variants: function + dispatch: + CPU, CUDA, MPS, XPU: xlogy_out + tags: pointwise + +- func: xlogy.OutScalar_Self(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: xlogy_out + tags: pointwise + +- func: xlogy.OutScalar_Other(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: xlogy_out + tags: pointwise + +- func: logspace(Scalar start, Scalar end, int steps, float base=10.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: logspace + +- func: logspace.Tensor_Tensor(Tensor start, Tensor end, int steps, float base=10.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + category_override: factory + dispatch: + CompositeExplicitAutograd: logspace + +- func: logspace.Tensor_Scalar(Tensor start, Scalar end, int steps, float base=10.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + category_override: factory + dispatch: + CompositeExplicitAutograd: logspace + +- func: logspace.Scalar_Tensor(Scalar start, Tensor end, int steps, float base=10.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + category_override: factory + dispatch: + CompositeExplicitAutograd: logspace + +- func: logspace.out(Scalar start, Scalar end, int steps, float base=10.0, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, Meta: logspace_out + CUDA: logspace_cuda_out + XPU: logspace_xpu_out + +- func: logspace.Tensor_Tensor_out(Tensor start, Tensor end, int steps, float base=10.0, *, Tensor(a!) out) -> Tensor(a!) + category_override: factory + dispatch: + CompositeExplicitAutograd: logspace_out + +- func: logspace.Tensor_Scalar_out(Tensor start, Scalar end, int steps, float base=10.0, *, Tensor(a!) out) -> Tensor(a!) + category_override: factory + dispatch: + CompositeExplicitAutograd: logspace_out + +- func: logspace.Scalar_Tensor_out(Scalar start, Tensor end, int steps, float base=10.0, *, Tensor(a!) out) -> Tensor(a!) + category_override: factory + dispatch: + CompositeExplicitAutograd: logspace_out + +# log_softmax allows positional dtype, unlike most operators, because kwonly is BC-breaking when loading jit models. +- func: log_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor + variants: function, method + +- func: log_softmax.int_out(Tensor self, int dim, ScalarType? dtype=None, *, Tensor(a!) out) -> Tensor(a!) + variants: function + dispatch: + CompositeExplicitAutograd: log_softmax_out + +- func: _log_softmax(Tensor self, int dim, bool half_to_float) -> Tensor + structured_delegate: _log_softmax.out + tags: core + +- func: _log_softmax.out(Tensor self, int dim, bool half_to_float, *, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU: log_softmax_cpu_out + CUDA: log_softmax_cuda_out + MTIA: log_softmax_mtia_out + MPS: log_softmax_mps_out + XPU: log_softmax_xpu_out + +- func: _log_softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor + structured_delegate: _log_softmax_backward_data.out + +- func: _log_softmax_backward_data.out(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype, *, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU: log_softmax_backward_cpu_out + CUDA: log_softmax_backward_cuda_out + MTIA: log_softmax_backward_mtia_out + MPS: log_softmax_backward_mps_out + XPU: log_softmax_backward_xpu_out + +- func: _logcumsumexp(Tensor self, int dim) -> Tensor + dispatch: + CPU: _logcumsumexp_cpu + CUDA: _logcumsumexp_cuda + MPS: _logcumsumexp_mps + XPU: _logcumsumexp_xpu + +- func: _logcumsumexp.out(Tensor self, int dim, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU: _logcumsumexp_out_cpu + CUDA: _logcumsumexp_out_cuda + MPS: _logcumsumexp_out_mps + XPU: _logcumsumexp_out_xpu + +- func: logcumsumexp(Tensor self, int dim) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: logcumsumexp + +- func: logcumsumexp.out(Tensor self, int dim, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: logcumsumexp_out + +- func: logsumexp(Tensor self, int[1] dim, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: logsumexp + tags: reduction + +- func: logsumexp.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + # calls squeeze + CompositeExplicitAutogradNonFunctional: logsumexp_out + tags: reduction + +- func: margin_ranking_loss(Tensor input1, Tensor input2, Tensor target, float margin=0.0, int reduction=Mean) -> Tensor + +- func: matmul(Tensor self, Tensor other) -> Tensor + variants: function, method + dispatch: + CompositeImplicitAutograd: matmul + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: matmul_nested + +- func: matmul_backward(Tensor grad, Tensor self, Tensor other, bool[2] mask) -> (Tensor, Tensor) + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: matmul_backward_nested + autogen: matmul_backward.out + +- func: matmul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeImplicitAutograd: matmul_out + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: matmul_out_nested + +# Alias to linalg.matrix_power +- func: matrix_power(Tensor self, int n) -> Tensor + variants: function, method + +# Alias to linalg.matrix_power +- func: matrix_power.out(Tensor self, int n, *, Tensor(a!) out) -> Tensor(a!) + +# Alias to linalg.matrix_exp +- func: matrix_exp(Tensor self) -> Tensor + variants: function, method + +# This function should be deprecated in favor of differential_analytic_matrix_function in FunctionsManual.cpp +- func: matrix_exp_backward(Tensor self, Tensor grad) -> Tensor + +# DEPRECATED: Use torch.aminmax instead +- func: _aminmax(Tensor self) -> (Tensor, Tensor) + dispatch: + CPU, CUDA, XPU: _aminmax_all + autogen: _aminmax.out + +# DEPRECATED: Use torch.aminmax instead +- func: _aminmax.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor, Tensor) + dispatch: + CPU, CUDA, XPU: _aminmax + autogen: _aminmax.dim_out + +- func: aminmax(Tensor self, *, int? dim=None, bool keepdim=False) -> (Tensor min, Tensor max) + device_check: NoCheck # TensorIterator + structured_delegate: aminmax.out + variants: function, method + tags: reduction + +- func: aminmax.out(Tensor self, *, int? dim=None, bool keepdim=False, Tensor(a!) min, Tensor(b!) max) -> (Tensor(a!) min, Tensor(b!) max) + device_check: NoCheck # TensorIterator + structured: True + dispatch: + CPU, CUDA, MPS, XPU: aminmax_out + tags: reduction + +- func: _compute_linear_combination(Tensor input, Tensor coefficients) -> Tensor + dispatch: + CPU, CUDA, XPU, MPS: _compute_linear_combination + +- func: _compute_linear_combination.out(Tensor input, Tensor coefficients, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, XPU, MPS: _compute_linear_combination_out + +- func: max.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) + device_check: NoCheck # TensorIterator + structured_delegate: max.dim_max + variants: function, method + dispatch: + QuantizedCPU, QuantizedCUDA: qmax + tags: [core, reduction] + +- func: max.dim_max(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices) + device_check: NoCheck # TensorIterator + structured: True + precomputed: + - dim -> int dim + dispatch: + CPU, CUDA, MTIA, XPU: max_out + MPS: max_out_mps + tags: reduction + +- func: value_selecting_reduction_backward(Tensor grad, int dim, Tensor indices, SymInt[] sizes, bool keepdim) -> Tensor + variants: function + device_check: NoCheck + device_guard: False + dispatch: + CompositeImplicitAutograd: value_selecting_reduction_backward_symint + NestedTensorCPU, NestedTensorCUDA: value_selecting_reduction_backward_nested_symint + +- func: amax(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor + variants: function, method + structured_delegate: amax.out + tags: [core, reduction] + +- func: amax.out(Tensor self, int[1] dim=[], bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU, CUDA, MPS, XPU: amax_out + tags: reduction + +# Return: (Tensor output, Tensor indices) +- func: max_pool1d_with_indices(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, int[1] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor) + +- func: max_pool1d(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, int[1] dilation=1, bool ceil_mode=False) -> Tensor + +- func: max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor + dispatch: + CompositeImplicitAutograd: max_pool2d + MPS: mps_max_pool2d + +- func: max_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor + dispatch: + MPS: mps_max_pool2d_backward + autogen: max_pool2d_backward.out + +- func: mkldnn_max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor + dispatch: + MkldnnCPU: mkldnn_max_pool2d + autogen: mkldnn_max_pool2d.out + +- func: mkldnn_max_pool2d_backward(Tensor grad_output, Tensor output, Tensor input, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor + dispatch: + MkldnnCPU: mkldnn_max_pool2d_backward + autogen: mkldnn_max_pool2d_backward.out + +- func: mkldnn_max_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor + dispatch: + MkldnnCPU: mkldnn_max_pool3d + autogen: mkldnn_max_pool3d.out + +- func: mkldnn_max_pool3d_backward(Tensor grad_output, Tensor output, Tensor input, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor + dispatch: + MkldnnCPU: mkldnn_max_pool3d_backward + autogen: mkldnn_max_pool3d_backward.out + +- func: quantized_max_pool1d(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, int[1] dilation=1, bool ceil_mode=False) -> Tensor + dispatch: + QuantizedCPU: quantized_max_pool1d + autogen: quantized_max_pool1d.out + +- func: quantized_max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor + dispatch: + QuantizedCPU: quantized_max_pool2d + QuantizedCUDA: quantized_max_pool2d_cudnn + autogen: quantized_max_pool2d.out + +- func: quantized_max_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor + dispatch: + QuantizedCPU: quantized_max_pool3d + autogen: quantized_max_pool3d.out + +- func: max_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor + +# The CPU and GPU dispatch variants are named weirdly here because otherwise there +# are namespacing issues in C++ +- func: mean(Tensor self, *, ScalarType? dtype=None) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: mean + tags: [core, reduction] + +# For normal naming convention this should be `mean.out`. However since we already have `mean.out` we have to rename this. +- func: mean.dtype_out(Tensor self, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CompositeExplicitAutograd: mean_dtype_out + tags: reduction + +- func: mean.dim(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + structured_delegate: mean.out + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + QuantizedCPU: mean_quantized_cpu + tags: [core, reduction] + +- func: mean.out(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + structured: True + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, XPU: mean_out + QuantizedCPU: mean_out_quantized_cpu + tags: reduction + +- func: nanmean(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + device_check: NoCheck # Composite + variants: function, method + +- func: nanmean.out(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # Composite + +- func: median(Tensor self) -> Tensor + variants: function, method + dispatch: + CPU: median_cpu + CUDA: median_cuda + MPS: median_mps + XPU: median_xpu + autogen: median.out + +- func: median.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) + variants: function, method + dispatch: + CompositeExplicitAutograd: median + +- func: median.dim_values(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) + dispatch: + CPU: median_out_cpu + CUDA: median_out_cuda + MPS: median_out_mps + XPU: median_out_xpu + +- func: nanmedian(Tensor self) -> Tensor + variants: function, method + dispatch: + CPU: nanmedian_cpu + CUDA: nanmedian_cuda + MPS: nanmedian_mps + XPU: nanmedian_xpu + autogen: nanmedian.out + +- func: nanmedian.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) + variants: function, method + dispatch: + CompositeExplicitAutograd: nanmedian + +- func: nanmedian.dim_values(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) + dispatch: + CPU: nanmedian_out_cpu + CUDA: nanmedian_out_cuda + MPS: nanmedian_out_mps + XPU: nanmedian_out_xpu + +- func: min.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) + device_check: NoCheck # TensorIterator + structured_delegate: min.dim_min + variants: function, method + dispatch: + QuantizedCPU, QuantizedCUDA: qmin + tags: [core, reduction] + +- func: min.dim_min(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) min, Tensor(b!) min_indices) -> (Tensor(a!) values, Tensor(b!) indices) + device_check: NoCheck # TensorIterator + structured: True + precomputed: + - dim -> int dim + dispatch: + CPU, CUDA, MTIA, XPU: min_out + MPS: min_out_mps + tags: reduction + +- func: amin(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor + variants: function, method + structured_delegate: amin.out + tags: [core, reduction] + +- func: amin.out(Tensor self, int[1] dim=[], bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU, CUDA, MPS, XPU: amin_out + tags: reduction + +# TODO: Add this function to MPS dispatch key so that we avoid declaring it in +# native_functions.yaml +# https://github.com/pytorch/pytorch/issues/77394 +- func: _mps_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor + dispatch: + MPS: _mps_convolution + autogen: _mps_convolution.out + +- func: mps_convolution_backward(Tensor self, Tensor grad_output, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) + dispatch: + MPS: mps_convolution_backward + autogen: mps_convolution_backward.out + +- func: mkldnn_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor + dispatch: + CompositeExplicitAutograd: mkldnn_convolution + autogen: mkldnn_convolution.out + +- func: mkldnn_rnn_layer(Tensor input, Tensor weight0, Tensor weight1, Tensor weight2, Tensor weight3, Tensor hx_, Tensor cx_, bool reverse, int[] batch_sizes, int mode, int hidden_size, int num_layers, bool has_biases, bool bidirectional, bool batch_first, bool train) -> (Tensor, Tensor, Tensor, Tensor) + dispatch: + CPU: mkldnn_rnn_layer + MkldnnCPU: mkldnn_rnn_layer + autogen: mkldnn_rnn_layer.out + +- func: mkldnn_rnn_layer_backward(Tensor input, Tensor weight1, Tensor weight2, Tensor weight3, Tensor weight4, Tensor hx_, Tensor cx_tmp, Tensor output, Tensor hy_, Tensor cy_, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, bool reverse, int mode, int hidden_size, int num_layers, bool has_biases, bool train, bool bidirectional, int[] batch_sizes, bool batch_first, Tensor workspace) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor) + dispatch: + CPU: mkldnn_rnn_layer_backward + autogen: mkldnn_rnn_layer_backward.out + +- func: miopen_batch_norm(Tensor input, Tensor weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float exponential_average_factor, float epsilon) -> (Tensor, Tensor, Tensor) + dispatch: + CUDA: miopen_batch_norm + autogen: miopen_batch_norm.out + +- func: miopen_batch_norm_backward(Tensor input, Tensor grad_output, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, float epsilon) -> (Tensor, Tensor, Tensor) + dispatch: + CUDA: miopen_batch_norm_backward + autogen: miopen_batch_norm_backward.out + +- func: miopen_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor + dispatch: + CUDA: miopen_convolution + autogen: miopen_convolution.out + +- func: miopen_convolution_transpose(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor + dispatch: + CUDA: miopen_convolution_transpose + autogen: miopen_convolution_transpose.out + +- func: miopen_depthwise_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor + dispatch: + CUDA: miopen_depthwise_convolution + autogen: miopen_depthwise_convolution.out + +- func: miopen_convolution_relu(Tensor self, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor + dispatch: + CUDA: miopen_convolution_relu + +- func: miopen_convolution_add_relu(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor + dispatch: + CUDA: miopen_convolution_add_relu + +- func: miopen_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor hx, Tensor? cx, int mode, int hidden_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor) + dispatch: + CUDA: miopen_rnn + autogen: miopen_rnn.out + tags: nondeterministic_seeded + +- func: miopen_rnn_backward(Tensor input, Tensor[] weight, int weight_stride0, Tensor weight_buf, Tensor hx, Tensor? cx, Tensor output, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, int mode, int hidden_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state, Tensor reserve, bool[4] output_mask) -> (Tensor, Tensor, Tensor, Tensor[]) + dispatch: + CUDA: miopen_rnn_backward + autogen: miopen_rnn_backward.out + +- func: _use_miopen_ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank) -> bool + device_check: NoCheck # Tensor arguments allowed to be on different devices, see also miopen_ctc_loss + dispatch: + CUDA: _use_miopen_ctc_loss + +- func: _use_miopen_ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank) -> bool + device_check: NoCheck # Tensor arguments allowed to be on different devices, see also miopen_ctc_loss + dispatch: + CUDA: _use_miopen_ctc_loss_tensor + +- func: miopen_ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor) + device_check: NoCheck # log_probs is expected to be on CUDA while targets is expected to be on CPU + dispatch: + CUDA: miopen_ctc_loss + autogen: miopen_ctc_loss.out + +- func: miopen_ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor) + device_check: NoCheck # log_probs is expected to be on CUDA while targets is expected to be on CPU + dispatch: + CUDA: miopen_ctc_loss_tensor + +- func: mm(Tensor self, Tensor mat2) -> Tensor + structured_delegate: mm.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: _sparse_mm + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: _sparse_csr_mm + tags: core + +- func: mm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU: mm_out_cpu + CUDA: mm_out_cuda + MTIA: mm_out_mtia + MPS: mm_out_mps + XPU: mm_out_xpu + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: _sparse_mm_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: _sparse_csr_mm_out + +- func: mm.dtype(Tensor self, Tensor mat2, ScalarType out_dtype) -> Tensor + dispatch: + CUDA: _mm_dtype_cuda + XPU: _mm_dtype_xpu + +- func: mm.dtype_out(Tensor self, Tensor mat2, ScalarType out_dtype, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CUDA: _mm_dtype_out_cuda + XPU: _mm_dtype_out_xpu + +- func: _int_mm(Tensor self, Tensor mat2) -> Tensor + dispatch: + CPU: _int_mm_cpu + CUDA: _int_mm_cuda + XPU: _int_mm_xpu + +- func: _int_mm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU: _int_mm_out_cpu + CUDA: _int_mm_out_cuda + XPU: _int_mm_out_xpu + +- func: _convert_weight_to_int4pack(Tensor self, int innerKTiles) -> Tensor + dispatch: + CUDA: _convert_weight_to_int4pack_cuda + MPS: _convert_weight_to_int4pack_mps + XPU: _convert_weight_to_int4pack_xpu + +- func: _weight_int4pack_mm(Tensor self, Tensor mat2, int qGroupSize, Tensor qScaleAndZeros) -> Tensor + dispatch: + MPS: _weight_int4pack_mm_mps + CUDA: _weight_int4pack_mm_cuda + XPU: _weight_int4pack_mm_xpu + +- func: _weight_int4pack_mm_with_scales_and_zeros(Tensor self, Tensor mat2, int qGroupSize, Tensor qScale, Tensor qZeros) -> Tensor + dispatch: + XPU: _weight_int4pack_mm_xpu + +# Split int4 pack weight between cpu and other devices due to +# https://github.com/pytorch/ao/issues/1117#issuecomment-2451252756. +- func: _convert_weight_to_int4pack_for_cpu(Tensor self, int innerKTiles) -> Tensor + dispatch: + CPU: _convert_weight_to_int4pack_cpu + +- func: _weight_int4pack_mm_for_cpu(Tensor self, Tensor mat2, int qGroupSize, Tensor qScaleAndZeros) -> Tensor + dispatch: + CPU: _weight_int4pack_mm_cpu + +- func: _dyn_quant_pack_4bit_weight(Tensor weights, Tensor scales_zeros, Tensor? bias, int block_size, int in_features, int out_features) -> Tensor + dispatch: + CPU: _dyn_quant_pack_4bit_weight_cpu + +- func: _dyn_quant_matmul_4bit(Tensor inp, Tensor packed_weights, int block_size, int in_features, int out_features) -> Tensor + dispatch: + CPU: _dyn_quant_matmul_4bit_cpu + +- func: _weight_int8pack_mm(Tensor self, Tensor mat2, Tensor scales) -> Tensor + dispatch: + CPU: _weight_int8pack_mm_cpu + CUDA: _weight_int8pack_mm_cuda + MPS: _weight_int8pack_mm_mps + XPU: _weight_int8pack_mm_xpu + +- func: _sparse_mm(Tensor sparse, Tensor dense) -> Tensor + python_module: sparse + +- func: _sparse_mm.reduce(Tensor sparse, Tensor dense, str reduce) -> Tensor + python_module: sparse + +- func: _sparse_sparse_matmul(Tensor self, Tensor other) -> Tensor + dispatch: + SparseCPU: sparse_sparse_matmul_cpu + SparseCUDA: sparse_sparse_matmul_cuda + SparseMPS: sparse_sparse_matmul_mps + SparseXPU: sparse_sparse_matmul_xpu + autogen: _sparse_sparse_matmul.out + +- func: mode(Tensor self, int dim=-1, bool keepdim=False) -> (Tensor values, Tensor indices) + variants: function, method + dispatch: + CPU, CUDA, XPU: mode + +- func: mode.values(Tensor self, int dim=-1, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) + dispatch: + CompositeExplicitAutograd: mode_out + +- func: mul.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: mul.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: mul_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: mul_sparse_csr + MkldnnCPU: mkldnn_mul + ZeroTensor: mul_zerotensor + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_mul_Tensor + tags: [core, pointwise] + +- func: mul_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: mul.out + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: mul_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: mul_sparse_csr_ + MkldnnCPU: mkldnn_mul_ + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_mul__Tensor + tags: pointwise + +- func: mul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: mul_out + SparseCPU: mul_out_sparse_cpu + SparseCUDA: mul_out_sparse_cuda + SparseMPS: mul_out_sparse_mps + SparseXPU: mul_out_sparse_xpu + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: mul_out_sparse_csr + MkldnnCPU: mkldnn_mul_out + tags: pointwise + # For C++ only, until we have conversion from C++ numbers to Tensor + +- func: mul.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: mul + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: mul_scalar_sparse_csr + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_mul_Scalar + tags: [core, pointwise] + +- func: mul_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: mul_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: mul__scalar_sparse_csr + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_mul__Scalar + autogen: mul.Scalar_out + tags: pointwise +# multiply, alias for mul + +- func: multiply.Tensor(Tensor self, Tensor other) -> Tensor + variants: function, method + +- func: multiply_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + variants: method + +- func: multiply.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + +- func: multiply.Scalar(Tensor self, Scalar other) -> Tensor + variants: function, method + +- func: multiply_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + variants: method + +- func: mv(Tensor self, Tensor vec) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: mv + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: mv_sparse + +- func: mv.out(Tensor self, Tensor vec, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: mv_out + +- func: mvlgamma.out(Tensor self, int p, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: mvlgamma_out + tags: pointwise + +- func: mvlgamma(Tensor self, int p) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: mvlgamma + tags: pointwise + +- func: mvlgamma_(Tensor(a!) self, int p) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: mvlgamma_ + tags: pointwise + +- func: narrow_copy(Tensor self, int dim, SymInt start, SymInt length) -> Tensor + variants: function, method + dispatch: + CPU: narrow_copy_dense_cpu + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: narrow_copy_sparse + CompositeExplicitAutogradNonFunctional: narrow_copy_dense_symint + tags: view_copy + +- func: narrow_copy.out(Tensor self, int dim, SymInt start, SymInt length, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU: narrow_copy_dense_cpu_out + +- func: narrow(Tensor(a) self, int dim, SymInt start, SymInt length) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeImplicitAutograd: narrow_symint + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: narrow_nested_symint + +- func: narrow.Tensor(Tensor(a) self, int dim, Tensor start, SymInt length) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeImplicitAutograd: narrow_tensor_symint + +- func: native_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor) + dispatch: + CPU: batch_norm_cpu + CUDA: batch_norm_cuda + MPS: batch_norm_mps + XPU: batch_norm_xpu + MkldnnCPU: mkldnn_batch_norm + +- func: native_batch_norm.out(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, *, Tensor(a!) out, Tensor(b!) save_mean, Tensor(c!) save_invstd) -> (Tensor(a!), Tensor(b!), Tensor(c!)) + dispatch: + CUDA: batch_norm_cuda_out + MPS: batch_norm_mps_out + CPU: batch_norm_cpu_out + XPU: batch_norm_xpu_out + +# TODO: In 2 weeks, we should make native_batch_norm composite implicit so that this correct schema percolates correctly through our dispatching +- func: _native_batch_norm_legit(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor) + dispatch: + CPU: _batch_norm_legit_cpu + CUDA: _batch_norm_legit_cuda + MPS: _batch_norm_legit_mps + XPU: _batch_norm_legit_xpu + MkldnnCPU: _mkldnn_batch_norm_legit + autogen: _native_batch_norm_legit_functional + tags: core + +# HACK: identical to _native_batch_norm_legit, but training is known to be False, +# So we known that running stats will not be mutated. +# The real fix here is batch norm consolidation. +- func: _native_batch_norm_legit_no_training(Tensor input, Tensor? weight, Tensor? bias, Tensor running_mean, Tensor running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor) + dispatch: + CompositeExplicitAutograd: _batch_norm_legit_no_training + autogen: _native_batch_norm_legit_no_training.out + tags: core + +- func: _native_batch_norm_legit.out(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps, *, Tensor(d!) out, Tensor(e!) save_mean, Tensor(f!) save_invstd) -> (Tensor(d!), Tensor(e!), Tensor(f!)) + dispatch: + CPU: _batch_norm_legit_cpu_out + CUDA: _batch_norm_legit_cuda_out + MPS: _batch_norm_legit_mps_out + XPU: _batch_norm_legit_xpu_out + +- func: _native_batch_norm_legit.no_stats(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor) + dispatch: + CPU: _batch_norm_legit_no_stats_cpu + CUDA: _batch_norm_legit_no_stats_cuda + MPS: _batch_norm_legit_no_stats_mps + XPU: _batch_norm_legit_no_stats_xpu + MkldnnCPU: _mkldnn_batch_norm_legit_no_stats + tags: core + +- func: _native_batch_norm_legit.no_stats_out(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps, *, Tensor(a!) out, Tensor(b!) save_mean, Tensor(c!) save_invstd) -> (Tensor(a!), Tensor(b!), Tensor(c!)) + dispatch: + CPU: _batch_norm_legit_no_stats_cpu_out + CUDA: _batch_norm_legit_no_stats_cuda_out + MPS: _batch_norm_legit_no_stats_mps_out + XPU: _batch_norm_legit_no_stats_xpu_out + +- func: batch_norm_stats(Tensor input, float eps) -> (Tensor, Tensor) + dispatch: + CUDA: batch_norm_stats_cuda + XPU: batch_norm_stats_xpu + autogen: batch_norm_stats.out + +- func: batch_norm_elemt(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor invstd, float eps) -> Tensor + dispatch: + CUDA: batch_norm_elemt_cuda + XPU: batch_norm_elemt_xpu + +- func: batch_norm_elemt.out(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor invstd, float eps, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CUDA: batch_norm_elemt_cuda_out + XPU: batch_norm_elemt_xpu_out + +# for backward compatibility +- func: batch_norm_gather_stats(Tensor input, Tensor mean, Tensor invstd, Tensor? running_mean, Tensor? running_var, float momentum, float eps, int count) -> (Tensor, Tensor) + dispatch: + CUDA: batch_norm_gather_stats_cuda + XPU: batch_norm_gather_stats_xpu + autogen: batch_norm_gather_stats.out + +- func: batch_norm_gather_stats_with_counts(Tensor input, Tensor mean, Tensor invstd, Tensor? running_mean, Tensor? running_var, float momentum, float eps, Tensor counts) -> (Tensor, Tensor) + dispatch: + CUDA: batch_norm_gather_stats_with_counts_cuda + XPU: batch_norm_gather_stats_with_counts_xpu + autogen: batch_norm_gather_stats_with_counts.out + +- func: native_batch_norm_backward(Tensor grad_out, Tensor input, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_invstd, bool train, float eps, bool[3] output_mask) -> (Tensor, Tensor, Tensor) + dispatch: + CPU: batch_norm_backward_cpu + CUDA: batch_norm_backward_cuda + MPS: batch_norm_backward_mps + XPU: batch_norm_backward_xpu + MkldnnCPU: mkldnn_batch_norm_backward + autogen: native_batch_norm_backward.out + +- func: batch_norm_backward_reduce(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, bool input_g, bool weight_g, bool bias_g) -> (Tensor, Tensor, Tensor, Tensor) + dispatch: + CUDA: batch_norm_backward_reduce_cuda + XPU: batch_norm_backward_reduce_xpu + autogen: batch_norm_backward_reduce.out + +- func: batch_norm_backward_elemt(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, Tensor sum_dy, Tensor sum_dy_xmu, Tensor count) -> Tensor + dispatch: + CUDA: batch_norm_backward_elemt_cuda + XPU: batch_norm_backward_elemt_xpu + autogen: batch_norm_backward_elemt.out + +- func: batch_norm_update_stats(Tensor input, Tensor? running_mean, Tensor? running_var, float momentum) -> (Tensor, Tensor) + dispatch: + CPU: batch_norm_update_stats_cpu + CUDA: batch_norm_update_stats_cuda + XPU: batch_norm_update_stats_xpu + autogen: batch_norm_update_stats.out + +- func: is_vulkan_available() -> bool + +- func: _nnpack_available() -> bool + +- func: _nnpack_spatial_convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[2] padding, SymInt[2] stride=1) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: _nnpack_spatial_convolution + autogen: _nnpack_spatial_convolution.out + +- func: ones(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: ones + Meta: ones_meta_symint + +- func: ones.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: ones_out + +- func: ones_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd: ones_like + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: ones_like + autogen: ones_like.out + +- func: pairwise_distance(Tensor x1, Tensor x2, float p=2, float eps=1e-06, bool keepdim=False) -> Tensor + +- func: cdist(Tensor x1, Tensor x2, float p=2, int? compute_mode=None) -> Tensor + +- func: _euclidean_dist(Tensor x1, Tensor x2) -> Tensor + dispatch: + CompositeExplicitAutograd: _euclidean_dist + autogen: _euclidean_dist.out + +- func: _cdist_forward(Tensor x1, Tensor x2, float p, int? compute_mode) -> Tensor + dispatch: + CPU, CUDA, MPS, XPU: _cdist_forward + MTIA: _cdist_forward_mtia + autogen: _cdist_forward.out + tags: core + +- func: _cdist_backward(Tensor grad_output, Tensor x1, Tensor x2, float p, Tensor cdist) -> Tensor + dispatch: + CPU, CUDA, MPS, XPU: _cdist_backward + autogen: _cdist_backward.out + +- func: pdist(Tensor self, float p=2) -> Tensor + +- func: _pdist_forward(Tensor self, float p=2) -> Tensor + dispatch: + CPU, CUDA, XPU: _pdist_forward + autogen: _pdist_forward.out + tags: core + +- func: _pdist_backward(Tensor grad_output, Tensor self, float p, Tensor pdist) -> Tensor + dispatch: + CPU, CUDA, XPU: _pdist_backward + autogen: _pdist_backward.out + +- func: cosine_similarity(Tensor x1, Tensor x2, int dim=1, float eps=1e-08) -> Tensor + variants: function + +- func: permute(Tensor(a) self, int[] dims) -> Tensor(a) + variants: function, method + dispatch: + CompositeExplicitAutograd: permute + MPS: permute_mps + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: permute_sparse_coo + tags: core + +- func: movedim.intlist(Tensor(a) self, int[] source, int[] destination) -> Tensor(a) + variants: function, method + +- func: movedim.int(Tensor(a) self, int source, int destination) -> Tensor(a) + variants: function, method + +# moveaxis, alias for movedim +- func: moveaxis.intlist(Tensor(a) self, int[] source, int[] destination) -> Tensor(a) + variants: function, method + +- func: moveaxis.int(Tensor(a) self, int source, int destination) -> Tensor(a) + variants: function, method + +# Only exposed from C++ -- in Python, +# we expose it as an attribute `T`, not a function. +# +# I'd like to name this "T" in C++ too, but +# calling a native function "T" causes undefined +# behavior on Windows, for reasons I don't understand +# (maybe related to capital letter collation somehow...) +- func: numpy_T(Tensor(a) self) -> Tensor(a) + variants: method + +# Exposed on Python as an attribute 'H' +- func: matrix_H(Tensor(a) self) -> Tensor(a) + variants: method + +# Exposed on Python as an attribute 'mT' +- func: mT(Tensor(a) self) -> Tensor(a) + variants: method + +# Exposed on Python as an attribute 'mH' +- func: mH(Tensor(a) self) -> Tensor(a) + variants: method + +- func: adjoint(Tensor(a) self) -> Tensor(a) + variants: function, method + +- func: pixel_shuffle(Tensor self, int upscale_factor) -> Tensor + dispatch: + CPU: pixel_shuffle_cpu + MPS: pixel_shuffle_mps + CompositeExplicitAutogradNonFunctional: math_pixel_shuffle + autogen: pixel_shuffle.out + +- func: pixel_unshuffle(Tensor self, int downscale_factor) -> Tensor + dispatch: + CPU: pixel_unshuffle_cpu + MPS: pixel_unshuffle_mps + CompositeExplicitAutogradNonFunctional: math_pixel_unshuffle + autogen: pixel_unshuffle.out + +- func: channel_shuffle(Tensor self, SymInt groups) -> Tensor + dispatch: + CPU, CUDA, XPU: channel_shuffle + QuantizedCPU: channel_shuffle_quantized_cpu + autogen: channel_shuffle.out + +- func: native_channel_shuffle(Tensor self, SymInt groups) -> Tensor + dispatch: + CPU: channel_shuffle_cpu + CompositeImplicitAutograd: math_channel_shuffle + +- func: is_pinned(Tensor self, Device? device=None) -> bool + variants: method + dispatch: + # the NestedTensor keys are necessary because NestedTensor has been removed + # from the CompositeExplicitAutograd keyset see Note [NestedTensor Not Included in Backend Keys] + CompositeExplicitAutograd, NestedTensorCPU: is_pinned + SparseCsrCPU: is_pinned_sparse_compressed + SparseCPU: is_pinned_sparse_coo + +# TODO: add a copy kwarg that guarantees that the tensor is put into fresh +# pinned memory +- func: pin_memory(Tensor(a) self, Device? device=None) -> Tensor(a) + variants: method + +# Unlike pin_memory, this is guaranteed to give a new non-aliasing tensor +- func: _pin_memory(Tensor self, Device? device=None) -> Tensor + dispatch: + CompositeExplicitAutograd: _pin_memory + NestedTensorCPU: _pin_memory_nested + SparseCPU: _pin_memory_sparse_coo + SparseCsrCPU: _pin_memory_sparse_compressed + autogen: _pin_memory.out + +- func: pinverse(Tensor self, float rcond=1e-15) -> Tensor + variants: function, method + +- func: poisson_nll_loss(Tensor input, Tensor target, bool log_input, bool full, float eps, int reduction) -> Tensor + variants: function + +- func: rad2deg(Tensor self) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: rad2deg + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: rad2deg_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: rad2deg_sparse_csr + tags: pointwise + +- func: rad2deg_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + dispatch: + CompositeExplicitAutograd: rad2deg_ + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: rad2deg_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: rad2deg_sparse_csr_ + tags: pointwise + +- func: rad2deg.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: rad2deg_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: rad2deg_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: rad2deg_sparse_csr_out + tags: pointwise + +- func: deg2rad(Tensor self) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: deg2rad + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: deg2rad_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: deg2rad_sparse_csr + tags: pointwise + +- func: deg2rad_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + dispatch: + CompositeExplicitAutograd: deg2rad_ + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: deg2rad_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: deg2rad_sparse_csr_ + tags: pointwise + +- func: deg2rad.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: deg2rad_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: deg2rad_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: deg2rad_sparse_csr_out + tags: pointwise + +- func: scalar_tensor(Scalar s, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: scalar_tensor + autogen: scalar_tensor.out + tags: core + +- func: rand(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + tags: [core, nondeterministic_seeded] + dispatch: + CompositeExplicitAutograd: rand + +- func: rand.generator(SymInt[] size, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: rand + +- func: rand.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!) + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: rand_out + +- func: rand.generator_out(SymInt[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!) + tags: nondeterministic_seeded + +- func: rand_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd: rand_like + autogen: rand_like.out + +- func: rand_like.generator(Tensor self, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: rand_like + autogen: rand_like.generator_out + +- func: randint(SymInt high, SymInt[] size, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: randint + +- func: randint.generator(SymInt high, SymInt[] size, *, Generator? generator, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: randint + +- func: randint.low(SymInt low, SymInt high, SymInt[] size, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: randint + +- func: randint.low_generator(SymInt low, SymInt high, SymInt[] size, *, Generator? generator, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: randint + +- func: randint.out(SymInt high, SymInt[] size, *, Tensor(a!) out) -> Tensor(a!) + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: randint_out + +- func: randint.generator_out(SymInt high, SymInt[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!) + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: randint_out + +- func: randint.low_out(SymInt low, SymInt high, SymInt[] size, *, Tensor(a!) out) -> Tensor(a!) + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: randint_out + +- func: randint.low_generator_out(SymInt low, SymInt high, SymInt[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!) + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: randint_out + +- func: randint_like(Tensor self, SymInt high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd: randint_like + autogen: randint_like.out + +- func: randint_like.generator(Tensor self, SymInt high, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd: randint_like + autogen: randint_like.generator_out + +- func: randint_like.Tensor(Tensor self, Tensor high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd: randint_like + autogen: randint_like.Tensor_out + +- func: randint_like.Tensor_generator(Tensor self, Tensor high, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd: randint_like + autogen: randint_like.Tensor_generator_out + +- func: randint_like.low_dtype(Tensor self, SymInt low, SymInt high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd: randint_like + autogen: randint_like.low_dtype_out + +- func: randint_like.low_generator_dtype(Tensor self, SymInt low, SymInt high, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd: randint_like + autogen: randint_like.low_generator_dtype_out + +- func: randn(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + tags: [core, nondeterministic_seeded] + dispatch: + CompositeExplicitAutograd: randn + +- func: randn.generator(SymInt[] size, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: randn + +- func: randn.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!) + tags: nondeterministic_seeded + +- func: randn.generator_out(SymInt[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!) + tags: nondeterministic_seeded + +- func: randn_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd, CompositeImplicitAutogradNestedTensor: randn_like + autogen: randn_like.out + +- func: randn_like.generator(Tensor self, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd, CompositeImplicitAutogradNestedTensor: randn_like + autogen: randn_like.generator_out + +- func: randperm(SymInt n, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + tags: [core, nondeterministic_seeded] + dispatch: + CompositeExplicitAutograd: randperm + +- func: randperm.generator(SymInt n, *, Generator? generator, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: randperm + +- func: randperm.out(SymInt n, *, Tensor(a!) out) -> Tensor(a!) + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: randperm_out + +- func: randperm.generator_out(SymInt n, *, Generator? generator, Tensor(a!) out) -> Tensor(a!) + tags: nondeterministic_seeded + dispatch: + CPU: randperm_out_cpu + CUDA: randperm_out_cuda + MPS: randperm_out_mps + XPU: randperm_out_xpu + +- func: range.step(Scalar start, Scalar end, Scalar step=1, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: range + +- func: range(Scalar start, Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: range + +- func: range.out_(Scalar start, Scalar end, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: range_out_no_step + +- func: range.out(Scalar start, Scalar end, Scalar step=1, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, Meta: range_out + CUDA: range_cuda_out + MPS: range_mps_out + XPU: range_xpu_out + cpp_no_default_args: ['step'] + +- func: ravel(Tensor(a) self) -> Tensor(a) + variants: function, method + +- func: reciprocal(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: reciprocal.out + variants: function, method + tags: [core, pointwise] + +- func: reciprocal_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: reciprocal.out + variants: function, method + tags: pointwise + +- func: reciprocal.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: reciprocal_out + tags: pointwise + +- func: neg(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: neg.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: neg_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: neg_sparse_csr + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_neg + tags: [core, pointwise] + +- func: neg_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: neg.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: neg_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: neg_sparse_csr_ + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_neg_ + tags: pointwise + +- func: neg.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: neg_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: neg_out_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: neg_sparse_csr_out + tags: pointwise +# Alias for neg + +- func: negative(Tensor self) -> Tensor + variants: function, method + +- func: negative_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + +- func: negative.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + +- func: repeat(Tensor self, SymInt[] repeats) -> Tensor + variants: method # This is method-only to match the previous tensor API. In the future we could make this a function too. + dispatch: + CompositeExplicitAutograd: repeat + MPS: repeat_mps + autogen: repeat.out + tags: core + +- func: repeat_interleave.Tensor(Tensor repeats, *, SymInt? output_size=None) -> Tensor + variants: function + dispatch: + CPU: repeat_interleave_cpu + CUDA: repeat_interleave_cuda + MPS: repeat_interleave_mps + XPU: repeat_interleave_xpu + tags: dynamic_output_shape + autogen: repeat_interleave.Tensor_out + +- func: repeat_interleave.self_Tensor(Tensor self, Tensor repeats, int? dim=None, *, SymInt? output_size=None) -> Tensor + variants: function, method + dispatch: + CompositeImplicitAutograd: repeat_interleave_symint + +- func: repeat_interleave.self_int(Tensor self, SymInt repeats, int? dim=None, *, SymInt? output_size=None) -> Tensor + variants: function, method + dispatch: + CompositeImplicitAutograd: repeat_interleave_symint + +- func: reshape(Tensor(a) self, SymInt[] shape) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeImplicitAutograd: reshape_symint + CompositeImplicitAutogradNestedTensor: reshape_nested_symint + +- func: _reshape_copy(Tensor self, SymInt[] size) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: _reshape_copy_symint + +# NOTE [ _reshape_alias ] is meant to be used in the implementation of reshape. +# They are not user-facing, hence the leading underscore. Please don't use it +# anywhere else. +- func: _reshape_alias(Tensor(a) self, SymInt[] size, SymInt[] stride) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CPU, CUDA, Meta, QuantizedCPU, QuantizedCUDA, MPS, MTIA, XPU: _reshape_alias + ZeroTensor: _reshape_alias_symint + # We don't need to support mkldnn since this is handled explicitly by the reshape operator. + +- func: _mkldnn_reshape(Tensor self, int[] shape) -> Tensor + device_check: NoCheck + device_guard: False + dispatch: + MkldnnCPU: mkldnn_reshape + autogen: _mkldnn_reshape.out + +- func: reshape_as(Tensor(a) self, Tensor other) -> Tensor(a) + variants: method + device_check: NoCheck + device_guard: False + dispatch: + CompositeImplicitAutograd: reshape_as + CompositeImplicitAutogradNestedTensor: reshape_as_nested + +- func: round(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: round.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: round_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: round_sparse_csr + tags: [core, pointwise] + +- func: round_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: round.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: round_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: round_sparse_csr_ + tags: pointwise + +- func: round.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: round_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: round_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: round_sparse_csr_out + tags: pointwise + +- func: round.decimals(Tensor self, *, int decimals) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: round.decimals_out + variants: function, method + tags: pointwise + +- func: round_.decimals(Tensor(a!) self, *, int decimals) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: round.decimals_out + variants: function, method + tags: pointwise + +- func: round.decimals_out(Tensor self, *, int decimals, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: round_decimals_out + tags: pointwise + +- func: rrelu(Tensor self, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor + device_check: NoCheck # TensorIterator + tags: [pointwise, nondeterministic_seeded] + +- func: rrelu_(Tensor(a!) self, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor(a!) + tags: nondeterministic_seeded + device_check: NoCheck # TensorIterator + +- func: relu(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CPU, CUDA, XPU: relu + MPS: relu_mps + MTIA: relu_mtia + MkldnnCPU: mkldnn_relu + QuantizedCPU: relu_quantized_cpu + QuantizedCUDA: relu_quantized_cuda + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_relu + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: relu_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: relu_sparse_csr + tags: [core, pointwise] + +- func: relu_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CPU, CUDA, XPU: relu_ + MPS: relu_mps_ + MTIA: relu_mtia_ + MkldnnCPU: mkldnn_relu_ + QuantizedCPU: relu_quantized_cpu_ + QuantizedCUDA: relu_quantized_cuda_ + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_relu_ + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: relu_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: relu_sparse_csr_ + autogen: relu.out + tags: pointwise + +- func: relu6(Tensor self) -> Tensor + python_module: nn + tags: pointwise + +- func: relu6_(Tensor(a!) self) -> Tensor(a!) + python_module: nn + +- func: prelu(Tensor self, Tensor weight) -> Tensor + variants: function, method + autogen: prelu.out + +- func: _prelu_kernel(Tensor self, Tensor weight) -> Tensor + dispatch: + CPU, CUDA, XPU: _prelu_kernel + QuantizedCPU: _prelu_kernel_quantized_cpu + MkldnnCPU: mkldnn_prelu + MPS: prelu_mps + +- func: _prelu_kernel_backward(Tensor grad_output, Tensor self, Tensor weight) -> (Tensor, Tensor) + dispatch: + CPU, CUDA, XPU: _prelu_kernel_backward + MkldnnCPU: mkldnn_prelu_backward + MPS: prelu_backward_mps + +- func: gelu.out(Tensor self, *, str approximate='none', Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + CPU: gelu_out_cpu + CUDA: gelu_out_cuda + MPS: gelu_out_mps + XPU: gelu_out_xpu + +- func: gelu_(Tensor(a!) self, *, str approximate='none') -> Tensor(a!) + structured_delegate: gelu.out + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + QuantizedCPU: gelu_quantized_cpu_ + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_gelu_ + +- func: gelu(Tensor self, *, str approximate='none') -> Tensor + structured_delegate: gelu.out + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + MkldnnCPU: mkldnn_gelu + QuantizedCPU: gelu_quantized_cpu + QuantizedCUDA: gelu_quantized_cuda + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_gelu + tags: [core, pointwise] + +- func: gelu_backward.grad_input(Tensor grad_output, Tensor self, *, str approximate='none', Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: nn + dispatch: + CPU: gelu_backward_out_cpu + CUDA: gelu_backward_out_cuda + MPS: gelu_backward_out_mps + XPU: gelu_backward_out_xpu + +- func: gelu_backward(Tensor grad_output, Tensor self, *, str approximate='none') -> Tensor + structured_delegate: gelu_backward.grad_input + python_module: nn + dispatch: + MkldnnCPU: mkldnn_gelu_backward + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: gelu_backwards_nested + tags: pointwise + +- func: infinitely_differentiable_gelu_backward(Tensor grad, Tensor self) -> Tensor + variants: function + python_module: nn + device_check: NoCheck + device_guard: False + +- func: hardshrink.out(Tensor self, Scalar lambd=0.5, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, XPU: hardshrink_out + +- func: hardshrink(Tensor self, Scalar lambd=0.5) -> Tensor + structured_delegate: hardshrink.out + device_check: NoCheck # TensorIterator + variants: function, method + tags: pointwise + +- func: hardshrink_backward.grad_input(Tensor grad_out, Tensor self, Scalar lambd, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: hardshrink_backward_out + +- func: hardshrink_backward(Tensor grad_out, Tensor self, Scalar lambd) -> Tensor + structured_delegate: hardshrink_backward.grad_input + variants: function, method + +- func: rsqrt(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: rsqrt.out + variants: function, method + tags: [core, pointwise] + +- func: rsqrt_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: rsqrt.out + variants: function, method + tags: pointwise + +- func: rsqrt.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: rsqrt_out + tags: pointwise + +- func: select.int(Tensor(a) self, int dim, SymInt index) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: select_symint + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: select_sparse_csr + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: select_nested + tags: core + +- func: select_backward(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt index) -> Tensor + variants: function + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutogradNonFunctional: select_backward_symint + autogen: select_backward.out + +- func: _nested_select_backward(Tensor grad_output, Tensor self, int dim, SymInt index) -> Tensor + variants: function + device_check: NoCheck + device_guard: False + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: _nested_select_backward_symint + +- func: selu(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + tags: pointwise + +- func: selu_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + tags: pointwise + +- func: celu(Tensor self, Scalar alpha=1.0) -> Tensor + device_check: NoCheck # TensorIterator + dispatch: + CompositeExplicitAutograd: celu + tags: pointwise + +- func: celu_(Tensor(a!) self, Scalar alpha=1.0) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CompositeExplicitAutograd: celu_ + autogen: celu.out + tags: pointwise + +- func: silu(Tensor self) -> Tensor + structured_delegate: silu.out + python_module: nn + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_silu + tags: pointwise + +- func: silu_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: silu.out + python_module: nn + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_silu_ + tags: pointwise + +- func: silu.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: nn + dispatch: + CPU, CUDA, MPS, MTIA, XPU: silu_out + tags: pointwise + +- func: silu_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: silu_backward_out + tags: pointwise + +- func: silu_backward(Tensor grad_output, Tensor self) -> Tensor + structured_delegate: silu_backward.grad_input + python_module: nn + dispatch: + CompositeImplicitAutograd: math_silu_backward + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: silu_backward_nested + tags: pointwise + +- func: mish(Tensor self) -> Tensor + structured_delegate: mish.out + python_module: nn + tags: pointwise + +- func: mish_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: mish.out + python_module: nn + +- func: mish.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: mish_out + +- func: mish_backward(Tensor grad_output, Tensor self) -> Tensor + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: mish_backward + CompositeImplicitAutograd: math_mish_backward + +- func: sigmoid(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: sigmoid.out + variants: function, method + dispatch: + QuantizedCPU: sigmoid_quantized_cpu + MkldnnCPU: mkldnn_sigmoid + tags: [core, pointwise] + +- func: sigmoid_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: sigmoid.out + variants: function, method + dispatch: + MkldnnCPU: mkldnn_sigmoid_ + tags: pointwise + +- func: sigmoid.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: sigmoid_out + tags: pointwise + +- func: logit(Tensor self, float? eps=None) -> Tensor + variants: function, method + dispatch: + CPU, CUDA, MTIA, XPU: logit + MPS: logit_mps + tags: pointwise + +- func: logit_(Tensor(a!) self, float? eps=None) -> Tensor(a!) + variants: function, method + dispatch: + CPU, CUDA, XPU: logit_ + tags: pointwise + +- func: logit.out(Tensor self, float? eps=None, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, XPU: logit_out + MPS: logit_out_mps + tags: pointwise + +- func: sin(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: sin.out + variants: function, method + dispatch: + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sin_sparse_csr + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sin_sparse + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_sin + tags: [core, pointwise] + +- func: sin_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: sin.out + variants: function, method + dispatch: + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sin_sparse_csr_ + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sin_sparse_ + tags: pointwise + +- func: sin.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: sin_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sin_sparse_csr_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sin_sparse_out + tags: pointwise + +- func: sinc(Tensor self) -> Tensor + structured_delegate: sinc.out + variants: function, method + tags: pointwise + +- func: sinc_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: sinc.out + variants: function, method + tags: pointwise + +- func: sinc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: sinc_out + tags: pointwise + +- func: sinh(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: sinh.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sinh_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sinh_sparse_csr + tags: [core, pointwise] + +- func: sinh_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: sinh.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sinh_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sinh_sparse_csr_ + tags: pointwise + +- func: sinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: sinh_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sinh_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sinh_sparse_csr_out + +# Returns a copy of this `Variable` that is detached from its autograd graph. +# This method is OK to call if the `Variable` is a view. +# +# NOTE: Previously, if we change the tensor metadata (e.g. sizes / strides / +# storage / storage_offset) of a tensor created from `detach()`, those metadata +# in the original tensor will also be updated. However, the new behavior is that +# those metadata changes to the detached tensor will not update the original tensor +# anymore, and in the `detach()` function we need to set `allow_tensor_metadata_change_` +# to false to make such changes explicitly illegal, in order to prevent users from +# changing metadata of the detached tensor and expecting the original tensor to also +# be updated. + tags: pointwise +- func: detach(Tensor(a) self) -> Tensor(a) + variants: function, method + dispatch: + CompositeExplicitAutograd: detach + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: detach + +# Like `detach()`, but modifies this `Variable` in-place. This method may +# only be called on non-view `Variable`s. You can use `is_view()` to check +# this. If this `Variable` is a view, throws an `std::runtime_error()`. +- func: detach_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + tags: inplace_view + dispatch: + CompositeExplicitAutograd: detach_ + +- func: size.int(Tensor self, int dim) -> int + variants: function + device_check: NoCheck + device_guard: False + manual_cpp_binding: True + +- func: sym_size.int(Tensor self, int dim) -> SymInt + variants: function + device_check: NoCheck + device_guard: False + tags: core + manual_cpp_binding: True + +- func: sym_is_contiguous(Tensor self, MemoryFormat memory_format=contiguous_format) -> SymBool + variants: function + device_check: NoCheck + device_guard: False + tags: core + manual_cpp_binding: True + +- func: sym_numel(Tensor self) -> SymInt + variants: function + device_check: NoCheck + device_guard: False + tags: core + manual_cpp_binding: True + +- func: sym_storage_offset(Tensor self) -> SymInt + variants: function + device_check: NoCheck + device_guard: False + tags: core + manual_cpp_binding: True + +- func: slice.Tensor(Tensor(a) self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: slice + tags: core + +# NOTE: The implementation of split_with_sizes bypasses the dispatcher to call this; undo +# that if adding specific implementations here! + +- func: slice_backward(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt start, SymInt end, SymInt step) -> Tensor + variants: function + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: slice_backward + autogen: slice_backward.out + +# NB: This op exists to back the implementation of reverse view_funcs for various views (chunk, +# slice.Tensor, split_with_sizes, et al.). Currently, these are only used during fake-ification +# of PT2 graph input subclass instances that are views. This means: +# * This op shouldn't really show up in eager mode (so e.g. XLA shouldn't have to implement it) +# * This op shouldn't show up in a PT2 graph (so a PT2 backend shouldn't have to implement it) +# * A subclass will have to implement this to work in PT2 if a subclass view is used as a graph +# input AND the view utilizes this op in its inverse. The idea is that slice_inverse() is +# easier to implement for a subclass than as_strided() +- func: slice_inverse(Tensor(a) self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: slice_inverse_symint + +- func: slice_scatter(Tensor self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutogradNonFunctional: slice_scatter + autogen: slice_scatter.out + tags: [core, view_copy] + +- func: select_scatter(Tensor self, Tensor src, int dim, SymInt index) -> Tensor + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutogradNonFunctional: select_scatter_symint + autogen: select_scatter.out + tags: core + +- func: diagonal_scatter(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1) -> Tensor + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutogradNonFunctional: diagonal_scatter + autogen: diagonal_scatter.out + +- func: as_strided_scatter(Tensor self, Tensor src, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutogradNonFunctional: as_strided_scatter_symint + autogen: as_strided_scatter.out + +- func: smm(Tensor self, Tensor mat2) -> Tensor + variants: function, method + +# softmax allows positional dtype, unlike most operators, because kwonly is BC-breaking when loading jit models. +- func: softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor + variants: function, method + +- func: softmax.int_out(Tensor self, int dim, ScalarType? dtype=None, *, Tensor(a!) out) -> Tensor(a!) + variants: function + dispatch: + CompositeExplicitAutograd: softmax_out + +- func: _softmax(Tensor self, int dim, bool half_to_float) -> Tensor + structured_delegate: _softmax.out + dispatch: + MkldnnCPU: mkldnn_softmax + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: softmax_nested + tags: core + +- func: _softmax.out(Tensor self, int dim, bool half_to_float, *, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU: softmax_cpu_out + CUDA: softmax_cuda_out + MPS: softmax_mps_out + XPU: softmax_xpu_out + +- func: _softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor + structured_delegate: _softmax_backward_data.out + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: nested_softmax_backward + +- func: _softmax_backward_data.out(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + dispatch: + CPU: softmax_backward_cpu_out + CUDA: softmax_backward_cuda_out + MPS: softmax_backward_mps_out + XPU: softmax_backward_xpu_out + +- func: unsafe_split.Tensor(Tensor self, SymInt split_size, int dim=0) -> Tensor[] + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: unsafe_split + autogen: unsafe_split.Tensor_out + +- func: split.Tensor(Tensor(a -> *) self, SymInt split_size, int dim=0) -> Tensor(a)[] + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: split + +- func: split.sizes(Tensor(a -> *) self, SymInt[] split_size, int dim=0) -> Tensor(a)[] + variants: function, method + device_guard: False + dispatch: + CompositeImplicitAutograd: split_symint + +- func: unsafe_split_with_sizes(Tensor self, SymInt[] split_sizes, int dim=0) -> Tensor[] + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: unsafe_split_with_sizes + autogen: unsafe_split_with_sizes.out + +- func: split_with_sizes(Tensor(a -> *) self, SymInt[] split_sizes, int dim=0) -> Tensor(a)[] + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: split_with_sizes + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: split_with_sizes_nested + tags: core + +- func: hsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[] + variants: function, method + +- func: hsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[] + variants: function, method + +- func: vsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[] + variants: function, method + +- func: vsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[] + variants: function, method + +- func: dsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[] + variants: function, method + +- func: dsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[] + variants: function, method + +- func: squeeze(Tensor(a) self) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: squeeze + QuantizedCPU, QuantizedCUDA: squeeze_quantized + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: squeeze_nested + +- func: squeeze.dim(Tensor(a) self, int dim) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: squeeze + QuantizedCPU, QuantizedCUDA: squeeze_quantized + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: squeeze_dim_nested + tags: core + +- func: squeeze.dims(Tensor(a) self, int[] dim) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: squeeze + QuantizedCPU, QuantizedCUDA: squeeze_quantized + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: squeeze_dim_nested + tags: core + +- func: squeeze_(Tensor(a!) self) -> Tensor(a!) + variants: method + device_check: NoCheck + device_guard: False + tags: inplace_view + dispatch: + CompositeExplicitAutograd: squeeze_ + +- func: squeeze_.dim(Tensor(a!) self, int dim) -> Tensor(a!) + variants: method + device_check: NoCheck + device_guard: False + tags: inplace_view + dispatch: + CompositeExplicitAutograd: squeeze_ + +- func: squeeze_.dims(Tensor(a!) self, int[] dim) -> Tensor(a!) + variants: method + device_check: NoCheck + device_guard: False + tags: inplace_view + dispatch: + CompositeExplicitAutograd: squeeze_ + +- func: sspaddmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + variants: function, method + +- func: sspaddmm.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU: _sspaddmm_out_only_sparse + CUDA: _sspaddmm_out_only_sparse_cuda + SparseCPU: _sspaddmm_out_cpu + SparseCUDA: _sspaddmm_out_cuda + +- func: _chunk_cat(Tensor[] tensors, int dim, int num_chunks) -> Tensor + dispatch: + CompositeExplicitAutograd: _chunk_cat + CUDA: _chunk_cat_cuda + XPU: _chunk_cat_xpu + +- func: _chunk_cat.out(Tensor[] tensors, int dim, int num_chunks, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: _chunk_cat_out + CUDA: _chunk_cat_out_cuda + XPU: _chunk_cat_out_xpu + +- func: stack(Tensor[] tensors, int dim=0) -> Tensor + dispatch: + CompositeExplicitAutograd: stack + Meta: stack_meta + +- func: stack.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: stack_out + +- func: _stack(Tensor[] tensors, int dim=0) -> Tensor + dispatch: # match the backends supported by _cat + CPU: _stack_cpu + CompositeExplicitAutograd: _stack + +- func: _stack.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!) + dispatch: # match the backends supported by _cat_out + CPU: _stack_out_cpu + CompositeExplicitAutograd: _stack_out + +- func: hstack(Tensor[] tensors) -> Tensor + +- func: hstack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) + +- func: vstack(Tensor[] tensors) -> Tensor + +- func: vstack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) + +- func: dstack(Tensor[] tensors) -> Tensor + +- func: dstack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) + +# Overload without center & pad mode, needed for forward-compatibility +- func: stft(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool normalized=False, bool? onesided=None, bool? return_complex=None, bool? align_to_window=None) -> Tensor + variants: function, method + cpp_no_default_args: ['hop_length', 'win_length', 'window', 'normalized'] + +- func: stft.center(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool center=True, str pad_mode="reflect", bool normalized=False, bool? onesided=None, bool? return_complex=None, bool? align_to_window=None) -> Tensor + variants: function, method + +- func: istft(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool center=True, bool normalized=False, bool? onesided=None, int? length=None, bool return_complex=False) -> Tensor + variants: function, method + +- func: stride.int(Tensor self, int dim) -> int + variants: function + device_check: NoCheck + device_guard: False + manual_cpp_binding: True + +- func: sym_stride.int(Tensor self, int dim) -> SymInt + variants: function + device_check: NoCheck + device_guard: False + tags: core + manual_cpp_binding: True + +- func: sum(Tensor self, *, ScalarType? dtype=None) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: sum + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: sum_coo + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sum_csr + autogen: sum.out + tags: reduction + +- func: sum.dim_IntList(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + # TODO: Align the signature of sum.dim_IntList and _sparse_csr_sum.dim_dtype + structured_delegate: sum.IntList_out + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + NestedTensorCPU: NestedTensor_sum_dim_CPU + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sum_sparse_coo + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sum_sparse_compressed + tags: [core, reduction] + +- func: sum.IntList_out(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + structured: True + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, XPU: sum_out + tags: reduction + +- func: _nested_sum_backward(Tensor grad, Tensor self, int[1]? dim, bool keepdim=False) -> Tensor + dispatch: + NestedTensorCPU: _nested_sum_backward_cpu + +- func: nansum(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + variants: function, method + dispatch: + CPU, CUDA, MPS, XPU: nansum + tags: reduction + +- func: nansum.out(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: nansum_out + tags: reduction + +- func: hash_tensor(Tensor self, int[1] dim=[], *, bool keepdim=False, int mode=0) -> Tensor + variants: function, method + structured_delegate: hash_tensor.out + +- func: hash_tensor.out(Tensor self, int[1] dim=[], *, bool keepdim=False, int mode=0, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU, CUDA: hash_tensor_out + +- func: sum_to_size(Tensor self, SymInt[] size) -> Tensor + variants: method + device_check: NoCheck + device_guard: False + dispatch: + CompositeImplicitAutograd: sum_to_size_symint + +- func: sqrt(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: sqrt.out + variants: function, method + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_sqrt + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sqrt_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sqrt_sparse_csr + tags: [core, pointwise] + +- func: sqrt_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: sqrt.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sqrt_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sqrt_sparse_csr_ + tags: pointwise + +- func: sqrt.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: sqrt_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sqrt_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sqrt_sparse_csr_out + tags: pointwise + +- func: square(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + tags: pointwise + +- func: square_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + tags: pointwise + +- func: square.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + tags: pointwise + +- func: std(Tensor self, bool unbiased=True) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + cpp_no_default_args: ["unbiased"] + tags: reduction + +- func: std.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + cpp_no_default_args: ["unbiased"] + tags: reduction + +- func: std.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CPU, CUDA, XPU: std + MPS: std_mps + QuantizedCPU: std_quantized_cpu + tags: reduction + +- func: std_mean(Tensor self, bool unbiased=True) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator + variants: function + cpp_no_default_args: ["unbiased"] + tags: reduction + +- func: std_mean.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator + variants: function + cpp_no_default_args: ["unbiased"] + tags: reduction + +- func: std_mean.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CPU, CUDA, XPU: std_mean + MPS: std_mean_mps + autogen: std_mean.correction_out + tags: reduction + +- func: std.out(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + cpp_no_default_args: ["unbiased"] + tags: reduction + +- func: std.correction_out(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, XPU: std_out + QuantizedCPU: std_out_quantized_cpu + tags: reduction + +- func: prod(Tensor self, *, ScalarType? dtype=None) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CPU, CUDA, XPU: prod + MPS: prod_mps + autogen: prod.out + tags: [core, reduction] + +- func: prod.dim_int(Tensor self, int dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + structured_delegate: prod.int_out + device_check: NoCheck # TensorIterator + variants: function, method + tags: [core, reduction] + +- func: prod.int_out(Tensor self, int dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + structured: True + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, XPU: prod_out + MPS: prod_out_mps + tags: reduction + +- func: t(Tensor(a) self) -> Tensor(a) + device_check: NoCheck + device_guard: False + variants: function, method + dispatch: + CompositeExplicitAutograd: t + +- func: t_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck + device_guard: False + variants: method + tags: inplace_view + dispatch: + CompositeExplicitAutograd: t_ + +- func: tan(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: tan.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: tan_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: tan_sparse_csr + tags: [core, pointwise] + +- func: tan_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: tan.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: tan_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: tan_sparse_csr_ + tags: pointwise + +- func: tan.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: tan_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: tan_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: tan_sparse_csr_out + tags: pointwise + +- func: tanh(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: tanh.out + variants: function, method + dispatch: + QuantizedCPU: tanh_quantized_cpu + MkldnnCPU: mkldnn_tanh + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: tanh_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: tanh_sparse_csr + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_tanh + tags: [core, pointwise] + +- func: tanh_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: tanh.out + variants: function, method + dispatch: + MkldnnCPU: mkldnn_tanh_ + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: tanh_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: tanh_sparse_csr_ + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_tanh_ + tags: pointwise + +- func: tanh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: tanh_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: tanh_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: tanh_sparse_csr_out + tags: pointwise + +- func: tensordot(Tensor self, Tensor other, int[] dims_self, int[] dims_other) -> Tensor + variants: function + +- func: tensordot.out(Tensor self, Tensor other, int[] dims_self, int[] dims_other, *, Tensor(a!) out) -> Tensor(a!) + variants: function + +# TODO: namespace threshold in 'nn' +- func: threshold(Tensor self, Scalar threshold, Scalar value) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + structured_delegate: threshold.out + dispatch: + QuantizedCPU: threshold_quantized_cpu + tags: pointwise + +- func: threshold_(Tensor(a!) self, Scalar threshold, Scalar value) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function + structured_delegate: threshold.out + +- func: threshold.out(Tensor self, Scalar threshold, Scalar value, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, XPU: threshold_out + MPS: threshold_out_mps + +- func: threshold_backward.grad_input(Tensor grad_output, Tensor self, Scalar threshold, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, XPU: threshold_backward_out + MPS: threshold_backward_out_mps + SparseCPU, SparseCUDA, SparseXPU: threshold_backward_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: threshold_backward_sparse_compressed_out + +- func: threshold_backward(Tensor grad_output, Tensor self, Scalar threshold) -> Tensor + variants: function + structured_delegate: threshold_backward.grad_input + dispatch: + MkldnnCPU: mkldnn_relu_backward + SparseCPU, SparseCUDA, SparseXPU: threshold_backward_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: threshold_backward_sparse_compressed + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: threshold_backwards_nested + tags: pointwise + +- func: tile(Tensor self, SymInt[] dims) -> Tensor + variants: function, method + dispatch: + CompositeImplicitAutograd: tile_symint + +- func: transpose.int(Tensor(a) self, int dim0, int dim1) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: transpose + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: transpose_nested + +- func: _mkldnn_transpose(Tensor self, int dim0, int dim1) -> Tensor + device_check: NoCheck + device_guard: False + dispatch: + MkldnnCPU: mkldnn_transpose + +- func: transpose_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!) + variants: method + device_check: NoCheck + device_guard: False + tags: inplace_view + dispatch: + CompositeExplicitAutograd: transpose_ + +- func: _mkldnn_transpose_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!) + device_check: NoCheck + device_guard: False + dispatch: + MkldnnCPU: mkldnn_transpose_ + autogen: _mkldnn_transpose.out + +- func: one_hot(Tensor self, int num_classes=-1) -> Tensor + python_module: nn + variants: function + tags: dynamic_output_shape + +- func: flip(Tensor self, int[] dims) -> Tensor + variants: function, method + dispatch: + CPU, QuantizedCPU, CUDA, QuantizedCUDA, XPU: flip + MPS: flip_mps + autogen: flip.out + tags: core + +- func: fliplr(Tensor self) -> Tensor + variants: function, method + +- func: flipud(Tensor self) -> Tensor + variants: function, method + +- func: roll(Tensor self, SymInt[1] shifts, int[1] dims=[]) -> Tensor + variants: function, method + dispatch: + CPU, MPS: roll + CUDA: roll_cuda + XPU: roll_xpu + autogen: roll.out + +# default int[] value [0,1] should not add space after comma, since codegen parser uses ', ' to split args + +- func: rot90(Tensor self, int k=1, int[] dims=[0,1]) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: rot90 + autogen: rot90.out + +- func: trapezoid.x(Tensor y, Tensor x, *, int dim=-1) -> Tensor + +- func: trapezoid.dx(Tensor y, *, Scalar dx=1, int dim=-1) -> Tensor + +- func: trapz.x(Tensor y, Tensor x, *, int dim=-1) -> Tensor + +- func: trapz.dx(Tensor y, *, float dx=1, int dim=-1) -> Tensor + +# Fused implementation detail for transformers. Adds in-projection bias to QKV and divides Q by sqrt(D/num_heads). +- func: _transform_bias_rescale_qkv(Tensor qkv, Tensor qkv_bias, int num_heads) -> (Tensor, Tensor, Tensor) + dispatch: + CPU, NestedTensorCPU: transform_bias_rescale_qkv_cpu + CUDA, NestedTensorCUDA: transform_bias_rescale_qkv_cuda + XPU, NestedTensorXPU: transform_bias_rescale_qkv_xpu + autogen: _transform_bias_rescale_qkv.out + +- func: _nested_tensor_from_mask(Tensor t, Tensor mask, bool mask_check=True) -> Tensor + dispatch: + CPU, CUDA, XPU: NestedTensor_nested_tensor_from_mask + autogen: _nested_tensor_from_mask.out + +- func: _nested_tensor_from_mask_left_aligned(Tensor t, Tensor mask) -> bool + dispatch: + CPU, CUDA, XPU: NestedTensor_nested_tensor_from_mask_left_aligned + +- func: _nested_from_padded(Tensor padded, Tensor cpu_nested_shape_example, bool fuse_transform_0213=False) -> Tensor + device_check: NoCheck # cpu_nested_shape_example will always be on CPU + dispatch: + CPU: nested_from_padded_generic + CUDA: nested_from_padded_cuda + XPU: nested_from_padded_xpu + autogen: _nested_from_padded.out + +# These private functions are temporary. They will be updated/deleted when nested tensors switch to using SymInts for their metadata representation +- func: _nested_tensor_size(Tensor self) -> Tensor + variants: method + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: _nested_tensor_size + autogen: _nested_tensor_size.out + +- func: _nested_tensor_strides(Tensor self) -> Tensor + variants: method + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: _nested_tensor_strides + autogen: _nested_tensor_strides.out + +- func: _nested_tensor_storage_offsets(Tensor self) -> Tensor + variants: method + dispatch: + NestedTensorCPU, NestedTensorCUDA, NestedTensorMeta, NestedTensorXPU: _nested_tensor_storage_offsets + autogen: _nested_tensor_storage_offsets.out + +# _nested_from_padded is not usable from Python, so +# _nested_from_padded_and_nested_example is available for testing. +- func: _nested_from_padded_and_nested_example(Tensor padded, Tensor nt_example) -> Tensor + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_from_padded_and_nested_example + autogen: _nested_from_padded_and_nested_example.out + +# The input arguments' types to this functions are temporary. When nested tensors switch to using SymInts for their metadata representation +# this will need to be updated +- func: _nested_view_from_buffer(Tensor(a) self, Tensor nested_size, Tensor nested_strides, Tensor offsets) -> Tensor(a) + variants: function + device_check: NoCheck + dispatch: + CPU, CUDA, XPU: _nested_view_from_buffer + +- func: _nested_view_from_buffer_copy(Tensor self, Tensor nested_size, Tensor nested_strides, Tensor offsets) -> Tensor + variants: function + device_check: NoCheck + tags: view_copy + dispatch: + CompositeExplicitAutogradNonFunctional: _nested_view_from_buffer_copy + autogen: _nested_view_from_buffer_copy.out + +- func: _nested_view_from_jagged(Tensor(a) self, Tensor offsets, Tensor dummy, Tensor? lengths=None, int ragged_idx=1, Tensor? min_seqlen=None, Tensor? max_seqlen=None) -> Tensor(a) + variants: function + device_check: NoCheck + dispatch: {} + +- func: _nested_view_from_jagged_copy(Tensor self, Tensor offsets, Tensor dummy, Tensor? lengths=None, int ragged_idx=1, Tensor? min_seqlen=None, Tensor? max_seqlen=None) -> Tensor + variants: function + device_check: NoCheck + tags: view_copy + dispatch: + CompositeExplicitAutogradNonFunctional: _nested_view_from_jagged_copy + autogen: _nested_view_from_jagged_copy.out + +- func: _nested_get_values(Tensor(a) self) -> Tensor(a) + variants: function + device_check: NoCheck + dispatch: {} + +- func: _nested_get_values_copy(Tensor self) -> Tensor + variants: function + device_check: NoCheck + tags: view_copy + dispatch: + CompositeExplicitAutogradNonFunctional: _nested_get_values_copy + autogen: _nested_get_values_copy.out + +- func: _nested_get_offsets(Tensor self) -> Tensor + variants: function + device_check: NoCheck + dispatch: {} + +# returns undefined Tensor if no lengths present +- func: _nested_get_lengths(Tensor self) -> Tensor + variants: function + device_check: NoCheck + dispatch: {} + +- func: _nested_get_ragged_idx(Tensor self) -> int + variants: function + device_check: NoCheck + dispatch: {} + +- func: _nested_get_min_seqlen(Tensor self) -> Tensor + variants: function + device_check: NoCheck + dispatch: {} + +- func: _nested_get_max_seqlen(Tensor self) -> Tensor + variants: function + device_check: NoCheck + dispatch: {} + +- func: _nested_get_jagged_dummy(Tensor any) -> Tensor + category_override: dummy + dispatch: {} + +- func: _nested_compute_contiguous_strides_offsets(Tensor nested_size) -> (Tensor, Tensor) + variants: function + device_check: NoCheck + dispatch: + CPU, CUDA, XPU: _nested_compute_contiguous_strides_offsets + +- func: _trilinear(Tensor i1, Tensor i2, Tensor i3, int[] expand1, int[] expand2, int[] expand3, int[] sumdim, int unroll_dim=1) -> Tensor + dispatch: + # calls unsqueeze + CompositeExplicitAutogradNonFunctional: _trilinear + autogen: _trilinear.out + +- func: triplet_margin_loss(Tensor anchor, Tensor positive, Tensor negative, float margin=1.0, float p=2, float eps=1e-06, bool swap=False, int reduction=Mean) -> Tensor + +- func: trunc(Tensor self) -> Tensor + structured_delegate: trunc.out + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: trunc_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta, SparseCsrXPU: trunc_sparse_csr + tags: [core, pointwise] + +- func: trunc_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: trunc.out + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: trunc_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta, SparseCsrXPU: trunc_sparse_csr_ + tags: pointwise + +- func: trunc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, XPU: trunc_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: trunc_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta, SparseCsrXPU: trunc_sparse_csr_out + tags: pointwise +# Alias for trunc + +- func: fix(Tensor self) -> Tensor + variants: function, method + +- func: fix_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + +- func: fix.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + +- func: type_as(Tensor self, Tensor other) -> Tensor + variants: method + +- func: _has_compatible_shallow_copy_type(Tensor self, Tensor from) -> bool + variants: function + +- func: _unique(Tensor self, bool sorted=True, bool return_inverse=False) -> (Tensor, Tensor) + variants: function + dispatch: + CPU: _unique_cpu + CUDA: _unique_cuda + MPS: _unique_mps + XPU: _unique_xpu + tags: dynamic_output_shape + autogen: _unique.out + +- func: unique_dim(Tensor self, int dim, bool sorted=True, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor) + variants: function + dispatch: + CPU: unique_dim_cpu + CUDA: unique_dim_cuda + MPS: unique_dim_mps + XPU: unique_dim_xpu + tags: dynamic_output_shape + autogen: unique_dim.out + +- func: unique_consecutive(Tensor self, bool return_inverse=False, bool return_counts=False, int? dim=None) -> (Tensor, Tensor, Tensor) + variants: function + dispatch: + CPU: unique_consecutive_cpu + CUDA: unique_consecutive_cuda + MPS: unique_consecutive_mps + XPU: unique_consecutive_xpu + tags: dynamic_output_shape + autogen: unique_consecutive.out + +- func: unique_dim_consecutive(Tensor self, int dim, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor) + variants: function + dispatch: + CPU: unique_dim_consecutive_cpu + CUDA: unique_dim_consecutive_cuda + MPS: unique_dim_consecutive_mps + XPU: unique_dim_consecutive_xpu + tags: dynamic_output_shape + autogen: unique_dim_consecutive.out + +# _unique and _unique_dim are fragile and modifying them easily cause internal break +# the below operator is a temporary hack for adding return_counts support +# Please don't rely on these two operators, they will be removed soon + +- func: _unique2(Tensor self, bool sorted=True, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor) + variants: function + dispatch: + CPU: _unique2_cpu + CUDA: _unique2_cuda + MPS: _unique2_mps + XPU: _unique2_xpu + tags: dynamic_output_shape + autogen: _unique2.out + +- func: _unsafe_view(Tensor self, SymInt[] size) -> Tensor + dispatch: + CompositeExplicitAutograd: _unsafe_view + autogen: _unsafe_view.out + +- func: unsqueeze(Tensor(a) self, int dim) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: unsqueeze + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: unsqueeze_sparse + QuantizedCPU, QuantizedCUDA: unsqueeze_quantized + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: unsqueeze_nested + tags: core + +- func: unsqueeze_(Tensor(a!) self, int dim) -> Tensor(a!) + variants: method + device_check: NoCheck + device_guard: False + tags: inplace_view + dispatch: + CompositeExplicitAutograd: unsqueeze_ + +- func: vander(Tensor x, int? N=None, bool increasing=False) -> Tensor + +- func: var(Tensor self, bool unbiased=True) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + cpp_no_default_args: ["unbiased"] + tags: reduction + +- func: var.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + tags: [core, reduction] + cpp_no_default_args: ["unbiased"] + +- func: var.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CPU, CUDA, XPU: var + MPS: var_mps + tags: [core, reduction] + +- func: var.out(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + cpp_no_default_args: ["unbiased"] + tags: reduction + +- func: var.correction_out(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, XPU: var_out + tags: reduction + +- func: var_mean(Tensor self, bool unbiased=True) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator + variants: function + cpp_no_default_args: ["unbiased"] + tags: reduction + +- func: var_mean.dim(Tensor self, int[1]? dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator + variants: function + cpp_no_default_args: ["unbiased"] + tags: reduction + +- func: var_mean.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CPU, CUDA, XPU: var_mean + MPS: var_mean_mps + autogen: var_mean.correction_out + tags: reduction + +- func: view_as(Tensor(a) self, Tensor other) -> Tensor(a) + variants: method + device_check: NoCheck + device_guard: False + +- func: where.self(Tensor condition, Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CPU, CUDA, MPS, MTIA, XPU: where + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_where + tags: [core, pointwise] + +- func: where.self_out(Tensor condition, Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: where_self_out + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_where_out + +- func: where.ScalarSelf(Tensor condition, Scalar self, Tensor other) -> Tensor + variants: function + +- func: where.ScalarOther(Tensor condition, Tensor self, Scalar other) -> Tensor + variants: function, method + +- func: where.Scalar(Tensor condition, Scalar self, Scalar other) -> Tensor + variants: function + +- func: where(Tensor condition) -> Tensor[] + device_check: NoCheck # TensorIterator + variants: function + +- func: norm_except_dim(Tensor v, int pow=2, int dim=0) -> Tensor + variants: function + +# VariableType::_weight_norm does not want to be given a gap in the autograd graph, +# so we don't define "dispatch" variants for it. +- func: _weight_norm(Tensor v, Tensor g, int dim=0) -> Tensor + variants: function + +- func: _weight_norm_interface(Tensor v, Tensor g, int dim=0) -> (Tensor, Tensor) + variants: function + dispatch: + CPU: weight_norm_cpu + CUDA: weight_norm_cuda + MPS: weight_norm_mps + XPU: weight_norm_xpu + autogen: _weight_norm_interface.out + +- func: _weight_norm_interface_backward(Tensor grad_w, Tensor saved_v, Tensor saved_g, Tensor saved_norms, int dim) -> (Tensor, Tensor) + variants: function + dispatch: + CPU: weight_norm_backward_cpu + CUDA: weight_norm_backward_cuda + MPS: weight_norm_backward_mps + XPU: weight_norm_backward_xpu + autogen: _weight_norm_interface_backward.out + +- func: _weight_norm_differentiable_backward(Tensor grad_w, Tensor saved_v, Tensor saved_g, Tensor saved_norms, int dim) -> (Tensor, Tensor) + variants: function + +- func: _efficientzerotensor(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CPU: _efficientzerotensor + CUDA: _efficientzerotensor_cuda + MPS: _efficientzerotensor_mps + XPU: _efficientzerotensor_xpu + Meta: _efficientzerotensor_meta_symint + autogen: _efficientzerotensor.out + +- func: zeros(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: zeros_symint + +- func: zeros.out(SymInt[] size, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: zeros_out + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: zeros_sparse_out + +- func: zeros_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + dispatch: + # NB: Although this composite mutates on the inside, it is + # non-differentiable so NonFunctional doesn't apply + CompositeExplicitAutograd, CompositeImplicitAutogradNestedTensor: zeros_like + autogen: zeros_like.out + +- func: _standard_gamma_grad(Tensor self, Tensor output) -> Tensor + variants: function + dispatch: + CPU: _standard_gamma_grad_cpu + CUDA: _standard_gamma_grad_cuda + MPS: _standard_gamma_grad_mps + XPU: _standard_gamma_grad_xpu + autogen: _standard_gamma_grad.out + +- func: _standard_gamma(Tensor self, Generator? generator=None) -> Tensor + variants: function + dispatch: + CPU: _s_gamma_cpu + CUDA: _s_gamma_cuda + MPS: _s_gamma_mps + XPU: _s_gamma_xpu + tags: nondeterministic_seeded + autogen: _standard_gamma.out + +- func: _philox_key_split(Tensor key, int num_splits) -> Tensor + variants: function + dispatch: + CPU: _philox_key_split_cpu + CUDA: _philox_key_split_cuda + +- func: _philox_key_fold_in(Tensor key, int data) -> Tensor + variants: function + dispatch: + CPU: _philox_key_fold_in_cpu + CUDA: _philox_key_fold_in_cuda + +- func: _philox_key_fold_in.Tensor(Tensor key, Tensor data) -> Tensor + variants: function + dispatch: + CPU: _philox_key_fold_in_tensor_cpu + CUDA: _philox_key_fold_in_tensor_cuda + +- func: _philox_normal_(Tensor(a!) self, Tensor key, float mean=0, float std=1) -> Tensor(a!) + variants: function, method + dispatch: + CPU: _philox_normal_cpu_ + CUDA: _philox_normal_cuda_ + autogen: _philox_normal, _philox_normal.out + +- func: _philox_uniform_(Tensor(a!) self, Tensor key, float low=0, float high=1) -> Tensor(a!) + variants: function, method + dispatch: + CPU: _philox_uniform_cpu_ + CUDA: _philox_uniform_cuda_ + autogen: _philox_uniform, _philox_uniform.out + +- func: _dirichlet_grad(Tensor x, Tensor alpha, Tensor total) -> Tensor + dispatch: + CPU: _dirichlet_grad_cpu + CUDA: _dirichlet_grad_cuda + MPS: _dirichlet_grad_mps + XPU: _dirichlet_grad_xpu + autogen: _dirichlet_grad.out + +- func: _sample_dirichlet(Tensor self, Generator? generator=None) -> Tensor + tags: nondeterministic_seeded + variants: function + dispatch: + CPU: _s_dirichlet_cpu + CUDA: _s_dirichlet_cuda + MPS: _s_dirichlet_mps + XPU: _s_dirichlet_xpu + autogen: _sample_dirichlet.out + +- func: poisson(Tensor self, Generator? generator=None) -> Tensor + device_check: NoCheck # TensorIterator + dispatch: + CPU: _s_poisson_cpu + CUDA: _s_poisson_cuda + MPS: _s_poisson_mps + XPU: _s_poisson_xpu + tags: nondeterministic_seeded + autogen: poisson.out + +- func: binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor + device_check: NoCheck # TensorIterator + dispatch: + CPU: _s_binomial_cpu + CUDA: _s_binomial_cuda + XPU: _s_binomial_xpu + MPS: _s_binomial_mps + tags: nondeterministic_seeded + autogen: binomial.out + +# When more variants get ported to native, this dispatch will get more +# complicated + +- func: native_norm(Tensor self, Scalar p=2) -> Tensor + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: norm_sparse + autogen: native_norm.out + +- func: native_norm.ScalarOpt_dim_dtype(Tensor self, Scalar? p, int[1] dim, bool keepdim, ScalarType? dtype) -> Tensor + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: norm_sparse + autogen: native_norm.ScalarOpt_dim_dtype_out + +- func: _batch_norm_with_update(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor, Tensor) + dispatch: + CPU: _batch_norm_with_update_cpu + CUDA: _batch_norm_with_update_cuda + MPS: _batch_norm_with_update_mps + XPU: _batch_norm_with_update_xpu + MkldnnCPU: _batch_norm_with_update_mkldnn + autogen: _batch_norm_with_update_functional + +- func: _batch_norm_with_update.out(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, float momentum, float eps, *, Tensor(d!) out, Tensor(e!) save_mean, Tensor(f!) save_invstd, Tensor(g!) reserve) -> (Tensor(d!), Tensor(e!), Tensor(f!), Tensor(g!)) + dispatch: + CPU: _batch_norm_with_update_cpu_out + CUDA: _batch_norm_with_update_cuda_out + MPS: _batch_norm_with_update_mps_out + XPU: _batch_norm_with_update_xpu_out + +- func: _batch_norm_no_update(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor, Tensor) + dispatch: + CompositeExplicitAutograd: _batch_norm_no_update + autogen: _batch_norm_no_update.out + +- func: batch_norm_backward(Tensor grad_out, Tensor input, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, bool update, float eps, bool[3] output_mask, Tensor reserve) -> (Tensor, Tensor, Tensor) + dispatch: + CPU: _new_batch_norm_backward_cpu + CUDA: _new_batch_norm_backward_cuda + MPS: _new_batch_norm_backward_mps + XPU: _new_batch_norm_backward_xpu + MkldnnCPU: _new_batch_norm_backward_mkldnn + +# TODO: reduce signatures down to one when optional args is available +- func: _sparse_sum(Tensor self) -> Tensor + +- func: _sparse_sum.dtype(Tensor self, *, ScalarType dtype) -> Tensor + +- func: _sparse_sum.dim(Tensor self, int[1] dim) -> Tensor + dispatch: + CompositeExplicitAutograd: _sparse_sum + autogen: _sparse_sum.dim_out + +- func: _sparse_sum.dim_dtype(Tensor self, int[1] dim, *, ScalarType dtype) -> Tensor + +- func: _sparse_sum_backward(Tensor grad, Tensor self, int[] dim) -> Tensor + dispatch: + SparseCPU: _sparse_sum_backward_cpu + SparseCUDA: _sparse_sum_backward_cuda + SparseMPS: _sparse_sum_backward_mps + SparseXPU: _sparse_sum_backward_xpu + autogen: _sparse_sum_backward.out + +- func: _sparse_csr_sum.dim_dtype(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + dispatch: + SparseCsrCPU: _sparse_csr_sum_cpu + SparseCsrCUDA: _sparse_csr_sum_cuda + SparseCsrXPU: _sparse_csr_sum_xpu + autogen: _sparse_csr_sum.dim_dtype_out + +- func: _sparse_csr_prod.dim_dtype(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + dispatch: + SparseCsrCPU: _sparse_csr_prod_cpu + SparseCsrCUDA: _sparse_csr_prod_cuda + SparseCsrXPU: _sparse_csr_prod_xpu + autogen: _sparse_csr_prod.dim_dtype_out + +- func: _sparse_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor + python_module: sparse + variants: function + +- func: _sparse_softmax(Tensor self, int dim, bool half_to_float) -> Tensor + python_module: sparse + dispatch: + SparseCPU: softmax_sparse_cpu + SparseCUDA: softmax_sparse_cuda + SparseMPS: softmax_sparse_mps + SparseXPU: softmax_sparse_xpu + autogen: _sparse_softmax.out + +- func: _sparse_softmax_backward_data(Tensor grad_output, Tensor output, int dim, Tensor self) -> Tensor + dispatch: + SparseCPU: softmax_backward_sparse_cpu + SparseCUDA: softmax_backward_sparse_cuda + SparseMPS: softmax_backward_sparse_mps + SparseXPU: softmax_backward_sparse_xpu + autogen: _sparse_softmax_backward_data.out + +- func: _sparse_log_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor + python_module: sparse + variants: function + +- func: _sparse_log_softmax(Tensor self, int dim, bool half_to_float) -> Tensor + python_module: sparse + dispatch: + SparseCPU: log_softmax_sparse_cpu + SparseCUDA: log_softmax_sparse_cuda + SparseMPS: log_softmax_sparse_mps + SparseXPU: log_softmax_sparse_xpu + autogen: _sparse_log_softmax.out + +- func: _sparse_log_softmax_backward_data(Tensor grad_output, Tensor output, int dim, Tensor self) -> Tensor + dispatch: + SparseCPU: log_softmax_backward_sparse_cpu + SparseCUDA: log_softmax_backward_sparse_cuda + SparseMPS: log_softmax_backward_sparse_mps + SparseXPU: log_softmax_backward_sparse_xpu + autogen: _sparse_log_softmax_backward_data.out + +- func: _spdiags(Tensor diagonals, Tensor offsets, int[] shape, Layout? layout=None) -> Tensor + python_module: sparse + dispatch: + CPU: spdiags + autogen: _spdiags.out + +- func: norm.ScalarOpt_dtype(Tensor self, Scalar? p, *, ScalarType dtype) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: norm + autogen: norm.ScalarOpt_dtype_out + tags: reduction + +- func: norm.Scalar(Tensor self, Scalar p=2) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: norm + autogen: norm.Scalar_out + tags: reduction + +- func: norm.ScalarOpt_dim_dtype(Tensor self, Scalar? p, int[1] dim, bool keepdim, *, ScalarType dtype) -> Tensor + structured_delegate: norm.dtype_out + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sparse_dtype_norm + tags: reduction + +- func: norm.ScalarOpt_dim(Tensor self, Scalar? p, int[1] dim, bool keepdim=False) -> Tensor + structured_delegate: norm.out + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sparse_norm + tags: reduction + +- func: norm.dtype_out(Tensor self, Scalar? p, int[1] dim, bool keepdim, *, ScalarType dtype, Tensor(a!) out) -> Tensor(a!) + structured: True + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, XPU: norm_dtype_out + tags: reduction + +- func: norm.out(Tensor self, Scalar? p, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + structured: True + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, XPU: norm_out + tags: reduction + +# These four redispatch in their implementation, so OK to be CompositeImplicitAutograd +- func: frexp.Tensor(Tensor self) -> (Tensor mantissa, Tensor exponent) + variants: method, function + dispatch: + CompositeExplicitAutograd: frexp + tags: pointwise + +- func: frexp.Tensor_out(Tensor self, *, Tensor(a!) mantissa, Tensor(b!) exponent) -> (Tensor(a!) mantissa, Tensor(b!) exponent) + dispatch: + CPU, CUDA, XPU: frexp_out + tags: pointwise + +# Deprecated (v.1.12) +- func: frobenius_norm.dim(Tensor self, int[1] dim, bool keepdim=False) -> Tensor + variants: function + +# Deprecated (v.1.12) +- func: frobenius_norm.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + variants: function + +# Deprecated (v.1.12) +- func: nuclear_norm(Tensor self, bool keepdim=False) -> Tensor + variants: function + +# Deprecated (v.1.12) +- func: nuclear_norm.out(Tensor self, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + variants: function + +# Deprecated (v.1.12) +- func: nuclear_norm.dim(Tensor self, int[2] dim, bool keepdim=False) -> Tensor + variants: function + +# Deprecated (v.1.12) +- func: nuclear_norm.dim_out(Tensor self, int[2] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + variants: function + +- func: clone(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: clone + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: clone_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: clone_sparse_compressed + MkldnnCPU: mkldnn_clone + QuantizedCPU, QuantizedCUDA: quantized_clone + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: clone_nested + autogen: clone.out + tags: [core, pointwise] + +- func: positive(Tensor(a) self) -> Tensor(a) + variants: function, method + tags: pointwise + +- func: resize_as_(Tensor(a!) self, Tensor the_template, *, MemoryFormat? memory_format=None) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True + variants: function, method + dispatch: + CompositeExplicitAutograd: resize_as_ + autogen: resize_as, resize_as.out + tags: inplace_view + +- func: resize_as_sparse_(Tensor(a!) self, Tensor the_template) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseXPU: resize_as_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: resize_as_sparse_compressed_ + autogen: resize_as_sparse, resize_as_sparse.out + +- func: zero_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CPU, CUDA, MPS, XPU: zero_ + Meta: zero_meta_ + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: zero_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: zero_sparse_csr_ + MkldnnCPU: mkldnn_zero_ + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: zero_nested_ + autogen: zero, zero.out + +- func: sub.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, XPU: sub_out + MPS: sub_out_mps + MTIA: sub_out_mtia + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sub_out_sparse + tags: pointwise + +- func: sub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: sub.out + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sub_sparse + ZeroTensor: sub_zerotensor + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_sub_Tensor + tags: [core, pointwise] + +- func: sub_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: sub.out + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sub_sparse_ + tags: pointwise +# For C++ only, until we have conversion from C++ numbers to Tensor + +- func: sub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: sub + tags: [core, pointwise] + +- func: sub_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: sub_ + autogen: sub.Scalar_out + tags: pointwise +# subtract, alias for sub + +- func: subtract.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + +- func: subtract.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor + variants: function, method + +- func: subtract_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!) + variants: method + +# For C++ only, until we have conversion from C++ numbers to Tensor +- func: subtract.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor + variants: function, method + +- func: subtract_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!) + variants: method + +- func: rsub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CPU, CUDA, MPS, MTIA, XPU: rsub + autogen: rsub.Tensor_out + +- func: heaviside.out(Tensor self, Tensor values, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, XPU: heaviside_out + tags: pointwise + +- func: heaviside(Tensor self, Tensor values) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: heaviside.out + tags: pointwise + +- func: heaviside_(Tensor(a!) self, Tensor values) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: heaviside.out + +# For C++ only, until we have conversion from C++ numbers to Tensor +- func: rsub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: rsub + autogen: rsub.Scalar_out + +# Functionally the same as addmm, but we give it a different derivative formula +# that doesn't propagate gradients to non-present entries on sparse. + tags: pointwise +- func: _sparse_addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + python_module: sparse + dispatch: + CompositeExplicitAutograd: _sparse_addmm + autogen: _sparse_addmm.out + +- func: sparse_sampled_addmm.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + python_module: sparse + dispatch: + SparseCsrCUDA: sparse_sampled_addmm_out_sparse_csr_cuda + SparseCsrCPU: sparse_sampled_addmm_out_sparse_csr_cpu + SparseCsrXPU: sparse_sampled_addmm_out_sparse_csr_xpu + +- func: sparse_sampled_addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + python_module: sparse + dispatch: + SparseCsrCUDA: sparse_sampled_addmm_sparse_csr_cuda + SparseCsrCPU: sparse_sampled_addmm_sparse_csr_cpu + SparseCsrXPU: sparse_sampled_addmm_sparse_csr_xpu + +- func: _sparse_mm_reduce_impl(Tensor self, Tensor other, str reduce) -> (Tensor, Tensor) + python_module: sparse + dispatch: + SparseCsrCPU: _sparse_mm_reduce_impl_sparse_csr_cpu + +- func: _sparse_mm_reduce_impl_backward(Tensor self, Tensor grad_out, Tensor weight, str reduce, Tensor arg_out, bool[2] output_mask) -> (Tensor, Tensor) + python_module: sparse + dispatch: + SparseCsrCPU: _sparse_mm_reduce_impl_backward_sparse_csr_cpu + +- func: addmm.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU: addmm_out_cpu + CUDA: addmm_out_cuda + MPS: addmm_out_mps + MTIA: addmm_out_mtia + XPU: addmm_out_xpu + SparseCPU: addmm_out_sparse_dense_cpu + SparseCUDA: addmm_out_sparse_dense_cuda + SparseMPS: addmm_out_sparse_dense_mps + SparseXPU: addmm_out_sparse_dense_xpu + SparseCsrCPU: addmm_out_sparse_compressed_cpu + SparseCsrCUDA: addmm_out_sparse_compressed_cuda + SparseCsrXPU: addmm_out_sparse_compressed_xpu + +- func: addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + structured_delegate: addmm.out + variants: function, method + dispatch: + SparseCPU: addmm_sparse_dense_cpu + SparseCUDA: addmm_sparse_dense_cuda + SparseMPS: addmm_sparse_dense_mps + SparseXPU: addmm_sparse_dense_xpu + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: addmm_sparse_compressed_dense + tags: core + +- func: addmm.dtype(Tensor self, Tensor mat1, Tensor mat2, ScalarType out_dtype, *, Scalar beta=1, Scalar alpha=1) -> Tensor + dispatch: + CUDA: _addmm_dtype_cuda + XPU: _addmm_dtype_xpu + +- func: addmm.dtype_out(Tensor self, Tensor mat1, Tensor mat2, ScalarType out_dtype, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + dispatch: + CUDA: _addmm_dtype_out_cuda + XPU: _addmm_dtype_out_xpu + +- func: addmm_(Tensor(a!) self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) + structured_delegate: addmm.out + variants: method + dispatch: + # Warning! For whatever reason, the inplace sparse addmm is NON + # broadcasting + SparseCPU: s_addmm_sparse_dense_cpu_ + SparseCUDA: s_addmm_sparse_dense_cuda_ + SparseXPU: s_addmm_sparse_dense_xpu_ + +- func: _addmm_activation.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, bool use_gelu=False, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU: addmm_activation_out_cpu + CUDA: addmm_activation_out_cuda + XPU: addmm_activation_out_xpu + +- func: _addmm_activation(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, bool use_gelu=False) -> Tensor + structured_delegate: _addmm_activation.out + variants: function, method + +- func: _scaled_mm(Tensor self, Tensor mat2, Tensor scale_a, Tensor scale_b, Tensor? bias=None, Tensor? scale_result=None, ScalarType? out_dtype=None, bool use_fast_accum=False) -> Tensor + variants: function + dispatch: + CPU: _scaled_mm_cpu + CUDA: _scaled_mm_cuda + XPU: _scaled_mm_xpu + tags: needs_exact_strides + +- func: _scaled_mm.out(Tensor self, Tensor mat2, Tensor scale_a, Tensor scale_b, Tensor? bias=None, Tensor? scale_result=None, ScalarType? out_dtype=None, bool use_fast_accum=False, *, Tensor(a!) out) -> Tensor(a!) + variants: function + dispatch: + CPU: _scaled_mm_out_cpu + CUDA: _scaled_mm_out_cuda + XPU: _scaled_mm_out_xpu + tags: needs_exact_strides + +- func: _scaled_mm_v2(Tensor self, Tensor mat2, Tensor[] scale_a, int[] recipe_a, int[] swizzle_a, Tensor[] scale_b, int[] recipe_b, int[] swizzle_b, Tensor? bias, ScalarType? out_dtype, int[] contraction_dim=[], bool use_fast_accum=False) -> Tensor + structured_delegate: _scaled_mm_v2.out + variants: function + tags: needs_exact_strides + +- func: _scaled_mm_v2.out(Tensor self, Tensor mat2, Tensor[] scale_a, int[] recipe_a, int[] swizzle_a, Tensor[] scale_b, int[] recipe_b, int[] swizzle_b, Tensor? bias, ScalarType? out_dtype, int[] contraction_dim=[], bool use_fast_accum=False, *, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CPU: _scaled_mm_cpu_v2_out + CUDA: _scaled_mm_cuda_v2_out + XPU: _scaled_mm_xpu_v2_out + tags: needs_exact_strides + +- func: _scaled_grouped_mm(Tensor self, Tensor mat2, Tensor scale_a, Tensor scale_b, Tensor? offs=None, Tensor? bias=None, Tensor? scale_result=None, ScalarType? out_dtype=None, bool use_fast_accum=False) -> Tensor + variants: function + dispatch: + CUDA: _scaled_grouped_mm_cuda + tags: needs_exact_strides + +- func: _scaled_grouped_mm_v2(Tensor self, Tensor mat2, Tensor[] scale_a, int[] recipe_a, int[] swizzle_a, Tensor[] scale_b, int[] recipe_b, int[] swizzle_b, Tensor? offs=None, Tensor? bias=None, ScalarType? out_dtype=None, int[] contraction_dim=[], bool use_fast_accum=False) -> Tensor + structured_delegate: _scaled_grouped_mm_v2.out + variants: function + tags: needs_exact_strides + +- func: _scaled_grouped_mm_v2.out(Tensor self, Tensor mat2, Tensor[] scale_a, int[] recipe_a, int[] swizzle_a, Tensor[] scale_b, int[] recipe_b, int[] swizzle_b, Tensor? offs=None, Tensor? bias=None, ScalarType? out_dtype=None, int[] contraction_dim=[], bool use_fast_accum=False, *, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CUDA: _scaled_grouped_mm_cuda_v2_out + tags: needs_exact_strides + +- func: _grouped_mm(Tensor self, Tensor mat2, Tensor? offs=None, Tensor? bias=None, ScalarType? out_dtype=None) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: _grouped_mm + CUDA: _grouped_mm_cuda + +# NOTE [ Sparse: autograd and API ] +# +# +# Sparse Tensor Constructors +# ~~~~~~~~~~~~~~~~~~~~~~~~~~ +# +# The API entry points to sparse tensor construction should be +# `sparse_coo tensor` and `_sparse_coo_tensor_unsafe`. Depending on whether the +# indices and values tensors are given, they eventually dispatch to either +# `sparse_coo_tensor_with_dims` or `sparse_coo_tensor_with_dims_and_tensors`. +# +# The autograd support for ctor is implement on `sparse_coo_tensor_with_dims_and_tensors`. +# +# The API methods `sparse_coo tensor` and `_sparse_coo_tensor_unsafe` +# **must not** have specific type dispatches because otherwise codegen will +# consider them as abstract methods (see Note [Abstract ATen methods]), dispatch +# using **Tensor** type, and thus lose autograd tracking on the actual method +# they dispatch to, e.g., `sparse_coo_tensor_with_dims_and_tensors`. +# +# +# Sparse Methods API Design +# ~~~~~~~~~~~~~~~~~~~~~~~~~ +# +# Goals: 1. Flexible API for users to write custom sparse ops +# 2. ctor and member accessor with autograd support +# +# To achieve 1, we need to provide a set of *dangerous* APIs (dangerous in the +# sense that misusing them will break sparse tensor invariant and may out in +# unexpected behavior, e.g., crash). These methods are all prefixed with +# underscore "_" to indicate that they should be used with care. We provide: +# +# + `_indices()`: returns the *raw* indices within the sparse tensor (not just +# sharing storage). Any inplace operation will change the +# actual indices, including t_, set_, as_strided_, resize_, +# etc. +# + `_values()`: returns the *raw* values within the sparse tensor. Similar +# semantics as `_indices()` +# + `_nnz()`: returns the number of non-zero entries. This will always be +# determined by the shapes of indices and values. +# + `_coalesced_(bool)`: inplace sets whether the tensor is coalesced, and +# returns itself. +# +# These methods are very useful in writing new operations, e.g., a custom +# autograd Function. +# +# We also provide other public *safe* APIs: +# + `indices()`: returns a **view** of the indices tensor if the sparse tensor +# is **coalesced**. +# + `values()`: returns a **view** of the values tensor if the containing +# sparse tensor is **coalesced**. +# + `sparse_dim()`: number of sparse dimensions +# + `dense_dim()`: number of dense dimensions +# + `is_coalesced()`: whether the sparse tensor is coalesced +# +# `_indices()` and `_values()` should returns the raw indices and values dense +# tensors within a sparse tensor. They can be quite unsafe with inplace +# operations like `t_()`, and exposes uncoalesced indices and values. The public +# recommended API is `indices()` and `values()`, both of which first check that +# the tensor is coalesced and return views on those tensors. +# +# +# Autograd Support +# ~~~~~~~~~~~~~~~~ +# +# Autograd is supported on `values()` and sparse tensor ctor with indices and +# values tensors. E.g., `torch.sparse_coo_tensor(i, v).values().sum()` is +# differentiable w.r.t. `v`. +# +# NB: The `values()` and `_values()` operators are special in that they are +# layout-aware, i.e., the output depends not just on the data it represents, but +# also on the input layout details (in this case, the `indices` tensor). See +# NOTE [ as_strided Backward and layout-aware/agnostic autograd ] in Functions.cpp +# for discussion on layout-aware vs layout-agnostic autograd. Since PyTorch ops +# operate in the layout-agnostic mode, similar to `as_strided`, backward of +# these two operators need to consider them in a layout-agnostic way: +# + `values()`: +# Input is coalesced. +# We just pretend having `input.indices()` as an additional argument +# `input_indices`, then forward is similar to +# `input.to(kStrided).index_select(input_indices)` regardless of the layout. +# Note that `values()` normally is layout-aware even if we constrain +# ourselves on sparse inputs since it may include all zeros values entries +# as "present" entries. +# + `_values()`: +# Input may be uncoalesced. +# It is not straightforward to construct a layout-agnostic version because +# duplicate indices entries may exist and additional parameterization is +# needed to distribute the value into different values entries. Furthermore, +# this op is intended to provide ways to write custom sparse ops, rather +# than being used in autograd graph, so it is marked as *non-differentiable* +# in derivatives.yaml. +# +# Before reading the following, see NOTE [ Autograd Variable Views ] in +# variable.h for details on views that are tracked by autograd, and views that +# are not. +# +# Moreover, these methods return tensors that share storage with inputs, so we +# mark these methods as view ops to support autograd history tracking. +# The sparse tensor ctor output should technically be view of both input indices +# and values tensors, but currently we only support setting as view of a single +# Variable, so it is only view of the values tensor. +# TODO: clone indices in sparse tensor ctor. +# +# For other methods that return outputs that share storage with inputs, i.e., +# `indices()` and `_indices()`. We mark their outputs as non-differentiable, so +# the view relation is not tracked by autograd, but the version counter is still +# shared. In other words, their outputs are non-differentiable views of the +# sparse tensor. +# FIXME: would be nicer if TensorOptions was optional based; not adding default arguments for options given +# the default would never make sense. + +- func: _sparse_compressed_tensor_with_dims(int nnz, int dense_dim, int[] size, int[] blocksize, ScalarType index_dtype, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor + dispatch: + CompositeExplicitAutograd: sparse_compressed_tensor_with_dims + +- func: sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor + dispatch: + CompositeExplicitAutograd: sparse_compressed_tensor + +- func: sparse_csr_tensor.crow_col_value_size(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +- func: sparse_csc_tensor.ccol_row_value_size(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +- func: sparse_bsr_tensor.crow_col_value_size(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +- func: sparse_bsc_tensor.ccol_row_value_size(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor + +- func: sparse_compressed_tensor.comp_plain_value(Tensor compressed_indices, Tensor plain_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor + dispatch: + CompositeExplicitAutograd: sparse_compressed_tensor +- func: sparse_csr_tensor.crow_col_value(Tensor crow_indices, Tensor col_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +- func: sparse_csc_tensor.ccol_row_value(Tensor ccol_indices, Tensor row_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +- func: sparse_bsr_tensor.crow_col_value(Tensor crow_indices, Tensor col_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor +- func: sparse_bsc_tensor.ccol_row_value(Tensor ccol_indices, Tensor row_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor + +- func: _sparse_compressed_tensor_unsafe(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeImplicitAutograd: _sparse_compressed_tensor_unsafe_symint + +- func: _sparse_csr_tensor_unsafe(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +- func: _sparse_csc_tensor_unsafe(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +- func: _sparse_bsr_tensor_unsafe(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +- func: _sparse_bsc_tensor_unsafe(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + +- func: sparse_coo_tensor.size(int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor + dispatch: + CompositeExplicitAutograd: sparse_coo_tensor + autogen: sparse_coo_tensor.size_out + +- func: sparse_coo_tensor.indices(Tensor indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool? is_coalesced=None) -> Tensor + +- func: sparse_coo_tensor.indices_size(Tensor indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool? is_coalesced=None) -> Tensor + +- func: _sparse_coo_tensor_unsafe(Tensor indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool? is_coalesced=None) -> Tensor + dispatch: + CompositeImplicitAutograd: _sparse_coo_tensor_unsafe_symint + +- func: _validate_sparse_coo_tensor_args(Tensor indices, Tensor values, int[] size, bool? is_coalesced=None, bool? check_pinning=None) -> () + +- func: _validate_sparse_compressed_tensor_args(Tensor compressed_indices, Tensor plain_indices, Tensor values, int[] size, Layout layout, bool? check_pinning=None) -> () +- func: _validate_sparse_csr_tensor_args(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, bool? check_pinning=None) -> () +- func: _validate_sparse_csc_tensor_args(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, bool? check_pinning=None) -> () +- func: _validate_sparse_bsr_tensor_args(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, bool? check_pinning=None) -> () +- func: _validate_sparse_bsc_tensor_args(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, bool? check_pinning=None) -> () + +- func: _sparse_coo_tensor_with_dims(int sparse_dim, int dense_dim, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor + dispatch: + SparseCPU, SparseCUDA, SparseMeta, SparseMPS, SparseXPU, Meta: new_with_dims_sparse + autogen: _sparse_coo_tensor_with_dims.out + +- func: _sparse_coo_tensor_with_dims_and_tensors(int sparse_dim, int dense_dim, SymInt[] size, Tensor indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False, bool? is_coalesced=None) -> Tensor + dispatch: + SparseCPU, SparseCUDA, SparseMeta, SparseMPS, SparseXPU, Meta: new_with_dims_and_tensor_sparse_symint + autogen: _sparse_coo_tensor_with_dims_and_tensors.out + +- func: sparse_resize_(Tensor(a!) self, int[] size, int sparse_dim, int dense_dim) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: sparse_resize_ + autogen: sparse_resize, sparse_resize.out + +- func: sparse_resize_and_clear_(Tensor(a!) self, int[] size, int sparse_dim, int dense_dim) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: sparse_resize_and_clear_ + autogen: sparse_resize_and_clear, sparse_resize_and_clear.out + +- func: sparse_mask(Tensor self, Tensor mask) -> Tensor + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sparse_mask + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sparse_mask_sparse_compressed + autogen: sparse_mask.out + +- func: _sparse_mask_projection(Tensor self, Tensor mask, bool accumulate_matches=False) -> Tensor + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sparse_mask_projection + autogen: _sparse_mask_projection.out + +- func: _to_cpu(Tensor[] tensors) -> Tensor[] + variants: function + +- func: to_dense(Tensor self, ScalarType? dtype=None, *, bool? masked_grad=None) -> Tensor + variants: method + +# Special case of to_dense with custom derivative +- func: _to_dense(Tensor self, ScalarType? dtype=None, bool? masked_grad=None) -> Tensor + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sparse_to_dense + SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta, SparseCsrXPU: sparse_compressed_to_dense + MkldnnCPU: mkldnn_to_dense + autogen: _to_dense.out + +- func: to_dense_backward(Tensor grad, Tensor input, bool? masked_grad=None) -> Tensor + +- func: sparse_dim(Tensor self) -> int + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: sparse_dim_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta, SparseCsrXPU: sparse_dim_sparse_csr + CompositeExplicitAutograd: sparse_dim_default + device_check: NoCheck + device_guard: False + +# legacy method +- func: _dimI(Tensor self) -> int + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseXPU: sparse_dim_sparse + device_check: NoCheck + device_guard: False + +- func: dense_dim(Tensor self) -> int + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: dense_dim_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta, SparseCsrXPU: dense_dim_sparse_csr + CompositeExplicitAutograd: dense_dim_default + device_check: NoCheck + device_guard: False + +# legacy method +- func: _dimV(Tensor self) -> int + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMeta, SparseXPU: dense_dim_sparse + device_check: NoCheck + device_guard: False + +- func: _nnz(Tensor self) -> int + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: _nnz_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMPS, SparseCsrMeta, SparseCsrXPU: _nnz_sparse_csr + device_check: NoCheck + device_guard: False + +# NOTE: [ coalesce autograd ] +# coalesce returns self directly for already coalesced sparse tensors. +# This means coalesce cannot have a derivative registered, otherwise it creates +# circular references in the autograd graph (see gh-52874). +# Instead, the derivative is registered on the slow-path "_coalesce" +- func: coalesce(Tensor(a) self) -> Tensor(a) + variants: method + +- func: _coalesce(Tensor self) -> Tensor + dispatch: + SparseCPU: _coalesce_sparse_cpu + SparseCUDA: _coalesce_sparse_cuda + SparseMPS: _coalesce_sparse_mps + SparseXPU: _coalesce_sparse_xpu + autogen: _coalesce.out + +- func: is_coalesced(Tensor self) -> bool + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: is_coalesced_sparse + CompositeExplicitAutograd: is_coalesced_default + device_check: NoCheck + device_guard: False + +- func: _indices(Tensor(a) self) -> Tensor(a) + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: _indices_sparse + device_check: NoCheck + device_guard: False + +- func: _values(Tensor(a) self) -> Tensor(a) + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: _values_sparse + device_check: NoCheck + device_guard: False + +# This method doesn't do any check but only directly sets the flag. So it can be +# a bit unsafe. Similar to _indices and _values, this is useful for implementing +# custom sparse operations in Python/C++ extension. +- func: _coalesced_(Tensor(a!) self, bool coalesced) -> Tensor(a!) + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: _coalesced_sparse_ + device_check: NoCheck + device_guard: False + autogen: _coalesced, _coalesced.out + +- func: indices(Tensor(a) self) -> Tensor(a) + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: indices_sparse + CompositeExplicitAutograd: indices_default + device_check: NoCheck + device_guard: False + +- func: values(Tensor(a) self) -> Tensor(a) + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: values_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: values_sparse_csr + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: values_nested + CompositeExplicitAutograd: values_default + device_check: NoCheck + device_guard: False + +- func: crow_indices(Tensor(a) self) -> Tensor(a) + variants: method + dispatch: + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: crow_indices_sparse_csr + CompositeExplicitAutograd: crow_indices_default + device_check: NoCheck + device_guard: False + +- func: col_indices(Tensor(a) self) -> Tensor(a) + variants: method + dispatch: + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: col_indices_sparse_csr + CompositeExplicitAutograd: col_indices_default + device_check: NoCheck + device_guard: False + +- func: ccol_indices(Tensor(a) self) -> Tensor(a) + variants: method + dispatch: + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: ccol_indices_sparse_csr + CompositeExplicitAutograd: ccol_indices_default + device_check: NoCheck + device_guard: False + +- func: row_indices(Tensor(a) self) -> Tensor(a) + variants: method + dispatch: + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: row_indices_sparse_csr + CompositeExplicitAutograd: row_indices_default + device_check: NoCheck + device_guard: False + +- func: hspmm.out(Tensor mat1, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + SparseCPU: hspmm_out_sparse_cpu + SparseCUDA: hspmm_out_sparse_cuda + SparseXPU: hspmm_out_sparse_xpu + +- func: hspmm(Tensor mat1, Tensor mat2) -> Tensor + dispatch: + SparseCPU: hspmm_sparse_cpu + SparseCUDA: hspmm_sparse_cuda + SparseXPU: hspmm_sparse_xpu + +- func: copy_sparse_to_sparse_(Tensor(a!) self, Tensor src, bool non_blocking=False) -> Tensor(a!) + device_check: NoCheck # Allows copy into different device + variants: function + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseMeta, SparseXPU: copy_sparse_ + autogen: copy_sparse_to_sparse, copy_sparse_to_sparse.out + +# By adding the AutogradNestedTensor this makes this function CompositeImplicit-like for nested tensors +- func: unbind.int(Tensor(a -> *) self, int dim=0) -> Tensor(a)[] + variants: function, method + dispatch: + CompositeExplicitAutograd: unbind + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_unbind + +- func: to_sparse.sparse_dim(Tensor self, int sparse_dim) -> Tensor + variants: method + +# Special case of to_sparse.sparse_dim with custom derivative +- func: _to_sparse.sparse_dim(Tensor self, int sparse_dim) -> Tensor + variants: method + dispatch: + CPU, CUDA, MPS, XPU: dense_to_sparse + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sparse_coo_to_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrMPS, SparseCsrXPU: sparse_compressed_to_sparse + autogen: _to_sparse.sparse_dim_out + +- func: to_sparse(Tensor self, *, Layout? layout=None, int[2]? blocksize=None, int? dense_dim=None) -> Tensor + variants: method + +# Special case of to_sparse with custom derivative +- func: _to_sparse(Tensor self, *, Layout? layout=None, int[2]? blocksize=None, int? dense_dim=None) -> Tensor + variants: method + dispatch: + CPU, CUDA, MPS, XPU: dense_to_sparse + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sparse_coo_to_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sparse_compressed_to_sparse + autogen: _to_sparse.out + +- func: to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor + variants: method + +# Special case of to_sparse_csr with custom derivative +- func: _to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor + variants: method + dispatch: + CPU, CUDA, XPU: dense_to_sparse_csr + SparseCPU, SparseCUDA, SparseXPU: coo_to_sparse_csr + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sparse_compressed_to_sparse_csr + autogen: _to_sparse_csr.out + +- func: to_sparse_csc(Tensor self, int? dense_dim=None) -> Tensor + variants: method + +# Special case of to_sparse_csc with custom derivative +- func: _to_sparse_csc(Tensor self, int? dense_dim=None) -> Tensor + variants: method + dispatch: + CPU, CUDA, XPU: dense_to_sparse_csc + SparseCPU, SparseCUDA, SparseXPU: coo_to_sparse_csc + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sparse_compressed_to_sparse_csc + autogen: _to_sparse_csc.out + +- func: to_sparse_bsr(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor + variants: method + +# Special case of to_sparse_bsr with custom derivative +- func: _to_sparse_bsr(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor + variants: method + dispatch: + CPU, CUDA, XPU: dense_to_sparse_bsr + SparseCPU, SparseCUDA, SparseXPU: coo_to_sparse_bsr + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sparse_compressed_to_sparse_bsr + autogen: _to_sparse_bsr.out + +- func: to_sparse_bsc(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor + variants: method + +# Special case of to_sparse_bsc with custom derivative +- func: _to_sparse_bsc(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor + variants: method + dispatch: + CPU, CUDA, XPU: dense_to_sparse_bsc + SparseCPU, SparseCUDA, SparseXPU: coo_to_sparse_bsc + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sparse_compressed_to_sparse_bsc + autogen: _to_sparse_bsc.out + +- func: _to_sparse_semi_structured(Tensor dense) -> (Tensor, Tensor) + variants: function + dispatch: + CUDA: _to_sparse_semi_structured + +- func: to_mkldnn(Tensor self, ScalarType? dtype=None) -> Tensor + variants: method + dispatch: + CPU: dense_to_mkldnn + autogen: to_mkldnn.out + +- func: mkldnn_reorder_conv2d_weight(Tensor self, SymInt[2] padding=0, SymInt[2] stride=1, SymInt[2] dilation=1, SymInt groups=1, SymInt[]? input_size=None) -> Tensor + variants: function + python_module: nn + dispatch: + MkldnnCPU: mkldnn_reorder_conv2d_weight + autogen: mkldnn_reorder_conv2d_weight.out + +- func: mkldnn_reorder_conv3d_weight(Tensor self, SymInt[3] padding=0, SymInt[3] stride=1, SymInt[3] dilation=1, SymInt groups=1, SymInt[]? input_size=None) -> Tensor + variants: function + python_module: nn + dispatch: + MkldnnCPU: mkldnn_reorder_conv3d_weight + autogen: mkldnn_reorder_conv3d_weight.out + +- func: to_mkldnn_backward(Tensor grad, Tensor input) -> Tensor + +- func: quantize_per_tensor_dynamic(Tensor self, ScalarType dtype, bool reduce_range) -> Tensor + variants: function + dispatch: + CPU, CUDA, XPU: quantize_per_tensor_dynamic + autogen: quantize_per_tensor_dynamic.out + +- func: quantize_per_tensor(Tensor self, float scale, int zero_point, ScalarType dtype) -> Tensor + variants: function + dispatch: + CPU, CUDA, XPU: quantize_per_tensor + autogen: quantize_per_tensor.out + +- func: quantize_per_tensor.tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, ScalarType dtype) -> Tensor + variants: function + dispatch: + CPU, CUDA, XPU: quantize_per_tensor_tensor_qparams + autogen: quantize_per_tensor.tensor_qparams_out + +- func: quantize_per_tensor.tensors(Tensor[] tensors, Tensor scales, Tensor zero_points, ScalarType dtype) -> Tensor[] + variants: function + dispatch: + CPU: quantize_per_tensor_list_cpu + autogen: quantize_per_tensor.tensors_out + +- func: quantize_per_channel(Tensor self, Tensor scales, Tensor zero_points, int axis, ScalarType dtype) -> Tensor + variants: function + dispatch: + CPU, CUDA, XPU: quantize_per_channel + autogen: quantize_per_channel.out + +- func: dequantize.self(Tensor self) -> Tensor + variants: function, method + dispatch: + CPU, CUDA, XPU: dequantize_cpu_or_cuda + QuantizedCPU, QuantizedCUDA: dequantize_quantized + autogen: dequantize.self_out + +- func: dequantize.tensors(Tensor[] tensors) -> Tensor[] + variants: function + dispatch: + QuantizedCPU: dequantize_tensors_quantized_cpu + autogen: dequantize.tensors_out + +- func: q_scale(Tensor self) -> float + variants: function, method + dispatch: + QuantizedCPU, QuantizedCUDA: q_scale_quant + +- func: q_zero_point(Tensor self) -> int + variants: function, method + dispatch: + QuantizedCPU, QuantizedCUDA: q_zero_point_quant + +- func: q_per_channel_scales(Tensor self) -> Tensor + variants: function, method + dispatch: + QuantizedCPU, QuantizedCUDA: q_per_channel_scales + autogen: q_per_channel_scales.out + +- func: q_per_channel_zero_points(Tensor self) -> Tensor + variants: function, method + dispatch: + QuantizedCPU, QuantizedCUDA: q_per_channel_zero_points + autogen: q_per_channel_zero_points.out + +- func: q_per_channel_axis(Tensor self) -> int + variants: function, method + dispatch: + QuantizedCPU, QuantizedCUDA: q_per_channel_axis + +- func: int_repr(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + QuantizedCPU: int_repr_quantized_cpu + QuantizedCUDA: int_repr_quantized_cuda + autogen: int_repr.out + +- func: _make_per_tensor_quantized_tensor(Tensor self, float scale, int zero_point) -> Tensor + dispatch: + CPU: make_per_tensor_quantized_tensor_cpu + CUDA: make_per_tensor_quantized_tensor_cuda + XPU: make_per_tensor_quantized_tensor_xpu + autogen: _make_per_tensor_quantized_tensor.out + +- func: _make_per_channel_quantized_tensor(Tensor self, Tensor scale, Tensor zero_point, int axis) -> Tensor + dispatch: + CPU: make_per_channel_quantized_tensor_cpu + CUDA: make_per_channel_quantized_tensor_cuda + XPU: make_per_channel_quantized_tensor_xpu + autogen: _make_per_channel_quantized_tensor.out + +- func: qscheme(Tensor self) -> QScheme + variants: method + dispatch: + QuantizedCPU, QuantizedCUDA: qscheme_quant + +- func: fake_quantize_per_tensor_affine(Tensor self, float scale, int zero_point, int quant_min, int quant_max) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + +- func: fake_quantize_per_tensor_affine.tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, int quant_min, int quant_max) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + +- func: fake_quantize_per_tensor_affine_cachemask(Tensor self, float scale, int zero_point, int quant_min, int quant_max) -> (Tensor output, Tensor mask) + variants: function + dispatch: + CPU, CUDA, XPU: fake_quantize_per_tensor_affine_cachemask + autogen: fake_quantize_per_tensor_affine_cachemask.out + +- func: _fake_quantize_per_tensor_affine_cachemask_tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, Tensor fake_quant_enabled, int quant_min, int quant_max) -> (Tensor output, Tensor mask) + variants: function + dispatch: + CPU, CUDA, XPU: _fake_quantize_per_tensor_affine_cachemask_tensor_qparams + autogen: _fake_quantize_per_tensor_affine_cachemask_tensor_qparams.out + +- func: fake_quantize_per_tensor_affine_cachemask_backward(Tensor grad, Tensor mask) -> Tensor + variants: function + +- func: _fake_quantize_learnable_per_tensor_affine(Tensor self, Tensor scale, Tensor zero_point, int quant_min, int quant_max, float grad_factor=1.0) -> Tensor + variants: function + dispatch: + CPU, CUDA, XPU: _fake_quantize_learnable_per_tensor_affine + autogen: _fake_quantize_learnable_per_tensor_affine.out + +- func: _fake_quantize_learnable_per_tensor_affine_backward(Tensor grad, Tensor self, Tensor scale, Tensor zero_point, int quant_min, int quant_max, float grad_factor=1.0) -> (Tensor, Tensor, Tensor) + variants: function + dispatch: + CPU, CUDA, XPU: _fake_quantize_learnable_per_tensor_affine_backward + +- func: fake_quantize_per_channel_affine(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + +- func: fake_quantize_per_channel_affine_cachemask(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max) -> (Tensor output, Tensor mask) + variants: function + dispatch: + CPU, CUDA, XPU: fake_quantize_per_channel_affine_cachemask + autogen: fake_quantize_per_channel_affine_cachemask.out + +- func: fake_quantize_per_channel_affine_cachemask_backward(Tensor grad, Tensor mask) -> Tensor + variants: function + +- func: _fake_quantize_learnable_per_channel_affine(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max, float grad_factor=1.0) -> Tensor + variants: function + dispatch: + CPU, CUDA, XPU: _fake_quantize_learnable_per_channel_affine + autogen: _fake_quantize_learnable_per_channel_affine.out + +- func: _fake_quantize_learnable_per_channel_affine_backward(Tensor grad, Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max, float grad_factor=1.0) -> (Tensor, Tensor, Tensor) + variants: function + dispatch: + CPU, CUDA, XPU: _fake_quantize_learnable_per_channel_affine_backward + +- func: fused_moving_avg_obs_fake_quant(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> Tensor + variants: function + +- func: _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask) + dispatch: + CPU: fused_moving_avg_obs_fake_quant_cpu + CUDA: fused_moving_avg_obs_fake_quant_cuda + XPU: fused_moving_avg_obs_fake_quant_xpu + autogen: _fused_moving_avg_obs_fq_helper_functional, _fused_moving_avg_obs_fq_helper.out + +- func: _choose_qparams_per_tensor(Tensor self, bool reduce_range=False) -> (float, int) + variants: function + +- func: _saturate_weight_to_fp16(Tensor weight) -> Tensor + variants: function + +- func: choose_qparams_optimized(Tensor input, int numel, int n_bins, float ratio, int bit_width) -> (Tensor, Tensor) + variants: function + +- func: _autocast_to_reduced_precision(Tensor(a) self, bool cuda_enabled, bool cpu_enabled, ScalarType cuda_dtype, ScalarType cpu_dtype) -> Tensor(a) + variants: method + device_guard: False + +- func: _autocast_to_full_precision(Tensor(a) self, bool cuda_enabled, bool cpu_enabled) -> Tensor(a) + variants: method + device_guard: False + +- func: _to_copy(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, MemoryFormat? memory_format=None) -> Tensor + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: _to_copy + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: _to_copy_nested + autogen: _to_copy.out + tags: core + +# to(Device) must not exist because all constructors of Device also works for +# TensorOptions. Otherwise, an ambiguity error is thrown. +# See NOTE [ TensorOptions Constructors ]. +- func: to.dtype_layout(Tensor(a) self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a) + variants: method + device_check: NoCheck + device_guard: False + +- func: to.device(Tensor(a) self, Device device, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a) + variants: method + device_check: NoCheck + device_guard: False + +- func: to.dtype(Tensor(a) self, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a) + variants: method + device_check: NoCheck + device_guard: False + +- func: to.other(Tensor(a) self, Tensor other, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a) + variants: method + device_check: NoCheck + device_guard: False + +- func: meshgrid(Tensor[] tensors) -> Tensor[] + +# TODO: Two weeks after this lands, combine these two overloads, +# making "indexing" optional. These are temporarily distinct for +# forward-compatibility reasons. +- func: meshgrid.indexing(Tensor[] tensors, *, str indexing) -> Tensor[] + +- func: cartesian_prod(Tensor[] tensors) -> Tensor + variants: function + tags: maybe_aliasing_or_mutating + +- func: combinations(Tensor self, int r=2, bool with_replacement=False) -> Tensor + variants: function + +- func: item(Tensor self) -> Scalar + tags: data_dependent_output + variants: method + +- func: result_type.Tensor(Tensor tensor, Tensor other) -> ScalarType + variants: function + +- func: result_type.Scalar(Tensor tensor, Scalar other) -> ScalarType + variants: function + +- func: result_type.Scalar_Tensor(Scalar scalar, Tensor tensor) -> ScalarType + variants: function + +- func: result_type.Scalar_Scalar(Scalar scalar1, Scalar scalar2) -> ScalarType + +- func: can_cast(ScalarType from_, ScalarType to) -> bool + variants: function + +- func: promote_types(ScalarType type1, ScalarType type2) -> ScalarType + variants: function + +# NB: Does NOT check precondition that numel == 1 +- func: _local_scalar_dense(Tensor self) -> Scalar + tags: [core, data_dependent_output] + dispatch: + CPU: _local_scalar_dense_cpu + CUDA: _local_scalar_dense_cuda + MPS: _local_scalar_dense_mps + XPU: _local_scalar_dense_xpu + variants: function + +# MPS LSTM implementation + +- func: _lstm_mps(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor) + dispatch: + MPS: _lstm_mps + autogen: _lstm_mps.out + tags: nondeterministic_seeded + +- func: lstm_mps_backward(Tensor? grad_y, Tensor? grad_hy, Tensor? grad_cy, Tensor z_state, Tensor cell_state_fwd, Tensor input, Tensor layersOutputs, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor[], Tensor[]) + dispatch: + MPS: lstm_mps_backward + autogen: lstm_mps_backward.out + +# Fused RNN kernels +- func: _thnn_fused_lstm_cell(Tensor input_gates, Tensor hidden_gates, Tensor cx, Tensor? input_bias=None, Tensor? hidden_bias=None) -> (Tensor, Tensor, Tensor) + dispatch: + CUDA: _thnn_fused_lstm_cell_cuda + XPU: _thnn_fused_lstm_cell_xpu + autogen: _thnn_fused_lstm_cell.out + +# NB: The composite version of this function below is a simple wrapper that duplicates some of the outputs +# It is necessary to avoid triggering TensorImpl use count checks in debug mode +# NB: this is function is NOT differentiable +- func: _thnn_fused_lstm_cell_backward_impl(Tensor? grad_hy, Tensor? grad_cy, Tensor cx, Tensor cy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor) + dispatch: + CUDA: _thnn_fused_lstm_cell_backward_impl_cuda + XPU: _thnn_fused_lstm_cell_backward_xpu + autogen: _thnn_fused_lstm_cell_backward_impl.out + +- func: _thnn_fused_lstm_cell_backward(Tensor? grad_hy, Tensor? grad_cy, Tensor cx, Tensor cy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor) + +- func: _thnn_differentiable_lstm_cell_backward(Tensor? grad_hy, Tensor? grad_cy, Tensor input_gates, Tensor hidden_gates, Tensor? input_bias, Tensor? hidden_bias, Tensor cx, Tensor cy) -> (Tensor, Tensor, Tensor, Tensor, Tensor) + +- func: _thnn_fused_gru_cell(Tensor input_gates, Tensor hidden_gates, Tensor hx, Tensor? input_bias=None, Tensor? hidden_bias=None) -> (Tensor, Tensor) + dispatch: + CUDA: _thnn_fused_gru_cell_cuda + XPU: _thnn_fused_gru_cell_xpu + autogen: _thnn_fused_gru_cell.out + +- func: _thnn_fused_gru_cell_backward(Tensor grad_hy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor) + dispatch: + CUDA: _thnn_fused_gru_cell_backward_cuda + XPU: _thnn_fused_gru_cell_backward_xpu + autogen: _thnn_fused_gru_cell_backward.out + +- func: _thnn_differentiable_gru_cell_backward(Tensor grad_hy, Tensor input_gates, Tensor hidden_gates, Tensor hx, Tensor? input_bias, Tensor? hidden_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor) + +# RNN cells and layers +- func: lstm.input(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor, Tensor) + tags: nondeterministic_seeded + +- func: lstm.data(Tensor data, Tensor batch_sizes, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor, Tensor) + tags: nondeterministic_seeded + +- func: gru.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor) + tags: nondeterministic_seeded + +- func: gru.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor) + tags: nondeterministic_seeded + +- func: rnn_tanh.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor) + tags: nondeterministic_seeded + +- func: rnn_tanh.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor) + tags: nondeterministic_seeded + +- func: rnn_relu.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor) + tags: nondeterministic_seeded + +- func: rnn_relu.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor) + tags: nondeterministic_seeded + +- func: lstm_cell(Tensor input, Tensor[] hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> (Tensor, Tensor) + +- func: gru_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor + +- func: rnn_tanh_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor + +- func: rnn_relu_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor + +# Quantized RNN layer registration has been moved to C10 dispatch in `RNN.cpp` + +# Quantized RNN layers +# - func: quantized_lstm(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first, *, ScalarType? dtype=None, bool use_dynamic=False) -> (Tensor, Tensor, Tensor) + +# - func: quantized_lstm.data(Tensor data, Tensor batch_sizes, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, *, ScalarType? dtype=None, bool use_dynamic=False) -> (Tensor, Tensor, Tensor) + +# Quantized GRU layers + +# - func: quantized_gru.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor) +# + +# - func: quantized_gru.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor) +# + +# Quantized RNN cells +- func: quantized_lstm_cell(Tensor input, Tensor[] hx, Tensor w_ih, Tensor w_hh, Tensor b_ih, Tensor b_hh, Tensor packed_ih, Tensor packed_hh, Tensor col_offsets_ih, Tensor col_offsets_hh, Scalar scale_ih, Scalar scale_hh, Scalar zero_point_ih, Scalar zero_point_hh) -> (Tensor, Tensor) + +- func: quantized_gru_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor b_ih, Tensor b_hh, Tensor packed_ih, Tensor packed_hh, Tensor col_offsets_ih, Tensor col_offsets_hh, Scalar scale_ih, Scalar scale_hh, Scalar zero_point_ih, Scalar zero_point_hh) -> Tensor + +- func: quantized_rnn_relu_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor b_ih, Tensor b_hh, Tensor packed_ih, Tensor packed_hh, Tensor col_offsets_ih, Tensor col_offsets_hh, Scalar scale_ih, Scalar scale_hh, Scalar zero_point_ih, Scalar zero_point_hh) -> Tensor + +- func: quantized_rnn_tanh_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor b_ih, Tensor b_hh, Tensor packed_ih, Tensor packed_hh, Tensor col_offsets_ih, Tensor col_offsets_hh, Scalar scale_ih, Scalar scale_hh, Scalar zero_point_ih, Scalar zero_point_hh) -> Tensor + +# PackedSequence utilities +- func: _pack_padded_sequence(Tensor input, Tensor lengths, bool batch_first) -> (Tensor, Tensor) + dispatch: + CompositeExplicitAutograd: _pack_padded_sequence + autogen: _pack_padded_sequence.out + +- func: _pack_padded_sequence_backward(Tensor grad, SymInt[] input_size, Tensor batch_sizes, bool batch_first) -> Tensor + dispatch: + CompositeImplicitAutograd: _pack_padded_sequence_backward_symint + +- func: _pad_packed_sequence(Tensor data, Tensor batch_sizes, bool batch_first, Scalar padding_value, int total_length) -> (Tensor, Tensor) + +# wrappers for legacy TH methods + +- func: set_.source_Storage(Tensor(a!) self, Storage source) -> Tensor(a!) + variants: method + device_check: NoCheck + device_guard: False + dispatch: + CPU, CUDA, Meta, MPS, XPU: set_ + autogen: set.source_Storage, set.source_Storage_out + tags: inplace_view + +- func: set_.source_Storage_storage_offset(Tensor(a!) self, Storage source, SymInt storage_offset, SymInt[] size, SymInt[] stride=[]) -> Tensor(a!) + variants: method + device_check: NoCheck + device_guard: False + dispatch: + CPU: set_storage_cpu_ + Meta: set_storage_meta__symint + CUDA: set_storage_cuda_ + MPS: set_storage_mps_ + XPU: set_storage_xpu_ + QuantizedCPU, QuantizedCUDA: set_storage_quantized_ + autogen: set.source_Storage_storage_offset, set.source_Storage_storage_offset_out + tags: inplace_view + +- func: set_.source_Tensor_storage_offset(Tensor(a!) self, Tensor source, SymInt storage_offset, SymInt[] size, SymInt[] stride=[]) -> Tensor(a!) + variants: method + device_check: NoCheck + device_guard: False + dispatch: + CompositeImplicitAutograd: set__symint + tags: inplace_view + +- func: set_.source_Tensor(Tensor(a!) self, Tensor source) -> Tensor(a!) + variants: method + device_check: NoCheck + device_guard: False + dispatch: + CPU, CUDA, Meta, MPS, XPU: set_tensor_ + autogen: set.source_Tensor, set.source_Tensor_out + tags: inplace_view + +- func: set_(Tensor(a!) self) -> Tensor(a!) + variants: method + dispatch: + CPU: set_cpu_ + CUDA: set_cuda_ + Meta: set_meta_ + MPS: set_mps_ + XPU: set_xpu_ + autogen: set, set.out + tags: inplace_view + +# Not making it CompositeImplicitAutograd because lift +# should be a primitive w.r.t. functorch + +# TODO: this should have a view annotation +# TODO: shouldn't be a method +- func: lift(Tensor self) -> Tensor + dispatch: + CompositeExplicitAutograd: lift + autogen: lift.out + +# lift_fresh is called with an argument that is guaranteed to be +# fresh (i.e., newly allocated). This is ONLY called from a +# torch.tensor call; if you FX trace a lift_fresh, you are obligated +# to convert this into a lift_fresh_copy (because FX will violate the +# freshness invariant when tracing). +- func: lift_fresh(Tensor(a) self) -> Tensor(a) + dispatch: + CompositeExplicitAutograd: lift_fresh + +# Like lift, but it clones the input. +- func: lift_fresh_copy(Tensor self) -> Tensor + tags: view_copy + dispatch: + CompositeExplicitAutogradNonFunctional: lift_fresh_copy + autogen: lift_fresh_copy.out + +- func: is_set_to(Tensor self, Tensor tensor) -> bool + variants: method + device_check: NoCheck + device_guard: False + dispatch: + CPU, CUDA, MPS, XPU: is_set_to + +- func: masked_fill_.Scalar(Tensor(a!) self, Tensor mask, Scalar value) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CPU: masked_fill__cpu + CUDA: masked_fill__cuda + QuantizedCPU: masked_fill__quantized_cpu + QuantizedCUDA: masked_fill__quantized_cuda + MPS: masked_fill__mps + XPU: masked_fill__xpu + autogen: masked_fill.Scalar_out + +- func: masked_fill.Scalar(Tensor self, Tensor mask, Scalar value) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: masked_fill + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_masked_fill + tags: pointwise + +- func: masked_fill_.Tensor(Tensor(a!) self, Tensor mask, Tensor value) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CPU: masked_fill__cpu + CUDA: masked_fill__cuda + QuantizedCPU: masked_fill__quantized_cpu + QuantizedCUDA: masked_fill__quantized_cuda + MPS: masked_fill__mps + XPU: masked_fill__xpu + autogen: masked_fill.Tensor_out + +- func: masked_fill.Tensor(Tensor self, Tensor mask, Tensor value) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: masked_fill + +- func: masked_scatter_(Tensor(a!) self, Tensor mask, Tensor source) -> Tensor(a!) + variants: method + dispatch: + CPU: masked_scatter__cpu + CUDA: masked_scatter__cuda + MPS: masked_scatter__mps + XPU: masked_scatter__xpu + autogen: masked_scatter.out + +- func: masked_scatter(Tensor self, Tensor mask, Tensor source) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: masked_scatter + tags: core + +- func: masked_scatter_backward(Tensor grad_output, Tensor mask, SymInt[] sizes) -> Tensor + dispatch: + CompositeExplicitAutograd: masked_scatter_backward_symint + +- func: _masked_softmax(Tensor self, Tensor mask, int? dim=None, int? mask_type=None) -> Tensor + dispatch: + CUDA: masked_softmax_cuda + CPU: masked_softmax_cpu + XPU: masked_softmax_xpu + autogen: _masked_softmax.out + +- func: _masked_softmax_backward(Tensor grad_output, Tensor output, Tensor mask, int? dim=None) -> Tensor + dispatch: + CUDA: masked_softmax_backward_cuda + CPU: masked_softmax_backward_cpu + XPU: masked_softmax_backward_xpu + autogen: _masked_softmax_backward.out + +- func: view(Tensor(a) self, SymInt[] size) -> Tensor(a) + variants: method + device_check: NoCheck + device_guard: False + dispatch: + CPU, CUDA, QuantizedCPU, QuantizedCUDA, MPS, MTIA, XPU: view + Meta, ZeroTensor: view_symint + MkldnnCPU: mkldnn_view + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: view_nested + tags: core + +# Warning: If you want to change the name or overload name of this +# operator, you might also want to change the `isBlockListedSchema` +# function in `torch/csrc/jit/frontend/schema_catching.cpp`. +# The name and overload name of this operator is hardcoded in that +# function in order to workaround a bug: +# https://github.com/pytorch/pytorch/issues/47964 +- func: view.dtype(Tensor(a) self, ScalarType dtype) -> Tensor(a) + variants: method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: view_dtype + +- func: put_(Tensor(a!) self, Tensor index, Tensor source, bool accumulate=False) -> Tensor(a!) + variants: method + dispatch: + CPU, CUDA, XPU: put_ + autogen: put.out + +- func: put(Tensor self, Tensor index, Tensor source, bool accumulate=False) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: put + +- func: index_add.out(Tensor self, int dim, Tensor index, Tensor source, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + precomputed: + - dim -> int dim + dispatch: + CPU: index_add_cpu_out + CUDA: index_add_cuda_out + MPS: index_add_mps_out + XPU: index_add_xpu_out + +- func: index_add_(Tensor(a!) self, int dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor(a!) + structured_delegate: index_add.out + variants: method + +- func: index_add(Tensor self, int dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor + structured_delegate: index_add.out + variants: function, method + +- func: index_reduce.out(Tensor self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + precomputed: + - dim -> int dim + dispatch: + CPU: index_reduce_cpu_out + CUDA: index_reduce_cuda_out + MPS: index_reduce_mps_out + XPU: index_reduce_xpu_out + +- func: index_reduce_(Tensor(a!) self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True) -> Tensor(a!) + structured_delegate: index_reduce.out + variants: method + +- func: index_reduce(Tensor self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True) -> Tensor + structured_delegate: index_reduce.out + variants: function, method + +- func: index_fill_.int_Scalar(Tensor(a!) self, int dim, Tensor index, Scalar value) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CPU, CUDA, MPS, XPU: index_fill_ + autogen: index_fill.int_Scalar_out + +- func: index_fill.int_Scalar(Tensor self, int dim, Tensor index, Scalar value) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: index_fill + +- func: index_fill_.int_Tensor(Tensor(a!) self, int dim, Tensor index, Tensor value) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CPU, CUDA, MPS, XPU: index_fill_ + autogen: index_fill.int_Tensor_out + +- func: index_fill.int_Tensor(Tensor self, int dim, Tensor index, Tensor value) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + dispatch: + CompositeExplicitAutograd: index_fill + +- func: scatter.src(Tensor self, int dim, Tensor index, Tensor src) -> Tensor + structured_delegate: scatter.src_out + variants: function, method + tags: core + +- func: scatter_.src(Tensor(a!) self, int dim, Tensor index, Tensor src) -> Tensor(a!) + structured_delegate: scatter.src_out + variants: method + +- func: scatter.src_out(Tensor self, int dim, Tensor index, Tensor src, *, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CPU, CUDA, MPS, XPU: scatter_src_out + +- func: scatter.value(Tensor self, int dim, Tensor index, Scalar value) -> Tensor + structured_delegate: scatter.value_out + variants: function, method + tags: core + +- func: scatter_.value(Tensor(a!) self, int dim, Tensor index, Scalar value) -> Tensor(a!) + structured_delegate: scatter.value_out + variants: method + +- func: scatter.value_out(Tensor self, int dim, Tensor index, Scalar value, *, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CPU, CUDA, MPS, XPU: scatter_value_out + +- func: scatter.reduce(Tensor self, int dim, Tensor index, Tensor src, *, str reduce) -> Tensor + structured_delegate: scatter.reduce_out + variants: function, method + +- func: scatter_.reduce(Tensor(a!) self, int dim, Tensor index, Tensor src, *, str reduce) -> Tensor(a!) + structured_delegate: scatter.reduce_out + variants: method + +- func: scatter.reduce_out(Tensor self, int dim, Tensor index, Tensor src, *, str reduce, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CPU, CUDA, MPS, XPU: scatter_reduce_out + +- func: scatter.value_reduce(Tensor self, int dim, Tensor index, Scalar value, *, str reduce) -> Tensor + structured_delegate: scatter.value_reduce_out + variants: function, method + +- func: scatter_.value_reduce(Tensor(a!) self, int dim, Tensor index, Scalar value, *, str reduce) -> Tensor(a!) + structured_delegate: scatter.value_reduce_out + variants: method + +- func: scatter.value_reduce_out(Tensor self, int dim, Tensor index, Scalar value, *, str reduce, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CPU, CUDA, MPS, XPU: scatter_value_reduce_out + +- func: scatter_add(Tensor self, int dim, Tensor index, Tensor src) -> Tensor + structured_delegate: scatter_add.out + variants: function, method + tags: core + +- func: scatter_add_(Tensor(a!) self, int dim, Tensor index, Tensor src) -> Tensor(a!) + structured_delegate: scatter_add.out + variants: method + +- func: scatter_add.out(Tensor self, int dim, Tensor index, Tensor src, *, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CPU, CUDA, MPS, XPU: scatter_add + +- func: scatter_reduce.two(Tensor self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True) -> Tensor + structured_delegate: scatter_reduce.two_out + variants: function, method + tags: core + +- func: scatter_reduce_.two(Tensor(a!) self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True) -> Tensor(a!) + structured_delegate: scatter_reduce.two_out + variants: method + +- func: scatter_reduce.two_out(Tensor self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CPU, CUDA, MPS, XPU: scatter_reduce_two + +- func: eq_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + structured_delegate: eq.Scalar_out + device_check: NoCheck # TensorIterator + variants: method + +- func: eq_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: eq.Tensor_out + device_check: NoCheck # TensorIterator + variants: method + +- func: bitwise_and.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + variants: function + dispatch: + CPU, CUDA, MPS, MTIA, XPU: bitwise_and_out + tags: pointwise + +- func: bitwise_and.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: bitwise_and_out + tags: pointwise + +- func: bitwise_and.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CompositeExplicitAutograd: bitwise_and + tags: [core, pointwise] + +- func: bitwise_and.Scalar_Tensor(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: bitwise_and + autogen: bitwise_and.Scalar_Tensor_out + tags: pointwise + +- func: bitwise_and.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + structured_delegate: bitwise_and.Tensor_out + tags: [core, pointwise] + +- func: bitwise_and_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: bitwise_and_ + tags: pointwise + +- func: bitwise_and_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: bitwise_and.Tensor_out + tags: pointwise + +- func: __and__.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + +- func: __and__.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + +- func: __iand__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + +- func: __iand__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + +- func: bitwise_or.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + variants: function + dispatch: + CPU, CUDA, MPS, MTIA, XPU: bitwise_or_out + tags: pointwise + +- func: bitwise_or.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: bitwise_or_out + tags: pointwise + +- func: bitwise_or.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CompositeExplicitAutograd: bitwise_or + tags: [core, pointwise] + +- func: bitwise_or.Scalar_Tensor(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: bitwise_or + autogen: bitwise_or.Scalar_Tensor_out + tags: pointwise + +- func: bitwise_or.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + structured_delegate: bitwise_or.Tensor_out + tags: [core, pointwise] + +- func: bitwise_or_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: bitwise_or_ + tags: pointwise + +- func: bitwise_or_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: bitwise_or.Tensor_out + tags: pointwise + +- func: __or__.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + +- func: __or__.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + +- func: __ior__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + +- func: __ior__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + +- func: bitwise_xor.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + variants: function + dispatch: + CPU, CUDA, MPS, XPU: bitwise_xor_out + tags: pointwise + +- func: bitwise_xor.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: bitwise_xor_out + tags: pointwise + +- func: bitwise_xor.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CompositeExplicitAutograd: bitwise_xor + tags: [core, pointwise] + +- func: bitwise_xor.Scalar_Tensor(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: bitwise_xor + autogen: bitwise_xor.Scalar_Tensor_out + tags: pointwise + +- func: bitwise_xor.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + structured_delegate: bitwise_xor.Tensor_out + tags: [core, pointwise] + +- func: bitwise_xor_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: bitwise_xor_ + tags: pointwise + +- func: bitwise_xor_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: bitwise_xor.Tensor_out + tags: pointwise + +- func: __xor__.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + tags: pointwise + +- func: __xor__.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + tags: pointwise + +- func: __ixor__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + tags: pointwise + +- func: __ixor__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + tags: pointwise + +- func: __lshift__.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CPU, CUDA, MPS, MTIA, XPU: __lshift__ + tags: pointwise + +- func: __lshift__.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CPU, CUDA, MPS, MTIA, XPU: __lshift__ + tags: pointwise + +- func: __ilshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CPU, CUDA, MPS, XPU: __ilshift__ + autogen: __lshift__.Scalar_out + tags: pointwise + +- func: __ilshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CPU, CUDA, MPS, XPU: __ilshift__ + autogen: __lshift__.Tensor_out + tags: pointwise + +- func: bitwise_left_shift.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: bitwise_left_shift.Tensor_out + tags: pointwise + +- func: bitwise_left_shift_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: bitwise_left_shift.Tensor_out + tags: pointwise + +- func: bitwise_left_shift.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: bitwise_left_shift_out + tags: pointwise + +- func: bitwise_left_shift.Tensor_Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CompositeExplicitAutograd: bitwise_left_shift + tags: pointwise + +- func: bitwise_left_shift_.Tensor_Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: bitwise_left_shift_ + tags: pointwise + +- func: bitwise_left_shift.Tensor_Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: bitwise_left_shift_out + tags: pointwise + +- func: bitwise_left_shift.Scalar_Tensor(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: bitwise_left_shift + autogen: bitwise_left_shift.Scalar_Tensor_out + tags: pointwise + +- func: __rshift__.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CPU, CUDA, MPS, MTIA, XPU: __rshift__ + tags: pointwise + +- func: __rshift__.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CPU, CUDA, MPS, MTIA, XPU: __rshift__ + tags: pointwise + +- func: __irshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CPU, CUDA, MPS, XPU: __irshift__ + autogen: __rshift__.Scalar_out + +- func: __irshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CPU, CUDA, MPS, XPU: __irshift__ + autogen: __rshift__.Tensor_out + +- func: bitwise_right_shift.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: bitwise_right_shift.Tensor_out + tags: pointwise + +- func: bitwise_right_shift_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: bitwise_right_shift.Tensor_out + tags: pointwise + +- func: bitwise_right_shift.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: bitwise_right_shift_out + tags: pointwise + +- func: bitwise_right_shift.Tensor_Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CompositeExplicitAutograd: bitwise_right_shift + tags: pointwise + +- func: bitwise_right_shift_.Tensor_Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: bitwise_right_shift_ + tags: pointwise + +- func: bitwise_right_shift.Tensor_Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: bitwise_right_shift_out + tags: pointwise + +- func: bitwise_right_shift.Scalar_Tensor(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CompositeExplicitAutograd: bitwise_right_shift + autogen: bitwise_right_shift.Scalar_Tensor_out + tags: pointwise + +- func: tril_(Tensor(a!) self, SymInt diagonal=0) -> Tensor(a!) + structured_delegate: tril.out + variants: method + +- func: triu_(Tensor(a!) self, SymInt diagonal=0) -> Tensor(a!) + structured_delegate: triu.out + variants: method + +- func: digamma_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: digamma.out + variants: method + tags: pointwise + +- func: lerp_.Scalar(Tensor(a!) self, Tensor end, Scalar weight) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: lerp.Scalar_out + tags: pointwise + +- func: lerp_.Tensor(Tensor(a!) self, Tensor end, Tensor weight) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: lerp.Tensor_out + tags: pointwise + +- func: addbmm_(Tensor(a!) self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) + variants: method + dispatch: + MPS: addbmm_mps_ + CPU, CUDA, XPU: addbmm_ + +- func: addbmm.out(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + dispatch: + MPS: addbmm_out_mps + CPU, CUDA, XPU: addbmm_out + +- func: addbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + variants: method, function + dispatch: + MPS: addbmm_mps + CPU, CUDA, XPU: addbmm + +- func: random_.from(Tensor(a!) self, int from, int? to, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + tags: nondeterministic_seeded + dispatch: + CPU, CUDA, MPS, XPU: random_ + Meta: random_meta_ + autogen: random.from, random.from_out + +- func: random_.to(Tensor(a!) self, int to, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator + tags: nondeterministic_seeded + variants: method + dispatch: + CPU, CUDA, MPS, XPU: random_ + Meta: random_meta_ + autogen: random.to, random.to_out + +- func: random_(Tensor(a!) self, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator + tags: nondeterministic_seeded + variants: method + dispatch: + CPU, CUDA, MPS, XPU: random_ + Meta: random_meta_ + autogen: random, random.out + +- func: uniform_(Tensor(a!) self, float from=0, float to=1, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator + tags: nondeterministic_seeded + variants: method + dispatch: + CPU, CUDA, MPS, XPU: uniform_ + Meta: uniform_meta_ + autogen: uniform, uniform.out + +- func: cauchy_(Tensor(a!) self, float median=0, float sigma=1, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + tags: nondeterministic_seeded + dispatch: + CPU, CUDA, MPS, XPU: cauchy_ + autogen: cauchy, cauchy.out + +- func: log_normal_(Tensor(a!) self, float mean=1, float std=2, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator + tags: nondeterministic_seeded + variants: method + dispatch: + CPU, CUDA, MPS, XPU: log_normal_ + autogen: log_normal, log_normal.out + +- func: exponential_(Tensor(a!) self, float lambd=1, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator + tags: nondeterministic_seeded + variants: method + dispatch: + CPU, CUDA, MPS, XPU: exponential_ + autogen: exponential, exponential.out + +- func: geometric_(Tensor(a!) self, float p, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator + tags: nondeterministic_seeded + variants: method + dispatch: + CPU, CUDA, MPS, XPU: geometric_ + + # wrappers for TH functions + autogen: geometric, geometric.out + +- func: diag.out(Tensor self, int diagonal=0, *, Tensor(a!) out) -> Tensor(a!) + +- func: diag(Tensor self, int diagonal=0) -> Tensor + variants: method, function + +- func: cross.out(Tensor self, Tensor other, int? dim=None, *, Tensor(a!) out) -> Tensor(a!) + +- func: cross(Tensor self, Tensor other, int? dim=None) -> Tensor + variants: method, function + +- func: triu.out(Tensor self, SymInt diagonal=0, *, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU: triu_cpu + CUDA: triu_cuda + MPS: triu_mps_out + XPU: triu_xpu + +- func: triu(Tensor self, SymInt diagonal=0) -> Tensor + structured_delegate: triu.out + variants: method, function + +- func: tril.out(Tensor self, SymInt diagonal=0, *, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU: tril_cpu + CUDA: tril_cuda + MPS: tril_mps_out + XPU: tril_xpu + +- func: tril(Tensor self, SymInt diagonal=0) -> Tensor + structured_delegate: tril.out + variants: method, function + +- func: tril_indices(int row, int col, int offset=0, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CPU: tril_indices_cpu + CUDA: tril_indices_cuda + MPS: tril_indices_mps + XPU: tril_indices_xpu + autogen: tril_indices.out + +- func: triu_indices(int row, int col, int offset=0, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CPU: triu_indices_cpu + CUDA: triu_indices_cuda + MPS: triu_indices_mps + XPU: triu_indices_xpu + autogen: triu_indices.out + +- func: trace(Tensor self) -> Tensor + variants: method, function + dispatch: + CPU: trace_cpu + CUDA: trace_cuda + MPS: trace_mps + XPU: trace_xpu + autogen: trace.out + +- func: trace_backward(Tensor grad, SymInt[] sizes) -> Tensor + variants: function + device_check: NoCheck + device_guard: False + dispatch: + CompositeImplicitAutograd: trace_backward_symint + +- func: ne.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: ne_Scalar_out + QuantizedCPU: ne_out_quantized_cpu + tags: pointwise + +- func: ne.Scalar(Tensor self, Scalar other) -> Tensor + structured_delegate: ne.Scalar_out + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + QuantizedCPU: ne_quantized_cpu + tags: [core, pointwise] + +- func: ne.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: ne_Tensor_out + QuantizedCPU: ne_out_quantized_cpu + tags: pointwise + +- func: ne.Tensor(Tensor self, Tensor other) -> Tensor + structured_delegate: ne.Tensor_out + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + QuantizedCPU: ne_quantized_cpu + tags: [core, pointwise] + +- func: ne_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + structured_delegate: ne.Scalar_out + device_check: NoCheck # TensorIterator + variants: method + +- func: ne_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: ne.Tensor_out + device_check: NoCheck # TensorIterator + variants: method + +# not_equal, alias for torch.ne +- func: not_equal.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + +- func: not_equal.Scalar(Tensor self, Scalar other) -> Tensor + variants: method, function + +- func: not_equal.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + +- func: not_equal.Tensor(Tensor self, Tensor other) -> Tensor + variants: method, function + +- func: not_equal_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + variants: method + +- func: not_equal_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + variants: method + +- func: eq.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: eq_Scalar_out + QuantizedCPU: eq_out_quantized_cpu + tags: pointwise + +- func: eq.Scalar(Tensor self, Scalar other) -> Tensor + structured_delegate: eq.Scalar_out + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + QuantizedCPU: eq_quantized_cpu + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: eq_scalar_nested + tags: [core, pointwise] + +- func: eq.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: eq_Tensor_out + QuantizedCPU: eq_out_quantized_cpu + tags: pointwise + +- func: eq.Tensor(Tensor self, Tensor other) -> Tensor + structured_delegate: eq.Tensor_out + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + QuantizedCPU: eq_quantized_cpu + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: eq_tensor_nested + tags: [core, pointwise] + +- func: ge.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: ge_Scalar_out + QuantizedCPU: ge_out_quantized_cpu + tags: pointwise + +- func: ge.Scalar(Tensor self, Scalar other) -> Tensor + structured_delegate: ge.Scalar_out + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + QuantizedCPU: ge_quantized_cpu + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: ge_scalar_nested + tags: [core, pointwise] + +- func: ge.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: ge_Tensor_out + QuantizedCPU: ge_out_quantized_cpu + tags: pointwise + +- func: ge.Tensor(Tensor self, Tensor other) -> Tensor + structured_delegate: ge.Tensor_out + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + QuantizedCPU: ge_quantized_cpu + tags: [core, pointwise] + +- func: ge_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + structured_delegate: ge.Scalar_out + device_check: NoCheck # TensorIterator + variants: method + +- func: ge_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: ge.Tensor_out + device_check: NoCheck # TensorIterator + variants: method + +# greater_equal, alias for torch.ge +- func: greater_equal.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + +- func: greater_equal.Scalar(Tensor self, Scalar other) -> Tensor + variants: method, function + +- func: greater_equal.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + +- func: greater_equal.Tensor(Tensor self, Tensor other) -> Tensor + variants: method, function + +- func: greater_equal_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + variants: method + +- func: greater_equal_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + variants: method + +- func: le.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: le_Scalar_out + QuantizedCPU: le_out_quantized_cpu + tags: pointwise + +- func: le.Scalar(Tensor self, Scalar other) -> Tensor + structured_delegate: le.Scalar_out + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + QuantizedCPU: le_quantized_cpu + tags: [core, pointwise] + +- func: le.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: le_Tensor_out + QuantizedCPU: le_out_quantized_cpu + tags: pointwise + +- func: le.Tensor(Tensor self, Tensor other) -> Tensor + structured_delegate: le.Tensor_out + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + QuantizedCPU: le_quantized_cpu + tags: [core, pointwise] + +- func: le_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + structured_delegate: le.Scalar_out + device_check: NoCheck # TensorIterator + variants: method + +- func: le_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: le.Tensor_out + device_check: NoCheck # TensorIterator + variants: method + +# less_equal, alias for torch.le +- func: less_equal.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + +- func: less_equal.Scalar(Tensor self, Scalar other) -> Tensor + variants: method, function + +- func: less_equal.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + +- func: less_equal.Tensor(Tensor self, Tensor other) -> Tensor + variants: method, function + +- func: less_equal_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + variants: method + +- func: less_equal_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + variants: method + +- func: gt.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: gt_Scalar_out + QuantizedCPU: gt_out_quantized_cpu + tags: pointwise + +- func: gt.Scalar(Tensor self, Scalar other) -> Tensor + structured_delegate: gt.Scalar_out + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + QuantizedCPU: gt_quantized_cpu + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: gt_scalar_nested + tags: [core, pointwise] + +- func: gt.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: gt_Tensor_out + QuantizedCPU: gt_out_quantized_cpu + tags: pointwise + +- func: gt.Tensor(Tensor self, Tensor other) -> Tensor + structured_delegate: gt.Tensor_out + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + QuantizedCPU: gt_quantized_cpu + tags: [core, pointwise] + +- func: gt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + structured_delegate: gt.Scalar_out + device_check: NoCheck # TensorIterator + variants: method + +- func: gt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: gt.Tensor_out + device_check: NoCheck # TensorIterator + variants: method + +# greater, alias for torch.gt +- func: greater.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + +- func: greater.Scalar(Tensor self, Scalar other) -> Tensor + variants: method, function + +- func: greater.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + +- func: greater.Tensor(Tensor self, Tensor other) -> Tensor + variants: method, function + +- func: greater_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + variants: method + +- func: greater_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + variants: method + +- func: lt.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: lt_Scalar_out + QuantizedCPU: lt_out_quantized_cpu + tags: pointwise + +- func: lt.Scalar(Tensor self, Scalar other) -> Tensor + structured_delegate: lt.Scalar_out + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + QuantizedCPU: lt_quantized_cpu + tags: [core, pointwise] + +- func: lt.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, MTIA, XPU: lt_Tensor_out + QuantizedCPU: lt_out_quantized_cpu + tags: pointwise + +- func: lt.Tensor(Tensor self, Tensor other) -> Tensor + structured_delegate: lt.Tensor_out + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + QuantizedCPU: lt_quantized_cpu + tags: [core, pointwise] + +- func: lt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + structured_delegate: lt.Scalar_out + device_check: NoCheck # TensorIterator + variants: method + +- func: lt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: lt.Tensor_out + device_check: NoCheck # TensorIterator + variants: method + +# less, alias for torch.lt +- func: less.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + +- func: less.Scalar(Tensor self, Scalar other) -> Tensor + variants: method, function + +- func: less.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + +- func: less.Tensor(Tensor self, Tensor other) -> Tensor + variants: method, function + +- func: less_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + variants: method + +- func: less_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + variants: method + +- func: take.out(Tensor self, Tensor index, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, XPU: take_out + +- func: take(Tensor self, Tensor index) -> Tensor + variants: method, function + dispatch: + CPU, CUDA, XPU: take + +- func: take_along_dim.out(Tensor self, Tensor indices, int? dim=None, *, Tensor(a!) out) -> Tensor(a!) + +- func: take_along_dim(Tensor self, Tensor indices, int? dim=None) -> Tensor + variants: method, function + +- func: index_select.out(Tensor self, int dim, Tensor index, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, QuantizedCPU: index_select_out_cpu_ + CUDA, QuantizedCUDA: index_select_out_cuda + MPS: index_select_out_mps + XPU: index_select_out_xpu + +- func: index_select(Tensor self, int dim, Tensor index) -> Tensor + variants: method, function + dispatch: + CPU: index_select_cpu_ + QuantizedCPU: index_select_quantized_cpu_ + CUDA: index_select_cuda + QuantizedCUDA: index_select_quantized_cuda + SparseCPU: index_select_sparse_cpu + SparseCUDA: index_select_sparse_cuda + SparseMPS: index_select_sparse_mps + SparseXPU: index_select_sparse_xpu + MPS: index_select_mps + XPU: index_select_xpu_ + tags: core + +- func: index_select_backward(Tensor grad, SymInt[] self_sizes, int dim, Tensor index) -> Tensor + variants: function + device_check: NoCheck + device_guard: False + dispatch: + CompositeImplicitAutograd: index_select_backward_symint + +- func: masked_select.out(Tensor self, Tensor mask, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU: masked_select_out_cpu + CUDA: masked_select_out_cuda + MPS: masked_select_out_mps + XPU: masked_select_out_xpu + tags: dynamic_output_shape + +- func: masked_select(Tensor self, Tensor mask) -> Tensor + variants: method, function + dispatch: + CPU: masked_select_cpu + CUDA: masked_select_cuda + MPS: masked_select_mps + XPU: masked_select_xpu + tags: dynamic_output_shape + +- func: masked_select_backward(Tensor grad, Tensor input, Tensor mask) -> Tensor + variants: function + device_check: NoCheck + device_guard: False + +- func: nonzero.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU: nonzero_out_cpu + CUDA: nonzero_out_cuda + MPS: nonzero_out_mps + XPU: nonzero_out_xpu + tags: dynamic_output_shape + +- func: nonzero(Tensor self) -> Tensor + variants: method, function + dispatch: + CPU: nonzero_cpu + CUDA: nonzero_cuda + MPS: nonzero_mps + XPU: nonzero_xpu + tags: [dynamic_output_shape, core] + +- func: nonzero_static.out(Tensor self, *, SymInt size, int fill_value=-1, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU: nonzero_static_out_cpu + CUDA: nonzero_static_out_cuda + MPS: nonzero_static_out_mps + XPU: nonzero_static_out_xpu + +- func: nonzero_static(Tensor self, *, SymInt size, int fill_value=-1) -> Tensor + variants: method, function + dispatch: + CPU: nonzero_static_cpu + CUDA: nonzero_static_cuda + MPS: nonzero_static_mps + XPU: nonzero_static_xpu + +- func: nonzero_numpy(Tensor self) -> Tensor[] + variants: method, function + +- func: argwhere(Tensor self) -> Tensor + variants: method, function + tags: dynamic_output_shape + +- func: gather.out(Tensor self, int dim, Tensor index, *, bool sparse_grad=False, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU, CUDA, MPS, XPU: gather_out + +- func: gather(Tensor self, int dim, Tensor index, *, bool sparse_grad=False) -> Tensor + variants: method, function + structured_delegate: gather.out + tags: core + +- func: gather_backward(Tensor grad, Tensor self, int dim, Tensor index, bool sparse_grad) -> Tensor + variants: function + device_check: NoCheck + device_guard: False + +- func: _gather_sparse_backward(Tensor self, int dim, Tensor index, Tensor grad) -> Tensor + +- func: addcmul.out(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MTIA, XPU: addcmul_out + MPS: addcmul_out_mps + tags: pointwise + +- func: addcmul(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor + structured_delegate: addcmul.out + device_check: NoCheck # TensorIterator + variants: method, function + tags: pointwise + +- func: addcmul_(Tensor(a!) self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor(a!) + structured_delegate: addcmul.out + device_check: NoCheck # TensorIterator + variants: method + tags: pointwise + +- func: addcdiv.out(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MTIA, XPU: addcdiv_out + MPS: addcdiv_out_mps + tags: pointwise + +- func: addcdiv(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor + structured_delegate: addcdiv.out + device_check: NoCheck # TensorIterator + variants: method, function + tags: pointwise + +- func: addcdiv_(Tensor(a!) self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor(a!) + structured_delegate: addcdiv.out + device_check: NoCheck # TensorIterator + variants: method + tags: pointwise + +- func: cross_entropy_loss(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100, float label_smoothing=0.0) -> Tensor + python_module: nn + dispatch: + CompositeImplicitAutograd: cross_entropy_loss_symint + +- func: triangular_solve.X(Tensor self, Tensor A, bool upper=True, bool transpose=False, bool unitriangular=False, *, Tensor(a!) X, Tensor(b!) M) -> (Tensor(a!) solution, Tensor(b!) cloned_coefficient) + structured: True + dispatch: + CPU, CUDA: triangular_solve_out + MPS: triangular_solve_mps_out + SparseCsrCPU: triangular_solve_out_sparse_csr_cpu + SparseCsrCUDA: triangular_solve_out_sparse_csr_cuda + SparseCsrXPU: triangular_solve_out_sparse_csr_xpu + +- func: triangular_solve(Tensor self, Tensor A, bool upper=True, bool transpose=False, bool unitriangular=False) -> (Tensor solution, Tensor cloned_coefficient) + structured_delegate: triangular_solve.X + variants: method, function + +- func: _linalg_check_errors(Tensor info, str api_name, *, bool is_matrix) -> () + dispatch: + CompositeExplicitAutograd: _linalg_check_errors + +- func: linalg_solve_triangular.out(Tensor self, Tensor B, *, bool upper, bool left=True, bool unitriangular=False, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + dispatch: + CPU, CUDA, XPU: linalg_solve_triangular_out + MPS: linalg_solve_triangular_mps_out + +- func: linalg_solve_triangular(Tensor self, Tensor B, *, bool upper, bool left=True, bool unitriangular=False) -> Tensor + python_module: linalg + variants: function + dispatch: + CPU, CUDA, XPU: linalg_solve_triangular + MPS: linalg_solve_triangular_mps + +- func: linalg_vander(Tensor x, *, SymInt? N=None) -> Tensor + python_module: linalg + dispatch: + CompositeImplicitAutograd: linalg_vander_symint + +- func: svd.U(Tensor self, bool some=True, bool compute_uv=True, *, Tensor(a!) U, Tensor(b!) S, Tensor(c!) V) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) V) + +- func: svd(Tensor self, bool some=True, bool compute_uv=True) -> (Tensor U, Tensor S, Tensor V) + variants: method, function + +# swapaxes, alias for transpose +- func: swapaxes(Tensor(a) self, int axis0, int axis1) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + +- func: swapaxes_(Tensor(a!) self, int axis0, int axis1) -> Tensor(a!) + variants: method + device_check: NoCheck + device_guard: False + tags: inplace_view + +# swapdims, alias for transpose +- func: swapdims(Tensor(a) self, int dim0, int dim1) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + +- func: swapdims_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!) + variants: method + device_check: NoCheck + device_guard: False + tags: inplace_view + +- func: cholesky_solve.out(Tensor self, Tensor input2, bool upper=False, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: cholesky_solve_out + +- func: cholesky_solve(Tensor self, Tensor input2, bool upper=False) -> Tensor + variants: method, function + dispatch: + CompositeExplicitAutograd: cholesky_solve + +- func: _cholesky_solve_helper(Tensor self, Tensor A, bool upper) -> Tensor + variants: function + dispatch: + CPU: _cholesky_solve_helper_cpu + CUDA: _cholesky_solve_helper_cuda + MPS: _cholesky_solve_helper_mps + autogen: _cholesky_solve_helper.out + +- func: cholesky_inverse(Tensor self, bool upper=False) -> Tensor + variants: method, function + dispatch: + CPU, CUDA, MPS: cholesky_inverse + +- func: cholesky_inverse.out(Tensor self, bool upper=False, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS: cholesky_inverse_out + +- func: geqrf.a(Tensor self, *, Tensor(a!) a, Tensor(b!) tau) -> (Tensor(a!) a, Tensor(b!) tau) + dispatch: + CPU, CUDA, MPS: geqrf_out + +- func: geqrf(Tensor self) -> (Tensor a, Tensor tau) + variants: method, function + dispatch: + CPU, CUDA, MPS: geqrf + +# orgqr, alias for linalg_householder_product +- func: orgqr(Tensor self, Tensor input2) -> Tensor + variants: method, function + +- func: orgqr.out(Tensor self, Tensor input2, *, Tensor(a!) out) -> Tensor(a!) + +- func: ormqr.out(Tensor self, Tensor input2, Tensor input3, bool left=True, bool transpose=False, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA: ormqr_out + +- func: ormqr(Tensor self, Tensor input2, Tensor input3, bool left=True, bool transpose=False) -> Tensor + variants: method, function + dispatch: + CPU, CUDA: ormqr + +- func: _lu_with_info(Tensor self, bool pivot=True, bool check_errors=True) -> (Tensor LU, Tensor pivots, Tensor info) + variants: function + +- func: lu_solve.out(Tensor self, Tensor LU_data, Tensor LU_pivots, *, Tensor(a!) out) -> Tensor(a!) + +- func: lu_solve(Tensor self, Tensor LU_data, Tensor LU_pivots) -> Tensor + variants: method, function + +# lu_unpack +- func: lu_unpack(Tensor LU_data, Tensor LU_pivots, bool unpack_data=True, bool unpack_pivots=True) -> (Tensor P, Tensor L, Tensor U) + structured_delegate: lu_unpack.out + variants: function + +- func: lu_unpack.out(Tensor LU_data, Tensor LU_pivots, bool unpack_data=True, bool unpack_pivots=True, *, Tensor(a!) P, Tensor(b!) L, Tensor(c!) U) -> (Tensor(a!) P, Tensor(b!) L, Tensor(c!) U) + variants: function + structured: True + dispatch: + CPU, CUDA, MPS: lu_unpack_out + +# TODO: remove dispatch section when porting TH CUDA to ATen +- func: multinomial.out(Tensor self, SymInt num_samples, bool replacement=False, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!) + tags: nondeterministic_seeded + dispatch: + CPU, CUDA, MPS, XPU: multinomial_out + +- func: multinomial(Tensor self, SymInt num_samples, bool replacement=False, *, Generator? generator=None) -> Tensor + variants: method, function + dispatch: + CPU, CUDA, MPS, XPU: multinomial + tags: nondeterministic_seeded + +- func: lgamma.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: lgamma_out + tags: pointwise + +- func: lgamma_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: lgamma.out + variants: method + tags: pointwise + +- func: lgamma(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: lgamma.out + variants: method, function + tags: pointwise + +- func: digamma.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: digamma_out + tags: pointwise + +- func: digamma(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: digamma.out + variants: method, function + tags: pointwise + +- func: polygamma.out(int n, Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: polygamma_out + tags: pointwise + +- func: polygamma(int n, Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: polygamma.out + variants: method, function + tags: pointwise + +- func: polygamma_(Tensor(a!) self, int n) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: polygamma_ + tags: pointwise + +- func: erfinv(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: erfinv.out + variants: method, function + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: erfinv_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: erfinv_sparse_csr + tags: pointwise + +- func: erfinv_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: erfinv.out + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: erfinv_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: erfinv_sparse_csr_ + tags: pointwise + +- func: erfinv.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: erfinv_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: erfinv_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: erfinv_sparse_csr_out + tags: pointwise + +- func: i0(Tensor self) -> Tensor + structured_delegate: i0.out + variants: function, method + tags: pointwise + +- func: i0_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: i0.out + variants: function, method + tags: pointwise + +- func: i0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: i0_out + tags: pointwise + +- func: sign(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: sign.out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sign_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sign_sparse_csr + tags: [core, pointwise] + +- func: sign_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: sign.out + variants: method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sign_sparse_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sign_sparse_csr_ + tags: pointwise + +- func: sign.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, XPU: sign_out + MPS: sign_out_mps + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: sign_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: sign_sparse_csr_out + tags: pointwise + +- func: signbit(Tensor self) -> Tensor + variants: function, method + structured_delegate: signbit.out + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: signbit_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: signbit_sparse_csr + tags: pointwise + +- func: signbit.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, XPU: signbit_out + MPS: signbit_out_mps + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: signbit_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: signbit_sparse_csr_out + tags: pointwise + +- func: dist(Tensor self, Tensor other, Scalar p=2) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CompositeExplicitAutograd: dist + autogen: dist.out + +- func: atan2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: atan2_out + tags: [core, pointwise] + +- func: atan2_(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: atan2.out + variants: method + tags: pointwise + +- func: atan2(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: atan2.out + variants: method, function + tags: [core, pointwise] +# arctan2, alias of atan2 + +- func: arctan2(Tensor self, Tensor other) -> Tensor + variants: method, function + +- func: arctan2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + +- func: arctan2_(Tensor(a!) self, Tensor other) -> Tensor(a!) + variants: method + +- func: lerp.Scalar_out(Tensor self, Tensor end, Scalar weight, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: lerp_Scalar + tags: pointwise + +- func: lerp.Tensor_out(Tensor self, Tensor end, Tensor weight, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: lerp_Tensor + tags: pointwise + +- func: lerp.Scalar(Tensor self, Tensor end, Scalar weight) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + structured_delegate: lerp.Scalar_out + tags: pointwise + +- func: lerp.Tensor(Tensor self, Tensor end, Tensor weight) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + structured_delegate: lerp.Tensor_out + tags: pointwise + +- func: histc.out(Tensor self, int bins=100, Scalar min=0, Scalar max=0, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, MPS: histogram_histc_out + CUDA: _histc_out_cuda + XPU: _histc_out_xpu + +- func: histc(Tensor self, int bins=100, Scalar min=0, Scalar max=0) -> Tensor + variants: method, function + dispatch: + CPU, MPS: histogram_histc + CUDA: _histc_cuda + XPU: _histc_xpu + +- func: histogram.bins_tensor_out(Tensor self, Tensor bins, *, Tensor? weight=None, bool density=False, Tensor(a!) hist, Tensor(b!) bin_edges) -> (Tensor(a!) hist, Tensor(b!) bin_edges) + dispatch: + CPU, MPS, XPU: histogram_out + +- func: histogram.bins_tensor(Tensor self, Tensor bins, *, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor bin_edges) + variants: method, function + dispatch: + CPU, MPS, XPU: histogram + +- func: histogram.bin_ct_out(Tensor self, int bins=100, *, float[]? range=None, Tensor? weight=None, bool density=False, Tensor(a!) hist, Tensor(b!) bin_edges) -> (Tensor(a!) hist, Tensor(b!) bin_edges) + dispatch: + CPU, MPS, XPU: histogram_out + +- func: histogram.bin_ct(Tensor self, int bins=100, *, float[]? range=None, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor bin_edges) + variants: method, function + dispatch: + CPU, MPS, XPU: histogram + +- func: _histogramdd_bin_edges(Tensor self, int[] bins, *, float[]? range=None, Tensor? weight=None, bool density=False) -> Tensor[] + dispatch: + CPU, MPS: histogramdd_bin_edges + autogen: _histogramdd_bin_edges.out + +- func: _histogramdd_from_bin_cts(Tensor self, int[] bins, *, float[]? range=None, Tensor? weight=None, bool density=False) -> Tensor + dispatch: + CPU, MPS: _histogramdd + autogen: _histogramdd_from_bin_cts.out + +- func: _histogramdd_from_bin_tensors(Tensor self, Tensor[] bins, *, Tensor? weight=None, bool density=False) -> Tensor + dispatch: + CPU, MPS: _histogramdd + autogen: _histogramdd_from_bin_tensors.out + +- func: histogramdd(Tensor self, int[] bins, float[]? range=None, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor[] bin_edges) + +- func: histogramdd.int_bins(Tensor self, int bins, float[]? range=None, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor[] bin_edges) + +- func: histogramdd.TensorList_bins(Tensor self, Tensor[] bins, float[]? range=None, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor[] bin_edges) + +- func: fmod.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CompositeExplicitAutograd: fmod_out + tags: pointwise + +- func: fmod.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CompositeExplicitAutograd: fmod + tags: [core, pointwise] + +- func: fmod_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: fmod_ + tags: pointwise + +- func: fmod.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: fmod_out + tags: pointwise + +- func: fmod.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: fmod.Tensor_out + variants: method, function + tags: [core, pointwise] + +- func: fmod_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: fmod.Tensor_out + tags: pointwise + +- func: hypot.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: hypot_out + tags: pointwise + +- func: hypot(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: hypot.out + variants: method, function + tags: pointwise + +- func: hypot_(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: hypot.out + variants: method + tags: pointwise + +- func: igamma.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: igamma_out + tags: pointwise + +- func: igamma(Tensor self, Tensor other) -> Tensor + structured_delegate: igamma.out + variants: method, function + tags: pointwise + +- func: igamma_(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: igamma.out + variants: method + tags: pointwise + +- func: igammac.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: igammac_out + tags: pointwise + +- func: igammac(Tensor self, Tensor other) -> Tensor + structured_delegate: igammac.out + variants: method, function + tags: pointwise + +- func: igammac_(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: igammac.out + variants: method + tags: pointwise + +- func: nextafter.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: nextafter_out + tags: pointwise + +- func: nextafter(Tensor self, Tensor other) -> Tensor + structured_delegate: nextafter.out + variants: method, function + tags: pointwise + +- func: nextafter_(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: nextafter.out + variants: method + tags: pointwise + +- func: remainder.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: remainder_out + tags: pointwise + +- func: remainder.Scalar(Tensor self, Scalar other) -> Tensor + variants: method, function + dispatch: + CompositeExplicitAutograd: remainder + tags: [core, pointwise] + +- func: remainder_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + variants: method + dispatch: + CompositeExplicitAutograd: remainder_ + tags: pointwise + +- func: remainder.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, MTIA, XPU: remainder_out + tags: pointwise + +- func: remainder.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: remainder.Tensor_out + variants: method, function + tags: [core, pointwise] + +- func: remainder_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: remainder.Tensor_out + variants: method + tags: pointwise + +- func: remainder.Scalar_Tensor(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CPU, CUDA, MPS, XPU: remainder + autogen: remainder.Scalar_Tensor_out + tags: pointwise + +- func: min(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CPU, CUDA, XPU: min + MPS: min_mps + QuantizedCPU: min_quantized_cpu + tags: [reduction] + +- func: min.unary_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, XPU: min_unary_out + QuantizedCPU: min_quantized_unary_out + tags: [reduction] + +- func: fmin(Tensor self, Tensor other) -> Tensor + structured_delegate: fmin.out + device_check: NoCheck # TensorIterator + variants: method, function + tags: pointwise + +- func: fmin.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, XPU: fmin_out + tags: pointwise + +- func: max(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CPU, CUDA, XPU: max + MPS: max_mps + QuantizedCPU: max_quantized_cpu + tags: [reduction] + +- func: fmax(Tensor self, Tensor other) -> Tensor + structured_delegate: fmax.out + device_check: NoCheck # TensorIterator + variants: method, function + tags: pointwise + +- func: fmax.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MPS, XPU: fmax_out + tags: pointwise + +- func: maximum(Tensor self, Tensor other) -> Tensor + structured_delegate: maximum.out + device_check: NoCheck # TensorIterator + variants: method, function + tags: [core, pointwise] + +- func: maximum.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MTIA, MPS, XPU: maximum_out + tags: pointwise + +# binary max, alias of maximum +# NOTE: max is not an alias for maximum, since there is also unary max +- func: max.other(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + tags: pointwise + +- func: max.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + tags: pointwise + +- func: max.unary_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, XPU: max_unary_out + QuantizedCPU: max_quantized_unary_out + tags: [reduction] + +- func: minimum(Tensor self, Tensor other) -> Tensor + structured_delegate: minimum.out + device_check: NoCheck # TensorIterator + variants: method, function + tags: [core, pointwise] + +- func: minimum.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA, MTIA, MPS, XPU: minimum_out + tags: pointwise + +# binary min, alias for minimum +# NOTE: min is not an alias for minimum, since there is also unary min +- func: min.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + tags: pointwise + +- func: min.other(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + tags: pointwise + +- func: quantile(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor + variants: method, function + +- func: quantile.out(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!) + +- func: quantile.scalar(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor + variants: method, function + +- func: quantile.scalar_out(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!) + +- func: nanquantile(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor + variants: method, function + +- func: nanquantile.out(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!) + +- func: nanquantile.scalar(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor + variants: method, function + +- func: nanquantile.scalar_out(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!) + +- func: sort.values(Tensor self, int dim=-1, bool descending=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) + device_check: NoCheck # TensorIterator + dispatch: + CompositeExplicitAutograd: sort_out + +- func: sort.values_stable(Tensor self, *, bool? stable, int dim=-1, bool descending=False, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) + structured: True + dispatch: + CPU, CUDA, XPU: sort_stable_out + MPS: sort_stable_out_mps + +- func: sort(Tensor self, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices) + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CompositeExplicitAutograd: sort + tags: core + +- func: sort.stable(Tensor self, *, bool? stable, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices) + structured_delegate: sort.values_stable + variants: method, function + dispatch: + QuantizedCPU: sort_quantized_cpu_stable + +- func: msort.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + +- func: msort(Tensor self) -> Tensor + variants: method, function + +- func: argsort(Tensor self, int dim=-1, bool descending=False) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + +- func: argsort.stable(Tensor self, *, bool stable, int dim=-1, bool descending=False) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + +- func: argsort.stable_out(Tensor self, *, bool stable, int dim=-1, bool descending=False, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function + +- func: topk.values(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) + structured: True + dispatch: + CPU: topk_out_cpu + CUDA: topk_out_cuda + MPS: topk_out_mps + XPU: topk_out_xpu + +- func: topk(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True) -> (Tensor values, Tensor indices) + variants: method, function + structured_delegate: topk.values + dispatch: + QuantizedCPU: topk_quantized_cpu + tags: core + +- func: all(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: all.all_out + variants: method, function + tags: reduction + +- func: all.all_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + structured: True + dispatch: + CPU, CUDA, MPS, XPU: all_all_out + MTIA: all_all_out_mtia + tags: reduction + +- func: any(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: any.all_out + variants: method, function + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: any_sparse + tags: [core, reduction] + +- func: any.all_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + structured: True + dispatch: + CPU, CUDA, MPS, XPU: any_all_out + tags: reduction + +- func: renorm.out(Tensor self, Scalar p, int dim, Scalar maxnorm, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + dispatch: + CPU, CUDA, XPU: renorm_out + MPS: renorm_out_mps + +- func: renorm(Tensor self, Scalar p, int dim, Scalar maxnorm) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + structured_delegate: renorm.out + +- func: renorm_(Tensor(a!) self, Scalar p, int dim, Scalar maxnorm) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: renorm.out + +- func: unfold(Tensor(a) self, int dimension, int size, int step) -> Tensor(a) + variants: method + device_check: NoCheck + device_guard: False + dispatch: + CPU, CUDA, Meta, MPS, MTIA, XPU: unfold + QuantizedCPU, QuantizedCUDA: unfold + +- func: unfold_backward(Tensor grad_in, SymInt[] input_sizes, int dim, int size, int step) -> Tensor + variants: function + dispatch: + CPU, CUDA, MPS, XPU: unfold_backward + autogen: unfold_backward.out + +- func: equal(Tensor self, Tensor other) -> bool + tags: [data_dependent_output, pointwise] + variants: method, function + dispatch: + CPU: cpu_equal + CUDA: cuda_equal + MPS: mps_equal + XPU: xpu_equal + QuantizedCPU: equal_quantized_cpu + +- func: pow.Tensor_Tensor_out(Tensor self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, XPU: pow_Tensor_Tensor_out + MPS: pow_tensor_tensor_out_mps + tags: pointwise + +- func: pow.Tensor_Tensor(Tensor self, Tensor exponent) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: pow.Tensor_Tensor_out + variants: method, function + tags: [core, pointwise] + +- func: pow.Scalar_out(Scalar self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + dispatch: + CPU, CUDA, XPU: pow_Scalar_out + MPS: pow_Scalar_out_mps + tags: pointwise + +- func: pow.Scalar(Scalar self, Tensor exponent) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: pow.Scalar_out + tags: [core, pointwise] + +- func: pow.Tensor_Scalar_out(Tensor self, Scalar exponent, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: pow_Tensor_Scalar_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: pow_out_sparse_scalar + tags: pointwise + +- func: pow.Tensor_Scalar(Tensor self, Scalar exponent) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: pow.Tensor_Scalar_out + variants: function, method + dispatch: + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: pow_sparse_scalar + tags: [core, pointwise] + +- func: pow_.Scalar(Tensor(a!) self, Scalar exponent) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: pow.Tensor_Scalar_out + variants: method + tags: pointwise + +- func: pow_.Tensor(Tensor(a!) self, Tensor exponent) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: pow.Tensor_Tensor_out + variants: method + tags: pointwise + +- func: float_power.Tensor_Tensor_out(Tensor self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!) + tags: pointwise + +- func: float_power.Tensor_Tensor(Tensor self, Tensor exponent) -> Tensor + variants: function, method + tags: pointwise + +- func: float_power.Scalar_out(Scalar self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!) + tags: pointwise + +- func: float_power.Scalar(Scalar self, Tensor exponent) -> Tensor + tags: pointwise + +- func: float_power.Tensor_Scalar_out(Tensor self, Scalar exponent, *, Tensor(a!) out) -> Tensor(a!) + tags: pointwise + +- func: float_power.Tensor_Scalar(Tensor self, Scalar exponent) -> Tensor + variants: function, method + tags: pointwise + +- func: float_power_.Scalar(Tensor(a!) self, Scalar exponent) -> Tensor(a!) + variants: method + tags: pointwise + +- func: float_power_.Tensor(Tensor(a!) self, Tensor exponent) -> Tensor(a!) + variants: method + tags: pointwise + +- func: normal_(Tensor(a!) self, float mean=0, float std=1, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator + tags: nondeterministic_seeded + variants: method + dispatch: + CPU, CUDA, MPS, XPU: normal_ + Meta: normal_meta_ + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: normal_sparse_csr_ + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: normal_nested_ + autogen: normal.out + +# Only used by the functionalization pass. +# Normally, the codegen would be able to generate a normal() NativeFunction, +# but we can't due to overload ambiguity with normal.Tensor_float. +- func: normal_functional(Tensor self, float mean=0, float std=1, *, Generator? generator=None) -> Tensor + device_check: NoCheck # TensorIterator + tags: nondeterministic_seeded + dispatch: + CompositeExplicitAutograd: normal_functional + +- func: normal.Tensor_float_out(Tensor mean, float std=1, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!) + tags: nondeterministic_seeded + dispatch: + CPU, CUDA, MPS, XPU: normal_out + Meta: normal_out_meta + +- func: normal.Tensor_float(Tensor mean, float std=1, *, Generator? generator=None) -> Tensor + dispatch: + CPU, CUDA, MPS, XPU: normal + Meta: normal_meta + tags: nondeterministic_seeded + +- func: normal.float_Tensor_out(float mean, Tensor std, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: normal_out + Meta: normal_out_meta + tags: nondeterministic_seeded + +- func: normal.float_Tensor(float mean, Tensor std, *, Generator? generator=None) -> Tensor + dispatch: + CPU, CUDA, MPS, XPU: normal + Meta: normal_meta + tags: nondeterministic_seeded + +- func: normal.Tensor_Tensor_out(Tensor mean, Tensor std, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: normal_out + Meta: normal_out_meta + tags: nondeterministic_seeded + +- func: normal.Tensor_Tensor(Tensor mean, Tensor std, *, Generator? generator=None) -> Tensor + dispatch: + CPU, CUDA, MPS, XPU: normal + Meta: normal_meta + tags: nondeterministic_seeded + +- func: normal.float_float(float mean, float std, SymInt[] size, *, Generator? generator=None, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: normal + tags: nondeterministic_seeded + +- func: normal.float_float_out(float mean, float std, SymInt[] size, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: normal_out + tags: nondeterministic_seeded + +- func: alias(Tensor(a) self) -> Tensor(a) + variants: method, function + dispatch: + CompositeExplicitAutograd: alias + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: alias_nested + tags: core + +- func: _amp_foreach_non_finite_check_and_unscale_(Tensor(a!)[] self, Tensor(b!) found_inf, Tensor inv_scale) -> () + variants: function + dispatch: + CUDA: _amp_foreach_non_finite_check_and_unscale_cuda_ + CPU: _amp_foreach_non_finite_check_and_unscale_cpu_ + MPS: _amp_foreach_non_finite_check_and_unscale_mps_ + XPU: _amp_foreach_non_finite_check_and_unscale_xpu_ + autogen: _amp_foreach_non_finite_check_and_unscale, _amp_foreach_non_finite_check_and_unscale.out + +- func: _amp_update_scale_(Tensor(a!) self, Tensor(b!) growth_tracker, Tensor found_inf, float scale_growth_factor, float scale_backoff_factor, int growth_interval) -> Tensor(a!) + variants: function + dispatch: + CUDA: _amp_update_scale_cuda_ + CPU: _amp_update_scale_cpu_ + MPS: _amp_update_scale_mps_ + XPU: _amp_update_scale_xpu_ + autogen: _amp_update_scale, _amp_update_scale.out + + #- func: _cat(Tensor[] tensors, int dim=0) -> Tensor + #dispatch: + #CPU: _cat_cpu + #CUDA: cat_cuda + #MPS: cat_mps + #QuantizedCPU: cat_quantized_cpu + + #- func: _cat.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!) + #dispatch: + #CPU: _cat_out_cpu + #CUDA: cat_out_cuda + #QuantizedCPU: cat_out_quantized_cpu + +- func: _foreach_add.Scalar(Tensor[] self, Scalar scalar) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_add_scalar_kernel_slow + CUDA: foreach_tensor_add_scalar_kernel_cuda + XPU: foreach_tensor_add_scalar_kernel_xpu + +- func: _foreach_add_.Scalar(Tensor(a!)[] self, Scalar scalar) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_add_scalar_kernel_slow_ + CUDA: foreach_tensor_add_scalar_kernel_cuda_ + MTIA: foreach_tensor_add_scalar_kernel_mtia_ + XPU: foreach_tensor_add_scalar_kernel_xpu_ + autogen: _foreach_add.Scalar_out + +- func: _foreach_add.List(Tensor[] self, Tensor[] other, *, Scalar alpha=1) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_add_list_kernel_slow + CUDA: foreach_tensor_add_list_kernel_cuda + MTIA: foreach_tensor_add_list_kernel_mtia + XPU: foreach_tensor_add_list_kernel_xpu + +- func: _foreach_add_.List(Tensor(a!)[] self, Tensor[] other, *, Scalar alpha=1) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_add_list_kernel_slow_ + CUDA: foreach_tensor_add_list_kernel_cuda_ + MTIA: foreach_tensor_add_list_kernel_mtia_ + XPU: foreach_tensor_add_list_kernel_xpu_ + autogen: _foreach_add.List_out + +- func: _foreach_add.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_add_scalarlist_kernel_slow + CUDA: foreach_tensor_add_scalarlist_kernel_cuda + XPU: foreach_tensor_add_scalarlist_kernel_xpu + +- func: _foreach_add_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_add_scalarlist_kernel_slow_ + CUDA: foreach_tensor_add_scalarlist_kernel_cuda_ + XPU: foreach_tensor_add_scalarlist_kernel_xpu_ + autogen: _foreach_add.ScalarList_out + +- func: _foreach_add.Tensor(Tensor[] self, Tensor other, *, Scalar alpha=1) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_add_tensor_kernel_slow + CUDA: foreach_tensor_add_tensor_kernel_cuda + XPU: foreach_tensor_add_tensor_kernel_xpu + +- func: _foreach_add_.Tensor(Tensor(a!)[] self, Tensor other, *, Scalar alpha=1) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_add_tensor_kernel_slow_ + CUDA: foreach_tensor_add_tensor_kernel_cuda_ + MTIA: foreach_tensor_add_tensor_kernel_mtia_ + XPU: foreach_tensor_add_tensor_kernel_xpu_ + autogen: _foreach_add.Tensor_out + +- func: _foreach_sub.Scalar(Tensor[] self, Scalar scalar) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sub_scalar_kernel_slow + CUDA: foreach_tensor_sub_scalar_kernel_cuda + XPU: foreach_tensor_sub_scalar_kernel_xpu + +- func: _foreach_sub_.Scalar(Tensor(a!)[] self, Scalar scalar) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sub_scalar_kernel_slow_ + CUDA: foreach_tensor_sub_scalar_kernel_cuda_ + XPU: foreach_tensor_sub_scalar_kernel_xpu_ + autogen: _foreach_sub.Scalar_out + +- func: _foreach_sub.List(Tensor[] self, Tensor[] other, *, Scalar alpha=1) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sub_list_kernel_slow + CUDA: foreach_tensor_sub_list_kernel_cuda + XPU: foreach_tensor_sub_list_kernel_xpu + +- func: _foreach_sub_.List(Tensor(a!)[] self, Tensor[] other, *, Scalar alpha=1) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sub_list_kernel_slow_ + CUDA: foreach_tensor_sub_list_kernel_cuda_ + XPU: foreach_tensor_sub_list_kernel_xpu_ + autogen: _foreach_sub.List_out + +- func: _foreach_sub.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sub_scalarlist_kernel_slow + CUDA: foreach_tensor_sub_scalarlist_kernel_cuda + XPU: foreach_tensor_sub_scalarlist_kernel_xpu + +- func: _foreach_sub_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sub_scalarlist_kernel_slow_ + CUDA: foreach_tensor_sub_scalarlist_kernel_cuda_ + XPU: foreach_tensor_sub_scalarlist_kernel_xpu_ + autogen: _foreach_sub.ScalarList_out + +- func: _foreach_mul.Scalar(Tensor[] self, Scalar scalar) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_mul_scalar_kernel_slow + CUDA: foreach_tensor_mul_scalar_kernel_cuda + XPU: foreach_tensor_mul_scalar_kernel_xpu + +- func: _foreach_mul_.Scalar(Tensor(a!)[] self, Scalar scalar) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_mul_scalar_kernel_slow_ + CUDA: foreach_tensor_mul_scalar_kernel_cuda_ + MTIA: foreach_tensor_mul_scalar_kernel_mtia_ + XPU: foreach_tensor_mul_scalar_kernel_xpu_ + autogen: _foreach_mul.Scalar_out + +- func: _foreach_mul.List(Tensor[] self, Tensor[] other) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_mul_list_kernel_slow + CUDA: foreach_tensor_mul_list_kernel_cuda + MTIA: foreach_tensor_mul_list_kernel_mtia + XPU: foreach_tensor_mul_list_kernel_xpu + +- func: _foreach_mul_.List(Tensor(a!)[] self, Tensor[] other) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_mul_list_kernel_slow_ + CUDA: foreach_tensor_mul_list_kernel_cuda_ + MTIA: foreach_tensor_mul_list_kernel_mtia_ + XPU: foreach_tensor_mul_list_kernel_xpu_ + autogen: _foreach_mul.List_out + +- func: _foreach_mul.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_mul_scalarlist_kernel_slow + CUDA: foreach_tensor_mul_scalarlist_kernel_cuda + XPU: foreach_tensor_mul_scalarlist_kernel_xpu + +- func: _foreach_mul_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_mul_scalarlist_kernel_slow_ + CUDA: foreach_tensor_mul_scalarlist_kernel_cuda_ + XPU: foreach_tensor_mul_scalarlist_kernel_xpu_ + autogen: _foreach_mul.ScalarList_out + +- func: _foreach_mul.Tensor(Tensor[] self, Tensor other) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_mul_tensor_kernel_slow + CUDA: foreach_tensor_mul_tensor_kernel_cuda + MTIA: foreach_tensor_mul_tensor_kernel_mtia + XPU: foreach_tensor_mul_tensor_kernel_xpu + +- func: _foreach_mul_.Tensor(Tensor(a!)[] self, Tensor other) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_mul_tensor_kernel_slow_ + CUDA: foreach_tensor_mul_tensor_kernel_cuda_ + MTIA: foreach_tensor_mul_tensor_kernel_mtia_ + XPU: foreach_tensor_mul_tensor_kernel_xpu_ + autogen: _foreach_mul.Tensor_out + +- func: _foreach_div.Scalar(Tensor[] self, Scalar scalar) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_div_scalar_kernel_slow + CUDA: foreach_tensor_div_scalar_kernel_cuda + XPU: foreach_tensor_div_scalar_kernel_xpu + +- func: _foreach_div_.Scalar(Tensor(a!)[] self, Scalar scalar) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_div_scalar_kernel_slow_ + CUDA: foreach_tensor_div_scalar_kernel_cuda_ + XPU: foreach_tensor_div_scalar_kernel_xpu_ + autogen: _foreach_div.Scalar_out + +- func: _foreach_div.List(Tensor[] self, Tensor[] other) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_div_list_kernel_slow + CUDA: foreach_tensor_div_list_kernel_cuda + MTIA: foreach_tensor_div_list_kernel_mtia + XPU: foreach_tensor_div_list_kernel_xpu + +- func: _foreach_div_.List(Tensor(a!)[] self, Tensor[] other) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_div_list_kernel_slow_ + CUDA: foreach_tensor_div_list_kernel_cuda_ + MTIA: foreach_tensor_div_list_kernel_mtia_ + XPU: foreach_tensor_div_list_kernel_xpu_ + autogen: _foreach_div.List_out + +- func: _foreach_div.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_div_scalarlist_kernel_slow + CUDA: foreach_tensor_div_scalarlist_kernel_cuda + XPU: foreach_tensor_div_scalarlist_kernel_xpu + +- func: _foreach_div_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_div_scalarlist_kernel_slow_ + CUDA: foreach_tensor_div_scalarlist_kernel_cuda_ + XPU: foreach_tensor_div_scalarlist_kernel_xpu_ + autogen: _foreach_div.ScalarList_out + +- func: _foreach_div.Tensor(Tensor[] self, Tensor other) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_div_tensor_kernel_slow + CUDA: foreach_tensor_div_tensor_kernel_cuda + MTIA: foreach_tensor_div_tensor_kernel_mtia + XPU: foreach_tensor_div_tensor_kernel_xpu + +- func: _foreach_div_.Tensor(Tensor(a!)[] self, Tensor other) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_div_tensor_kernel_slow_ + CUDA: foreach_tensor_div_tensor_kernel_cuda_ + MTIA: foreach_tensor_div_tensor_kernel_mtia_ + XPU: foreach_tensor_div_tensor_kernel_xpu_ + autogen: _foreach_div.Tensor_out + +- func: _foreach_clamp_max.Scalar(Tensor[] self, Scalar scalar) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_max_scalar_kernel_slow + CUDA: foreach_tensor_clamp_max_scalar_kernel_cuda + XPU: foreach_tensor_clamp_max_scalar_kernel_xpu + +- func: _foreach_clamp_max_.Scalar(Tensor(a!)[] self, Scalar scalar) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_max_scalar_kernel_slow_ + CUDA: foreach_tensor_clamp_max_scalar_kernel_cuda_ + XPU: foreach_tensor_clamp_max_scalar_kernel_xpu_ + autogen: _foreach_clamp_max.Scalar_out + +- func: _foreach_clamp_max.List(Tensor[] self, Tensor[] other) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_max_list_kernel_slow + CUDA: foreach_tensor_clamp_max_list_kernel_cuda + XPU: foreach_tensor_clamp_max_list_kernel_xpu + +- func: _foreach_clamp_max_.List(Tensor(a!)[] self, Tensor[] other) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_max_list_kernel_slow_ + CUDA: foreach_tensor_clamp_max_list_kernel_cuda_ + XPU: foreach_tensor_clamp_max_list_kernel_xpu_ + autogen: _foreach_clamp_max.List_out + +- func: _foreach_clamp_max.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_max_scalarlist_kernel_slow + CUDA: foreach_tensor_clamp_max_scalarlist_kernel_cuda + XPU: foreach_tensor_clamp_max_scalarlist_kernel_xpu + +- func: _foreach_clamp_max_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_max_scalarlist_kernel_slow_ + CUDA: foreach_tensor_clamp_max_scalarlist_kernel_cuda_ + XPU: foreach_tensor_clamp_max_scalarlist_kernel_xpu_ + autogen: _foreach_clamp_max.ScalarList_out + +- func: _foreach_clamp_min.Scalar(Tensor[] self, Scalar scalar) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_min_scalar_kernel_slow + CUDA: foreach_tensor_clamp_min_scalar_kernel_cuda + XPU: foreach_tensor_clamp_min_scalar_kernel_xpu + +- func: _foreach_clamp_min_.Scalar(Tensor(a!)[] self, Scalar scalar) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_min_scalar_kernel_slow_ + CUDA: foreach_tensor_clamp_min_scalar_kernel_cuda_ + XPU: foreach_tensor_clamp_min_scalar_kernel_xpu_ + autogen: _foreach_clamp_min.Scalar_out + +- func: _foreach_clamp_min.List(Tensor[] self, Tensor[] other) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_min_list_kernel_slow + CUDA: foreach_tensor_clamp_min_list_kernel_cuda + XPU: foreach_tensor_clamp_min_list_kernel_xpu + +- func: _foreach_clamp_min_.List(Tensor(a!)[] self, Tensor[] other) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_min_list_kernel_slow_ + CUDA: foreach_tensor_clamp_min_list_kernel_cuda_ + XPU: foreach_tensor_clamp_min_list_kernel_xpu_ + autogen: _foreach_clamp_min.List_out + +- func: _foreach_clamp_min.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_min_scalarlist_kernel_slow + CUDA: foreach_tensor_clamp_min_scalarlist_kernel_cuda + XPU: foreach_tensor_clamp_min_scalarlist_kernel_xpu + +- func: _foreach_clamp_min_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_min_scalarlist_kernel_slow_ + CUDA: foreach_tensor_clamp_min_scalarlist_kernel_cuda_ + XPU: foreach_tensor_clamp_min_scalarlist_kernel_xpu_ + autogen: _foreach_clamp_min.ScalarList_out + +# foreach_minimum/maximum dispatches to clamp_max/min +- func: _foreach_maximum.Scalar(Tensor[] self, Scalar scalar) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_min_scalar_kernel_slow + CUDA: foreach_tensor_clamp_min_scalar_kernel_cuda + XPU: foreach_tensor_clamp_min_scalar_kernel_xpu + +- func: _foreach_maximum_.Scalar(Tensor(a!)[] self, Scalar scalar) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_min_scalar_kernel_slow_ + CUDA: foreach_tensor_clamp_min_scalar_kernel_cuda_ + MTIA: foreach_tensor_maximum_scalar_kernel_mtia_ + XPU: foreach_tensor_clamp_min_scalar_kernel_xpu_ + autogen: _foreach_maximum.Scalar_out + +# foreach_minimum/maximum dispatches to clamp_max/min +- func: _foreach_maximum.List(Tensor[] self, Tensor[] other) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_min_list_kernel_slow + CUDA: foreach_tensor_clamp_min_list_kernel_cuda + XPU: foreach_tensor_clamp_min_list_kernel_xpu + +- func: _foreach_maximum_.List(Tensor(a!)[] self, Tensor[] other) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_min_list_kernel_slow_ + CUDA: foreach_tensor_clamp_min_list_kernel_cuda_ + XPU: foreach_tensor_clamp_min_list_kernel_xpu_ + autogen: _foreach_maximum.List_out + +# foreach_minimum/maximum dispatches to clamp_max/min +- func: _foreach_maximum.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_min_scalarlist_kernel_slow + CUDA: foreach_tensor_clamp_min_scalarlist_kernel_cuda + XPU: foreach_tensor_clamp_min_scalarlist_kernel_xpu + +- func: _foreach_maximum_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_min_scalarlist_kernel_slow_ + CUDA: foreach_tensor_clamp_min_scalarlist_kernel_cuda_ + XPU: foreach_tensor_clamp_min_scalarlist_kernel_xpu_ + autogen: _foreach_maximum.ScalarList_out + +- func: _foreach_minimum.Scalar(Tensor[] self, Scalar scalar) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_max_scalar_kernel_slow + CUDA: foreach_tensor_clamp_max_scalar_kernel_cuda + XPU: foreach_tensor_clamp_max_scalar_kernel_xpu + +- func: _foreach_minimum_.Scalar(Tensor(a!)[] self, Scalar scalar) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_max_scalar_kernel_slow_ + CUDA: foreach_tensor_clamp_max_scalar_kernel_cuda_ + XPU: foreach_tensor_clamp_max_scalar_kernel_xpu_ + autogen: _foreach_minimum.Scalar_out + +- func: _foreach_minimum.List(Tensor[] self, Tensor[] other) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_max_list_kernel_slow + CUDA: foreach_tensor_clamp_max_list_kernel_cuda + XPU: foreach_tensor_clamp_max_list_kernel_xpu + +- func: _foreach_minimum_.List(Tensor(a!)[] self, Tensor[] other) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_max_list_kernel_slow_ + CUDA: foreach_tensor_clamp_max_list_kernel_cuda_ + XPU: foreach_tensor_clamp_max_list_kernel_xpu_ + autogen: _foreach_minimum.List_out + +- func: _foreach_minimum.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_max_scalarlist_kernel_slow + CUDA: foreach_tensor_clamp_max_scalarlist_kernel_cuda + XPU: foreach_tensor_clamp_max_scalarlist_kernel_xpu + +- func: _foreach_minimum_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clamp_max_scalarlist_kernel_slow_ + CUDA: foreach_tensor_clamp_max_scalarlist_kernel_cuda_ + XPU: foreach_tensor_clamp_max_scalarlist_kernel_xpu_ + autogen: _foreach_minimum.ScalarList_out + +- func: _foreach_addcdiv.Scalar(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_addcdiv_scalar_slow + CUDA: foreach_tensor_addcdiv_scalar_cuda + XPU: foreach_tensor_addcdiv_scalar_xpu + +- func: _foreach_addcdiv.ScalarList(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_addcdiv_scalarlist_slow + CUDA: foreach_tensor_addcdiv_scalarlist_cuda + XPU: foreach_tensor_addcdiv_scalarlist_xpu + +- func: _foreach_addcdiv.Tensor(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Tensor scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_addcdiv_tensor_slow + CUDA: foreach_tensor_addcdiv_tensor_cuda + XPU: foreach_tensor_addcdiv_tensor_xpu + +- func: _foreach_addcdiv_.Scalar(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_addcdiv_scalar_slow_ + CUDA: foreach_tensor_addcdiv_scalar_cuda_ + XPU: foreach_tensor_addcdiv_scalar_xpu_ + autogen: _foreach_addcdiv.Scalar_out + +- func: _foreach_addcdiv_.ScalarList(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_addcdiv_scalarlist_slow_ + CUDA: foreach_tensor_addcdiv_scalarlist_cuda_ + XPU: foreach_tensor_addcdiv_scalarlist_xpu_ + autogen: _foreach_addcdiv.ScalarList_out + +- func: _foreach_addcdiv_.Tensor(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Tensor scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_addcdiv_tensor_slow_ + CUDA: foreach_tensor_addcdiv_tensor_cuda_ + XPU: foreach_tensor_addcdiv_tensor_xpu_ + autogen: _foreach_addcdiv.Tensor_out + +- func: _foreach_addcmul.Scalar(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_addcmul_scalar_slow + CUDA: foreach_tensor_addcmul_scalar_cuda + MTIA: foreach_tensor_addcmul_scalar_mtia + XPU: foreach_tensor_addcmul_scalar_xpu + +- func: _foreach_addcmul.ScalarList(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_addcmul_scalarlist_slow + CUDA: foreach_tensor_addcmul_scalarlist_cuda + XPU: foreach_tensor_addcmul_scalarlist_xpu + +- func: _foreach_addcmul.Tensor(Tensor[] self, Tensor[] tensor1, Tensor[] tensor2, Tensor scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_addcmul_tensor_slow + CUDA: foreach_tensor_addcmul_tensor_cuda + XPU: foreach_tensor_addcmul_tensor_xpu + +- func: _foreach_addcmul_.Scalar(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_addcmul_scalar_slow_ + CUDA: foreach_tensor_addcmul_scalar_cuda_ + MTIA: foreach_tensor_addcmul_scalar_mtia_ + XPU: foreach_tensor_addcmul_scalar_xpu_ + autogen: _foreach_addcmul.Scalar_out + +- func: _foreach_addcmul_.ScalarList(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_addcmul_scalarlist_slow_ + CUDA: foreach_tensor_addcmul_scalarlist_cuda_ + XPU: foreach_tensor_addcmul_scalarlist_xpu_ + autogen: _foreach_addcmul.ScalarList_out + +- func: _foreach_addcmul_.Tensor(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Tensor scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_addcmul_tensor_slow_ + CUDA: foreach_tensor_addcmul_tensor_cuda_ + XPU: foreach_tensor_addcmul_tensor_xpu_ + autogen: _foreach_addcmul.Tensor_out + +- func: _foreach_abs(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_abs_slow + CUDA: foreach_tensor_abs_cuda + MTIA: foreach_tensor_abs_mtia + XPU: foreach_tensor_abs_xpu + +- func: _foreach_abs_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_abs_slow_ + CUDA: foreach_tensor_abs_cuda_ + MTIA: foreach_tensor_abs_mtia_ + XPU: foreach_tensor_abs_xpu_ + autogen: _foreach_abs.out + +- func: _foreach_acos(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_acos_slow + CUDA: foreach_tensor_acos_cuda + XPU: foreach_tensor_acos_xpu + +- func: _foreach_acos_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_acos_slow_ + CUDA: foreach_tensor_acos_cuda_ + XPU: foreach_tensor_acos_xpu_ + autogen: _foreach_acos.out + +- func: _foreach_asin(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_asin_slow + CUDA: foreach_tensor_asin_cuda + XPU: foreach_tensor_asin_xpu + +- func: _foreach_asin_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_asin_slow_ + CUDA: foreach_tensor_asin_cuda_ + XPU: foreach_tensor_asin_xpu_ + autogen: _foreach_asin.out + +- func: _foreach_atan(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_atan_slow + CUDA: foreach_tensor_atan_cuda + XPU: foreach_tensor_atan_xpu + +- func: _foreach_atan_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_atan_slow_ + CUDA: foreach_tensor_atan_cuda_ + XPU: foreach_tensor_atan_xpu_ + autogen: _foreach_atan.out + +- func: _foreach_ceil(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_ceil_slow + CUDA: foreach_tensor_ceil_cuda + XPU: foreach_tensor_ceil_xpu + +- func: _foreach_ceil_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_ceil_slow_ + CUDA: foreach_tensor_ceil_cuda_ + XPU: foreach_tensor_ceil_xpu_ + autogen: _foreach_ceil.out + +- func: _foreach_cos(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_cos_slow + CUDA: foreach_tensor_cos_cuda + XPU: foreach_tensor_cos_xpu + +- func: _foreach_cos_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_cos_slow_ + CUDA: foreach_tensor_cos_cuda_ + XPU: foreach_tensor_cos_xpu_ + autogen: _foreach_cos.out + +- func: _foreach_cosh(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_cosh_slow + CUDA: foreach_tensor_cosh_cuda + XPU: foreach_tensor_cosh_xpu + +- func: _foreach_cosh_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_cosh_slow_ + CUDA: foreach_tensor_cosh_cuda_ + XPU: foreach_tensor_cosh_xpu_ + autogen: _foreach_cosh.out + +- func: _foreach_erf(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_erf_slow + CUDA: foreach_tensor_erf_cuda + XPU: foreach_tensor_erf_xpu + +- func: _foreach_erf_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_erf_slow_ + CUDA: foreach_tensor_erf_cuda_ + XPU: foreach_tensor_erf_xpu_ + autogen: _foreach_erf.out + +- func: _foreach_erfc(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_erfc_slow + CUDA: foreach_tensor_erfc_cuda + XPU: foreach_tensor_erfc_xpu + +- func: _foreach_erfc_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_erfc_slow_ + CUDA: foreach_tensor_erfc_cuda_ + XPU: foreach_tensor_erfc_xpu_ + autogen: _foreach_erfc.out + +- func: _foreach_exp(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_exp_slow + CUDA: foreach_tensor_exp_cuda + XPU: foreach_tensor_exp_xpu + +- func: _foreach_exp_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_exp_slow_ + CUDA: foreach_tensor_exp_cuda_ + XPU: foreach_tensor_exp_xpu_ + autogen: _foreach_exp.out + +- func: _foreach_expm1(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_expm1_slow + CUDA: foreach_tensor_expm1_cuda + XPU: foreach_tensor_expm1_xpu + +- func: _foreach_expm1_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_expm1_slow_ + CUDA: foreach_tensor_expm1_cuda_ + XPU: foreach_tensor_expm1_xpu_ + autogen: _foreach_expm1.out + +- func: _foreach_floor(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_floor_slow + CUDA: foreach_tensor_floor_cuda + XPU: foreach_tensor_floor_xpu + +- func: _foreach_floor_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_floor_slow_ + CUDA: foreach_tensor_floor_cuda_ + XPU: foreach_tensor_floor_xpu_ + autogen: _foreach_floor.out + +- func: _foreach_frac(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_frac_slow + CUDA: foreach_tensor_frac_cuda + XPU: foreach_tensor_frac_xpu + +- func: _foreach_frac_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_frac_slow_ + CUDA: foreach_tensor_frac_cuda_ + XPU: foreach_tensor_frac_xpu_ + autogen: _foreach_frac.out + +- func: _foreach_lerp.List(Tensor[] self, Tensor[] tensors1, Tensor[] weights) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensors are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_ternary_lerp_slow + CUDA: foreach_tensor_lerp_ternary_cuda + XPU: foreach_tensor_lerp_ternary_xpu + autogen: _foreach_lerp.List_out + +- func: _foreach_lerp_.List(Tensor(a!)[] self, Tensor[] tensors1, Tensor[] weights) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensors are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_ternary_lerp_slow_ + CUDA: foreach_tensor_lerp_ternary_cuda_ + XPU: foreach_tensor_lerp_ternary_xpu_ + autogen: _foreach_lerp.List_out + +- func: _foreach_lerp.Scalar(Tensor[] self, Tensor[] tensors1, Scalar weight) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensors are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_lerp_list_kernel_slow + CUDA: foreach_tensor_lerp_list_cuda + XPU: foreach_tensor_lerp_list_xpu + autogen: _foreach_lerp.Scalar_out + +- func: _foreach_lerp_.Scalar(Tensor(a!)[] self, Tensor[] tensors1, Scalar weight) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensors are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_lerp_list_kernel_slow_ + CUDA: foreach_tensor_lerp_list_cuda_ + XPU: foreach_tensor_lerp_list_xpu_ + autogen: _foreach_lerp.Scalar_out + +- func: _foreach_lerp.ScalarList(Tensor[] self, Tensor[] tensors1, Scalar[] weight) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensors are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_lerp_scalarlist_kernel_slow + CUDA: foreach_tensor_lerp_scalarlist_cuda + XPU: foreach_tensor_lerp_scalarlist_xpu + autogen: _foreach_lerp.ScalarList_out + +- func: _foreach_lerp_.ScalarList(Tensor(a!)[] self, Tensor[] tensors1, Scalar[] weight) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensors are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_lerp_scalarlist_kernel_slow_ + CUDA: foreach_tensor_lerp_scalarlist_cuda_ + XPU: foreach_tensor_lerp_scalarlist_xpu_ + autogen: _foreach_lerp.ScalarList_out + +- func: _foreach_lgamma(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_lgamma_slow + CUDA: foreach_tensor_lgamma_cuda + XPU: foreach_tensor_lgamma_xpu + +- func: _foreach_lgamma_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_lgamma_slow_ + CUDA: foreach_tensor_lgamma_cuda_ + XPU: foreach_tensor_lgamma_xpu_ + autogen: _foreach_lgamma.out + +- func: _foreach_log(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_log_slow + CUDA: foreach_tensor_log_cuda + XPU: foreach_tensor_log_xpu + +- func: _foreach_log_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_log_slow_ + CUDA: foreach_tensor_log_cuda_ + XPU: foreach_tensor_log_xpu_ + autogen: _foreach_log.out + +- func: _foreach_log10(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_log10_slow + CUDA: foreach_tensor_log10_cuda + XPU: foreach_tensor_log10_xpu + +- func: _foreach_log10_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_log10_slow_ + CUDA: foreach_tensor_log10_cuda_ + XPU: foreach_tensor_log10_xpu_ + autogen: _foreach_log10.out + +- func: _foreach_log1p(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_log1p_slow + CUDA: foreach_tensor_log1p_cuda + XPU: foreach_tensor_log1p_xpu + +- func: _foreach_log1p_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_log1p_slow_ + CUDA: foreach_tensor_log1p_cuda_ + XPU: foreach_tensor_log1p_xpu_ + autogen: _foreach_log1p.out + +- func: _foreach_log2(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_log2_slow + CUDA: foreach_tensor_log2_cuda + XPU: foreach_tensor_log2_xpu + +- func: _foreach_log2_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_log2_slow_ + CUDA: foreach_tensor_log2_cuda_ + XPU: foreach_tensor_log2_xpu_ + autogen: _foreach_log2.out + +- func: _foreach_max(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_max_slow + CUDA: foreach_tensor_max_cuda + XPU: foreach_tensor_max_xpu + autogen: _foreach_max.out + +- func: _foreach_neg(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_neg_slow + CUDA: foreach_tensor_neg_cuda + XPU: foreach_tensor_neg_xpu + +- func: _foreach_neg_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_neg_slow_ + CUDA: foreach_tensor_neg_cuda_ + XPU: foreach_tensor_neg_xpu_ + autogen: _foreach_neg.out + +- func: _foreach_norm.Scalar(Tensor[] self, Scalar ord=2, ScalarType? dtype=None) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_norm_slow + CUDA: foreach_tensor_norm_cuda + MTIA: foreach_tensor_norm_mtia + XPU: foreach_tensor_norm_xpu + autogen: _foreach_norm.Scalar_out + +# Like _foreach_norm but returns sum(|x|^ord) without the final root +- func: _foreach_powsum.Scalar(Tensor[] self, Scalar ord=2, ScalarType? dtype=None) -> Tensor[] + device_check: NoCheck + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_powsum_slow + CUDA: foreach_tensor_powsum_cuda + autogen: _foreach_powsum.Scalar_out + +- func: _foreach_pow.List(Tensor[] self, Tensor[] exponent) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_pow_list_kernel_slow + CUDA: foreach_tensor_pow_list_kernel_cuda + XPU: foreach_tensor_pow_list_kernel_xpu + +- func: _foreach_pow.Scalar(Tensor[] self, Scalar exponent) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_pow_scalar_kernel_slow + CUDA: foreach_tensor_pow_scalar_kernel_cuda + XPU: foreach_tensor_pow_scalar_kernel_xpu + +- func: _foreach_pow.ScalarList(Tensor[] self, Scalar[] exponent) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_pow_scalarlist_kernel_slow + CUDA: foreach_tensor_pow_scalarlist_kernel_cuda + XPU: foreach_tensor_pow_scalarlist_kernel_xpu + +- func: _foreach_pow.ScalarAndTensor(Scalar self, Tensor[] exponent) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_scalar_pow_list_kernel_slow + CUDA: foreach_scalar_pow_list_kernel_cuda + XPU: foreach_scalar_pow_list_kernel_xpu + +- func: _foreach_pow_.List(Tensor(a!)[] self, Tensor[] exponent) -> () + device_check: NoCheck + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_pow_list_kernel_slow_ + CUDA: foreach_tensor_pow_list_kernel_cuda_ + XPU: foreach_tensor_pow_list_kernel_xpu_ + autogen: _foreach_pow.List_out + +- func: _foreach_pow_.Scalar(Tensor(a!)[] self, Scalar exponent) -> () + device_check: NoCheck + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_pow_scalar_kernel_slow_ + CUDA: foreach_tensor_pow_scalar_kernel_cuda_ + XPU: foreach_tensor_pow_scalar_kernel_xpu_ + autogen: _foreach_pow.Scalar_out + +- func: _foreach_pow_.ScalarList(Tensor(a!)[] self, Scalar[] exponent) -> () + device_check: NoCheck + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_pow_scalarlist_kernel_slow_ + CUDA: foreach_tensor_pow_scalarlist_kernel_cuda_ + XPU: foreach_tensor_pow_scalarlist_kernel_xpu_ + autogen: _foreach_pow.ScalarList_out + +- func: _foreach_reciprocal(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_reciprocal_slow + CUDA: foreach_tensor_reciprocal_cuda + XPU: foreach_tensor_reciprocal_xpu + +- func: _foreach_reciprocal_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_reciprocal_slow_ + CUDA: foreach_tensor_reciprocal_cuda_ + XPU: foreach_tensor_reciprocal_xpu_ + autogen: _foreach_reciprocal.out + +- func: _foreach_round(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_round_slow + CUDA: foreach_tensor_round_cuda + XPU: foreach_tensor_round_xpu + +- func: _foreach_round_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_round_slow_ + CUDA: foreach_tensor_round_cuda_ + XPU: foreach_tensor_round_xpu_ + autogen: _foreach_round.out + +- func: _foreach_rsqrt(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_rsqrt_slow + CUDA: foreach_tensor_rsqrt_cuda + XPU: foreach_tensor_rsqrt_xpu + +- func: _foreach_rsqrt_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_rsqrt_slow_ + CUDA: foreach_tensor_rsqrt_cuda_ + XPU: foreach_tensor_rsqrt_xpu_ + autogen: _foreach_rsqrt.out + +- func: _foreach_sigmoid(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sigmoid_slow + CUDA: foreach_tensor_sigmoid_cuda + XPU: foreach_tensor_sigmoid_xpu + +- func: _foreach_sigmoid_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sigmoid_slow_ + CUDA: foreach_tensor_sigmoid_cuda_ + XPU: foreach_tensor_sigmoid_xpu_ + autogen: _foreach_sigmoid.out + +- func: _foreach_sign(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sign_slow + CUDA: foreach_tensor_sign_cuda + XPU: foreach_tensor_sign_xpu + +- func: _foreach_sign_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sign_slow_ + CUDA: foreach_tensor_sign_cuda_ + XPU: foreach_tensor_sign_xpu_ + autogen: _foreach_sign.out + +- func: _foreach_sin(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sin_slow + CUDA: foreach_tensor_sin_cuda + XPU: foreach_tensor_sin_xpu + +- func: _foreach_sin_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sin_slow_ + CUDA: foreach_tensor_sin_cuda_ + XPU: foreach_tensor_sin_xpu_ + autogen: _foreach_sin.out + +- func: _foreach_sinh(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sinh_slow + CUDA: foreach_tensor_sinh_cuda + XPU: foreach_tensor_sinh_xpu + +- func: _foreach_sinh_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sinh_slow_ + CUDA: foreach_tensor_sinh_cuda_ + XPU: foreach_tensor_sinh_xpu_ + autogen: _foreach_sinh.out + +- func: _foreach_sqrt(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sqrt_slow + CUDA: foreach_tensor_sqrt_cuda + XPU: foreach_tensor_sqrt_xpu + +- func: _foreach_sqrt_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_sqrt_slow_ + CUDA: foreach_tensor_sqrt_cuda_ + MTIA: foreach_tensor_sqrt_mtia_ + XPU: foreach_tensor_sqrt_xpu_ + autogen: _foreach_sqrt.out + +- func: _foreach_tan(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_tan_slow + CUDA: foreach_tensor_tan_cuda + XPU: foreach_tensor_tan_xpu + +- func: _foreach_tan_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_tan_slow_ + CUDA: foreach_tensor_tan_cuda_ + XPU: foreach_tensor_tan_xpu_ + autogen: _foreach_tan.out + +- func: _foreach_tanh(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_tanh_slow + CUDA: foreach_tensor_tanh_cuda + XPU: foreach_tensor_tanh_xpu + +- func: _foreach_tanh_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_tanh_slow_ + CUDA: foreach_tensor_tanh_cuda_ + XPU: foreach_tensor_tanh_xpu_ + autogen: _foreach_tanh.out + +- func: _foreach_trunc(Tensor[] self) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_trunc_slow + CUDA: foreach_tensor_trunc_cuda + XPU: foreach_tensor_trunc_xpu + +- func: _foreach_trunc_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_trunc_slow_ + CUDA: foreach_tensor_trunc_cuda_ + XPU: foreach_tensor_trunc_xpu_ + autogen: _foreach_trunc.out + +- func: _foreach_zero_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_zero_slow_ + CUDA: foreach_tensor_zero_cuda_ + XPU: foreach_tensor_zero_xpu_ + autogen: _foreach_zero, _foreach_zero.out + +- func: _foreach_clone(Tensor[] self, *, MemoryFormat? memory_format=None) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_clone_slow + CUDA: foreach_tensor_clone_cuda + autogen: _foreach_clone.out + +- func: _foreach_copy_(Tensor(a!)[] self, Tensor[] src, bool non_blocking=False) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function + dispatch: + CompositeExplicitAutograd: foreach_tensor_copy_list_kernel_slow_ + CUDA: foreach_tensor_copy_list_kernel_cuda_ + MTIA: foreach_tensor_copy_list_kernel_mtia_ + XPU: foreach_tensor_copy_list_kernel_xpu_ + autogen: _foreach_copy.out + +- func: _foreach_copy(Tensor[] self, Tensor[] src, bool non_blocking=False) -> Tensor[] self_out + device_check: NoCheck + variants: function + dispatch: + CompositeExplicitAutograd: _foreach_copy + MTIA: foreach_tensor_copy_list_kernel_mtia + +- func: _foreach_mm(Tensor[] self, Tensor[] mat2) -> Tensor[] + device_check: NoCheck + variants: function + dispatch: + CompositeExplicitAutograd: _foreach_mm + +- func: bucketize.Tensor(Tensor self, Tensor boundaries, *, bool out_int32=False, bool right=False) -> Tensor + dispatch: + CPU: bucketize_cpu + CUDA: bucketize_cuda + MPS: bucketize_mps + XPU: bucketize_xpu + +- func: bucketize.Tensor_out(Tensor self, Tensor boundaries, *, bool out_int32=False, bool right=False, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU: bucketize_out_cpu + CUDA: bucketize_out_cuda + MPS: bucketize_out_mps + XPU: bucketize_out_xpu + +- func: bucketize.Scalar(Scalar self, Tensor boundaries, *, bool out_int32=False, bool right=False) -> Tensor + dispatch: + CPU: bucketize_cpu + CUDA: bucketize_cuda + MPS: bucketize_mps + XPU: bucketize_xpu + autogen: bucketize.Scalar_out + +- func: searchsorted.Tensor(Tensor sorted_sequence, Tensor self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None) -> Tensor + dispatch: + CPU: searchsorted_cpu + CUDA: searchsorted_cuda + MPS: searchsorted_mps + XPU: searchsorted_xpu + +- func: searchsorted.Tensor_out(Tensor sorted_sequence, Tensor self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU: searchsorted_out_cpu + CUDA: searchsorted_out_cuda + MPS: searchsorted_out_mps + XPU: searchsorted_out_xpu + +- func: searchsorted.Scalar(Tensor sorted_sequence, Scalar self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None) -> Tensor + dispatch: + CPU: searchsorted_cpu + CUDA: searchsorted_cuda + MPS: searchsorted_mps + XPU: searchsorted_xpu + +- func: searchsorted.Scalar_out(Tensor sorted_sequence, Scalar self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU: searchsorted_out_cpu + CUDA: searchsorted_out_cuda + MPS: searchsorted_out_mps + XPU: searchsorted_out_xpu + +- func: _convert_indices_from_coo_to_csr(Tensor self, int size, *, bool out_int32=False) -> Tensor + structured_delegate: _convert_indices_from_coo_to_csr.out + +- func: _convert_indices_from_coo_to_csr.out(Tensor self, int size, *, bool out_int32=False, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU: _convert_indices_from_coo_to_csr_structured_cpu + CUDA: _convert_indices_from_coo_to_csr_structured_cuda + XPU: _convert_indices_from_coo_to_csr_structured_xpu + +- func: _convert_indices_from_csr_to_coo(Tensor crow_indices, Tensor col_indices, *, bool out_int32=False, bool transpose=False) -> Tensor + structured_delegate: _convert_indices_from_csr_to_coo.out + +- func: _convert_indices_from_csr_to_coo.out(Tensor crow_indices, Tensor col_indices, *, bool out_int32=False, bool transpose=False, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU: _convert_indices_from_csr_to_coo_structured_cpu + CUDA: _convert_indices_from_csr_to_coo_structured_cuda + XPU: _convert_indices_from_csr_to_coo_structured_xpu + +## NN wrappers + +- func: mse_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + python_module: nn + dispatch: + CPU, CUDA, XPU: mse_loss_out + MPS: mse_loss_out_mps + +- func: mse_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: mse_loss.out + python_module: nn + +- func: mse_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU, CUDA, XPU: mse_loss_backward_out + MPS: mse_loss_backward_out_mps + +- func: mse_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction) -> Tensor + python_module: nn + dispatch: + CPU, CUDA, XPU: mse_loss_backward + MPS: mse_loss_backward_mps + +- func: l1_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor + python_module: nn + +- func: multi_margin_loss.out(Tensor self, Tensor target, Scalar p=1, Scalar margin=1, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + dispatch: + CPU: multi_margin_loss_cpu_out + CUDA: multi_margin_loss_cuda_out + XPU: multi_margin_loss_xpu_out + +- func: multi_margin_loss(Tensor self, Tensor target, Scalar p=1, Scalar margin=1, Tensor? weight=None, int reduction=Mean) -> Tensor + python_module: nn + dispatch: + CPU: multi_margin_loss_cpu + CUDA: multi_margin_loss_cuda + XPU: multi_margin_loss_xpu + +- func: multi_margin_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Scalar p, Scalar margin, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU: multi_margin_loss_cpu_backward_out + CUDA: multi_margin_loss_cuda_backward_out + XPU: multi_margin_loss_xpu_backward_out + +- func: multi_margin_loss_backward(Tensor grad_output, Tensor self, Tensor target, Scalar p, Scalar margin, Tensor? weight=None, int reduction=Mean) -> Tensor + python_module: nn + dispatch: + CPU: multi_margin_loss_cpu_backward + CUDA: multi_margin_loss_cuda_backward + XPU: multi_margin_loss_xpu_backward + +- func: multilabel_margin_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + +- func: multilabel_margin_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor + python_module: nn + +- func: multilabel_margin_loss_forward.output(Tensor self, Tensor target, int reduction, *, Tensor(a!) output, Tensor(b!) is_target) -> (Tensor(a!), Tensor(b!)) + python_module: nn + dispatch: + CPU: multilabel_margin_loss_forward_out_cpu + CUDA: multilabel_margin_loss_forward_out_cuda + XPU: multilabel_margin_loss_forward_out_xpu + +- func: multilabel_margin_loss_forward(Tensor self, Tensor target, int reduction) -> (Tensor output, Tensor is_target) + python_module: nn + dispatch: + CPU: multilabel_margin_loss_forward_cpu + CUDA: multilabel_margin_loss_forward_cuda + XPU: multilabel_margin_loss_forward_xpu + +- func: multilabel_margin_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, Tensor is_target, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU: multilabel_margin_loss_backward_cpu_out + CUDA: multilabel_margin_loss_backward_cuda_out + XPU: multilabel_margin_loss_backward_xpu_out + +- func: multilabel_margin_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, Tensor is_target) -> Tensor + python_module: nn + dispatch: + CPU: multilabel_margin_loss_backward_cpu + CUDA: multilabel_margin_loss_backward_cuda + XPU: multilabel_margin_loss_backward_xpu + +- func: nll_loss.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + +- func: nll_loss_nd(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor + python_module: nn + dispatch: + CompositeImplicitAutograd: nll_loss_nd_symint + +- func: nll_loss(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor + python_module: nn + dispatch: + CompositeImplicitAutograd: nll_loss_symint + +- func: nll_loss_forward.output(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, *, Tensor(a!) output, Tensor(b!) total_weight) -> (Tensor(a!), Tensor(b!)) + python_module: nn + structured: True + dispatch: + CPU: nll_loss_forward_out_cpu + CUDA: nll_loss_forward_out_cuda + MPS: nll_loss_forward_out_mps + XPU: nll_loss_forward_out_xpu + +- func: nll_loss_forward(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index) -> (Tensor output, Tensor total_weight) + python_module: nn + structured_delegate: nll_loss_forward.output + +- func: nll_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: nll_loss_backward_out_cpu + CUDA: nll_loss_backward_out_cuda + MPS: nll_loss_backward_out_mps + XPU: nll_loss_backward_out_xpu + +- func: nll_loss_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor + python_module: nn + structured_delegate: nll_loss_backward.grad_input + +- func: nll_loss2d.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + +- func: nll_loss2d(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, SymInt ignore_index=-100) -> Tensor + python_module: nn + dispatch: + CompositeImplicitAutograd: nll_loss2d_symint + +- func: nll_loss2d_forward.output(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, *, Tensor(a!) output, Tensor(b!) total_weight) -> (Tensor(a!), Tensor(b!)) + python_module: nn + dispatch: + CPU: nll_loss2d_forward_out_cpu + CUDA: nll_loss2d_forward_out_cuda + MPS: nll_loss2d_forward_out_mps + XPU: nll_loss2d_forward_out_xpu + +- func: nll_loss2d_forward(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index) -> (Tensor output, Tensor total_weight) + python_module: nn + dispatch: + CPU: nll_loss2d_forward_cpu + CUDA: nll_loss2d_forward_cuda + MPS: nll_loss2d_forward_mps + XPU: nll_loss2d_forward_xpu + +- func: nll_loss2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU: nll_loss2d_backward_out_cpu + CUDA: nll_loss2d_backward_out_cuda + MPS: nll_loss2d_backward_out_mps + XPU: nll_loss2d_backward_out_xpu + +- func: nll_loss2d_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor + python_module: nn + dispatch: + CPU: nll_loss2d_backward_cpu + CUDA: nll_loss2d_backward_cuda + MPS: nll_loss2d_backward_mps + XPU: nll_loss2d_backward_xpu + +- func: smooth_l1_loss.out(Tensor self, Tensor target, int reduction=Mean, float beta=1.0, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + python_module: nn + dispatch: + CPU, CUDA, XPU: smooth_l1_loss_out + MPS: smooth_l1_loss_out_mps + +- func: smooth_l1_loss(Tensor self, Tensor target, int reduction=Mean, float beta=1.0) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: smooth_l1_loss.out + python_module: nn + +- func: smooth_l1_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, float beta, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU, XPU: smooth_l1_loss_backward_out + CUDA: smooth_l1_loss_backward_out + MPS: smooth_l1_loss_backward_out_mps + +- func: smooth_l1_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, float beta) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: smooth_l1_loss_backward + +- func: huber_loss.out(Tensor self, Tensor target, int reduction=Mean, float delta=1.0, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + dispatch: + CPU, CUDA, XPU: huber_loss_out + MPS: huber_loss_out_mps + +- func: huber_loss(Tensor self, Tensor target, int reduction=Mean, float delta=1.0) -> Tensor + python_module: nn + dispatch: + CPU, CUDA, XPU: huber_loss + MPS: huber_loss_mps + +- func: huber_loss_backward.out(Tensor grad_output, Tensor self, Tensor target, int reduction, float delta, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU, CUDA, XPU: huber_loss_backward_out + MPS: huber_loss_backward_out_mps + +- func: huber_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, float delta) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: huber_loss_backward + +- func: soft_margin_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + dispatch: + CompositeExplicitAutograd: soft_margin_loss_out + +- func: soft_margin_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: soft_margin_loss + +- func: soft_margin_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CompositeExplicitAutograd: soft_margin_loss_backward_out + +- func: soft_margin_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: soft_margin_loss_backward + +- func: elu.out(Tensor self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: elu_out + +- func: elu(Tensor self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1) -> Tensor + structured_delegate: elu.out + device_check: NoCheck # TensorIterator + python_module: nn + tags: [core, pointwise] + +- func: elu_backward.grad_input(Tensor grad_output, Scalar alpha, Scalar scale, Scalar input_scale, bool is_result, Tensor self_or_result, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: elu_backward_out + +- func: elu_backward(Tensor grad_output, Scalar alpha, Scalar scale, Scalar input_scale, bool is_result, Tensor self_or_result) -> Tensor + structured_delegate: elu_backward.grad_input + python_module: nn + +- func: elu_(Tensor(a!) self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1) -> Tensor(a!) + structured_delegate: elu.out + device_check: NoCheck # TensorIterator + python_module: nn + tags: pointwise + +- func: glu.out(Tensor self, int dim=-1, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: nn + dispatch: + CPU, CUDA, XPU: glu_out + MPS: glu_out_mps + +- func: glu(Tensor self, int dim=-1) -> Tensor + structured_delegate: glu.out + device_check: NoCheck # TensorIterator + python_module: nn + +- func: glu_backward.grad_input(Tensor grad_output, Tensor self, int dim, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU: glu_backward_cpu_out + CUDA: glu_backward_cuda_out + MPS: glu_backward_mps_out + XPU: glu_backward_xpu_out + +- func: glu_backward(Tensor grad_output, Tensor self, int dim) -> Tensor + python_module: nn + dispatch: + CPU: glu_backward_cpu + CUDA: glu_backward_cuda + MPS: glu_backward_mps + XPU: glu_backward_xpu + +- func: glu_jvp(Tensor glu, Tensor x, Tensor dx, int dim) -> Tensor + python_module: nn + dispatch: + CPU, CUDA, XPU: glu_jvp + autogen: glu_jvp.out + +- func: glu_backward_jvp(Tensor grad_x, Tensor grad_glu, Tensor x, Tensor dgrad_glu, Tensor dx, int dim) -> Tensor + python_module: nn + dispatch: + CPU, CUDA, XPU: glu_backward_jvp + autogen: glu_backward_jvp.out + +- func: hardsigmoid.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: hardsigmoid_out + QuantizedCPU: hardsigmoid_out_quantized_cpu + +- func: hardsigmoid(Tensor self) -> Tensor + structured_delegate: hardsigmoid.out + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + QuantizedCPU: hardsigmoid_quantized_cpu + tags: pointwise + +- func: hardsigmoid_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: hardsigmoid.out + device_check: NoCheck # TensorIterator + python_module: nn + tags: pointwise + +- func: hardsigmoid_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: hardsigmoid_backward_out + +- func: hardsigmoid_backward(Tensor grad_output, Tensor self) -> Tensor + structured_delegate: hardsigmoid_backward.grad_input + python_module: nn + +- func: hardtanh.out(Tensor self, Scalar min_val=-1, Scalar max_val=1, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: hardtanh_out + QuantizedCPU: hardtanh_out_quantized_cpu + +- func: hardtanh(Tensor self, Scalar min_val=-1, Scalar max_val=1) -> Tensor + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: hardtanh + QuantizedCPU: hardtanh_quantized_cpu + tags: [pointwise, core] + +- func: hardtanh_backward.grad_input(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU, CUDA, XPU: hardtanh_backward_out + MPS: hardtanh_backward_out_mps + +- func: hardtanh_backward(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val) -> Tensor + python_module: nn + dispatch: + CPU, CUDA, XPU: hardtanh_backward + MPS: hardtanh_backward_mps + +- func: hardtanh_(Tensor(a!) self, Scalar min_val=-1, Scalar max_val=1) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: hardtanh_ + QuantizedCPU: hardtanh_quantized_cpu_ + tags: pointwise + +- func: hardswish.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: hardswish_out + +- func: hardswish(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: hardswish + +- func: hardswish_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: hardswish_ + +- func: hardswish_backward(Tensor grad_output, Tensor self) -> Tensor + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: hardswish_backward + autogen: hardswish_backward.out + +- func: leaky_relu.out(Tensor self, Scalar negative_slope=0.01, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: leaky_relu_out + QuantizedCPU: leaky_relu_out_quantized_cpu + +- func: leaky_relu(Tensor self, Scalar negative_slope=0.01) -> Tensor + structured_delegate: leaky_relu.out + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + QuantizedCPU: leaky_relu_quantized_cpu + tags: [core, pointwise] + +- func: leaky_relu_backward.grad_input(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: leaky_relu_backward_out + +- func: leaky_relu_backward(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result) -> Tensor + structured_delegate: leaky_relu_backward.grad_input + python_module: nn + +- func: leaky_relu_(Tensor(a!) self, Scalar negative_slope=0.01) -> Tensor(a!) + structured_delegate: leaky_relu.out + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + QuantizedCPU: leaky_relu_quantized_cpu_ + tags: pointwise + +- func: log_sigmoid.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: nn + +- func: log_sigmoid(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + python_module: nn + +- func: log_sigmoid_forward.output(Tensor self, *, Tensor(a!) output, Tensor(b!) buffer) -> (Tensor(a!), Tensor(b!)) + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + CPU: log_sigmoid_forward_out_cpu + CUDA: log_sigmoid_forward_out_cuda + MPS: log_sigmoid_forward_out_mps + XPU: log_sigmoid_forward_out_xpu + +- func: log_sigmoid_forward(Tensor self) -> (Tensor output, Tensor buffer) + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + CPU: log_sigmoid_forward_cpu + CUDA: log_sigmoid_forward_cuda + MPS: log_sigmoid_forward_mps + XPU: log_sigmoid_forward_xpu + +- func: log_sigmoid_backward.grad_input(Tensor grad_output, Tensor self, Tensor buffer, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU: log_sigmoid_backward_cpu_out + CUDA: log_sigmoid_backward_cuda_out + MPS: log_sigmoid_backward_mps_out + XPU: log_sigmoid_backward_xpu_out + +- func: log_sigmoid_backward(Tensor grad_output, Tensor self, Tensor buffer) -> Tensor + python_module: nn + dispatch: + CPU: log_sigmoid_backward_cpu + CUDA: log_sigmoid_backward_cuda + MPS: log_sigmoid_backward_mps + XPU: log_sigmoid_backward_xpu + +- func: rrelu_with_noise.out(Tensor self, Tensor(b!) noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + tags: nondeterministic_seeded + dispatch: + CPU: rrelu_with_noise_out_cpu + CUDA: rrelu_with_noise_out_cuda + XPU: rrelu_with_noise_out_xpu + +- func: rrelu_with_noise(Tensor self, Tensor(b!) noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor + python_module: nn + dispatch: + CPU: rrelu_with_noise_cpu + CUDA: rrelu_with_noise_cuda + XPU: rrelu_with_noise_xpu + tags: nondeterministic_seeded + autogen: rrelu_with_noise_functional + +- func: rrelu_with_noise_backward(Tensor grad_output, Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, bool self_is_result) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: rrelu_with_noise_backward + autogen: rrelu_with_noise_backward.out + +- func: rrelu_with_noise_(Tensor(a!) self, Tensor(b!) noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor(a!) + python_module: nn + tags: nondeterministic_seeded + dispatch: + CPU: rrelu_with_noise_cpu_ + CUDA: rrelu_with_noise_cuda_ + XPU: rrelu_with_noise_xpu_ + +- func: softplus.out(Tensor self, Scalar beta=1, Scalar threshold=20, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + CPU, CUDA, XPU: softplus_out + MPS: softplus_out_mps + +- func: softplus(Tensor self, Scalar beta=1, Scalar threshold=20) -> Tensor + structured_delegate: softplus.out + device_check: NoCheck # TensorIterator + python_module: nn + tags: pointwise + +- func: softplus_backward.grad_input(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: nn + dispatch: + CPU, CUDA, XPU: softplus_backward_out + MPS: softplus_backward_out_mps + +- func: softplus_backward(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold) -> Tensor + structured_delegate: softplus_backward.grad_input + python_module: nn + +- func: softshrink.out(Tensor self, Scalar lambd=0.5, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: softshrink_out + +- func: softshrink(Tensor self, Scalar lambd=0.5) -> Tensor + structured_delegate: softshrink.out + device_check: NoCheck # TensorIterator + python_module: nn + tags: pointwise + +- func: softshrink_backward.grad_input(Tensor grad_output, Tensor self, Scalar lambd, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: nn + dispatch: + CPU, CUDA, MPS, XPU: softshrink_backward_out + +- func: softshrink_backward(Tensor grad_output, Tensor self, Scalar lambd) -> Tensor + structured_delegate: softshrink_backward.grad_input + python_module: nn + +- func: adaptive_avg_pool2d.out(Tensor self, SymInt[2] output_size, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + dispatch: + CPU: adaptive_avg_pool2d_out_cpu + CUDA: adaptive_avg_pool2d_out_cuda + MPS: adaptive_avg_pool2d_out_mps + XPU: adaptive_avg_pool2d_out_xpu + MkldnnCPU: mkldnn_adaptive_avg_pool2d_out_stub + +- func: adaptive_avg_pool2d(Tensor self, SymInt[2] output_size) -> Tensor + python_module: nn + dispatch: + CompositeImplicitAutograd: adaptive_avg_pool2d_symint + +- func: mkldnn_adaptive_avg_pool2d(Tensor self, int[2] output_size) -> Tensor + dispatch: + MkldnnCPU: mkldnn_adaptive_avg_pool2d + +- func: mkldnn_adaptive_avg_pool2d.out(Tensor self, int[2] output_size, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + MkldnnCPU: mkldnn_adaptive_avg_pool2d_out + +- func: mkldnn_adaptive_avg_pool2d_backward(Tensor grad_output, Tensor self) -> Tensor + dispatch: + MkldnnCPU: mkldnn_adaptive_avg_pool2d_backward + autogen: mkldnn_adaptive_avg_pool2d_backward.out + +- func: _adaptive_avg_pool2d(Tensor self, SymInt[2] output_size) -> Tensor + dispatch: + CPU: adaptive_avg_pool2d_cpu + CUDA: adaptive_avg_pool2d_cuda + MPS: adaptive_avg_pool2d_mps + XPU: adaptive_avg_pool2d_xpu + QuantizedCPU: adaptive_avg_pool2d_quantized_cpu + QuantizedCUDA: adaptive_avg_pool2d_quantized_cuda + autogen: _adaptive_avg_pool2d.out + tags: core + +- func: _adaptive_avg_pool2d_backward(Tensor grad_output, Tensor self) -> Tensor + python_module: nn + dispatch: + CPU: adaptive_avg_pool2d_backward_cpu + CUDA: adaptive_avg_pool2d_backward_cuda + MPS: adaptive_avg_pool2d_backward_mps + XPU: adaptive_avg_pool2d_backward_xpu + autogen: _adaptive_avg_pool2d_backward.out + tags: core + +- func: adaptive_avg_pool3d.out(Tensor self, SymInt[3] output_size, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + dispatch: + CPU: adaptive_avg_pool3d_out_cpu + CUDA: adaptive_avg_pool3d_out_cuda + XPU: adaptive_avg_pool3d_out_xpu + QuantizedCPU: adaptive_avg_pool3d_out_quantized_cpu + +- func: adaptive_avg_pool3d(Tensor self, SymInt[3] output_size) -> Tensor + python_module: nn + dispatch: + CompositeImplicitAutograd: adaptive_avg_pool3d_symint + +- func: _adaptive_avg_pool3d(Tensor self, SymInt[3] output_size) -> Tensor + dispatch: + CPU: adaptive_avg_pool3d_cpu + CUDA: adaptive_avg_pool3d_cuda + XPU: adaptive_avg_pool3d_xpu + QuantizedCPU: adaptive_avg_pool3d_quantized_cpu + autogen: _adaptive_avg_pool3d.out + tags: core + +- func: adaptive_avg_pool3d_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU: adaptive_avg_pool3d_backward_out_cpu + CUDA: adaptive_avg_pool3d_backward_out_cuda + XPU: adaptive_avg_pool3d_backward_out_xpu + +- func: _adaptive_avg_pool3d_backward(Tensor grad_output, Tensor self) -> Tensor + python_module: nn + dispatch: + CPU: adaptive_avg_pool3d_backward_cpu + CUDA: adaptive_avg_pool3d_backward_cuda + XPU: adaptive_avg_pool3d_backward_xpu + autogen: _adaptive_avg_pool3d_backward.out + +# Return: (Tensor output, Tensor indices) +- func: adaptive_max_pool2d.out(Tensor self, int[2] output_size, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) + python_module: nn + structured: True + dispatch: + CPU: adaptive_max_pool2d_out_cpu + CUDA: adaptive_max_pool2d_out_cuda + MPS: adaptive_max_pool2d_out_mps + XPU: adaptive_max_pool2d_out_xpu + +# Return: (Tensor output, Tensor indices) +- func: adaptive_max_pool2d(Tensor self, int[2] output_size) -> (Tensor, Tensor) + python_module: nn + structured_delegate: adaptive_max_pool2d.out + +- func: adaptive_max_pool2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: adaptive_max_pool2d_backward_out_cpu + CUDA: adaptive_max_pool2d_backward_out_cuda + MPS: adaptive_max_pool2d_backward_out_mps + XPU: adaptive_max_pool2d_backward_out_xpu + +- func: adaptive_max_pool2d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor + python_module: nn + structured_delegate: adaptive_max_pool2d_backward.grad_input + +# Return: (Tensor output, Tensor indices) +- func: adaptive_max_pool3d.out(Tensor self, int[3] output_size, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) + python_module: nn + structured: True + dispatch: + CPU: adaptive_max_pool3d_out_cpu + CUDA: adaptive_max_pool3d_out_cuda + XPU: adaptive_max_pool3d_out_xpu + +# Return: (Tensor output, Tensor indices) +- func: adaptive_max_pool3d(Tensor self, int[3] output_size) -> (Tensor, Tensor) + python_module: nn + structured_delegate: adaptive_max_pool3d.out + +- func: adaptive_max_pool3d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: adaptive_max_pool3d_backward_out_cpu + CUDA: adaptive_max_pool3d_backward_out_cuda + XPU: adaptive_max_pool3d_backward_out_xpu + +- func: adaptive_max_pool3d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor + python_module: nn + structured_delegate: adaptive_max_pool3d_backward.grad_input + +- func: avg_pool2d.out(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + precomputed: + - kernel_size -> int kH, int kW + - stride -> int dH, int dW + - padding -> int padH, int padW + dispatch: + CPU: avg_pool2d_out_cpu + CUDA: avg_pool2d_out_cuda + MPS: avg_pool2d_out_mps + XPU: avg_pool2d_out_xpu + MkldnnCPU: mkldnn_avg_pool2d_out + +- func: avg_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None) -> Tensor + python_module: nn + structured_delegate: avg_pool2d.out + dispatch: + MkldnnCPU: mkldnn_avg_pool2d + QuantizedCPU: avg_pool2d_quantized_cpu + tags: core + +- func: avg_pool2d_backward.grad_input(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, bool ceil_mode, bool count_include_pad, int? divisor_override, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: avg_pool2d_backward_out_cpu + CUDA: avg_pool2d_backward_out_cuda + MPS: avg_pool2d_backward_out_mps + XPU: avg_pool2d_backward_out_xpu + MkldnnCPU: mkldnn_avg_pool2d_backward_out + +- func: avg_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor + python_module: nn + structured_delegate: avg_pool2d_backward.grad_input + dispatch: + MkldnnCPU: mkldnn_avg_pool2d_backward + tags: core + +- func: avg_pool3d.out(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: avg_pool3d_out_cpu + CUDA: avg_pool3d_out_cuda + MPS: avg_pool3d_out_mps + XPU: avg_pool3d_out_xpu + MkldnnCPU: mkldnn_avg_pool3d_out + +- func: avg_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None) -> Tensor + python_module: nn + structured_delegate: avg_pool3d.out + dispatch: + MkldnnCPU: mkldnn_avg_pool3d + QuantizedCPU: avg_pool3d_quantized_cpu + tags: core + +- func: avg_pool3d_backward.grad_input(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, bool ceil_mode, bool count_include_pad, int? divisor_override, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: avg_pool3d_backward_out_cpu + CUDA: avg_pool3d_backward_out_cuda + MPS: avg_pool3d_backward_out_mps + XPU: avg_pool3d_backward_out_xpu + MkldnnCPU: mkldnn_avg_pool3d_backward_out + +- func: avg_pool3d_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor + python_module: nn + structured_delegate: avg_pool3d_backward.grad_input + dispatch: + MkldnnCPU: mkldnn_avg_pool3d_backward + +# Return: (Tensor output, Tensor indices) +- func: fractional_max_pool2d.output(Tensor self, int[2] kernel_size, int[2] output_size, Tensor random_samples, *, Tensor(a!) output, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) + python_module: nn + structured: True + dispatch: + CPU: fractional_max_pool2d_out_cpu + CUDA: fractional_max_pool2d_out_cuda + XPU: fractional_max_pool2d_out_xpu + +# Return: (Tensor output, Tensor indices) +- func: fractional_max_pool2d(Tensor self, int[2] kernel_size, int[2] output_size, Tensor random_samples) -> (Tensor, Tensor) + python_module: nn + structured_delegate: fractional_max_pool2d.output + +- func: fractional_max_pool2d_backward.grad_input(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] output_size, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: fractional_max_pool2d_backward_cpu + CUDA: fractional_max_pool2d_backward_cuda + XPU: fractional_max_pool2d_backward_xpu + +- func: fractional_max_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] output_size, Tensor indices) -> Tensor + python_module: nn + structured_delegate: fractional_max_pool2d_backward.grad_input + +# Return: (Tensor output, Tensor indices) +- func: fractional_max_pool3d.output(Tensor self, int[3] kernel_size, int[3] output_size, Tensor random_samples, *, Tensor(a!) output, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) + python_module: nn + structured: True + precomputed: + - kernel_size -> int poolSizeT, int poolSizeH, int poolSizeW + - output_size -> int outputT, int outputH, int outputW + - int numBatch, int numPlanes, int inputT, int inputH, int inputW + dispatch: + CPU: fractional_max_pool3d_out_cpu + CUDA: fractional_max_pool3d_out_cuda + XPU: fractional_max_pool3d_out_xpu + +# Return: (Tensor output, Tensor indices) +- func: fractional_max_pool3d(Tensor self, int[3] kernel_size, int[3] output_size, Tensor random_samples) -> (Tensor, Tensor) + python_module: nn + structured_delegate: fractional_max_pool3d.output + +- func: fractional_max_pool3d_backward.grad_input(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] output_size, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU: fractional_max_pool3d_backward_out_cpu + CUDA: fractional_max_pool3d_backward_out_cuda + XPU: fractional_max_pool3d_backward_out_xpu + +- func: fractional_max_pool3d_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] output_size, Tensor indices) -> Tensor + python_module: nn + dispatch: + CPU: fractional_max_pool3d_backward_cpu + CUDA: fractional_max_pool3d_backward_cuda + XPU: fractional_max_pool3d_backward_xpu + +# Return: (Tensor output, Tensor indices) +- func: max_pool2d_with_indices.out(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) + python_module: nn + structured: True + dispatch: + CPU: max_pool2d_with_indices_out_cpu + CUDA: max_pool2d_with_indices_out_cuda + MPS: max_pool2d_with_indices_out_mps + XPU: max_pool2d_with_indices_out_xpu + +# Return: (Tensor output, Tensor indices) +- func: max_pool2d_with_indices(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor) + python_module: nn + structured_delegate: max_pool2d_with_indices.out + tags: core + +- func: max_pool2d_with_indices_backward.grad_input(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, bool ceil_mode, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: max_pool2d_with_indices_backward_out_cpu + CUDA: max_pool2d_with_indices_backward_out_cuda + MPS: max_pool2d_with_indices_backward_out_mps + XPU: max_pool2d_with_indices_backward_out_xpu + +- func: max_pool2d_with_indices_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, bool ceil_mode, Tensor indices) -> Tensor + python_module: nn + structured_delegate: max_pool2d_with_indices_backward.grad_input + tags: core + +# Return: (Tensor output, Tensor indices) +- func: max_pool3d_with_indices.out(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) + python_module: nn + dispatch: + CPU: max_pool3d_with_indices_out_cpu + CUDA: max_pool3d_with_indices_out_cuda + MPS: max_pool3d_with_indices_out_mps + XPU: max_pool3d_with_indices_out_xpu + +# Return: (Tensor output, Tensor indices) +- func: max_pool3d_with_indices(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor) + python_module: nn + dispatch: + CPU: max_pool3d_with_indices_cpu + CUDA: max_pool3d_with_indices_cuda + MPS: max_pool3d_with_indices_mps + XPU: max_pool3d_with_indices_xpu + tags: core + +- func: max_pool3d_with_indices_backward.grad_input(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, int[3] dilation, bool ceil_mode, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU: max_pool3d_with_indices_backward_out_cpu + CUDA: max_pool3d_with_indices_backward_out_cuda + MPS: max_pool3d_with_indices_backward_out_mps + XPU: max_pool3d_with_indices_backward_out_xpu + +- func: max_pool3d_with_indices_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, int[3] dilation, bool ceil_mode, Tensor indices) -> Tensor + python_module: nn + dispatch: + CPU: max_pool3d_with_indices_backward_cpu + CUDA: max_pool3d_with_indices_backward_cuda + MPS: max_pool3d_with_indices_backward_mps + XPU: max_pool3d_with_indices_backward_xpu + +- func: max_unpool2d.out(Tensor self, Tensor indices, SymInt[2] output_size, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + dispatch: + CPU: max_unpooling2d_forward_out_cpu + CUDA: max_unpooling2d_forward_out_cuda + MPS: max_unpooling2d_forward_out_mps + XPU: max_unpooling2d_forward_out_xpu + +- func: max_unpool2d(Tensor self, Tensor indices, SymInt[2] output_size) -> Tensor + python_module: nn + dispatch: + CPU: max_unpooling2d_forward_cpu + CUDA: max_unpooling2d_forward_cuda + MPS: max_unpooling2d_forward_mps + XPU: max_unpooling2d_forward_xpu + +- func: max_unpool3d.out(Tensor self, Tensor indices, SymInt[3] output_size, int[3] stride, int[3] padding, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + dispatch: + CPU: max_unpooling3d_forward_out_cpu + CUDA: max_unpooling3d_forward_out_cuda + MPS: max_unpooling3d_forward_out_mps + XPU: max_unpooling3d_forward_out_xpu + +- func: max_unpool3d(Tensor self, Tensor indices, SymInt[3] output_size, int[3] stride, int[3] padding) -> Tensor + python_module: nn + dispatch: + CPU: max_unpooling3d_forward_cpu + CUDA: max_unpooling3d_forward_cuda + MPS: max_unpooling3d_forward_mps + XPU: max_unpooling3d_forward_xpu + +- func: reflection_pad1d.out(Tensor self, SymInt[2] padding, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: reflection_pad1d_out_cpu + QuantizedCPU: reflection_pad1d_out_quantized_cpu + CUDA: reflection_pad1d_out_cuda + MPS: reflection_pad1d_out_mps + XPU: reflection_pad1d_out_xpu + +- func: reflection_pad1d(Tensor self, SymInt[2] padding) -> Tensor + python_module: nn + structured_delegate: reflection_pad1d.out + tags: core + +- func: reflection_pad1d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: reflection_pad1d_backward_out_cpu + CUDA: reflection_pad1d_backward_out_cuda + MPS: reflection_pad1d_backward_out_mps + XPU: reflection_pad1d_backward_out_xpu + +- func: reflection_pad1d_backward(Tensor grad_output, Tensor self, SymInt[2] padding) -> Tensor + python_module: nn + structured_delegate: reflection_pad1d_backward.grad_input + +- func: reflection_pad2d.out(Tensor self, SymInt[4] padding, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + dispatch: + CPU, QuantizedCPU: reflection_pad2d_out_cpu + CUDA: reflection_pad2d_out_cuda + MPS: reflection_pad2d_out_mps + XPU: reflection_pad2d_out_xpu + +- func: reflection_pad2d(Tensor self, SymInt[4] padding) -> Tensor + python_module: nn + dispatch: + CPU: reflection_pad2d_cpu + QuantizedCPU: reflection_pad2d_quantized_cpu + CUDA: reflection_pad2d_cuda + MPS: reflection_pad2d_mps + XPU: reflection_pad2d_xpu + tags: core + +- func: reflection_pad2d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[4] padding, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU: reflection_pad2d_backward_out_cpu + CUDA: reflection_pad2d_backward_out_cuda + MPS: reflection_pad2d_backward_out_mps + XPU: reflection_pad2d_backward_out_xpu + +- func: reflection_pad2d_backward(Tensor grad_output, Tensor self, SymInt[4] padding) -> Tensor + python_module: nn + dispatch: + CPU: reflection_pad2d_backward_cpu + CUDA: reflection_pad2d_backward_cuda + MPS: reflection_pad2d_backward_mps + XPU: reflection_pad2d_backward_xpu + +- func: reflection_pad3d.out(Tensor self, SymInt[6] padding, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: reflection_pad3d_out_cpu + CUDA: reflection_pad3d_out_cuda + MPS: reflection_pad3d_out_mps + XPU: reflection_pad3d_out_xpu + +- func: reflection_pad3d(Tensor self, SymInt[6] padding) -> Tensor + python_module: nn + structured_delegate: reflection_pad3d.out + tags: core + +- func: reflection_pad3d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[6] padding, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: reflection_pad3d_backward_out_cpu + CUDA: reflection_pad3d_backward_out_cuda + MPS: reflection_pad3d_backward_out_mps + XPU: reflection_pad3d_backward_out_xpu + +- func: reflection_pad3d_backward(Tensor grad_output, Tensor self, SymInt[6] padding) -> Tensor + python_module: nn + structured_delegate: reflection_pad3d_backward.grad_input + +- func: replication_pad1d.out(Tensor self, SymInt[2] padding, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: replication_pad1d_out_cpu + CUDA: replication_pad1d_out_cuda + MPS: replication_pad1d_out_mps + XPU: replication_pad1d_out_xpu + +- func: replication_pad1d(Tensor self, SymInt[2] padding) -> Tensor + python_module: nn + structured_delegate: replication_pad1d.out + +- func: replication_pad1d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: replication_pad1d_backward_out_cpu + CUDA: replication_pad1d_backward_out_cuda + MPS: replication_pad1d_backward_out_mps + XPU: replication_pad1d_backward_out_xpu + +- func: replication_pad1d_backward(Tensor grad_output, Tensor self, SymInt[2] padding) -> Tensor + python_module: nn + structured_delegate: replication_pad1d_backward.grad_input + +- func: replication_pad2d.out(Tensor self, SymInt[4] padding, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: replication_pad2d_out_cpu + CUDA: replication_pad2d_out_cuda + MPS: replication_pad2d_out_mps + XPU: replication_pad2d_out_xpu + +- func: replication_pad2d(Tensor self, SymInt[4] padding) -> Tensor + python_module: nn + structured_delegate: replication_pad2d.out + tags: core + +- func: replication_pad2d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[4] padding, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU: replication_pad2d_backward_out_cpu + CUDA: replication_pad2d_backward_out_cuda + MPS: replication_pad2d_backward_out_mps + XPU: replication_pad2d_backward_out_xpu + +- func: replication_pad2d_backward(Tensor grad_output, Tensor self, SymInt[4] padding) -> Tensor + python_module: nn + dispatch: + CPU: replication_pad2d_backward_cpu + CUDA: replication_pad2d_backward_cuda + MPS: replication_pad2d_backward_mps + XPU: replication_pad2d_backward_xpu + +- func: replication_pad3d.out(Tensor self, SymInt[6] padding, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: replication_pad3d_out_cpu + CUDA: replication_pad3d_out_cuda + MPS: replication_pad3d_out_mps + XPU: replication_pad3d_out_xpu + +- func: replication_pad3d(Tensor self, SymInt[6] padding) -> Tensor + python_module: nn + structured_delegate: replication_pad3d.out + tags: core + +- func: replication_pad3d_backward.grad_input(Tensor grad_output, Tensor self, SymInt[6] padding, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU: replication_pad3d_backward_out_cpu + CUDA: replication_pad3d_backward_out_cuda + MPS: replication_pad3d_backward_out_mps + XPU: replication_pad3d_backward_out_xpu + +- func: replication_pad3d_backward(Tensor grad_output, Tensor self, SymInt[6] padding) -> Tensor + python_module: nn + dispatch: + CPU: replication_pad3d_backward_cpu + CUDA: replication_pad3d_backward_cuda + MPS: replication_pad3d_backward_mps + XPU: replication_pad3d_backward_xpu + +- func: _pad_circular(Tensor self, SymInt[] pad) -> Tensor + python_module: nn + dispatch: + CompositeImplicitAutograd: _pad_circular_symint + +- func: _pad_enum(Tensor self, SymInt[] pad, int mode, float? value=None) -> Tensor + python_module: nn + dispatch: + CompositeImplicitAutograd: _pad_enum_symint + +- func: pad(Tensor self, SymInt[] pad, str mode="constant", float? value=None) -> Tensor + python_module: nn + dispatch: + CompositeImplicitAutograd: pad_symint + +- func: upsample_linear1d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor + python_module: nn + autogen: upsample_linear1d.vec_out + +- func: upsample_bilinear2d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor + python_module: nn + autogen: upsample_bilinear2d.vec_out + tags: core + +- func: _upsample_bilinear2d_aa.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor + python_module: nn + autogen: _upsample_bilinear2d_aa.vec_out + +- func: upsample_trilinear3d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor + python_module: nn + autogen: upsample_trilinear3d.vec_out + +- func: upsample_bicubic2d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor + python_module: nn + autogen: upsample_bicubic2d.vec_out + +- func: _upsample_bicubic2d_aa.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor + python_module: nn + autogen: _upsample_bicubic2d_aa.vec_out + +- func: _upsample_lanczos2d_aa.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor + python_module: nn + autogen: _upsample_lanczos2d_aa.vec_out + +- func: upsample_nearest1d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor + python_module: nn + autogen: upsample_nearest1d.vec_out + +- func: _upsample_nearest_exact1d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor + python_module: nn + autogen: _upsample_nearest_exact1d.vec_out + +- func: upsample_nearest2d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor + python_module: nn + autogen: upsample_nearest2d.vec_out + tags: core + +- func: _upsample_nearest_exact2d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor + python_module: nn + autogen: _upsample_nearest_exact2d.vec_out + +- func: upsample_nearest3d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor + python_module: nn + autogen: upsample_nearest3d.vec_out + +- func: _upsample_nearest_exact3d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor + python_module: nn + autogen: _upsample_nearest_exact3d.vec_out + +# NOTE: all of the non-"vec" upsample overloads are only kept for backward compatibility. +- func: upsample_linear1d.out(Tensor self, SymInt[1] output_size, bool align_corners, float? scales=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: upsample_linear1d_out_cpu + CUDA: upsample_linear1d_out_cuda + MPS: upsample_linear1d_out_mps + XPU: upsample_linear1d_out_xpu + +- func: upsample_linear1d(Tensor self, SymInt[1] output_size, bool align_corners, float? scales=None) -> Tensor + python_module: nn + structured_delegate: upsample_linear1d.out + +- func: upsample_linear1d_backward.grad_input(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, bool align_corners, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: upsample_linear1d_backward_out_cpu + CUDA: upsample_linear1d_backward_out_cuda + MPS: upsample_linear1d_backward_out_mps + XPU: upsample_linear1d_backward_out_xpu + +- func: upsample_linear1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, bool align_corners, float? scales=None) -> Tensor + python_module: nn + structured_delegate: upsample_linear1d_backward.grad_input + +- func: upsample_bilinear2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: upsample_bilinear2d_out_cpu + CUDA: upsample_bilinear2d_out_cuda + MPS: upsample_bilinear2d_out_mps + XPU: upsample_bilinear2d_out_xpu + +- func: upsample_bilinear2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: upsample_bilinear2d.out + dispatch: + QuantizedCPU: upsample_bilinear2d_quantized_cpu + +- func: upsample_bilinear2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: upsample_bilinear2d_backward_out_cpu + CUDA: upsample_bilinear2d_backward_out_cuda + MPS: upsample_bilinear2d_backward_out_mps + XPU: upsample_bilinear2d_backward_out_xpu + +- func: upsample_bilinear2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: upsample_bilinear2d_backward.grad_input + +- func: _upsample_bilinear2d_aa.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_bilinear2d_aa_out_cpu + CUDA: _upsample_bilinear2d_aa_out_cuda + MPS: _upsample_bilinear2d_aa_out_mps + XPU: _upsample_bilinear2d_aa_out_xpu + +- func: _upsample_bilinear2d_aa(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_bilinear2d_aa.out + +- func: _upsample_bilinear2d_aa_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_bilinear2d_aa_backward_out_cpu + CUDA: _upsample_bilinear2d_aa_backward_out_cuda + XPU: _upsample_bilinear2d_aa_backward_out_xpu + MPS: _upsample_bilinear2d_aa_backward_out_mps + +- func: _upsample_bilinear2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_bilinear2d_aa_backward.grad_input + +- func: upsample_bicubic2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: upsample_bicubic2d_out_cpu + CUDA: upsample_bicubic2d_out_cuda + MPS: upsample_bicubic2d_out_mps + XPU: upsample_bicubic2d_out_xpu + +- func: upsample_bicubic2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: upsample_bicubic2d.out + +- func: upsample_bicubic2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: upsample_bicubic2d_backward_out_cpu + CUDA: upsample_bicubic2d_backward_out_cuda + MPS: upsample_bicubic2d_backward_out_mps + XPU: upsample_bicubic2d_backward_out_xpu + +- func: upsample_bicubic2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: upsample_bicubic2d_backward.grad_input + +- func: _upsample_bicubic2d_aa.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_bicubic2d_aa_out_cpu + CUDA: _upsample_bicubic2d_aa_out_cuda + MPS: _upsample_bicubic2d_aa_out_mps + XPU: _upsample_bicubic2d_aa_out_xpu + +- func: _upsample_bicubic2d_aa(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_bicubic2d_aa.out + +- func: _upsample_bicubic2d_aa_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_bicubic2d_aa_backward_out_cpu + CUDA: _upsample_bicubic2d_aa_backward_out_cuda + XPU: _upsample_bicubic2d_aa_backward_out_xpu + MPS: _upsample_bicubic2d_aa_backward_out_mps + +- func: _upsample_bicubic2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_bicubic2d_aa_backward.grad_input + +- func: _upsample_lanczos2d_aa.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_lanczos2d_aa_out_cpu + +- func: _upsample_lanczos2d_aa(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_lanczos2d_aa.out + +- func: _upsample_lanczos2d_aa_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_lanczos2d_aa_backward_out_cpu + +- func: _upsample_lanczos2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_lanczos2d_aa_backward.grad_input + +- func: upsample_trilinear3d.out(Tensor self, SymInt[3] output_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: upsample_trilinear3d_out_cpu + CUDA: upsample_trilinear3d_out_cuda + MPS: upsample_trilinear3d_out_mps + XPU: upsample_trilinear3d_out_xpu + +- func: upsample_trilinear3d(Tensor self, SymInt[3] output_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: upsample_trilinear3d.out + +- func: upsample_trilinear3d_backward.grad_input(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: upsample_trilinear3d_backward_out_cpu + CUDA: upsample_trilinear3d_backward_out_cuda + MPS: upsample_trilinear3d_backward_out_mps + XPU: upsample_trilinear3d_backward_out_xpu + +- func: upsample_trilinear3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: upsample_trilinear3d_backward.grad_input + +- func: upsample_nearest1d.out(Tensor self, SymInt[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: upsample_nearest1d_out_cpu + CUDA: upsample_nearest1d_out_cuda + MPS: upsample_nearest1d_out_mps + XPU: upsample_nearest1d_out_xpu + +- func: _upsample_nearest_exact1d.out(Tensor self, SymInt[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_nearest_exact1d_out_cpu + CUDA: _upsample_nearest_exact1d_out_cuda + MPS: _upsample_nearest_exact1d_out_mps + XPU: _upsample_nearest_exact1d_out_xpu + +- func: upsample_nearest1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor + python_module: nn + structured_delegate: upsample_nearest1d.out + +- func: _upsample_nearest_exact1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor + python_module: nn + structured_delegate: _upsample_nearest_exact1d.out + +- func: upsample_nearest1d_backward.grad_input(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: upsample_nearest1d_backward_out_cpu + CUDA: upsample_nearest1d_backward_out_cuda + MPS: upsample_nearest1d_backward_out_mps + XPU: upsample_nearest1d_backward_out_xpu + +- func: _upsample_nearest_exact1d_backward.grad_input(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_nearest_exact1d_backward_out_cpu + CUDA: _upsample_nearest_exact1d_backward_out_cuda + MPS: _upsample_nearest_exact1d_backward_out_mps + XPU: _upsample_nearest_exact1d_backward_out_xpu + +- func: upsample_nearest1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None) -> Tensor + python_module: nn + structured_delegate: upsample_nearest1d_backward.grad_input + +- func: _upsample_nearest_exact1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None) -> Tensor + python_module: nn + structured_delegate: _upsample_nearest_exact1d_backward.grad_input + +- func: upsample_nearest2d.out(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: upsample_nearest2d_out_cpu + CUDA: upsample_nearest2d_out_cuda + MPS: upsample_nearest2d_out_mps + XPU: upsample_nearest2d_out_xpu + +- func: _upsample_nearest_exact2d.out(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_nearest_exact2d_out_cpu + CUDA: _upsample_nearest_exact2d_out_cuda + MPS: _upsample_nearest_exact2d_out_mps + XPU: _upsample_nearest_exact2d_out_xpu + +- func: upsample_nearest2d(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: upsample_nearest2d.out + dispatch: + QuantizedCPU: upsample_nearest2d_quantized_cpu + +- func: _upsample_nearest_exact2d(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_nearest_exact2d.out + dispatch: + QuantizedCPU: _upsample_nearest_exact2d_quantized_cpu + +- func: upsample_nearest2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: upsample_nearest2d_backward_out_cpu + CUDA: upsample_nearest2d_backward_out_cuda + MPS: upsample_nearest2d_backward_out_mps + XPU: upsample_nearest2d_backward_out_xpu + +- func: _upsample_nearest_exact2d_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_nearest_exact2d_backward_out_cpu + CUDA: _upsample_nearest_exact2d_backward_out_cuda + MPS: _upsample_nearest_exact2d_backward_out_mps + XPU: _upsample_nearest_exact2d_backward_out_xpu + +- func: upsample_nearest2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: upsample_nearest2d_backward.grad_input + +- func: _upsample_nearest_exact2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_nearest_exact2d_backward.grad_input + +- func: upsample_nearest3d.out(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: upsample_nearest3d_out_cpu + CUDA: upsample_nearest3d_out_cuda + MPS: upsample_nearest3d_out_mps + XPU: upsample_nearest3d_out_xpu + +- func: _upsample_nearest_exact3d.out(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_nearest_exact3d_out_cpu + CUDA: _upsample_nearest_exact3d_out_cuda + MPS: _upsample_nearest_exact3d_out_mps + XPU: _upsample_nearest_exact3d_out_xpu + +- func: upsample_nearest3d(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: upsample_nearest3d.out + dispatch: + QuantizedCPU: upsample_nearest3d_quantized_cpu + +- func: _upsample_nearest_exact3d(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_nearest_exact3d.out + dispatch: + QuantizedCPU: _upsample_nearest_exact3d_quantized_cpu + +- func: upsample_nearest3d_backward.grad_input(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: upsample_nearest3d_backward_out_cpu + CUDA: upsample_nearest3d_backward_out_cuda + MPS: upsample_nearest3d_backward_out_mps + XPU: upsample_nearest3d_backward_out_xpu + +- func: _upsample_nearest_exact3d_backward.grad_input(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_nearest_exact3d_backward_out_cpu + CUDA: _upsample_nearest_exact3d_backward_out_cuda + MPS: _upsample_nearest_exact3d_backward_out_mps + XPU: _upsample_nearest_exact3d_backward_out_xpu + +- func: upsample_nearest3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: upsample_nearest3d_backward.grad_input + +- func: _upsample_nearest_exact3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_nearest_exact3d_backward.grad_input + +- func: sigmoid_backward.grad_input(Tensor grad_output, Tensor output, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: sigmoid_backward_out + tags: pointwise + +- func: sigmoid_backward(Tensor grad_output, Tensor output) -> Tensor + python_module: nn + structured_delegate: sigmoid_backward.grad_input + tags: pointwise + +- func: logit_backward.grad_input(Tensor grad_output, Tensor self, float? eps=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, XPU: logit_backward_out + MPS: logit_backward_out_mps + tags: pointwise + +- func: logit_backward(Tensor grad_output, Tensor self, float? eps=None) -> Tensor + python_module: nn + structured_delegate: logit_backward.grad_input + tags: pointwise + +- func: tanh_backward.grad_input(Tensor grad_output, Tensor output, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MTIA, XPU: tanh_backward_out + MPS: tanh_backward_out_mps + tags: pointwise + +- func: tanh_backward(Tensor grad_output, Tensor output) -> Tensor + python_module: nn + structured_delegate: tanh_backward.grad_input + +# What's a thnn_conv_ versus a slow_conv_? +# +# Historically, we have inefficient implementations of convolutions +# coming from the THNN/THCUNN library. These convolutions typically +# operated by computing the Toeplitz matrix and then doing a matrix +# multiply with the input; this is very memory inefficient! However, +# occasionally, we really don't have anything better, so it's helpful +# to have these fallbacks when there is no more optimized implementation +# in cudnn or mkldnn, etc. Both thnn_ and slow_ convolutions fall +# into this bucket. +# +# The difference between these two designations, is that thnn_ refers +# to a convolution that is still written in the "legacy" style; that is, +# C code in the THNN/ or THCUNN/ directory. A slow_ convolution is +# one that is written in the native style: modern C++. Algorithmically, +# these are the same thing, but we give them different prefixes to +# make the operational distinction clear. + tags: pointwise + +- func: slow_conv_transpose2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt[2] dilation=1, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: slow_conv_transpose2d_structured_cpu + CUDA: slow_conv_transpose2d_structured_cuda + +- func: slow_conv_transpose2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt[2] dilation=1) -> Tensor + python_module: nn + structured_delegate: slow_conv_transpose2d.out + +- func: slow_conv_transpose3d.out(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt[3] dilation=1, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + dispatch: + CPU: slow_conv_transpose3d_out_cpu + CUDA: slow_conv_transpose3d_out_cuda + +- func: slow_conv_transpose3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt[3] dilation=1) -> Tensor + python_module: nn + dispatch: + CPU: slow_conv_transpose3d_cpu + CUDA: slow_conv_transpose3d_cuda + +- func: thnn_conv2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + +- func: thnn_conv2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0) -> Tensor + python_module: nn + +- func: _slow_conv2d_forward.output(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, *, Tensor(a!) output) -> Tensor(a!) + python_module: nn + dispatch: + CPU: slow_conv2d_forward_out_cpu + CUDA: slow_conv2d_forward_out_cuda + +- func: _slow_conv2d_forward(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding) -> Tensor + python_module: nn + dispatch: + CPU: slow_conv2d_forward_cpu + CUDA: slow_conv2d_forward_cuda + +- func: _slow_conv2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, *, Tensor(a!) grad_input, Tensor(b!) grad_weight, Tensor(c!) grad_bias) -> (Tensor(a!), Tensor(b!), Tensor(c!)) + python_module: nn + dispatch: + CPU: slow_conv2d_backward_out_cpu + CUDA: slow_conv2d_backward_out_cuda + +- func: _slow_conv2d_backward.output_mask(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias) + python_module: nn + dispatch: + CPU: slow_conv2d_backward_cpu + CUDA: slow_conv2d_backward_cuda + autogen: _slow_conv2d_backward.output_mask_out + +- func: _conv_depthwise2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, SymInt[2] dilation, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + dispatch: + CUDA: conv_depthwise2d_cuda_out + +- func: _conv_depthwise2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, SymInt[2] dilation) -> Tensor + python_module: nn + dispatch: + CUDA: conv_depthwise2d_cuda + +- func: conv_depthwise3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding, SymInt[3] dilation) -> Tensor + python_module: nn + dispatch: + CUDA: conv_depthwise3d_cuda + autogen: conv_depthwise3d.out + +- func: slow_conv3d.out(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + +- func: slow_conv3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0) -> Tensor + python_module: nn + +- func: slow_conv3d_forward.output(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding, *, Tensor(a!) output) -> Tensor(a!) + python_module: nn + dispatch: + CPU: slow_conv3d_forward_out_cpu + +- func: slow_conv3d_forward(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding) -> Tensor + python_module: nn + dispatch: + CPU: slow_conv3d_forward_cpu + +- func: slow_conv_dilated2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] dilation=1) -> Tensor + python_module: nn + dispatch: + CPU: slow_conv_dilated2d_cpu + CUDA: slow_conv_dilated2d_cuda + autogen: slow_conv_dilated2d.out + +- func: slow_conv_dilated3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] dilation=1) -> Tensor + python_module: nn + dispatch: + CPU: slow_conv_dilated3d_cpu + CUDA: slow_conv_dilated3d_cuda + autogen: slow_conv_dilated3d.out + +- func: col2im.out(Tensor self, SymInt[2] output_size, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + dispatch: + CPU: col2im_out_cpu + CUDA: col2im_out_cuda + MPS: col2im_out_mps + XPU: col2im_out_xpu + +- func: col2im(Tensor self, SymInt[2] output_size, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride) -> Tensor + python_module: nn + dispatch: + CPU: col2im_cpu + CUDA: col2im_cuda + MPS: col2im_mps + XPU: col2im_xpu + tags: core + +- func: column_stack(Tensor[] tensors) -> Tensor + +- func: column_stack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) + +- func: im2col.out(Tensor self, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + dispatch: + CPU: im2col_out_cpu + CUDA: im2col_out_cuda + MPS: im2col_out_mps + XPU: im2col_out_xpu + +- func: im2col(Tensor self, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride) -> Tensor + python_module: nn + dispatch: + CPU: im2col_cpu + CUDA: im2col_cuda + MPS: im2col_mps + XPU: im2col_xpu + +- func: isfinite(Tensor self) -> Tensor + variants: function, method + device_check: NoCheck + device_guard: False + tags: pointwise + +- func: isinf(Tensor self) -> Tensor + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: isinf + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_isinf + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: isinf_sparse + SparseMeta: isinf_sparse_meta + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: isinf_sparse_csr + autogen: isinf.out + tags: [core, pointwise] + +- func: record_stream(Tensor(a!) self, Stream s) -> () + variants: method + dispatch: + CUDA: record_stream_cuda + XPU: record_stream_xpu + +- func: isposinf(Tensor self) -> Tensor + variants: function, method + structured_delegate: isposinf.out + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_isposinf + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: isposinf_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: isposinf_sparse_csr + tags: pointwise + +- func: isposinf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: isposinf_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: isposinf_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: isposinf_sparse_csr_out + tags: pointwise + +- func: isneginf(Tensor self) -> Tensor + variants: function, method + structured_delegate: isneginf.out + dispatch: + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: NestedTensor_isneginf + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: isneginf_sparse + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: isneginf_sparse_csr + tags: pointwise + +- func: isneginf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: isneginf_out + SparseCPU, SparseCUDA, SparseMPS, SparseXPU: isneginf_sparse_out + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: isneginf_sparse_csr_out + tags: pointwise + +# NOTE [_add_batch_dim and _remove_batch_dim] +# _add_batch_dim and _remove_batch_dim are meant to be used in the implementation +# of the vmap frontend API (see torch/_vmap_internals.py). They are not +# user-facing, hence the leading underscore. Please don't use them them anywhere else. +- func: _add_batch_dim(Tensor self, int batch_dim, int level) -> Tensor + variants: function + +# See NOTE [_add_batch_dim and _remove_batch_dim] +- func: _remove_batch_dim(Tensor self, int level, SymInt batch_size, int out_dim) -> Tensor + variants: function + +## Functions related to the `torch.special` namespace +# Note [special namespace binding] +# Functions in the special python module should have their names start with +# "special_" underscore and be bound to the desired Python name in +# torch/special/__init__.py, and the desired C++ name in torch/csrc/api/include/torch/special.h. +# The "special_" names should be hidden from the user and not documented. + +- func: special_entr(Tensor self) -> Tensor + structured_delegate: special_entr.out + python_module: special + variants: function + tags: pointwise + +- func: special_entr.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: special + variants: function + dispatch: + CPU, CUDA, MPS, XPU: special_entr_out + tags: pointwise + +- func: special_ndtri(Tensor self) -> Tensor + structured_delegate: special_ndtri.out + python_module: special + variants: function + tags: pointwise + +- func: special_ndtri.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: special + variants: function + dispatch: + CPU, CUDA, XPU: special_ndtri_out + tags: pointwise + +- func: special_log_ndtr(Tensor self) -> Tensor + structured_delegate: special_log_ndtr.out + python_module: special + variants: function + tags: pointwise + +- func: special_log_ndtr.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: special + variants: function + dispatch: + CPU, CUDA, XPU: special_log_ndtr_out + tags: pointwise + +- func: special_expm1(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_expm1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_exp2(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_exp2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_psi(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_psi.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_digamma(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_digamma.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_gammaln(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_gammaln.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_erf(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_erf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_erfc(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_erfc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + +- func: special_erfcx(Tensor self) -> Tensor + python_module: special + variants: function + structured_delegate: special_erfcx.out + tags: pointwise + +- func: special_erfcx.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: special_erfcx_out + tags: pointwise + +- func: special_erfinv(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_erfinv.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + +- func: special_ndtr(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_ndtr.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_xlog1py(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + structured_delegate: special_xlog1py.out + tags: pointwise + +- func: special_xlog1py.self_scalar(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_xlog1py + tags: pointwise + +- func: special_xlog1py.other_scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_xlog1py + tags: pointwise + +- func: special_xlog1py.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + python_module: special + variants: function + dispatch: + CPU, CUDA, MPS, XPU: special_xlog1py_out + tags: pointwise + +- func: special_xlog1py.self_scalar_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_xlog1py_out + tags: pointwise + +- func: special_xlog1py.other_scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_xlog1py_out + tags: pointwise + +- func: special_xlogy(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + +- func: special_xlogy.self_scalar(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + +- func: special_xlogy.other_scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + +- func: special_xlogy.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: special + variants: function + +- func: special_xlogy.self_scalar_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: special + variants: function + +- func: special_xlogy.other_scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: special + variants: function + +- func: special_zeta(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + structured_delegate: special_zeta.out + tags: pointwise + +- func: special_zeta.self_scalar(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_zeta + tags: pointwise + +- func: special_zeta.other_scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_zeta + tags: pointwise + +- func: special_zeta.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + python_module: special + variants: function + dispatch: + CPU, CUDA, MPS, XPU: special_zeta_out + tags: pointwise + +- func: special_zeta.self_scalar_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_zeta_out + tags: pointwise + +- func: special_zeta.other_scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_zeta_out + tags: pointwise + +- func: special_i0(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_i0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_i0e(Tensor self) -> Tensor + python_module: special + variants: function + structured_delegate: special_i0e.out + tags: pointwise + +- func: special_i0e.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: special_i0e_out + tags: pointwise + +- func: special_i1(Tensor self) -> Tensor + python_module: special + variants: function + structured_delegate: special_i1.out + tags: pointwise + +- func: special_i1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: special_i1_out + tags: pointwise + +- func: special_i1e(Tensor self) -> Tensor + python_module: special + variants: function + structured_delegate: special_i1e.out + tags: pointwise + +- func: special_i1e.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA, MPS, XPU: special_i1e_out + tags: pointwise + +- func: special_logit(Tensor self, float? eps=None) -> Tensor + python_module: special + variants: function + +- func: special_logit.out(Tensor self, float? eps=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + +- func: special_polygamma(int n, Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_polygamma.out(int n, Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + +- func: special_logsumexp(Tensor self, int[1] dim, bool keepdim=False) -> Tensor + python_module: special + variants: function + +- func: special_logsumexp.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + +- func: special_expit(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_expit.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_sinc(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_sinc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_round(Tensor self, *, int decimals=0) -> Tensor + python_module: special + variants: function + +- func: special_round.out(Tensor self, *, int decimals=0, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_log1p(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_log1p.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_log_softmax(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor + python_module: special + variants: function + +- func: special_gammainc.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_gammainc(Tensor self, Tensor other) -> Tensor + python_module: special + variants: function + +- func: special_gammaincc.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_gammaincc(Tensor self, Tensor other) -> Tensor + python_module: special + variants: function + +- func: special_multigammaln(Tensor self, int p) -> Tensor + python_module: special + variants: function + +- func: special_multigammaln.out(Tensor self, int p, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_softmax(Tensor self, int dim, ScalarType? dtype=None) -> Tensor + python_module: special + variants: function + +## Functions related to the fast Fourier transform and the torch.fft namespace +# Note [FFT namespace binding] +# Functions in the fft python module should have their names start with +# "fft_" underscore and be bound to the desired Python name in +# torch/fft/__init__.py, and the desired C++ name in torch/csrc/api/include/torch/fft.h. +# The "fft_" names should be hidden from the user and not documented. +# +# See fft_fft as an example. + +# torch.fft.fft +# NOTE: NOT an alias for torch.fft, which has different semantics +- func: fft_fft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_fft_symint + +- func: fft_fft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_fft_symint_out + +- func: fft_ifft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_ifft_symint + +- func: fft_ifft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_ifft_symint_out + +- func: fft_rfft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_rfft_symint + +- func: fft_rfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_rfft_symint_out + +- func: fft_irfft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_irfft_symint + +- func: fft_irfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_irfft_symint_out + +- func: fft_hfft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_hfft_symint + +- func: fft_hfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_hfft_symint_out + +- func: fft_ihfft(Tensor self, SymInt? n=None, int dim=-1, str? norm=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_ihfft_symint + +- func: fft_ihfft.out(Tensor self, SymInt? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_ihfft_symint_out + +- func: fft_fft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_fft2_symint + +- func: fft_fft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_fft2_symint_out + +- func: fft_ifft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_ifft2_symint + +- func: fft_ifft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_ifft2_symint_out + +- func: fft_rfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_rfft2_symint + +- func: fft_rfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_rfft2_symint_out + +- func: fft_irfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_irfft2_symint + +- func: fft_irfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_irfft2_symint_out + +- func: fft_hfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor + use_const_ref_for_mutable_tensors: True + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_hfft2_symint + +- func: fft_hfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_hfft2_symint_out + +- func: fft_ihfft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor + use_const_ref_for_mutable_tensors: True + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_ihfft2_symint + +- func: fft_ihfft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_ihfft2_symint_out + +- func: fft_fftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_fftn_symint + +- func: fft_fftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_fftn_symint_out + +- func: fft_ifftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_ifftn_symint + +- func: fft_ifftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_ifftn_symint_out + +- func: fft_rfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_rfftn_symint + +- func: fft_rfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_rfftn_symint_out + +- func: fft_irfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_irfftn_symint + +- func: fft_irfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_irfftn_symint_out + +- func: fft_hfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor + use_const_ref_for_mutable_tensors: True + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_hfftn_symint + +- func: fft_hfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_hfftn_symint_out + +- func: fft_ihfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor + use_const_ref_for_mutable_tensors: True + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_ihfftn_symint + +- func: fft_ihfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeImplicitAutograd: fft_ihfftn_symint_out + +- func: fft_fftfreq(int n, float d=1.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeExplicitAutograd: fft_fftfreq + +- func: fft_fftfreq.out(int n, float d=1.0, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeExplicitAutograd: fft_fftfreq_out + +- func: fft_rfftfreq(int n, float d=1.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + python_module: fft + variants: function + dispatch: + CompositeExplicitAutograd: fft_rfftfreq + +- func: fft_rfftfreq.out(int n, float d=1.0, *, Tensor(a!) out) -> Tensor(a!) + python_module: fft + variants: function + dispatch: + CompositeExplicitAutograd: fft_rfftfreq_out + +- func: fft_fftshift(Tensor self, int[1]? dim=None) -> Tensor + python_module: fft + variants: function + +- func: fft_ifftshift(Tensor self, int[1]? dim=None) -> Tensor + python_module: fft + variants: function + +## Functions for linear algebra and the torch.linalg namespace +# Note [linalg namespace binding] +# Functions in the linalg python module should have their names start with +# "linalg_" and be bound to the desired Python name in +# torch/linalg/__init__.py, and the desired C++ name in torch/csrc/api/include/torch/linalg.h. +# The "linalg_" names should be hidden from the user and not documented. +# +# See linalg_det as an example. + +# "_ex" stands for experimental +- func: linalg_cholesky_ex(Tensor self, *, bool upper=False, bool check_errors=False) -> (Tensor L, Tensor info) + python_module: linalg + structured_delegate: linalg_cholesky_ex.L + +- func: linalg_cholesky_ex.L(Tensor self, *, bool upper=False, bool check_errors=False, Tensor(a!) L, Tensor(b!) info) -> (Tensor(a!) L, Tensor(b!) info) + python_module: linalg + structured: True + dispatch: + CPU, CUDA, MPS: linalg_cholesky_ex_out + +- func: linalg_cholesky(Tensor self, *, bool upper=False) -> Tensor + python_module: linalg + +- func: linalg_cholesky.out(Tensor self, *, bool upper=False, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +- func: linalg_cross(Tensor self, Tensor other, *, int dim=-1) -> Tensor + python_module: linalg + variants: function + structured_delegate: linalg_cross.out + dispatch: + ZeroTensor: linalg_cross_zerotensor + +- func: linalg_cross.out(Tensor self, Tensor other, *, int dim=-1, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + structured: True + dispatch: + CPU, CUDA, MPS, XPU: linalg_cross_out + +# linalg.lu_factor +- func: linalg_lu_factor(Tensor A, *, bool pivot=True) -> (Tensor LU, Tensor pivots) + python_module: linalg + variants: function + +- func: linalg_lu_factor.out(Tensor A, *, bool pivot=True, Tensor(a!) LU, Tensor(b!) pivots) -> (Tensor(a!) LU, Tensor(b!) pivots) + python_module: linalg + variants: function + +- func: linalg_lu_factor_ex(Tensor A, *, bool pivot=True, bool check_errors=False) -> (Tensor LU, Tensor pivots, Tensor info) + python_module: linalg + structured_delegate: linalg_lu_factor_ex.out + variants: function + +- func: linalg_lu_factor_ex.out(Tensor A, *, bool pivot=True, bool check_errors=False, Tensor(a!) LU, Tensor(b!) pivots, Tensor(c!) info) -> (Tensor(a!) LU, Tensor(b!) pivots, Tensor(c!) info) + python_module: linalg + variants: function + structured: True + dispatch: + CPU, CUDA, XPU: linalg_lu_factor_ex_out + MPS: linalg_lu_factor_ex_out_mps + +# linalg.lu +- func: linalg_lu(Tensor A, *, bool pivot=True) -> (Tensor P, Tensor L, Tensor U) + python_module: linalg + structured_delegate: linalg_lu.out + variants: function + +- func: linalg_lu.out(Tensor A, *, bool pivot=True, Tensor(a!) P, Tensor(b!) L, Tensor(c!) U) -> (Tensor(a!) P, Tensor(b!) L, Tensor(c!) U) + python_module: linalg + variants: function + structured: True + dispatch: + CPU, CUDA, MPS: linalg_lu_out + +# linalg.lu_solve +- func: linalg_lu_solve(Tensor LU, Tensor pivots, Tensor B, *, bool left=True, bool adjoint=False) -> Tensor + python_module: linalg + structured_delegate: linalg_lu_solve.out + variants: function + +- func: linalg_lu_solve.out(Tensor LU, Tensor pivots, Tensor B, *, bool left=True, bool adjoint=False, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + structured: True + dispatch: + CPU, CUDA, XPU, MPS: linalg_lu_solve_out + +# linalg.det +- func: _linalg_det(Tensor A) -> (Tensor result, Tensor LU, Tensor pivots) + structured_delegate: _linalg_det.result + +- func: _linalg_det.result(Tensor A, *, Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots) -> (Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots) + structured: True + dispatch: + CPU, CUDA, MPS, XPU: _linalg_det_out + +- func: linalg_det(Tensor A) -> Tensor + python_module: linalg + variants: function + +- func: linalg_det.out(Tensor A, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +# torch.det, alias for torch.linalg.det +- func: det(Tensor self) -> Tensor + variants: function, method + +- func: linalg_ldl_factor_ex(Tensor self, *, bool hermitian=False, bool check_errors=False) -> (Tensor LD, Tensor pivots, Tensor info) + structured_delegate: linalg_ldl_factor_ex.out + python_module: linalg + variants: function + +- func: linalg_ldl_factor_ex.out(Tensor self, *, bool hermitian=False, bool check_errors=False, Tensor(a!) LD, Tensor(b!) pivots, Tensor(c!) info) -> (Tensor(a!) LD, Tensor(b!) pivots, Tensor(c!) info) + structured: True + python_module: linalg + variants: function + dispatch: + CPU, CUDA: linalg_ldl_factor_ex_out + +- func: linalg_ldl_factor(Tensor self, *, bool hermitian=False) -> (Tensor LD, Tensor pivots) + python_module: linalg + variants: function + +- func: linalg_ldl_factor.out(Tensor self, *, bool hermitian=False, Tensor(a!) LD, Tensor(b!) pivots) -> (Tensor(a!) LD, Tensor(b!) pivots) + python_module: linalg + variants: function + +- func: linalg_ldl_solve(Tensor LD, Tensor pivots, Tensor B, *, bool hermitian=False) -> Tensor + structured_delegate: linalg_ldl_solve.out + python_module: linalg + variants: function + +- func: linalg_ldl_solve.out(Tensor LD, Tensor pivots, Tensor B, *, bool hermitian=False, Tensor(a!) out) -> Tensor(a!) + structured: True + python_module: linalg + variants: function + dispatch: + CPU, CUDA: linalg_ldl_solve_out + +- func: linalg_lstsq(Tensor self, Tensor b, float? rcond=None, *, str? driver=None) -> (Tensor solution, Tensor residuals, Tensor rank, Tensor singular_values) + python_module: linalg + variants: function + dispatch: + CompositeExplicitAutograd: linalg_lstsq + tags: dynamic_output_shape + +- func: linalg_lstsq.out(Tensor self, Tensor b, float? rcond=None, *, str? driver=None, Tensor(a!) solution, Tensor(b!) residuals, Tensor(c!) rank, Tensor(d!) singular_values) -> (Tensor(a!) solution, Tensor(b!) residuals, Tensor(c!) rank, Tensor(d!) singular_values) + python_module: linalg + variants: function + dispatch: + CPU, CUDA, MPS: linalg_lstsq_out + tags: dynamic_output_shape + +# torch.linalg.matmul, alias for torch.matmul +- func: linalg_matmul(Tensor self, Tensor other) -> Tensor + python_module: linalg + variants: function + +- func: linalg_matmul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +- func: linalg_vecdot(Tensor x, Tensor y, *, int dim=-1) -> Tensor + python_module: linalg + variants: function + +- func: linalg_vecdot.out(Tensor x, Tensor y, *, int dim=-1, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +- func: linalg_matrix_exp(Tensor self) -> Tensor + python_module: linalg + variants: function + dispatch: + CPU, CUDA, MPS: linalg_matrix_exp + autogen: linalg_matrix_exp.out + +- func: linalg_matrix_sqrth(Tensor self) -> Tensor + python_module: linalg + variants: function + dispatch: + CPU, CUDA: linalg_matrix_sqrth + autogen: linalg_matrix_sqrth.out + +- func: _linalg_slogdet(Tensor A) -> (Tensor sign, Tensor logabsdet, Tensor LU, Tensor pivots) + structured_delegate: _linalg_slogdet.sign + +- func: _linalg_slogdet.sign(Tensor A, *, Tensor(a!) sign, Tensor(b!) logabsdet, Tensor(c!) LU, Tensor(d!) pivots) -> (Tensor(a!) sign, Tensor(b!) logabsdet, Tensor(c!) LU, Tensor(d!) pivots) + structured: True + dispatch: + CPU, CUDA, MPS, XPU: _linalg_slogdet_out + +- func: linalg_slogdet(Tensor A) -> (Tensor sign, Tensor logabsdet) + python_module: linalg + +- func: linalg_slogdet.out(Tensor A, *, Tensor(a!) sign, Tensor(b!) logabsdet) -> (Tensor(a!) sign, Tensor(b!) logabsdet) + python_module: linalg + +- func: slogdet(Tensor self) -> (Tensor sign, Tensor logabsdet) + variants: function, method + +- func: slogdet.out(Tensor self, *, Tensor(a!) sign, Tensor(b!) logabsdet) -> (Tensor(a!) sign, Tensor(b!) logabsdet) + variants: function + +- func: logdet(Tensor self) -> Tensor + variants: function, method + +- func: linalg_eig(Tensor self) -> (Tensor eigenvalues, Tensor eigenvectors) + python_module: linalg + variants: function + dispatch: + CPU, CUDA: linalg_eig + +- func: linalg_eig.out(Tensor self, *, Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) + python_module: linalg + dispatch: + CPU, CUDA: linalg_eig_out + +- func: _linalg_eigvals(Tensor self) -> Tensor + python_module: linalg + dispatch: + CPU, CUDA: _linalg_eigvals + +- func: linalg_eigvals(Tensor self) -> Tensor + python_module: linalg + +- func: linalg_eigvals.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + dispatch: + CPU, CUDA: linalg_eigvals_out + +# This function is exposes the `compute_v` flag, which is then used to implement `linalg.eigh` and +# `linalg.eigvalsh` as composite functions that call this one +- func: _linalg_eigh(Tensor A, str UPLO="L", bool compute_v=True) -> (Tensor eigenvalues, Tensor eigenvectors) + structured_delegate: _linalg_eigh.eigenvalues + +- func: _linalg_eigh.eigenvalues(Tensor A, str UPLO="L", bool compute_v=True, *, Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) + structured: True + dispatch: + CPU, CUDA, MPS: _linalg_eigh_out + +- func: linalg_eigh(Tensor self, str UPLO="L") -> (Tensor eigenvalues, Tensor eigenvectors) + python_module: linalg + +- func: linalg_eigh.eigvals(Tensor self, str UPLO="L", *, Tensor(a!) eigvals, Tensor(b!) eigvecs) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) + python_module: linalg + +- func: linalg_eigvalsh(Tensor self, str UPLO="L") -> Tensor + python_module: linalg + +- func: linalg_eigvalsh.out(Tensor self, str UPLO="L", *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +- func: linalg_householder_product(Tensor input, Tensor tau) -> Tensor + python_module: linalg + variants: function + dispatch: + CPU, CUDA, MPS: linalg_householder_product + +- func: linalg_householder_product.out(Tensor input, Tensor tau, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + dispatch: + CPU, CUDA, MPS: linalg_householder_product_out + +- func: linalg_inv_ex(Tensor A, *, bool check_errors=False) -> (Tensor inverse, Tensor info) + python_module: linalg + structured_delegate: linalg_inv_ex.inverse + +- func: linalg_inv_ex.inverse(Tensor A, *, bool check_errors=False, Tensor(a!) inverse, Tensor(b!) info) -> (Tensor(a!) inverse, Tensor(b!) info) + python_module: linalg + structured: True + dispatch: + CPU, CUDA, XPU: linalg_inv_ex_out + MPS: linalg_inv_ex_out_mps + +- func: linalg_inv(Tensor A) -> Tensor + python_module: linalg + +- func: linalg_inv.out(Tensor A, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +- func: inverse(Tensor self) -> Tensor + variants: function, method + +- func: inverse.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + +- func: inner(Tensor self, Tensor other) -> Tensor + variants: function, method + +- func: inner.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + +- func: outer(Tensor self, Tensor vec2) -> Tensor + variants: function, method + +- func: outer.out(Tensor self, Tensor vec2, *, Tensor(a!) out) -> Tensor(a!) + +# torch.ger, alias for torch.outer +- func: ger(Tensor self, Tensor vec2) -> Tensor + variants: function, method + +- func: ger.out(Tensor self, Tensor vec2, *, Tensor(a!) out) -> Tensor(a!) + +- func: linalg_norm(Tensor self, Scalar? ord=None, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + python_module: linalg + variants: function + +- func: linalg_norm.ord_str(Tensor self, str ord, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + python_module: linalg + variants: function + +- func: linalg_norm.out(Tensor self, Scalar? ord=None, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_norm.ord_str_out(Tensor self, str ord, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_vector_norm(Tensor self, Scalar ord=2, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + python_module: linalg + variants: function + structured_delegate: linalg_vector_norm.out + dispatch: + SparseCPU, SparseCUDA, SparseMPS: linalg_vector_norm_sparse + tags: reduction + +- func: linalg_vector_norm.out(Tensor self, Scalar ord=2, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + structured: True + dispatch: + CPU, CUDA, MPS, XPU: linalg_vector_norm_out + tags: reduction + +# Computes sum(|x|^ord) - the "power sum" without the final root. +# This is useful for distributed computing where partial power sums +# can be reduced across shards before taking the final root. +- func: linalg__powsum(Tensor self, Scalar ord=2, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + python_module: linalg + variants: function + dispatch: + CompositeExplicitAutograd: linalg__powsum_slow + CPU, CUDA: linalg__powsum + tags: reduction + +- func: linalg_matrix_norm(Tensor self, Scalar ord, int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + python_module: linalg + +- func: linalg_matrix_norm.out(Tensor self, Scalar ord, int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +- func: linalg_matrix_norm.str_ord(Tensor self, str ord='fro', int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + python_module: linalg + +- func: linalg_matrix_norm.str_ord_out(Tensor self, str ord='fro', int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +# This function is exposes the `compute_uv` flag, which is then used to implement `linalg.svd` and +# `linalg.svdvals` as composite functions that call this one +- func: _linalg_svd(Tensor A, bool full_matrices=False, bool compute_uv=True, *, str? driver=None) -> (Tensor U, Tensor S, Tensor Vh) + variants: function + structured_delegate: _linalg_svd.U + +- func: _linalg_svd.U(Tensor A, bool full_matrices=False, bool compute_uv=True, *, str? driver=None, Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh) + structured: True + dispatch: + CPU, CUDA, MPS: _linalg_svd_out + +- func: linalg_svd(Tensor A, bool full_matrices=True, *, str? driver=None) -> (Tensor U, Tensor S, Tensor Vh) + python_module: linalg + variants: function + +- func: linalg_svd.U(Tensor A, bool full_matrices=True, *, str? driver=None, Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh) + python_module: linalg + variants: function + +- func: linalg_svdvals(Tensor A, *, str? driver=None) -> Tensor + python_module: linalg + variants: function + +- func: linalg_svdvals.out(Tensor A, *, str? driver=None, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_cond(Tensor self, Scalar? p=None) -> Tensor + python_module: linalg + variants: function + +- func: linalg_cond.out(Tensor self, Scalar? p=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_cond.p_str(Tensor self, str p) -> Tensor + python_module: linalg + variants: function + +- func: linalg_cond.p_str_out(Tensor self, str p, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_pinv.atol_rtol_tensor(Tensor self, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False) -> Tensor + python_module: linalg + variants: function + dispatch: + # calls svd, which calls mH() (view op) + # also calls narrow() + CompositeExplicitAutogradNonFunctional: linalg_pinv + +- func: linalg_pinv.atol_rtol_tensor_out(Tensor self, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + dispatch: + CompositeExplicitAutograd: linalg_pinv_out + +- func: linalg_pinv.atol_rtol_float(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False) -> Tensor + cpp_no_default_args: ['atol', 'rtol'] + python_module: linalg + variants: function + +- func: linalg_pinv.atol_rtol_float_out(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!) + cpp_no_default_args: ['atol', 'rtol'] + python_module: linalg + variants: function + +- func: linalg_pinv(Tensor self, float rcond, bool hermitian=False) -> Tensor + python_module: linalg + variants: function + +- func: linalg_pinv.rcond_tensor(Tensor self, Tensor rcond, bool hermitian=False) -> Tensor + python_module: linalg + variants: function + +- func: linalg_pinv.out(Tensor self, float rcond, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_pinv.out_rcond_tensor(Tensor self, Tensor rcond, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: _linalg_solve_ex(Tensor A, Tensor B, *, bool left=True, bool check_errors=False) -> (Tensor result, Tensor LU, Tensor pivots, Tensor info) + structured_delegate: _linalg_solve_ex.result + +- func: _linalg_solve_ex.result(Tensor A, Tensor B, *, bool left=True, bool check_errors=False, Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots, Tensor(d!) info) -> (Tensor(a!) result, Tensor(b!) LU, Tensor(c!) pivots, Tensor(d!) info) + structured: True + dispatch: + CPU, CUDA, XPU: _linalg_solve_ex_out + MPS: _linalg_solve_ex_out_mps + +- func: linalg_solve_ex(Tensor A, Tensor B, *, bool left=True, bool check_errors=False) -> (Tensor result, Tensor info) + python_module: linalg + +- func: linalg_solve_ex.out(Tensor A, Tensor B, *, bool left=True, bool check_errors=False, Tensor(a!) result, Tensor(b!) info) -> (Tensor(a!) result, Tensor(b!) info) + python_module: linalg + +- func: linalg_solve(Tensor A, Tensor B, *, bool left=True) -> Tensor + python_module: linalg + +- func: _spsolve(Tensor A, Tensor B, *, bool left=True) -> Tensor + python_module: sparse + dispatch: + SparseCsrCUDA: _sparse_csr_linear_solve + +- func: linalg_solve.out(Tensor A, Tensor B, *, bool left=True, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +- func: linalg_tensorinv(Tensor self, int ind=2) -> Tensor + python_module: linalg + variants: function + +- func: linalg_tensorinv.out(Tensor self, int ind=2, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_tensorsolve(Tensor self, Tensor other, int[]? dims=None) -> Tensor + python_module: linalg + variants: function + +- func: linalg_tensorsolve.out(Tensor self, Tensor other, int[]? dims=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_qr(Tensor A, str mode='reduced') -> (Tensor Q, Tensor R) + python_module: linalg + variants: function + structured_delegate: linalg_qr.out + +- func: linalg_qr.out(Tensor A, str mode='reduced', *, Tensor(a!) Q, Tensor(b!) R) -> (Tensor(a!) Q, Tensor(b!) R) + python_module: linalg + structured: True + dispatch: + CPU, CUDA, MPS: linalg_qr_out + +- func: linalg_polar(Tensor A) -> (Tensor U, Tensor H) + python_module: linalg + variants: function + structured_delegate: linalg_polar.out + +- func: linalg_polar.out(Tensor A, *, Tensor(a!) U, Tensor(b!) H) -> (Tensor(a!) U, Tensor(b!) H) + python_module: linalg + structured: True + dispatch: + CPU, CUDA, MPS: linalg_polar_out + +- func: linalg_matrix_power(Tensor self, int n) -> Tensor + python_module: linalg + +- func: linalg_matrix_power.out(Tensor self, int n, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +- func: linalg_matrix_rank.atol_rtol_tensor(Tensor input, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False) -> Tensor + python_module: linalg + variants: function + +- func: linalg_matrix_rank.atol_rtol_tensor_out(Tensor input, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_matrix_rank.atol_rtol_float(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False) -> Tensor + cpp_no_default_args: ['atol', 'rtol'] + python_module: linalg + variants: function + +- func: linalg_matrix_rank.atol_rtol_float_out(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!) + cpp_no_default_args: ['atol', 'rtol'] + python_module: linalg + variants: function + +- func: linalg_matrix_rank(Tensor self, float tol, bool hermitian=False) -> Tensor + python_module: linalg + variants: function + +- func: linalg_matrix_rank.out(Tensor self, float tol, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_matrix_rank.tol_tensor(Tensor input, Tensor tol, bool hermitian=False) -> Tensor + python_module: linalg + variants: function + +- func: linalg_matrix_rank.out_tol_tensor(Tensor input, Tensor tol, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_multi_dot(Tensor[] tensors) -> Tensor + python_module: linalg + +- func: linalg_multi_dot.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +## Functions related to the `torch.nested` namespace +# Note [nested namespace binding] +# Functions in the nested python module should have their names start with +# "nested_" underscore and be bound to the desired Python name in +# torch/nested/__init__.py, and the desired C++ name in torch/csrc/api/include/torch/nested.h. +# The "nested_" names should be hidden from the user and not documented. + +- func: nested_to_padded_tensor(Tensor self, float padding, int[]? output_size=None) -> Tensor + python_module: nested + variants: function + +## Functions that are only for testing +# It is undocumented and should not be used outside of tests. +- func: _test_serialization_subcmul(Tensor self, Tensor other, Scalar alpha=1) -> Tensor + +# Note: for testing COW materialization within `at::parallel_for` loop function +- func: _test_parallel_materialize(Tensor self, int num_parallel, bool skip_first=False) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: _test_parallel_materialize + +# Note: this function is only for testing. +- func: _test_optional_intlist(Tensor values, int[]? addends) -> Tensor + python_module: nn + dispatch: + CPU: _test_optional_intlist + autogen: _test_optional_intlist.out + +# Note: this function is only for testing. +- func: _test_optional_filled_intlist(Tensor values, int[2]? addends) -> Tensor + python_module: nn + dispatch: + CPU: _test_optional_intlist + autogen: _test_optional_filled_intlist.out + +# Note: this function is only for testing. +- func: _test_optional_floatlist(Tensor values, float[]? addends) -> Tensor + python_module: nn + dispatch: + CPU: _test_optional_floatlist + autogen: _test_optional_floatlist.out + +# Note: this function is only for testing. +- func: _test_string_default(Tensor dummy, str a="\"'\\", str b='"\'\\') -> Tensor + python_module: nn + +# Note: this function is only for testing. +- func: _test_ambiguous_defaults.a(Tensor dummy, int a=1, int b=1) -> Tensor + python_module: nn + +# Note: this function is only for testing. +- func: _test_ambiguous_defaults.b(Tensor dummy, int a=2, str b="2") -> Tensor + cpp_no_default_args: ['a', 'b'] + python_module: nn + +# Note: this function is only for testing. +- func: _test_warn_in_autograd(Tensor self) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: _test_warn_in_autograd + autogen: _test_warn_in_autograd.out + +# Note: this function is only for testing. +- func: _test_autograd_multiple_dispatch.fullcoverage(Tensor self) -> Tensor + dispatch: + # the NestedTensor keys are necessary because NestedTensor has been removed + # from the CompositeExplicitAutograd keyset see Note [NestedTensor Not Included in Backend Keys] + CompositeExplicitAutograd, NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: _test_autograd_multiple_dispatch_fullcoverage + autogen: _test_autograd_multiple_dispatch.fullcoverage_out + +# Note: this function is only for testing. +- func: _test_autograd_multiple_dispatch.ntonly(Tensor self, bool b) -> Tensor + dispatch: + CompositeImplicitAutograd, NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: _test_autograd_multiple_dispatch_ntonly + +# Note: this function is only for testing. +- func: _test_autograd_multiple_dispatch_view(Tensor(a) self) -> Tensor(a) + dispatch: + CompositeExplicitAutograd: _test_autograd_multiple_dispatch_view + +# Note: this function is only for testing. +- func: _test_autograd_multiple_dispatch_view_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: _test_autograd_multiple_dispatch_view_copy + tags: view_copy + autogen: _test_autograd_multiple_dispatch_view_copy.out + +- func: segment_reduce(Tensor data, str reduce, *, Tensor? lengths=None, Tensor? indices=None, Tensor? offsets=None, int axis=0, bool unsafe=False, Scalar? initial=None) -> Tensor + variants: function + dispatch: + CPU, CUDA, XPU: segment_reduce_kernel + autogen: segment_reduce.out + +- func: _segment_reduce_backward(Tensor grad, Tensor output, Tensor data, str reduce, *, Tensor? lengths=None, Tensor? offsets=None, int axis=0, Scalar? initial=None) -> Tensor + variants: function + dispatch: + CPU, CUDA, XPU: _segment_reduce_backward_kernel + autogen: _segment_reduce_backward.out + +- func: pad_sequence(Tensor[] sequences, bool batch_first=False, float padding_value=0.0, str padding_side="right") -> Tensor + python_module: nn + variants: function + +- func: flatten_dense_tensors(Tensor[] tensors) -> Tensor + variants: function + python_module: nn + +- func: unflatten_dense_tensors(Tensor flat, Tensor[] tensors) -> Tensor[] + variants: function + python_module: nn + +- func: _nested_tensor_from_tensor_list(Tensor[] list, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: _nested_tensor_from_tensor_list + autogen: _nested_tensor_from_tensor_list.out + +- func: _fw_primal_copy(Tensor self, int level) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: _fw_primal_copy + tags: view_copy + autogen: _fw_primal_copy.out + +- func: _make_dual_copy(Tensor primal, Tensor tangent, int level) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: _make_dual_copy + tags: view_copy + autogen: _make_dual_copy.out + +- func: view_as_real_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: view_as_real_copy + tags: view_copy + autogen: view_as_real_copy.out + +- func: view_as_complex_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: view_as_complex_copy + tags: view_copy + autogen: view_as_complex_copy.out + +- func: _conj_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: _conj_copy + tags: view_copy + autogen: _conj_copy.out + +- func: _neg_view_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: _neg_view_copy + tags: view_copy + autogen: _neg_view_copy.out + +- func: as_strided_copy(Tensor self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: as_strided_copy_symint + tags: view_copy + autogen: as_strided_copy.out + +- func: _sparse_broadcast_to_copy(Tensor self, int[] size) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: _sparse_broadcast_to_copy + tags: view_copy + autogen: _sparse_broadcast_to_copy.out + +- func: diagonal_copy(Tensor self, int offset=0, int dim1=0, int dim2=1) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: diagonal_copy + tags: view_copy + autogen: diagonal_copy.out + +- func: expand_copy(Tensor self, SymInt[] size, *, bool implicit=False) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: expand_copy_symint + tags: view_copy + autogen: expand_copy.out + +- func: permute_copy(Tensor self, int[] dims) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: permute_copy + tags: view_copy + autogen: permute_copy.out + +- func: _reshape_alias_copy(Tensor self, SymInt[] size, SymInt[] stride) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: _reshape_alias_copy_symint + tags: view_copy + autogen: _reshape_alias_copy.out + +- func: select_copy.int(Tensor self, int dim, SymInt index) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: select_copy_symint + SparseCsrCPU, SparseCsrCUDA, SparseCsrMeta, SparseCsrXPU: select_copy_sparse_csr + tags: view_copy + autogen: select_copy.int_out + +- func: detach_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: detach_copy + tags: view_copy + autogen: detach_copy.out + +- func: slice_copy.Tensor(Tensor self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: slice_copy_Tensor_symint + tags: view_copy + autogen: slice_copy.Tensor_out + +- func: split_copy.Tensor(Tensor self, SymInt split_size, int dim=0) -> Tensor[] + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: split_copy_Tensor_symint + tags: view_copy + +- func: split_with_sizes_copy(Tensor self, SymInt[] split_sizes, int dim=0) -> Tensor[] + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: split_with_sizes_copy_symint + tags: view_copy + +- func: squeeze_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: squeeze_copy + tags: view_copy + autogen: squeeze_copy.out + +- func: squeeze_copy.dim(Tensor self, int dim) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: squeeze_copy_dim + tags: view_copy + autogen: squeeze_copy.dim_out + +- func: squeeze_copy.dims(Tensor self, int[] dim) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: squeeze_copy_dims + tags: view_copy + autogen: squeeze_copy.dims_out + +- func: t_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: t_copy + tags: view_copy + autogen: t_copy.out + +- func: transpose_copy.int(Tensor self, int dim0, int dim1) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: transpose_copy_int + tags: view_copy + autogen: transpose_copy.int_out + +- func: unsqueeze_copy(Tensor self, int dim) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: unsqueeze_copy + tags: view_copy + autogen: unsqueeze_copy.out + +- func: _indices_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: _indices_copy + tags: view_copy + autogen: _indices_copy.out + +- func: _values_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: _values_copy + tags: view_copy + autogen: _values_copy.out + +- func: indices_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: indices_copy + tags: view_copy + autogen: indices_copy.out + +- func: values_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: values_copy + tags: view_copy + autogen: values_copy.out + +- func: crow_indices_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: crow_indices_copy + tags: view_copy + autogen: crow_indices_copy.out + +- func: col_indices_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: col_indices_copy + tags: view_copy + autogen: col_indices_copy.out + +- func: ccol_indices_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: ccol_indices_copy + tags: view_copy + autogen: ccol_indices_copy.out + +- func: row_indices_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: row_indices_copy + tags: view_copy + autogen: row_indices_copy.out + +- func: unbind_copy.int(Tensor self, int dim=0) -> Tensor[] + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: unbind_copy_int + tags: view_copy + +- func: unbind_copy.int_out(Tensor self, int dim=0, *, Tensor(a!)[] out) -> () + variants: function + dispatch: + CompositeExplicitAutograd: unbind_copy_int_out + +- func: split_copy.Tensor_out(Tensor self, SymInt split_size, int dim=0, *, Tensor(a!)[] out) -> () + variants: function + dispatch: + CompositeExplicitAutograd: split_copy_Tensor_out + +- func: split_with_sizes_copy.out(Tensor self, SymInt[] split_sizes, int dim=0, *, Tensor(a!)[] out) -> () + variants: function + dispatch: + CompositeExplicitAutograd: split_with_sizes_copy_out + CUDA: split_with_sizes_copy_out_cuda + XPU: split_with_sizes_copy_out_xpu + +- func: view_copy(Tensor self, SymInt[] size) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: view_copy_symint + tags: view_copy + autogen: view_copy.out + +- func: view_copy.dtype(Tensor self, ScalarType dtype) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: view_copy_dtype + tags: view_copy + autogen: view_copy.dtype_out + +- func: unfold_copy(Tensor self, int dimension, int size, int step) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: unfold_copy + tags: view_copy + autogen: unfold_copy.out + +- func: alias_copy(Tensor self) -> Tensor + variants: function + dispatch: + CompositeExplicitAutogradNonFunctional: alias_copy + tags: view_copy + autogen: alias_copy.out + +- func: to_padded_tensor(Tensor self, float padding, SymInt[]? output_size=None) -> Tensor + variants: method + dispatch: + NestedTensorCPU: NestedTensor_to_padded_tensor_generic + NestedTensorCUDA: NestedTensor_to_padded_tensor_cuda + NestedTensorXPU: NestedTensor_to_padded_tensor_xpu + autogen: to_padded_tensor.out + +- func: _jagged_to_padded_dense_forward(Tensor values, Tensor[] offsets, SymInt[] max_lengths, float padding_value=0.0) -> Tensor + variants: function + dispatch: + CUDA: _fbgemm_jagged_to_padded_dense_forward + CPU: _jagged_to_padded_dense_forward_cpu + XPU: _jagged_to_padded_dense_forward_xpu + +- func: _padded_dense_to_jagged_forward(Tensor dense, Tensor[] offsets, SymInt? total_L=None) -> Tensor + variants: function + dispatch: + CUDA: _fbgemm_dense_to_jagged_forward_symint + CPU: _padded_dense_to_jagged_forward_cpu + XPU: _padded_dense_to_jagged_forward_symint_xpu + +- func: _nested_from_padded_tensor(Tensor padded, Tensor offsets, Tensor dummy, int ragged_idx=1, Tensor? min_seqlen=None, Tensor? max_seqlen=None, SymInt? sum_S=None) -> Tensor + variants: function + device_check: NoCheck + dispatch: {} + +- func: _nested_tensor_softmax_with_shape(Tensor self, Tensor query) -> Tensor + dispatch: + NestedTensorCPU: NestedTensor_softmax_dropout + NestedTensorCUDA: NestedTensor_softmax_dropout_cuda + NestedTensorXPU: NestedTensor_softmax_dropout_xpu + tags: nondeterministic_seeded + +- func: _safe_softmax(Tensor self, int dim, ScalarType? dtype=None) -> Tensor + dispatch: + CompositeExplicitAutograd: _safe_softmax + XPU: _safe_softmax_xpu + NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: _safe_softmax + +# Apparently, putting "forward" in the name will cause Python bindings to be skipped, so "fwd" it is. +- func: _transformer_encoder_layer_fwd(Tensor src, int embed_dim, int num_heads, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, bool use_gelu, bool norm_first, float eps, Tensor norm_weight_1, Tensor norm_bias_1, Tensor norm_weight_2, Tensor norm_bias_2, Tensor ffn_weight_1, Tensor ffn_bias_1, Tensor ffn_weight_2, Tensor ffn_bias_2, Tensor? mask=None, int? mask_type=None) -> Tensor + variants: function + dispatch: + CPU, CUDA, XPU, NestedTensorCPU, NestedTensorHPU, NestedTensorCUDA, NestedTensorXPU: transformer_encoder_layer_forward + autogen: _transformer_encoder_layer_fwd.out + +- func: _native_multi_head_attention(Tensor query, Tensor key, Tensor value, int embed_dim, int num_head, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, Tensor? mask=None, bool need_weights=True, bool average_attn_weights=True, int? mask_type=None) -> (Tensor, Tensor) + variants: function + dispatch: + CPU, NestedTensorCPU: native_multi_head_attention_cpu + CUDA, NestedTensorCUDA: native_multi_head_attention_cuda + XPU, NestedTensorXPU: native_multi_head_attention_xpu + autogen: _native_multi_head_attention.out + +- func: scaled_dot_product_attention(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, *, float? scale=None, bool enable_gqa=False) -> Tensor + python_module: nn + variants: function + autogen: scaled_dot_product_attention.out + tags: nondeterministic_seeded + +# This aten function is kept so that we can test the choice function from Python +- func: _fused_sdp_choice(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, *, float? scale=None, bool enable_gqa=False) -> int + dispatch: + Meta: _fused_sdp_choice_meta + CPU, NestedTensorCPU: _fused_sdp_choice_cpp + CUDA, NestedTensorCUDA: _fused_sdp_choice_cuda + XPU: _fused_sdp_choice_xpu + tags: nondeterministic_seeded + +- func: _scaled_dot_product_attention_math(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, Tensor? dropout_mask=None, *, float? scale=None, bool enable_gqa=False) -> (Tensor, Tensor) + variants: function + tags: nondeterministic_seeded + +- func: _scaled_dot_product_attention_math_for_mps(Tensor query, Tensor key, Tensor value, Tensor? attn_mask=None, float dropout_p=0.0, bool is_causal=False, Tensor? dropout_mask=None, *, float? scale=None, bool enable_gqa=False) -> (Tensor, Tensor) + dispatch: + MPS: _scaled_dot_product_attention_math_mps + tags: nondeterministic_seeded + +- func: _scaled_dot_product_flash_attention(Tensor query, Tensor key, Tensor value, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor rng_state, Tensor unused, Tensor debug_attn_mask) + dispatch: + CUDA: _scaled_dot_product_flash_attention_cuda + XPU: _scaled_dot_product_flash_attention_xpu + NestedTensorCUDA: _scaled_dot_product_flash_attention_nestedtensor_cuda + tags: nondeterministic_seeded + +- func: _scaled_dot_product_flash_attention.quantized(Tensor query, Tensor key, Tensor value, Tensor? q_descale, Tensor? k_descale, Tensor? v_descale, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor rng_state, Tensor unused, Tensor debug_attn_mask) + dispatch: + CUDA: _scaled_dot_product_flash_attention_cuda_quantized + tags: nondeterministic_seeded + +- func: _scaled_dot_product_flash_attention_for_cpu(Tensor query, Tensor key, Tensor value, float dropout_p=0.0, bool is_causal=False, *, Tensor? attn_mask=None, float? scale=None) -> (Tensor output, Tensor logsumexp) + dispatch: + CPU: _scaled_dot_product_flash_attention_cpu + tags: nondeterministic_seeded + +- func: _scaled_dot_product_fused_attention_overrideable(Tensor query, Tensor key, Tensor value, Tensor? attn_bias=None, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask) + dispatch: + CompositeExplicitAutograd: _scaled_dot_product_fused_attention_overrideable + XPU: _scaled_dot_product_fused_attention_overrideable_xpu + tags: nondeterministic_seeded + +- func: _scaled_dot_product_flash_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value) + device_check: NoCheck + variants: function + dispatch: + CUDA: _scaled_dot_product_flash_attention_backward_cuda + XPU: _scaled_dot_product_flash_attention_backward_xpu + NestedTensorCUDA: _scaled_dot_product_flash_attention_backward_nested + +- func: _scaled_dot_product_flash_attention_for_cpu_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, float dropout_p, bool is_causal, *, Tensor? attn_mask=None, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value) + device_check: NoCheck + variants: function + dispatch: + CPU: _scaled_dot_product_flash_attention_cpu_backward + +- func: _scaled_dot_product_fused_attention_overrideable_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor attn_bias, bool[4] grad_input_mask, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value, Tensor grad_attn_bias) + device_check: NoCheck + variants: function + dispatch: + CompositeExplicitAutograd: _scaled_dot_product_fused_attention_overrideable_backward + +- func: _scaled_dot_product_efficient_attention(Tensor query, Tensor key, Tensor value, Tensor? attn_bias, bool compute_log_sumexp, float dropout_p=0.0, bool is_causal=False, *, float? scale=None) -> (Tensor output, Tensor log_sumexp, Tensor philox_seed, Tensor philox_offset) + dispatch: + CUDA: _scaled_dot_product_efficient_attention_cuda + XPU: _scaled_dot_product_efficient_attention_xpu + NestedTensorCUDA: _scaled_dot_product_efficient_attention_nestedtensor_cuda + tags: nondeterministic_seeded + +- func: _scaled_dot_product_efficient_attention_backward(Tensor grad_out_, Tensor query, Tensor key, Tensor value, Tensor attn_bias, Tensor out, Tensor logsumexp, Tensor philox_seed, Tensor philox_offset, float dropout_p, bool[4] grad_input_mask, bool is_causal=False, *, float? scale=None) -> (Tensor, Tensor, Tensor, Tensor) + device_check: NoCheck + dispatch: + CUDA: _scaled_dot_product_efficient_attention_backward_cuda + XPU: _scaled_dot_product_efficient_attention_backward_xpu + tags: nondeterministic_seeded + +- func: _scaled_dot_product_cudnn_attention(Tensor query, Tensor key, Tensor value, Tensor? attn_bias, bool compute_log_sumexp, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask) + dispatch: + CUDA: _scaled_dot_product_cudnn_attention_cuda + NestedTensorCUDA: _scaled_dot_product_cudnn_attention_nestedtensor_cuda + tags: nondeterministic_seeded + +- func: _scaled_dot_product_cudnn_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor philox_seed, Tensor philox_offset, Tensor attn_bias, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, *, float? scale=None) -> (Tensor, Tensor, Tensor) + dispatch: + CUDA: _scaled_dot_product_cudnn_attention_backward_cuda + NestedTensorCUDA: _scaled_dot_product_cudnn_attention_nestedtensor_backward_cuda + tags: nondeterministic_seeded + +- func: _flash_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, bool return_debug_mask, *, float? scale=None, SymInt? window_size_left=None, SymInt? window_size_right=None, Tensor? seqused_k=None, Tensor? alibi_slopes=None, Tensor? block_table=None, int? num_splits=None) -> (Tensor output, Tensor softmax_logsumexp, Tensor rng_state, Tensor unused, Tensor debug_attn_mask) + variants: function + dispatch: + CUDA: _flash_attention_forward + tags: nondeterministic_seeded + +- func: _flash_attention_forward_no_dropout_inplace(Tensor(a!) out, Tensor query, Tensor key, Tensor value, Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, bool return_debug_mask, *, float? scale=None, SymInt? window_size_left=None, SymInt? window_size_right=None, Tensor? seqused_k=None, Tensor? alibi_slopes=None, Tensor? block_table=None, int? num_splits=None) -> Tensor softmax_logsumexp + variants: function + dispatch: + CUDA: _flash_attention_forward_no_dropout_inplace + tags: nondeterministic_seeded + +- func: _flash_attention_forward.quantized(Tensor query, Tensor key, Tensor value, Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, bool return_debug_mask, Tensor? q_descale, Tensor? k_descale, Tensor? v_descale, *, float? scale=None, SymInt? window_size_left=None, SymInt? window_size_right=None, Tensor? seqused_k=None, Tensor? alibi_slopes=None) -> (Tensor output, Tensor softmax_logsumexp, Tensor rng_state, Tensor unused, Tensor debug_attn_mask) + variants: function + dispatch: + CUDA: _flash_attention_forward_quantized + tags: nondeterministic_seeded + +- func: _flash_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor rng_state, Tensor unused, *, float? scale=None, SymInt? window_size_left=None, SymInt? window_size_right=None) -> (Tensor, Tensor, Tensor) + device_check: NoCheck + variants: function + dispatch: + CUDA: _flash_attention_backward + +# Returns output, logsumexp if compute_logsumexp +- func: _efficient_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? bias, Tensor? cu_seqlens_q, Tensor? cu_seqlens_k, SymInt? max_seqlen_q, SymInt? max_seqlen_k, float dropout_p, int custom_mask_type, bool compute_log_sumexp=False, *, float? scale=None, Tensor? seqlen_k=None, int? window_size=None) -> (Tensor output, Tensor logsumexp, Tensor philox_seed, Tensor philox_offset, SymInt max_seqlen_batch_q, SymInt max_seqlen_batch_k) + variants: function + dispatch: + CUDA: _efficient_attention_forward + tags: nondeterministic_seeded + +- func: _efficient_attention_backward(Tensor grad_out_, Tensor query, Tensor key, Tensor value, Tensor? bias, Tensor out, Tensor? cu_seqlens_q, Tensor? cu_seqlens_k, SymInt max_seqlen_q, SymInt max_seqlen_k, Tensor logsumexp, float dropout_p, Tensor philox_seed, Tensor philox_offset, int custom_mask_type, bool bias_requires_grad, *, float? scale=None, int? num_splits_key=None, int? window_size=None, bool shared_storage_dqdkdv=False) -> (Tensor, Tensor, Tensor, Tensor) + device_check: NoCheck + variants: function + dispatch: + CUDA: _efficient_attention_backward + +- func: _cudnn_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? attn_bias, Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, bool compute_log_sumexp, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None, Tensor? seqused_k=None, Tensor? block_table=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask) + dispatch: + CUDA: _cudnn_attention_forward + tags: nondeterministic_seeded + +- func: _cudnn_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor philox_seed, Tensor philox_offset, Tensor attn_bias, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, *, float? scale=None) -> (Tensor, Tensor, Tensor) + dispatch: + CUDA: _cudnn_attention_backward + tags: nondeterministic_seeded + +- func: _triton_scaled_dot_attention(Tensor q, Tensor k, Tensor v, float dropout_p=0.0) -> Tensor + variants: function + dispatch: + CUDA: triton_scaled_dot_attention + tags: nondeterministic_seeded + autogen: _triton_scaled_dot_attention.out + +- func: _fill_mem_eff_dropout_mask_(Tensor(a!) self, float dropout_p, int seed, int offset) -> Tensor(a!) + variants: function + dispatch: + CUDA, XPU: _fill_mem_eff_dropout_mask_ + tags: nondeterministic_seeded + +- func: _triton_multi_head_attention(Tensor query, Tensor key, Tensor value, int embed_dim, int num_head, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, Tensor? mask=None) -> Tensor + variants: function + dispatch: + CUDA: triton_multi_head_attention + autogen: _triton_multi_head_attention.out + +- func: special_airy_ai(Tensor x) -> Tensor + python_module: special + structured_delegate: special_airy_ai.out + variants: function + tags: pointwise + +- func: special_airy_ai.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, XPU: special_airy_ai_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_bessel_j0(Tensor self) -> Tensor + python_module: special + structured_delegate: special_bessel_j0.out + variants: function + tags: pointwise + +- func: special_bessel_j0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: special_bessel_j0_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_bessel_j1(Tensor self) -> Tensor + python_module: special + structured_delegate: special_bessel_j1.out + variants: function + tags: pointwise + +- func: special_bessel_j1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: special_bessel_j1_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_bessel_y0(Tensor self) -> Tensor + python_module: special + structured_delegate: special_bessel_y0.out + variants: function + tags: pointwise + +- func: special_bessel_y0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: special_bessel_y0_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_bessel_y1(Tensor self) -> Tensor + python_module: special + structured_delegate: special_bessel_y1.out + variants: function + tags: pointwise + +- func: special_bessel_y1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: special_bessel_y1_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_t(Tensor x, Tensor n) -> Tensor + device_check: NoCheck + python_module: special + structured_delegate: special_chebyshev_polynomial_t.out + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_t.x_scalar(Scalar x, Tensor n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_t + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_t.n_scalar(Tensor x, Scalar n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_t + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_t.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + dispatch: + CPU, CUDA, MPS, XPU: special_chebyshev_polynomial_t_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_t.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_t_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_t.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_t_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_u(Tensor x, Tensor n) -> Tensor + device_check: NoCheck + python_module: special + structured_delegate: special_chebyshev_polynomial_u.out + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_u.x_scalar(Scalar x, Tensor n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_u + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_u.n_scalar(Tensor x, Scalar n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_u + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_u.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + dispatch: + CPU, CUDA, MPS, XPU: special_chebyshev_polynomial_u_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_u.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_u_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_u.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_u_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_v(Tensor x, Tensor n) -> Tensor + device_check: NoCheck + python_module: special + structured_delegate: special_chebyshev_polynomial_v.out + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_v.x_scalar(Scalar x, Tensor n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_v + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_v.n_scalar(Tensor x, Scalar n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_v + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_v.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + dispatch: + CPU, CUDA, MPS, XPU: special_chebyshev_polynomial_v_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_v.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_v_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_v.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_v_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_w(Tensor x, Tensor n) -> Tensor + device_check: NoCheck + python_module: special + structured_delegate: special_chebyshev_polynomial_w.out + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_w.x_scalar(Scalar x, Tensor n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_w + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_w.n_scalar(Tensor x, Scalar n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_w + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_w.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + dispatch: + CPU, CUDA, MPS, XPU: special_chebyshev_polynomial_w_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_w.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_w_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_chebyshev_polynomial_w.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_chebyshev_polynomial_w_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_hermite_polynomial_h(Tensor x, Tensor n) -> Tensor + device_check: NoCheck + python_module: special + structured_delegate: special_hermite_polynomial_h.out + variants: function + tags: pointwise + +- func: special_hermite_polynomial_h.x_scalar(Scalar x, Tensor n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_hermite_polynomial_h + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_hermite_polynomial_h.n_scalar(Tensor x, Scalar n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_hermite_polynomial_h + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_hermite_polynomial_h.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + dispatch: + CPU, CUDA, MPS, XPU: special_hermite_polynomial_h_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_hermite_polynomial_h.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_hermite_polynomial_h_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_hermite_polynomial_h.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_hermite_polynomial_h_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_hermite_polynomial_he(Tensor x, Tensor n) -> Tensor + device_check: NoCheck + python_module: special + structured_delegate: special_hermite_polynomial_he.out + variants: function + tags: pointwise + +- func: special_hermite_polynomial_he.x_scalar(Scalar x, Tensor n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_hermite_polynomial_he + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_hermite_polynomial_he.n_scalar(Tensor x, Scalar n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_hermite_polynomial_he + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_hermite_polynomial_he.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + dispatch: + CPU, CUDA, MPS, XPU: special_hermite_polynomial_he_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_hermite_polynomial_he.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_hermite_polynomial_he_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_hermite_polynomial_he.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_hermite_polynomial_he_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_laguerre_polynomial_l(Tensor x, Tensor n) -> Tensor + device_check: NoCheck + python_module: special + structured_delegate: special_laguerre_polynomial_l.out + variants: function + tags: pointwise + +- func: special_laguerre_polynomial_l.x_scalar(Scalar x, Tensor n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_laguerre_polynomial_l + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_laguerre_polynomial_l.n_scalar(Tensor x, Scalar n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_laguerre_polynomial_l + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_laguerre_polynomial_l.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + dispatch: + CPU, CUDA, XPU: special_laguerre_polynomial_l_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_laguerre_polynomial_l.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_laguerre_polynomial_l_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_laguerre_polynomial_l.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_laguerre_polynomial_l_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_legendre_polynomial_p(Tensor x, Tensor n) -> Tensor + device_check: NoCheck + python_module: special + structured_delegate: special_legendre_polynomial_p.out + variants: function + tags: pointwise + +- func: special_legendre_polynomial_p.x_scalar(Scalar x, Tensor n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_legendre_polynomial_p + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_legendre_polynomial_p.n_scalar(Tensor x, Scalar n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_legendre_polynomial_p + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_legendre_polynomial_p.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + dispatch: + CPU, CUDA, XPU: special_legendre_polynomial_p_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_legendre_polynomial_p.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_legendre_polynomial_p_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_legendre_polynomial_p.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_legendre_polynomial_p_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_modified_bessel_i0(Tensor self) -> Tensor + python_module: special + structured_delegate: special_modified_bessel_i0.out + variants: function + tags: pointwise + +- func: special_modified_bessel_i0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: special_modified_bessel_i0_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_modified_bessel_i1(Tensor self) -> Tensor + python_module: special + structured_delegate: special_modified_bessel_i1.out + variants: function + tags: pointwise + +- func: special_modified_bessel_i1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: special_modified_bessel_i1_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_modified_bessel_k0(Tensor self) -> Tensor + python_module: special + structured_delegate: special_modified_bessel_k0.out + variants: function + tags: pointwise + +- func: special_modified_bessel_k0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: special_modified_bessel_k0_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_modified_bessel_k1(Tensor self) -> Tensor + python_module: special + structured_delegate: special_modified_bessel_k1.out + variants: function + tags: pointwise + +- func: special_modified_bessel_k1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: special_modified_bessel_k1_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_scaled_modified_bessel_k0(Tensor x) -> Tensor + python_module: special + structured_delegate: special_scaled_modified_bessel_k0.out + variants: function + tags: pointwise + +- func: special_scaled_modified_bessel_k0.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: special_scaled_modified_bessel_k0_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_scaled_modified_bessel_k1(Tensor x) -> Tensor + python_module: special + structured_delegate: special_scaled_modified_bessel_k1.out + variants: function + tags: pointwise + +- func: special_scaled_modified_bessel_k1.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: special_scaled_modified_bessel_k1_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_t(Tensor x, Tensor n) -> Tensor + device_check: NoCheck + python_module: special + structured_delegate: special_shifted_chebyshev_polynomial_t.out + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_t.x_scalar(Scalar x, Tensor n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_t + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_t.n_scalar(Tensor x, Scalar n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_t + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_t.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + dispatch: + CPU, CUDA, MPS, XPU: special_shifted_chebyshev_polynomial_t_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_t.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_t_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_t.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_t_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_u(Tensor x, Tensor n) -> Tensor + device_check: NoCheck + python_module: special + structured_delegate: special_shifted_chebyshev_polynomial_u.out + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_u.x_scalar(Scalar x, Tensor n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_u + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_u.n_scalar(Tensor x, Scalar n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_u + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_u.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + dispatch: + CPU, CUDA, MPS, XPU: special_shifted_chebyshev_polynomial_u_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_u.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_u_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_u.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_u_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_v(Tensor x, Tensor n) -> Tensor + device_check: NoCheck + python_module: special + structured_delegate: special_shifted_chebyshev_polynomial_v.out + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_v.x_scalar(Scalar x, Tensor n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_v + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_v.n_scalar(Tensor x, Scalar n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_v + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_v.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + dispatch: + CPU, CUDA, MPS, XPU: special_shifted_chebyshev_polynomial_v_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_v.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_v_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_v.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_v_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_w(Tensor x, Tensor n) -> Tensor + device_check: NoCheck + python_module: special + structured_delegate: special_shifted_chebyshev_polynomial_w.out + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_w.x_scalar(Scalar x, Tensor n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_w + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_w.n_scalar(Tensor x, Scalar n) -> Tensor + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_w + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_w.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + dispatch: + CPU, CUDA, MPS, XPU: special_shifted_chebyshev_polynomial_w_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_w.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_w_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_shifted_chebyshev_polynomial_w.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: special_shifted_chebyshev_polynomial_w_out + device_check: NoCheck + python_module: special + variants: function + tags: pointwise + +- func: special_spherical_bessel_j0(Tensor x) -> Tensor + python_module: special + structured_delegate: special_spherical_bessel_j0.out + variants: function + tags: pointwise + +- func: special_spherical_bessel_j0.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA, MPS, XPU: special_spherical_bessel_j0_out + python_module: special + structured_inherits: TensorIteratorBase + structured: True + variants: function + tags: pointwise + +# Aux function used in the test TestPythonDispatch.test_kwarg_only_and_positional_default +# within test/test_python_dispatch.py +- func: _foobar(Tensor self, bool arg1=True, bool arg2=True, *, bool arg3=True) -> Tensor + dispatch: + CPU: foobar + autogen: _foobar.out + +- func: _fused_adam_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, float lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> () + # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now). + variants: function + dispatch: + CPU: _fused_adam_kernel_cpu_ + CUDA: _fused_adam_kernel_cuda_ + MPS: _fused_adam_kernel_mps_ + XPU: _fused_adam_kernel_xpu_ + autogen: _fused_adam, _fused_adam.out + +- func: _fused_adam_.tensor_lr(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, Tensor lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> () + # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now), + # but still skip the device check as the Tensor LR can be on CPU + device_check: NoCheck + variants: function + dispatch: + CPU: _fused_adam_kernel_cpu_ + CUDA: _fused_adam_kernel_cuda_ + MPS: _fused_adam_kernel_mps_ + XPU: _fused_adam_kernel_xpu_ + autogen: _fused_adam.tensor_lr, _fused_adam.tensor_lr_out + +- func: _fused_adamw_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, float lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> () + # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now). + variants: function + dispatch: + CPU: _fused_adamw_kernel_cpu_ + CUDA: _fused_adamw_kernel_cuda_ + MPS: _fused_adamw_kernel_mps_ + XPU: _fused_adamw_kernel_xpu_ + autogen: _fused_adamw, _fused_adamw.out + +- func: _fused_adamw_.tensor_lr(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] exp_avgs, Tensor(d!)[] exp_avg_sqs, Tensor(e!)[] max_exp_avg_sqs, Tensor[] state_steps, *, Tensor lr, float beta1, float beta2, float weight_decay, float eps, bool amsgrad, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> () + # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now), + # but still skip the device check as the Tensor LR can be on CPU + device_check: NoCheck + variants: function + dispatch: + CPU: _fused_adamw_kernel_cpu_ + CUDA: _fused_adamw_kernel_cuda_ + MPS: _fused_adamw_kernel_mps_ + XPU: _fused_adamw_kernel_xpu_ + autogen: _fused_adamw.tensor_lr, _fused_adamw.tensor_lr_out + +- func: _fused_sgd_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] momentum_buffer_list, *, float weight_decay, float momentum, float lr, float dampening, bool nesterov, bool maximize, bool is_first_step, Tensor? grad_scale=None, Tensor? found_inf=None) -> () + # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now). + variants: function + dispatch: + CPU: _fused_sgd_kernel_cpu_ + CUDA: _fused_sgd_kernel_cuda_ + MPS: _fused_sgd_kernel_mps_ + XPU: _fused_sgd_kernel_xpu_ + autogen: _fused_sgd, _fused_sgd.out + +- func: _fused_sgd_.tensor_lr(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] momentum_buffer_list, *, float weight_decay, float momentum, Tensor lr, float dampening, bool nesterov, bool maximize, bool is_first_step, Tensor? grad_scale=None, Tensor? found_inf=None) -> () + # Unlike "foreach" functions, lists of tensors should be guaranteed to be on the same device (for now). + # but still skip the device check as the Tensor LR can be on CPU + device_check: NoCheck + variants: function + dispatch: + CPU: _fused_sgd_kernel_cpu_ + CUDA: _fused_sgd_kernel_cuda_ + MPS: _fused_sgd_kernel_mps_ + XPU: _fused_sgd_kernel_xpu_ + autogen: _fused_sgd.tensor_lr, _fused_sgd.tensor_lr_out + +- func: _fused_adagrad_(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] state_sums, Tensor(d!)[] state_steps, *, float lr, float lr_decay, float weight_decay, float eps, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> () + variants: function + dispatch: + CPU: _fused_adagrad_kernel_cpu_ + CUDA: _fused_adagrad_kernel_cuda_ + XPU: _fused_adagrad_kernel_xpu_ + autogen: _fused_adagrad, _fused_adagrad.out + +- func: _fused_adagrad_.tensor_lr(Tensor(a!)[] self, Tensor(b!)[] grads, Tensor(c!)[] state_sums, Tensor[] state_steps, *, Tensor lr, float lr_decay, float weight_decay, float eps, bool maximize, Tensor? grad_scale=None, Tensor? found_inf=None) -> () + device_check: NoCheck + variants: function + dispatch: + CPU: _fused_adagrad_kernel_cpu_ + CUDA: _fused_adagrad_kernel_cuda_ + XPU: _fused_adagrad_kernel_xpu_ + autogen: _fused_adagrad.tensor_lr, _fused_adagrad.tensor_lr_out + +# This op is ONLY used by pytorch/XLA in functionalization, and should never show up in vanilla eager mode or in any pytorch tracing contexts. +- func: _propagate_xla_data(Tensor input, Tensor output) -> () + variants: function diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/native/tags.yaml b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/native/tags.yaml new file mode 100644 index 0000000000000000000000000000000000000000..91f65970aa21358fc1995919b67c60c3c9ef32c7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/native/tags.yaml @@ -0,0 +1,114 @@ +# This yaml file contains all the possible tags that can be defined in `tags` in `native_functions.yaml` + +- tag: inplace_view + desc: | + This tag indicates if an operator *only* modifies the tensor metadata +- tag: pt2_compliant_tag + desc: | + This tag indicates if the operator is guaranteed to + work with the PT2 compilation APIs (torch.compile, + torch.export, etc). If you add this tag to an + operator, please use + `torch.testing._internal.optest.opcheck` to test that + the operator has been registered correctly and + works with torch.compile +- tag: view_copy + desc: | + This tag indicates operators that are *_copy* variants + of view/aliasing operators. If an operator has a view_copy tag, + then it should have the name {op}_copy, where {op} is a view operator. +- tag: dynamic_output_shape + desc: | + This tag indicates if an operator's output's shape depends on input Tensor + data. +- tag: data_dependent_output + desc: | + Operator has a non-Tensor output whose value is dependent on the data + of Tensor inputs. Among other things, this implies that this operator + cannot be run with meta tensor (since data is not available), nor + can it be symbolically traced. +- tag: generated + desc: | + This tag indicates that the operator doesn't have an explicit entry in + native_functions.yaml, and instead was generated automatically by the codegen. +- tag: nondeterministic_seeded + desc: | + This tag indicates if an operator is nondeterministically seeded + (i.e., is random) such that the operator intentionally produces + different results when run twice on the same inputs, but this randomness + is controlled by a Generator which, if reseeded would give you the + same result. +- tag: nondeterministic_bitwise + desc: | + This tag indicates if an operator doesn't guarantee bitwise equivalence + across different runs of an operator with identical inputs. +- tag: needs_exact_strides + desc: | + This tag indicates that the operator should be passed Tensors following + the same strides as observed in eager when compiled in inductor. + Only one of {needs_exact_strides, needs_contiguous_strides, needs_fixed_stride_order, flexible_layout} + can apply; if multiple are assigned then we assume the most restrictive one. +- tag: needs_contiguous_strides + desc: | + This tag indicates that the operator should be passed contiguous Tensors. + Failure to do so will result in undefined behavior. +- tag: needs_fixed_stride_order + desc: | + This tag indicates that the operator should be passed Tensors following + the same stride permutation as observed in eager when compiled in inductor. + Only one of {needs_exact_strides, needs_contiguous_strides, needs_fixed_stride_order, flexible_layout} + can apply; if multiple are assigned then we assume the most restrictive one. +- tag: flexible_layout + desc: | + This tag indicates that the custom operator can accept inputs with varying + strides/storage_offset and that when compiled, Inductor is allowed to change + the strides/storage_offset of inputs to the custom operator. + Only one of {needs_exact_strides, needs_contiguous_strides, needs_fixed_stride_order, flexible_layout} + can apply; if multiple are assigned then we assume the most restrictive one. + +# NOTE [Core ATen Ops] +- tag: core + desc: | + Core aten ops is a subset of aten ops that remains after aten-to-aten decomposition and + functionalization pass. Core aten ops are fully functional and adhere to single static + assignment (SSA): this implies there will be no `inplace` or `_out` variants in this opset. + This opset is designed to serve as the functional IR to interface with compiler backends. + In contrast to primTorch, core aten opset doesn't decompose ops into explicit + type promotion and broadcasting ops. + Core aten ops is also effectively the opset produced by torchdynamo.export(aten_graph=True), + and thus can be used as an opset for export purpose. +- tag: pointwise + desc: | + Pointwise operators are operators where each element of the output is computed only by accessing + the corresponding element of all the broadcasted inputs. The output shape will be the broadcasted + shape of the inputs. +- tag: maybe_aliasing_or_mutating + desc: | + For some ops, we can't statically determine whether the op is functional or not. Note that this is only + relevant to CIA ops that decompose before functionalization/autograd. It is useful to + know this information for export as we would want to decompose these ops as they are unsafe to be + preserved. +- tag: cudagraph_unsafe + desc: | + This operator does not support cudagraphs. The presence of this tag on an operator will cause + Inductor to split the graph around this operator. Note that operators without this tag may still + not support CUDAGraphs. Inductor may have other hardcoded lists around that. +- tag: reduction + desc: | + This tag indicates that an operator performs a reduction operation, computing aggregate values + (sum, mean, max, min, etc.) across one or more dimensions of the input tensor(s). +- tag: inplace + desc: | + This tag indicates that an operator has inplace semantics: it mutates + its first positional argument (self) and returns it. For custom + operators, self must be a plain Tensor. Some native operators have + Tensor[] self with no return, but this is subject to change. +- tag: out + desc: | + This tag indicates that an operator has "out" semantics: its mutable + arguments are write-only output buffers that are not read from. + The operator must return exactly the mutable arguments in the order + they are declared, and nothing else. +- tag: out_variant + desc: | + Deprecated, does nothing. Use "out" instead. diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/ATenOpList.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/ATenOpList.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5de3424857e236917eb68940e7904446de59f586 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/ATenOpList.cpp @@ -0,0 +1,36 @@ +#include + +#include +#include +#include +#include +#include + +// ${generated_comment} + +namespace at { + +namespace { +struct OpNameEquals final { + bool operator()(const std::pair& lhs, const std::pair& rhs) const { + return 0 == strcmp(lhs.first, rhs.first) && 0 == strcmp(lhs.second, rhs.second); + } +}; + +struct OpNameHash final { + size_t operator()(const std::pair& p) const { + // use std::hash because std::hash would hash pointers and not pointed-to strings + return std::hash()(p.first) ^ (~ std::hash()(p.second)); + } +}; +} + +bool is_custom_op(const c10::OperatorName& opName) { + static std::unordered_set, OpNameHash, OpNameEquals> ops { + ${aten_ops} + {"", ""} + }; + return ops.count(std::make_pair( + opName.name.c_str(), opName.overload_name.c_str())) == 0; +} +} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/CompositeViewCopyKernels.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/CompositeViewCopyKernels.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47097d7aa4320674bec4bddbb5ac861309334f0c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/CompositeViewCopyKernels.cpp @@ -0,0 +1,73 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// ${generated_comment} + +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +$ops_headers +#endif + +namespace at { +namespace native { + +// This file contains a number of kernels for aten functions that are fully code-generated. +// TODO: rename this file to something more generic. + +namespace { +at::Tensor clone_arg(const at::Tensor& t) { + return t.clone(); +} + +std::vector clone_arg(const at::TensorList& t_list) { + std::vector out(t_list.size()); + for (const auto& i : c10::irange(t_list.size())) { + out[i] = t_list[i].clone(); + } + return out; +} + +// duped with gen_resize_out_helper from structured kernels +void copy_arg(const at::Tensor& dst, const at::Tensor& src) { + TORCH_CHECK(src.dtype() == dst.dtype(), + "Expected out tensor to have dtype ", src.dtype(), ", but got ", dst.dtype(), " instead"); + TORCH_CHECK(src.device() == dst.device(), + "Expected out tensor to have device ", src.device(), ", but got ", dst.device(), " instead"); + dst.copy_(src); +} + +void copy_arg(const at::TensorList& dst, const at::TensorList& src) { + TORCH_INTERNAL_ASSERT(dst.size() == src.size()); + for (const auto& i : c10::irange(dst.size())) { + copy_arg(dst[i], src[i]); + } +} + +// TODO: this doesn't handle restriding empty tensors correctly; see +// gen_resize_out_helper for the correct algorithm + +void resize_out_helper(const at::Tensor& dst, const at::Tensor& src) { + at::native::resize_output(dst, src.sizes()); +} + +void resize_out_helper(const at::TensorList& dst, const at::TensorList& src) { + TORCH_INTERNAL_ASSERT(dst.size() == src.size()); + for (const auto& i : c10::irange(dst.size())) { + at::native::resize_output(dst[i], src[i].sizes()); + } +} +} + + +${CompositeViewCopyKernel_Definitions} + +${GeneratedCompositeFunctional_Definitions} + +${GeneratedCompositeOut_Definitions} + +} // namespace native +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunction.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunction.h new file mode 100644 index 0000000000000000000000000000000000000000..c92d5eb3898ecea0fb9e1f79c2725d1bc6dfa7fb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunction.h @@ -0,0 +1,23 @@ +#pragma once +// ${generated_comment} + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace ${dispatch_namespace} { + +${dispatch_namespaced_declarations} + +} // namespace ${dispatch_namespace} +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..35f43297fdd9ca9f932c8c53b5b773f1b9b8a427 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions.h @@ -0,0 +1,29 @@ +#include + +// TODO Undo all logic introduced for Note [Avoiding Include Cycles In Static Dispatch] +// Code introduced to avoid cyclic dependency in static dispatch is no longer +// needed as static dispatch logic is moved from TensorBody.h, which caused cycles in the first place, +// to Operators.cpp for supporting multiple backends with multiple kernels. +// +// Note [Avoiding Include Cycles In Static Dispatch] +// In order to avoid #include cycles in the static dispatch build, we've carefully split out +// the static function definition files into {DispatchKey}Functions.h and {DispatchKey}Functions_inl.h. +// +// Without this split, the include cycle looks like TensorBody.h -> CPUFunctions.h -> TensorBody.h. +// - TensorBody.h #includes CPUFunctions.h in the static dispatch build, because the tensor methods +// all need to call into the fastpath C++ API defined in CPUFunctions.h. The methods are also all +// directly inlined into TensorBody.h. +// - CPUFunctions.h #includes TensorBody.h because it contains function declarations for the entire C++ API, +// which include functions that have defaultable std::optional arguments. +// That requires knowing the full Tensor class definition. +// +// We break the cycle by doing the following: +// - Split out CPUFunction.h into two files: CPUFunctions.h and CPUFunctions_inl.h +// - CPUFunction.h is a dummy file that just includes the Tensor class and includes CPUFunctions_inl., +// - CPUFunctions_inl.h includes everything else +// - (only in the static dispatch build) TensorBody.h makes sure to finish defining the Tensor class, +// and then it includes CPUFunctions_inl.h. +// - All other files that want the cpu fastpath functions can include CPUFunctions.h directly. +// - This also means that static dispatch build, CPUFunctions.h only needs to +// #include TensorBody.h, and it will automatically bring in CPUFunctions_inl.h. +${inline_headers} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions_inl.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..fbb71c2cb123cb21fb57ec32341d86bff06f6a17 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions_inl.h @@ -0,0 +1,22 @@ +#pragma once +// ${generated_comment} + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +#if defined(AT_PER_OPERATOR_HEADERS) && defined(TORCH_ASSERT_ONLY_METHOD_OPERATORS) +#error This change adds a dependency on all pytorch operators, meaning the \ + file will need to be re-compiled every time an operator is changed or added. \ + Consider including a specific operator from \ + . \ + See NOTE [TORCH_ASSERT_ONLY_METHOD_OPERATORS]. +#endif + +${DispatchKeyFunctions_inl_includes} + + +${dispatch_namespaced_declarations} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7647f459a744b2eacfac6aaea4f49b86babbb234 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.cpp @@ -0,0 +1,13 @@ +// ${generated_comment} +${includes} +${native_functions_include} + +namespace { +${helper_fns} +} // namespace + +${namespace_prologue} + +${native_function_definitions} + +${namespace_epilogue} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..b45a17b5922f8a0b76e0237616914ce9969efca5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.h @@ -0,0 +1,19 @@ +#pragma once + +// an external backend might generate file within its code tree +// and check all the source files within the tree with clang-format. +// so, disable it since the backend might have a different config. +// clang-format off + +// ${generated_comment} + +#include + +${namespace_prologue} + +struct ${class_name} { + +${dispatch_declarations} + +}; +${namespace_epilogue} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Function.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Function.h new file mode 100644 index 0000000000000000000000000000000000000000..73096afbf11571cbe4147bb63f035a054ca842db --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Function.h @@ -0,0 +1,27 @@ +#pragma once + +// ${generated_comment} + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +${static_dispatch_ops_headers} + +${operator_includes} + +namespace at { + +${function_definitions} + +} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/FunctionalInverses.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/FunctionalInverses.h new file mode 100644 index 0000000000000000000000000000000000000000..b15cd09a6c65da3127be8245b87bff2f8c795a3d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/FunctionalInverses.h @@ -0,0 +1,23 @@ +#pragma once + +// ${generated_comment} + +#include +#include + +namespace at { +namespace functionalization { + +struct FunctionalInverses { + +${view_inverse_declarations} + +// NB: These are not generated! They're manually implemented in the template. +// TODO: Change codegen to generate these. See the following link: +// https://github.com/pytorch/pytorch/blob/main/torchgen/model.py#L2583-L2585 +static at::Tensor chunk_inverse(const at::Tensor & base, const at::Tensor & mutated_view, InverseReturnMode inverse_return_mode, int64_t mutated_view_idx, int chunks, int dim); +static at::Tensor narrow_inverse(const at::Tensor & base, const at::Tensor & mutated_view, InverseReturnMode inverse_return_mode, int dim, c10::SymInt start, c10::SymInt length); + +}; +} +} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Functions.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Functions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5f97714dc9f33f4d585af5dfa43157792c7df5ca --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Functions.cpp @@ -0,0 +1,105 @@ +#include + +#include +#include +#include + +namespace at { + +Tensor TensorMaker::make_tensor() { + AutoDispatchBelowADInplaceOrView guard{}; // TODO: Remove. + tracer::impl::NoTracerDispatchMode tracer_guard{}; + + check_size_nonnegative(sizes_); + + TORCH_CHECK_VALUE( + !deleter_ || !ctx_, + "The deleter and context arguments are mutually exclusive."); + + if (device_ == std::nullopt) { + device_ = globalContext().getDeviceFromPtr(data_, opts_.device().type()); + } + + if (opts_.device().has_index()) { + // clang-format off + TORCH_CHECK_VALUE( + opts_.device() == *device_, + "Specified device ", opts_.device(), " does not match device of data ", *device_); + // clang-format on + } + + std::size_t size_bytes = computeStorageSize(); + + DataPtr data_ptr{}; + if (deleter_) { + data_ptr = makeDataPtrFromDeleter(); + } else { + data_ptr = makeDataPtrFromContext(); + } + + TORCH_CHECK(!resizeable_ || allocator_ != nullptr, "Must specify an allocator with allocator() if you want to use resizeable_storage()"); + Storage storage{Storage::use_byte_size_t{}, size_bytes, std::move(data_ptr), /*allocator=*/allocator_, /*resizable=*/resizeable_}; + + Tensor tensor = detail::make_tensor( + std::move(storage), opts_.computeDispatchKey(), opts_.dtype()); + + TensorImpl* tensor_impl = tensor.unsafeGetTensorImpl(); + if (strides_) { + tensor_impl->set_sizes_and_strides(sizes_, *strides_); + } else { + tensor_impl->set_sizes_contiguous(sizes_); + } + if (storage_offset_) { + tensor_impl->set_storage_offset(*storage_offset_); + } + + tensor_impl->set_requires_grad(opts_.requires_grad()); + + return tensor; + } + + std::size_t TensorMaker::computeStorageSize() const { + std::size_t itemsize = opts_.dtype().itemsize(); + + if (strides_) { + auto storage_size = detail::computeStorageNbytes(sizes_, *strides_, itemsize); + if (storage_offset_) { + storage_size += storage_offset_.value() * itemsize; + } + return storage_size; + } + + std::size_t size = 1; + for (std::int64_t s : sizes_) { + size *= static_cast(s); + } + auto storage_size = size * itemsize; + if (storage_offset_) { + storage_size += storage_offset_.value() * itemsize; + } + return storage_size; + } + + inline DataPtr TensorMaker::makeDataPtrFromDeleter() noexcept { + return InefficientStdFunctionContext::makeDataPtr(data_, std::move(deleter_), *device_); + } + + inline DataPtr TensorMaker::makeDataPtrFromContext() noexcept { + return DataPtr{data_, ctx_.release(), ctx_.get_deleter(), *device_}; + } + + IntArrayRef TensorMaker::makeTempSizes() const noexcept { + static std::int64_t zeros[5] = {0, 0, 0, 0, 0}; + if (opts_.has_memory_format()) { + MemoryFormat format = *opts_.memory_format_opt(); + if (format == MemoryFormat::ChannelsLast) { + return IntArrayRef(zeros, 4); + } + if (format == MemoryFormat::ChannelsLast3d) { + return IntArrayRef(zeros, 5); + } + } + return IntArrayRef(zeros, 1); + } + +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Functions.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Functions.h new file mode 100644 index 0000000000000000000000000000000000000000..b1feaf9d4daa9786359c97434e4c59d3c75778c7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Functions.h @@ -0,0 +1,143 @@ +#pragma once + +// ${generated_comment} + +#ifdef TORCH_ASSERT_NO_OPERATORS +#error This change adds a dependency on native_functions.yaml, \ + meaning the file will need to be re-compiled every time an operator \ + is changed or added. Consider if your change would be better placed in \ + another file, or if a more specific header might achieve the same goal. \ + See NOTE: [Tensor vs. TensorBase] +#endif + +#if defined(AT_PER_OPERATOR_HEADERS) && defined(TORCH_ASSERT_ONLY_METHOD_OPERATORS) +#error This change adds a dependency on all pytorch operators, meaning the \ + file will need to be re-compiled every time an operator is changed or added. \ + Consider including a specific operator from and \ + see NOTE [TORCH_ASSERT_ONLY_METHOD_OPERATORS]. +#endif + +// NOTE: [TORCH_ASSERT_ONLY_METHOD_OPERATORS] +// +// In ATen, certain generated headers files include the definitions of +// every single operator in PyTorch. Unfortunately this means every +// time an operator signature is updated or changed in +// native_functions.yaml, you (and every other PyTorch developer) need +// to recompile every source file that includes any of these headers. +// +// To break up these header dependencies, and improve incremental +// build times for all PyTorch developers. These headers are split +// into per-operator headers in the `ATen/ops` folder. This limits +// incremental builds to only changes to methods of `Tensor`, or files +// that use the specific operator being changed. With `at::sum` as an +// example, you should include +// +// // instead of ATen/Functions.h +// // instead of ATen/NativeFunctions.h +// // instead of ATen/Operators.h +// // instead of ATen/CPUFunctions.h +// +// However, even if you're careful to use this in your own code. +// `Functions.h` might be included indirectly through another header +// without you realising. To avoid this, you can add +// +// #define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// +// to the top of your source file. This way any time the non-specific +// headers are included, the compiler will error out. +// +// Also, be aware that `ops` are not available in all build +// configurations (namely fb-internal) so you must guard these +// includes with `#ifdef AT_PER_OPERATOR_HEADERS`. e.g. +// +// #ifndef AT_PER_OPERATOR_HEADERS +// #include +// #else +// #include +// #endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +${Functions_includes} + +namespace at { + +${Functions_declarations} + +// Special C++ only overloads for std()-like functions (See gh-40287) +// These are needed because int -> bool conversion takes precedence over int -> IntArrayRef +// So, for example std(0) would select the std(unbiased=False) overload +inline Tensor var(const Tensor& self, int dim) { + return at::var(self, IntArrayRef{dim}); +} +inline std::tuple var_mean(const Tensor& self, int dim) { + return at::var_mean(self, IntArrayRef{dim}); +} +inline Tensor std(const Tensor& self, int dim) { + return at::std(self, IntArrayRef{dim}); +} +inline std::tuple std_mean(const Tensor& self, int dim) { + return at::std_mean(self, IntArrayRef{dim}); +} + +inline int64_t numel(const Tensor& tensor) { + return tensor.numel(); +} + +inline int64_t size(const Tensor& tensor, int64_t dim) { + return tensor.size(dim); +} + +inline int64_t stride(const Tensor& tensor, int64_t dim) { + return tensor.stride(dim); +} + +inline bool is_complex(const Tensor& tensor) { + return tensor.is_complex(); +} + +inline bool is_floating_point(const Tensor& tensor) { + return tensor.is_floating_point(); +} + +inline bool is_signed(const Tensor& tensor) { + return tensor.is_signed(); +} + +inline bool is_inference(const Tensor& tensor) { + return tensor.is_inference(); +} + +inline bool _is_zerotensor(const Tensor& tensor) { + return tensor._is_zerotensor(); +} + +inline bool is_conj(const Tensor& tensor) { + return tensor.is_conj(); +} + +inline Tensor conj(const Tensor& tensor) { + return tensor.conj(); +} + +inline bool is_neg(const Tensor& tensor) { + return tensor.is_neg(); +} + +} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/LazyIr.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/LazyIr.h new file mode 100644 index 0000000000000000000000000000000000000000..9190ff8243d316fd2bd472bb3f0603701761bdb7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/LazyIr.h @@ -0,0 +1,19 @@ +#pragma once + +// This file contains autogenerated LazyTensor IR nodes +${lazy_ir_sysinc} +${lazy_ir_inc} + +${namespace_prologue} +using at::operator<<; + +// kNullValue is used to contribute a static hash value any time +// a node has an Optional input that is nullopt. It is important +// to differentiate between HASH(std::nullopt, something) and HASH(something, std::nullopt), +// and using kNullValue in the hash function in the order of arguments +// serves this purpose. +static const torch::lazy::Value kNullValue = torch::lazy::Value(); + +${ir_declarations} + +${namespace_epilogue} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/LazyNonNativeIr.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/LazyNonNativeIr.h new file mode 100644 index 0000000000000000000000000000000000000000..18eaf6da52e4b3654becac6cc89849bc0806ae09 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/LazyNonNativeIr.h @@ -0,0 +1,11 @@ +#pragma once + +${lazy_non_native_ir_inc} + +// This file contains autogenerated LazyTensor Non Native IR nodes + +${namespace_prologue} + +${non_native_ir_nodes} + +${namespace_epilogue} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/MethodOperators.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/MethodOperators.h new file mode 100644 index 0000000000000000000000000000000000000000..0e192cd05ef3c78fa74848c93de32150c1e3fd8b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/MethodOperators.h @@ -0,0 +1,24 @@ +#pragma once + +// ${generated_comment} + +#ifdef TORCH_ASSERT_NO_OPERATORS +#error This change adds a dependency on native_functions.yaml, \ + meaning the file will need to be re-compiled every time an operator \ + is changed or added. Consider if your change would be better placed in \ + another file, or if a more specific header might achieve the same goal. \ + See NOTE: [Tensor vs. TensorBase] +#endif + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +${MethodOperators_includes} + +namespace at { +namespace _ops { +${MethodOperators_declarations} +} // namespace _ops +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/NativeFunction.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/NativeFunction.h new file mode 100644 index 0000000000000000000000000000000000000000..a5441ad85d1d5e28c4e31dd3f0dc7f66dfbff9e7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/NativeFunction.h @@ -0,0 +1,17 @@ +#pragma once + +// ${generated_comment} + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +${extra_includes} + +${native_function_declarations} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/NativeFunctions.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/NativeFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..9dc972495ca038bddb7b887c39c2e0507e487213 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/NativeFunctions.h @@ -0,0 +1,33 @@ +#pragma once + +// ${generated_comment} + +#ifdef TORCH_ASSERT_NO_OPERATORS +#error This change adds a dependency on native_functions.yaml, \ + meaning the file will need to be re-compiled every time an operator \ + is changed or added. Consider if your change would be better placed in \ + another file, or if a more specific header might achieve the same goal. \ + See NOTE: [Tensor vs. TensorBase] +#endif + +#if defined(AT_PER_OPERATOR_HEADERS) && defined(TORCH_ASSERT_ONLY_METHOD_OPERATORS) +#error This change adds a dependency on all pytorch operators, meaning the \ + file will need to be re-compiled every time an operator is changed or added. \ + Consider including a specific operator from \ + and see NOTE [TORCH_ASSERT_ONLY_METHOD_OPERATORS]. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +${NativeFunctions_includes} + +${NativeFunctions_declarations} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/NativeMetaFunction.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/NativeMetaFunction.h new file mode 100644 index 0000000000000000000000000000000000000000..6522c97546d0498e4b3825fb4eafefbb34c71911 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/NativeMetaFunction.h @@ -0,0 +1,23 @@ +#pragma once + +// ${generated_comment} + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +${meta_function_declarations} + +} // namespace native +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/NativeMetaFunctions.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/NativeMetaFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..89989e2121c9aa34a4583205c3541a04edd36700 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/NativeMetaFunctions.h @@ -0,0 +1,19 @@ +#pragma once + +// ${generated_comment} + +#include +#include +#include +#include + +${NativeMetaFunctions_includes} + +namespace at { + +namespace meta { + +${NativeMetaFunctions_declarations} + +} // namespace meta +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Operator.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Operator.h new file mode 100644 index 0000000000000000000000000000000000000000..ed220f917290c2062481eb53dca232b47d180e2d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Operator.h @@ -0,0 +1,19 @@ +#pragma once + +// ${generated_comment} + +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + +${declarations} + +}} // namespace at::_ops diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Operators.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Operators.cpp new file mode 100644 index 0000000000000000000000000000000000000000..082bb67c3e2043f2c36b29345f57048ec2e9eea7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Operators.cpp @@ -0,0 +1,19 @@ +#include +#include + +// ${generated_comment} +// NOTE See [Sharded File] comment in VariableType + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +${operator_headers} +#endif + +${static_dispatch_extra_headers} + +namespace at { namespace _ops { + +${definitions} + +}} // namespace at::_ops diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Operators.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Operators.h new file mode 100644 index 0000000000000000000000000000000000000000..e74b96ef3d5c6b6d50fe63eac4dca51f0655daa5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/Operators.h @@ -0,0 +1,74 @@ +#pragma once + +// ${generated_comment} + +#ifdef TORCH_ASSERT_NO_OPERATORS +#error This change adds a dependency on native_functions.yaml, \ + meaning the file will need to be re-compiled every time an operator \ + is changed or added. Consider if your change would be better placed in \ + another file, or if a more specific header might achieve the same goal. \ + See NOTE: [Tensor vs. TensorBase] +#endif + +#if defined(AT_PER_OPERATOR_HEADERS) && defined(TORCH_ASSERT_ONLY_METHOD_OPERATORS) +#error This change adds a dependency on all pytorch operators, meaning the \ + file will need to be re-compiled every time an operator is changed or added. \ + Consider including a specific operator from \ + and see NOTE [TORCH_ASSERT_ONLY_METHOD_OPERATORS]. +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +${Operators_includes} + +// Extension writers: do you write wrapper functions? Are you frustrated with +// resolving overloads of operators? Are you frustrated with dealing with +// pointer-to-methods and resolving overloads of pointer-to-methods?? Look no +// further, this is the utility for you. +// +// Given an operator schema: aten::op.overload(... +// +// Use ATEN_FN2(op, overload) to get a *function* version of the operator +// that is guaranteed to not be overloaded. This means that you can safely +// decltype(&ATEN_FN2(op, overload)) it. NB: the 2 means this macro takes 2 args. +// +// Given an operator schema without an overload name: aten::op(... +// +// Use ATEN_FN(op) to get an unambiguous *function* version of the operator. +// +// There is some interesting behavior for out= operations. +// ATEN_FN2(sin, out) gives a function that is *faithful* to the schema; +// that is, the order of arguments is exactly what it looks like in the schema. + +#define ATEN_FN2(op_name, overload) at::_ops::op_name##_##overload::call +#define ATEN_FN(op_name) at::_ops::op_name::call + +// Separately, ATEN_OP(op) and ATEN_OP2(op, overload) define a class containing compile-time +// metadata about a given aten operator. +// Notable data on the class includes: +// - ATEN_OP2(add, Tensor)::name // returns the string name: "add" +// - ATEN_OP2(add, Tensor)::overload_name // returns the string overload name: "Tensor" +// - ATEN_OP2(add, Tensor)::schema // returns the C++ schema type: at::Tensor (const at::Tensor &, const at::Tensor &, const at::Scalar &) +// - ATEN_OP2(add, Tensor)::schema_str // returns the string jit type: "add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor" + +#define ATEN_OP2(op_name, overload) at::_ops::op_name##_##overload +#define ATEN_OP(op_name) at::_ops::op_name + +// WARNING: Please do not call any of the ops in the _ops namespace directly. +// Use the ATEN_FN macros. We do not guarantee stability of the naming +// scheme for the functions in at::_ops + +// See Note [The ATen Operators API] for details of the at::_ops namespace + +namespace at { +namespace _ops { +${Operators_declarations} +} // namespace _ops +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RedispatchFunctions.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RedispatchFunctions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..58102bd97fca4eaef477818b0b0a92b7995e38b1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RedispatchFunctions.cpp @@ -0,0 +1,15 @@ +// ${generated_comment} + +#include +#include + +#include +#include + +namespace at { + +namespace redispatch { + ${function_redispatch_definitions} +} // namespace redispatch + +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RedispatchFunctions.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RedispatchFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..2422cdd409cfdd59c2a05df27d28bb25ee610463 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RedispatchFunctions.h @@ -0,0 +1,32 @@ +#pragma once + +// ${generated_comment} + +#ifdef TORCH_ASSERT_ONLY_METHOD_OPERATORS +#error This change adds a dependency on all pytorch operators, meaning the \ + file will need to be re-compiled every time an operator is changed or added. \ + Consider using the at::_ops::{name}::redispatch() interface by including \ + the specific operator from +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { + +namespace redispatch { + ${function_redispatch_definitions} +} // namespace redispatch + +} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterBackendSelect.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterBackendSelect.cpp new file mode 100644 index 0000000000000000000000000000000000000000..018cf358f11237d5bdc9bca01aa8d09d1462f574 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterBackendSelect.cpp @@ -0,0 +1,29 @@ +// We register ops with a higher priority dispatch key (BackendSelect) than the usual backend-specific keys (e.g. CPU) +// which makes calls to the factory functions dispatch to here. +// We then 'manually' compute a lower-priority to re-dispatch to (e.g. CPU) to get to the eventually correct backend. +// ${generated_comment} + +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else + +${ops_headers} +#endif + +namespace at { + +namespace { + +${backend_select_method_definitions} + +TORCH_LIBRARY_IMPL(aten, BackendSelect, m) { + ${backend_select_function_registrations}; +} + +} // namespace +} // at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterCodegenUnboxedKernels.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterCodegenUnboxedKernels.cpp new file mode 100644 index 0000000000000000000000000000000000000000..279f987c66a26c2eb5d11c664c85b3604b67684b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterCodegenUnboxedKernels.cpp @@ -0,0 +1,41 @@ +#include +#include +#include + +#include + +// ${generated_comment} + +// NOTE [Sharded File]: This file is generated in a sharded fashion to speed up +// incremental rebuilds. See the comment at the top of +// templates/VariableType.cpp for an analogous, in-depth discussion. +// +// Generated by tools/jit/gen_unboxing.py. This file registers all ATen ops into JIT op registry instead of c10 +// dispatcher. JIT op registry only takes boxed kernels, so we are calling unboxing functions in UnboxingFunctions.h +// to cast arguments into C++ types (instead of IValue) and delegate to unboxed kernels. + +namespace torch { namespace jit { + +using autograd::Variable; +using autograd::variable_list; +using at::Scalar; +using at::ScalarType; +using at::Tensor; +using at::TensorOptions; +using at::DeviceGuard; + +using ::c10::fmap; +using ::c10::filter; + +namespace { + +RegisterOperators reg({ + + // Generated operators + ${unboxed_ops} +}); + +} // anon namespace + + +}} // namespace torch::jit diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterDispatchDefinitions.ini b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterDispatchDefinitions.ini new file mode 100644 index 0000000000000000000000000000000000000000..97c921de18f62832d1ca09c245f2466541fe908d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterDispatchDefinitions.ini @@ -0,0 +1,22 @@ +${ns_prologue} + +// NB: TORCH_LIBRARY_IMPL must be in an anonymous namespace to avoid +// ambiguity with conflicting identifiers that may have been defined in +// at namespace already. +namespace { + +${dispatch_anonymous_definitions} + +${static_init_dispatch_registrations} + +} // anonymous namespace + +${deferred_dispatch_registrations} + +namespace ${dispatch_namespace} { + +${dispatch_namespaced_definitions} + +} // namespace ${dispatch_namespace} + +${ns_epilogue} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterDispatchKey.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterDispatchKey.cpp new file mode 100644 index 0000000000000000000000000000000000000000..107fe587c7aa7f5c74cee25b7959b30d86b41989 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterDispatchKey.cpp @@ -0,0 +1,50 @@ +// an external backend might generate file within its code tree +// and check all the source files within the tree with clang-format. +// so, disable it since the backend might have a different config. +// clang-format off + +// NOTE: This condition is true for all PyTorch internal libraries, it +// just excludes external projects such as torch_xla which +// reuse some of the PyTorch codegen machinery. +#if defined(CAFFE2_BUILD_MAIN_LIB) || \ + defined(TORCH_CUDA_BUILD_MAIN_LIB) || \ + defined(TORCH_XPU_BUILD_MAIN_LIB) +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#endif + +// ${generated_comment} + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +$extra_cuda_headers +$external_backend_headers +$dispatch_headers +$ops_headers + +namespace at { +namespace { +$dispatch_helpers +} // namespace +} // namespace at + +// See template file RegisterDispatchDefinitions.ini +$dispatch_definitions diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterFunctionalization.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterFunctionalization.cpp new file mode 100644 index 0000000000000000000000000000000000000000..408aff0cdab40461a7ba731bab216a7b7435331e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterFunctionalization.cpp @@ -0,0 +1,116 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// ${generated_comment} + +#include +#include +#include +#include +#include +#include + +#include +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +// needed for the meta tensor calls to get stride info in functionalization +#include +// needed for special handling of copy_(). +// See Note [functionalizating copy_() and not preserving strides] +#include +#include + +$ops_headers +#endif + +namespace at { +namespace functionalization { + +// This keyset is used by functionalization when it calls into meta kernels +// to accurately propagate stride metadata. +// Exclude any modes: the purpose of calling into meta kernels is only as an implementation +// detail to perform shape inference, and we don't want any modal keys to run. +// Specifically, we want to prevent functionalization and Python modes from running. +constexpr auto exclude_keys_for_meta_dispatch = + c10::functorch_transforms_ks | + c10::DispatchKeySet({ + c10::DispatchKey::FuncTorchDynamicLayerBackMode, + c10::DispatchKey::FuncTorchDynamicLayerFrontMode, + c10::DispatchKey::Python, + c10::DispatchKey::PreDispatch, + + }); + +// Helper around at::has_internal_overlap. +// The ATen util is used in hot-path eager mode: it's always fast, +// but might return TOO_HARD sometimes. +// During functionalization, we're ok taking a bit longer +// to detect memory overlap. +inline bool has_internal_overlap_helper(const at::Tensor t) { + auto has_overlap = at::has_internal_overlap(t); + if (has_overlap == at::MemOverlap::Yes) return true; + if (has_overlap == at::MemOverlap::No) return false; + return false; +} + + +inline Tensor to_meta(const Tensor& t) { + if (!t.defined()) return t; + return at::native::empty_strided_meta_symint(t.sym_sizes(), t.sym_strides(), +/*dtype=*/t.scalar_type(), /*layout=*/t.layout(), +/*device=*/c10::Device(kMeta), /*pin_memory=*/std::nullopt); +} + +inline std::optional to_meta(const std::optional& t) { + if (t.has_value()) { + return to_meta(*t); + } + return std::nullopt; +} + +inline std::vector to_meta(at::ITensorListRef t_list) { + std::vector outputs; + outputs.reserve(t_list.size()); + for (const auto& tensor : t_list) { + outputs.push_back(to_meta(tensor)); + } + return outputs; +} + +inline c10::List to_meta(const c10::List& t_list) { + c10::List outputs; + outputs.reserve(t_list.size()); + for (const auto i : c10::irange(t_list.size())) { + outputs.push_back(to_meta(t_list[i])); + } + return outputs; +} + +inline c10::List<::std::optional> to_meta(const c10::List<::std::optional>& t_list) { + c10::List<::std::optional> outputs; + outputs.reserve(t_list.size()); + for (const auto i : c10::irange(t_list.size())) { + outputs.push_back(to_meta(t_list[i])); + } + return outputs; +} + +static bool disable_meta_reference() { + static auto env = c10::utils::get_env("TORCH_DISABLE_FUNCTIONALIZATION_META_REFERENCE"); + return env == "1"; +} + + +${func_definitions} + +} // namespace functionalization + +namespace { + +TORCH_LIBRARY_IMPL(aten, Functionalize, m) { + ${func_registrations}; +} + +} // namespace + +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterSchema.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterSchema.cpp new file mode 100644 index 0000000000000000000000000000000000000000..029796d3e575b2bde85cfd44af9e6fcbb56466cd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegisterSchema.cpp @@ -0,0 +1,13 @@ +// ${generated_comment} +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +namespace at { +TORCH_LIBRARY(aten, m) { + ${aten_schema_registrations}; + // Distributed Ops + // Implementations located in torch/csrc/jit/runtime/register_distributed_ops.cpp + m.def("get_gradients(int context_id) -> Dict(Tensor, Tensor)"); +} +${schema_registrations} +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegistrationDeclarations.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegistrationDeclarations.h new file mode 100644 index 0000000000000000000000000000000000000000..5a0f0d0c7b44dabb60061d32ced243fe607069d8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/RegistrationDeclarations.h @@ -0,0 +1,4 @@ +// This file contains all native_functions that can be registered to +// and the schema string that they should be registered with + +${registration_declarations} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/TensorBody.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/TensorBody.h new file mode 100644 index 0000000000000000000000000000000000000000..61ee127493e91c6bbbeb4098d5c3bf5f5c528bc5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/TensorBody.h @@ -0,0 +1,745 @@ +#pragma once + +#ifdef TORCH_ASSERT_NO_OPERATORS +#error This change adds a dependency on native_functions.yaml, \ + meaning the file will need to be re-compiled every time an operator \ + is changed or added. Consider if your change would be better placed in \ + another file, or if a more specific header might achieve the same goal. \ + See NOTE: [Tensor vs. TensorBase] +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include + +namespace c10{ +template class List; +template class IListRef; +} +namespace at { +struct Generator; +struct Type; +class DeprecatedTypeProperties; +class Tensor; +} // namespace at +namespace at { +namespace indexing { +struct TensorIndex; +} // namespace indexing +} // namespace at + +namespace torch { namespace autograd { + +struct Node; + +}} // namespace torch::autograd + +namespace at { + +class OptionalTensorRef; +class TensorRef; +class Tensor; +using TensorList = ArrayRef; +using ITensorList = c10::IListRef; + +using Stream = c10::Stream; + +// Tensor is a "generic" object holding a pointer to the underlying TensorImpl object, which +// has an embedded reference count. In this way, Tensor is similar to boost::intrusive_ptr. +// +// For example: +// +// void func(Tensor a) { +// Tensor b = a; +// ... +// } +// +// In this example, when we say Tensor b = a, we are creating a new object that points to the +// same underlying TensorImpl, and bumps its reference count. When b goes out of scope, the +// destructor decrements the reference count by calling release() on the TensorImpl it points to. +// The existing constructors, operator overloads, etc. take care to implement the correct semantics. +// +// Note that Tensor can also be NULL, i.e. it is not associated with any underlying TensorImpl, and +// special care must be taken to handle this. +class TORCH_API Tensor: public TensorBase { + protected: + // Create a Tensor with a +0 reference count. Special care must be + // taken to avoid decrementing this reference count at destruction + // time. Intended to support MaybeOwnedTraits. + explicit Tensor(unsafe_borrow_t, const TensorBase& rhs): TensorBase(unsafe_borrow_t{}, rhs) {} + friend MaybeOwnedTraits; + friend OptionalTensorRef; + friend TensorRef; + + public: + Tensor() = default; + // This constructor should not be used by end users and is an implementation + // detail invoked by autogenerated code. + explicit Tensor( + c10::intrusive_ptr tensor_impl) + : TensorBase(std::move(tensor_impl)) {} + Tensor(const Tensor &tensor) = default; + Tensor(Tensor &&tensor) = default; + + // Implicitly move-constructible from TensorBase, but must be explicit to increase refcount + explicit Tensor(const TensorBase &base): TensorBase(base) {} + /*implicit*/ Tensor(TensorBase &&base): TensorBase(std::move(base)) {} + + // Creates a new wrapper from TensorImpl. Intentionally a free method because + // it should be used with care. Checks necessary invariants + static Tensor wrap_tensor_impl( + c10::intrusive_ptr tensor_impl) { + return TensorBase::wrap_tensor_impl(std::move(tensor_impl)); + } + + Tensor contiguous(MemoryFormat memory_format=MemoryFormat::Contiguous) const { + return TensorBase::contiguous(memory_format); + } + + Tensor conj() const { + if (!this->is_complex()) { + return *this; + } + + C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wswitch-enum") + switch (this->layout()) { + case at::kSparse: + case at::kSparseCsr: + case at::kSparseCsc: + case at::kSparseBsr: + case at::kSparseBsc: + return this->conj_physical(); + default: + return this->_conj(); + } + C10_DIAGNOSTIC_POP() + } + + // Bring in base class methods + using TensorBase::size; + using TensorBase::sym_size; + using TensorBase::stride; + + /// Should be used if *this can reasonably be expected to be contiguous and + /// performance is important. + /// Compared to contiguous, it saves a reference count + /// increment/decrement if *this is already contiguous, at the cost + /// in all cases of an extra pointer of stack usage, an extra branch + /// to access, and an extra branch at destruction time. + c10::MaybeOwned expect_contiguous(MemoryFormat memory_format=MemoryFormat::Contiguous) const &; + + // Use .contiguous() instead. Trying to borrow from a prvalue Tensor + // will only lead to trouble and dangling references. + c10::MaybeOwned expect_contiguous(MemoryFormat memory_format=MemoryFormat::Contiguous) && = delete; + + // The following overloads are very intriguing. Consider the following + // program: + // + // x[1] = 3; + // + // We would expect that the first entry of x is written to 3. But how can we + // actually achieve this? x[1] evaluates to a tensor... + // + // The answer is, using a ref-qualifier. x[1] is an rvalue, which cannot be + // (profitably) assigned to in the traditional sense, so we overload + // assignment to mean, "Actually, copy 3 into the tensor data." This is done + // with an rvalue-reference ref-qualified overload (the methods with && at the + // end of their type.) + // + // There's one more fly in the ointment: We also want + // + // Tensor x = y; + // + // to work, and we want it NOT to copy. So we need a traditional operator= + // overload. But we MUST specify a mutable lvalue ref-qualifier, to + // disambiguate the traditional overload from the rvalue-reference + // ref-qualified overload. Otherwise, it will be ambiguous, because + // a non ref-qualified method is eligible for all situations. + + // Unfortunately, we have to write these constructors out manually + // to work around an MSVC bug: + // error C2580: 'at::Tensor &at::Tensor::operator =(const at::Tensor &) &': + // multiple versions of a defaulted special member functions are not allowed + // Tensor& operator=(const Tensor&) & = default; + // Tensor& operator=(Tensor&&) & = default; + + // Also MSVC will wrongly issue the following warning with the aforementioned fix + // warning C4522: 'at::Tensor': multiple assignment operators specified + // Let's just skip the warning. + // + // TODO: temporarily disabled + + Tensor& operator=(const TensorBase& x) & noexcept { + impl_ = x.getIntrusivePtr(); + return *this; + } + Tensor& operator=(TensorBase&& x) & noexcept { + impl_ = x.unsafeReleaseIntrusivePtr(); + return *this; + } + + Tensor& operator=(const Tensor &x) & noexcept { + return operator=(static_cast(x)); + } + Tensor& operator=(Tensor &&x) & noexcept { + return operator=(static_cast(x)); + } + + Tensor& operator=(const Scalar &v) && { + return fill_(v); + } + Tensor& operator=(const Tensor &rhs) && { + return copy_(rhs); + } + + // NOLINTNEXTLINE(performance-noexcept-move-constructor) + Tensor& operator=(Tensor&& rhs) && { + return copy_(rhs); + } + + C10_DEPRECATED_MESSAGE("Tensor.type() is deprecated. Instead use Tensor.options(), which in many cases (e.g. in a constructor) is a drop-in replacement. If you were using data from type(), that is now available from Tensor itself, so instead of tensor.type().scalar_type(), use tensor.scalar_type() instead and instead of tensor.type().backend() use tensor.device().") + DeprecatedTypeProperties & type() const { + return globalDeprecatedTypePropertiesRegistry().getDeprecatedTypeProperties( + dispatchKeyToBackend(legacyExtractDispatchKey(key_set())), + scalar_type()); + } + + Tensor toType(ScalarType t) const { + return to(options().dtype(t), /*non_blocking*/ false, /*copy*/ false); + } + + // TODO: Deprecate me + Tensor toBackend(Backend b) const { + return to(options().device(backendToDeviceType(b)).layout(layout_from_backend(b)), /*non_blocking*/ false, /*copy*/ false); + } + + template + C10_DEPRECATED_MESSAGE("Tensor.data() is deprecated. Please use Tensor.data_ptr() instead.") + T * data() const { + return data_ptr(); + } + + template + T item() const; + + template class PtrTraits = DefaultPtrTraits, typename index_t = int64_t> + C10_DEPRECATED_MESSAGE("packed_accessor is deprecated, use packed_accessor32 or packed_accessor64 instead") + GenericPackedTensorAccessor packed_accessor() const & { + return generic_packed_accessor(); + } + template class PtrTraits = DefaultPtrTraits, typename index_t = int64_t> + C10_DEPRECATED_MESSAGE("packed_accessor is deprecated, use packed_accessor32 or packed_accessor64 instead") + GenericPackedTensorAccessor packed_accessor() && = delete; + + Tensor operator~() const { + return bitwise_not(); + } + Tensor operator-() const { + return neg(); + } + Tensor& operator+=(const Tensor & other) { + return add_(other); + } + Tensor& operator+=(const Scalar & other) { + return add_(other); + } + Tensor& operator-=(const Tensor & other) { + return sub_(other); + } + Tensor& operator-=(const Scalar & other) { + return sub_(other); + } + Tensor& operator*=(const Tensor & other) { + return mul_(other); + } + Tensor& operator*=(const Scalar & other) { + return mul_(other); + } + Tensor& operator/=(const Tensor & other) { + return div_(other); + } + Tensor& operator/=(const Scalar & other) { + return div_(other); + } + Tensor& operator&=(const Tensor & other) { + return bitwise_and_(other); + } + Tensor& operator|=(const Tensor & other) { + return bitwise_or_(other); + } + Tensor& operator^=(const Tensor & other) { + return bitwise_xor_(other); + } + Tensor operator[](const Scalar & index) const { + if (!index.isIntegral(false)) { + TORCH_CHECK_INDEX(false, "Can only index tensors with integral scalars"); + } + return this->operator[](index.toLong()); + } + Tensor operator[](const Tensor & index) const { + // These properties are checked in the Scalar constructor, but we already + // check them here to provide more useful diagnostics for the user. + if (!index.defined()) { + TORCH_CHECK_INDEX(false, "Can only index with tensors that are defined"); + } + if (index.dim() != 0) { + TORCH_CHECK_INDEX(false, + "Can only index with tensors that are scalars (zero-dim)"); + } + // The Scalar(Tensor) constructor is explicit, so we need to call it. + return this->operator[](index.item()); + } + Tensor operator[](int64_t index) const { + return select(0, index); + } + + Tensor index(ArrayRef indices) const; + Tensor index(std::initializer_list indices) const; + + Tensor & index_put_(ArrayRef indices, Tensor const & rhs); + Tensor & index_put_(ArrayRef indices, const Scalar& v); + Tensor & index_put_(std::initializer_list indices, Tensor const & rhs); + Tensor & index_put_(std::initializer_list indices, const Scalar& v); + + Tensor cpu() const { + return to(options().device(c10::DeviceType::CPU), /*non_blocking*/ false, /*copy*/ false); + } + + // TODO: The Python version also accepts arguments + Tensor cuda() const { + return to(options().device(c10::DeviceType::CUDA), /*non_blocking*/ false, /*copy*/ false); + } + + Tensor hip() const { + return to(options().device(c10::DeviceType::HIP), /*non_blocking*/ false, /*copy*/ false); + } + + Tensor ve() const { + return to(options().device(c10::DeviceType::VE), /*non_blocking*/ false, /*copy*/ false); + } + + Tensor vulkan() const { + return to(options().device(c10::DeviceType::Vulkan), /*non_blocking*/ false, /*copy*/ false); + } + + Tensor metal() const { + return to(options().device(c10::DeviceType::Metal), /*non_blocking*/ false, /*copy*/ false); + } + + Tensor meta() const { + return to(options().device(c10::DeviceType::Meta), /*non_blocking*/ false, /*copy*/ false); + } + + // ~~~~~ Autograd API ~~~~~ + + /// \fn bool is_leaf() const; + /// + /// All Tensors that have `requires_grad()` which is ``false`` will be leaf Tensors by convention. + /// + /// For Tensors that have `requires_grad()` which is ``true``, they will be leaf Tensors if they were + /// created by the user. This means that they are not the result of an operation and so + /// `grad_fn()` is `nullptr`. + /// + /// Only leaf Tensors will have their `grad()` populated during a call to `backward()`. + /// To get `grad()` populated for non-leaf Tensors, you can use `retain_grad()`. + /// + /// Example: + /// @code + /// auto a = torch::rand(10, torch::requires_grad()); + /// std::cout << a.is_leaf() << std::endl; // prints `true` + /// + /// auto b = torch::rand(10, torch::requires_grad()).to(torch::kCUDA); + /// std::cout << b.is_leaf() << std::endl; // prints `false` + /// // b was created by the operation that cast a cpu Tensor into a cuda Tensor + /// + /// auto c = torch::rand(10, torch::requires_grad()) + 2; + /// std::cout << c.is_leaf() << std::endl; // prints `false` + /// // c was created by the addition operation + /// + /// auto d = torch::rand(10).cuda(); + /// std::cout << d.is_leaf() << std::endl; // prints `true` + /// // d does not require gradients and so has no operation creating it (that is tracked by the autograd engine) + /// + /// auto e = torch::rand(10).cuda().requires_grad_(); + /// std::cout << e.is_leaf() << std::endl; // prints `true` + /// // e requires gradients and has no operations creating it + /// + /// auto f = torch::rand(10, torch::device(torch::kCUDA).requires_grad(true)); + /// std::cout << f.is_leaf() << std::endl; // prints `true` + /// // f requires grad, has no operation creating it + /// @endcode + + /// \fn void backward(const Tensor & gradient={}, std::optional retain_graph=std::nullopt, bool create_graph=false, std::optional inputs=std::nullopt) const; + /// + /// Computes the gradient of current tensor with respect to graph leaves. + /// + /// The graph is differentiated using the chain rule. If the tensor is + /// non-scalar (i.e. its data has more than one element) and requires + /// gradient, the function additionally requires specifying ``gradient``. + /// It should be a tensor of matching type and location, that contains + /// the gradient of the differentiated function w.r.t. this Tensor. + /// + /// This function accumulates gradients in the leaves - you might need to + /// zero them before calling it. + /// + /// \param gradient Gradient w.r.t. the + /// tensor. If it is a tensor, it will be automatically converted + /// to a Tensor that does not require grad unless ``create_graph`` is True. + /// None values can be specified for scalar Tensors or ones that + /// don't require grad. If a None value would be acceptable then + /// this argument is optional. + /// \param retain_graph If ``false``, the graph used to compute + /// the grads will be freed. Note that in nearly all cases setting + /// this option to True is not needed and often can be worked around + /// in a much more efficient way. Defaults to the value of + /// ``create_graph``. + /// \param create_graph If ``true``, graph of the derivative will + /// be constructed, allowing to compute higher order derivative + /// products. Defaults to ``false``. + /// \param inputs Inputs w.r.t. which the gradient will be accumulated into + /// ``at::Tensor::grad``. All other Tensors will be ignored. If not + /// provided, the gradient is accumulated into all the leaf Tensors + /// that were used to compute the current tensor. + /// When inputs are provided and a given input is not a leaf, + /// the current implementation will call its grad_fn (even though it is not strictly needed to get this gradients). + /// It is an implementation detail on which the user should not rely. + /// See https://github.com/pytorch/pytorch/pull/60521#issuecomment-867061780 for more details. + void backward(const Tensor & gradient={}, std::optional retain_graph=std::nullopt, bool create_graph=false, std::optional inputs=std::nullopt) const { + // NB: Adding this wrapper to _backward here because we'd like our + // 'backwards' api to accept the 'inputs' argument optionally. Since code gen + // currently does not support optional of TensorList our approach is to replace + // backward in native_functions.yaml with _backward and call it here instead. + if (inputs.has_value()) { + TORCH_CHECK(inputs.value().size() > 0, "'inputs' argument to backward cannot be empty") + this->_backward(inputs.value(), gradient, retain_graph, create_graph); + } else { + this->_backward({}, gradient, retain_graph, create_graph); + } + } + + /// \fn Tensor detach() const; + /// + /// Returns a new Tensor, detached from the current graph. + /// The result will never require gradient. + + /// \fn Tensor & detach_() const; + /// + /// Detaches the Tensor from the graph that created it, making it a leaf. + /// Views cannot be detached in-place. + + /// \fn void retain_grad() const; + /// + /// Enables this Tensor to have their :attr:`grad` populated during + /// :func:`backward`. This is a no-op for leaf tensors. + + /// \fn bool retains_grad() const; + /// + /// Is ``true`` if this Tensor is non-leaf and its :attr:`grad` is enabled to be + /// populated during :func:`backward`, ``false`` otherwise. + + const Tensor& set_requires_grad(bool requires_grad) const { + TensorBase::set_requires_grad(requires_grad); + return *this; + } + + /// Return a mutable reference to the gradient. This is conventionally + /// used as `t.grad() = x` to set a gradient to a completely new tensor. + /// Note that this function work with a non-const Tensor and is not + /// thread safe. + Tensor& mutable_grad() const { + return impl_->mutable_grad(); + } + + /// This function returns an undefined tensor by default and returns a defined tensor + /// the first time a call to `backward()` computes gradients for this Tensor. + /// The attribute will then contain the gradients computed and future calls + /// to `backward()` will accumulate (add) gradients into it. + const Tensor& grad() const { + const Tensor& maybe_grad = impl_->grad(); + if (!is_leaf() && !retains_grad() && !maybe_grad.defined()) { + TORCH_WARN( + "The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad " + "attribute won't be populated during autograd.backward(). If you indeed want the .grad " + "field to be populated for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. " + "If you access the non-leaf Tensor by mistake, make sure you access the leaf Tensor " + "instead. See github.com/pytorch/pytorch/pull/30531 for more information."); + } + return maybe_grad; + } + + // The Forward AD API functions below are low level and are not to be used by end + // users who should use the API provided in torch/csrc/autograd.h + + /// This function returns the forward gradient for this Tensor at the given level. + const Tensor& _fw_grad(uint64_t level) const { + return impl_->_fw_grad(level, *this); + } + + /// This function can be used to set the value of the forward grad. + /// Note that the given new_grad might not be used directly if it has different + /// metadata (size/stride/storage offset) compared to this Tensor. In that case, + /// new_grad content will be copied into a new Tensor + void _set_fw_grad(const TensorBase& new_grad, uint64_t level, bool is_inplace_op) const { + impl_->_set_fw_grad(new_grad, *this, level, is_inplace_op); + } + + + // STOP. Thinking of adding a method here, which only makes use + // of other ATen methods? Define it in native_functions.yaml. + + //example + //Tensor * add(Tensor & b); + ${tensor_method_declarations} + + // Special C++ only overloads for std()-like functions (See gh-40287) + // These are needed because int -> bool conversion takes precedence over int -> IntArrayRef + // So, for example std(0) would select the std(unbiased=False) overload + + Tensor var(int dim) const { + return var(IntArrayRef{dim}); + } + + Tensor std(int dim) const { + return std(IntArrayRef{dim}); + } + + // We changed .dtype() to return a TypeMeta in #12766. Ideally, we want the + // at::kDouble and its friends to be TypeMeta's, but that hasn't happened yet. + // Before that change, we make this method to maintain BC for C++ usage like + // `x.to(y.dtype)`. + // TODO: remove following two after at::kDouble and its friends are TypeMeta's. + inline Tensor to(caffe2::TypeMeta type_meta, bool non_blocking=false, bool copy=false) const { + return this->to(/*scalar_type=*/typeMetaToScalarType(type_meta), non_blocking, copy); + } + inline Tensor to(Device device, caffe2::TypeMeta type_meta, bool non_blocking=false, bool copy=false) const { + return this->to(device, /*scalar_type=*/typeMetaToScalarType(type_meta), non_blocking, copy); + } + + template + decltype(auto) m(F func, Args&&... params) const { + return func(*this, std::forward(params)...); + } + + /// NOTE: This is similar to the legacy `.data()` function on `Variable`, and is intended + /// to be used from functions that need to access the `Variable`'s equivalent `Tensor` + /// (i.e. `Tensor` that shares the same storage and tensor metadata with the `Variable`). + /// + /// One notable difference with the legacy `.data()` function is that changes to the + /// returned `Tensor`'s tensor metadata (e.g. sizes / strides / storage / storage_offset) + /// will not update the original `Variable`, due to the fact that this function + /// shallow-copies the `Variable`'s underlying TensorImpl. + at::Tensor tensor_data() const { + return TensorBase::tensor_data(); + } + + /// NOTE: `var.variable_data()` in C++ has the same semantics as `tensor.data` + /// in Python, which create a new `Variable` that shares the same storage and + /// tensor metadata with the original `Variable`, but with a completely new + /// autograd history. + /// + /// NOTE: If we change the tensor metadata (e.g. sizes / strides / + /// storage / storage_offset) of a variable created from `var.variable_data()`, those + /// changes will not update the original variable `var`. In `.variable_data()`, we set + /// `allow_tensor_metadata_change_` to false to make such changes explicitly illegal, + /// in order to prevent users from changing metadata of `var.variable_data()` + /// and expecting the original variable `var` to also be updated. + at::Tensor variable_data() const { + return TensorBase::variable_data(); + } + + // Hooks + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + /// Registers a backward hook. + /// + /// The hook will be called every time a gradient with respect to the Tensor is computed. + /// The hook should have one of the following signature: + /// ``` + /// hook(Tensor grad) -> Tensor + /// ``` + /// ``` + /// hook(Tensor grad) -> void + /// ``` + /// The hook should not modify its argument, but it can optionally return a new gradient + /// which will be used in place of `grad`. + /// + /// This function returns the index of the hook in the list which can be used to remove hook. + /// + /// Example: + /// @code + /// auto v = torch::tensor({0., 0., 0.}, torch::requires_grad()); + /// auto h = v.register_hook([](torch::Tensor grad){ return grad * 2; }); // double the gradient + /// v.backward(torch::tensor({1., 2., 3.})); + /// // This prints: + /// // ``` + /// // 2 + /// // 4 + /// // 6 + /// // [ CPUFloatType{3} ] + /// // ``` + /// std::cout << v.grad() << std::endl; + /// v.remove_hook(h); // removes the hook + /// @endcode + template + unsigned register_hook(T&& hook) const; + + // Variable methods + //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Tensor data() const { + return TensorBase::data(); + } + + void _backward(TensorList inputs, const std::optional& gradient, std::optional keep_graph, bool create_graph) const; + + const Tensor& requires_grad_(bool _requires_grad=true) const { + TensorBase::requires_grad_(_requires_grad); + return *this; + } +}; + +namespace detail { +// Helper creator for Tensor class which doesn't requires the users to pass +// in an intrusive_ptr instead it just converts the argument passed to +// requested intrusive_ptr type. +template +Tensor make_tensor(Args&&... args) { + return Tensor(c10::make_intrusive(std::forward(args)...)); +} + +} // namespace detail + +} // namespace at + + +namespace at { +${tensor_method_definitions} +} // namespace at + + +namespace c10 { +template <> +struct MaybeOwnedTraits { + using owned_type = at::Tensor; + using borrow_type = at::Tensor; + + static borrow_type createBorrow(const owned_type& from) { + // NOTE: this can be implemented without the special + // unsafe_borrow_t Tensor constructor as + // + // return borrow_type(c10::intrusive_ptr::reclaim(from.unsafeGetTensorImpl())); + // + // but that hurts inlining due to the nullptr check in the + // Tensor(c10::intrusive_ptr<...>) constructor. We already know + // that from.impl_ isn't null because from is a valid Tensor, so + // we needn't do the check again. (using __builtin_assume can + // avoid this, but wouldn't be portable to MSVC.) + return borrow_type(borrow_type::unsafe_borrow_t{}, from); + } + + static void assignBorrow(borrow_type& lhs, const borrow_type& rhs) { + lhs.unsafeReleaseTensorImpl(); + // See above note: this can be implemented with public API + // similarly to createBorrow(), but that would hurt inlining. + lhs = borrow_type(borrow_type::unsafe_borrow_t{}, rhs); + } + + static void destroyBorrow(borrow_type& toDestroy) { + toDestroy.unsafeReleaseTensorImpl(); // "leak" it, but it was already +0. + } + + static const owned_type& referenceFromBorrow(const borrow_type& borrow) { + return borrow; + } + + static const owned_type* pointerFromBorrow(const borrow_type& borrow) { + return &borrow; + } + + static bool debugBorrowIsValid(const borrow_type& /*borrow*/) { + return true; + } +}; + +template <> +struct ExclusivelyOwnedTraits { + using repr_type = at::Tensor; + using pointer_type = at::Tensor*; + using const_pointer_type = const at::Tensor*; + + static repr_type nullRepr() { + return at::Tensor(); + } + + template + static repr_type createInPlace(Args&&... args) { + return at::Tensor(std::forward(args)...); + } + + static repr_type moveToRepr(at::Tensor&& x) { + return std::move(x); + } + + static void destroyOwned(at::Tensor& x) { + return ExclusivelyOwnedTraits::destroyOwned(x); + } + + static at::Tensor take(at::Tensor& x) { + return std::move(x); + } + + static pointer_type getImpl(repr_type& x) { + return &x; + } + + static const_pointer_type getImpl(const repr_type& x) { + return &x; + } +}; +} // namespace c10 + +namespace at { + +inline c10::MaybeOwned borrow_from_optional_tensor( + const std::optional& opt) { + return opt.has_value() + ? c10::MaybeOwned::borrowed(*opt) + : c10::MaybeOwned::owned(std::in_place); +} + +inline c10::MaybeOwned Tensor::expect_contiguous(MemoryFormat memory_format) const & { + if (is_contiguous(memory_format)) { + return c10::MaybeOwned::borrowed(*this); + } else { + return c10::MaybeOwned::owned(__dispatch_contiguous(memory_format)); + } +} +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/TensorMethods.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/TensorMethods.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a016af0238317606433c9016511d57ade6f721b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/TensorMethods.cpp @@ -0,0 +1,66 @@ +#include +#include +#include + +#include + +namespace at { + +namespace { + +// Verifies the requested type is the same as the Tensor's type. +void check_type(const TensorBase& tensor, ScalarType type) { + TORCH_CHECK( + tensor.scalar_type() == type + || (isQIntType(tensor.scalar_type()) + && toUnderlying(tensor.scalar_type()) == type), + "expected scalar type ", type, " but found ", tensor.scalar_type()); +} + +} // namespace + +template +const T* TensorBase::const_data_ptr() const { + using NonConstT = std::remove_const_t; + check_type(*this, c10::CppTypeToScalarType()); + return this->unsafeGetTensorImpl()->data_ptr_impl(); +} + +template +T* TensorBase::mutable_data_ptr() const { + check_type(*this, c10::CppTypeToScalarType()); + return this->unsafeGetTensorImpl()->mutable_data_ptr_impl(); +} + +template +T* TensorBase::data_ptr() const { + return this->mutable_data_ptr(); +} + +#define DEFINE_CAST(T, name) \ + template TORCH_API const T* TensorBase::const_data_ptr() const; \ + template TORCH_API const T* TensorBase::const_data_ptr() const; \ + template TORCH_API T* TensorBase::mutable_data_ptr() const; \ + template TORCH_API T* TensorBase::data_ptr() const; + + AT_FORALL_SCALAR_TYPES_V2( + AT_WRAP(DEFINE_CAST), + AT_EXPAND(AT_ALL_SCALAR_TYPES_WITH_COMPLEX), + kUInt16, + kUInt32, + kUInt64) + AT_FORALL_QINT_TYPES(DEFINE_CAST) + #undef DEFINE_CAST + + #define DEFINE_ITEM(T, name) \ + template <> \ + TORCH_API T Tensor::item() const { \ + return item().to(); \ + } + + AT_FORALL_SCALAR_TYPES_V2( + AT_WRAP(DEFINE_ITEM), + AT_EXPAND(AT_ALL_SCALAR_TYPES_WITH_COMPLEX)) + #undef DEFINE_ITEM + + } //namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UfuncCPU.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UfuncCPU.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b363a508907cc064e41794720657541fc28c301 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UfuncCPU.cpp @@ -0,0 +1,19 @@ +#define TORCH_ASSERT_NO_OPERATORS + +#include +#include +#include + +namespace at { + +// NB: this is explicitly copied here (via codegen) rather than +// included via NativeFunctions.h to avoid recompiling this file when +// NativeFunctions.h changes +namespace meta { +${meta_declaration} +} + +namespace native { +${native_declaration} +${native_definitions} +}} // namespace at::native diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UfuncCPUKernel.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UfuncCPUKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0cac55664d6125287bdee0bd94c150462b81d5b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UfuncCPUKernel.cpp @@ -0,0 +1,14 @@ +#define TORCH_ASSERT_NO_OPERATORS + +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +${native_definitions} +}} // namespace at::native diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UfuncCUDA.cu b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UfuncCUDA.cu new file mode 100644 index 0000000000000000000000000000000000000000..e75d82d9cc84bd8fddfd303f610412e5d0a98729 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UfuncCUDA.cu @@ -0,0 +1,21 @@ +#define TORCH_ASSERT_NO_OPERATORS + +#include +#include +#include +#include +${cuda_headers} + +namespace at { + +// NB: this is explicitly copied here (via codegen) rather than +// included via NativeFunctions.h to avoid recompiling this file when +// NativeFunctions.h changes +namespace meta { +${meta_declaration} +} + +namespace native { +${native_declaration} +${native_definitions} +}} // namespace at::native diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UnboxingFunctions.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UnboxingFunctions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..86c13235d8623964d734e743f5f15cf68a8df63c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UnboxingFunctions.cpp @@ -0,0 +1,35 @@ +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace at { +namespace unboxing { + +using ::c10::fmap; +using ::c10::filter; +using torch::jit::peek; +using torch::jit::drop; +using torch::jit::pack; +using torch::jit::pop; + +// Generated function declaration +${definitions} + +} // namespace unboxing +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UnboxingFunctions.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UnboxingFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..a65469a9b0123cbfd4075ff3c263276aa47f137f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/UnboxingFunctions.h @@ -0,0 +1,32 @@ +// ${generated_comment} + +// Generated by tools/jit/gen_unboxing.py. This file declares code generated boxed C++ functions for operators, +// base off of native_functions.yaml (or similar yaml file with the same syntax). The definition of such a boxed +// function will pop out IValues from the stack then convert them into the correct C++ types based on given schema. This +// unboxing logic is an alternative to template-based metaprogramming unboxing. + +#pragma once + +#include +namespace at { +namespace unboxing { +namespace { + +template +std::array as_array(const c10::List& list) { + std::array res; + AT_ASSERT(list.size() == N); + std::vector vec; + for (c10::IValue elem : list) { + vec.push_back(elem.to()); + } + std::copy(vec.begin(), vec.end(), res.begin()); + return res; +} +} // namespace +using Stack = std::vector; +// Generated function declaration +${declarations} + +} // namespace unboxing +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/ViewMetaClasses.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/ViewMetaClasses.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0fd53171935f9147ba54bcd39a886e2f4dda6b2f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/ViewMetaClasses.cpp @@ -0,0 +1,19 @@ +// ${generated_comment} + +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +${op_headers} +#endif + +namespace at { +namespace functionalization { + +${view_meta_implementations} + +} // namespace functionalization +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/ViewMetaClasses.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/ViewMetaClasses.h new file mode 100644 index 0000000000000000000000000000000000000000..be2dee2a871b35258864377fbac83e3037108b2b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/ViewMetaClasses.h @@ -0,0 +1,12 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// ${generated_comment} + +#include + +namespace at { +namespace functionalization { + +${view_meta_declarations} + +} // namespace functionalization +} // namespace at diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/ViewMetaClassesPythonBinding.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/ViewMetaClassesPythonBinding.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c784e5abe5c88dfb5bc418e60d48b28391274718 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/ViewMetaClassesPythonBinding.cpp @@ -0,0 +1,11 @@ +#include +#include + +namespace torch::functionalization { + +void initGenerated(PyObject* module) { + auto functionalization = py::handle(module).cast(); + $view_meta_bindings +} + +} // namespace torch::functionalization diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/aten_interned_strings.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/aten_interned_strings.h new file mode 100644 index 0000000000000000000000000000000000000000..326d4622334a776f4f1f94fb49a70f2c53c7e6eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/aten_interned_strings.h @@ -0,0 +1,22 @@ +#pragma once + +// ${generated_comment} + +#if defined(TORCH_ASSERT_NO_OPERATORS) || defined(TORCH_ASSERT_ONLY_METHOD_OPERATORS) +#error This change adds a dependency on native_functions.yaml, \ + meaning the file will need to be re-compiled every time an operator \ + is changed or added. Consider if including for \ + the c10::Symbol class would be sufficient, or if your change would be \ + better placed in another file. +#endif + +// ATen symbols correspond exactly to operators defined in ATen. Every +// symbol here corresponds exactly to an ATen operation defined in +// native_functions.yaml; attributes are in one-to-one correspondence +// with their ATen name. + +#define FORALL_ATEN_BASE_SYMBOLS(_) \ +${aten_symbols} + +#define FORALL_ATTR_BASE_SYMBOLS(_) \ +${attr_symbols} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/enum_tag.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/enum_tag.h new file mode 100644 index 0000000000000000000000000000000000000000..49c174b721153eeba19f98601bd742a0eb5b64ab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/ATen/templates/enum_tag.h @@ -0,0 +1,19 @@ +#pragma once + +// ${generated_comment} + +#include + +HIDDEN_NAMESPACE_BEGIN(torch, headeronly) + +// Enum of valid tags obtained from the entries in tags.yaml +enum class Tag { + ${enum_of_valid_tags} +}; + +HIDDEN_NAMESPACE_END(torch, headeronly) + +// Re-expose in the at:: namespace for backward compatibility +namespace at { + using torch::headeronly::Tag; +} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__init__.py b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55df4b599246af8b39e5620e025d1e8315977e81 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/context.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..064dac5de4fd285f77107880f15a37e4dd88eb7b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/context.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_annotated_fn_args.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_annotated_fn_args.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..614e1a03b98a12ed5e7b27296479f62684840c55 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_annotated_fn_args.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_autograd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_autograd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fae38bf2b34596e3ff7895d766123135bef544d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_autograd.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_autograd_functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_autograd_functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3e53cf1a35285765f81cece33f56ba264f32e82 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_autograd_functions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_inplace_or_view_type.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_inplace_or_view_type.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f8b9fab7240a75da59367c8df19028b8f5b7a2a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_inplace_or_view_type.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_python_functions.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_python_functions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e71a282a7bfa6a1c0f43545734a50742907c116 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_python_functions.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_trace_type.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_trace_type.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9a57de4957af2121e6954f2fe0e4f47071fbafd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_trace_type.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_variable_factories.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_variable_factories.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9da9501405c98a3a922ee71641fd31dec857e9a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_variable_factories.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_variable_type.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_variable_type.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53968ee7a046ec14b64748e9f3ad2bfd1f18b4b8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_variable_type.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_view_funcs.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_view_funcs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de0ae7490bfe0415d28bc0f31027e5b4ed895b59 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/gen_view_funcs.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/load_derivatives.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/load_derivatives.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd23009e89c6b442ccebdee5692af92d564fb208 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/__pycache__/load_derivatives.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/context.py b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/context.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed4b2ee4d014be3dca01c3f2293b36b03b7880b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/context.py @@ -0,0 +1,31 @@ +import functools +from collections.abc import Callable + +from torchgen.api.autograd import NativeFunctionWithDifferentiabilityInfo as NFWDI +from torchgen.context import native_function_manager +from torchgen.utils import T + + +# Like tools.api.context.with_native_function, but for +# NativeFunctionWithDifferentiabilityInfo. +def with_native_function_with_differentiability_info( + func: Callable[[NFWDI], T], +) -> Callable[[NFWDI], T]: + @functools.wraps(func) + def wrapper(f: NFWDI) -> T: + with native_function_manager(f.func): + return func(f) + + return wrapper + + +# Like the above but with an additional dispatch key string argument +def with_native_function_with_differentiability_info_and_key( + func: Callable[[NFWDI, str], T], +) -> Callable[[NFWDI, str], T]: + @functools.wraps(func) + def wrapper(f: NFWDI, key: str) -> T: + with native_function_manager(f.func): + return func(f, key) + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/deprecated.yaml b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/deprecated.yaml new file mode 100644 index 0000000000000000000000000000000000000000..52f7ec50b6ea15dae1c3308358997950d295c924 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/deprecated.yaml @@ -0,0 +1,134 @@ +# Deprecated function signatures. These are exposed in Python, but not included +# in the error message suggestions. + +- name: add(Tensor self, Scalar alpha, Tensor other) -> Tensor + aten: add(self, other, alpha) + +- name: add_(Tensor(a!) self, Scalar alpha, Tensor other) -> Tensor(a!) + aten: add_(self, other, alpha) + +- name: add(Tensor self, Scalar alpha, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + aten: add_out(out, self, other, alpha) + +- name: addbmm(Scalar beta, Tensor self, Scalar alpha, Tensor batch1, Tensor batch2) -> Tensor + aten: addbmm(self, batch1, batch2, beta, alpha) + +- name: addbmm_(Scalar beta, Tensor(a!) self, Scalar alpha, Tensor batch1, Tensor batch2) -> Tensor(a!) + aten: addbmm_(self, batch1, batch2, beta, alpha) + +- name: addbmm(Scalar beta, Tensor self, Scalar alpha, Tensor batch1, Tensor batch2, *, Tensor(a!) out) -> Tensor(a!) + aten: addbmm_out(out, self, batch1, batch2, beta, alpha) + +- name: addbmm(Scalar beta, Tensor self, Tensor batch1, Tensor batch2) -> Tensor + aten: addbmm(self, batch1, batch2, beta, 1) + +- name: addbmm_(Scalar beta, Tensor(a!) self, Tensor batch1, Tensor batch2) -> Tensor(a!) + aten: addbmm_(self, batch1, batch2, beta, 1) + +- name: addbmm(Scalar beta, Tensor self, Tensor batch1, Tensor batch2, *, Tensor(a!) out) -> Tensor(a!) + aten: addbmm_out(out, self, batch1, batch2, beta, 1) + +- name: addcdiv(Tensor self, Scalar value, Tensor tensor1, Tensor tensor2) -> Tensor + aten: addcdiv(self, tensor1, tensor2, value) + +- name: addcdiv_(Tensor(a!) self, Scalar value, Tensor tensor1, Tensor tensor2) -> Tensor(a!) + aten: addcdiv_(self, tensor1, tensor2, value) + +- name: addcdiv(Tensor self, Scalar value, Tensor tensor1, Tensor tensor2, *, Tensor(a!) out) -> Tensor(a!) + aten: addcdiv_out(out, self, tensor1, tensor2, value) + +- name: addcmul(Tensor self, Scalar value, Tensor tensor1, Tensor tensor2) -> Tensor + aten: addcmul(self, tensor1, tensor2, value) + +- name: addcmul_(Tensor(a!) self, Scalar value, Tensor tensor1, Tensor tensor2) -> Tensor(a!) + aten: addcmul_(self, tensor1, tensor2, value) + +- name: addcmul(Tensor self, Scalar value, Tensor tensor1, Tensor tensor2, *, Tensor(a!) out) -> Tensor(a!) + aten: addcmul_out(out, self, tensor1, tensor2, value) + +- name: addmm(Scalar beta, Tensor self, Scalar alpha, Tensor mat1, Tensor mat2) -> Tensor + aten: addmm(self, mat1, mat2, beta, alpha) + +- name: addmm_(Scalar beta, Tensor(a!) self, Scalar alpha, Tensor mat1, Tensor mat2) -> Tensor(a!) + aten: addmm_(self, mat1, mat2, beta, alpha) + +- name: addmm(Scalar beta, Tensor self, Scalar alpha, Tensor mat1, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!) + aten: addmm_out(out, self, mat1, mat2, beta, alpha) + +- name: addmm(Scalar beta, Tensor self, Tensor mat1, Tensor mat2) -> Tensor + aten: addmm(self, mat1, mat2, beta, 1) + +- name: addmm_(Scalar beta, Tensor(a!) self, Tensor mat1, Tensor mat2) -> Tensor(a!) + aten: addmm_(self, mat1, mat2, beta, 1) + +- name: addmm(Scalar beta, Tensor self, Tensor mat1, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!) + aten: addmm_out(out, self, mat1, mat2, beta, 1) + +- name: sspaddmm(Scalar beta, Tensor self, Scalar alpha, Tensor mat1, Tensor mat2) -> Tensor + aten: sspaddmm(self, mat1, mat2, beta, alpha) + +- name: sspaddmm(Scalar beta, Tensor self, Tensor mat1, Tensor mat2) -> Tensor + aten: sspaddmm(self, mat1, mat2, beta, 1) + +- name: addmv(Scalar beta, Tensor self, Scalar alpha, Tensor mat, Tensor vec) -> Tensor + aten: addmv(self, mat, vec, beta, alpha) + +- name: addmv_(Scalar beta, Tensor(a!) self, Scalar alpha, Tensor mat, Tensor vec) -> Tensor(a!) + aten: addmv_(self, mat, vec, beta, alpha) + +- name: addmv(Scalar beta, Tensor self, Scalar alpha, Tensor mat, Tensor vec, *, Tensor(a!) out) -> Tensor(a!) + aten: addmv_out(out, self, mat, vec, beta, alpha) + +- name: addmv(Scalar beta, Tensor self, Tensor mat, Tensor vec) -> Tensor + aten: addmv(self, mat, vec, beta, 1) + +- name: addmv_(Scalar beta, Tensor(a!) self, Tensor mat, Tensor vec) -> Tensor(a!) + aten: addmv_(self, mat, vec, beta, 1) + +- name: addmv(Scalar beta, Tensor self, Tensor mat, Tensor vec, *, Tensor(a!) out) -> Tensor(a!) + aten: addmv_out(out, self, mat, vec, beta, 1) + +- name: addr(Scalar beta, Tensor self, Scalar alpha, Tensor vec1, Tensor vec2) -> Tensor + aten: addr(self, vec1, vec2, beta, alpha) + +- name: addr_(Scalar beta, Tensor(a!) self, Scalar alpha, Tensor vec1, Tensor vec2) -> Tensor(a!) + aten: addr_(self, vec1, vec2, beta, alpha) + +- name: addr(Scalar beta, Tensor self, Scalar alpha, Tensor vec1, Tensor vec2, *, Tensor(a!) out) -> Tensor(a!) + aten: addr_out(out, self, vec1, vec2, beta, alpha) + +- name: addr(Scalar beta, Tensor self, Tensor vec1, Tensor vec2) -> Tensor + aten: addr(self, vec1, vec2, beta, 1) + +- name: addr_(Scalar beta, Tensor(a!) self, Tensor vec1, Tensor vec2) -> Tensor(a!) + aten: addr_(self, vec1, vec2, beta, 1) + +- name: addr(Scalar beta, Tensor self, Tensor vec1, Tensor vec2, *, Tensor(a!) out) -> Tensor(a!) + aten: addr_out(out, self, vec1, vec2, beta, 1) + +- name: baddbmm(Scalar beta, Tensor self, Scalar alpha, Tensor batch1, Tensor batch2) -> Tensor + aten: baddbmm(self, batch1, batch2, beta, alpha) + +- name: baddbmm_(Scalar beta, Tensor(a!) self, Scalar alpha, Tensor batch1, Tensor batch2) -> Tensor(a!) + aten: baddbmm_(self, batch1, batch2, beta, alpha) + +- name: baddbmm(Scalar beta, Tensor self, Scalar alpha, Tensor batch1, Tensor batch2, *, Tensor(a!) out) -> Tensor(a!) + aten: baddbmm_out(out, self, batch1, batch2, beta, alpha) + +- name: baddbmm(Scalar beta, Tensor self, Tensor batch1, Tensor batch2) -> Tensor + aten: baddbmm(self, batch1, batch2, beta, 1) + +- name: baddbmm_(Scalar beta, Tensor(a!) self, Tensor batch1, Tensor batch2) -> Tensor(a!) + aten: baddbmm_(self, batch1, batch2, beta, 1) + +- name: baddbmm(Scalar beta, Tensor self, Tensor batch1, Tensor batch2, *, Tensor(a!) out) -> Tensor(a!) + aten: baddbmm_out(out, self, batch1, batch2, beta, 1) + +- name: sub(Tensor self, Scalar alpha, Tensor other) -> Tensor + aten: sub(self, other, alpha) + +- name: sub_(Tensor(a!) self, Scalar alpha, Tensor other) -> Tensor(a!) + aten: sub_(self, other, alpha) + +- name: sub(Tensor self, Scalar alpha, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + aten: sub_out(out, self, other, alpha) diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/derivatives.yaml b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/derivatives.yaml new file mode 100644 index 0000000000000000000000000000000000000000..55e0f644ce4334068e734cca1b48e66a959da425 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/derivatives.yaml @@ -0,0 +1,3299 @@ +# Defines derivative formulas and Python signatures of methods on Variable +# +# Note about possibly confusing nomenclature: An 'output gradient' is the +# gradient of an output of a forward function. Output gradients are used as +# the inputs to backward functions. `grads` is a vector of output gradients, +# and `grad == grads[0]`, in all the derivative formulas in this file. +# An 'input gradient' is the gradient of an input to a forward function. +# Input gradients are the outputs of backward functions, corresponding to the +# input names included in the derivative formulas defined in this file. +# Also, every time we talk computing "gradient" we actually mean computing +# the vector jacobian product using the given 'output gradient' as the vector. +# +# Each entry consists of: +# - A 'name', which specifies the ATen name of the function you +# are defining derivatives for, and an argument specification. +# - An optional 'dispatch' entry which can be used to specify +# per-autograd dispatch key derivatives. If this entry is not +# specified, then the gradient entries will be taken as the +# default gradients (i.e. registered for every backward dispatch +# key). (see _test_autograd_multiple_dispatch for an example +# of how to register separate derivates for different dispatch keys). +# The list of allowed dispatch keys (in addition to 'Default' which +# represents the Autograd alias key) is torchgen/model.py:AUTOGRAD_KEYS. +# - One or more gradients entries, mapping differentiable input +# names to a formula specifying how to compute its gradient. +# Note that a single gradient entry can specify the gradient +# formula for multiple input names, by specifying a key +# "input1, input2" (see atan2 for an example). +# - An argument can be flagged as 'non_differentiable'. +# - Optional entry with key 'output_differentiability' and value a list of the +# same length as the number of outputs from the forward function. The list +# should contain only booleans, specifying whether each of the output Tensor +# is differentiable. +# If it is not specified for a function that returns multiple elements but +# uses `grad` instead of `grads[idx]`, then all but the first output will +# be marked as non-differentiable. +# If None of the output is differentiable, you can also add the function +# name to `gen_variable_type.py`'s `DONT_REQUIRE_DERIVATIVE` list. +# +# There are two cases for Tensor and TensorList arguments here: +# - If that argument is differentiable, in the sense that a gradient with respect +# to that argument could exist. You should either: +# - Specify the formula for that gradient +# - Specify not_implemented("function_name") as a formula to say that this is not +# implemented yet (but might be in the future and the user can request that on an issue) +# - If that argument is not differentiable, because it is not a floating point dtype or the +# function is not differentiable with respect to that argument for +# example. You should either: +# - Do not specify any formula for this argument +# - Specify explicitly that this argument is "non_differentiable". Note that in this case, +# we trust you that this argument will never have requires_grad=True and it will be silently +# ignored if it does. +# +# If a function has out-of-place and in-place variants, then the derivative +# definition for the in-place variant is optional. It will default to the +# definition for the out-of-place variant. Note that _out variants are never +# differentiable. +# +# Gradient expressions are standard C++ expressions operating on ATen +# variables. In a gradient expression, the following variables/functions +# are in scope: +# +# - 'grad', the gradient of the output (often spelled grad_output +# in Python) which we are going to left-multiply. +# +# When a function returns multiple *differentiable* outputs, +# you can refer to the gradients of each outputs using 'grads', +# e.g., 'grads[0]', 'grads[1]'. +# +# When a function returns multiple *differentiable* outputs that +# are named, you can refer to the gradients of each outputs using +# 'grad_{name}', e.g., 'grad_x', 'grad_y'. +# +# When a function returns *one* differentiable output (the +# first output) and some more nondifferentiable outputs, +# you MUST refer to the gradient of the differentiable output with +# 'grad' (this case is special-cased in our code generation). +# +# Note that the number of differentiable outputs can be modified by the +# 'output_differentiability' entry (see above). +# +# Across a differentiable function's derivatives set, it is not +# permitted to mix the use of "grad", "grads", and +# "grad_{name}". You must be consistent for that differentiable +# function. +# +# - Any of the input arguments, tensor or non-tensor, including +# argument names that only appear in Declarations.yaml, e.g. 'output'. +# +# - 'result', representing the result of evaluating the forward +# expression for ATen native function declarations. If the forward +# expression outputs a tuple, use 'resultX' instead to access the +# X-th entry +# +# - 'grad_input_mask', a std::array, specifies which input +# gradients are actually needed. For example, in the entry +# `input0, input1: foo(grad_input_mask)`, `grad_input_mask` is a size +# two array, where `grad_input_mask[0]` is true if `input0` requires +# grad, and `grad_input_mask[1]` is true if `input1` requires grad. +# +# (NB: if your function computes gradient for a list of tensors, +# the `grad_input_mask` will only have a single entry for the list +# specifying if either zero or at least one tensor from the list requires +# grad. If we want to support more fine-grained signalling, +# we'll need some alternate variable which is not a std::array) +# +# - 'retain_variables', a bool which is true if a user has specified +# that saved variables should be retained in case the backwards is +# run again later. This allows an optimization where we can +# destroy saved buffers if we know variables are not going to be retained, +# e.g., it is used by _cudnn_rnn +# +# - `wrap_opt_if`, is a 2-argument function that accepts a tensor +# variable and a boolean condition that dictates whether to save that +# variable in a graph. The result of this function is `std::optional`, +# and it is `::std::nullopt` when the condition evaluates to `false`, +# otherwise it is the variable wrapped in `std::optional`. +# For example, wrap_opt_if(var_0, grad_input_mask[1] || grad_input_mask[2]) +# would mean that `var_0` is saved as long as the second (grad_input_mask[1]) +# or the third (grad_input_mask[2]) argument requires gradients. +# Another interpretation of this expression would read as `var_0` is needed +# in the backward computation of the second or the third argument. +# NOTE: the usage of `var_i.requires_grad()` in the conditional expression +# is not supported, use `grad_input_mask[i]` instead. +# NOTE: `wrap_opt_if` could be used to prevent saving redundant variables +# with multi-output backward formulas. +# See https://github.com/pytorch/pytorch/issues/97575 for more details +# on the issue. +# +# If you need a complex expression, e.g., with local variables, +# write a _backward function in torch/csrc/autograd/FunctionsManual.cpp +# and invoke it from here. By the way, go read +# https://github.com/zdevito/ATen/issues/163; this describes an +# important hazard that occurs when porting backwards from Python to C++ +# +# Double backwards gradient expressions can be somewhat confusing; +# the most important thing to remember is: (1) you need to define a +# derivative formula for every input, including inputs named things +# like 'grad_output', and (2) the gradient to multiply with is always +# called 'grad' (even though it really is a grad-grad). +# +# You can also add forward derivative definition by defining a formula for +# a returned value (in general "result" if the name is not specified). This +# formula works the same way as the backward one and advanced implementations +# should also be placed in the FunctionsManual file. +# This formula should compute a single Jacobian vector product using the (primal) +# value of the argument "foo_p", its forward grad "foo_t" and the result of the +# function as "result". +# Note that the forward derivative can be automatically generated in two cases: +# - if your function is linear (NOT affine or multi-linear), then you can +# specify so by just using the string "auto_linear" for the formula. +# - if your function is applied element wise (and has a single input), you +# can specify so by just using the string "auto_element_wise" for the formula. +# +# Note that to avoid unpacking overhead, functions taking TensorList as inputs +# will always have their forward grad formula called. This function is responsible +# to check if any computation is needed and should return an undefined Tensor when +# there is nothing to do. You can check "cat_forward" for a full example. +# +# NB: There are a number of gradient definitions in here which are bogus +# (implemented using zeros_like). These gradients are (hopefully) not +# used by our frontend. You MUST check the frontend code; search for +# OpName.apply to see if it's still using a legacy Python style API. +# +# Note: Returning views. +# The following cases exist: +# - If a function returns no view, it can have arbitrary outputs. +# - If a function return at least one Tensor that is a differentiable view +# of one of its input: +# - If there is only one differentiable output, this Tensor is marked as a +# differentiable view. (alias or transpose for example) +# - If there are more than one differentiable output, by default all the views are +# marked as differentiable views and created with allow_rebase_history=false. +# Meaning that any inplace operation on it will raise an error. (unbind for example) +# +# Notes about undefined output gradients: +# All backward functions must support all combinations of undefined output +# gradient Tensors, where `grad[i].defined() == false`. Depending on the +# number of input and output grads your derivative formula uses, code +# generation may automatically add some level of undefined grad support, +# according to these three cases: +# +# * 1 input grad and 1 output grad: +# Complete undefined grad support is automatically added, so you +# shouldn't have to think about it, unless there is a bug in the code +# generation. +# +# * 1 input grad and multiple output grads: +# Undefined grad support is automatically added ONLY in the case where +# all output grads are undefined. You will have to add explicit support +# for cases where a subset of output grads is undefined. +# +# * multiple input grads: +# No automatic support, so you will need to add it. +# +# If your derivative formula uses more than one output grad, it is usually +# preferable to add undefined grad support in the backward function itself +# (if you're using one), rather than in the derivative formula in this file. +# +# Undefined Tensors are created with the default constructor `at::Tensor()`. +# It is an efficient way to represent a Tensor filled with zeros because +# the Tensor holds no sizing information and no Storage data is allocated. +# But consequently, Tensor operations cannot be performed on them. +# Therefore, your backward function should treat an undefined output grad as +# a zero, and it needs to be a special case. +# +# If all output grads are undefined, then it should be correct for the +# backward function to return undefined input grads. Since we use the chain +# rule, output grads equal to zero should result in input grads equal to zero, +# unless there is some rare special case. +# +# If a subset of output grads is undefined, then it may be acceptable for +# the backward function to return undefined input grads--it depends on the +# specific function, so you'll have to determine that yourself. If returning +# an undefined Tensor is correct for a given input grad, it is also logically +# correct to return a defined grad full of zeros, but that would not be +# preferable since it would be less efficient. +# +# NB: The parameter names here MUST be consistent with the parameter names +# in native_functions.yaml +- name: abs(Tensor self) -> Tensor + self: grad * self.sgn() + result: handle_r_to_c(result.scalar_type(), self_t.conj() * self_p.sgn()) + +- name: acos(Tensor self) -> Tensor + self: grad * -((-self * self + 1).rsqrt()).conj() + result: auto_element_wise + +- name: add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor + self: handle_r_to_c(self.scalar_type(), grad) + other: handle_r_to_c(other.scalar_type(), maybe_multiply(grad, alpha.conj())) + result: self_t + maybe_multiply(other_t, alpha) + +- name: add.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor + self: handle_r_to_c(self.scalar_type(), grad) + result: self_t.clone() + +- name: addbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + self: maybe_multiply(grad, beta.conj()) + batch1: maybe_multiply(grad.unsqueeze(0).expand_symint({ batch1.sym_size(0), batch1.sym_size(1), batch2.sym_size(2) }).bmm(batch2.transpose(1, 2).conj()), alpha.conj()) + batch2: maybe_multiply(batch1.transpose(1, 2).conj().bmm(grad.unsqueeze(0).expand_symint({ batch1.sym_size(0), batch1.sym_size(1), batch2.sym_size(2) })), alpha.conj()) + result: maybe_multiply(self_t, beta) + maybe_multiply(batch1_t.bmm(batch2_p).sum(0), alpha) + maybe_multiply(batch1_p.bmm(batch2_t).sum(0), alpha) + +- name: addcdiv(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor + self: handle_r_to_c(self.scalar_type(), grad) + tensor1: handle_r_to_c(tensor1.scalar_type(), grad * (value / tensor2).conj()) + tensor2: handle_r_to_c(tensor2.scalar_type(), -grad * (value * tensor1 / (tensor2 * tensor2)).conj()) + result: self_t + maybe_multiply(tensor1_t / tensor2_p, value) - maybe_multiply(tensor2_t * (tensor1_p / tensor2_p) / tensor2_p, value) + +- name: addcmul(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor + self: handle_r_to_c(self.scalar_type(), grad) + tensor1: handle_r_to_c(tensor1.scalar_type(), grad * (tensor2 * value).conj()) + tensor2: handle_r_to_c(tensor2.scalar_type(), grad * (tensor1 * value).conj()) + result: self_t + maybe_multiply(tensor1_t * tensor2_p, value) + maybe_multiply(tensor2_t * tensor1_p, value) + +- name: addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + self: maybe_multiply(grad, beta.conj()) + mat1: mm_mat1_backward(grad, mat2, mat1.sym_sizes(), mat1.sym_strides(), mat1.layout(), alpha) + mat2: mm_mat2_backward(grad, mat1, mat2.sym_sizes(), mat2.sym_strides(), mat2.layout(), alpha) + result: maybe_multiply(self_t, beta) + maybe_multiply(mat1_t.mm(mat2_p), alpha) + maybe_multiply(mat1_p.mm(mat2_t), alpha) + +- name: _sparse_addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + self: maybe_multiply(grad, beta) + mat1: mm_mat1_sparse_backward(grad, mat1, mat2, alpha) + mat2: mm_mat2_backward(grad, mat1, mat2.sym_sizes(), mat2.sym_strides(), mat2.layout(), alpha) + +- name: addmv(Tensor self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1) -> Tensor + self: maybe_multiply(grad, beta.conj()) + mat: maybe_multiply(grad.ger(vec.conj()), alpha.conj()) + vec: maybe_multiply(mat.t().conj().mv(grad), alpha.conj()) + result: maybe_multiply(self_t, beta) + maybe_multiply(mat_t.mv(vec_p), alpha) + maybe_multiply(mat_p.mv(vec_t), alpha) + +- name: addr(Tensor self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + self: maybe_multiply(grad, beta.conj()) + vec1: maybe_multiply(grad.mv(vec2.conj()), alpha.conj()) + vec2: maybe_multiply(grad.t().mv(vec1.conj()), alpha.conj()) + result: maybe_multiply(self_t, beta) + maybe_multiply(vec1_t.outer(vec2_p), alpha) + maybe_multiply(vec1_p.outer(vec2_t), alpha) + +- name: affine_grid_generator(Tensor theta, SymInt[] size, bool align_corners) -> Tensor + theta: affine_grid_generator_backward_symint(grad, size, align_corners) + result: auto_linear + +- name: alias(Tensor(a) self) -> Tensor(a) + self: grad + result: self_t + +- name: angle(Tensor self) -> Tensor + self: angle_backward(grad, self) + result: handle_r_to_c(result.scalar_type(), angle_backward(self_t.conj(), self_p).conj()) + +# The four items below are necessary because TensorIterator doesn't work on +# Variables (codegen does not unwrap the input Tensor for all() and any() ). +- name: any(Tensor self) -> Tensor + output_differentiability: [False] + +- name: any.dim(Tensor self, int dim, bool keepdim=False) -> Tensor + output_differentiability: [False] + +- name: any.dims(Tensor self, int[]? dim=None, bool keepdim=False) -> Tensor + output_differentiability: [False] + +- name: _is_all_true(Tensor self) -> Tensor + self: non_differentiable + +- name: _is_any_true(Tensor self) -> Tensor + self: non_differentiable + +- name: all(Tensor self) -> Tensor + output_differentiability: [False] + +- name: all.dim(Tensor self, int dim, bool keepdim=False) -> Tensor + output_differentiability: [False] + +- name: all.dims(Tensor self, int[]? dim=None, bool keepdim=False) -> Tensor + output_differentiability: [False] + +- name: acosh(Tensor self) -> Tensor +# Save one rsqrt in the real case by using that for x real and positive sqrt(x*y) = sqrt(x)*sqrt(y) (not true in the complex case) + self: "self.is_complex() ? grad * ((self + 1).rsqrt() * (self - 1).rsqrt()).conj() : grad * (self * self - 1).rsqrt()" + result: auto_element_wise + +- name: acosh_(Tensor(a!) self) -> Tensor(a!) + self: not_implemented("inplace version of acosh") + +- name: asinh(Tensor self) -> Tensor + self: grad * (self.pow(2) + 1).rsqrt().conj() + result: auto_element_wise + +- name: asinh_(Tensor(a!) self) -> Tensor(a!) + self: not_implemented("inplace version of asinh") + +- name: atanh(Tensor self) -> Tensor + self: grad * 1 / (1 - self.pow(2)).conj() + result: auto_element_wise + +- name: atanh_(Tensor(a!) self) -> Tensor(a!) + self: not_implemented("inplace version of atanh") + +- name: as_strided(Tensor(a) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a) + self: as_strided_backward(grad, TensorGeometry(self), size, stride, storage_offset) + result: auto_linear + +- name: as_strided_(Tensor(a!) self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor(a!) + self: as_strided_backward(grad, TensorGeometry(self), size, stride, storage_offset) + result: auto_linear + +- name: asin(Tensor self) -> Tensor + self: grad * (-self * self + 1).rsqrt().conj() + result: auto_element_wise + +- name: atan(Tensor self) -> Tensor + self: grad / (self * self + 1).conj() + result: auto_element_wise + +- name: atan2(Tensor self, Tensor other) -> Tensor + self, other: atan2_backward(grad, self, other, grad_input_mask) + result: (-self_p * other_t + other_p * self_t) / (self_p.pow(2) + other_p.pow(2)) + +- name: baddbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + self: maybe_multiply(grad, beta.conj()) + batch1: maybe_multiply(grad.bmm(batch2.transpose(1, 2).conj()), alpha.conj()) + batch2: maybe_multiply(batch1.transpose(1, 2).conj().bmm(grad), alpha.conj()) + result: maybe_multiply(self_t, beta) + maybe_multiply(batch1_t.bmm(batch2_p), alpha) + maybe_multiply(batch1_p.bmm(batch2_t), alpha) + +- name: bernoulli(Tensor self, *, Generator? generator=None) -> Tensor + self: zeros_like(grad) + result: auto_element_wise + +- name: bernoulli_.Tensor(Tensor(a!) self, Tensor p, *, Generator? generator=None) -> Tensor(a!) + self: zeros_like(grad) + p: zeros_like(p) + result: self_t.zero_() + +- name: bernoulli_.float(Tensor(a!) self, float p=0.5, *, Generator? generator=None) -> Tensor(a!) + self: zeros_like(grad) + result: self_t.zero_() + +- name: bmm(Tensor self, Tensor mat2) -> Tensor + self: grad.bmm(mat2.transpose(1, 2).conj()) + mat2: self.transpose(1, 2).conj().bmm(grad) + result: self_t.bmm(mat2_p) + self_p.bmm(mat2_t) + +- name: matmul(Tensor self, Tensor other) -> Tensor + self, other: matmul_backward(grad, self, other, grad_input_mask) + +- name: cat(Tensor[] tensors, int dim=0) -> Tensor + tensors: cat_tensors_backward(grad, to_args_sizes_symint(tensors), to_args_scalartypes(tensors), dim) + result: cat_jvp(tensors, dim) + +- name: cauchy_(Tensor(a!) self, float median=0, float sigma=1, *, Generator? generator=None) -> Tensor(a!) + self: zeros_like(grad) + result: self_t.zero_() + +- name: ceil(Tensor self) -> Tensor + self: zeros_like(grad) + result: auto_element_wise + +- name: chunk(Tensor(a -> *) self, int chunks, int dim=0) -> Tensor(a)[] + dispatch: + Default: + # the default case will use the CompositeImplicitAutograd + self: not_implemented("chunk") + AutogradNestedTensor: + self: chunk_backward_nested(grads, self, chunks, dim) + +- name: linalg_cholesky_ex(Tensor self, *, bool upper=False, bool check_errors=False) -> (Tensor L, Tensor info) + self: cholesky_backward(grad, upper, L) + L: cholesky_jvp(self_t, L, upper) + +- name: cholesky_solve(Tensor self, Tensor input2, bool upper=False) -> Tensor + self, input2: cholesky_solve_backward(grad, self, input2, result, upper, grad_input_mask) + result: cholesky_solve_jvp(result, input2_p, input2_t, self_t, upper) + +- name: cholesky_inverse(Tensor self, bool upper=False) -> Tensor + self: cholesky_inverse_backward(grad, self, upper, result) + result: cholesky_inverse_jvp(self_p, self_t, result, upper) + +# Tensor-bound clamp treats its differentiable Tensor arguments jointly, so +# ordinary boundary ties split the gradient evenly between the Tensor inputs. +- name: clamp.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor + self: clamp_backward(grad, self, min, max) + min, max: clamp_backward_min_max(grad, self, min, max, grad_input_mask) + result: clamp_jvp(self_p, self_t, min_p, min_t, max_p, max_t) + +- name: clamp(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor + self: clamp_backward(grad, self, min, max) + result: auto_element_wise + +- name: clamp_min(Tensor self, Scalar min) -> Tensor + self: where(self > min, grad, at::scalar_tensor(0., grad.options())) + result: auto_element_wise + +- name: clamp_min.Tensor(Tensor self, Tensor min) -> Tensor + # Split ties first, then reuse the where output when transforms and tensor subclasses allow safe in-place masking. + self: masked_fill_inplace_if_safe(at::where(self == min, grad / 2, grad), self < min, 0) + min: masked_fill_inplace_if_safe(at::where(self == min, grad / 2, grad), self > min, 0) + # masked_fill_ cannot select the Tensor-valued min_t; use where to keep the JVP differentiable for higher-order AD. + result: at::where(self_p == min_p, (self_t + min_t) / 2, at::where(self_p > min_p, self_t, min_t)) + +- name: clamp_max(Tensor self, Scalar max) -> Tensor + self: where(self < max, grad, at::scalar_tensor(0., grad.options())) + result: auto_element_wise + +- name: clamp_max.Tensor(Tensor self, Tensor max) -> Tensor + # Split ties first, then reuse the where output when transforms and tensor subclasses allow safe in-place masking. + self: masked_fill_inplace_if_safe(at::where(self == max, grad / 2, grad), self > max, 0) + max: masked_fill_inplace_if_safe(at::where(self == max, grad / 2, grad), self < max, 0) + # masked_fill_ cannot select the Tensor-valued max_t; use where to keep the JVP differentiable for higher-order AD. + result: at::where(self_p == max_p, (self_t + max_t) / 2, at::where(self_p < max_p, self_t, max_t)) + +- name: clone(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor + self: grad + result: auto_linear + +- name: _lazy_clone(Tensor self) -> Tensor + self: grad + result: auto_linear + +- name: _to_copy(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, MemoryFormat? memory_format=None) -> Tensor + self: _to_copy_backward(grad, self.options()) + result: _to_copy(self_t, dtype, layout, device, pin_memory, non_blocking, memory_format) + # The condition is: if dtype is not nullopt, then isDifferentiableType(*dtype) + # (If dtype IS nullopt, we rely on the regular check that any input requires grad). + output_differentiability: ["!dtype || isDifferentiableType(*dtype)"] + +- name: _coalesce(Tensor self) -> Tensor + self: grad + +- name: complex(Tensor real, Tensor imag) -> Tensor + real: at::real(grad) + imag: at::imag(grad) + result: at::complex(real_t, imag_t) + +- name: polar(Tensor abs, Tensor angle) -> Tensor + abs, angle: polar_backward(grad, result) + result: at::complex(abs_t*angle_p.cos() - angle_t*abs_p*angle_p.sin(), abs_t*angle_p.sin() + angle_t*abs_p*angle_p.cos()) + +- name: _conj(Tensor(a) self) -> Tensor(a) + self: grad.conj() + result: self_t.conj() + +- name: _neg_view(Tensor(a) self) -> Tensor(a) + self: grad.neg() + result: self_t._neg_view() + +- name: _conj_physical(Tensor self) -> Tensor + self: grad.conj_physical() + result: self_t.conj_physical() + +- name: conj_physical_(Tensor(a!) self) -> Tensor(a!) + self: grad.conj_physical() + result: self_t.conj_physical_() + +- name: copysign.Tensor(Tensor self, Tensor other) -> Tensor + self: copysign_tensor_self_backward(grad, self, result) + other: zeros_like(other) + result: copysign_tensor_self_backward(self_t, self_p, result) + +- name: copysign.Scalar(Tensor self, Scalar other) -> Tensor + self: copysign_tensor_self_backward(grad, self, result) + result: auto_element_wise + +- name: cos(Tensor self) -> Tensor + self: grad * -self.sin().conj() + result: auto_element_wise + +- name: cosh(Tensor self) -> Tensor + self: grad * self.sinh().conj() + result: auto_element_wise + +- name: count_nonzero.dim_IntList(Tensor self, int[] dim) -> Tensor + output_differentiability: [False] + +- name: count_nonzero(Tensor self, int? dim=None) -> Tensor + output_differentiability: [False] + +- name: linalg_cross(Tensor self, Tensor other, *, int dim=-1) -> Tensor + self: at::linalg_cross(other.conj(), grad, dim) + other: at::linalg_cross(grad, self.conj(), dim) + result: "at::linalg_cross(self_t, other_p, dim) + at::linalg_cross(self_p, other_t, dim)" + +- name: logcumsumexp(Tensor self, int dim) -> Tensor + self: logcumsumexp_backward(grad, self, result, dim) + result: logcumsumexp_jvp(self_p, self_t, dim) + +- name: cumprod(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor + self: cumprod_backward(grad.to(self.scalar_type()), self, dim, result) + result: "cumprod_jvp(self_t, self_p, result, dim).to(dtype.has_value() ? *dtype : self_p.scalar_type())" + +- name: cumsum(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor + self: cumsum_backward(grad.to(self.scalar_type()), dim) + result: auto_linear + +- name: cummax(Tensor self, int dim) -> (Tensor values, Tensor indices) + self: cummaxmin_backward(grad, self, indices, dim) + values: self_t.gather(dim, indices) + +- name: cummin(Tensor self, int dim) -> (Tensor values, Tensor indices) + self: cummaxmin_backward(grad, self, indices, dim) + values: self_t.gather(dim, indices) + +- name: conv_tbc(Tensor self, Tensor weight, Tensor bias, int pad=0) -> Tensor + self, weight, bias: "grad.defined() ? conv_tbc_backward(grad, self, weight, bias, pad) : std::tuple()" + +- name: _ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank=0, bool zero_infinity=False) -> (Tensor, Tensor) + log_probs: _ctc_loss_backward(grad, log_probs, targets, input_lengths, target_lengths, result0, result1, blank, zero_infinity) + +- name: _ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank=0, bool zero_infinity=False) -> (Tensor, Tensor) + log_probs: _ctc_loss_backward(grad, log_probs, targets, input_lengths, target_lengths, result0, result1, blank, zero_infinity) + +- name: deg2rad(Tensor self) -> Tensor + self: deg2rad_backward(grad) + result: auto_element_wise + +- name: _linalg_det(Tensor A) -> (Tensor result, Tensor LU, Tensor pivots) + A: linalg_det_backward(grad, result, A, LU, pivots) + result: linalg_det_jvp(A_t, result, LU, pivots, A_p.is_contiguous() && !A_p.is_complex()) + output_differentiability: [True, False, False] + +- name: _linalg_slogdet(Tensor A) -> (Tensor sign, Tensor logabsdet, Tensor LU, Tensor pivots) + A: slogdet_backward(grad_sign, grad_logabsdet, A, sign, LU, pivots) + sign, logabsdet: slogdet_jvp(LU, pivots, A_t, sign, A_p.is_contiguous() && !A_p.is_complex()) + output_differentiability: [True, True, False, False] + +- name: block_diag(Tensor[] tensors) -> Tensor + tensors: block_diag_backward(grad, to_args_sizes(tensors), to_args_scalartypes(tensors)) + result: block_diag_jvp(tensors) + +- name: diag_embed(Tensor self, int offset=0, int dim1=-2, int dim2=-1) -> Tensor + self: grad.diagonal(offset, dim1, dim2) + result: auto_linear + +- name: diagonal(Tensor(a) self, int offset=0, int dim1=0, int dim2=1) -> Tensor(a) + self: diagonal_backward_symint(grad, self.sym_sizes(), offset, dim1, dim2) + result: auto_linear + +- name: diagonal_backward(Tensor grad_output, SymInt[] input_sizes, int offset, int dim1, int dim2) -> Tensor + grad_output: grad.diagonal(offset, dim1, dim2) + result: auto_linear + +- name: dist(Tensor self, Tensor other, Scalar p=2) -> Tensor + self: norm_backward(grad, self - other, p, result) + other: -norm_backward(grad, self - other, p, result) + result: norm_jvp(self_p - other_p, self_t - other_t, p, result, {}, false) + +# The backward formula is done in this order to improve numerical stability +# of the higher order derivatives, see https://github.com/pytorch/pytorch/issues/43414 +# Note that we don't use "result" because saving it would be BC-breaking when it is used in an inplace operation later +- name: div.Tensor(Tensor self, Tensor other) -> Tensor + self: div_tensor_self_backward(grad, other, self.scalar_type()) + other: div_tensor_other_backward(grad, self, other) + result: (self_t - other_t * result) / other_p + +- name: div.Scalar(Tensor self, Scalar other) -> Tensor + self: div_tensor_self_backward(grad, other, self.scalar_type()) + result: self_t / other + +- name: div.Tensor_mode(Tensor self, Tensor other, *, str? rounding_mode) -> Tensor + self: div_tensor_self_backward(grad, other, self.scalar_type(), rounding_mode) + other: div_tensor_other_backward(grad, self, other, rounding_mode) + result: "rounding_mode.has_value() ? result.new_zeros_symint(result.sym_sizes()) : self_t / other_p - other_t * (self_p / other_p) / other_p" + +- name: div.Scalar_mode(Tensor self, Scalar other, *, str? rounding_mode) -> Tensor + self: div_tensor_self_backward(grad, other, self.scalar_type(), rounding_mode) + result: "rounding_mode.has_value() ? result.new_zeros_symint(result.sym_sizes()) : self_t / other" + +- name: dot(Tensor self, Tensor tensor) -> Tensor + self: grad * tensor.conj() + tensor: grad * self.conj() + result: at::dot(self_t, tensor_p) + at::dot(self_p, tensor_t) + +- name: vdot(Tensor self, Tensor other) -> Tensor + self: grad.conj() * other + other: grad * self + result: at::vdot(self_t, other_p) + at::vdot(self_p, other_t) + +- name: _fused_dropout(Tensor self, float p, Generator? generator=None) -> (Tensor, Tensor) + self: _fused_dropout_backward(grad, result1, p) + +- name: native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor) + input: "GradMode::is_enabled() ? infinitely_differentiable_native_dropout_backward(grad, result1, (!train.has_value() || !train.value() ? 1 : (p == 1 ? 0.0 : 1.0 / (1.0 - p)))) : native_dropout_backward(grad, result1, (!train.has_value() || !train.value() ? 1 : (p == 1 ? 0.0 : 1.0 / (1.0 - p))))" + result0: "(!train.has_value() || train.value()) ? (p == 1 ? 0.0 : 1.0 / (1.0 - p)) * input_t * result1 : input_t" + +- name: native_dropout_backward(Tensor grad_output, Tensor mask, float scale) -> Tensor + grad_output: "native_dropout_double_backward(grad, grad_output, mask, scale)" + mask: 'not_implemented("native_dropout_backward: mask")' + +- name: eq_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + self: zeros_like(self) + result: self_t.zero_() + +- name: eq_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + self: zeros_like(self) + other: zeros_like(other) + result: self_t.zero_() + +- name: erf(Tensor self) -> Tensor + self: M_2_SQRTPI * exp(-(self.pow(2))) * grad + result: auto_element_wise + +- name: erfc(Tensor self) -> Tensor + self: -M_2_SQRTPI * exp(-(self.pow(2))) * grad + result: auto_element_wise + +- name: special_erfcx(Tensor self) -> Tensor + self: (2.0 * self * result - M_2_SQRTPI) * grad + result: auto_element_wise + +- name: erfinv(Tensor self) -> Tensor + self: (M_PI_4 * M_2_SQRTPI) * exp(self.erfinv().pow(2)) * grad + result: auto_element_wise + +- name: exp(Tensor self) -> Tensor + self: grad * result.conj() + result: auto_element_wise + +- name: exp2(Tensor self) -> Tensor + self: grad * result.conj() * M_LN2 + result: auto_element_wise + +- name: expm1(Tensor self) -> Tensor + self: grad * (result.conj() + 1) + result: auto_element_wise + +# TODO: this derivative is not SymInt safe, need sum_to support +- name: expand(Tensor(a) self, SymInt[] size, *, bool implicit=False) -> Tensor(a) + self: at::sum_to(grad, self.sym_sizes()) + result: auto_linear + +- name: exponential_(Tensor(a!) self, float lambd=1, *, Generator? generator=None) -> Tensor(a!) + self: zeros_like(grad) + result: self_t.zero_() + +- name: fake_quantize_per_tensor_affine_cachemask(Tensor self, float scale, int zero_point, int quant_min, int quant_max) -> (Tensor output, Tensor mask) + self: fake_quantize_per_tensor_affine_cachemask_backward(grad, mask) + +- name: _fake_quantize_per_tensor_affine_cachemask_tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, Tensor fake_quant_enabled, int quant_min, int quant_max) -> (Tensor output, Tensor mask) + self: fake_quantize_per_tensor_affine_cachemask_backward(grad, mask) + +- name: _fake_quantize_learnable_per_tensor_affine(Tensor self, Tensor scale, Tensor zero_point, int quant_min, int quant_max, float grad_factor=1.0) -> Tensor + self, scale, zero_point: "grad.defined() ? _fake_quantize_learnable_per_tensor_affine_backward(grad, self, scale, zero_point, quant_min, quant_max, grad_factor) : std::tuple()" + +- name: fake_quantize_per_channel_affine_cachemask(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max) -> (Tensor output, Tensor mask) + self: fake_quantize_per_channel_affine_cachemask_backward(grad, mask) + +- name: _fake_quantize_learnable_per_channel_affine(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max, float grad_factor=1.0) -> Tensor + self, scale, zero_point: "grad.defined() ? _fake_quantize_learnable_per_channel_affine_backward(grad, self, scale, zero_point, axis, quant_min, quant_max, grad_factor) : std::tuple()" + +- name: _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask) + self: fake_quantize_per_tensor_affine_cachemask_backward(grad, mask) + +- name: fill.Scalar(Tensor self, Scalar value) -> Tensor + self: zeros_like(grad) + result: at::fill(self_t, 0) + +- name: fill.Tensor(Tensor self, Tensor value) -> Tensor + self: zeros_like(grad) + value: grad.sum() + result: at::fill(self_t, value_t) + +- name: fill_.Scalar(Tensor(a!) self, Scalar value) -> Tensor(a!) + self: zeros_like(grad) + result: self_t.fill_(0) + +- name: fill_.Tensor(Tensor(a!) self, Tensor value) -> Tensor(a!) + self: zeros_like(grad) + value: grad.sum() + result: self_t.fill_(value_t) + +- name: floor(Tensor self) -> Tensor + self: zeros_like(grad) + result: auto_element_wise + +- name: fmod.Scalar(Tensor self, Scalar other) -> Tensor + self: grad + result: auto_element_wise + +- name: fmod.Tensor(Tensor self, Tensor other) -> Tensor + self: grad + other: -grad * self.div(other, /*rounding_mode=*/"trunc") + result: self_t - other_t * self_p.div(other_p, /*rounding_mode=*/"trunc") + +- name: frac(Tensor self) -> Tensor + self: grad + result: self_t + +- name: frexp.Tensor(Tensor self) -> (Tensor mantissa, Tensor exponent) + self: grad / exponent.exp2() + mantissa: self_t / exponent.exp2() + +- name: gather(Tensor self, int dim, Tensor index, *, bool sparse_grad=False) -> Tensor + self: gather_backward(grad, self, dim, index, sparse_grad) + index: non_differentiable + result: auto_linear + +- name: ge_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + self: zeros_like(self) + result: self_t.zero_() + +- name: ge_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + self: zeros_like(self) + other: zeros_like(other) + result: self_t.zero_() + +- name: geometric_(Tensor(a!) self, float p, *, Generator? generator=None) -> Tensor(a!) + self: zeros_like(grad) + result: self_t.zero_() + +- name: geqrf(Tensor self) -> (Tensor a, Tensor tau) + self: not_implemented("geqrf") + +- name: indices(Tensor(a) self) -> Tensor(a) + output_differentiability: [False] + +- name: _indices(Tensor(a) self) -> Tensor(a) + output_differentiability: [False] + +- name: crow_indices(Tensor(a) self) -> Tensor(a) + output_differentiability: [False] + +- name: col_indices(Tensor(a) self) -> Tensor(a) + output_differentiability: [False] + +- name: ccol_indices(Tensor(a) self) -> Tensor(a) + output_differentiability: [False] + +- name: row_indices(Tensor(a) self) -> Tensor(a) + output_differentiability: [False] + +- name: grid_sampler_2d(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor + input, grid: "grad.defined() ? grid_sampler_2d_backward(grad, input, grid, interpolation_mode, padding_mode, align_corners, grad_input_mask) : std::tuple()" + +- name: grid_sampler_2d_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, bool[2] output_mask) -> (Tensor, Tensor) + grad_output, input, grid: grid_sampler_2d_double_backward(grads[0], grads[1], grad_output, input, grid, interpolation_mode, padding_mode, align_corners, grad_input_mask) + +- name: grid_sampler_3d(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor + input, grid: "grad.defined() ? grid_sampler_3d_backward(grad, input, grid, interpolation_mode, padding_mode, align_corners, grad_input_mask) : std::tuple()" + +- name: grid_sampler_3d_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, bool[2] output_mask) -> (Tensor, Tensor) + grad_output, input, grid: grid_sampler_3d_double_backward(grads[0], grads[1], grad_output, input, grid, interpolation_mode, padding_mode, align_corners, grad_input_mask) + +# See NOTE [ grid_sample CPU fallback ] +- name: _grid_sampler_2d_cpu_fallback(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor + input, grid: "grad.defined() ? _grid_sampler_2d_cpu_fallback_backward(grad, input, grid, interpolation_mode, padding_mode, align_corners) : std::tuple()" + +- name: _grid_sampler_2d_cpu_fallback_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> (Tensor, Tensor) + grad_output, input, grid: grid_sampler_2d_double_backward(grads[0], grads[1], grad_output, input, grid, interpolation_mode, padding_mode, align_corners, grad_input_mask) + +- name: gt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + self: zeros_like(self) + result: self_t.zero_() + +- name: gt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + self: zeros_like(self) + other: zeros_like(other) + result: self_t.zero_() + +- name: hardsigmoid(Tensor self) -> Tensor + self: hardsigmoid_backward(grad, self) + result: auto_element_wise + +- name: histc(Tensor self, int bins=100, Scalar min=0, Scalar max=0) -> Tensor + output_differentiability: [False] + +- name: hardswish(Tensor self) -> Tensor + self: hardswish_backward(grad, self) + result: auto_element_wise + +- name: hardswish_backward(Tensor grad_output, Tensor self) -> Tensor + grad_output: hardswish_backward(grad, self) + self: at::where(at::logical_and(-3.0 < self, self < 3.0), grad * grad_output / 3.0, at::zeros({}, self.options())) + result: "hardswish_backward(grad_output_t, self_p) + + at::where(at::logical_and(-3.0 < self_p, self_p < 3.0), self_t * grad_output_p / 3.0, at::zeros({}, self_p.options()))" + +- name: hypot(Tensor self, Tensor other) -> Tensor + self: grad * self / result + other: grad * other / result + result: self_t * self_p / result + other_t * other_p / result + +- name: i0(Tensor self) -> Tensor + self: grad * at::special_i1(self) + result: auto_element_wise + +- name: special_i0e(Tensor self) -> Tensor + self: grad * (at::special_i1e(self) - self.sgn() * result) + result: auto_element_wise + +- name: special_i1(Tensor self) -> Tensor + self: i1_backward(grad, self, result) + result: auto_element_wise + +- name: special_i1e(Tensor self) -> Tensor + self: i1e_backward(grad, self, result) + result: auto_element_wise + +- name: igamma(Tensor self, Tensor other) -> Tensor + self: 'not_implemented("igamma: input")' + other: grad * exp((self - 1) * log(other) - other - lgamma(self)) + +- name: igammac(Tensor self, Tensor other) -> Tensor + self: 'not_implemented("igammac: input")' + other: -grad * exp((self - 1) * log(other) - other - lgamma(self)) + +- name: index.Tensor(Tensor self, Tensor?[] indices) -> Tensor + self: index_backward(grad.new_zeros_symint(self.sym_sizes(), self.options()), indices, grad) + result: auto_linear + +- name: _unsafe_index.Tensor(Tensor self, Tensor?[] indices) -> Tensor + self: at::_unsafe_index_put(grad.new_zeros_symint(self.sym_sizes(), self.options()), indices, grad, true) + result: auto_linear + +- name: _unsafe_masked_index(Tensor self, Tensor mask, Tensor?[] indices, Scalar fill) -> Tensor + self: at::_unsafe_masked_index_put_accumulate(grad.new_zeros_symint(self.sym_sizes(), self.options()), mask, indices, grad) + mask: non_differentiable + result: _unsafe_masked_index(self_t, mask, indices, 0) + +- name: _unsafe_masked_index_put_accumulate(Tensor self, Tensor mask, Tensor?[] indices, Tensor values) -> Tensor + self: grad + mask: non_differentiable + values: at::_unsafe_masked_index(grad, mask, indices, 0) + result: at::_unsafe_masked_index_put_accumulate(self_t, mask, indices, values_t) + +- name: index_add(Tensor self, int dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor + self: grad + # The case source.dim() == 0 is necessary to support scalar tensors of the form + # source.dim() == 0 and index.dim() == 1 and index.size() == (1,), + # This is because source is not broadcastable to index, as source.dim() < index.dim() + source: "maybe_multiply(source.dim() > 0 ? grad.index_select(dim, index).expand_as(source) : grad.index_select(dim, index.squeeze(0)), alpha)" + index: non_differentiable + result: at::index_add(self_t, dim, index, maybe_multiply(source_t, alpha)) + +- name: index_reduce(Tensor self, int dim, Tensor index, Tensor source, str reduce, *, bool include_self=True) -> Tensor + self, source: index_reduce_backward(grad, self, dim, index, source, reduce, include_self, result) + index: non_differentiable + +- name: index_copy(Tensor self, int dim, Tensor index, Tensor source) -> Tensor + self: grad.index_fill(dim, index, 0) + # The case source.dim() == 0 is necessary to support scalar tensors of the form + # source.dim() == 0 and index.dim() == 1 and index.size() == (1,), + # This is because source is not broadcastable to index, as source.dim() < index.dim() + source: "source.dim() > 0 ? grad.index_select(dim, index).expand_as(source) : grad.index_select(dim, index.squeeze(0))" + index: non_differentiable + result: self_t.index_copy(dim, index, source_t) + +- name: index_fill.int_Scalar(Tensor self, int dim, Tensor index, Scalar value) -> Tensor + self: grad.index_fill(dim, index, 0) + index: non_differentiable + result: self_t.index_fill(dim, index, 0) + +- name: index_fill.int_Tensor(Tensor self, int dim, Tensor index, Tensor value) -> Tensor + self: grad.index_fill(dim, index, 0) + value: grad.index_select(dim, std::get<0>(at::_unique(index, /*sorted=*/false))).sum() + index: non_differentiable + result: self_t.index_fill(dim, index, value_t) + +- name: index_put(Tensor self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor + self: "accumulate ? grad : grad.index_put(indices, zeros_like(values), false)" + values: grad.index(indices) + result: self_t.index_put(indices, values_t, accumulate) + +- name: _unsafe_index_put(Tensor self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor + self: "accumulate ? grad : at::_unsafe_index_put(grad, indices, zeros_like(values), false)" + values: at::_unsafe_index(grad, indices) + result: at::_unsafe_index_put(self_t, indices, values_t, accumulate) + +- name: _index_put_impl_(Tensor(a!) self, Tensor?[] indices, Tensor values, bool accumulate=False, bool unsafe=False) -> Tensor(a!) + self: "accumulate ? grad : grad.index_put(indices, zeros_like(values), false)" + values: grad.index(indices) + result: at::_index_put_impl_(self_t, indices, values_t, accumulate, unsafe) + +- name: index_select(Tensor self, int dim, Tensor index) -> Tensor + self: index_select_backward_symint(grad, self.sym_sizes(), dim, index) + index: non_differentiable + result: auto_linear + +- name: linalg_inv_ex(Tensor A, *, bool check_errors=False) -> (Tensor inverse, Tensor info) + A: -at::matmul(inverse.mH(), at::matmul(grad, inverse.mH())) + inverse: -at::matmul(at::matmul(inverse, A_t), inverse) + output_differentiability: [True, False] + +- name: linalg_pinv.atol_rtol_tensor(Tensor self, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False) -> Tensor + self: pinv_backward(grad, result, self) + result: pinv_jvp(self_p, result, self_t) + +- name: isnan(Tensor self) -> Tensor + self: non_differentiable + +- name: kthvalue(Tensor self, SymInt k, int dim=-1, bool keepdim=False) -> (Tensor values, Tensor indices) + self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), keepdim) + values: gather_with_keepdimed_indices(self_t, dim, indices, keepdim) + +- name: ldexp.Tensor(Tensor self, Tensor other) -> Tensor + self: grad * at::pow(2.0, other).conj() + other: grad * result.conj() * M_LN2 + result: self_t * at::pow(2.0, other_p) + other_t * result * M_LN2 + +- name: le_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + self: zeros_like(self) + result: self_t.zero_() + +- name: le_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + self: zeros_like(self) + other: zeros_like(other) + result: self_t.zero_() + +- name: lerp.Scalar(Tensor self, Tensor end, Scalar weight) -> Tensor + self: "weight.isComplex() ? grad * (1 - weight.conj().toComplexDouble()) : grad * (1 - weight.toDouble())" + end: grad * weight.conj() + result: at::lerp(self_t, end_t, weight) + +- name: lerp.Tensor(Tensor self, Tensor end, Tensor weight) -> Tensor + self: grad * (1 - weight).conj() + end: grad * weight.conj() + weight: grad * (end - self).conj() + result: at::lerp(self_t, end_t, weight_p) + weight_t * (end_p - self_p) + +- name: lgamma(Tensor self) -> Tensor + self: grad * digamma(self) + result: auto_element_wise + +- name: digamma(Tensor self) -> Tensor + self: grad * polygamma(1, self) + result: auto_element_wise + +- name: polygamma(int n, Tensor self) -> Tensor + self: grad * polygamma(n + 1, self) + result: auto_element_wise + +- name: polygamma_(Tensor(a!) self, int n) -> Tensor(a!) + self: grad * polygamma(n + 1, self) + result: self_t.mul_(polygamma(n + 1, original_self_p)) + +- name: log(Tensor self) -> Tensor + self: grad.div(self.conj()) + result: auto_element_wise + +- name: log10(Tensor self) -> Tensor + self: grad / (self.conj() * M_LN10) + result: auto_element_wise + +- name: log1p(Tensor self) -> Tensor + self: log1p_backward(grad, self) + result: auto_element_wise + +- name: log2(Tensor self) -> Tensor + self: grad / (self.conj() * M_LN2) + result: auto_element_wise + +- name: logaddexp(Tensor self, Tensor other) -> Tensor + self: grad / (1 + exp(other - self)).conj() + other: grad / (1 + exp(self - other)).conj() + result: self_t / (1 + exp(other_p - self_p)) + other_t / (1 + exp(self_p - other_p)) + +- name: logaddexp2(Tensor self, Tensor other) -> Tensor + self: grad / (1 + pow(2, other - self)) + other: grad / (1 + pow(2, self - other)) + result: self_t / (1 + pow(2, other_p - self_p)) + other_t / (1 + pow(2, self_p - other_p)) + +# Note [Gradient formula for xlogy at x = 0, y <= 0] +# x * log(y) is not defined at y <= 0, so we cannot even talk about differentiability +# Now, xlogy(0, y) = 0 by definition. +# This does not make it differentiable as it's not defined in a neighbourhood of a point +# (0, y) when y <= 0. +# Now, when a function is non-differentiable, sometimes we return "a relatively sensible value" +# In this case, as per the discussion in https://github.com/pytorch/pytorch/issues/80770, we choose +# this value to be zero, which is the directional derivative along the line {x = 0}. +- name: xlogy.Tensor(Tensor self, Tensor other) -> Tensor + self: at::xlogy(grad, other).masked_fill((self == 0.) & (other <= 0.), 0.) + other: grad * self / other + result: at::xlogy(self_t, other_p).masked_fill((self_p == 0.) & (other_p <= 0.), 0.) + other_t * self_p / other_p + +- name: xlogy.Scalar_Self(Scalar self, Tensor other) -> Tensor + other: grad * self / other + result: auto_element_wise + +- name: xlogy.Scalar_Other(Tensor self, Scalar other) -> Tensor + self: "other.toDouble() > 0. + ? at::xlogy(grad, other) + : at::xlogy(grad, other).masked_fill(self == 0., 0.)" + result: auto_element_wise + +# See Note [Gradient formula for xlogy at x = 0, y <= 0] +# Same here but with y <= -1 +- name: special_xlog1py(Tensor self, Tensor other) -> Tensor + self: at::special_xlog1py(grad, other).masked_fill((self == 0.) & (other <= -1.), 0.) + other: grad * self / (other + 1) + result: at::special_xlog1py(self_t, other_p).masked_fill((self_p == 0.) & (other_p <= -1.), 0.) + other_t * self_p / (other_p + 1) + +- name: special_xlog1py.self_scalar(Scalar self, Tensor other) -> Tensor + other: grad * self / (other + 1) + result: auto_element_wise + +- name: special_xlog1py.other_scalar(Tensor self, Scalar other) -> Tensor + self: "other.toDouble() > -1. + ? at::special_xlog1py(grad, other) + : at::special_xlog1py(grad, other).masked_fill(self == 0., 0.)" + result: auto_element_wise + +- name: special_zeta(Tensor self, Tensor other) -> Tensor + self: not_implemented("zeta") + other: grad * -self * special_zeta(self + 1., other) + +- name: special_zeta.self_scalar(Scalar self, Tensor other) -> Tensor + other: grad * -self * special_zeta(self.toDouble() + 1., other) + +- name: special_zeta.other_scalar(Tensor self, Scalar other) -> Tensor + self: not_implemented("zeta") + +- name: log_normal_(Tensor(a!) self, float mean=1, float std=2, *, Generator? generator=None) -> Tensor(a!) + self: zeros_like(grad) + result: self_t.zero_() + +- name: logsumexp(Tensor self, int[1] dim, bool keepdim=False) -> Tensor + self: logsumexp_backward(grad, self, result, dim, keepdim) + result: logsumexp_jvp(self_p, self_t, dim, keepdim) + +- name: linalg_lstsq(Tensor self, Tensor b, float? rcond=None, *, str? driver=None) -> (Tensor solution, Tensor residuals, Tensor rank, Tensor singular_values) + self, b: linalg_lstsq_backward(grads[0], grads[1], self, b, solution, grad_input_mask) + solution: linalg_lstsq_solution_jvp(self_p, b_p, self_t, b_t) + residuals: linalg_lstsq_residuals_jvp(self_p, b_p, self_t, b_t, solution, residuals) + output_differentiability: [True, True, False, False] + +- name: lt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + self: zeros_like(self) + result: self_t.zero_() + +- name: lt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + self: zeros_like(self) + other: zeros_like(other) + result: self_t.zero_() + +- name: linalg_lu_factor_ex(Tensor A, *, bool pivot=True, bool check_errors=False) -> (Tensor LU, Tensor pivots, Tensor info) + A: lu_factor_ex_backward(grad, LU, pivots, pivot) + LU: lu_factor_ex_jvp(A_t, LU, pivots, pivot) + output_differentiability: [True, False, False] + +- name: linalg_lu(Tensor A, *, bool pivot=True) -> (Tensor P, Tensor L, Tensor U) + A: linalg_lu_backward(grad_L, grad_U, P, L, U, pivot) + L: std::get<0>(linalg_lu_jvp(A_t, P, L, U, pivot)) + U: std::get<1>(linalg_lu_jvp(A_t, P, L, U, pivot)) + output_differentiability: [False, True, True] + +- name: linalg_lu_solve(Tensor LU, Tensor pivots, Tensor B, *, bool left=True, bool adjoint=False) -> Tensor + LU: linalg_lu_solve_LU(grad, LU, pivots, result, left, adjoint) + B: "at::linalg_lu_solve(LU, pivots, grad, left, !adjoint)" + result: linalg_lu_solve_jvp(result, LU_p, pivots, LU_t, B_t, left, adjoint) + +- name: lu_unpack(Tensor LU_data, Tensor LU_pivots, bool unpack_data=True, bool unpack_pivots=True) -> (Tensor P, Tensor L, Tensor U) + LU_data: lu_unpack_backward(grad_L, grad_U, LU_data.sym_size(-2), LU_data.sym_size(-1)) + LU_pivots: non_differentiable + L: "LU_data_t.sym_size(-2) >= LU_data_t.sym_size(-1) ? LU_data_t.tril_symint(-1) : LU_data_t.narrow_symint(-1, 0, LU_data_t.sym_size(-2)).tril_symint(-1)" + U: "LU_data_t.sym_size(-1) >= LU_data_t.sym_size(-2) ? LU_data_t.triu_symint() : LU_data_t.narrow_symint(-2, 0, LU_data_t.sym_size(-1)).triu_symint()" + output_differentiability: [False, True, True] + +- name: masked_fill.Scalar(Tensor self, Tensor mask, Scalar value) -> Tensor + self: grad.masked_fill(mask, 0) + mask: non_differentiable + result: self_t.masked_fill(mask, 0) + +- name: masked_fill.Tensor(Tensor self, Tensor mask, Tensor value) -> Tensor + self: grad.masked_fill(mask, 0) + value: masked_fill_backward(grad, mask) + mask: non_differentiable + result: self_t.masked_fill(mask, value_t) + +- name: masked_scatter(Tensor self, Tensor mask, Tensor source) -> Tensor + self: grad.masked_fill(mask, 0) + source: masked_scatter_backward_symint(grad, mask, source.sym_sizes()) + mask: non_differentiable + result: self_t.masked_scatter(mask, source_t) + +- name: masked_scatter_backward(Tensor grad_output, Tensor mask, SymInt[] sizes) -> Tensor + grad_output: zeros_like(grad_output).masked_scatter(mask, grad) + mask: non_differentiable + result: masked_scatter_backward(grad_output_t, mask, grad_output_t.sizes()) + +- name: masked_select(Tensor self, Tensor mask) -> Tensor + self: masked_select_backward(grad, self, mask) + mask: non_differentiable + result: auto_linear + +- name: linalg_matrix_exp(Tensor self) -> Tensor + self: linalg_matrix_exp_differential(self, grad, /*adjoint*/ true) + result: linalg_matrix_exp_differential(self_p, self_t, /*adjoint*/ false) + +- name: linalg_matrix_sqrth(Tensor self) -> Tensor + self: linalg_matrix_sqrth_differential(self, grad) + result: linalg_matrix_sqrth_differential(self_p, self_t) + +- name: linalg_polar(Tensor A) -> (Tensor U, Tensor H) + A: linalg_polar_backward(grad_U, grad_H, A, U, H) + U, H: linalg_polar_jvp(A_t, A_p, U, H) + +- name: max.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) + self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), keepdim) + values: gather_with_keepdimed_indices(self_t, dim, indices, keepdim) + +- name: max(Tensor self) -> Tensor + self: evenly_distribute_backward(grad, self, result) + result: evenly_read_jvp(self_t, self_p, result) + +- name: maximum(Tensor self, Tensor other) -> Tensor + # Reuse the tie-split output when transforms and tensor subclasses allow safe in-place masking. + self: masked_fill_inplace_if_safe(at::where(self == other, grad / 2, grad), self < other, 0) + other: masked_fill_inplace_if_safe(at::where(self == other, grad / 2, grad), self > other, 0) + # Do not blend tangents arithmetically: an inactive infinite tangent would produce 0 * inf = nan. + result: at::where(self_p == other_p, (self_t + other_t) / 2, at::where(self_p > other_p, self_t, other_t)) + +- name: fmax(Tensor self, Tensor other) -> Tensor + # Reuse the tie-split output when transforms and tensor subclasses allow safe in-place masking. + self: masked_fill_inplace_if_safe(at::where(self == other, grad / 2, grad), self < other, 0) + other: masked_fill_inplace_if_safe(at::where(self == other, grad / 2, grad), self > other, 0) + # Do not blend tangents arithmetically: an inactive NaN or infinite tangent must not contaminate the result. + result: at::where(self_p == other_p, (self_t + other_t) / 2, at::where(self_p > other_p, self_t, other_t)) + +- name: mean(Tensor self, *, ScalarType? dtype=None) -> Tensor + dispatch: + Default: + self: grad.expand_symint(self.sym_sizes()) / self.sym_numel() + result: auto_linear + AutogradNestedTensor: + # TODO: replace this with grad.expand_as(self) / self.sym_numel() when that is supported + self: (ones_like(self) * grad) / self.sym_numel() + result: auto_linear + +- name: mean.dim(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + self: mean_backward(grad, self.sym_sizes(), dim, self.sym_numel(), keepdim) + result: auto_linear + +- name: median(Tensor self) -> Tensor + self: evenly_distribute_backward(grad, self, result) + result: evenly_read_jvp(self_t, self_p, result) + +- name: nanmedian(Tensor self) -> Tensor + self: evenly_distribute_backward(grad, self, result) + result: evenly_read_jvp(self_t, self_p, result) + +# This is in theory incorrect in the following case: +# sorted list: [..., a, b, b, ..., b, b, c, ...] with median = b and the value +# | at middle position of the +# | list between two `b`s. E.g., +# | +# ^the middle position +# The gradient exists and is essentially 0 in this case. +# +# In case where the middle position is at the boundary of `b` range, e.g., +# sorted list: [..., a, b, b, ..., b, b, c, ...] +# | +# ^the middle position +# The backward implementation is correct in the sense that it returns the +# subgradient on one side. +- name: median.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) + self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), keepdim) + values: gather_with_keepdimed_indices(self_t, dim, indices, keepdim) + +- name: nanmedian.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) + self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), keepdim) + values: gather_with_keepdimed_indices(self_t, dim, indices, keepdim) + +- name: min.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) + self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), keepdim) + values: gather_with_keepdimed_indices(self_t, dim, indices, keepdim) + +- name: min(Tensor self) -> Tensor + self: evenly_distribute_backward(grad, self, result) + result: evenly_read_jvp(self_t, self_p, result) + +- name: minimum(Tensor self, Tensor other) -> Tensor + # Reuse the tie-split output when transforms and tensor subclasses allow safe in-place masking. + self: masked_fill_inplace_if_safe(at::where(self == other, grad / 2, grad), self > other, 0) + other: masked_fill_inplace_if_safe(at::where(self == other, grad / 2, grad), self < other, 0) + # Do not blend tangents arithmetically: an inactive infinite tangent would produce 0 * inf = nan. + result: at::where(self_p == other_p, (self_t + other_t) / 2, at::where(self_p < other_p, self_t, other_t)) + +- name: fmin(Tensor self, Tensor other) -> Tensor + # Reuse the tie-split output when transforms and tensor subclasses allow safe in-place masking. + self: masked_fill_inplace_if_safe(at::where(self == other, grad / 2, grad), self > other, 0) + other: masked_fill_inplace_if_safe(at::where(self == other, grad / 2, grad), self < other, 0) + # Do not blend tangents arithmetically: an inactive NaN or infinite tangent must not contaminate the result. + result: at::where(self_p == other_p, (self_t + other_t) / 2, at::where(self_p < other_p, self_t, other_t)) + +- name: amax(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor + self: scale_grad_by_count(restore_reduced_dims(grad, dim, keepdim), restore_reduced_dims(result, dim, keepdim) == self, dim) + result: amaxamin_jvp(self_p, self_t, result, dim, keepdim) + +- name: amin(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor + self: scale_grad_by_count(restore_reduced_dims(grad, dim, keepdim), restore_reduced_dims(result, dim, keepdim) == self, dim) + result: amaxamin_jvp(self_p, self_t, result, dim, keepdim) + +- name: aminmax(Tensor self, *, int? dim=None, bool keepdim=False) -> (Tensor min, Tensor max) + self: aminmax_backward(self, dim, keepdim, grad_min, grad_max, min, max) + min: aminmax_jvp(self_p, self_t, min, dim, keepdim) + max: aminmax_jvp(self_p, self_t, max, dim, keepdim) + +- name: mm(Tensor self, Tensor mat2) -> Tensor + self: mm_mat1_backward(grad, mat2, self.sym_sizes(), self.sym_strides(), self.layout(), 1) + mat2: mm_mat2_backward(grad, self, mat2.sym_sizes(), mat2.sym_strides(), mat2.layout(), 1) + result: at::mm(self_t, mat2_p) + at::mm(self_p, mat2_t) + +- name: _grouped_mm(Tensor self, Tensor mat2, Tensor? offs=None, Tensor? bias=None, ScalarType? out_dtype=None) -> Tensor + self: _grouped_mm_mat1_backward(grad, mat2, self.sym_sizes(), self.sym_strides(), self.layout(), offs, 1) + mat2: _grouped_mm_mat2_backward(grad, self, mat2.sym_sizes(), mat2.sym_strides(), mat2.layout(), offs, 1) + +- name: mode(Tensor self, int dim=-1, bool keepdim=False) -> (Tensor values, Tensor indices) + self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), keepdim) + values: gather_with_keepdimed_indices(self_t, dim, indices, keepdim) + +- name: mul.Tensor(Tensor self, Tensor other) -> Tensor + self: mul_tensor_backward(grad, other, self.scalar_type()) + other: mul_tensor_backward(grad, self, other.scalar_type()) + result: other_t * self_p + self_t * other_p + +- name: mul.Scalar(Tensor self, Scalar other) -> Tensor + self: mul_tensor_backward(grad, other, self.scalar_type()) + result: self_t * other + +- name: mv(Tensor self, Tensor vec) -> Tensor + self: grad.ger(vec.conj()) + vec: self.conj().t().mv(grad) + result: mv(self_t, vec_p) + mv(self_p, vec_t) + +- name: mvlgamma(Tensor self, int p) -> Tensor + self: mvlgamma_backward(grad, self, p) + result: auto_element_wise + +- name: nan_to_num(Tensor self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor + self: grad * at::isfinite(self) + result: auto_element_wise + +- name: native_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor) + input, weight, bias: "grad.defined() ? native_batch_norm_backward(grad, input, weight, running_mean, running_var, result1, result2, training, eps, grad_input_mask) : std::tuple()" + result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, running_mean, running_var, result1, result2, training, eps) + +- name: _native_batch_norm_legit(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor) + input, weight, bias: "grad.defined() ? native_batch_norm_backward(grad, input, weight, running_mean, running_var, result1, result2, training, eps, grad_input_mask) : std::tuple()" + result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, running_mean, running_var, result1, result2, training, eps) + +- name: _native_batch_norm_legit_no_training(Tensor input, Tensor? weight, Tensor? bias, Tensor running_mean, Tensor running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor) + input, weight, bias: "grad.defined() ? native_batch_norm_backward(grad, input, weight, running_mean, running_var, result1, result2, /*training=*/false, eps, grad_input_mask) : std::tuple()" + result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, running_mean, running_var, result1, result2, /*training=*/false, eps) + +- name: _native_batch_norm_legit.no_stats(Tensor input, Tensor? weight, Tensor? bias, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor) + input, weight, bias: "grad.defined() ? native_batch_norm_backward(grad, input, weight, Tensor(), Tensor(), result1, result2, training, eps, grad_input_mask) : std::tuple()" + result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, Tensor(), Tensor(), result1, result2, training, eps) + +- name: native_batch_norm_backward(Tensor grad_out, Tensor input, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_invstd, bool train, float eps, bool[3] output_mask) -> (Tensor, Tensor, Tensor) + input, weight, grad_out: batchnorm_double_backward(input, weight, grads[0], grads[1], grads[2], grad_out, running_mean, running_var, train, eps, save_mean, save_invstd, grad_input_mask) + save_mean: not_implemented("native_batch_norm_backward save_mean") + save_invstd: not_implemented("native_batch_norm_backward save_invstd") + +- name: native_layer_norm(Tensor input, SymInt[] normalized_shape, Tensor? weight, Tensor? bias, float eps) -> (Tensor, Tensor, Tensor) + input, weight, bias: "grad.defined() ? native_layer_norm_backward_symint(grad, input, normalized_shape, result1, result2, weight, bias, grad_input_mask) : std::tuple()" + result0: layer_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, result1, result2, normalized_shape) + +- name: native_layer_norm_backward(Tensor grad_out, Tensor input, SymInt[] normalized_shape, Tensor mean, Tensor rstd, Tensor? weight, Tensor? bias, bool[3] output_mask) -> (Tensor, Tensor, Tensor) + input, weight, grad_out: layer_norm_double_backward(input, weight, grads[0], grads[1], grads[2], grad_out, mean, rstd, normalized_shape, grad_input_mask) + bias: Tensor() + mean: not_implemented("native_layer_norm_backward mean") + rstd: not_implemented("native_layer_norm_backward rstd") + +- name: _fused_rms_norm(Tensor input, int[] normalized_shape, Tensor? weight, float? eps) -> (Tensor, Tensor) + input, weight: "GradMode::is_enabled() || grads[1].defined() ? infinitely_differentiable_native_rms_norm_backward(grads[0], grads[1], input, normalized_shape, result1, weight, grad_input_mask) : (grads[0].defined() ? _fused_rms_norm_backward(grads[0], input, normalized_shape, result1, weight, grad_input_mask) : std::tuple())" + result0: rms_norm_jvp(input_p, input_t, weight_p, weight_t, result1, normalized_shape) + result1: rms_norm_rstd_jvp(input_p, input_t, result1, normalized_shape) + +- name: native_group_norm(Tensor input, Tensor? weight, Tensor? bias, SymInt N, SymInt C, SymInt HxW, int group, float eps) -> (Tensor, Tensor, Tensor) + input, weight, bias: "GradMode::is_enabled() || grads[1].defined() || grads[2].defined() ? native_group_norm_backward_dispatcher(grads[0], grads[1], grads[2], input, result1, result2, weight, N, C, HxW, group, grad_input_mask) : (grads[0].defined() ? native_group_norm_backward_symint(grads[0], input, result1, result2, weight, N, C, HxW, group, grad_input_mask) : std::tuple())" + result0: group_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, result1, result2, group) + result1: group_norm_mean_jvp(input_t, result1, group) + result2: group_norm_invstd_jvp(input_p, input_t, result1, result2, group) + +- name: ne_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + self: zeros_like(self) + result: self_t.zero_() + +- name: ne_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + self: zeros_like(self) + other: zeros_like(other) + result: self_t.zero_() + +- name: neg(Tensor self) -> Tensor + self: grad.neg() + result: auto_element_wise + +- name: _batch_norm_with_update(Tensor input, Tensor? weight, Tensor? bias, Tensor(a!) running_mean, Tensor(b!) running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor, Tensor) + input, weight, bias: "grad.defined() ? batch_norm_backward(grad, input, weight, running_mean, running_var, result1, result2, /*update*/true, eps, grad_input_mask, retain_variables ? result3.clone() : result3) : std::tuple()" + result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, running_mean, running_var, result1, result2, true, eps) + +- name: _batch_norm_no_update(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, float momentum, float eps) -> (Tensor, Tensor, Tensor, Tensor) + input, weight, bias: "grad.defined() ? batch_norm_backward(grad, input, weight, running_mean, running_var, result1, result2, /*update*/false, eps, grad_input_mask, retain_variables ? result3.clone() : result3) : std::tuple()" + result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, running_mean, running_var, result1, result2, false, eps) + +- name: batch_norm_backward(Tensor grad_out, Tensor input, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, bool update, float eps, bool[3] output_mask, Tensor reserve) -> (Tensor, Tensor, Tensor) + input, weight, grad_out: batchnorm_double_backward(input, weight, grads[0], grads[1], grads[2], grad_out, running_mean, running_var, update, eps, save_mean, save_var, grad_input_mask) + save_mean: not_implemented("batch_norm_backward save_mean") + save_var: not_implemented("batch_norm_backward save_var") + reserve: not_implemented("batch_norm_backward reserve") + +- name: nextafter(Tensor self, Tensor other) -> Tensor + self: at::where(self != other, grad, 0) + other: zeros_like(other) + result: at::where(self_p != other_p, self_t, 0) + +- name: norm.Scalar(Tensor self, Scalar p=2) -> Tensor + self: norm_backward(grad, self, p, result) + result: norm_jvp(self_p, self_t, p, result) + +- name: norm.ScalarOpt_dim(Tensor self, Scalar? p, int[1] dim, bool keepdim=False) -> Tensor + self: norm_backward(grad, self, p, result, dim, keepdim) + result: norm_jvp(self_p, self_t, p, result, dim, keepdim) + +- name: norm.ScalarOpt_dtype(Tensor self, Scalar? p, *, ScalarType dtype) -> Tensor + self: norm_backward(grad, self.to(grad.scalar_type()), p, result) + result: norm_jvp(self_p, self_t, p, result) + +- name: norm.ScalarOpt_dim_dtype(Tensor self, Scalar? p, int[1] dim, bool keepdim, *, ScalarType dtype) -> Tensor + self: norm_backward(grad, self.to(grad.scalar_type()), p, result, dim, keepdim) + result: norm_jvp(self_p, self_t, p, result, dim, keepdim) + +- name: linalg_vector_norm(Tensor self, Scalar ord=2, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + self: linalg_vector_norm_backward(grad, self, ord, result, dim, keepdim) + result: linalg_vector_norm_jvp(self_p, self_t, ord, result, dim, keepdim) + +- name: _pdist_forward(Tensor self, float p=2) -> Tensor + self: _pdist_backward(grad, self, p, result) + +- name: _pdist_backward(Tensor grad_output, Tensor self, float p, Tensor pdist) -> Tensor + grad_output, self, pdist: "_pdist_backward_backward(grad, grad_output, self, p, pdist, grad_input_mask)" + +- name: _euclidean_dist(Tensor x1, Tensor x2) -> Tensor + x1, x2: _euclidean_dist_backward(grad, x1, x2, result) + +- name: _cdist_forward(Tensor x1, Tensor x2, float p, int? compute_mode) -> Tensor + x1: _cdist_backward(grad.contiguous(), x1, x2, p, result) + x2: _cdist_backward(grad.mT().contiguous(), x2, x1, p, result.mT().contiguous()) + +- name: _cdist_backward(Tensor grad_output, Tensor x1, Tensor x2, float p, Tensor cdist) -> Tensor + grad_output, x1, x2, cdist: "_cdist_backward_backward(grad, grad_output, x1, x2, p, cdist, grad_input_mask)" + +- name: normal_(Tensor(a!) self, float mean=0, float std=1, *, Generator? generator=None) -> Tensor(a!) + self: zeros_like(grad) + result: self_t.zero_() + +- name: normal.Tensor_float(Tensor mean, float std=1, *, Generator? generator=None) -> Tensor + mean: at::zeros_symint(mean.sym_sizes(), grad.options()) + result: auto_element_wise + +- name: normal.float_Tensor(float mean, Tensor std, *, Generator? generator=None) -> Tensor + std: at::zeros_symint(std.sym_sizes(), grad.options()) + result: auto_element_wise + +- name: normal.Tensor_Tensor(Tensor mean, Tensor std, *, Generator? generator=None) -> Tensor + mean: at::zeros_symint(mean.sym_sizes(), grad.options()) + std: at::zeros_symint(std.sym_sizes(), grad.options()) + result: zeros_like(mean_t) + +- name: linalg_householder_product(Tensor input, Tensor tau) -> Tensor + input, tau: householder_product_backward(grad, result, input, tau) + result: householder_product_jvp(input_t, tau_t, result, input_p, tau_p) + +- name: ormqr(Tensor self, Tensor input2, Tensor input3, bool left=True, bool transpose=False) -> Tensor + self, input2, input3: ormqr_backward(grad, result, self, input2, input3, left, transpose, grad_input_mask) + +- name: permute(Tensor(a) self, int[] dims) -> Tensor(a) + self: permute_backwards(grad, dims) + result: auto_linear + +- name: poisson(Tensor self, Generator? generator=None) -> Tensor + self: zeros_like(self) + result: auto_element_wise + +- name: pow.Tensor_Scalar(Tensor self, Scalar exponent) -> Tensor + self: pow_backward(grad, self, exponent) + result: auto_element_wise + +- name: pow.Tensor_Tensor(Tensor self, Tensor exponent) -> Tensor + self: pow_backward_self(grad, self, exponent) + exponent: pow_backward_exponent(grad, self, exponent, result) + result: (pow_backward_self(self_t.conj(), self_p, exponent_p) + pow_backward_exponent(exponent_t.conj(), self_p, exponent_p, result)).conj() + +- name: pow.Scalar(Scalar self, Tensor exponent) -> Tensor + exponent: pow_backward_exponent(grad, self, exponent, result) + result: auto_element_wise + +- name: prod(Tensor self, *, ScalarType? dtype=None) -> Tensor + self: prod_backward(grad, self.to(grad.scalar_type()), result) + result: (prod_backward(at::ones({}, result.options()).expand_as(result), self_p.to(result.scalar_type()), result) * self_t.conj()).sum().conj() + +- name: prod.dim_int(Tensor self, int dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + self: prod_backward(grad, self.to(grad.scalar_type()), result, dim, keepdim) + result: (prod_backward(at::ones({}, result.options()).expand_as(result), self_p.to(result.scalar_type()), result, dim, keepdim) * self_t.conj()).sum(dim, keepdim).conj() + +- name: put(Tensor self, Tensor index, Tensor source, bool accumulate=False) -> Tensor + self: "accumulate ? grad : grad.put(index, zeros_like(source), false)" + index: non_differentiable + source: grad.take(index).reshape_as(source) + result: self_t.put(index, source_t, accumulate) + +- name: linalg_qr(Tensor A, str mode='reduced') -> (Tensor Q, Tensor R) + A: linalg_qr_backward(grad_Q, grad_R, Q, R, mode) + Q, R: linalg_qr_jvp(A_t, Q, R, mode) + +- name: rad2deg(Tensor self) -> Tensor + self: rad2deg_backward(grad) + result: auto_element_wise + +- name: random_.from(Tensor(a!) self, int from, int? to, *, Generator? generator=None) -> Tensor(a!) + self: zeros_like(grad) + result: self_t.zero_() + +- name: random_.to(Tensor(a!) self, int to, *, Generator? generator=None) -> Tensor(a!) + self: zeros_like(grad) + result: self_t.zero_() + +- name: random_(Tensor(a!) self, *, Generator? generator=None) -> Tensor(a!) + self: zeros_like(grad) + result: self_t.zero_() + +- name: reciprocal(Tensor self) -> Tensor + self: -grad * (result * result).conj() + result: auto_element_wise + +- name: remainder.Scalar(Tensor self, Scalar other) -> Tensor + self: grad + result: auto_element_wise + +- name: remainder.Tensor(Tensor self, Tensor other) -> Tensor + self: grad + other: -grad * self.div(other, /*rounding_mode=*/"floor") + result: self_t - other_t * self_p.div(other_p, /*rounding_mode=*/"floor") + +- name: renorm(Tensor self, Scalar p, int dim, Scalar maxnorm) -> Tensor + self: renorm_backward(grad, self, p, dim, maxnorm) + result: renorm_jvp(self_p, self_t, p, dim, maxnorm) + +- name: repeat(Tensor self, SymInt[] repeats) -> Tensor + self: repeat_backward(grad, repeats, self.sym_sizes()) + result: auto_linear + +- name: special_entr(Tensor self) -> Tensor + self: grad * (-(1 + self.log())) + result: auto_element_wise + +- name: special_ndtri(Tensor self) -> Tensor + self: grad * (M_PI_2 * M_SQRT2 * M_2_SQRTPI) * (result.square() * 0.5).exp() + result: auto_element_wise + +- name: special_log_ndtr(Tensor self) -> Tensor + self: grad * (M_2_SQRTPI * M_SQRT2 * 0.25) * (result + self.pow(2) * 0.5).neg().exp() + result: auto_element_wise + +# [Note: Sometimes view derivatives] +# The following situation applies to other operations as well. +# TODO: This note is only referenced by to_dense and to_sparse*. Make +# this more generic if it's been referenced more than once. +# +# DO NOT define a backward for reshape! +# reshape is special in that it sometimes returns a view, and sometimes not. +# Defining a backward will make codegen spit out the forward call as +# as_variable(baseType->reshape(self)), +# making it impossible (hard) to detect when it is actually a view. +# - name: reshape(Tensor self, IntArrayRef shape) + +- name: _reshape_alias(Tensor(a) self, SymInt[] size, SymInt[] stride) -> Tensor(a) + self: grad.reshape_symint(self.sym_sizes()) + result: auto_linear + +- name: round(Tensor self) -> Tensor + self: zeros_like(grad) + result: auto_element_wise + +- name: round.decimals(Tensor self, *, int decimals) -> Tensor + self: zeros_like(grad) + result: auto_element_wise + +- name: rsqrt(Tensor self) -> Tensor + self: -0.5 * grad * result.pow(3).conj() + result: auto_element_wise + +- name: scatter.src(Tensor self, int dim, Tensor index, Tensor src) -> Tensor + self: grad.scatter(dim, index, 0) + index: non_differentiable + src: grad.gather(dim, index) + result: self_t.scatter(dim, index, src_t) + +- name: scatter.value(Tensor self, int dim, Tensor index, Scalar value) -> Tensor + self: grad.scatter(dim, index, 0) + index: non_differentiable + result: self_t.scatter(dim, index, 0) + +- name: scatter_add(Tensor self, int dim, Tensor index, Tensor src) -> Tensor + self: grad + index: non_differentiable + src: grad.gather(dim, index) + result: scatter_add(self_t, dim, index, src_t) + +- name: select.int(Tensor(a) self, int dim, SymInt index) -> Tensor(a) + dispatch: + Default: + self: select_backward_symint(grad, self.sym_sizes(), dim, index) + result: auto_linear + AutogradNestedTensor: + self: _nested_select_backward_symint(grad, self, dim, index) + +- name: select_backward(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt index) -> Tensor + grad_output: grad.select_symint(dim, index) + result: auto_linear + +- name: sigmoid(Tensor self) -> Tensor + self: sigmoid_backward(grad, result) + result: auto_element_wise + +- name: logit(Tensor self, float? eps=None) -> Tensor + self: "GradMode::is_enabled() ? infinitely_differentiable_logit_backward(grad, self, eps) : logit_backward(grad, self, eps)" + result: auto_element_wise + +- name: sign(Tensor self) -> Tensor + self: zeros_like(grad) + result: auto_element_wise + +- name: sgn(Tensor self) -> Tensor + self: sgn_backward(self, grad, result) + # Cannot use auto_element_wise here because the Jacobian is *not* Hermitian (in fact, it is symmetric) + # The function is not holomorphic, so there's no reason for its Jacobian to be Hermitian + # auto_element_wise has a name that's a bit deceiving in the complex case + result: sgn_backward(self_p, self_t, result) + +- name: sin(Tensor self) -> Tensor + self: grad * self.cos().conj() + result: auto_element_wise + +- name: sinc(Tensor self) -> Tensor + self: sinc_backward(grad, self) + result: auto_element_wise + +- name: sinh(Tensor self) -> Tensor + self: grad * self.cosh().conj() + result: auto_element_wise + +- name: slice.Tensor(Tensor(a) self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a) + self: slice_backward_wrapper(grad, self.sym_sizes(), dim, start, end, step) + result: auto_linear + +- name: slice_backward(Tensor grad_output, SymInt[] input_sizes, int dim, SymInt start, SymInt end, SymInt step) -> Tensor + grad_output: grad.slice_symint(dim, start, end, step) + result: auto_linear + +- name: slice_inverse(Tensor(a) self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor(a) + self: grad.slice_symint(dim, start, end, step) + src: slice_scatter_symint(grad, zeros_like(self), dim, start, end, step) + result: auto_linear + +- name: slice_scatter(Tensor self, Tensor src, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor + self: slice_scatter_symint(grad, zeros_like(src), dim, start, end, step) + src: grad.slice_symint(dim, start, end, step) + result: auto_linear + +- name: select_scatter(Tensor self, Tensor src, int dim, SymInt index) -> Tensor + self: select_scatter_symint(grad, zeros_like(src), dim, index) + src: grad.select_symint(dim, index) + result: auto_linear + +- name: diagonal_scatter(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1) -> Tensor + self: diagonal_scatter(grad, zeros_like(src), offset, dim1, dim2) + src: grad.diagonal(offset, dim1, dim2) + result: auto_linear + +- name: as_strided_scatter(Tensor self, Tensor src, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor + self: as_strided_scatter_backward(grad, TensorGeometry(self), TensorGeometry(src), size, stride, storage_offset) + # See Note [as_strided_scatter backward support] + src: grad.contiguous().as_strided_symint(size, stride, storage_offset) + result: auto_linear + +- name: _linalg_solve_ex(Tensor A, Tensor B, *, bool left=True, bool check_errors=False) -> (Tensor result, Tensor LU, Tensor pivots, Tensor info) + A, B: linalg_solve_backward(grad, result, A, LU, pivots, left, grad_input_mask[1]) + result: "linalg_solve_jvp(A_t, B_t, result, LU, pivots, left)" + output_differentiability: [True, False, False, False] # LU is an auxiliary tensor not exposed to the user + +- name: sort(Tensor self, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices) + self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), true) + output_differentiability: [True, False] + values: gather_with_keepdimed_indices(self_t, dim, indices, true) + +- name: sort.stable(Tensor self, *, bool? stable, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices) + self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), true) + output_differentiability: [True, False] + values: gather_with_keepdimed_indices(self_t, dim, indices, true) + +- name: split.Tensor(Tensor(a -> *) self, SymInt split_size, int dim=0) -> Tensor(a)[] + self: split_backward(grads, split_size, dim, self.sym_sizes(), self.options()) + result: auto_linear + +- name: unsafe_split.Tensor(Tensor self, SymInt split_size, int dim=0) -> Tensor[] + self: split_backward(grads, split_size, dim, self.sym_sizes(), self.options()) + result: auto_linear + +- name: split_with_sizes(Tensor(a -> *) self, SymInt[] split_sizes, int dim=0) -> Tensor(a)[] + dispatch: + Default: + self: split_with_sizes_backward(grads, split_sizes, dim, self.sym_sizes(), self.options()) + result: auto_linear + AutogradNestedTensor: + self: _nested_split_with_sizes_backward(grads, split_sizes, dim, at::native::get_nested_tensor_impl(self)->get_nested_sizes(), self.options()) + +- name: unsafe_split_with_sizes(Tensor self, SymInt[] split_sizes, int dim=0) -> Tensor[] + self: split_with_sizes_backward(grads, split_sizes, dim, self.sym_sizes(), self.options()) + result: auto_linear + +- name: sqrt(Tensor self) -> Tensor + self: grad / (2 * result.conj()) + result: auto_element_wise + +- name: squeeze(Tensor(a) self) -> Tensor(a) + self: unsqueeze_to(grad, self.sym_sizes()) + result: auto_linear + +- name: squeeze.dim(Tensor(a) self, int dim) -> Tensor(a) + dispatch: + Default: + self: unsqueeze_to(grad, dim, self.sym_sizes()) + result: auto_linear + AutogradNestedTensor: + self: grad.unsqueeze(dim) + +- name: squeeze.dims(Tensor(a) self, int[] dim) -> Tensor(a) + dispatch: + Default: + self: unsqueeze_to(grad, dim, self.sym_sizes()) + result: auto_linear + AutogradNestedTensor: + self: unsqueeze_multiple(grad, dim, self.dim()) + +- name: squeeze_(Tensor(a!) self) -> Tensor(a!) + self: unsqueeze_to(grad, self.sym_sizes()) + result: auto_linear + +- name: squeeze_.dim(Tensor(a!) self, int dim) -> Tensor(a!) + self: unsqueeze_to(grad, dim, self.sym_sizes()) + result: auto_linear + +- name: squeeze_.dims(Tensor(a!) self, int[] dim) -> Tensor(a!) + self: unsqueeze_to(grad, dim, self.sym_sizes()) + result: auto_linear + +- name: std.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> Tensor + self: std_backward(result, grad, self, dim, correction, keepdim) + # pointwise (variance) + sum + sqrt + result: (at::real(var_backward(self_t.conj(), self_p, dim, correction, true).sum(dim.value_or(IntArrayRef({})), keepdim)) / (2. * result)).masked_fill_(result == 0, 0) + +- name: std_mean.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor) + self: std_mean_backward(grads[0], grads[1], self, result0, dim, correction, keepdim) + result0: (at::real(var_backward(self_t.conj(), self_p, dim, correction, true).sum(dim.value_or(IntArrayRef({})), keepdim)) / (2. * result0)).masked_fill_(result0 == 0, 0) + # linear + result1: mean(self_t, dim.value_or(IntArrayRef({})), keepdim) + +- name: sub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor + self: handle_r_to_c(self.scalar_type(), grad) + other: handle_r_to_c(other.scalar_type(), maybe_multiply(-grad, alpha.conj())) + result: self_t - maybe_multiply(other_t, alpha) + +- name: sub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor + self: handle_r_to_c(self.scalar_type(), grad) + result: auto_element_wise + +- name: rsub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor + self: handle_r_to_c(self.scalar_type(), maybe_multiply(-grad, alpha.conj())) + other: handle_r_to_c(other.scalar_type(), grad) + result: -maybe_multiply(self_t, alpha) + other_t + +- name: rsub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor + self: handle_r_to_c(self.scalar_type(), maybe_multiply(-grad, alpha.conj())) + result: auto_element_wise + +- name: sum(Tensor self, *, ScalarType? dtype=None) -> Tensor + dispatch: + Default: + self: grad.expand_symint(self.sym_sizes()) + result: auto_linear + AutogradNestedTensor: + # TODO: replace this with grad.expand_as(self) when that is supported + self: ones_like(self) * grad + result: auto_linear + +- name: sum.dim_IntList(Tensor self, int[1]? dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + dispatch: + Default: + self: sum_backward(grad, self.sym_sizes(), dim, keepdim) + result: auto_linear + AutogradNestedTensor: + # TODO: replace this function once semantics for nested tensor expand have been settled on + self: _nested_sum_backward(grad, self, dim, keepdim) + +- name: nansum(Tensor self, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + self: nansum_backward(grad.to(self.scalar_type()), self, dim, keepdim) + result: at::where(self_p.isnan(), 0, self_t).sum(dim, keepdim, dtype) + +# We never call _linalg_svd with compute_uv=False in an autograd context, so we don't even consider it here +- name: _linalg_svd(Tensor A, bool full_matrices=False, bool compute_uv=True, *, str? driver=None) -> (Tensor U, Tensor S, Tensor Vh) + A: "svd_backward(full_matrices && grad_U.defined() ? grad_U.narrow_symint(-1, 0, S.sym_size(-1)) : grad_U, + grad_S, + full_matrices && grad_Vh.defined() ? grad_Vh.narrow_symint(-2, 0, S.sym_size(-1)) : grad_Vh, + full_matrices ? U.narrow_symint(-1, 0, S.sym_size(-1)) : U, + S, + full_matrices ? Vh.narrow_symint(-2, 0, S.sym_size(-1)) : Vh)" + U, S, Vh: linalg_svd_jvp(A_t, U, S, Vh, full_matrices) + +- name: _linalg_eigh(Tensor A, str UPLO="L", bool compute_v=True) -> (Tensor eigenvalues, Tensor eigenvectors) + A: linalg_eig_backward(grads[0], grads[1], eigenvalues, eigenvectors, /*is_hermitian=*/true) + eigenvalues, eigenvectors: linalg_eig_jvp(A_t, eigenvalues, eigenvectors, /*is_hermitian=*/true) + +- name: linalg_eig(Tensor self) -> (Tensor eigenvalues, Tensor eigenvectors) + self: handle_r_to_c(self.scalar_type(), linalg_eig_backward(grads[0], grads[1], eigenvalues, eigenvectors, /*is_hermitian=*/false)) + eigenvalues, eigenvectors: linalg_eig_jvp(self_t, eigenvalues, eigenvectors, /*is_hermitian=*/false) + +- name: t(Tensor(a) self) -> Tensor(a) + self: grad.t() + result: auto_linear + +- name: t_(Tensor(a!) self) -> Tensor(a!) + self: grad.t() + result: auto_linear + +- name: one_hot(Tensor self, int num_classes=-1) -> Tensor + self: non_differentiable + +- name: flip(Tensor self, int[] dims) -> Tensor + self: grad.flip(dims) + result: auto_linear + +- name: roll(Tensor self, SymInt[1] shifts, int[1] dims=[]) -> Tensor + self: grad.roll_symint(fmap(reverse_list_symint(shifts), [](c10::SymInt i){return -i;}), reverse_list(dims)) + result: auto_linear + +- name: rot90(Tensor self, int k=1, int[] dims=[0,1]) -> Tensor + self: grad.rot90(-k, dims) + result: auto_linear + +- name: take(Tensor self, Tensor index) -> Tensor + self: take_backward(grad, self, index) + index: non_differentiable + result: auto_linear + +- name: tan(Tensor self) -> Tensor + self: grad * (1 + result.pow(2)).conj() + result: auto_element_wise + +- name: tanh(Tensor self) -> Tensor + self: tanh_backward(grad, result) + result: auto_element_wise + +- name: topk(Tensor self, SymInt k, int dim=-1, bool largest=True, bool sorted=True) -> (Tensor values, Tensor indices) + self: value_selecting_reduction_backward_symint(grad, dim, indices, self.sym_sizes(), true) + output_differentiability: [True, False] + values: gather(self_t, dim, indices) + +- name: trace(Tensor self) -> Tensor + self: trace_backward_symint(grad, self.sym_sizes()) + result: auto_linear + +- name: transpose.int(Tensor(a) self, int dim0, int dim1) -> Tensor(a) + self: grad.transpose(dim0, dim1) + result: auto_linear + +- name: transpose_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!) + self: grad.transpose(dim0, dim1) + result: auto_linear + +- name: triangular_solve(Tensor self, Tensor A, bool upper=True, bool transpose=False, bool unitriangular=False) -> (Tensor solution, Tensor cloned_coefficient) + self, A: triangular_solve_backward(grad_solution, grad_cloned_coefficient, self, A, solution, upper, transpose, unitriangular, grad_input_mask) + solution: triangular_solve_jvp(solution, A_p, A_t, self_t, upper, transpose, unitriangular) + cloned_coefficient: A_t + +- name: linalg_solve_triangular(Tensor self, Tensor B, *, bool upper, bool left=True, bool unitriangular=False) -> Tensor + self, B: linalg_solve_triangular_backward(grad, self, result, upper, left, unitriangular, grad_input_mask) + result: linalg_solve_triangular_forward_AD(self_t, B_t, self_p, result, upper, left, unitriangular) + +- name: tril(Tensor self, SymInt diagonal=0) -> Tensor + self: grad.tril_symint(diagonal) + result: auto_linear + +- name: triu(Tensor self, SymInt diagonal=0) -> Tensor + self: grad.triu_symint(diagonal) + result: auto_linear + +- name: trunc(Tensor self) -> Tensor + self: zeros_like(grad) + result: auto_element_wise + +- name: hash_tensor(Tensor self, int[1] dim=[], *, bool keepdim=False, int mode=0) -> Tensor + output_differentiability: [False] + +# DO NOT define a backward for to_dense +# See [Note: Sometimes view derivatives] +# - name: to_dense(Tensor self, ScalarType? dtype=None, *, bool? masked_grad=None) -> Tensor +# +- name: _to_dense(Tensor self, ScalarType? dtype=None, bool? masked_grad=None) -> Tensor + self: to_dense_backward(grad, self, masked_grad) + +# DO NOT define a backward for to_sparse.sparse_dim +# See [Note: Sometimes view derivatives] +# - name: to_sparse.sparse_dim(Tensor self, int sparse_dim) -> Tensor +# +- name: _to_sparse.sparse_dim(Tensor self, int sparse_dim) -> Tensor + self: to_sparse_backward(grad, self.layout(), self.sym_blocksize()) + +# DO NOT define a backward for to_sparse +# See [Note: Sometimes view derivatives] +# - name: to_sparse(Tensor self, *, Layout? layout=None, int[2]? blocksize=None, int? dense_dim=None) -> Tensor +# +- name: _to_sparse(Tensor self, *, Layout? layout=None, int[2]? blocksize=None, int? dense_dim=None) -> Tensor + self: to_sparse_backward(grad, self.layout(), self.sym_blocksize()) + +# DO NOT define a backward for to_sparse_csr +# See [Note: Sometimes view derivatives] +# - name: to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor +# +- name: _to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor + self: to_sparse_backward(grad, self.layout(), self.sym_blocksize()) + +# DO NOT define a backward for to_sparse_csc +# See [Note: Sometimes view derivatives] +# - name: to_sparse_csc(Tensor self, int? dense_dim=None) -> Tensor +# +- name: _to_sparse_csc(Tensor self, int? dense_dim=None) -> Tensor + self: to_sparse_backward(grad, self.layout(), self.sym_blocksize()) + +# DO NOT define a backward for to_sparse_bsr +# See [Note: Sometimes view derivatives] +# - name: to_sparse_bsr(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor +# +- name: _to_sparse_bsr(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor + self: to_sparse_backward(grad, self.layout(), self.sym_blocksize()) + +# DO NOT define a backward for to_sparse_bsc +# See [Note: Sometimes view derivatives] +# - name: to_sparse_bsc(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor +# +- name: _to_sparse_bsc(Tensor self, int[2] blocksize, int? dense_dim=None) -> Tensor + self: to_sparse_backward(grad, self.layout(), self.sym_blocksize()) + +- name: to_mkldnn(Tensor self, ScalarType? dtype=None) -> Tensor + self: to_mkldnn_backward(grad, self) + +- name: unfold(Tensor(a) self, int dimension, int size, int step) -> Tensor(a) + self: unfold_backward_symint(grad, self.sym_sizes(), dimension, size, step) + result: auto_linear + +- name: unfold_backward(Tensor grad_in, SymInt[] input_sizes, int dim, int size, int step) -> Tensor + grad_in: grad.unfold(dim, size, step) + result: auto_linear + +- name: uniform_(Tensor(a!) self, float from=0, float to=1, *, Generator? generator=None) -> Tensor(a!) + self: zeros_like(grad) + result: self_t.zero_() + +- name: _unique(Tensor self, bool sorted=True, bool return_inverse=False) -> (Tensor, Tensor) + output_differentiability: [True, False] + self: not_implemented("_unique") + +- name: unique_dim(Tensor self, int dim, bool sorted=True, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor) + output_differentiability: [True, False, False] + self: not_implemented("unique_dim") + +- name: unique_consecutive(Tensor self, bool return_inverse=False, bool return_counts=False, int? dim=None) -> (Tensor, Tensor, Tensor) + output_differentiability: [True, False, False] + self: not_implemented("unique_consecutive") + +- name: unique_dim_consecutive(Tensor self, int dim, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor) + output_differentiability: [True, False, False] + self: not_implemented("unique_dim_consecutive") + +- name: _unique2(Tensor self, bool sorted=True, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor) + output_differentiability: [True, False, False] + self: not_implemented("_unique2") + +- name: _unsafe_view(Tensor self, SymInt[] size) -> Tensor + self: grad.reshape_symint(self.sym_sizes()) + result: auto_linear + +- name: lift(Tensor self) -> Tensor + self: grad + result: auto_linear + +- name: lift_fresh(Tensor(a) self) -> Tensor(a) + self: grad + result: auto_linear + +- name: unsqueeze(Tensor(a) self, int dim) -> Tensor(a) + self: grad.squeeze(dim) + result: auto_linear + +- name: unsqueeze_(Tensor(a!) self, int dim) -> Tensor(a!) + self: grad.squeeze(dim) + result: auto_linear + +- name: var.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> Tensor + self: var_backward(grad, self, dim, correction, keepdim) + # pointwise + sum + result: at::real(var_backward(self_t.conj(), self_p, dim, correction, true).sum(dim.value_or(IntArrayRef({})), keepdim)) + +- name: var_mean.correction(Tensor self, int[1]? dim=None, *, Scalar? correction=None, bool keepdim=False) -> (Tensor, Tensor) + self: var_mean_backward(grads[0], grads[1], self, dim, correction, keepdim) + result0: at::real(var_backward(self_t.conj(), self_p, dim, correction, true).sum(dim.value_or(IntArrayRef({})), keepdim)) + # linear + result1: mean(self_t, dim.value_or(IntArrayRef({})), keepdim) + +- name: view(Tensor(a) self, SymInt[] size) -> Tensor(a) + dispatch: + Default: + self: grad.reshape_symint(self.sym_sizes()) + result: auto_linear + AutogradNestedTensor: + self: grad.reshape_as(self) + result: auto_linear + +- name: view.dtype(Tensor(a) self, ScalarType dtype) -> Tensor(a) + output_differentiability: [False] + +- name: view_as_real(Tensor(a) self) -> Tensor(a) + self: at::view_as_complex(grad.contiguous()) # gx0 + 1j * gx1 + result: at::view_as_real(self_t) + +- name: view_as_complex(Tensor(a) self) -> Tensor(a) + self: at::view_as_real(grad.contiguous().resolve_conj()) # [gx, gy] + result: at::view_as_complex(self_t) + +- name: where.self(Tensor condition, Tensor self, Tensor other) -> Tensor + condition: non_differentiable + self: where(condition, grad, 0) + other: where(condition, 0, grad) + result: where(condition, self_t, other_t) + +# weight_norm_cuda_interface_backward does not have an explicitly defined derivative, so if we do happen +# to be running backward with create_graph=True, fall back to a backward function that uses +# differentiable ops. +- name: _weight_norm_interface(Tensor v, Tensor g, int dim=0) -> (Tensor, Tensor) + v, g: "grad.defined() ? (GradMode::is_enabled() ? _weight_norm_differentiable_backward(grad.contiguous(), v, g, result1, dim) : _weight_norm_interface_backward(grad.contiguous(), v, g, result1, dim)) : std::tuple()" + +- name: zero_(Tensor(a!) self) -> Tensor(a!) + self: zeros_like(grad) + result: auto_linear + +- name: sparse_mask(Tensor self, Tensor mask) -> Tensor + self: sparse_mask_backward(grad, mask, self.layout()) + mask: non_differentiable + +- name: _sparse_coo_tensor_with_dims_and_tensors(int sparse_dim, int dense_dim, SymInt[] size, Tensor indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False, bool? is_coalesced=None) -> Tensor + indices: non_differentiable + values: grad.sparse_mask(result)._values() + +- name: sparse_compressed_tensor.comp_plain_value_size(Tensor compressed_indices, Tensor plain_indices, Tensor values, SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor + compressed_indices: non_differentiable + plain_indices: non_differentiable + # TODO: remove to_dense after gh-107381 is fixed + values: grad.to_dense().sparse_mask(result).values() + +- name: _sparse_sum.dim(Tensor self, int[1] dim) -> Tensor + self: at::_sparse_sum_backward(grad, self, dim) + +- name: _standard_gamma(Tensor self, Generator? generator=None) -> Tensor + self: grad * _standard_gamma_grad(self, result) + +- name: _standard_gamma_grad(Tensor self, Tensor output) -> Tensor + self: not_implemented("_standard_gamma_grad") + +- name: values(Tensor(a) self) -> Tensor(a) + dispatch: + Default: + self: values_backward(grad, self) + AutogradNestedTensor: + self: at::_nested_view_from_buffer(grad.contiguous(), self._nested_tensor_size(), self._nested_tensor_strides(), self._nested_tensor_storage_offsets()) + +# Why is _values() not differentiable? +# See NOTE [ Sparse: autograd and API ] +- name: _values(Tensor(a) self) -> Tensor(a) + output_differentiability: [False] + +# NN +- name: _trilinear(Tensor i1, Tensor i2, Tensor i3, int[] expand1, int[] expand2, int[] expand3, int[] sumdim, int unroll_dim=1) -> Tensor + i1, i2, i3: "_trilinear_backward(grad, + wrap_opt_if(i1, grad_input_mask[1] || grad_input_mask[2]), + wrap_opt_if(i2, grad_input_mask[0] || grad_input_mask[2]), + wrap_opt_if(i3, grad_input_mask[0] || grad_input_mask[1]), + expand1, expand2, expand3, sumdim, grad_input_mask)" + result: "_trilinear(i1_t, i2_p, i3_p, expand1, expand2, expand3, sumdim, unroll_dim) + + _trilinear(i1_p, i2_t, i3_p, expand1, expand2, expand3, sumdim, unroll_dim) + + _trilinear(i1_p, i2_p, i3_t, expand1, expand2, expand3, sumdim, unroll_dim)" + +- name: constant_pad_nd(Tensor self, SymInt[] pad, Scalar value=0) -> Tensor + self: constant_pad_nd_backward(grad, pad) + result: constant_pad_nd_symint(self_t, pad, 0) + +- name: binary_cross_entropy(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor + self: binary_cross_entropy_backward(grad, self, target, weight, reduction) + target: binary_cross_entropy_target_backward(grad, self, target, weight, reduction) + result: "apply_loss_reduction( + binary_cross_entropy_backward(self_t, self_p, target_p, weight, at::Reduction::None) + + binary_cross_entropy_target_backward(target_t, self_p, target_p, weight, at::Reduction::None), + reduction)" + +- name: binary_cross_entropy_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor + self: binary_cross_entropy_double_backward(grad_output, grad, self, target, weight, reduction) + target: binary_cross_entropy_double_backward_target(grad, grad_output, self, target, weight, reduction) + grad_output: binary_cross_entropy_double_backward_grad_output(grad, self, target, weight, reduction) + result: " binary_cross_entropy_double_backward(grad_output_p, self_t, self_p, target_p, weight, reduction) + + binary_cross_entropy_double_backward_target(target_t, grad_output_p, self_p, target_p, weight, reduction) + + binary_cross_entropy_double_backward_grad_output(grad_output_t, self_p, target_p, weight, reduction)" + +- name: binary_cross_entropy_with_logits(Tensor self, Tensor target, Tensor? weight=None, Tensor? pos_weight=None, int reduction=Mean) -> Tensor + self: binary_cross_entropy_with_logits_backward(grad, self, target, weight, pos_weight, reduction) + target: binary_cross_entropy_with_logits_target_backward(grad, self, target, weight, pos_weight, reduction) + result: "apply_loss_reduction( + binary_cross_entropy_with_logits_backward(self_t, self_p, target_p, weight, pos_weight, at::Reduction::None) + + binary_cross_entropy_with_logits_target_backward(target_t, self_p, target_p, weight, pos_weight, at::Reduction::None), + reduction)" + +- name: embedding(Tensor weight, Tensor indices, SymInt padding_idx=-1, bool scale_grad_by_freq=False, bool sparse=False) -> Tensor + indices: non_differentiable + weight: embedding_backward_symint(grad, indices, weight.sym_size(0), padding_idx, scale_grad_by_freq, sparse) + result: auto_linear + +- name: embedding_dense_backward(Tensor grad_output, Tensor indices, SymInt num_weights, SymInt padding_idx, bool scale_grad_by_freq) -> Tensor + grad_output: embedding_dense_double_backward_symint(grad, indices, padding_idx) + indices: non_differentiable + result: auto_linear + +- name: _embedding_bag(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1) -> (Tensor, Tensor, Tensor, Tensor) + indices: non_differentiable + offsets: non_differentiable + weight: _embedding_bag_backward_symint(grad, indices, offsets, result1, result2, result3, weight.sym_size(0), scale_grad_by_freq, mode, sparse, per_sample_weights, padding_idx) + per_sample_weights: _embedding_bag_per_sample_weights_backward(grad, weight, indices, offsets, result1, mode, padding_idx) + +- name: _embedding_bag_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor + grad: not_implemented("_embedding_bag_backward") + indices: non_differentiable + offsets: non_differentiable + offset2bag: non_differentiable + bag_size: non_differentiable + maximum_indices: non_differentiable + per_sample_weights: not_implemented("_embedding_bag_backward") + +- name: _embedding_bag_dense_backward(Tensor grad, Tensor indices, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor + grad: not_implemented("_embedding_bag_dense_backward") + indices: non_differentiable + offset2bag: non_differentiable + bag_size: non_differentiable + maximum_indices: non_differentiable + per_sample_weights: not_implemented("_embedding_bag_dense_backward") + +- name: embedding_renorm_(Tensor(a!) self, Tensor indices, float max_norm, float norm_type) -> Tensor(a!) + indices: non_differentiable + self: not_implemented("embedding_renorm") + +- name: mse_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor + self: mse_loss_backward(grad, self, target, reduction) + target: mse_loss_backward(grad, target, self, reduction) + result: apply_loss_reduction(mse_loss_backward(self_t.conj(), self_p, target_p, at::Reduction::None).conj() + mse_loss_backward(target_t.conj(), target_p, self_p, at::Reduction::None).conj(), reduction) + +- name: multi_margin_loss(Tensor self, Tensor target, Scalar p=1, Scalar margin=1, Tensor? weight=None, int reduction=Mean) -> Tensor + self: multi_margin_loss_backward(grad, self, target, p, margin, weight, reduction) + target: non_differentiable + +- name: multilabel_margin_loss_forward(Tensor self, Tensor target, int reduction) -> (Tensor output, Tensor is_target) + self: multilabel_margin_loss_backward(grad, self, target, reduction, is_target) + target: non_differentiable + +- name: nll_loss_forward(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index) -> (Tensor output, Tensor total_weight) + self: nll_loss_backward_symint(grad, self, target, weight, reduction, ignore_index, total_weight) + target: non_differentiable + output: std::get<0>(nll_loss_forward_symint(self_t, target, weight, reduction, ignore_index)) + +- name: nll_loss2d_forward(Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index) -> (Tensor output, Tensor total_weight) + self: nll_loss2d_backward_symint(grad, self, target, weight, reduction, ignore_index, total_weight) + target: non_differentiable + output: std::get<0>(nll_loss2d_forward_symint(self_t, target, weight, reduction, ignore_index)) + +- name: smooth_l1_loss(Tensor self, Tensor target, int reduction=Mean, float beta=1.0) -> Tensor + self: smooth_l1_loss_backward(grad, self, target, reduction, beta) + target: smooth_l1_loss_backward(grad, target, self, reduction, beta) + result: apply_loss_reduction(smooth_l1_loss_backward(self_t.conj(), self_p, target_p, at::Reduction::None, beta).conj() + smooth_l1_loss_backward(target_t.conj(), target_p, self_p, at::Reduction::None, beta).conj(), reduction) + +- name: huber_loss(Tensor self, Tensor target, int reduction=Mean, float delta=1.0) -> Tensor + self: huber_loss_backward(grad, self, target, reduction, delta) + target: huber_loss_backward(grad, target, self, reduction, delta) + result: apply_loss_reduction(huber_loss_backward(self_t.conj(), self_p, target_p, at::Reduction::None, delta).conj() + huber_loss_backward(target_t.conj(), target_p, self_p, at::Reduction::None, delta).conj(), reduction) + +- name: soft_margin_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor + self: soft_margin_loss_backward(grad, self, target, reduction) + result: apply_loss_reduction(soft_margin_loss_backward(self_t.conj(), self_p, target, at::Reduction::None).conj(), reduction) + +- name: relu(Tensor self) -> Tensor + self: threshold_backward(grad, result, 0) + result: auto_element_wise + +- name: silu(Tensor self) -> Tensor + self: "GradMode::is_enabled() ? infinitely_differentiable_silu_backward(grad, self) : silu_backward(grad, self)" + result: auto_element_wise + +- name: mish(Tensor self) -> Tensor + self: "GradMode::is_enabled() ? infinitely_differentiable_mish_backward(grad, self) : mish_backward(grad, self)" + result: auto_element_wise + +- name: elu(Tensor self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1) -> Tensor + self: elu_backward(grad, alpha, scale, input_scale, /* is_result */ false, self) + result: auto_element_wise + +- name: elu_(Tensor(a!) self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1) -> Tensor(a!) + self: elu_backward(grad, alpha, scale, input_scale, /* is_result */ true, result) + result: self_t.copy_(elu_backward(original_self_t, alpha, scale, input_scale, /* is_result */ true, result)) + +- name: celu(Tensor self, Scalar alpha=1.0) -> Tensor + self: elu_backward(grad, alpha, 1, 1.0/alpha.toFloat(), /* is_result */ false, self) + result: auto_element_wise + +- name: celu_(Tensor(a!) self, Scalar alpha=1.0) -> Tensor(a!) + self: elu_backward(grad, alpha, 1, 1.0/alpha.toFloat(), /* is_result */ true, result) + result: self_t.copy_(elu_backward(original_self_t, alpha, 1, 1.0/alpha.toFloat(), /* is_result */ true, result)) + +- name: gelu(Tensor self, *, str approximate='none') -> Tensor + self: gelu_backward(grad, self, approximate) + result: auto_element_wise + +- name: gelu_backward(Tensor grad_output, Tensor self, *, str approximate='none') -> Tensor + grad_output: gelu_backward(grad, self, approximate) + self: gelu_double_backward(grad, grad_output, self, approximate) + result: gelu_backward(grad_output_t, self_p, approximate) + gelu_double_backward(self_t, grad_output_p, self_p, approximate) + +- name: glu(Tensor self, int dim=-1) -> Tensor + # TODO: glu_backward can benefit from forward result, + # and forward ad/forward over reverse ad for that matter + self: glu_backward(grad, self, dim) + result: glu_jvp(result, self_p, self_t, dim) + +- name: hardshrink(Tensor self, Scalar lambd=0.5) -> Tensor + self: hardshrink_backward(grad, self, lambd) + result: auto_element_wise + +- name: hardshrink_backward(Tensor grad_out, Tensor self, Scalar lambd) -> Tensor + grad_out: hardshrink_backward(grad, self, lambd) + self: zeros_like(grad) + result: at::where((self_p > lambd).logical_or(self_p < -lambd), grad_out_t, at::zeros({}, result.options()).expand_as(result)) + +- name: hardtanh(Tensor self, Scalar min_val=-1, Scalar max_val=1) -> Tensor + self: hardtanh_backward(grad, self, min_val, max_val) + result: auto_element_wise + +- name: leaky_relu(Tensor self, Scalar negative_slope=0.01) -> Tensor + self: leaky_relu_backward(grad, self, negative_slope, false) + result: auto_element_wise + +- name: leaky_relu_(Tensor(a!) self, Scalar negative_slope=0.01) -> Tensor(a!) + self: leaky_relu_backward(grad, result, negative_slope, true) + result: self_t.copy_(leaky_relu_backward(original_self_t.conj(), result, negative_slope, true).conj()) + +- name: log_sigmoid_forward(Tensor self) -> (Tensor output, Tensor buffer) + self: log_sigmoid_backward(grad, self, buffer) + output: log_sigmoid_backward(self_t.conj(), self_p, buffer).conj() + output_differentiability: [True, False] + +- name: _log_softmax(Tensor self, int dim, bool half_to_float) -> Tensor + self: _log_softmax_backward_data(grad, result, dim, self.scalar_type()) + result: self_t - logsumexp_jvp(self_p, self_t, {dim}, true) + +- name: _sparse_log_softmax(Tensor self, int dim, bool half_to_float) -> Tensor + self: _sparse_log_softmax_backward_data(grad, result, dim, self) + +- name: _masked_softmax(Tensor self, Tensor mask, int? dim=None, int? mask_type=None) -> Tensor + self: _masked_softmax_backward(grad, result, mask, dim) + mask: non_differentiable + +- name: _prelu_kernel(Tensor self, Tensor weight) -> Tensor + self, weight: "grad.defined() ? _prelu_kernel_backward(grad, self, weight) : std::tuple()" + result: at::where(self_p >= 0, self_t, weight_p * self_t + weight_t * self_p) + +- name: _prelu_kernel_backward(Tensor grad_output, Tensor self, Tensor weight) -> (Tensor, Tensor) + grad_output: "grads[0].defined() ? + (grads[1].defined() ? at::where(self >= 0, grads[0], grads[0] * weight + grads[1] * self) + : at::where(self >= 0, grads[0], grads[0] * weight)) + : at::where(self >= 0, at::zeros({}, grad_output.options()), grads[1] * self)" + self: "grads[1].defined() ? at::where(self >= 0, at::zeros({}, self.options()), grad_output * grads[1]) : zeros_like(self)" + weight: "grads[0].defined() ? at::where(self >= 0, at::zeros({}, weight.options()), grad_output * grads[0]) : zeros_like(self)" + result0: at::where(self_p >= 0, grad_output_t, grad_output_t * weight_p + grad_output_p * weight_t) + result1: at::where(self_p >= 0, at::zeros({}, self_p.options()), grad_output_p * self_t + grad_output_t * self_p) + +- name: rrelu_with_noise(Tensor self, Tensor(b!) noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor + self: rrelu_with_noise_backward(grad, self, noise, lower, upper, training, false) + result: auto_element_wise + +- name: rrelu_with_noise_(Tensor(a!) self, Tensor(b!) noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor(a!) + self: rrelu_with_noise_backward(grad, result, noise, lower, upper, training, true) + +- name: rrelu_with_noise_functional(Tensor self, Tensor noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> (Tensor, Tensor noise_out) + noise: non_differentiable + self: rrelu_with_noise_backward(grad, self, noise, lower, upper, training, false) + +- name: _softmax(Tensor self, int dim, bool half_to_float) -> Tensor + self: _softmax_backward_data(grad, result, dim, self.scalar_type()) + result: result * (self_t - logsumexp_jvp(self_p, self_t, {dim}, true)) + +- name: _sparse_softmax(Tensor self, int dim, bool half_to_float) -> Tensor + self: _sparse_softmax_backward_data(grad, result, dim, self) + +- name: _sparse_sparse_matmul(Tensor self, Tensor other) -> Tensor + self: sparse_sparse_matmul_backward(grad, self, other, 0) + other: sparse_sparse_matmul_backward(grad, self, other, 1) + +- name: softplus(Tensor self, Scalar beta=1, Scalar threshold=20) -> Tensor + self: softplus_backward(grad, self, beta, threshold) + result: auto_element_wise + +- name: softshrink(Tensor self, Scalar lambd=0.5) -> Tensor + self: softshrink_backward(grad, self, lambd) + result: auto_element_wise + +- name: threshold(Tensor self, Scalar threshold, Scalar value) -> Tensor + self: threshold_backward(grad, self, threshold) + result: auto_element_wise + +- name: threshold_(Tensor(a!) self, Scalar threshold, Scalar value) -> Tensor(a!) + self: threshold_backward(grad, self, threshold) + result: self_t.copy_(threshold_backward(self_t.conj(), original_self_p, threshold).conj()) + +- name: reflection_pad1d(Tensor self, SymInt[2] padding) -> Tensor + self: reflection_pad1d_backward_symint(grad, self, padding) + result: auto_linear + +- name: reflection_pad2d(Tensor self, SymInt[4] padding) -> Tensor + self: reflection_pad2d_backward_symint(grad, self, padding) + result: auto_linear + +- name: reflection_pad3d(Tensor self, SymInt[6] padding) -> Tensor + self: reflection_pad3d_backward_symint(grad, self, padding) + result: auto_linear + +- name: replication_pad1d(Tensor self, SymInt[2] padding) -> Tensor + self: replication_pad1d_backward_symint(grad, self, padding) + result: auto_linear + +- name: replication_pad2d(Tensor self, SymInt[4] padding) -> Tensor + self: replication_pad2d_backward_symint(grad, self, padding) + result: auto_linear + +- name: replication_pad3d(Tensor self, SymInt[6] padding) -> Tensor + self: replication_pad3d_backward_symint(grad, self, padding) + result: auto_linear + +- name: upsample_linear1d(Tensor self, SymInt[1] output_size, bool align_corners, float? scales=None) -> Tensor + self: upsample_linear1d_backward_symint(grad, output_size, self.sym_sizes(), align_corners, scales) + result: auto_linear + +- name: upsample_bilinear2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + self: upsample_bilinear2d_backward_symint(grad, output_size, self.sym_sizes(), align_corners, scales_h, scales_w) + result: auto_linear + +- name: _upsample_bilinear2d_aa(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + self: _upsample_bilinear2d_aa_backward_symint(grad, output_size, self.sym_sizes(), align_corners, scales_h, scales_w) + result: auto_linear + +- name: upsample_bicubic2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + self: upsample_bicubic2d_backward_symint(grad, output_size, self.sym_sizes(), align_corners, scales_h, scales_w) + result: auto_linear + +- name: _upsample_bicubic2d_aa(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + self: _upsample_bicubic2d_aa_backward_symint(grad, output_size, self.sym_sizes(), align_corners, scales_h, scales_w) + result: auto_linear + +- name: _upsample_lanczos2d_aa(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + self: _upsample_lanczos2d_aa_backward_symint(grad, output_size, self.sym_sizes(), align_corners, scales_h, scales_w) + result: auto_linear + +- name: upsample_trilinear3d(Tensor self, SymInt[3] output_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor + self: upsample_trilinear3d_backward_symint(grad, output_size, self.sym_sizes(), align_corners, scales_d, scales_h, scales_w) + result: auto_linear + +- name: upsample_nearest1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor + self: upsample_nearest1d_backward_symint(grad, output_size, self.sym_sizes(), scales) + result: auto_linear + +- name: _upsample_nearest_exact1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor + self: _upsample_nearest_exact1d_backward_symint(grad, output_size, self.sym_sizes(), scales) + result: auto_linear + +- name: upsample_nearest2d(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None) -> Tensor + self: upsample_nearest2d_backward_symint(grad, output_size, self.sym_sizes(), scales_h, scales_w) + result: auto_linear + +- name: _upsample_nearest_exact2d(Tensor self, SymInt[2] output_size, float? scales_h=None, float? scales_w=None) -> Tensor + self: _upsample_nearest_exact2d_backward_symint(grad, output_size, self.sym_sizes(), scales_h, scales_w) + result: auto_linear + +- name: upsample_nearest3d(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor + self: upsample_nearest3d_backward_symint(grad, output_size, self.sym_sizes(), scales_d, scales_h, scales_w) + result: auto_linear + +- name: _upsample_nearest_exact3d(Tensor self, SymInt[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor + self: _upsample_nearest_exact3d_backward_symint(grad, output_size, self.sym_sizes(), scales_d, scales_h, scales_w) + result: auto_linear + +- name: pixel_shuffle(Tensor self, int upscale_factor) -> Tensor + self: pixel_unshuffle(grad, upscale_factor) + result: auto_linear + +- name: pixel_unshuffle(Tensor self, int downscale_factor) -> Tensor + self: pixel_shuffle(grad, downscale_factor) + result: auto_linear + +- name: channel_shuffle(Tensor self, SymInt groups) -> Tensor + self: channel_shuffle_symint(grad, grad.sym_size(1) / groups) + result: auto_linear + +- name: _adaptive_avg_pool2d(Tensor self, SymInt[2] output_size) -> Tensor + self: _adaptive_avg_pool2d_backward(grad, self) + result: auto_linear + +- name: _adaptive_avg_pool3d(Tensor self, SymInt[3] output_size) -> Tensor + self: _adaptive_avg_pool3d_backward(grad, self) + result: auto_linear + +- name: adaptive_max_pool2d(Tensor self, int[2] output_size) -> (Tensor, Tensor) + self: adaptive_max_pool2d_backward(grad, self, result1) + result0: gather(self_t.flatten(-2), -1, result1.flatten(-2)).view_as(result1) + output_differentiability: [True, False] + +- name: adaptive_max_pool3d(Tensor self, int[3] output_size) -> (Tensor, Tensor) + self: adaptive_max_pool3d_backward(grad, self, result1) + result0: gather(self_t.flatten(-3), -1, result1.flatten(-3)).view_as(result1) + output_differentiability: [True, False] + +- name: avg_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None) -> Tensor + self: avg_pool2d_backward(grad, self, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override) + result: auto_linear + +- name: avg_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None) -> Tensor + self: avg_pool3d_backward(grad, self, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override) + result: auto_linear + +- name: fractional_max_pool2d(Tensor self, int[2] kernel_size, int[2] output_size, Tensor random_samples) -> (Tensor, Tensor) + self: fractional_max_pool2d_backward(grad, self, kernel_size, output_size, result1) + result0: gather(self_t.flatten(-2), -1, result1.flatten(-2)).view_as(result1) + output_differentiability: [True, False] + +- name: fractional_max_pool3d(Tensor self, int[3] kernel_size, int[3] output_size, Tensor random_samples) -> (Tensor, Tensor) + self: fractional_max_pool3d_backward(grad, self, kernel_size, output_size, result1) + result0: gather(self_t.flatten(-3), -1, result1.flatten(-3)).view_as(result1) + output_differentiability: [True, False] + +- name: linear(Tensor input, Tensor weight, Tensor? bias=None) -> Tensor + input, weight, bias: "grad.defined() ? linear_backward(input, grad, weight, grad_input_mask) : std::tuple()" + +- name: linear_backward(Tensor self, Tensor grad_output, Tensor weight, bool[3] output_mask) -> (Tensor, Tensor, Tensor) + self, grad_output, weight: linear_double_backward(grads, self, grad_output, weight) + +#mps +- name: max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor + self: max_pool2d_backward(grad, self, kernel_size, stride, padding, dilation, ceil_mode) + +- name: _mps_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor + self, weight, bias: "grad.defined() ? mps_convolution_backward_symint(self, grad, weight, padding, stride, dilation, groups, grad_input_mask) : std::tuple()" + +- name: mps_convolution_backward(Tensor self, Tensor grad_output, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) + grad_output, self, weight: _convolution_double_backward_symint(grads[0], grads[1], grads[2], grad_output, weight, self, stride, padding, dilation, false, std::vector(padding.size(), 0), groups, grad_input_mask) + +- name: max_pool2d_with_indices(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor) + self: max_pool2d_with_indices_backward(grad, self, kernel_size, stride, padding, dilation, ceil_mode, result1) + result0: gather(self_t.flatten(-2), -1, result1.flatten(-2)).view_as(result1) + output_differentiability: [True, False] + +- name: max_pool3d_with_indices(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor) + self: max_pool3d_with_indices_backward(grad, self, kernel_size, stride, padding, dilation, ceil_mode, result1) + result0: gather(self_t.flatten(-3), -1, result1.flatten(-3)).view_as(result1) + output_differentiability: [True, False] + +- name: max_unpool2d(Tensor self, Tensor indices, SymInt[2] output_size) -> Tensor + self: max_pool_double_backward(grad, indices, 2) + indices: non_differentiable + result: auto_linear + +- name: max_unpool3d(Tensor self, Tensor indices, SymInt[3] output_size, int[3] stride, int[3] padding) -> Tensor + self: max_pool_double_backward(grad, indices, 3) + indices: non_differentiable + result: auto_linear + +- name: convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups) -> Tensor + input, weight, bias: "grad.defined() ? convolution_backward_symint(grad, input, weight, bias->sym_sizes(), stride, padding, dilation, transposed, output_padding, groups, grad_input_mask) : std::tuple()" + result: convolution_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, stride, padding, dilation, transposed, output_padding, groups) + +# TorchScript serializes calls to _convolution so this entry is present until that is changed to use convolution. +# Note that the benchmark, deterministic, cudnn_enabled, and allow_tf32 flags are queried from the global context +# by convolution_backward instead of being passed along from the forward pass. +- name: _convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32) -> Tensor + input, weight, bias: "grad.defined() ? convolution_backward_symint(grad, input, weight, bias->sym_sizes(), stride, padding, dilation, transposed, output_padding, groups, grad_input_mask) : std::tuple()" + result: _convolution_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, stride, padding, dilation, transposed, output_padding, groups, benchmark, deterministic, cudnn_enabled, allow_tf32) + +- name: convolution_backward(Tensor grad_output, Tensor input, Tensor weight, SymInt[]? bias_sizes, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) + grad_output, input, weight: _convolution_double_backward_symint(grads[0], grads[1], grads[2], grad_output, weight, input, stride, padding, dilation, transposed, output_padding, groups, grad_input_mask) + result0: std::get<0>(convolution_backward_symint(grad_output_p, input_p, weight_t, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, {true, false, false})) + std::get<0>(convolution_backward_symint(grad_output_t, input_p, weight_p, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, {true, false, false})) + result1: std::get<1>(convolution_backward_symint(grad_output_p, input_t, weight_p, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, {false, true, false})) + std::get<1>(convolution_backward_symint(grad_output_t, input_p, weight_p, bias_sizes, stride, padding, dilation, transposed, output_padding, groups, {false, true, false})) + result2: convolution_backward_jvp_grad_bias(grad_output_t, result2) + +- name: convolution_overrideable(Tensor input, Tensor weight, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups) -> Tensor + input, weight, bias: "grad.defined() ? convolution_backward_overrideable_symint(grad, input, weight, stride, padding, dilation, transposed, output_padding, groups, grad_input_mask) : std::tuple()" + +- name: convolution_backward_overrideable(Tensor grad_output, Tensor input, Tensor weight, SymInt[] stride, SymInt[] padding, SymInt[] dilation, bool transposed, SymInt[] output_padding, SymInt groups, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias) + grad_output, input, weight: _convolution_double_backward_symint(grads[0], grads[1], grads[2], grad_output, weight, input, stride, padding, dilation, transposed, output_padding, groups, grad_input_mask) + +- name: slow_conv_transpose2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt[2] dilation=1) -> Tensor + self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, true, output_padding, 1, grad_input_mask) : std::tuple()" + +- name: slow_conv_transpose3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] output_padding=0, SymInt[3] dilation=1) -> Tensor + self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, true, output_padding, 1, grad_input_mask) : std::tuple()" + +- name: _slow_conv2d_forward(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding) -> Tensor + self, weight, bias: "grad.defined() ? _slow_conv2d_backward_symint(grad, self, weight, kernel_size, stride, padding, grad_input_mask) : std::tuple()" + +- name: _slow_conv2d_backward.output_mask(Tensor grad_output, Tensor self, Tensor weight, SymInt[2] kernel_size, SymInt[2] stride, SymInt[2] padding, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias) + grad_output, self, weight: _convolution_double_backward_symint(grads[0], grads[1], grads[2], grad_output, weight, self, stride, padding, {{1, 1}}, false, {{0, 0}}, 1, grad_input_mask) + +- name: _conv_depthwise2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias, SymInt[2] stride, SymInt[2] padding, SymInt[2] dilation) -> Tensor + self, weight, bias: "grad.defined() ? convolution_backward_symint(grad.contiguous(), self, weight, bias->sym_sizes(), stride, padding, dilation, /*transposed=*/ false, /*output_padding=*/ {{0, 0}}, /*groups=*/ 1, grad_input_mask) : std::tuple()" + +- name: conv_depthwise3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding, SymInt[3] dilation) -> Tensor + self, weight, bias: "grad.defined() ? convolution_backward_symint(grad.contiguous(), self, weight, bias->sym_sizes(), stride, padding, dilation, /*transposed=*/ false, /*output_padding=*/ {{0, 0, 0}}, /*groups=*/ 1, grad_input_mask) : std::tuple()" + +- name: slow_conv3d_forward(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias, SymInt[3] stride, SymInt[3] padding) -> Tensor + self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, /*dilation=*/ {{1, 1, 1}}, false, /*output_padding=*/ {{0, 0, 0}}, 1, grad_input_mask) : std::tuple()" + +- name: slow_conv_dilated2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] dilation=1) -> Tensor + self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, false, std::vector(padding.size(), 0), 1, grad_input_mask) : std::tuple()" + +- name: slow_conv_dilated3d(Tensor self, Tensor weight, SymInt[3] kernel_size, Tensor? bias=None, SymInt[3] stride=1, SymInt[3] padding=0, SymInt[3] dilation=1) -> Tensor + self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, false, std::vector(padding.size(), 0), 1, grad_input_mask) : std::tuple()" + +- name: col2im(Tensor self, SymInt[2] output_size, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride) -> Tensor + self: im2col(grad, kernel_size, dilation, padding, stride) + result: auto_linear + +- name: im2col(Tensor self, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride) -> Tensor + self: col2im_symint(grad, {self.sym_size(-2), self.sym_size(-1)}, kernel_size, dilation, padding, stride) + result: auto_linear + +- name: _adaptive_avg_pool2d_backward(Tensor grad_output, Tensor self) -> Tensor + grad_output: _adaptive_avg_pool2d_symint(grad, {grad_output.sym_size(-2), grad_output.sym_size(-1)}) + self: zeros_like(self) + result: _adaptive_avg_pool2d_backward(grad_output_t, self_p) + +- name: _adaptive_avg_pool3d_backward(Tensor grad_output, Tensor self) -> Tensor + grad_output: _adaptive_avg_pool3d_symint(grad, { grad_output.sym_size(-3), grad_output.sym_size(-2), grad_output.sym_size(-1) }) + self: zeros_like(self) + result: _adaptive_avg_pool3d_backward(grad_output_t, self_p) + +- name: adaptive_max_pool2d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor + grad_output: max_pool_double_backward(grad, indices, 2) + self: zeros_like(self) + result: auto_linear + +- name: adaptive_max_pool3d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor + grad_output: max_pool_double_backward(grad, indices, 3) + self: zeros_like(self) + result: auto_linear + +- name: avg_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor + grad_output: avg_pool2d(grad, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override) + self: zeros_like(self) + result: avg_pool2d_backward(grad_output_t, self_p, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override) + +- name: avg_pool3d_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor + grad_output: avg_pool3d(grad, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override) + self: zeros_like(self) + result: avg_pool3d_backward(grad_output_t, self_p, kernel_size, stride, padding, ceil_mode, count_include_pad, divisor_override) + +- name: elu_backward(Tensor grad_output, Scalar alpha, Scalar scale, Scalar input_scale, bool is_result, Tensor self_or_result) -> Tensor + grad_output: elu_backward(grad, alpha, scale, input_scale, is_result, self_or_result) + self_or_result: elu_double_backward(grad, grad_output, alpha, scale, input_scale, is_result, self_or_result) + result: elu_backward(grad_output_t, alpha, scale, input_scale, is_result, self_or_result_p) + elu_double_backward(self_or_result_t, grad_output_p, alpha, scale, input_scale, is_result, self_or_result_p) + +- name: fractional_max_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] output_size, Tensor indices) -> Tensor + grad_output: max_pool_double_backward(grad, indices, 2) + self: zeros_like(self) + result: auto_linear + +- name: fractional_max_pool3d_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] output_size, Tensor indices) -> Tensor + grad_output: max_pool_double_backward(grad, indices, 3) + self: zeros_like(self) + result: auto_linear + +- name: glu_backward(Tensor grad_output, Tensor self, int dim) -> Tensor + grad_output: glu_double_backward_grad_output(grad, self, dim) + self: glu_double_backward(grad, grad_output, self, dim) + result: glu_backward_jvp(result, grad_output_p, self_p, grad_output_t, self_t, dim) + +- name: hardtanh_backward(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val) -> Tensor + grad_output: hardtanh_backward(grad, self, min_val, max_val) + self: zeros_like(grad) + result: at::where((self_p > min_val).logical_and(self_p < max_val), grad_output_t, at::zeros({}, result.options()).expand_as(result)) + +- name: log_sigmoid_backward(Tensor grad_output, Tensor self, Tensor buffer) -> Tensor + grad_output: log_sigmoid_backward(grad, self, buffer) + self: log_sigmoid_double_backward(grad * grad_output, self) + result: log_sigmoid_backward(grad_output_t, self_p, buffer) + log_sigmoid_double_backward(self_t * grad_output_p, self_p) + +- name: _log_softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor + grad_output: grad.to(output.dtype()) - (grad.to(output.dtype()) * output.exp()).sum(dim, true) + output: (-grad_output.sum(dim, true) * output.exp() * grad.to(output.dtype())).to(output.dtype()) + +- name: leaky_relu_backward(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result) -> Tensor + # self_is_result is always false here since double backward call is an out-of-place call, self is input itself + grad_output: leaky_relu_backward(grad, self, negative_slope, false) + self: zeros_like(grad) + # leaky_relu_backward(grad_output, self, negative_slope, false) + # computes grad_output * at::where(self_p > 0, 1, negative_slope) + # so the jvp formula is the following: + # grad_output_t * at::where(self_p > 0, self_p.new_ones([]), negative_slope); + # + # leaky_relu_backward(grad_output, result, negative_slope, true) + # computes grad_output * at::where(result > 0, 1, negative_slope) + # under the assumption that `negative_slope` is positive (otherwise, + # it is not possible to compute the gradient). + # + # so the jvp formula is the following: + # grad_output_t * at::where(result_p > 0, result_p.new_ones([]), negative_slope); + # with the assumption that negative_slope is positive. + # + # Combined together that results in the following optimized kernel which + # also checks the assumption that negative_slope is positive when self_is_result + # is True: + result: leaky_relu_backward(grad_output_t, self_p, negative_slope, self_is_result) + +# This derivative is mps-only, and `error_for_max_pool2d_double_backward` just raises an error. +- name: max_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor + grad_output: error_for_max_pool2d_double_backward() + self: zeros_like(self) + result: auto_linear + +- name: max_pool2d_with_indices_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, bool ceil_mode, Tensor indices) -> Tensor + grad_output: max_pool_double_backward(grad, indices, 2) + self: zeros_like(self) + indices: non_differentiable + result: auto_linear + +- name: max_pool3d_with_indices_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, int[3] dilation, bool ceil_mode, Tensor indices) -> Tensor + grad_output: max_pool_double_backward(grad, indices, 3) + self: zeros_like(self) + indices: non_differentiable + result: auto_linear + +- name: mse_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction) -> Tensor + grad_output: mse_loss_backward(grad, self, target, reduction) + self: mse_loss_double_backward(grad * grad_output, self, reduction) + target: -mse_loss_double_backward(grad * grad_output, target, reduction) + result: " mse_loss_double_backward(self_t * grad_output_p, self_p, reduction) + - mse_loss_double_backward(target_t * grad_output_p, target_p, reduction) + + mse_loss_backward(grad_output_t, self_p, target_p, reduction) + " + +- name: nll_loss_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor + grad_output: nll_loss_symint(grad, target, weight, reduction, ignore_index) + self: zeros_like(grad) + target: non_differentiable + +- name: nll_loss2d_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, SymInt ignore_index, Tensor total_weight) -> Tensor + grad_output: nll_loss2d_symint(grad, target, weight, reduction, ignore_index) + self: zeros_like(grad) + target: non_differentiable + +- name: rrelu_with_noise_backward(Tensor grad_output, Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, bool self_is_result) -> Tensor + # self_is_result is always false here since double backward call is an out-of-place call, self is input itself + grad_output: rrelu_with_noise_backward(grad, self, noise, lower, upper, training, false) + self: zeros_like(grad) + result: rrelu_with_noise_backward(grad_output_t, self_p, noise, lower, upper, training, false) + +- name: reflection_pad1d_backward(Tensor grad_output, Tensor self, SymInt[2] padding) -> Tensor + grad_output: reflection_pad1d_symint(grad, padding) + self: zeros_like(self) + result: reflection_pad1d_backward_symint(grad_output_t, self_p, padding) + +- name: reflection_pad2d_backward(Tensor grad_output, Tensor self, SymInt[4] padding) -> Tensor + grad_output: reflection_pad2d_symint(grad, padding) + self: zeros_like(self) + result: reflection_pad2d_backward_symint(grad_output_t, self_p, padding) + +- name: reflection_pad3d_backward(Tensor grad_output, Tensor self, SymInt[6] padding) -> Tensor + grad_output: reflection_pad3d_symint(grad, padding) + self: zeros_like(self) + result: reflection_pad3d_backward_symint(grad_output_t, self_p, padding) + +- name: replication_pad1d_backward(Tensor grad_output, Tensor self, SymInt[2] padding) -> Tensor + grad_output: replication_pad1d_symint(grad, padding) + self: zeros_like(self) + result: replication_pad1d_backward_symint(grad_output_t, self_p, padding) + +- name: replication_pad2d_backward(Tensor grad_output, Tensor self, SymInt[4] padding) -> Tensor + grad_output: replication_pad2d_symint(grad, padding) + self: zeros_like(self) + result: replication_pad2d_backward_symint(grad_output_t, self_p, padding) + +- name: replication_pad3d_backward(Tensor grad_output, Tensor self, SymInt[6] padding) -> Tensor + grad_output: replication_pad3d_symint(grad, padding) + self: zeros_like(self) + result: replication_pad3d_backward_symint(grad_output_t, self_p, padding) + +- name: sparse_sampled_addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + self, mat1, mat2: "sparse_sampled_addmm_backward(grad, + self, + wrap_opt_if(mat1, grad_input_mask[2]), + wrap_opt_if(mat2, grad_input_mask[1]), + alpha, beta, grad_input_mask)" + +- name: _sparse_mm_reduce_impl(Tensor self, Tensor other, str reduce) -> (Tensor, Tensor) + output_differentiability: [True, False] + self, other: "grad.defined() ? _sparse_mm_reduce_impl_backward(self, grad, other, reduce, result1, grad_input_mask) : std::tuple()" + +- name: smooth_l1_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, float beta) -> Tensor + grad_output: smooth_l1_loss_backward(grad, self, target, reduction, beta) + self: smooth_l1_loss_double_backward(grad * grad_output, self, target, reduction, beta) + target: -smooth_l1_loss_double_backward(grad * grad_output, self, target, reduction, beta) + result: " smooth_l1_loss_double_backward(self_t * grad_output_p, self_p, target_p, reduction, beta) + - smooth_l1_loss_double_backward(target_t * grad_output_p, self_p, target_p, reduction, beta) + + smooth_l1_loss_backward(grad_output_t, self_p, target_p, reduction, beta) + " + +- name: huber_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, float delta) -> Tensor + grad_output: huber_loss_double_backward_grad_output(grad, grad_output, self, target, reduction, delta) + self: huber_loss_double_backward(grad * grad_output, self, target, reduction, delta) + target: -huber_loss_double_backward(grad * grad_output, self, target, reduction, delta) + +- name: softplus_backward(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold) -> Tensor + grad_output: softplus_backward(grad, self, beta, threshold) + self: softplus_double_backward(grad * grad_output, self, beta, threshold) + result: "softplus_backward(grad_output_t, self_p, beta, threshold) + + softplus_double_backward(self_t * grad_output_p, self_p, beta, threshold)" + +- name: _softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor + grad_output: _softmax_backward_data(grad.to(output.dtype()), output, dim, input_dtype) + output: softmax_double_backward(grad.to(output.dtype()), grad_output, dim, output).to(output.dtype()) + +- name: soft_margin_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction) -> Tensor + grad_output: soft_margin_loss_double_backward_grad_output(grad, grad_output, self, target, reduction) + self: soft_margin_loss_double_backward(grad * grad_output, self, target, reduction) + +- name: softshrink_backward(Tensor grad_output, Tensor self, Scalar lambd) -> Tensor + grad_output: softshrink_backward(grad, self, lambd) + self: zeros_like(grad) + result: at::where((self_p > lambd).logical_or(self_p < -lambd), grad_output_t, at::zeros({}, result.options()).expand_as(result)) + +- name: threshold_backward(Tensor grad_output, Tensor self, Scalar threshold) -> Tensor + grad_output: threshold_backward(grad, self, threshold) + self: zeros_like(grad) + result: zeros_like(self_t) + threshold_backward(grad_output_t, self_p, threshold) + +- name: upsample_linear1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, bool align_corners, float? scales=None) -> Tensor + grad_output: upsample_linear1d_symint(grad, output_size, align_corners, scales) + result: auto_linear + +- name: upsample_bilinear2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + grad_output: upsample_bilinear2d_symint(grad, output_size, align_corners, scales_h, scales_w) + result: auto_linear + +- name: _upsample_bilinear2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + grad_output: _upsample_bilinear2d_aa_symint(grad, output_size, align_corners, scales_h, scales_w) + result: auto_linear + +- name: upsample_bicubic2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + grad_output: upsample_bicubic2d_symint(grad, output_size, align_corners, scales_h, scales_w) + result: auto_linear + +- name: _upsample_bicubic2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + grad_output: _upsample_bicubic2d_aa_symint(grad, output_size, align_corners, scales_h, scales_w) + result: auto_linear + +- name: _upsample_lanczos2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + grad_output: _upsample_lanczos2d_aa_symint(grad, output_size, align_corners, scales_h, scales_w) + result: auto_linear + +- name: upsample_trilinear3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor + grad_output: upsample_trilinear3d_symint(grad, output_size, align_corners, scales_d, scales_h, scales_w) + result: auto_linear + +- name: upsample_nearest1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None) -> Tensor + grad_output: upsample_nearest1d_symint(grad, output_size, scales) + result: auto_linear + +- name: _upsample_nearest_exact1d_backward(Tensor grad_output, SymInt[1] output_size, SymInt[3] input_size, float? scales=None) -> Tensor + grad_output: _upsample_nearest_exact1d_symint(grad, output_size, scales) + result: auto_linear + +- name: upsample_nearest2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None) -> Tensor + grad_output: upsample_nearest2d_symint(grad, output_size, scales_h, scales_w) + result: auto_linear + +- name: _upsample_nearest_exact2d_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, float? scales_h=None, float? scales_w=None) -> Tensor + grad_output: _upsample_nearest_exact2d_symint(grad, output_size, scales_h, scales_w) + result: auto_linear + +- name: upsample_nearest3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor + grad_output: upsample_nearest3d_symint(grad, output_size, scales_d, scales_h, scales_w) + result: auto_linear + +- name: _upsample_nearest_exact3d_backward(Tensor grad_output, SymInt[3] output_size, SymInt[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor + grad_output: _upsample_nearest_exact3d_symint(grad, output_size, scales_d, scales_h, scales_w) + result: auto_linear + +- name: sigmoid_backward(Tensor grad_output, Tensor output) -> Tensor + grad_output: sigmoid_backward(grad, output.conj()) + output: grad.conj() * grad_output * (-2 * output.conj() + 1) + result: sigmoid_backward(grad_output_t, output_p) + output_t.conj() * grad_output_p * (-2 * output_p.conj() + 1) + +- name: tanh_backward(Tensor grad_output, Tensor output) -> Tensor + grad_output: tanh_backward(grad, output.conj()) + output: grad.conj() * (-2 * output.conj() * grad_output) + result: tanh_backward(grad_output_t, output_p) + output_t.conj() * (-2 * output_p.conj() * grad_output_p) + +# cudnn +- name: _cudnn_ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor) + log_probs: _cudnn_ctc_loss_backward(grad, result0, result1, zero_infinity) + +- name: _cudnn_ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor) + log_probs: _cudnn_ctc_loss_backward(grad, result0, result1, zero_infinity) + +- name: cudnn_convolution_transpose(Tensor self, Tensor weight, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor + self, weight: "_cudnn_convolution_backward(self, grad, weight, padding, output_padding, stride, dilation, true, groups, {grad_input_mask[0], grad_input_mask[1]})" + +- name: _mps_convolution_transpose(Tensor self, Tensor weight, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor + self, weight: "grad.defined() ? mps_convolution_transpose_backward_symint(self, grad, weight, padding, output_padding, stride, dilation, groups, grad_input_mask) : std::tuple()" + +- name: cudnn_convolution(Tensor self, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor + self, weight: "_cudnn_convolution_backward(self, grad, weight, padding, std::vector(padding.size(), 0), stride, dilation, false, groups, {grad_input_mask[0], grad_input_mask[1]})" + +- name: cudnn_grid_sampler(Tensor self, Tensor grid) -> Tensor output + self, grid: "grad.defined() ? cudnn_grid_sampler_backward(self, grid, grad) : std::tuple()" + +- name: cudnn_grid_sampler_backward(Tensor self, Tensor grid, Tensor grad_output) -> (Tensor grad_self, Tensor grad_grid) + grad_output, self, grid: grid_sampler_2d_double_backward(grads[0], grads[1], grad_output, self, grid, 0, 0, true, grad_input_mask) + +- name: cudnn_affine_grid_generator(Tensor theta, int N, int C, int H, int W) -> Tensor grid + theta: cudnn_affine_grid_generator_backward(grad, N, C, H, W) + +# NB: Why is the backwards here so complicated? CuDNN cannot be used to compute +# backward in evaluation mode, because the math for backward in evaluation mode +# is different (since the forward math is different), and CuDNN does not support +# it. And in any case, you shouldn't be using this bn in evaluation mode, +# because it should be merged into the previous convolution (left for future +# work.) +# NB2: The quotes around the gradient are needed to appease YAML parsing rules. +- name: cudnn_batch_norm(Tensor input, Tensor weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float exponential_average_factor, float epsilon) -> (Tensor, Tensor, Tensor, Tensor) + input, weight, bias: "grad.defined() ? (training ? cudnn_batch_norm_backward(input, grad.contiguous(input.suggest_memory_format()), weight, running_mean, running_var, result1, result2, epsilon, retain_variables ? result3.clone() : result3) : native_batch_norm_backward(grad, input, weight, running_mean, running_var, result1, result2, training, epsilon, grad_input_mask)) : std::tuple()" + result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, running_mean, running_var, result1, result2, training, epsilon) + +# HACK: save_mean and save_var are going to be passed in as +# requires_grad variables (even though we'll never backprop through +# them) so we need to prevent the unpacking from triggering an error. +- name: cudnn_batch_norm_backward(Tensor input, Tensor grad_output, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, float epsilon, Tensor reserveSpace) -> (Tensor, Tensor, Tensor) + save_mean: not_implemented("cudnn_batch_norm_backward save_mean") + save_var: not_implemented("cudnn_batch_norm_backward save_var") + reserveSpace: not_implemented("cudnn_batch_norm_backward reserveSpace") + input, weight, grad_output: batchnorm_double_backward(input, weight, grads[0], grads[1], grads[2], grad_output, running_mean, running_var, true, epsilon, save_mean, save_var, grad_input_mask) + +# nnpack + +- name: _nnpack_spatial_convolution(Tensor input, Tensor weight, Tensor? bias, SymInt[2] padding, SymInt[2] stride=1) -> Tensor + # NNPACK does not support strided convolutions in the backwards path, which is the reason why we are using the closest available function that does here. + input, weight, bias: "grad.defined() ? convolution_backward_symint(grad, input, weight, bias->sym_sizes(), stride, padding, std::vector(padding.size(), 1), false, std::vector(padding.size(), 0), 1, grad_input_mask) : std::tuple()" + +#LSTM MPS +- name: _lstm_mps(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor) + output_differentiability: [True, True, True, False, False, False] + input, hx, params: "lstm_mps_backward(grads[0], grads[1], grads[2], result3, result4, input, result5, hx, params, has_biases, num_layers, dropout, train, bidirectional, batch_first)" + +- name: lstm_mps_backward(Tensor? grad_y, Tensor? grad_hy, Tensor? grad_cy, Tensor z_state, Tensor cell_state_fwd, Tensor input, Tensor layersOutputs, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor[], Tensor[]) + + + +# Only frst three of _cudnn_rnn outputs can have gradients. +# _cudnn_rnn outputs: (output, hy, cy, reserve, weight_buf) +- name: _cudnn_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor? weight_buf, Tensor hx, Tensor? cx, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor) + dropout_state: non_differentiable + output_differentiability: [True, True, True, False, False] + input, hx, cx, weight: "_cudnn_rnn_backward_symint(input, weight, weight_stride0, result4, hx, cx, result0, grads[0], grads[1], grads[2], mode, hidden_size, proj_size, num_layers, batch_first, dropout, train, bidirectional, batch_sizes, dropout_state, retain_variables ? result3.clone() : result3, grad_input_mask)" + +- name: _cudnn_rnn_backward(Tensor input, Tensor[] weight, int weight_stride0, Tensor weight_buf, Tensor hx, Tensor? cx, Tensor output, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, int mode, SymInt hidden_size, SymInt proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, SymInt[] batch_sizes, Tensor? dropout_state, Tensor reserve, bool[4] output_mask) -> (Tensor, Tensor, Tensor, Tensor[]) + dropout_state: non_differentiable + input: not_implemented("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg) + weight: not_implemented_list("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg) + hx: not_implemented("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg) + cx: not_implemented("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg) + output: not_implemented("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg) + grad_output: not_implemented("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg) + grad_hy: not_implemented("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg) + grad_cy: not_implemented("_cudnn_rnn_backward", kCudnnDoubleBackwardMsg) + +# miopen + +- name: miopen_convolution_transpose(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] output_padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor + self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, true, output_padding, groups, grad_input_mask) : std::tuple()" + +- name: miopen_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor + self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, false, std::vector(padding.size(), 0), groups, grad_input_mask) : std::tuple()" + +- name: miopen_depthwise_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic) -> Tensor + self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, false, std::vector(padding.size(), 0), groups, grad_input_mask) : std::tuple()" + +- name: miopen_batch_norm(Tensor input, Tensor weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float exponential_average_factor, float epsilon) -> (Tensor, Tensor, Tensor) + input, weight, bias: "grad.defined() ? (training ? miopen_batch_norm_backward(input, grad.contiguous(input.suggest_memory_format()), weight, running_mean, running_var, result1, result2, epsilon) : native_batch_norm_backward(grad, input, weight, running_mean, running_var, result1, result2, training, epsilon, grad_input_mask)) : std::tuple()" + result0: batch_norm_jvp(input_p, input_t, weight_p, weight_t, bias_p, bias_t, running_mean, running_var, result1, result2, training, epsilon) + +- name: miopen_batch_norm_backward(Tensor input, Tensor grad_output, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, float epsilon) -> (Tensor, Tensor, Tensor) + save_mean: not_implemented("miopen_batch_norm_backward save_mean") + save_var: not_implemented("miopen_batch_norm_backward save_var") + input, weight, grad_output: batchnorm_double_backward(input, weight, grads[0], grads[1], grads[2], grad_output, running_mean, running_var, true, epsilon, save_mean, save_var, grad_input_mask) + +- name: miopen_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor hx, Tensor? cx, int mode, int hidden_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor) + dropout_state: non_differentiable + output_differentiability: [True, True, True, False, False] + input, hx, cx, weight: "miopen_rnn_backward(input, weight, weight_stride0, result4, hx, cx, result0, grads[0], grads[1], grads[2], mode, hidden_size, num_layers, batch_first, dropout, train, bidirectional, batch_sizes, dropout_state, retain_variables ? result3.clone() : result3, grad_input_mask)" + +- name: miopen_rnn_backward(Tensor input, Tensor[] weight, int weight_stride0, Tensor weight_buf, Tensor hx, Tensor? cx, Tensor output, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, int mode, int hidden_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state, Tensor reserve, bool[4] output_mask) -> (Tensor, Tensor, Tensor, Tensor[]) + dropout_state: non_differentiable + +- name: miopen_ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor) + log_probs: _miopen_ctc_loss_backward(grad, result0, result1, zero_infinity) + +- name: miopen_ctc_loss.Tensor(Tensor log_probs, Tensor targets, Tensor input_lengths, Tensor target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor) + log_probs: _miopen_ctc_loss_backward(grad, result0, result1, zero_infinity) + +- name: mkldnn_rnn_layer(Tensor input, Tensor weight0, Tensor weight1, Tensor weight2, Tensor weight3, Tensor hx_, Tensor cx_, bool reverse, int[] batch_sizes, int mode, int hidden_size, int num_layers, bool has_biases, bool bidirectional, bool batch_first, bool train) -> (Tensor, Tensor, Tensor, Tensor) + output_differentiability: [True, True, True, False] + input, weight0, weight1, weight2, weight3, hx_, cx_: "GradMode::is_enabled() ? mkldnn_rnn_layer_differentiable_backward(input, weight0, weight1, weight2, weight3, hx_, cx_, result0, result1, result2, grads[0], grads[1], grads[2], reverse, mode, hidden_size, num_layers, has_biases, train, bidirectional, batch_sizes, batch_first, result3) : mkldnn_rnn_layer_backward(input, weight0, weight1, weight2, weight3, hx_, cx_, result0, result1, result2, grads[0], grads[1], grads[2], reverse, mode, hidden_size, num_layers, has_biases, train, bidirectional, batch_sizes, batch_first, result3)" + +- name: mkldnn_rnn_layer_backward(Tensor input, Tensor weight1, Tensor weight2, Tensor weight3, Tensor weight4, Tensor hx_, Tensor cx_tmp, Tensor output, Tensor hy_, Tensor cy_, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, bool reverse, int mode, int hidden_size, int num_layers, bool has_biases, bool train, bool bidirectional, int[] batch_sizes, bool batch_first, Tensor workspace) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor) + +# mkldnn +- name: mkldnn_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor + self, weight, bias: "grad.defined() ? convolution_backward_symint(grad, self, weight, bias->sym_sizes(), stride, padding, dilation, /*transposed=*/ false, /*output_padding=*/ std::vector(padding.size(), 0), groups, grad_input_mask) : std::tuple()" + +- name: mkldnn_linear(Tensor self, Tensor weight, Tensor? bias=None) -> Tensor + self, weight, bias: mkldnn_linear_backward(self, grad, weight, grad_input_mask) + +- name: mkldnn_max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor + self: mkldnn_max_pool2d_backward(grad, result, self, kernel_size, stride, padding, dilation, ceil_mode) + +- name: mkldnn_max_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor + self: mkldnn_max_pool3d_backward(grad, result, self, kernel_size, stride, padding, dilation, ceil_mode) + +- name: mkldnn_adaptive_avg_pool2d(Tensor self, int[2] output_size) -> Tensor + self: mkldnn_adaptive_avg_pool2d_backward(grad, self) + +- name: _mkldnn_reshape(Tensor self, int[] shape) -> Tensor + self: grad.reshape_symint(self.sym_sizes()) + +# NestedTensor +- name: _nested_tensor_from_tensor_list(Tensor[] list, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + list: "grad.defined()? at::unbind(grad) : std::vector(list.size())" + +- name: _nested_tensor_from_mask(Tensor t, Tensor mask, bool mask_check=True) -> Tensor + t: grad.to_padded_tensor_symint(0, t.sym_sizes()) + mask: non_differentiable + +- name: _nested_from_padded(Tensor padded, Tensor cpu_nested_shape_example, bool fuse_transform_0213=False) -> Tensor + padded: _nested_from_padded_backward(grad, padded, fuse_transform_0213) + cpu_nested_shape_example: non_differentiable + +- name: to_padded_tensor(Tensor self, float padding, SymInt[]? output_size=None) -> Tensor + self: "self.layout() == c10::kJagged ? at::_nested_from_padded_tensor_symint(grad, at::_nested_get_offsets(self), at::_nested_get_jagged_dummy(self), at::_nested_get_ragged_idx(self), at::_nested_get_min_seqlen(self).defined() ? std::optional(at::_nested_get_min_seqlen(self)) : ::std::nullopt, at::_nested_get_max_seqlen(self).defined() ? std::optional(at::_nested_get_max_seqlen(self)) : ::std::nullopt, std::optional(at::_nested_get_values(self).sym_size(0))) : at::_nested_from_padded(grad, self._nested_tensor_size())" + padding: non_differentiable + +- name: _nested_from_padded_tensor(Tensor padded, Tensor offsets, Tensor dummy, int ragged_idx=1, Tensor? min_seqlen=None, Tensor? max_seqlen=None, SymInt? sum_S=None) -> Tensor + padded: grad.to_padded_tensor_symint(0.0, at::OptionalArrayRef(padded.sym_sizes())) + offsets: non_differentiable + dummy: non_differentiable + +- name: _nested_view_from_buffer(Tensor(a) self, Tensor nested_size, Tensor nested_strides, Tensor offsets) -> Tensor(a) + self: grad.values() + nested_size: non_differentiable + nested_strides: non_differentiable + +- name: _nested_view_from_jagged(Tensor(a) self, Tensor offsets, Tensor dummy, Tensor? lengths=None, int ragged_idx=1, Tensor? min_seqlen=None, Tensor? max_seqlen=None) -> Tensor(a) + self: grad.values() + offsets: non_differentiable + lengths: non_differentiable + dummy: non_differentiable + min_seqlen: non_differentiable + max_seqlen: non_differentiable + +- name: _nested_get_values(Tensor(a) self) -> Tensor(a) + self: "_nested_view_from_jagged(grad, at::_nested_get_offsets(self), at::_nested_get_jagged_dummy(self), at::_nested_get_lengths(self), at::_nested_get_ragged_idx(self), at::_nested_get_min_seqlen(self).defined() ? std::optional(at::_nested_get_min_seqlen(self)) : ::std::nullopt, at::_nested_get_max_seqlen(self).defined() ? std::optional(at::_nested_get_max_seqlen(self)) : ::std::nullopt)" + +# Transformer +- name: _safe_softmax(Tensor self, int dim, ScalarType? dtype=None) -> Tensor + self: _softmax_backward_data(grad, result, dim, self.scalar_type()) + result: result * (self_t - safe_logsumexp_jvp(self_p, self_t, {dim}, true)) + +- name: _scaled_dot_product_efficient_attention(Tensor query, Tensor key, Tensor value, Tensor? attn_bias, bool compute_log_sumexp, float dropout_p=0.0, bool is_causal=False, *, float? scale=None) -> (Tensor output, Tensor log_sumexp, Tensor philox_seed, Tensor philox_offset) + output_differentiability: [True, False, False, False] + query, key, value, attn_bias: _scaled_dot_product_efficient_attention_backward(grad, query, key, value, attn_bias, output, log_sumexp, philox_seed, philox_offset, dropout_p, grad_input_mask, is_causal, scale) + +- name: _scaled_dot_product_flash_attention(Tensor query, Tensor key, Tensor value, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor rng_state, Tensor unused, Tensor debug_attn_mask) + output_differentiability: [True, False, False, False, False, False, False, False, False] + query, key, value: _scaled_dot_product_flash_attention_backward_symint(grad, query, key, value, output, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, rng_state, unused, scale) + +- name: _scaled_dot_product_flash_attention_for_cpu(Tensor query, Tensor key, Tensor value, float dropout_p=0.0, bool is_causal=False, *, Tensor? attn_mask=None, float? scale=None) -> (Tensor output, Tensor logsumexp) + output_differentiability: [True, False] + query, key, value: _scaled_dot_product_flash_attention_for_cpu_backward(grad, query, key, value, output, logsumexp, dropout_p, is_causal, attn_mask, scale) + +- name: _flash_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, bool return_debug_mask, *, float? scale=None, SymInt? window_size_left=None, SymInt? window_size_right=None, Tensor? seqused_k=None, Tensor? alibi_slopes=None, Tensor? block_table=None, int? num_splits=None) -> (Tensor output, Tensor softmax_logsumexp, Tensor rng_state, Tensor unused, Tensor debug_attn_mask) + output_differentiability: [True, False, False, False, False] + query, key, value: _flash_attention_backward_symint(grad, query, key, value, output, softmax_logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, rng_state, unused, scale, window_size_left, window_size_right) + +- name: _efficient_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? bias, Tensor? cu_seqlens_q, Tensor? cu_seqlens_k, SymInt? max_seqlen_q, SymInt? max_seqlen_k, float dropout_p, int custom_mask_type, bool compute_log_sumexp=False, *, float? scale=None, Tensor? seqlen_k=None, int? window_size=None) -> (Tensor output, Tensor logsumexp, Tensor philox_seed, Tensor philox_offset, SymInt max_seqlen_batch_q, SymInt max_seqlen_batch_k) + output_differentiability: [True, False, False, False, False, False] + query, key, value, bias: _efficient_attention_backward_symint(grad, query, key, value, bias, output, cu_seqlens_q, cu_seqlens_k, max_seqlen_batch_q, max_seqlen_batch_k, logsumexp, dropout_p, philox_seed, philox_offset, custom_mask_type, bias.requires_grad(), scale) + +- name: _cudnn_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? attn_bias, Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, bool compute_log_sumexp, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None, Tensor? seqused_k=None, Tensor? block_table=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask) + output_differentiability: [True, False, False, False, False, False, False, False, False] + query, key, value: _cudnn_attention_backward_symint(grad, query, key, value, output, logsumexp, philox_seed, philox_offset, attn_bias, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, scale) + +- name: _scaled_dot_product_cudnn_attention(Tensor query, Tensor key, Tensor value, Tensor? attn_bias, bool compute_log_sumexp, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask) + output_differentiability: [True, False, False, False, False, False, False, False, False] + query, key, value: _scaled_dot_product_cudnn_attention_backward_symint(grad, query, key, value, output, logsumexp, philox_seed, philox_offset, attn_bias, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, scale) + +- name: _scaled_dot_product_fused_attention_overrideable(Tensor query, Tensor key, Tensor value, Tensor? attn_bias=None, float dropout_p=0.0, bool is_causal=False, bool return_debug_mask=False, *, float? scale=None) -> (Tensor output, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask) + output_differentiability: [True, False, False, False, False, False, False, False, False] + query, key, value, attn_bias: _scaled_dot_product_fused_attention_overrideable_backward_symint(grad, query, key, value, attn_bias, grad_input_mask, output, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, philox_seed, philox_offset, scale) + +# fft +- name: _fft_r2c(Tensor self, int[] dim, int normalization, bool onesided) -> Tensor + self: fft_r2c_backward(grad, dim, normalization, onesided, self.sym_size(dim.back())) + result: auto_linear + +- name: _fft_c2r(Tensor self, int[] dim, int normalization, SymInt last_dim_size) -> Tensor + self: fft_c2r_backward(grad, dim, normalization) + result: auto_linear + +- name: _fft_c2c(Tensor self, SymInt[] dim, int normalization, bool forward) -> Tensor + self: _fft_c2c_symint(grad, dim, normalization, !forward) + result: auto_linear + +- name: unbind.int(Tensor(a -> *) self, int dim=0) -> Tensor(a)[] + dispatch: + Default: + self: unbind_backward(grads, dim) + result: auto_linear + AutogradNestedTensor: + self: "self.layout() == c10::kJagged ? unbind_backward_nested_jagged(grads, self, dim) : unbind_backward_nested(grads, at::native::get_nested_tensor_impl(self)->get_nested_sizes(), dim, self.options())" + result: auto_linear + +- name: stack(Tensor[] tensors, int dim=0) -> Tensor + tensors: stack_tensors_backward(grad, dim, to_args_scalartypes(tensors)) + result: stack_jvp(tensors, dim) + +# fused RNN kernels + +# Only frst two of _thnn_fused_lstm_cell outputs can have gradients. +# _thnn_fused_lstm_cell outputs: (hy, cy, workspace) +- name: _thnn_fused_lstm_cell(Tensor input_gates, Tensor hidden_gates, Tensor cx, Tensor? input_bias=None, Tensor? hidden_bias=None) -> (Tensor, Tensor, Tensor) + output_differentiability: [True, True, False] + input_gates, hidden_gates, cx, input_bias, hidden_bias: "GradMode::is_enabled() ? _thnn_differentiable_lstm_cell_backward(grads[0], grads[1], input_gates, hidden_gates, input_bias, hidden_bias, cx, result1) : _thnn_fused_lstm_cell_backward(grads[0], grads[1], cx, result1, result2, input_bias.defined())" + +- name: _thnn_fused_gru_cell(Tensor input_gates, Tensor hidden_gates, Tensor hx, Tensor? input_bias=None, Tensor? hidden_bias=None) -> (Tensor, Tensor) + input_gates, hidden_gates, hx, input_bias, hidden_bias: "grad.defined() ? (GradMode::is_enabled() ? _thnn_differentiable_gru_cell_backward(grad, input_gates, hidden_gates, hx, input_bias, hidden_bias) : _thnn_fused_gru_cell_backward(grad, result1, input_bias.defined())) : std::tuple()" + +# PackedSequence helpers +- name: _pack_padded_sequence(Tensor input, Tensor lengths, bool batch_first) -> (Tensor, Tensor) + input: _pack_padded_sequence_backward_symint(grad, input.sym_sizes(), result1, batch_first) + +# TH wrappers +- name: eq.Scalar(Tensor self, Scalar other) -> Tensor + output_differentiability: [False] + +- name: eq.Tensor(Tensor self, Tensor other) -> Tensor + output_differentiability: [False] + +- name: ge.Scalar(Tensor self, Scalar other) -> Tensor + output_differentiability: [False] + +- name: ge.Tensor(Tensor self, Tensor other) -> Tensor + output_differentiability: [False] + +- name: gt.Scalar(Tensor self, Scalar other) -> Tensor + output_differentiability: [False] + +- name: gt.Tensor(Tensor self, Tensor other) -> Tensor + output_differentiability: [False] + +- name: le.Scalar(Tensor self, Scalar other) -> Tensor + output_differentiability: [False] + +- name: le.Tensor(Tensor self, Tensor other) -> Tensor + output_differentiability: [False] + +- name: lt.Scalar(Tensor self, Scalar other) -> Tensor + output_differentiability: [False] + +- name: lt.Tensor(Tensor self, Tensor other) -> Tensor + output_differentiability: [False] + +- name: ne.Scalar(Tensor self, Scalar other) -> Tensor + output_differentiability: [False] + +- name: ne.Tensor(Tensor self, Tensor other) -> Tensor + output_differentiability: [False] + +- name: multinomial(Tensor self, SymInt num_samples, bool replacement=False, *, Generator? generator=None) -> Tensor + output_differentiability: [False] + +- name: nonzero(Tensor self) -> Tensor + output_differentiability: [False] + +- name: segment_reduce(Tensor data, str reduce, *, Tensor? lengths=None, Tensor? indices=None, Tensor? offsets=None, int axis=0, bool unsafe=False, Scalar? initial=None) -> Tensor + data: _segment_reduce_backward(grad, result, data, reduce, lengths, offsets, axis, initial) + +- name: _pin_memory(Tensor self, Device? device=None) -> Tensor + self: grad + +- name: _new_zeros_with_same_feature_meta(Tensor self, Tensor other, *, int self_num_batch_dims=0) -> Tensor + self: non_differentiable + other: non_differentiable + output_differentiability: [False] + +- name: _test_warn_in_autograd(Tensor self) -> Tensor + self: warn_backwards(grad) + +- name: _test_autograd_multiple_dispatch.fullcoverage(Tensor self) -> Tensor + dispatch: + Default: + self: grad.expand_symint(self.sym_sizes()) + 1 + result: auto_linear + AutogradNestedTensor: + self: grad.mul(grad) + AutogradCUDA: + self: grad.expand_symint(self.sym_sizes()) * 2 + +- name: _test_autograd_multiple_dispatch.ntonly(Tensor self, bool b) -> Tensor + dispatch: + AutogradNestedTensor: + self: grad.mul(grad).add(grad) + +- name: _test_autograd_multiple_dispatch_view(Tensor(a) self) -> Tensor(a) + dispatch: + Default: + self: grad.reshape_as(self) + AutogradCUDA: + self: grad.reshape_as(self) + 1 + +- name: _efficientzerotensor(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + output_differentiability: [False] + +- name: scatter_reduce.two(Tensor self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True) -> Tensor + self, src: scatter_reduce_backward(grad, self, dim, index, src, reduce, include_self, result) + index: non_differentiable + result: scatter_reduce_jvp(self_p, self_t, dim, index, src_p, src_t, reduce, include_self, result) + +- name: special_airy_ai(Tensor x) -> Tensor + x: non_differentiable + +- name: special_bessel_j0(Tensor self) -> Tensor + self: non_differentiable + +- name: special_bessel_j1(Tensor self) -> Tensor + self: non_differentiable + +- name: special_bessel_y0(Tensor self) -> Tensor + self: non_differentiable + +- name: special_bessel_y1(Tensor self) -> Tensor + self: non_differentiable + +- name: special_chebyshev_polynomial_t(Tensor x, Tensor n) -> Tensor + x: non_differentiable + n: non_differentiable + +- name: special_chebyshev_polynomial_t.x_scalar(Scalar x, Tensor n) -> Tensor + n: non_differentiable + +- name: special_chebyshev_polynomial_t.n_scalar(Tensor x, Scalar n) -> Tensor + x: non_differentiable + +- name: special_chebyshev_polynomial_u(Tensor x, Tensor n) -> Tensor + x: non_differentiable + n: non_differentiable + +- name: special_chebyshev_polynomial_u.x_scalar(Scalar x, Tensor n) -> Tensor + n: non_differentiable + +- name: special_chebyshev_polynomial_u.n_scalar(Tensor x, Scalar n) -> Tensor + x: non_differentiable + +- name: special_chebyshev_polynomial_v(Tensor x, Tensor n) -> Tensor + x: non_differentiable + n: non_differentiable + +- name: special_chebyshev_polynomial_v.x_scalar(Scalar x, Tensor n) -> Tensor + n: non_differentiable + +- name: special_chebyshev_polynomial_v.n_scalar(Tensor x, Scalar n) -> Tensor + x: non_differentiable + +- name: special_chebyshev_polynomial_w(Tensor x, Tensor n) -> Tensor + x: non_differentiable + n: non_differentiable + +- name: special_chebyshev_polynomial_w.x_scalar(Scalar x, Tensor n) -> Tensor + n: non_differentiable + +- name: special_chebyshev_polynomial_w.n_scalar(Tensor x, Scalar n) -> Tensor + x: non_differentiable + +- name: special_hermite_polynomial_h(Tensor x, Tensor n) -> Tensor + x: non_differentiable + n: non_differentiable + +- name: special_hermite_polynomial_h.x_scalar(Scalar x, Tensor n) -> Tensor + n: non_differentiable + +- name: special_hermite_polynomial_h.n_scalar(Tensor x, Scalar n) -> Tensor + x: non_differentiable + +- name: special_hermite_polynomial_he(Tensor x, Tensor n) -> Tensor + x: non_differentiable + n: non_differentiable + +- name: special_hermite_polynomial_he.x_scalar(Scalar x, Tensor n) -> Tensor + n: non_differentiable + +- name: special_hermite_polynomial_he.n_scalar(Tensor x, Scalar n) -> Tensor + x: non_differentiable + +- name: special_laguerre_polynomial_l(Tensor x, Tensor n) -> Tensor + x: non_differentiable + n: non_differentiable + +- name: special_laguerre_polynomial_l.x_scalar(Scalar x, Tensor n) -> Tensor + n: non_differentiable + +- name: special_laguerre_polynomial_l.n_scalar(Tensor x, Scalar n) -> Tensor + x: non_differentiable + +- name: special_legendre_polynomial_p(Tensor x, Tensor n) -> Tensor + x: non_differentiable + n: non_differentiable + +- name: special_legendre_polynomial_p.x_scalar(Scalar x, Tensor n) -> Tensor + n: non_differentiable + +- name: special_legendre_polynomial_p.n_scalar(Tensor x, Scalar n) -> Tensor + x: non_differentiable + +- name: special_modified_bessel_i0(Tensor self) -> Tensor + self: non_differentiable + +- name: special_modified_bessel_i1(Tensor self) -> Tensor + self: non_differentiable + +- name: special_modified_bessel_k0(Tensor self) -> Tensor + self: non_differentiable + +- name: special_modified_bessel_k1(Tensor self) -> Tensor + self: non_differentiable + +- name: special_scaled_modified_bessel_k0(Tensor x) -> Tensor + x: non_differentiable + +- name: special_scaled_modified_bessel_k1(Tensor x) -> Tensor + x: non_differentiable + +- name: special_shifted_chebyshev_polynomial_t(Tensor x, Tensor n) -> Tensor + x: non_differentiable + n: non_differentiable + +- name: special_shifted_chebyshev_polynomial_t.x_scalar(Scalar x, Tensor n) -> Tensor + n: non_differentiable + +- name: special_shifted_chebyshev_polynomial_t.n_scalar(Tensor x, Scalar n) -> Tensor + x: non_differentiable + +- name: special_shifted_chebyshev_polynomial_u(Tensor x, Tensor n) -> Tensor + x: non_differentiable + n: non_differentiable + +- name: special_shifted_chebyshev_polynomial_u.x_scalar(Scalar x, Tensor n) -> Tensor + n: non_differentiable + +- name: special_shifted_chebyshev_polynomial_u.n_scalar(Tensor x, Scalar n) -> Tensor + x: non_differentiable + +- name: special_shifted_chebyshev_polynomial_v(Tensor x, Tensor n) -> Tensor + x: non_differentiable + n: non_differentiable + +- name: special_shifted_chebyshev_polynomial_v.x_scalar(Scalar x, Tensor n) -> Tensor + n: non_differentiable + +- name: special_shifted_chebyshev_polynomial_v.n_scalar(Tensor x, Scalar n) -> Tensor + x: non_differentiable + +- name: special_shifted_chebyshev_polynomial_w(Tensor x, Tensor n) -> Tensor + x: non_differentiable + n: non_differentiable + +- name: special_shifted_chebyshev_polynomial_w.x_scalar(Scalar x, Tensor n) -> Tensor + n: non_differentiable + +- name: special_shifted_chebyshev_polynomial_w.n_scalar(Tensor x, Scalar n) -> Tensor + x: non_differentiable + +- name: special_spherical_bessel_j0(Tensor x) -> Tensor + x: non_differentiable + +- name: _reshape_copy(Tensor self, SymInt[] size) -> Tensor + self: grad.reshape_symint(self.sym_sizes()) + result: auto_linear + +- name: narrow_copy(Tensor self, int dim, SymInt start, SymInt length) -> Tensor + self: slice_backward_wrapper(grad, self.sym_sizes(), dim, start, start + length, 1) + result: auto_linear + +# note(crcrpar): `torchgen/api/autograd` logic would unwantedly replace substrings of `self` and `other` of function names. +- name: _foreach_div.List(Tensor[] self, Tensor[] other) -> Tensor[] + self: div_tensor_self_backward(grads[i], other[i], self[i].scalar_type()) + other: div_tensor_other_backward(grads[i], self[i], other[i]) + result: (self_t - other_t * result[i]) / other_p + +- name: _foreach_pow.List(Tensor[] self, Tensor[] exponent) -> Tensor[] + self: pow_backward_self(grads[i], self[i], exponent[i]) + exponent: pow_backward_exponent(grads[i], self[i], exponent[i], result[i]) + result: (pow_backward_self(self_t.conj(), self_p, exponent_p) + pow_backward_exponent(exponent_t.conj(), self_p, exponent_p, result[i])).conj() + +- name: _foreach_pow.ScalarList(Tensor[] self, Scalar[] exponent) -> Tensor[] + self: pow_backward(grads[i], self[i], exponent[i]) + result: pow_backward(self_t.conj(), self_p, exponent[i]).conj() + +- name: _foreach_pow.ScalarAndTensor(Scalar self, Tensor[] exponent) -> Tensor[] + exponent: pow_backward_exponent(grads[i], self, exponent[i], result[i]) + +# note(crcrpar): following definitions seem necessary because the reference native functions +# of `maximum` and `minimum` don't have the overload def with Scalar as their second argument. +- name: _foreach_minimum.Scalar(Tensor[] self, Scalar scalar) -> Tensor[] + self: at::where(self[i] == scalar, grads[i] / 2, grads[i]).masked_fill_(self[i] > scalar, 0) + result: scalar + at::where(self_p == scalar, at::scalar_tensor(0.5, result[i].options()), (self_p < scalar).to(result[i].scalar_type())) * (self_t - scalar) + +- name: _foreach_minimum.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[] + self: at::where(self[i] == scalars[i], grads[i] / 2, grads[i]).masked_fill_(self[i] > scalars[i], 0) + result: scalars[i] + at::where(self_p == scalars[i], at::scalar_tensor(0.5, result[i].options()), (self_p < scalars[i]).to(result[i].scalar_type())) * (self_t - scalars[i]) + +- name: _foreach_maximum.Scalar(Tensor[] self, Scalar scalar) -> Tensor[] + self: at::where(self[i] == scalar, grads[i] / 2, grads[i]).masked_fill_(self[i] < scalar, 0) + result: scalar + at::where(self_p == scalar, at::scalar_tensor(0.5, result[i].options()), (self_p > scalar).to(result[i].scalar_type())) * (self_t - scalar) + +- name: _foreach_maximum.ScalarList(Tensor[] self, Scalar[] scalars) -> Tensor[] + self: at::where(self[i] == scalars[i], grads[i] / 2, grads[i]).masked_fill_(self[i] < scalars[i], 0) + result: scalars[i] + at::where(self_p == scalars[i], at::scalar_tensor(0.5, result[i].options()), (self_p > scalars[i]).to(result[i].scalar_type())) * (self_t - scalars[i]) + +# note(crcrpar): forward-mode AD is tricky for a simple string replace to handle: +# formula.replace("p", "ord") produces `norm_jvord(self_ord, self_t, ord, result)` +- name: _foreach_norm.Scalar(Tensor[] self, Scalar ord=2, ScalarType? dtype=None) -> Tensor[] + self: norm_backward(grads[i], self[i], ord, result[i]) + result: norm_jvp(self_p, self_t, ord, result[i]) + +- name: _foreach_mm(Tensor[] self, Tensor[] mat2) -> Tensor[] + self: mm_mat1_backward(grads[i], mat2[i], self[i].sym_sizes(), self[i].sym_strides(), self[i].layout(), 1) + mat2: mm_mat2_backward(grads[i], self[i], mat2[i].sym_sizes(), mat2[i].sym_strides(), mat2[i].layout(), 1) diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_annotated_fn_args.py b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_annotated_fn_args.py new file mode 100644 index 0000000000000000000000000000000000000000..2f61209fa6fd0041b732f1400e1162d2f124ad34 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_annotated_fn_args.py @@ -0,0 +1,134 @@ +""" +For procedural tests needed for __torch_function__, we use this function +to export method names and signatures as needed by the tests in +test/test_overrides.py. + +python -m tools.autograd.gen_annotated_fn_args \ + aten/src/ATen/native/native_functions.yaml \ + aten/src/ATen/native/tags.yaml \ + $OUTPUT_DIR \ + tools/autograd + +Where $OUTPUT_DIR is where you would like the files to be +generated. In the full build system, OUTPUT_DIR is +torch/testing/_internal/generated +""" + +from __future__ import annotations + +import argparse +import os +import textwrap +from collections import defaultdict +from typing import Any, TYPE_CHECKING + +import torchgen.api.python as python +from torchgen.context import with_native_function +from torchgen.gen import parse_native_yaml +from torchgen.utils import FileManager + +from .gen_python_functions import ( + is_py_fft_function, + is_py_linalg_function, + is_py_nn_function, + is_py_special_function, + is_py_torch_function, + is_py_variable_method, + should_generate_py_binding, +) + + +if TYPE_CHECKING: + from collections.abc import Sequence + + from torchgen.model import Argument, BaseOperatorName, NativeFunction + + +def gen_annotated( + native_yaml_path: str, tags_yaml_path: str, out: str, autograd_dir: str +) -> None: + native_functions = parse_native_yaml( + native_yaml_path, tags_yaml_path + ).native_functions + mappings = ( + (is_py_torch_function, "torch._C._VariableFunctions"), + (is_py_nn_function, "torch._C._nn"), + (is_py_linalg_function, "torch._C._linalg"), + (is_py_special_function, "torch._C._special"), + (is_py_fft_function, "torch._C._fft"), + (is_py_variable_method, "torch.Tensor"), + ) + annotated_args: list[str] = [] + for pred, namespace in mappings: + groups: dict[BaseOperatorName, list[NativeFunction]] = defaultdict(list) + for f in native_functions: + if not should_generate_py_binding(f) or not pred(f): + continue + groups[f.func.name.name].append(f) + for group in groups.values(): + for f in group: + annotated_args.append(f"{namespace}.{gen_annotated_args(f)}") + + template_path = os.path.join(autograd_dir, "templates") + fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False) + fm.write_with_template( + "annotated_fn_args.py", + "annotated_fn_args.py.in", + lambda: { + "annotated_args": textwrap.indent("\n".join(annotated_args), " "), + }, + ) + + +@with_native_function +def gen_annotated_args(f: NativeFunction) -> str: + def _get_kwargs_func_exclusion_list() -> list[str]: + # functions that currently don't work with kwargs in test_overrides.py + return [ + "diagonal", + "round_", + "round", + "scatter_", + ] + + def _add_out_arg( + out_args: list[dict[str, Any]], args: Sequence[Argument], *, is_kwarg_only: bool + ) -> None: + for arg in args: + if arg.default is not None: + continue + out_arg: dict[str, Any] = {} + out_arg["is_kwarg_only"] = str(is_kwarg_only) + out_arg["name"] = arg.name + out_arg["simple_type"] = python.argument_type_str( + arg.type, simple_type=True + ) + size_t = python.argument_type_size(arg.type) + if size_t: + out_arg["size"] = size_t + out_args.append(out_arg) + + out_args: list[dict[str, Any]] = [] + _add_out_arg(out_args, f.func.arguments.flat_positional, is_kwarg_only=False) + if f"{f.func.name.name}" not in _get_kwargs_func_exclusion_list(): + _add_out_arg(out_args, f.func.arguments.flat_kwarg_only, is_kwarg_only=True) + + return f"{f.func.name.name}: {repr(out_args)}," + + +def main() -> None: + parser = argparse.ArgumentParser(description="Generate annotated_fn_args script") + parser.add_argument( + "native_functions", metavar="NATIVE", help="path to native_functions.yaml" + ) + parser.add_argument("tags", metavar="TAGS", help="path to tags.yaml") + parser.add_argument("out", metavar="OUT", help="path to output directory") + parser.add_argument( + "autograd", metavar="AUTOGRAD", help="path to template directory" + ) + args = parser.parse_args() + gen_annotated(args.native_functions, args.tags, args.out, args.autograd) + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_autograd.py b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_autograd.py new file mode 100644 index 0000000000000000000000000000000000000000..d93d3f4cab4a6f37c0c81c548b4da3b6c5b9dc95 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_autograd.py @@ -0,0 +1,147 @@ +""" +To run this file by hand from the root of the PyTorch +repository, run: + +python -m tools.autograd.gen_autograd \ + aten/src/ATen/native/native_functions.yaml \ + aten/src/ATen/native/tags.yaml \ + $OUTPUT_DIR \ + tools/autograd + +Where $OUTPUT_DIR is where you would like the files to be +generated. In the full build system, OUTPUT_DIR is +torch/csrc/autograd/generated/ +""" + +# gen_autograd.py generates C++ autograd functions and Python bindings. +# +# It delegates to the following scripts: +# +# gen_autograd_functions.py: generates subclasses of torch::autograd::Node +# gen_variable_type.py: generates VariableType.h which contains all tensor methods +# gen_python_functions.py: generates Python bindings to THPVariable +# + +from __future__ import annotations + +import argparse +import os + +from torchgen.api import cpp +from torchgen.api.autograd import ( + match_differentiability_info, + NativeFunctionWithDifferentiabilityInfo, +) +from torchgen.gen import parse_native_yaml +from torchgen.selective_build.selector import SelectiveBuilder + +from . import gen_python_functions +from .gen_autograd_functions import ( + gen_autograd_functions_lib, + gen_autograd_functions_python, +) +from .gen_inplace_or_view_type import gen_inplace_or_view_type +from .gen_trace_type import gen_trace_type +from .gen_variable_factories import gen_variable_factories +from .gen_variable_type import gen_variable_type +from .gen_view_funcs import gen_view_funcs +from .load_derivatives import load_derivatives + + +def gen_autograd( + native_functions_path: str, + tags_path: str, + out: str, + autograd_dir: str, + operator_selector: SelectiveBuilder, + disable_autograd: bool = False, +) -> None: + # Parse and load derivatives.yaml + differentiability_infos, used_dispatch_keys = load_derivatives( + os.path.join(autograd_dir, "derivatives.yaml"), native_functions_path, tags_path + ) + + template_path = os.path.join(autograd_dir, "templates") + + native_funcs = parse_native_yaml(native_functions_path, tags_path).native_functions + fns = sorted( + filter( + operator_selector.is_native_function_selected_for_training, native_funcs + ), + key=lambda f: cpp.name(f.func), + ) + fns_with_diff_infos: list[NativeFunctionWithDifferentiabilityInfo] = ( + match_differentiability_info(fns, differentiability_infos) + ) + + # Generate VariableType.h/cpp + if not disable_autograd: + gen_variable_type( + out, + native_functions_path, + tags_path, + fns_with_diff_infos, + template_path, + used_dispatch_keys, + ) + + gen_inplace_or_view_type( + out, native_functions_path, tags_path, fns_with_diff_infos, template_path + ) + + # operator filter not applied as tracing sources are excluded in selective build + gen_trace_type(out, native_funcs, template_path) + # Generate Functions.h/cpp + gen_autograd_functions_lib(out, differentiability_infos, template_path) + + # Generate variable_factories.h + gen_variable_factories(out, native_functions_path, tags_path, template_path) + + # Generate ViewFuncs.h/cpp + gen_view_funcs(out, fns_with_diff_infos, template_path) + + +def gen_autograd_python( + native_functions_path: str, + tags_path: str, + out: str, + autograd_dir: str, +) -> None: + differentiability_infos, _ = load_derivatives( + os.path.join(autograd_dir, "derivatives.yaml"), native_functions_path, tags_path + ) + + template_path = os.path.join(autograd_dir, "templates") + + # Generate Functions.h/cpp + gen_autograd_functions_python(out, differentiability_infos, template_path) + + # Generate Python bindings + deprecated_path = os.path.join(autograd_dir, "deprecated.yaml") + gen_python_functions.gen( + out, native_functions_path, tags_path, deprecated_path, template_path + ) + + +def main() -> None: + parser = argparse.ArgumentParser(description="Generate autograd C++ files script") + parser.add_argument( + "native_functions", metavar="NATIVE", help="path to native_functions.yaml" + ) + parser.add_argument("tags", metavar="NATIVE", help="path to tags.yaml") + parser.add_argument("out", metavar="OUT", help="path to output directory") + parser.add_argument( + "autograd", metavar="AUTOGRAD", help="path to autograd directory" + ) + args = parser.parse_args() + gen_autograd( + args.native_functions, + args.tags, + args.out, + args.autograd, + SelectiveBuilder.get_nop_selector(), + ) + + +if __name__ == "__main__": + main() diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_autograd_functions.py b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_autograd_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..002a551c3e9154430cd2c12f2b3c1ffe3f4a114a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_autograd_functions.py @@ -0,0 +1,1080 @@ +# Generates C++ autograd functions for the derivatives of ATen operations +# +# This writes two files: +# Functions.h/cpp: subclasses of autograd::Node +# python_functions.h/cpp: Python bindings for the above classes +# + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from torchgen.api.autograd import ( + Derivative, + DifferentiabilityInfo, + SavedAttribute, + uses_retain_variables, + uses_single_grad, +) +from torchgen.api.types import ( + ArrayRefCType, + BaseCppType, + BaseCType, + Binding, + boolT, + doubleT, + intArrayRefT, + iTensorListRefT, + ListCType, + longT, + MutRefCType, + OptionalCType, + optionalIntArrayRefT, + optionalSymIntArrayRefT, + scalarT, + stringT, + symIntArrayRefT, + SymIntT, + TENSOR_LIST_LIKE_CTYPES, + tensorListT, + tensorT, + VectorCType, +) +from torchgen.code_template import CodeTemplate +from torchgen.model import Argument, FunctionSchema +from torchgen.utils import FileManager + +from .gen_inplace_or_view_type import VIEW_FUNCTIONS + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +FUNCTION_DECLARATION = CodeTemplate( + """\ +#ifdef _WIN32 +struct ${op} : public ${superclass} { + TORCH_API ${op}() = default; +#else +struct TORCH_API ${op} : public ${superclass} { +#endif + using ${superclass}::${superclass}; + variable_list apply(variable_list&& grads) override; + std::string name() const override { return "${op}"; } + void release_variables() override { + ${thread_lock} + ${release_variables} + } + ${will_release_variables} + void compiled_args(CompiledNodeArgs& args) const override; + variable_list apply_with_saved(const variable_list& inputs, SwapSavedVariables& saved) override; + ${saved_variables} + ${saved_list_sizes} +}; +""" +) + +WILL_RELEASE_VARIABLES = CodeTemplate( + """\ +bool retain_variables = true; +void will_release_variables() override { + retain_variables = false; +} +""" +) + +# We generate e.g. MulBackward0::apply and have that call into +# MulBackward0_apply_functional. The apply_functional is a pure function, +# that is, it does not rely on global state. MulBackward0::apply +# is responsible for querying the autograd engine for which outputs should +# be computed (needs_input_grad), applying locks, +# and unpacking saved variables to pass to MulBackward0_apply_functional. +# +# needs_input_grad is a mapping from input index to if that input needs +# gradients computed. For operators that take in List[Tensor], the List[Tensor] +# is one element in the needs_input_grad that specifies if *any* of the +# List[Tensor] needs input grad. In theory this could be optimized. +FUNCTION_DEFINITION = CodeTemplate( + """\ +static variable_list ${op}_apply_functional( + variable_list&& grads, + std::array needs_input_grad${,apply_functional_args_signature}) +{ + IndexRangeGenerator gen; + ${compute_index_ranges} + variable_list grad_inputs(gen.size()); + ${body} + return grad_inputs; +} +inline variable_list ${op}_apply_functional_ivalue(const variable_list& grads, const ivalue_list& args) +{ +#ifdef C10_MOBILE + TORCH_INTERNAL_ASSERT(false, "compiled autograd doesn't work on mobile"); +#else + auto packed_args = PackedArgs(args); + auto needs_input_grad = packed_args.unpack>(); + ${unpack_ivalues} + return ${op}_apply_functional(variable_list(grads), needs_input_grad${,apply_functional_args}); +#endif +} + +variable_list ${op}::apply(variable_list&& grads) { + ${thread_lock} + ${asserts} + ${unpacks} + ${compute_needs_input_grad} + return ${op}_apply_functional(std::move(grads), needs_input_grad${,apply_functional_args}); +} + +void ${op}::compiled_args(CompiledNodeArgs& args) const { + ${compiled_args} +} +variable_list ${op}::apply_with_saved(const variable_list& grads, SwapSavedVariables& saved) { +#ifdef C10_MOBILE + TORCH_INTERNAL_ASSERT(false, "compiled autograd doesn't work on mobile"); +#else + ${apply_with_saved_before} + + static bool called = false; + if (!called) { + called = true; + ${compute_schema} + const auto& pyinterface = torch::dynamo::autograd::getPyCompilerInterface(); + pyinterface->bind_function(saved.get_py_compiler(), name(), ${op}_apply_functional_ivalue, schema); + } + + variable_list output_result; + + PackedArgs packed_args; + ${asserts} + ${unpacks} + ${compute_needs_input_grad} + packed_args.pack(needs_input_grad); + ${get_packed_args} + + output_result = compiled_autograd_apply_functional(packed_args, next_edges(), saved, grads, name()); + + ${apply_with_saved_after} + return output_result; +#endif +} + +""" +) + +GRAD_INPUT_MASK = CodeTemplate( + """\ + auto grad_input_mask = std::array{ + ${masks} + }; +""" +) + +COMPUTE_NEEDS_INPUT_GRAD = CodeTemplate( + """\ +IndexRangeGenerator gen; +${compute_index_ranges} +auto needs_input_grad = std::array{ + ${masks} +};\ +""" +) + + +DERIVATIVE_SINGLE = CodeTemplate( + """\ +if (needs_input_grad[/*${name}*/${idx}]) { + auto grad_result = ${derivative}; + copy_range(grad_inputs, ${name}_ix, grad_result); +} +""" +) + +# note(crcrpar): `self` argument and other optional positional argument +# of foreach functions are basically a list of n `Tensor`s thus iterating over +# `grads` in order to utilize and apply the existing derivative definitions +# to each `Tensor`(s) of `self`, and the others. +DERIVATIVE_SINGLE_FOREACH = CodeTemplate( + """\ +if (needs_input_grad[/*${name}*/${idx}]) { // ${name} + std::vector grad_result; + grad_result.reserve(grads.size()); + for (const auto & i : c10::irange(grads.size())) { + if (grads[i].defined()) { + grad_result.emplace_back(${derivative}); + } else { + grad_result.emplace_back(Tensor()); + } + } + copy_range(grad_inputs, ${name}_ix, grad_result); +} +""" +) + +DERIVATIVE_MULTI_COPY_RANGE = CodeTemplate( + """\ + if (needs_input_grad[/*${name}*/${idx}]) { + copy_range(grad_inputs, ${name}_ix, std::get<${i}>(grad_result)); + } +""" +) + +DERIVATIVE_MULTI = CodeTemplate( + """\ +if (${needs_input_grad}) { + ${grad_input_mask} + auto grad_result = ${derivative}; + ${copy_ranges} +} +""" +) + +# Generates python bindings +# +# This generates the definitions for: +# (1) The PyTypeObject for each backward grad_fn subclassing Node +# (2) The entry for PyTypeObject's tp_getset slot (an array of PyGetSetDef structs) +# We generate one PyGetSetDef struct for each of grad_fn's saved inputs and outputs +# Each PyGetSetDef has a function ptr to a getter, also defined here (3). +# (3) Getters for each of grad_fn's saved inputs and outputs. +# +PY_FUNCTION_DEFINITION = CodeTemplate( + """\ +static PyTypeObject ${op}Class; +addClass<${op}>(module, ${op}Class, "${op}", ${op}_properties); +""" +) + +PY_FUNCTION_PROPS_AND_GETTERS = CodeTemplate( + """\ +${all_getter_definitions} + +static struct PyGetSetDef ${op}_properties[] = { + THP_FUNCTION_DEFAULT_PROPERTIES, + ${all_getsetdef_structs} + {nullptr} /* sentinel */ +}; + +""" +) + +PY_GETSETDEF_STRUCT = CodeTemplate( + """\ +{(char*)"_saved_${name}", (getter)THP${op}_${name}_getter, nullptr, nullptr, nullptr}""" +) + +PY_RAW_GETSETDEF_STRUCT = CodeTemplate( + """\ +{(char*)"_raw_saved_${name}", (getter)THP${op}_${name}_raw_getter, nullptr, nullptr, nullptr}""" +) + +# Getter templates +GETTER_DEFINITION = CodeTemplate( + """\ +static PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) { + HANDLE_TH_ERRORS + auto prop = static_cast<${op}*>(self->cdata.get())->${name}; + ${body} + END_HANDLE_TH_ERRORS +} +""" +) + +GETTER_DEFINITION_SAVEDVAR = CodeTemplate( + """\ +static PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) { + HANDLE_TH_ERRORS + const auto& prop = static_cast<${op}*>(self->cdata.get())->${name}_; + ${body} + END_HANDLE_TH_ERRORS +} +""" +) + +GETTER_DEFINITION_RAW_SAVEDVAR = CodeTemplate( + """\ +static PyObject* THP${op}_${name}_raw_getter(THPCppFunction *self, void *_unused) { + HANDLE_TH_ERRORS + const auto& prop = static_cast<${op}*>(self->cdata.get())->${name}_; + ${body} + END_HANDLE_TH_ERRORS +} +""" +) + +GETTER_DEFINITION_VEC_SAVEDVAR = CodeTemplate( + """\ +static PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) { + HANDLE_TH_ERRORS + const auto *node = static_cast<${op}*>(self->cdata.get()); + const auto& prop = node->${name}_; + if (node->${name}_released_) { + PyErr_SetString(PyExc_RuntimeError, ERR_BACKWARD_TWICE); + return nullptr; + } + ${body} + END_HANDLE_TH_ERRORS +} +""" +) + +GETTER_DEFINITION_RAW_VEC_SAVEDVAR = CodeTemplate( + """\ +static PyObject* THP${op}_${name}_raw_getter(THPCppFunction *self, void *_unused) { + HANDLE_TH_ERRORS + const auto *node = static_cast<${op}*>(self->cdata.get()); + const auto& prop = node->${name}_; + if (node->${name}_released_) { + PyErr_SetString(PyExc_RuntimeError, ERR_BACKWARD_TWICE); + return nullptr; + } + ${body} + END_HANDLE_TH_ERRORS +} +""" +) + +GETTER_DEFINITION_OPT = CodeTemplate( + """\ +static PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) { + HANDLE_TH_ERRORS + auto opt_prop = static_cast<${op}*>(self->cdata.get())->${name}; + if (!opt_prop.has_value()) { + Py_RETURN_NONE; + } + auto prop = opt_prop.value(); + ${body} + END_HANDLE_TH_ERRORS +} +""" +) + +GETTER_DEFINITION_OPT_ARRAYREF = CodeTemplate( + """\ +static PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) { + HANDLE_TH_ERRORS + auto opt_prop = static_cast<${op}*>(self->cdata.get())->${name}; + if (!opt_prop.list.has_value()) { + Py_RETURN_NONE; + } + auto prop = opt_prop.list.value(); + ${body} + END_HANDLE_TH_ERRORS +} +""" +) + +# Getter body +GETTER_BODY_SAVEDVAR = """\ +return THPVariable_Wrap(prop.unpack(self->cdata)); +""" + +GETTER_BODY_RAW_SAVEDVAR = """\ +pybind11::object obj = pybind11::cast(prop, pybind11::return_value_policy::reference); +return obj.release().ptr(); +""" + +GETTER_BODY_VEC_SAVEDVAR = """\ +PyObject* tup = PyTuple_New((Py_ssize_t) prop.size()); +for (auto i: c10::irange(prop.size())) { + PyTuple_SetItem(tup, (Py_ssize_t) i, THPVariable_Wrap(prop[i].unpack(self->cdata))); +} +return tup; +""" + +GETTER_BODY_RAW_VEC_SAVEDVAR = """\ +PyObject* tup = PyTuple_New((Py_ssize_t) prop.size()); +for (auto i : c10::irange(prop.size())) { + pybind11::object obj = pybind11::cast(prop[i], pybind11::return_value_policy::reference); + PyTuple_SetItem(tup, (Py_ssize_t) i, obj.release().ptr()); +} +return tup; +""" + +GETTER_BODY_ARRAYREF_LONG = """\ +PyObject* tup = PyTuple_New((Py_ssize_t) prop.size()); +for (auto i : c10::irange(prop.size())) { + PyTuple_SetItem(tup, (Py_ssize_t) i, PyLong_FromUnsignedLong((uint64_t) prop[i])); +} +return tup; +""" + +GETTER_BODY_ARRAYREF_SYMINT = """\ +PyObject* tup = PyTuple_New((Py_ssize_t) prop.size()); +for (auto i : c10::irange(prop.size())) { + auto si = prop[i]; + if (auto m = si.maybe_as_int()) { + PyTuple_SetItem(tup, (Py_ssize_t) i, PyLong_FromUnsignedLong(*m)); + } else { + auto py_symint = py::cast(si).release().ptr(); + PyTuple_SetItem(tup, (Py_ssize_t) i, py_symint); + } +} +return tup; +""" + +GETTER_BODY_ARRAYREF_DOUBLE = """\ +PyObject* tup = PyTuple_New((Py_ssize_t) prop.size()); +for (auto i : c10::irange(prop.size())) { + PyTuple_SetItem(tup, (Py_ssize_t) i, PyFloat_FromDouble((double) prop[i])); +} +return tup; +""" + +GETTER_BODY_INT64_T = """\ +return PyLong_FromUnsignedLong((int64_t) prop); +""" + +GETTER_BODY_SYMINT = """\ +if (auto m = prop.maybe_as_int()) { + return PyLong_FromUnsignedLong(*m); +} else { + return py::cast(prop).release().ptr(); +} +""" + +GETTER_BODY_DOUBLE = """\ +return PyFloat_FromDouble((double) prop); +""" + +GETTER_BODY_BOOL = """\ +if (prop) { + Py_RETURN_TRUE; +} else { + Py_RETURN_FALSE; +} +""" + +GETTER_BODY_STRING = """\ +return PyUnicode_FromStringAndSize(prop.data(), prop.size()); +""" + +GETTER_BODY_SCALAR = """\ +if (prop.isComplex()) { + auto cprop = prop.to>(); + return PyComplex_FromDoubles(cprop.real(), cprop.imag()); +} else if (prop.isFloatingPoint()) { + return PyFloat_FromDouble(prop.to()); +} else if (prop.isIntegral(/*includeBool=*/false)) { + return PyLong_FromLong(prop.to()); +} else if (prop.isBoolean()) { + if (prop.to()) { + Py_RETURN_TRUE; + } else { + Py_RETURN_FALSE; + } +} else { + PyErr_SetString(PyExc_RuntimeError, "Unknown scalar type"); + return nullptr; +} +""" + + +GETTER_BODY_VEC_SCALAR = """\ +PyObject* tup = PyTuple_New((Py_ssize_t) prop.size()); +for (auto i: c10::irange(prop.size())) { + if (prop[i].isComplex()) { + auto cprop = prop[i].to>(); + PyTuple_SetItem(tup, (Py_ssize_t) i, PyComplex_FromDoubles(cprop.real(), cprop.imag())); + } else if (prop[i].isFloatingPoint()) { + auto double_prop = prop[i].to(); + PyTuple_SetItem(tup, (Py_ssize_t) i, PyFloat_FromDouble(double_prop)); + } else if (prop[i].isIntegral(/*includeBool=*/false)) { + auto long_prop = prop[i].to(); + PyTuple_SetItem(tup, (Py_ssize_t) i, PyLong_FromLong(long_prop)); + } else if (prop[i].isBoolean()) { + if (prop[i].to()) { + PyTuple_SetItem(tup, (Py_ssize_t) i, Py_True); + } else { + PyTuple_SetItem(tup, (Py_ssize_t) i, Py_False); + } + } else { + PyErr_SetString(PyExc_RuntimeError, "Unknown scalar type"); + return nullptr; + } +} +return tup; +""" + + +MISC_GETTER_DEFS = { + OptionalCType(BaseCType(longT)): (GETTER_DEFINITION_OPT, GETTER_BODY_INT64_T), + OptionalCType(BaseCType(SymIntT)): (GETTER_DEFINITION_OPT, GETTER_BODY_SYMINT), + BaseCType(doubleT): (GETTER_DEFINITION, GETTER_BODY_DOUBLE), + OptionalCType(BaseCType(doubleT)): (GETTER_DEFINITION_OPT, GETTER_BODY_DOUBLE), + BaseCType(boolT): (GETTER_DEFINITION, GETTER_BODY_BOOL), + BaseCType(scalarT): (GETTER_DEFINITION, GETTER_BODY_SCALAR), + OptionalCType(BaseCType(scalarT)): (GETTER_DEFINITION_OPT, GETTER_BODY_SCALAR), +} + +# These functions have backwards which cannot be traced, and so must have +# their backward functions traced opaquely. +# VIEW_FUNCTIONS are not traceable because they use as_strided, which +# has an untraceable backwards, see +# https://github.com/pytorch/pytorch/issues/4250 +# TODO: This is probably not exhaustive, but it's a start +UNTRACEABLE_FUNCTIONS = VIEW_FUNCTIONS + + +def get_infos_with_derivatives_list( + differentiability_infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]], +) -> list[DifferentiabilityInfo]: + diff_info_list = [ + info + for diffinfo_dict in differentiability_infos.values() + for info in diffinfo_dict.values() + ] + + return list(filter(lambda info: info.args_with_derivatives, diff_info_list)) + + +def gen_autograd_functions_lib( + out: str, + differentiability_infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]], + template_path: str, +) -> None: + """Functions.h and Functions.cpp body + + These contain the auto-generated subclasses of torch::autograd::Node + for each every differentiable torch function. + """ + + # get a 1D list of diffinfos, we do not need them to be per FunctionSchema/DispatchKey here + # infos with the diff dispatchkeys but the same name will still be in the same shard. + infos = get_infos_with_derivatives_list(differentiability_infos) + declarations = [process_function(f, FUNCTION_DECLARATION) for f in infos] + definitions = [process_function(f, FUNCTION_DEFINITION) for f in infos] + + file_basename = "Functions" + fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False) + for suffix in [".h", ".cpp"]: + fname = file_basename + suffix + fm.write_with_template( + fname, + fname, + lambda: { + "generated_comment": "@" + + f"generated from {fm.template_dir_for_comments()}/{fname}", + "autograd_function_declarations": declarations, + "autograd_function_definitions": definitions, + }, + ) + + +def gen_autograd_functions_python( + out: str, + differentiability_infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]], + template_path: str, +) -> None: + fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False) + num_shards = 5 + fm.write( + "python_functions.h", + lambda: { + "generated_comment": "@" + + f"generated from {fm.template_dir_for_comments()}/python_functions.h", + "shard_forward_declare": [ + f"void initialize_autogenerated_functions_{i}(PyObject* module);" + for i in range(num_shards) + ], + "shard_call": [ + f"initialize_autogenerated_functions_{i}(module);" + for i in range(num_shards) + ], + }, + ) + + # get a 1D list of diffinfos, we do not need them to be per FunctionSchema/DispatchKey here + # infos with the diff dispatchkeys but the same name will still be in the same shard. + infos = get_infos_with_derivatives_list(differentiability_infos) + fm.write_sharded( + "python_functions.cpp", + infos, + key_fn=lambda info: info.name, + base_env={ + "generated_comment": "@" + + f"generated from {fm.template_dir_for_comments()}/python_functions.cpp", + }, + env_callable=lambda info: { + "py_function_initializers": [ + process_function(info, PY_FUNCTION_DEFINITION) + ], + "py_function_props_and_getters": [ + process_function(info, PY_FUNCTION_PROPS_AND_GETTERS) + ], + }, + num_shards=num_shards, + sharded_keys={"py_function_initializers", "py_function_props_and_getters"}, + ) + + +def process_function(info: DifferentiabilityInfo, template: CodeTemplate) -> str: + saved_variables: list[str] = [] + release_variables: list[str] = [] + saved_list_sizes: list[str] = [] + unpack: list[str] = [] + asserts: list[str] = [] + compute_index_ranges: list[str] = [] + getter_definitions: list[str] = [] + py_getsetdef_structs: list[str] = [] + compiled_args: list[str] = [] + apply_with_saved_before: list[str] = [] + apply_with_saved_after: list[str] = [] + apply_functional_args: list[str] = [] + apply_functional_args_ref_types: list[str] = [] + # Maps the name of an input (to the original forward operator; + # examples are "self", "other") to the order in which they appear in the + # operator. + # For example; if the operator is foo(Tensor self, int64_t k, Tensor other), + # the mapping is: {"self": 0, "other": 1}. + # We use this mapping to populate needs_input_grad in some order and then grab + # values from it. + input_name_to_idx: dict[str, int] = {} + + for idx, arg in enumerate(info.args_with_derivatives): + if arg.type in TENSOR_LIST_LIKE_CTYPES: + size = f"{arg.name}_size_" + saved_list_sizes.append(f"size_t {arg.name}_size_;") + apply_functional_args.append(f"{arg.name}_size_") + apply_functional_args_ref_types.append("size_t") + else: + size = "1" + compute_index_ranges.append(f"auto {arg.name}_ix = gen.range({size});") + input_name_to_idx[arg.name] = idx + + def save_var(var: SavedAttribute, is_output: bool) -> None: + name = var.nctype.name + type = var.nctype.type + should_append_getsetdef = True + should_append_raw_getsetdef = False + visit_name = name + uses_cpp_saved_variable_cls = False + unpacked_ref_type = None + + if ( + type == BaseCType(tensorT) + or type == OptionalCType(BaseCType(tensorT)) + or type == MutRefCType(OptionalCType(BaseCType(tensorT))) + or (type == BaseCType(scalarT) and is_output) + ): + uses_cpp_saved_variable_cls = True + saved_variables.append(f"SavedVariable {name}_;") + release_variables.append(f"{name}_.reset_data();") + ptr = "getptr()" if is_output else "" + unpack.append(f"auto {name} = {name}_.unpack({ptr});") + getter_definitions.append( + GETTER_DEFINITION_SAVEDVAR.substitute( + op=info.op, name=name, body=GETTER_BODY_SAVEDVAR + ) + ) + getter_definitions.append( + GETTER_DEFINITION_RAW_SAVEDVAR.substitute( + op=info.op, name=name, body=GETTER_BODY_RAW_SAVEDVAR + ) + ) + should_append_raw_getsetdef = True + visit_name = f"{name}_" + unpacked_ref_type = "Tensor&" + elif ( + type == BaseCType(tensorListT) + or type == BaseCType(iTensorListRefT) + or type == VectorCType(BaseCType(tensorT)) + ): + # note(crcrpar): [nuanced return type of out-of-place foreach functions] + # When an out-of-place foreach function whose return signature is `Tensor[]` + # spells out its backward definitions in `derivatives.yaml`, and some of them depend on + # `result`, `result`'s type is interpreted and treated as `std::vector`. + # An out-of-place foreach whose backwards rely on their output doesn't suffer from this + # difference if the definitions are codegen'ed. + # This special case is needed for `_foreach_pow.List` and `_foreach_pow.ScalarAndTensor` + # as of https://github.com/pytorch/pytorch/pull/105504. + if type == VectorCType(BaseCType(tensorT)): + if not ( + info.func.func.name.name.base.startswith("_foreach") and is_output + ): + raise AssertionError( + "VectorCType(BaseCType(tensorT)) requires foreach function and is_output" + ) + uses_cpp_saved_variable_cls = True + saved_variables.append(f"std::vector {name}_;") + saved_variables.append(f"bool {name}_released_ = false;") + # Just clear() is sufficient, we don't need to loop and clear each variable. + # Because the SavedVariable owns a tensor and a grad_fn, removing the SavedVariable makes them go away as well. + release_variables.append(f"{name}_.clear();") + release_variables.append(f"{name}_released_ = true;") + ptr = "getptr()" if is_output else "nullptr" + unpack.append(f"auto {name} = unpack_list({name}_, {ptr});") + asserts.append(f"TORCH_CHECK(!{name}_released_, ERR_BACKWARD_TWICE);") + getter_definitions.append( + GETTER_DEFINITION_VEC_SAVEDVAR.substitute( + op=info.op, name=name, body=GETTER_BODY_VEC_SAVEDVAR + ) + ) + getter_definitions.append( + GETTER_DEFINITION_RAW_VEC_SAVEDVAR.substitute( + op=info.op, name=name, body=GETTER_BODY_RAW_VEC_SAVEDVAR + ) + ) + should_append_raw_getsetdef = True + visit_name = f"{name}_" + unpacked_ref_type = "std::vector&" + elif type == ListCType(OptionalCType(BaseCType(tensorT))): + uses_cpp_saved_variable_cls = True + saved_variables.append(f"std::vector {name}_;") + saved_variables.append(f"bool {name}_released_ = false;") + # Just clear() is sufficient, we don't need to loop and clear each variable. + # Because the SavedVariable owns a tensor and a grad_fn, removing the SavedVariable makes them go away as well. + release_variables.append(f"{name}_.clear();") + release_variables.append(f"{name}_released_ = true;") + unpack.append(f"auto {name} = unpack_opt_list({name}_);") + asserts.append(f"TORCH_CHECK(!{name}_released_, ERR_BACKWARD_TWICE);") + getter_definitions.append( + GETTER_DEFINITION_VEC_SAVEDVAR.substitute( + op=info.op, name=name, body=GETTER_BODY_VEC_SAVEDVAR + ) + ) + getter_definitions.append( + GETTER_DEFINITION_RAW_VEC_SAVEDVAR.substitute( + op=info.op, name=name, body=GETTER_BODY_RAW_VEC_SAVEDVAR + ) + ) + should_append_raw_getsetdef = True + visit_name = f"{name}_" + unpacked_ref_type = "torch::List>&" + elif type == BaseCType(intArrayRefT): + saved_variables.append(f"std::vector {name};") + getter_definitions.append( + GETTER_DEFINITION.substitute( + op=info.op, name=name, body=GETTER_BODY_ARRAYREF_LONG + ) + ) + elif type == BaseCType(symIntArrayRefT): + saved_variables.append(f"std::vector {name};") + getter_definitions.append( + GETTER_DEFINITION.substitute( + op=info.op, name=name, body=GETTER_BODY_ARRAYREF_SYMINT + ) + ) + elif type == BaseCType(optionalIntArrayRefT): + saved_variables.append(f"c10::OptionalArray {name};") + getter_definitions.append( + GETTER_DEFINITION_OPT_ARRAYREF.substitute( + op=info.op, name=name, body=GETTER_BODY_ARRAYREF_LONG + ) + ) + elif type == BaseCType(optionalSymIntArrayRefT): + saved_variables.append(f"c10::OptionalArray {name};") + getter_definitions.append( + GETTER_DEFINITION_OPT_ARRAYREF.substitute( + op=info.op, name=name, body=GETTER_BODY_ARRAYREF_SYMINT + ) + ) + elif type == OptionalCType(BaseCType(intArrayRefT)): + saved_variables.append(f"c10::OptionalArray {name};") + getter_definitions.append( + GETTER_DEFINITION_OPT_ARRAYREF.substitute( + op=info.op, name=name, body=GETTER_BODY_ARRAYREF_LONG + ) + ) + elif type == OptionalCType(BaseCType(symIntArrayRefT)): + saved_variables.append(f"c10::OptionalArray {name};") + getter_definitions.append( + GETTER_DEFINITION_OPT_ARRAYREF.substitute( + op=info.op, name=name, body=GETTER_BODY_ARRAYREF_SYMINT + ) + ) + elif type == OptionalCType(ArrayRefCType(BaseCType(doubleT))): + saved_variables.append(f"c10::OptionalArray {name};") + getter_definitions.append( + GETTER_DEFINITION_OPT_ARRAYREF.substitute( + op=info.op, name=name, body=GETTER_BODY_ARRAYREF_DOUBLE + ) + ) + elif type == BaseCType(longT): + saved_variables.append(f"{type.cpp_type()} {name} = 0;") + getter_definitions.append( + GETTER_DEFINITION.substitute( + op=info.op, name=name, body=GETTER_BODY_INT64_T + ) + ) + elif type == BaseCType(SymIntT): + saved_variables.append(f"c10::SymInt {name};") + getter_definitions.append( + GETTER_DEFINITION.substitute( + op=info.op, name=name, body=GETTER_BODY_SYMINT + ) + ) + elif type == BaseCType(stringT): + saved_variables.append(f"std::string {name};") + getter_definitions.append( + GETTER_DEFINITION.substitute( + op=info.op, name=name, body=GETTER_BODY_STRING + ) + ) + elif type == OptionalCType(BaseCType(stringT)): + saved_variables.append(f"std::optional {name};") + getter_definitions.append( + GETTER_DEFINITION_OPT.substitute( + op=info.op, name=name, body=GETTER_BODY_STRING + ) + ) + elif type == ArrayRefCType( + elem=BaseCType(type=BaseCppType(ns="at", name="Scalar")) + ): + saved_variables.append(f"std::vector {name};") + unpacked_ref_type = "std::vector&" + saved_variables.append(f"bool {name}_released_ = false;") + # Just clear() is sufficient, we don't need to loop and clear each variable. + # Because the SavedVariable owns a tensor and a grad_fn, removing the SavedVariable makes them go away as well. + release_variables.append(f"{name}.clear();") + # release_variables.append(f"{name}_released_ = true;") + # unpack.append(f"auto {name} = unpack_list({name}_);") + # asserts.append(f"TORCH_CHECK(!{name}_released_, ERR_BACKWARD_TWICE);") + getter_definitions.append( + CodeTemplate( + """\ +static PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) { + HANDLE_TH_ERRORS + const auto *node = static_cast<${op}*>(self->cdata.get()); + const auto& prop = node->${name}; + if (node->${name}_released_) { + PyErr_SetString(PyExc_RuntimeError, ERR_BACKWARD_TWICE); + return nullptr; + } + ${body} + END_HANDLE_TH_ERRORS +} + """ + ).substitute( + op=info.op, + name=name, + body=GETTER_BODY_VEC_SCALAR, + ) + ) + else: + # Check for indicators that you're putting a non-owning reference + # into the saved variable field. If this is spuriously firing, + # edit this field. Otherwise, you probably need to add a case + # above. + if not ( + "ref" not in type.cpp_type().lower() + and "view" not in type.cpp_type().lower() + and "*" not in type.cpp_type() + and "&" not in type.cpp_type() + ): + raise AssertionError( + f"{type.cpp_type()} looks like it contains a non-owning reference" + ) + saved_variables.append(f"{type.cpp_type()} {name};") + + if type in MISC_GETTER_DEFS: + getter_def, body = MISC_GETTER_DEFS[type] + getter_definitions.append( + getter_def.substitute(op=info.op, name=name, body=body) + ) + else: + # Types we don't expose python bindings to yet: + # TypeAndSize, at::ScalarType, TensorOptions, TensorGeometry, + # std::vector>, std::vector + should_append_getsetdef = False + + if should_append_getsetdef: + py_getsetdef_structs.append( + PY_GETSETDEF_STRUCT.substitute(op=info.op, name=name) + ) + if should_append_raw_getsetdef: + py_getsetdef_structs.append( + PY_RAW_GETSETDEF_STRUCT.substitute(op=info.op, name=name) + ) + + if uses_cpp_saved_variable_cls: + compiled_args.append( + f"args.collect({visit_name}, {'true' if is_output else 'false'});" + ) + else: + compiled_args.append(f"args.collect({visit_name});") + apply_with_saved_before.append(f"saved.before({visit_name});") + apply_with_saved_after.append(f"saved.after({visit_name});") + + if unpacked_ref_type is None: + unpacked_ref_type = f"{saved_variables[-1].split(' ')[0]}&" + apply_functional_args.append(str(name)) + apply_functional_args_ref_types.append(unpacked_ref_type) + + for var in sorted(info.all_saved_inputs, key=lambda sa: str(sa.nctype.name)): + save_var(var, is_output=False) + for var in sorted(info.all_saved_outputs, key=lambda sa: str(sa.nctype.name)): + save_var(var, is_output=True) + + # lock the mutex when we release variables and in Node::apply to protect thread safety + # see Note [Thread Safety on Autograd Node] + if len(release_variables) > 0: + thread_lock = "std::lock_guard lock(mutex_);" + else: + thread_lock = "" + + if uses_retain_variables(info): + apply_functional_args.append("retain_variables") + apply_functional_args_ref_types.append("bool") + will_release_variables = WILL_RELEASE_VARIABLES.substitute() + else: + will_release_variables = "" + + body: list[str] = [] + + if uses_single_grad(info): + body.append("const auto& grad = grads[0];") + else: + # Generate aliases for gradients named for returned values. + body.extend( + f"const auto& {name} = grads[{info.available_named_gradients.index(name)}];" + for name in sorted(info.used_named_gradients) + ) + + def emit_derivative( + derivative: Derivative, + args_with_derivatives: Sequence[Binding], + ) -> tuple[bool, str]: + formula = derivative.formula + var_names = derivative.var_names + + if len(var_names) == 1: + checks_any_grad_defined = False + if "not_implemented" not in formula: + matching_args = [ + arg for arg in args_with_derivatives if arg.name == var_names[0] + ] + if len(matching_args) == 1: + # We can add undefined grad support if the input variable is a Tensor + arg = matching_args[0] + if isinstance(arg.argument, Argument) and str( + arg.argument.type + ) in ("Tensor", "Tensor?"): + formula = "any_grad_defined ? (" + formula + ") : Tensor()" + checks_any_grad_defined = True + if info.name.startswith("_foreach_"): + derivative_template = DERIVATIVE_SINGLE_FOREACH + else: + derivative_template = DERIVATIVE_SINGLE + return ( + checks_any_grad_defined, + derivative_template.substitute( + name=var_names[0], + derivative=formula, + idx=input_name_to_idx[var_names[0]], + ), + ) + + else: + if "grad_input_mask" in formula: + masks = [ + f"needs_input_grad[{input_name_to_idx[name]}]," + for name in var_names + ] + grad_input_mask = GRAD_INPUT_MASK.substitute( + n=len(var_names), masks=masks + ) + else: + grad_input_mask = "" + needs_input_grad = [ + f"needs_input_grad[{input_name_to_idx[name]}]" for name in var_names + ] + needs_input_grad = " || ".join(needs_input_grad) + copy_ranges: list[str] = [] + for i, n in enumerate(var_names): + copy_ranges.append( + DERIVATIVE_MULTI_COPY_RANGE.substitute( + name=n, i=i, idx=input_name_to_idx[n] + ) + ) + return False, DERIVATIVE_MULTI.substitute( + needs_input_grad=needs_input_grad, + copy_ranges=copy_ranges, + derivative=formula, + grad_input_mask=grad_input_mask, + ) + + masks = [] + + need_any_grad_defined_var = False + for derivative in info.derivatives: + checks_any_grad_defined, derivative_text = emit_derivative( + derivative, info.args_with_derivatives + ) + body.append(derivative_text) + need_any_grad_defined_var |= checks_any_grad_defined + + for name in input_name_to_idx: + masks.append(f"task_should_compute_output({{ {name}_ix }}),") + + # Since single-output derivative formulas need to check if grads are + # defined, only perform the check once, before all the formulas + if need_any_grad_defined_var: + body.insert( + -len(info.derivatives), + "bool any_grad_defined = any_variable_defined(grads);", + ) + + if info.name in UNTRACEABLE_FUNCTIONS: + superclass = "Node" + else: + superclass = "TraceableFunction" + + all_getsetdef_structs = ( + ",\n".join(py_getsetdef_structs) + "," if len(py_getsetdef_structs) != 0 else "" + ) + all_getter_definitions = "\n".join(getter_definitions) + + compute_needs_input_grad = COMPUTE_NEEDS_INPUT_GRAD.substitute( + n=len(masks), compute_index_ranges=compute_index_ranges, masks=masks + ) + apply_functional_args_signature = [ + f"{T} {x}" + for T, x in zip(apply_functional_args_ref_types, apply_functional_args) + ] + get_packed_args = "\n".join( + f"packed_args.pack({name});" for name in apply_functional_args + ) + unpack_ivalues = [] + for typ, name in zip(apply_functional_args_ref_types, apply_functional_args): + typ = typ.removesuffix("&") + unpack_ivalues.append(f"auto {name} = packed_args.unpack<{typ}>();") + + schema_args = [f"std::array"] + for typ in apply_functional_args_ref_types: + typ = typ.removesuffix("&") + typ = typ.removeprefix("const") + schema_args.append(typ.strip()) + compute_schema = ["std::vector schema = {"] + for schema_arg in schema_args: + compute_schema.append( + f" torch::dynamo::autograd::IValuePacker<{schema_arg}>::packed_type()," + ) + compute_schema.append("};") + + return template.substitute( + unpacks="\n".join(unpack), + op=info.op, + compute_schema="\n".join(compute_schema), + apply_functional_args=apply_functional_args, + apply_functional_args_signature=apply_functional_args_signature, + compute_needs_input_grad=compute_needs_input_grad, + num_inputs=len(input_name_to_idx), + unpack_ivalues="\n".join(unpack_ivalues), + compute_index_ranges=compute_index_ranges, + saved_variables=saved_variables, + release_variables=release_variables, + saved_list_sizes=saved_list_sizes, + asserts=asserts, + thread_lock=thread_lock, + will_release_variables=will_release_variables, + body=body, + superclass=superclass, + all_getter_definitions=all_getter_definitions, + all_getsetdef_structs=all_getsetdef_structs, + compiled_args=compiled_args, + apply_with_saved_before=apply_with_saved_before, + apply_with_saved_after=apply_with_saved_after, + get_packed_args=get_packed_args, + ) diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_inplace_or_view_type.py b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_inplace_or_view_type.py new file mode 100644 index 0000000000000000000000000000000000000000..bbdb833143c47225e9ebbea6de94778c6b298db8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_inplace_or_view_type.py @@ -0,0 +1,676 @@ +# Generates ADInplaceOrViewType.h/cpp +# +# NOTE: If any changes are being made to the ADInplaceOrView codegen please also check +# if updates are needed in torch/csrc/autograd/autograd_not_implemented_fallback.cpp +# The fallback is expected to mimic this codegen, so we should keep the two in sync. + +from __future__ import annotations + +from torchgen.api import cpp +from torchgen.api.autograd import ( + dispatch_strategy, + gen_differentiable_outputs, + NativeFunctionWithDifferentiabilityInfo, +) +from torchgen.api.types import ( + BaseCType, + Binding, + boolT, + ConstRefCType, + CType, + DispatcherSignature, + intArrayRefT, + longT, + OptionalCType, + symIntArrayRefT, + SymIntT, + tensorT, +) +from torchgen.code_template import CodeTemplate +from torchgen.context import with_native_function +from torchgen.model import ( + NativeFunction, + SchemaKind, + SelfArgument, + TensorOptionsArguments, + Type, +) +from torchgen.utils import FileManager + +from .context import with_native_function_with_differentiability_info +from .gen_trace_type import ( + get_return_value, + MANUAL_AUTOGRAD, + tie_return_values, + type_wrapper_name, +) + + +# See NOTE [ Autograd View Variables ] in variable.h for details. +# If you update list VIEW_FUNCTIONS or RETURNS_VIEWS_OF_INPUT, +# you **MUST** also update the public list of view ops accordingly in +# docs/source/tensor_view.rst. Note not all ATen functions are exposed to public, +# e.g alias & sparse_coo_tensor_with_dims_and_tensors. +# +# A map: function name => name of the argument that all outputs are view of + +VIEW_FUNCTIONS_WITH_METADATA_CHANGE = [ + "view_as_complex", + "view_as_real", + "_conj", + "_neg_view", + "_nested_get_values", + "_nested_view_from_buffer", + "_nested_view_from_jagged", +] + +VIEW_FUNCTIONS = { + "numpy_T": "self", + "alias": "self", + "as_strided": "self", + "diagonal": "self", + "expand": "self", + "permute": "self", + "select": "self", + "slice": "self", + "slice_inverse": "self", + "split": "self", + "split_with_sizes": "self", + "squeeze": "self", + "t": "self", + "transpose": "self", + "unfold": "self", + "unsqueeze": "self", + "flatten": "self", + "view": "self", + "unbind": "self", + "_indices": "self", + "_values": "self", + "indices": "self", + "values": "self", + "crow_indices": "self", + "col_indices": "self", + "ccol_indices": "self", + "row_indices": "self", + # sparse_coo ctor output should really be views of both indices and values, + # but we only supports making as view of a single variable, and indices is + # discrete anyways. + # FIXME: clone indices on construction. + "sparse_coo_tensor_with_dims_and_tensors": "values", + "_reshape_alias": "self", + "_test_autograd_multiple_dispatch_view": "self", +} + +for key in VIEW_FUNCTIONS_WITH_METADATA_CHANGE: + VIEW_FUNCTIONS[key] = "self" + +# note: some VIEW_FUNCTIONS are just compositions of the view functions above +# this list contains both the root view functions and any that are purely composed +# of viewing functions, and is used by the JIT to determine when an operator +# may return a view of its inputs; however they may sometimes return a copy. +# (e.g. `contiguous`) +RETURNS_VIEWS_OF_INPUT = set(VIEW_FUNCTIONS.keys()).union( + { + "chunk", + "detach", + "contiguous", + "reshape", + "reshape_as", + "expand_as", + "view_as", + "real", + "imag", + "narrow", + "movedim", + "tensor_split", + "swapdims", + "swapaxes", + "mT", + "mH", + "adjoint", + "matrix_H", + } +) + +# These are the functions we consider views for the purposes of validating +# StorageImpl and TensorImpl in gen_variable_type. +# `_unsafe_view` is not included in VIEW_FUNCTIONS above because it is not a +# view for the purposes of ADInplaceOrView kernel, we do not want to call as_view +# See NOTE [Unsafe View] for more info. +ALL_VIEW_FUNCTIONS = { + **VIEW_FUNCTIONS, + "_unsafe_view": "self", +} + +ARRAYREF_TO_VEC = CodeTemplate( + """\ +auto ${vec} = ${arg}.vec(); +""" +) + +OPTIONAL_TO_VAL = CodeTemplate( + """\ +auto ${val} = ${arg}.value_or(${default}); +""" +) + +CALL_DISPATCH = CodeTemplate( + """\ +at::_ops::${unambiguous_name}::call(${unpacked_args})""" +) + +REVERSE_VIEW_DISPATCH = CodeTemplate( + """\ +${reverse_name}(${unpacked_args})""" +) + +MULTI_OUTPUT_VIEW_ITERATION = CodeTemplate( + """\ +for (auto ${view_idx} : c10::irange(${var}.size())) { + ${body} +} +""" +) + +SETUP_REPLAY_VIEW_IF_NOT_SUPPORT_AS_STRIDED_OR_VIEW_WITH_METADATA_CHANGE = CodeTemplate( + """\ +std::unique_ptr func(nullptr); +std::function rev_func=nullptr; +if (${is_view_with_metadata_change} || + !self.unsafeGetTensorImpl()->support_as_strided() || + self.unsafeGetTensorImpl()->is_python_dispatch() || + c10::AutogradState::get_tls_state().get_view_replay_enabled()) { + ${replay_view_func} + ${reverse_replay_view_func} +} +""" +) + +REPLAY_VIEW_FUNC = CodeTemplate( + """\ +func = std::make_unique<${view_func_name}>(${view_func_args}); +""" +) + +REVERSE_REPLAY_VIEW_LAMBDA_FUNC = CodeTemplate( + """\ +rev_func = [=](const at::Tensor& ${input_view}) { + return ${reverse_replay_view_call}; +}; +""" +) + +METHOD_DEFINITION = CodeTemplate( + """\ +${return_type} ${type_wrapper_name}(${formals}) { + ${type_definition_body} +} +""" +) + +WRAPPER_REGISTRATION = CodeTemplate( + """\ +m.impl("${unqual_operator_name_with_overload}", + TORCH_FN(${class_type}::${type_wrapper_name}) +); +""" +) + +AUTOGRAD_NOT_IMPLEMENTED_REGISTRATION = CodeTemplate( + """\ +m.impl("${unqual_operator_name_with_overload}", torch::autograd::autogradNotImplementedFallback()); +""" +) + +INPLACE_REDISPATCH = CodeTemplate( + """\ +{ + at::AutoDispatchBelowADInplaceOrView guard; + at::_ops::${unambiguous_name}::redispatch(${unpacked_args}); +} +""" +) + +ASSIGN_RETURN_VALUE = CodeTemplate( + """\ +${return_values} = ${rhs_value}; +""" +) + +VIEW_REDISPATCH = CodeTemplate( + """\ +${assign_return_values} ([&]() { + at::AutoDispatchBelowADInplaceOrView guard; + return at::_ops::${unambiguous_name}::redispatch(${unpacked_args}); +})(); +""" +) + +TMP_VAR = "_tmp" + + +# FIXME: Ideally these functions should be methods on Type class, but we have a +# comment in codegen/model.py there saying these concepts are not well defined. +# Thus we put a version that commonly used by autograd codegen here. +def is_tensor_type(t: Type) -> bool: + # TODO: Should handle optional here? + return t.is_tensor_like() and t.is_list_like() is None + + +def is_tensor_list_type(t: Type) -> bool: + # TODO: Should handle optional here? + return t.is_tensor_like() and t.is_list_like() is not None + + +UNPACK_TENSOR = CodeTemplate( + """\ +auto${ref} ${arg_name}_ = unpack${suffix}(${arg_name}, "${arg_name}", ${arg_pos});""" +) + + +def unpacked_name(arg_name: str) -> str: + return arg_name + "_" + + +# e.g. select.int -> select_copy_int_inverse() +def inverse_view_name(f: NativeFunction) -> str: + copy_variant = f"{f.root_name}_copy" + overload = f"{f.func.name.overload_name}" + if overload != "": + overload = "_" + overload + return f"{copy_variant}{overload}_inverse" + + +def extract_bindings(f: NativeFunction) -> list[Binding]: + return [ + r + for a in f.func.schema_order_arguments() + for r in cpp.argument( + a, + method=False, + symint=True, + cpp_no_default_args=set(), + faithful=False, + has_tensor_options=False, + ) + ] + + +@with_native_function +def unpack_args(f: NativeFunction) -> tuple[list[str], list[Binding]]: + body: list[str] = [] + unpacked_bindings: list[Binding] = [] + + for i, binding in enumerate(extract_bindings(f)): + if isinstance(binding.argument, SelfArgument): + raise AssertionError("Binding argument should not be SelfArgument") + if isinstance(binding.argument, TensorOptionsArguments): + raise RuntimeError("VariableKernel shouldn't take TensorOptions") + + is_nullable = binding.argument.type.is_nullable() + if not binding.argument.type.is_tensor_like() or is_nullable: + unpacked_bindings.append(binding) + continue + + is_tensor_list = is_tensor_list_type(binding.argument.type) + ref = (not is_nullable) and not is_tensor_list + suffix = "_opt" if is_nullable and not is_tensor_list else "" + body.append( + UNPACK_TENSOR.substitute( + arg_name=binding.name, + arg_pos=i, + suffix=suffix, + ref="&" if ref else "", + ) + ) + unpacked_bindings.append( + Binding( + name=unpacked_name(binding.name), + nctype=binding.nctype, + argument=binding.argument, + default=binding.default, + ) + ) + + return body, unpacked_bindings + + +def get_base_name(f: NativeFunction) -> str: + return f.func.name.name.base # TODO: should be str(f.func.name.name)? + + +def get_view_info(f: NativeFunction) -> str | None: + base_name = get_base_name(f) + view_info = VIEW_FUNCTIONS.get(base_name) + if view_info is None and base_name in RETURNS_VIEWS_OF_INPUT: + view_info = "self" + return view_info + + +def emit_view_func( + f: NativeFunction, bindings: list[Binding], view_idx: str | None = None +) -> str: + """Generate an additional lambda function to recover views in backward when as_strided is not supported. + See Note [View + Inplace update for base tensor] and [View + Inplace update for view tensor] for more details. + """ + # TODO: Clean this logic up if we get rid of reverse view funcs or reify them. + input_base = "input_base" + replay_view_func = "" + updated_args: list[str] = [] + known_view_arg_simple_types: list[CType] = [ + BaseCType(longT), + OptionalCType(BaseCType(longT)), + BaseCType(SymIntT), + OptionalCType(BaseCType(SymIntT)), + BaseCType(boolT), + BaseCType(intArrayRefT), + BaseCType(symIntArrayRefT), + ConstRefCType(BaseCType(tensorT)), + ConstRefCType(OptionalCType(BaseCType(tensorT))), + ] + for binding in bindings: + arg, arg_type = binding.name, binding.nctype.type + if arg == "self": + updated_args.append(input_base) + continue + if arg_type not in known_view_arg_simple_types: + known_types_str = ", ".join([str(t) for t in known_view_arg_simple_types]) + raise TypeError( + f"You are adding an {arg_type} {arg} argument to op {cpp.name(f.func)} in addition to known types: " + f"{known_types_str}. Please update the list or materialize it so that it can be closed " + "over by value, also add a test in pytorch/xla/test/test_operations.py where this code " + "is exercised." + ) + if arg_type == BaseCType(intArrayRefT) or arg_type == BaseCType( + symIntArrayRefT + ): + # It's not safe to close over IntArrayRef by value, since this is a + # reference type, so materialize a vector to close over by value + arg_vec = arg + "_vec" + replay_view_func += ARRAYREF_TO_VEC.substitute(arg=arg, vec=arg_vec) + updated_args.append(arg_vec) + elif arg_type == OptionalCType(BaseCType(longT)): + # Materialize int64_t? to int64_t + arg_value = arg + "_val" + replay_view_func += OPTIONAL_TO_VAL.substitute( + arg=arg, val=arg_value, default="0" + ) + updated_args.append(arg_value) + elif arg_type == ConstRefCType(BaseCType(tensorT)) or arg_type == ConstRefCType( + OptionalCType(BaseCType(tensorT)) + ): + # NB: Closing over a tensor. If a user modifies this tensor, this will be silently + # incorrect. The proper thing to do is to store the version counter and copy on write. + updated_args.append(arg) + else: + updated_args.append(arg) + + from .gen_view_funcs import view_func_name + + view_func_args = [b.name for b in bindings if b.name != "self"] + if view_idx is not None: + view_func_args.append(f"{view_idx}") + replay_view_func += REPLAY_VIEW_FUNC.substitute( + view_func_name=view_func_name(f, include_namespace=True), + view_func_args=view_func_args, + ) + + input_view = "input_view" + reverse_unpacked_args = [ + "self", + f"{input_view}", + # inverse_return_mode= + "at::functionalization::InverseReturnMode::AlwaysView", + *(() if view_idx is None else (f"{view_idx}",)), + # skip input_base arg + *updated_args[1:], + ] + + from torchgen.api.functionalization import reverse_name + + reverse_replay_view_call = REVERSE_VIEW_DISPATCH.substitute( + reverse_name=reverse_name(f, include_namespace=True), + unpacked_args=reverse_unpacked_args, + ) + reverse_replay_view_func = REVERSE_REPLAY_VIEW_LAMBDA_FUNC.substitute( + input_view=input_view, reverse_replay_view_call=reverse_replay_view_call + ) + + is_view_with_metadata_change = ( + "true" if cpp.name(f.func) in VIEW_FUNCTIONS_WITH_METADATA_CHANGE else "false" + ) + + return SETUP_REPLAY_VIEW_IF_NOT_SUPPORT_AS_STRIDED_OR_VIEW_WITH_METADATA_CHANGE.substitute( + is_view_with_metadata_change=is_view_with_metadata_change, + replay_view_func=replay_view_func, + reverse_replay_view_func=reverse_replay_view_func, + ) + + +def emit_view_body( + fn: NativeFunctionWithDifferentiabilityInfo, var: str +) -> tuple[str, str]: + # See NOTE [ Autograd View Variables ] in variable.h for details. + f = fn.func + base_name = get_base_name(f) + view_info = get_view_info(f) + call = "" + differentiable_outputs = gen_differentiable_outputs(fn) + differentiable_output_vars = {r.name for r in differentiable_outputs} + if not isinstance(view_info, str): + raise TypeError( + f"The view info should be a string for {base_name}, but it is: {view_info}" + ) + if len(differentiable_output_vars) == 0: + # no output is differentiable (.indices() for SparseTensors for example) + rhs_value = ( + f"as_view({view_info}, {var}, " + f"/* is_bw_differentiable */ false, /* is_fw_differentiable */ false)" + ) + elif len(differentiable_output_vars) == 1: + # Single differentiable output (Tensor or Tensor[]) + return_info = differentiable_outputs[0] + # We only support simple Tensor or a TensorList for functions that return views + if not is_tensor_type(return_info.type) and not is_tensor_list_type( + return_info.type + ): + raise RuntimeError( + f"{base_name} that return differentiable views can only return Tensor or Tensor[]" + ) + + # See Note [ View + Inplace detection] + def get_creation_meta_in_mode(original: str) -> str: + creation_meta_with_grad_mode = f"(at::GradMode::is_enabled() ? {original} : CreationMeta::NO_GRAD_MODE)" + return f"InferenceMode::is_enabled() ? CreationMeta::INFERENCE_MODE : {creation_meta_with_grad_mode}" + + # Only allow rebasing of the history if we return a single Tensor + # If we are in a no grad block, raise a warning + # See NOTE [ View + Inplace detection ] for more details about this logic + if is_tensor_list_type(return_info.type): + creation_meta = get_creation_meta_in_mode("CreationMeta::MULTI_OUTPUT_NODE") + view_idx = "view_idx" + view_func = emit_view_func( + f, extract_bindings(f), view_idx=view_idx + ).strip() + as_view_call = ( + f"as_view(/* base */ {view_info}, /* output */ {var}[{view_idx}], " + "/* is_bw_differentiable */ true, /* is_fw_differentiable */ true, " + "/* view_func */ std::move(func), /* rev_view_func */ rev_func, " + f"/* creation_meta */ {creation_meta});" + ) + call += MULTI_OUTPUT_VIEW_ITERATION.substitute( + var=var, view_idx=view_idx, body=f"{view_func}\n{as_view_call}" + ) + rhs_value = f"std::move({var})" + else: + call += emit_view_func(f, extract_bindings(f), view_idx=None) + creation_meta = get_creation_meta_in_mode("CreationMeta::DEFAULT") + rhs_value = ( + f"as_view(/* base */ {view_info}, /* output */ {var}, /* is_bw_differentiable */ true, " + "/* is_fw_differentiable */ true, " + f"/* view_func */ std::move(func), /* rev_view_func */ rev_func, /* creation_meta */ {creation_meta})" + ) + else: + # This could be supported but we don't need it at the moment, so keeping things simple. + raise RuntimeError( + "Function that return multiple differentiable output " + "when at least one of them is view is not supported." + ) + return call, rhs_value + + +def modifies_arguments(f: NativeFunction) -> bool: + return f.func.kind() in [SchemaKind.inplace, SchemaKind.out] + + +@with_native_function_with_differentiability_info +def emit_inplace_or_view_body(fn: NativeFunctionWithDifferentiabilityInfo) -> list[str]: + f = fn.func + inplace_view_body: list[str] = [] + + dispatcher_sig = DispatcherSignature.from_schema(f.func) + dispatcher_exprs = dispatcher_sig.exprs() + + # code-generated ADInplaceOrView kernels plumb and recompute dispatch keys directly through the kernel for performance. + # See Note [Plumbing Keys Through The Dispatcher] for details. + dispatch_key_set = "ks & c10::after_ADInplaceOrView_keyset" + redispatch_args = ", ".join([dispatch_key_set] + [a.expr for a in dispatcher_exprs]) + + # Note that this calls the slow, dispatching variants of manual_cpp_binding ops. + # We could probably work harder to ensure that the fast variants are called instead, but the perf benefit would be minimal. + if modifies_arguments(f): # inplace op + inplace_view_body.append( + INPLACE_REDISPATCH.substitute( + unambiguous_name=f.func.name.unambiguous_name(), + unpacked_args=redispatch_args, + ) + ) + for r in cpp.return_names(f): + inplace_view_body.append(f"increment_version({r});") + else: + if get_view_info(f) is None: + raise AssertionError("Expected view info to be non-None") + inplace_view_body.append( + VIEW_REDISPATCH.substitute( + assign_return_values="auto " + TMP_VAR + " = ", + unambiguous_name=f.func.name.unambiguous_name(), + unpacked_args=redispatch_args, + ) + ) + call, rhs_value = emit_view_body(fn, TMP_VAR) + inplace_view_body.append(call) + if rhs_value is None: + raise AssertionError("Expected rhs_value to be non-None") + inplace_view_body.append( + ASSIGN_RETURN_VALUE.substitute( + return_values=tie_return_values(f), rhs_value=rhs_value + ) + ) + if f.func.returns: + inplace_view_body.append(f"return {get_return_value(f)};") + return inplace_view_body + + +@with_native_function +def gen_formals(f: NativeFunction) -> str: + return ", ".join( + # code-generated autograd kernels plumb and recompute dispatch keys directly through the kernel for performance. + # See Note [Plumbing Keys Through The Dispatcher] for details. + ["c10::DispatchKeySet ks"] + + [ + f"{cpp.argument_type(a, binds='__placeholder__', symint=True).cpp_type()} {a.name}" + for a in f.func.schema_order_arguments() + ] + ) + + +@with_native_function_with_differentiability_info +def inplace_or_view_method_definition( + fn: NativeFunctionWithDifferentiabilityInfo, +) -> str | None: + f = fn.func + if get_view_info(f) is None and ( + # For functions that modify their inputs but don't return them, + # we can't give them autograd support. + # See https://github.com/pytorch/pytorch/issues/53796 + not modifies_arguments(f) or len(f.func.returns) == 0 + ): + return None + return METHOD_DEFINITION.substitute( + return_type=cpp.returns_type(f.func.returns, symint=True).cpp_type(), + type_wrapper_name=type_wrapper_name(f), + formals=gen_formals(f), + type_definition_body=emit_inplace_or_view_body(fn), + ) + + +@with_native_function_with_differentiability_info +def inplace_or_view_method_registration( + fn: NativeFunctionWithDifferentiabilityInfo, +) -> str | None: + f = fn.func + if get_view_info(f) is None and ( + not modifies_arguments(f) or len(f.func.returns) == 0 + ): + return None + return WRAPPER_REGISTRATION.substitute( + unqual_operator_name_with_overload=f.func.name, + type_wrapper_name=type_wrapper_name(f), + class_type="ADInplaceOrView", + ) + + +def use_derived(fn: NativeFunctionWithDifferentiabilityInfo) -> bool: + f = fn.func + name = cpp.name(f.func) + return name not in MANUAL_AUTOGRAD and dispatch_strategy(fn) == "use_derived" + + +def gen_inplace_or_view_type_env( + fn: NativeFunctionWithDifferentiabilityInfo, +) -> dict[str, list[str]]: + definition = inplace_or_view_method_definition(fn) + registration = inplace_or_view_method_registration(fn) + + return { + "ops_headers": ( + [f"#include "] + if definition is not None + else [] + ), + "inplace_or_view_method_definitions": [definition] + if definition is not None + else [], + "inplace_or_view_wrapper_registrations": [registration] + if registration is not None + else [], + } + + +def gen_inplace_or_view_type( + out: str, + native_yaml_path: str, + tags_yaml_path: str, + fns_with_infos: list[NativeFunctionWithDifferentiabilityInfo], + template_path: str, +) -> None: + # NOTE: see Note [Sharded File] at the top of the VariableType.cpp + # template regarding sharding of the generated files. + + fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False) + fm.write_sharded( + "ADInplaceOrViewType.cpp", + [fn for fn in fns_with_infos if use_derived(fn)], + key_fn=lambda fn: fn.func.root_name, + base_env={ + "generated_comment": "@" + + f"generated from {fm.template_dir_for_comments()}/ADInplaceOrViewType.cpp", + }, + env_callable=gen_inplace_or_view_type_env, + num_shards=2, + sharded_keys={ + "ops_headers", + "inplace_or_view_method_definitions", + "inplace_or_view_wrapper_registrations", + }, + ) diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_python_functions.py b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_python_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..4731183c93c1faeb61a84ec85f42711c43835231 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_python_functions.py @@ -0,0 +1,1411 @@ +# Generates Python bindings for ATen functions +# +# The bindings are generated as methods on python_variable or functions on the +# torch._C._nn. torch._C._fft, torch._C._linalg, torch._C._nested, torch._C._sparse +# or torch._C._special objects. +# + +# Code tries to stick to the following rules: +# +# - templates should be colocated with the functions that use them. +# no templates are currently shared between functions, but if that +# happens, maybe put the template with the first one +# +# - don't use environment dictionaries when calling template.substitute(). +# pass named arguments directly for everything, otherwise it's much too +# hard to track what's actually being used and by who +# +# - colocate any new hacks/adjustments with existing ones of the same kind. +# ideally in a data structure rather than code if possible. See e.g. +# SCHEMA_DEFAULT_CONVERSION_HACKS, etc. +# +# - similarly, conversions from one format to another should ideally happen +# all at once in a single place. +# +# - no nontrivial nested functions. couple-liners are ok but please no more. +# especially avoid functions that read/write outer variables defined far away. +# +# - raise RuntimeError instead of asserting, and put as much +# information as is available into the message. I.e. no need to +# plumb in new params whose only purpose is to fill out an error +# message, but use what's there +# + +from __future__ import annotations + +import itertools +import re +from collections import defaultdict +from typing import TYPE_CHECKING + +import yaml + +from torchgen.api import cpp +from torchgen.api.python import ( + arg_parser_output_exprs, + cpp_dispatch_exprs, + cpp_dispatch_target, + dispatch_lambda_args, + dispatch_lambda_exprs, + dispatch_lambda_return_str, + has_tensor_options, + PythonSignature, + PythonSignatureDeprecated, + PythonSignatureGroup, + PythonSignatureNativeFunctionPair, + signature, + signature_from_schema, + structseq_fieldnames, +) +from torchgen.code_template import CodeTemplate +from torchgen.context import with_native_function +from torchgen.gen import cpp_string, parse_native_yaml, parse_tags_yaml +from torchgen.model import ( + Argument, + BaseOperatorName, + FunctionSchema, + NativeFunction, + SchemaKind, + Type, + Variant, +) +from torchgen.utils import FileManager, split_name_params +from torchgen.yaml_utils import YamlLoader + +from .gen_inplace_or_view_type import is_tensor_list_type +from .gen_trace_type import should_trace + + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Sequence + + +# +# declarations blocklist +# We skip codegen for these functions, for various reasons. +# Future PRs will categorize this list and eliminate or hoist +# them out of eager-only codegen. +# See https://github.com/pytorch/pytorch/issues/30788 +# + +# These functions require manual Python bindings or are not exposed to Python +_SKIP_PYTHON_BINDINGS = [ + "alias", + "contiguous", + "dim", + "get_device", + "is_contiguous", + "is_cuda", + "is_sparse", + "is_sparse_csr", + "numel", + "size", + "storage_offset", + "stride", + "sym_is_contiguous", + "sym_size", + "sym_stride", + "sym_storage_offset", + "sym_numel", + ".*_backward", + ".*_backward_(out|input|weight|bias)", + ".*_forward", + ".*_forward_out", + ".*_jvp", + "_unsafe_view", + "tensor", + "_?sparse_(coo|compressed|csr|csc|bsr|bsc)_tensor.*", + "_range.*", + "_sparse_add_out", + "_sparse_div.*", + "_sparse_mul.*", + "_sparse_sub.*", + "_sparse_dense_add_out", + "index", + "index_out", + "unique_dim_consecutive", + "_cumsum.*", + "_cumprod.*", + "_sum.*", + "_prod.*", + "_th_.*", + "_thnn_.*", + "range.*", + "_solve.*", + "_inverse.*", + "_cholesky.*", + "_triangular_solve.*", + "_qr.*", + "_svd.*", + "slice", + "item", + "_local_scalar_dense", + "to", + "_to_copy", + "_to_copy_out", + "_reshape_copy", + "_reshape_copy_out", + "copy_sparse_to_sparse_", + "copy_", + "_foreach_copy", + "numpy_T", + "matrix_H", + "mT", + "mH", # these need to be an attributes in Python, not functions + "nonzero(_(out|numpy))?", + "set_data", + ".*_overrideable", # overridable functions for backend extension + "data", + "is_leaf", + "output_nr", + "_version", + "requires_grad_", + "retains_grad", + "set_", + "_fw_primal", + "fake_quantize_per_tensor_affine_cachemask", + "fake_quantize_per_channel_affine_cachemask", + "_new_zeros_with_same_feature_meta", + "_has_same_storage_numel", # used for forward AD internals + "_reshape_alias", + "replace_", # only used by the functionalization pass, doesn't need to be exposed to python + "copy", # only used by the functionalization pass + "fill.Tensor", # only used by the functionalization pass + "fill.Scalar", # only used by the functionalization pass + "lift.*", + "normal_functional", # only used by the functionalization pass + "nbytes", + "itemsize", + "_batch_norm_with_update", + "_batch_norm_with_update_out", + "_batch_norm_no_update", +] + +SKIP_PYTHON_BINDINGS = [ + re.compile(rf"^{pattern}$") for pattern in _SKIP_PYTHON_BINDINGS +] + +# These function signatures are not exposed to Python. Note that this signature +# list does not support regex. +SKIP_PYTHON_BINDINGS_SIGNATURES = [ + "add.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor", + "add_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)", + "sub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor", + "sub_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)", + "mul.Scalar(Tensor self, Scalar other) -> Tensor", + "mul_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)", + "div.Scalar(Tensor self, Scalar other) -> Tensor", + "div_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)", +] + + +@with_native_function +def should_generate_py_binding(f: NativeFunction) -> bool: + # NativeFunctions that are entirely code-generated should not get python bindings + # because these codegen implementations are often inefficient. A handful of + # view_copy style ops were exposed accidentally when they were handwritten and now + # that we are moving them to codegen for bc reasons we need to keep them exposed in + # python. + if "generated" in f.tags and "view_copy" not in f.tags: + return False + + name = cpp.name(f.func) + for skip_regex in SKIP_PYTHON_BINDINGS: + if skip_regex.match(name): + return False + + signature = str(f.func) + for pattern in SKIP_PYTHON_BINDINGS_SIGNATURES: + if pattern == signature: + return False + return True + + +def get_pycname(name: BaseOperatorName) -> str: + return f"THPVariable_{name}" + + +def is_noarg(overloads: Sequence[PythonSignatureNativeFunctionPair]) -> bool: + return len(overloads) == 1 and overloads[0].signature.arguments_count() == 0 + + +def is_py_variable_method(f: NativeFunction) -> bool: + return f.python_module is None and Variant.method in f.variants + + +def is_py_torch_function(f: NativeFunction) -> bool: + return f.python_module is None and Variant.function in f.variants + + +def is_py_nn_function(f: NativeFunction) -> bool: + return f.python_module == "nn" + + +def is_py_fft_function(f: NativeFunction) -> bool: + return f.python_module == "fft" + + +def is_py_linalg_function(f: NativeFunction) -> bool: + return f.python_module == "linalg" + + +def is_py_nested_function(f: NativeFunction) -> bool: + return f.python_module == "nested" + + +def is_py_sparse_function(f: NativeFunction) -> bool: + return f.python_module == "sparse" + + +def is_py_special_function(f: NativeFunction) -> bool: + return f.python_module == "special" + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Main Function +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def gen( + out: str, + native_yaml_path: str, + tags_yaml_path: str, + deprecated_yaml_path: str, + template_path: str, + *, + symint: bool = True, +) -> None: + fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False) + native_functions = parse_native_yaml( + native_yaml_path, tags_yaml_path + ).native_functions + native_functions = list(filter(should_generate_py_binding, native_functions)) + + methods = load_signatures(native_functions, deprecated_yaml_path, method=True) + create_python_bindings( + fm, + methods, + is_py_variable_method, + None, + "python_variable_methods.cpp", + method=True, + symint=symint, + ) + + # NOTE: num_shards here must be synced with gatherTorchFunctions in + # torch/csrc/autograd/python_torch_functions_manual.cpp + functions = load_signatures(native_functions, deprecated_yaml_path, method=False) + create_python_bindings_sharded( + fm, + functions, + is_py_torch_function, + "torch", + "python_torch_functions.cpp", + method=False, + num_shards=3, + symint=symint, + ) + + create_python_bindings( + fm, + functions, + is_py_nn_function, + "torch.nn", + "python_nn_functions.cpp", + method=False, + symint=symint, + ) + + create_python_bindings( + fm, + functions, + is_py_fft_function, + "torch.fft", + "python_fft_functions.cpp", + method=False, + symint=symint, + ) + + create_python_bindings( + fm, + functions, + is_py_linalg_function, + "torch.linalg", + "python_linalg_functions.cpp", + method=False, + symint=symint, + ) + + create_python_bindings( + fm, + functions, + is_py_nested_function, + "torch.nested", + "python_nested_functions.cpp", + method=False, + ) + + create_python_bindings( + fm, + functions, + is_py_sparse_function, + "torch.sparse", + "python_sparse_functions.cpp", + method=False, + symint=symint, + ) + + create_python_bindings( + fm, + functions, + is_py_special_function, + "torch.special", + "python_special_functions.cpp", + method=False, + symint=symint, + ) + + # Currently, we only use `functions` to generate `return_types` bindings. + # All methods which return structseq have function variant at this point. + # If any method only operator with structseq is added in the future, + # we will have to address that. + create_python_return_type_bindings( + fm, functions, lambda fn: True, "python_return_types.cpp" + ) + create_python_return_type_bindings_header( + fm, functions, lambda fn: True, "python_return_types.h" + ) + + valid_tags = parse_tags_yaml(tags_yaml_path) + + def gen_tags_enum() -> dict[str, str]: + return { + "enum_of_valid_tags": ( + "".join( + [f'\n.value("{tag}", at::Tag::{tag})' for tag in sorted(valid_tags)] + ) + ) + } + + fm.write("python_enum_tag.cpp", gen_tags_enum) + + +def group_filter_overloads( + pairs: Sequence[PythonSignatureNativeFunctionPair], + pred: Callable[[NativeFunction], bool], +) -> dict[BaseOperatorName, list[PythonSignatureNativeFunctionPair]]: + grouped: dict[BaseOperatorName, list[PythonSignatureNativeFunctionPair]] = ( + defaultdict(list) + ) + for pair in pairs: + if pred(pair.function): + grouped[pair.function.func.name.name].append(pair) + return grouped + + +def create_python_bindings( + fm: FileManager, + pairs: Sequence[PythonSignatureNativeFunctionPair], + pred: Callable[[NativeFunction], bool], + module: str | None, + filename: str, + *, + method: bool, + symint: bool = True, +) -> None: + """Generates Python bindings to ATen functions""" + py_methods: list[str] = [] + ops_headers: list[str] = [] + py_method_defs: list[str] = [] + py_forwards: list[str] = [] + + grouped = group_filter_overloads(pairs, pred) + + for name in sorted(grouped.keys(), key=str): + overloads = grouped[name] + py_methods.append( + method_impl(name, module, overloads, method=method, symint=symint) + ) + py_method_defs.append(method_def(name, module, overloads, method=method)) + py_forwards.extend(forward_decls(name, overloads, method=method)) + ops_headers.append(f"#include ") + + fm.write_with_template( + filename, + filename, + lambda: { + "generated_comment": "@" + + f"generated from {fm.template_dir_for_comments()}/{filename}", + "ops_headers": ops_headers, + "py_forwards": py_forwards, + "py_methods": py_methods, + "py_method_defs": py_method_defs, + }, + ) + + +def create_python_return_type_bindings( + fm: FileManager, + pairs: Sequence[PythonSignatureNativeFunctionPair], + pred: Callable[[NativeFunction], bool], + filename: str, +) -> None: + """ + Generate function to initialize and return named tuple for native functions + which returns named tuple and registration invocations in `python_return_types.cpp`. + """ + py_return_types_definition: list[str] = [] + py_return_types_registrations: list[str] = [] + + grouped = group_filter_overloads(pairs, pred) + + for name in sorted(grouped.keys(), key=str): + overloads = grouped[name] + definitions, registrations = generate_return_type_definition_and_registrations( + overloads + ) + py_return_types_definition.append( + "" if not definitions else "\n".join(definitions) + ) + py_return_types_registrations.append( + "" if not registrations else "\n".join(registrations) + ) + + fm.write_with_template( + filename, + filename, + lambda: { + "generated_comment": "@" + + f"generated from {fm.template_dir_for_comments()}/{filename}", + "py_return_types": py_return_types_definition, + "py_return_types_registrations": py_return_types_registrations, + }, + ) + + +def create_python_return_type_bindings_header( + fm: FileManager, + pairs: Sequence[PythonSignatureNativeFunctionPair], + pred: Callable[[NativeFunction], bool], + filename: str, +) -> None: + """ + Generate function to initialize and return named tuple for native functions + which returns named tuple and relevant entry for the map in `python_return_types.cpp`. + """ + py_return_types_declarations: list[str] = [] + + grouped = group_filter_overloads(pairs, pred) + + for name in sorted(grouped.keys(), key=str): + overloads = grouped[name] + declarations = generate_return_type_declarations(overloads) + py_return_types_declarations.append( + "" if not declarations else "\n".join(declarations) + ) + + fm.write_with_template( + filename, + filename, + lambda: { + "generated_comment": "@" + + f"generated from {fm.template_dir_for_comments()}/{filename}", + "py_return_types_declarations": py_return_types_declarations, + }, + ) + + +def create_python_bindings_sharded( + fm: FileManager, + pairs: Sequence[PythonSignatureNativeFunctionPair], + pred: Callable[[NativeFunction], bool], + module: str | None, + filename: str, + *, + method: bool, + num_shards: int, + symint: bool = True, +) -> None: + """Generates Python bindings to ATen functions""" + grouped = group_filter_overloads(pairs, pred) + + def key_func( + kv: tuple[BaseOperatorName, list[PythonSignatureNativeFunctionPair]], + ) -> str: + return kv[0].base + + def env_func( + kv: tuple[BaseOperatorName, list[PythonSignatureNativeFunctionPair]], + ) -> dict[str, list[str]]: + name, fn_pairs = kv + return { + "ops_headers": [f"#include "], + "py_forwards": list(forward_decls(name, fn_pairs, method=method)), + "py_methods": [ + method_impl(name, module, fn_pairs, method=method, symint=symint) + ], + "py_method_defs": [method_def(name, module, fn_pairs, method=method)], + } + + fm.write_sharded( + filename, + grouped.items(), + base_env={ + "generated_comment": "@" + + f"generated from {fm.template_dir_for_comments()}/{filename}", + }, + key_fn=key_func, + env_callable=env_func, + num_shards=num_shards, + sharded_keys={"ops_headers", "py_forwards", "py_methods", "py_method_defs"}, + ) + + +def load_signatures( + native_functions: list[NativeFunction], + deprecated_yaml_path: str, + *, + method: bool, + skip_deprecated: bool = False, + pyi: bool = False, +) -> Sequence[PythonSignatureNativeFunctionPair]: + @with_native_function + def gen_signature_pairs(f: NativeFunction) -> PythonSignatureNativeFunctionPair: + return PythonSignatureNativeFunctionPair( + signature=signature(f, method=method, pyi=pyi), + function=f, + ) + + pairs = list(map(gen_signature_pairs, native_functions)) + deprecated = load_deprecated_signatures( + pairs, deprecated_yaml_path, method=method, pyi=pyi + ) + return pairs if skip_deprecated else pairs + deprecated + + +def load_deprecated_signatures( + pairs: Sequence[PythonSignatureNativeFunctionPair], + deprecated_yaml_path: str, + *, + method: bool, + pyi: bool, +) -> list[PythonSignatureNativeFunctionPair]: + # The deprecated.yaml doesn't have complete type information, we need + # find and leverage the original ATen signature (to which it delegates + # the call) to generate the full python signature. + # We join the deprecated and the original signatures using type-only form. + + # group the original ATen signatures by name + grouped: dict[str, list[PythonSignatureNativeFunctionPair]] = defaultdict(list) + for pair in pairs: + grouped[pair.signature.name].append(pair) + + # find matching original signatures for each deprecated signature + results: list[PythonSignatureNativeFunctionPair] = [] + + with open(deprecated_yaml_path) as f: + deprecated_defs = yaml.load(f, Loader=YamlLoader) + + for deprecated in deprecated_defs: + schema = FunctionSchema.parse(deprecated["name"]) + aten_name, call_args = split_name_params(deprecated["aten"]) + is_out = aten_name.endswith("_out") + if is_out: + aten_name = aten_name.replace("_out", "") + + # HACK: these are fixed constants used to pass the aten function. + # The type must be known ahead of time + known_constants = { + "1": Type.parse("Scalar"), + } + schema_args_by_name = {a.name: a for a in schema.arguments.flat_all} + for name in call_args: + if name not in schema_args_by_name and name not in known_constants: + raise AssertionError( + f"deprecation definition: Unrecognized value {name}" + ) + + # Map deprecated signature arguments to their aten signature and test + # if the types and alias annotation match. + def is_schema_compatible( + aten_schema: FunctionSchema, + ) -> bool: + arguments: Iterable[Argument] + if is_out: + arguments = itertools.chain( + aten_schema.arguments.out, aten_schema.arguments.flat_non_out + ) + else: + arguments = aten_schema.arguments.flat_all + + for i, arg in enumerate(arguments): + if i < len(call_args): + arg_name = call_args[i] + if arg_name in known_constants: + schema_type = known_constants[arg_name] + schema_annotation = None + else: + schema_arg = schema_args_by_name[arg_name] + schema_type = schema_arg.type + schema_annotation = schema_arg.annotation + + if schema_type != arg.type or schema_annotation != arg.annotation: + return False + else: + if arg.default is None: + return False + + return len(schema.returns) == len(aten_schema.returns) and all( + a == b for a, b in zip(schema.returns, aten_schema.returns) + ) + + any_schema_found = False + for pair in grouped[aten_name]: + if not is_schema_compatible(pair.function.func): + continue + any_schema_found = True + + python_sig = signature_from_schema( + schema, + category_override=pair.function.category_override, + method=method, + pyi=pyi, + ) + + results.append( + PythonSignatureNativeFunctionPair( + signature=PythonSignatureDeprecated( + name=python_sig.name, + input_args=python_sig.input_args, + input_kwargs=python_sig.input_kwargs, + output_args=python_sig.output_args, + tensor_options_args=python_sig.tensor_options_args, + method=python_sig.method, + deprecated_schema=schema, + deprecated_args_exprs=tuple(call_args), + returns=python_sig.returns, + ), + function=pair.function, + ) + ) + if not any_schema_found: + raise AssertionError( + f"No native function with name {aten_name} matched signature:\n {str(schema)}" + ) + + return results + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Named Tuple Codegen +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +@with_native_function +def gen_structseq_typename_key(f: NativeFunction) -> str: + name = cpp.name(f.func) + fieldnames = structseq_fieldnames(f.func.returns) + return "_".join([name] + fieldnames) + + +def emit_structseq_call( + overloads: Sequence[PythonSignatureNativeFunctionPair], +) -> tuple[list[str], dict[str, str]]: + """ + Generate block of named tuple type def inits, and add typeref snippets + to declarations that use them + """ + typenames: dict[ + str, str + ] = {} # map from unique name + field name lists to typedef name + typedefs: list[str] = [] # typedef declarations and init code + + for overload in overloads: + fieldnames = structseq_fieldnames(overload.function.func.returns) + if not fieldnames: + continue + + name = cpp.name(overload.function.func) # use @with_native_function? + tn_key = gen_structseq_typename_key(overload.function) + typename = typenames.get(tn_key) + if typename is None: + typename = f"NamedTuple{'' if not typedefs else len(typedefs)}" + typenames[tn_key] = typename + typedefs.append( + f"""\ +static PyTypeObject* {typename} = generated::get_{name}_structseq();""" + ) + + return typedefs, typenames + + +def generate_return_type_definition_and_registrations( + overloads: Sequence[PythonSignatureNativeFunctionPair], +) -> tuple[list[str], list[str]]: + """ + Generate block of function in `python_return_types.cpp` to initialize + and return named tuple for a native function which returns named tuple + and registration invocations in same file. + """ + typenames: dict[ + str, str + ] = {} # map from unique name + field name lists to typedef name + definitions: list[str] = [] # function definition to register the typedef + registrations: list[str] = [] # register call for the typedef + + for overload in overloads: + fieldnames = structseq_fieldnames(overload.function.func.returns) + if not fieldnames: + continue + + fields = ", ".join(f'{{"{fn}", ""}}' for fn in fieldnames) + + name = cpp.name(overload.function.func) # use @with_native_function? + tn_key = gen_structseq_typename_key(overload.function) + typename = typenames.get(tn_key) + + if typename is None: + typename = f"{name}NamedTuple{'' if not definitions else len(definitions)}" + typenames[tn_key] = typename + definitions.append( + f"""\ +PyTypeObject* get_{name}_structseq() {{ + static PyStructSequence_Field NamedTuple_fields[] = {{ {fields}, {{nullptr}} }}; + static PyTypeObject {typename}; + static bool is_initialized = false; + static PyStructSequence_Desc desc = {{ "torch.return_types.{name}", nullptr, NamedTuple_fields, {len(fieldnames)} }}; + if (!is_initialized) {{ + PyStructSequence_InitType(&{typename}, &desc); + {typename}.tp_repr = (reprfunc)torch::utils::returned_structseq_repr; + is_initialized = true; + }} + return &{typename}; +}} +""" + ) + registrations.append( + f'addReturnType(return_types_module, "{name}", generated::get_{name}_structseq());' + ) + + return definitions, registrations + + +def generate_return_type_declarations( + overloads: Sequence[PythonSignatureNativeFunctionPair], +) -> list[str]: + """ + Generate block of function declarations in `python_return_types.h` to initialize + and return named tuple for a native function. + """ + typenames: dict[ + str, str + ] = {} # map from unique name + field name lists to typedef name + declarations: list[str] = [] # function declaration to register the typedef + + for overload in overloads: + fieldnames = structseq_fieldnames(overload.function.func.returns) + if not fieldnames: + continue + + name = cpp.name(overload.function.func) # use @with_native_function? + tn_key = gen_structseq_typename_key(overload.function) + typename = typenames.get(tn_key) + + if typename is None: + typename = ( + f"{name}NamedTuple{'' if not declarations else len(declarations)}" + ) + typenames[tn_key] = typename + declarations.append(f"PyTypeObject* get_{name}_structseq();") + + return declarations + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Method Impl Codegen +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + +# python binding for all overloads of a particular function/method +PY_VARIABLE_METHOD_VARARGS = CodeTemplate( + r"""\ +// ${name} +static PyObject * ${pycname}(PyObject* self_, PyObject* args, PyObject* kwargs) +{ + ${method_header} + static PythonArgParser parser({ + ${signatures} + }, /*traceable=*/${traceable}); + + ParsedArgs<${max_args}> parsed_args; + auto _r = parser.parse(${self_}, args, kwargs, parsed_args); + ${check_has_torch_function} + switch (_r.idx) { + ${dispatch} + } + ${method_footer} +} + +""" +) + +# handler for a single parsed signature - may be a single overload or +# a pair of overloads that whose signatures only differ in output params +# (plugged into PY_VARIABLE_METHOD_VARARGS as an item in ${dispatch}) +PY_VARIABLE_CASE = CodeTemplate( + """\ +case ${overload_index}: { + ${body} +} +""" +) + +# python binding for single-overload function/method +PY_VARIABLE_METHOD_VARARGS_SINGLETON = CodeTemplate( + """\ +// ${name} +static PyObject * ${pycname}(PyObject* self_, PyObject* args, PyObject* kwargs) +{ + ${method_header} + static PythonArgParser parser({ + ${signatures} + }, /*traceable=*/${traceable}); + + ParsedArgs<${max_args}> parsed_args; + auto _r = parser.parse(${self_}, args, kwargs, parsed_args); + ${check_has_torch_function} + ${dispatch} + ${method_footer} +} + +""" +) + +# python binding for a method with no args, shortcuts parsing +PY_VARIABLE_METHOD_NOARGS = CodeTemplate( + """\ +// ${name} +static PyObject * ${pycname}(PyObject* self_, PyObject* args) +{ + ${method_header} + ${check_has_torch_function} + ${dispatch} + ${method_footer} +} + +""" +) + + +def method_impl( + name: BaseOperatorName, + module: str | None, + overloads: Sequence[PythonSignatureNativeFunctionPair], + *, + method: bool, + symint: bool = True, +) -> str: + """ + Generate a python binding for all overloads of an op. + """ + pycname = get_pycname(name) + noarg = is_noarg(overloads) + structseq_inits, structseq_typenames = emit_structseq_call(overloads) + + method_header = ["HANDLE_TH_ERRORS"] + method_header += structseq_inits + method_header += ( + ["const Tensor& self = THPVariable_Unpack(self_);"] if method else [] + ) + + method_footer = ([] if noarg else ["Py_RETURN_NONE;"]) + ["END_HANDLE_TH_ERRORS"] + + traceable = "true" if all(should_trace(o.function) for o in overloads) else "false" + + grouped_overloads: Sequence[PythonSignatureGroup] = group_overloads( + overloads, symint=symint + ) + is_singleton = len(grouped_overloads) == 1 + signatures: list[str] = [] + dispatch: list[str] = [] + for overload_index, overload in enumerate(grouped_overloads): + signature = overload.signature.signature_str(symint=symint) + signatures.append(f"{cpp_string(str(signature))},") + dispatch_body = emit_dispatch_case(overload, structseq_typenames, symint=symint) + dispatch.append( + PY_VARIABLE_CASE.substitute( + overload_index=overload_index, body=dispatch_body + ) + if not is_singleton + else dispatch_body + ) + + if noarg: + template = PY_VARIABLE_METHOD_NOARGS + elif is_singleton: + template = PY_VARIABLE_METHOD_VARARGS_SINGLETON + else: + template = PY_VARIABLE_METHOD_VARARGS + + return template.substitute( + name=name, + pycname=pycname, + method_header=method_header, + max_args=max(o.signature.arguments_count() for o in overloads), + signatures=signatures, + traceable=traceable, + check_has_torch_function=gen_has_torch_function_check( + name=name, + module=module, + noarg=noarg, + method=method, + ), + dispatch=dispatch, + method_footer=method_footer, + self_="self_" if method else "nullptr", + ) + + +def gen_has_torch_function_check( + name: BaseOperatorName, module: str | None, *, noarg: bool, method: bool +) -> str: + if noarg: + if method: + return f"""\ +if (has_torch_function(self_)) {{ + return handle_torch_function(self_, "{name}"); +}} +""" + else: + return "" + + self_ = "self_" if method else "nullptr" + namespace = ( + { + "torch": "THPVariableFunctionsModule", + "torch.nn": "THPNNVariableFunctionsModule", + "torch.fft": "THPFFTVariableFunctionsModule", + "torch.linalg": "THPLinalgVariableFunctionsModule", + "torch.nested": "THPNestedVariableFunctionsModule", + "torch.sparse": "THPSparseVariableFunctionsModule", + "torch.special": "THPSpecialVariableFunctionsModule", + }[module] + if module + else "THPVariableClass" + ) + + return f"""\ +if(_r.has_torch_function()) {{ + return handle_torch_function(_r, {self_}, args, kwargs, {namespace}, "{module or "torch.Tensor"}"); +}} +""" + + +# handler for output/no-output overload pair +PY_VARIABLE_OUT = CodeTemplate( + """\ +if (_r.isNone(${out_idx})) { + ${call_dispatch} +} else { + ${call_dispatch_out} +} +""" +) + + +def emit_dispatch_case( + overload: PythonSignatureGroup, + structseq_typenames: dict[str, str], + *, + symint: bool = True, +) -> str: + """ + Emit dispatch code for a single parsed signature. This corresponds to either + a single native function, or a pair that differ only in output params. In the + latter case, a single python signature is used for both and dispatching + switches on the presence/absence of passed output args. + """ + if overload.outplace is not None: + # dispatch output and no-output variants, branch on _r.isNone() + return PY_VARIABLE_OUT.substitute( + out_idx=overload.signature.output_idx(), + call_dispatch=emit_single_dispatch( + overload.signature, overload.base, structseq_typenames, symint=symint + ), + call_dispatch_out=emit_single_dispatch( + overload.signature, + overload.outplace, + structseq_typenames, + symint=symint, + ), + ) + else: + # no-output version only + return emit_single_dispatch( + overload.signature, overload.base, structseq_typenames, symint=symint + ) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Forward Declarations Codegen +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def forward_decls( + name: BaseOperatorName, + overloads: Sequence[PythonSignatureNativeFunctionPair], + *, + method: bool, +) -> tuple[str, ...]: + if method: + return () + + pycname = get_pycname(name) + if is_noarg(overloads): + return ( + f"""\ +static PyObject * {pycname}(PyObject* self_, PyObject* args); +""", + ) + else: + return ( + f"""\ +static PyObject * {pycname}(PyObject* self_, PyObject* args, PyObject* kwargs); +""", + ) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Method Def (Binding Table Entry) Codegen +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def method_def( + name: BaseOperatorName, + module: str | None, + overloads: Sequence[PythonSignatureNativeFunctionPair], + *, + method: bool, +) -> str: + """ + Generate method def entry. + """ + pycname = get_pycname(name) + + if name.dunder_method: + # PyMethodDef entry for binary op, throws not implemented error + pycname = f"TypeError_to_NotImplemented_<{pycname}>" + + if is_noarg(overloads): + flags = "METH_NOARGS" if method else "METH_VARARGS | METH_KEYWORDS" + else: + pycname = f"castPyCFunctionWithKeywords({pycname})" + flags = "METH_VARARGS | METH_KEYWORDS" + + if module == "torch": + flags += " | METH_STATIC" + + return f'{{"{name}", {pycname}, {flags}, nullptr}},' + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Overload Sorting and Grouping +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def group_overloads( + overloads: Sequence[PythonSignatureNativeFunctionPair], *, symint: bool = True +) -> Sequence[PythonSignatureGroup]: + bases: dict[str, PythonSignatureNativeFunctionPair] = {} + outplaces: dict[str, PythonSignatureNativeFunctionPair] = {} + + # first group by signature ignoring out arguments + for overload in overloads: + sig = overload.signature.signature_str(skip_outputs=True, symint=symint) + if overload.function.func.is_out_fn(): + if sig in outplaces: + raise RuntimeError( + f"Found duplicated function definition:\n- {overload.function.func}.\n" + f"Existing definition:\n- {outplaces[sig].function.func}." + ) + outplaces[sig] = overload + else: + if sig in bases: + raise RuntimeError( + f"Found duplicated function definition:\n- {overload.function.func}.\n" + f"Existing definition:\n- {bases[sig].function.func}." + ) + bases[sig] = overload + + for sig, out in outplaces.items(): + if sig not in bases: + candidates: list[str] = [] + for overload in overloads: + if ( + str(overload.function.func.name.name) + == str(out.function.func.name.name) + and not overload.function.func.is_out_fn() + and not overload.signature.deprecated + ): + candidates.append( + overload.signature.signature_str( + skip_outputs=True, symint=symint + ) + ) + out_sig = out.signature.signature_str(symint=symint) + raise RuntimeError( + f"While identifying overloads, we found an out schema {out_sig} without a corresponding non-out variant. " + f"We expected the non-out variant to have schema: \n- {sig}\nPlease check that you spelled the schema " + "correctly in native_functions.yaml. We discovered the following candidate(s): \n" + + "\n".join(f"- {candidate}" for candidate in candidates) + ) + + grouped = [ + PythonSignatureGroup.from_pairs( + functional=base, + out=outplaces.get(sig), + ) + for sig, base in bases.items() + ] + return sort_overloads(grouped, symint=symint) + + +# This function declares a partial order on declarations, and sorts them according +# to its linear extension. This is necessary, because there's some ambiguity in the +# choice of overload, and we want a different order. +# +# See Note[Order of overloads matters] +# +# A few examples of ambiguous python signature pairs. +# +# All parameters have the same type, except one taking Tensor the other taking +# Scalar. A numeric PyObject can be casted into Tensor, and a zero-dim Tensor +# object can be accepted as Scalar type parameter (see python_arg_parser.cpp). +# Therefore, same input arguments might be accepted by either python signature. +# We want to always parse the one taking Tensor first. +# +# bitwise_and(Tensor input, Tensor other, *, Tensor out=None) +# bitwise_and(Tensor input, Scalar other, *, Tensor out=None) +# +# If they have different number of parameters then they are not ambiguous - but +# the difference on output param can be ignored as it's optional. +# +# multiply(Tensor input, Tensor other, *, Tensor out=None) +# multiply(Tensor input, Scalar other) +# +# Both positional args and keyword-only args are considered together. +# +# subtract(Tensor other, *, Scalar alpha=1) +# subtract(Scalar other, Scalar alpha=1) +# +# A few ambiguous cases which it does NOT handle yet. +# +# If there is any difference in other parameters besides the Tensor/Scalar +# difference, then they are not considered ambiguous by this method anymore. +# However, the difference could be too trivial to disambiguate. +# +# foo(Tensor input, Scalar other, Scalar bar) +# foo(Tensor input, Tensor other, double bar) +# +# If they are taking different number of parameters then they are not considered +# ambiguous anymore, even if the difference is only on optional kwargs. +# +# foo(Scalar other, Scalar alpha=1) +# foo(Tensor other, *, Scalar alpha=1, Scalar beta=1) +# + + +def sort_overloads( + grouped_overloads: Sequence[PythonSignatureGroup], *, symint: bool = True +) -> Sequence[PythonSignatureGroup]: + # NB: Smaller here means lower priority + + def is_arg_smaller(t1: Type, t2: Type) -> bool: + return ( + str(t1) == "Scalar" + and str(t2) == "Tensor" + or str(t1) == "Scalar?" + and str(t2) == "Tensor?" + or + # In the discussion https://github.com/pytorch/pytorch/issues/54555 it has been + # discussed why it is important to prioritize int/int? over int[] + str(t1) == "int[]" + and (str(t2) == "int" or str(t2) == "int?") + or + # TensorList currently throws an error during argument parsing, that's why it needs to be + # last in signature ordering. See discussion: https://github.com/pytorch/pytorch/issues/58087 + str(t1) == "Tensor[]" + and str(t2).find("[]") != -1 + or + # Prioritize IntArrayRef overload over SymIntArrayRef + str(t1) == "SymInt[]" + and str(t2) == "int[]" + or + # Make sure both in, SymInt are sorted consistently w.r.t. Tensor since Tensor can be implicitly + # converted to either int or SymInt. Prioritize the Tensor overload since it otherwise gets shadowed. + (str(t1) == "SymInt" or str(t1) == "int") + and str(t2) == "Tensor" + ) + + def is_smaller(s1: PythonSignature, s2: PythonSignature) -> bool: + """Returns True if s1 < s2 in the partial order.""" + args1, args2 = s1.arguments(skip_outputs=True), s2.arguments(skip_outputs=True) + if len(args1) != len(args2): + return False + # TODO: should use some canonical form instead of 'str(arg.type)' - see comments + # above. The old codegen used the deprecated 'dynamic_type(arg.type)', which + # ignores the optional annotation, i.e. 'Scalar' and 'Scalar?'. + equal = all(arg1.type == arg2.type for arg1, arg2 in zip(args1, args2)) + smaller_or_equal = all( + str(arg1.type) == str(arg2.type) or is_arg_smaller(arg1.type, arg2.type) + for arg1, arg2 in zip(args1, args2) + ) + return smaller_or_equal and not equal + + # First sort by signature + grouped_overloads = sorted( + grouped_overloads, key=lambda x: x.signature.signature_str(symint=symint) + ) + + # Construct the relation graph + larger_than: dict[int, set[int]] = defaultdict(set) + for i1, overload1 in enumerate(grouped_overloads): + for i2, overload2 in enumerate(grouped_overloads): + if is_smaller(overload1.signature, overload2.signature): + larger_than[i1].add(i2) + + if not larger_than: + return list(grouped_overloads) + + # Use a topological sort to sort overloads according to the partial order. + N = len(grouped_overloads) + sorted_ids: list[int] = list(filter(lambda x: x not in larger_than, range(N))) + + for idx in range(N): + # The size of sorted_ids will grow to N eventually. + i = sorted_ids[idx] + for j in sorted(larger_than.keys()): + larger = larger_than[j] + larger.discard(i) + if not larger: + del larger_than[j] + sorted_ids.append(j) + + return [grouped_overloads[x] for x in sorted_ids] + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # +# +# Codegen API Integration +# +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # + + +def emit_single_dispatch( + ps: PythonSignature, + f: NativeFunction, + structseq_typenames: dict[str, str], + *, + symint: bool = True, +) -> str: + """ + Emit dispatch code for a single native function. + """ + + @with_native_function + def go(f: NativeFunction) -> str: + # header comments + if isinstance(ps, PythonSignatureDeprecated): + schema_comment = f"// [deprecated] aten::{ps.deprecated_schema}" + else: + schema_comment = f"// aten::{f.func}" + + # dispatch lambda signature + name = cpp.name(f.func) + lambda_formals = ", ".join( + f"{a.type_str} {a.name}" for a in dispatch_lambda_args(ps, f, symint=symint) + ) + lambda_return = dispatch_lambda_return_str(f) + + # dispatch lambda body + dispatch_callee = cpp_dispatch_target(f) + dispatch_args = ", ".join(cpp_dispatch_exprs(f, python_signature=ps)) + + # from arg parser outputs to dispatch lambda arguments + parser_outputs = arg_parser_output_exprs(ps, f, symint=symint) + lambda_arg_exprs = dispatch_lambda_exprs(ps, f, symint=symint) + inits = "\n".join(lambda_arg_exprs.inits) + lambda_args = ", ".join(lambda_arg_exprs.exprs) + + # scatter fields + # TODO: Checking `ps.method and ('requires_grad' in parser_outputs)` is a hacky + # solution for enabling the 'requires_grad' argument for tensor methods + # new_full, new_empty, and new_zeros. A much better but more difficult to + # implement solution involves refactoring according to Ed's description here: + # https://github.com/pytorch/pytorch/issues/36455#issuecomment-614767589 + need_set_requires_grad = ps.tensor_options_args and ( + not has_tensor_options(f) + or (ps.method and ("requires_grad" in parser_outputs)) + ) + set_requires_grad = ( + f".set_requires_grad({parser_outputs['requires_grad'].expr})" + if need_set_requires_grad + else "" + ) + + if lambda_return == "void": + # Make in-place foreach return `self` at python-binding level. + # ref: https://github.com/pytorch/pytorch/pull/118622#pullrequestreview-1904804954 + self_arg = f.func.arguments.self_arg + return_stmt: str + if ( + str(f.func.name).startswith("_foreach_") + and f.func.kind() == SchemaKind.inplace + ): + # note(crcrpar): `_foreach_pow.ScalarAndTensor` does NOT have its in-place + # variant and it unlikely to have it in the future. Thus it's safe to have the following check. + if self_arg is None or not is_tensor_list_type(self_arg.argument.type): + raise AssertionError( + "Expected self_arg to be a tensor list type for inplace foreach" + ) + return_stmt = """PyObject* self_tensorlist = _r.args[0]; +Py_INCREF(self_tensorlist); +return self_tensorlist; +""" + else: + return_stmt = "Py_RETURN_NONE;" + return f"""\ +{schema_comment} +{inits} +auto dispatch_{name} = []({lambda_formals}) -> {lambda_return} {{ + pybind11::gil_scoped_release no_gil; + {dispatch_callee}({dispatch_args}); +}}; +dispatch_{name}({lambda_args}){set_requires_grad}; +{return_stmt} +""" + else: + typename = structseq_typenames.get(gen_structseq_typename_key(f)) + structseq_typeref = f"{typename}, " if typename is not None else "" + return f"""\ +{schema_comment} +{inits} +auto dispatch_{name} = []({lambda_formals}) -> {lambda_return} {{ + pybind11::gil_scoped_release no_gil; + return {dispatch_callee}({dispatch_args}); +}}; +return wrap({structseq_typeref}dispatch_{name}({lambda_args}){set_requires_grad}); +""" + + return go(f) diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_trace_type.py b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_trace_type.py new file mode 100644 index 0000000000000000000000000000000000000000..89408bda6de923f13b18e71073eb88a721d105f0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_trace_type.py @@ -0,0 +1,542 @@ +from __future__ import annotations + +import itertools +from typing import TYPE_CHECKING + +from torchgen.api import cpp +from torchgen.api.types import DispatcherSignature +from torchgen.code_template import CodeTemplate +from torchgen.context import with_native_function +from torchgen.model import Argument, NativeFunction, SchemaKind, TensorOptionsArguments +from torchgen.utils import FileManager + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +# Note [Manual Backend kernels] +# For these ops, we want to manually register to dispatch key Backend and +# skip codegen-ed registration to all keys before Backend. +# For codegen this means: +# - op set below must match ops with manual_kernel_registration=True in native_functions.yaml +# where we skip codegen backend kernels +# - all ops below are part of MANUAL_AUTOGRAD to skip codegen Autograd kernel registration +# - all ops below are part of MANUAL_TRACER to skip codegen Tracer kernel registration +# Note: we still register to dispatch key Profiler for these ops, keeping it untouched for now. +# You can find the manual registration in torch/csrc/autograd/VariableTypeManual.cpp +MANUAL_BACKEND = { + "options", + "data", + "set_data", + "is_leaf", + "output_nr", + "_version", + "retain_grad", + "_backward", + "requires_grad_", +} + +# For these ops we want to skip the codegen-ed registration to both Autograd and Tracer keys. +# You can find the manual registration in torch/csrc/autograd/VariableTypeManual.cpp +MANUAL_AUTOGRAD_AND_TRACER = { + "resize_", + "resize_as_", + "detach", + "detach_", + "copy_", + "_fw_primal", + "_make_dual", +} + +# Currently MANUAL_AUTOGRAD and MANUAL_TRACER share the same set of ops: +# union(MANUAL_BACKEND, MANUAL_AUTOGRAD_AND_TRACER) +# You can find the manual registration in torch/csrc/autograd/VariableTypeManual.cpp +MANUAL_AUTOGRAD = MANUAL_TRACER = MANUAL_BACKEND | MANUAL_AUTOGRAD_AND_TRACER + +# These functions we don't want to record for tracing, because we always want +# to trace their constituent parts. This is a temporary hack in lieue +# of proper scopes, where subsequent compilation passes can ask for the unfolding +# on demand. Only concrete ATen methods can be disabled this way; it will have +# NO EFFECT otherwise. +DONT_RECORD_TRACE = { + "convolution", + "conv1d", + "conv2d", + "conv3d", + "conv_transpose1d", + "conv_transpose2d", + "conv_transpose3d", + "lstm_cell", + "gru_cell", + "rnn_tanh_cell", + "rnn_relu_cell", + # FIXME: figure out a better way when we support sparse tensors in jit + "_coalesced", +} + + +def should_trace(f: NativeFunction) -> bool: + # Operations involving Storage or Type are not traceable at the moment + if any( + str(arg.type) in {"Storage", "Type"} for arg in f.func.schema_order_arguments() + ): + return False + # We can't trace functions which don't have any Tensor or TensorList returns + if not any(r.type.is_tensor_like() for r in f.func.returns): + return False + return f.func.name.name.base not in DONT_RECORD_TRACE + + +SELECT = CodeTemplate( + """\ + +if (${cond}) { + ${true} +} else { + ${false} +} +""" +) + +OP_NAME = CodeTemplate( + """\ +op_name = c10::Symbol::fromQualString("aten::${trace_name}"); +""" +) + +# These functions have their names recorded under trace renamed, +RENAME_TRACE = { + "zero": "zeros_like", # replacing aten::zero_ with aten::zeros_like + "fill": "full_like", # replacing aten::fill_ with aten::full_like +} + + +def format_trace_op_name(f: NativeFunction) -> str: + # TODO: byte-for-byte compatible with old codegen behavior - should clean up + if ( + f.func.kind() in (SchemaKind.functional, SchemaKind.out) + or f.func.name.name.dunder_method + ): + # special case for *_out functions: the in-place and out-of-place ops + # are overloaded with the same name in the JIT + trace_name = str(f.func.name.name) + trace_name = RENAME_TRACE.get(trace_name, trace_name) + return OP_NAME.substitute(trace_name=trace_name) + + # otherwise, this is an in-place op and we need to emit both in- and + # out-of-place versions + outplace_trace_name = f.func.name.name.base + inplace_trace_name = cpp.name(f.func) + outplace_trace_name = RENAME_TRACE.get(outplace_trace_name, outplace_trace_name) + inplace_trace_name = RENAME_TRACE.get(inplace_trace_name, inplace_trace_name) + + return SELECT.substitute( + cond="tracer_state->force_outplace", + true=OP_NAME.substitute(trace_name=outplace_trace_name), + false=OP_NAME.substitute(trace_name=inplace_trace_name), + ) + + +ADD_TRACE_INPUT = CodeTemplate("""jit::tracer::addInputs(node, "${name}", ${input});""") + + +def format_trace_inputs(f: NativeFunction) -> str: + def dispatch_trace_input(arg: Argument | TensorOptionsArguments) -> Sequence[str]: + if isinstance(arg, TensorOptionsArguments): + name = "options" + return [ + ADD_TRACE_INPUT.substitute( + name=name, input="c10::optTypeMetaToScalarType(options.dtype_opt())" + ), + ADD_TRACE_INPUT.substitute(name=name, input="options.layout()"), + ADD_TRACE_INPUT.substitute(name=name, input="options.device()"), + ADD_TRACE_INPUT.substitute(name=name, input="options.pinned_memory()"), + ] + else: + name = arg.name + if str(arg.type) == "Tensor?[]": + return [f'jit::tracer::addInputs(node, "{name}", {name});'] + else: + return [ADD_TRACE_INPUT.substitute(name=name, input=name)] + + args: list[Argument | TensorOptionsArguments] = list( + f.func.schema_order_arguments() + ) + + if f.func.is_out_fn(): + # *_out functions take the result as a separate argument, but we don't want to + # trace that argument directly. Instead, we trace its TensorOptions. + # So first, we need to remove the out argument from the list of arguments to trace. + num_out_args = len(f.func.arguments.out) + args = args[:-num_out_args] + + trace_inputs = itertools.chain.from_iterable( + dispatch_trace_input(arg) for arg in args + ) + + if f.func.is_out_fn(): + # for *_out functions, handle the result argument differently for inplace/outplace. + # For inplace: just add the input to the end to confirm with the JIT schema + inplace = [ + ADD_TRACE_INPUT.substitute( + name=f.func.arguments.out[i].name, input=f.func.arguments.out[i].name + ) + # pyrefly: ignore [unbound-name] + for i in range(num_out_args) + ] + + # for outplace: do nothing, except if the function is a factory. + # Factories are a bit special because their out-of-place overloads + # take an extra TensorOptions argument, which is missing in the _out function + has_tensor_return = any(r.type.is_tensor_like() for r in f.func.returns) + has_tensor_input_arg = any( + a.type.is_tensor_like() for a in f.func.arguments.flat_non_out + ) + is_factory_method = f.category_override == "factory" or ( + has_tensor_return and not has_tensor_input_arg + ) + + # HACK: preserve old codegen behavior - the old codegen set the `is_factory_method` + # flag for the whole family of ops with the same basename if any of them is a + # factory method. For most cases the whole family of ops are indeed all factory + # method - 'normal' is the only exception. So we handle it specially here to avoid + # cloning the old logic. + if f.func.name.name.base == "normal": + is_factory_method = True + + if is_factory_method: + outplace = [ + ADD_TRACE_INPUT.substitute( + name="out", + input="c10::optTypeMetaToScalarType(out.options().dtype_opt())", + ), + ADD_TRACE_INPUT.substitute(name="out", input="out.options().layout()"), + ADD_TRACE_INPUT.substitute(name="out", input="out.options().device()"), + ADD_TRACE_INPUT.substitute( + name="out", input="out.options().pinned_memory()" + ), + ] + else: + outplace = [] + + trace_inputs = itertools.chain( + trace_inputs, + [ + SELECT.substitute( + cond="tracer_state->force_outplace", + true="\n".join(outplace), + false="\n".join(inplace), + ) + ], + ) + + return "\n".join(trace_inputs) + + +# `torch.jit.trace` have undocumented keyword argument `_force_outplace`, +# which force jit to replace functions with outplace variants (for +# example `aten::add_` becomes `aten::add`). +# +# This replacement implemented in-place with minimum modifications of +# arguments stack (as it assumes that outplace call has the same arguments +# as inplace version). +# +# However there are no such substitutions available for `aten::fill_` +# and `aten::zero_` operators, as we never implemented `aten::fill` +# and `aten::zero`. So jit tracing hack replacing `aten::zero_` with +# `aten::zeros_like` and replacing `aten::fill_` with `aten::full_like`. +# +# But as they potentially can have different arguments, we also have +# to hack into the stack and add missing ones. +# +# A possible alternative would be: +# +# - Add `aten::fill` and `aten::zero` +# +# - Or keep `aten::zeros_like` arguments aligned with `aten::zero_` +# arguments (inside of the `native_functions.yaml`) +RENAME_TRACE_ADD_ARGS = { + "fill": """\ + jit::tracer::addInputs(node, "options", ::std::optional()); + jit::tracer::addInputs(node, "options", layout_or_default(::std::nullopt)); + jit::tracer::addInputs(node, "options", device_or_default(::std::nullopt)); + jit::tracer::addInputs(node, "options", pinned_memory_or_default(::std::nullopt)); + ::std::optional memory_format = c10::MemoryFormat::Preserve; + jit::tracer::addInputs(node, "memory_format", memory_format); +""", + "zero": """\ + jit::tracer::addInputs(node, "options", ::std::optional()); + jit::tracer::addInputs(node, "options", layout_or_default(::std::nullopt)); + jit::tracer::addInputs(node, "options", device_or_default(::std::nullopt)); + jit::tracer::addInputs(node, "options", pinned_memory_or_default(::std::nullopt)); + ::std::optional memory_format = c10::MemoryFormat::Preserve; + jit::tracer::addInputs(node, "memory_format", memory_format); +""", +} + +INPLACE_GUARD = CodeTemplate( + """\ +jit::tracer::ensureUniqueIfOutOfPlaced("${name}", ${mutable_input}); +""" +) + +PRE_RECORD_TRACE = CodeTemplate( + """\ +torch::jit::Node* node = nullptr; +std::shared_ptr tracer_state; +if (jit::tracer::isTracing()) { + tracer_state = jit::tracer::getTracingState(); + at::Symbol op_name; + ${set_op_name} + node = tracer_state->createNode(op_name, /*num_outputs=*/0); + jit::tracer::recordSourceLocation(node); + ${add_trace_inputs} + tracer_state->insertNode(node); + ${inplace_guard} + jit::tracer::setTracingState(nullptr); +} +""" +) + + +def format_prerecord_trace(f: NativeFunction) -> str: + if not should_trace(f): + return "" + + # TODO: clean up old codegen behavior + is_inplace = ( + f.func.kind() in (SchemaKind.inplace, SchemaKind.out) + and not f.func.name.name.dunder_method + ) + add_args = ( + RENAME_TRACE_ADD_ARGS.get(f.func.name.name.base, "") if is_inplace else "" + ) + additional_inputs = ( + SELECT.substitute( + cond="tracer_state->force_outplace", + true=add_args, + false="", + ) + if add_args + else "" + ) + + return PRE_RECORD_TRACE.substitute( + set_op_name=format_trace_op_name(f), + add_trace_inputs=format_trace_inputs(f) + additional_inputs, + inplace_guard=INPLACE_GUARD.substitute( + name=cpp.name(f.func), + mutable_input=f.func.arguments.out[0].name + if f.func.arguments.out + else "self", + ) + if is_inplace + else "", + ) + + +POST_RECORD_TRACE = CodeTemplate( + """\ +if (tracer_state) { + jit::tracer::setTracingState(std::move(tracer_state)); + ${add_trace_outputs} +} +""" +) + + +def format_postrecord_trace(f: NativeFunction) -> str: + if not should_trace(f): + return "" + + # For outplacing ops, *_out overloads require special handling to move the + # output *argument* to a return value + if f.func.is_out_fn(): + output_names_outplace = [arg.name for arg in f.func.arguments.out] + output_names_inplace = cpp.return_names(f) + + # Code size optimization: the common case is that the return value is + # the same for both variants + if output_names_outplace == output_names_inplace: + outputs = [ + f"jit::tracer::addOutput(node, {n});" for n in output_names_outplace + ] + return POST_RECORD_TRACE.substitute(add_trace_outputs=outputs) + + selection = SELECT.substitute( + cond="force_outplace", + true="\n".join( + f"jit::tracer::addOutput(node, {n});" for n in output_names_outplace + ), + false="\n".join( + f"jit::tracer::addOutput(node, {n});" for n in output_names_inplace + ), + ) + return POST_RECORD_TRACE.substitute(add_trace_outputs=selection) + else: + output_names = cpp.return_names(f) + outputs = [f"jit::tracer::addOutput(node, {n});" for n in output_names] + return POST_RECORD_TRACE.substitute(add_trace_outputs=outputs) + + +def tie_return_values(f: NativeFunction) -> str: + if len(f.func.returns) == 1: + return f"auto {f.func.returns[0].name or 'result'}" + names = cpp.return_names(f) + return f"auto [{', '.join(names)}]" + + +def get_return_value(f: NativeFunction) -> str: + names = cpp.return_names(f) + if len(f.func.returns) == 1: + return names[0] + if f.func.kind() == SchemaKind.out: + return f"std::forward_as_tuple({', '.join(names)})" + else: + moved = ", ".join(f"std::move({name})" for name in names) + return f"std::make_tuple({moved})" + + +TRACE_DISPATCH = CodeTemplate( + """\ +${assign_return_values}at::_ops::${unambiguous_name}::redispatch(${unpacked_args});""" +) + + +def emit_trace_body(f: NativeFunction) -> list[str]: + trace_body: list[str] = [] + + trace_body.append(format_prerecord_trace(f)) + + dispatcher_sig = DispatcherSignature.from_schema(f.func) + dispatcher_exprs = dispatcher_sig.exprs() + + # code-generated tracing kernels plumb and recompute dispatch keys directly through the kernel for performance. + # See Note [Plumbing Keys Through The Dispatcher] for details. + dispatch_key_set = "ks & c10::DispatchKeySet(c10::DispatchKeySet::FULL_AFTER, c10::DispatchKey::Tracer)" + redispatch_args = ", ".join([dispatch_key_set] + [a.expr for a in dispatcher_exprs]) + + assign_return_values = ( + f"{tie_return_values(f)} = " + if f.func.kind() in [SchemaKind.functional, SchemaKind.mutable] + and f.func.returns + else "" + ) + + # Note that this calls the slow, dispatching variants of manual_cpp_binding ops. + # We could probably work harder to ensure that the fast variants are + # called instead, but the perf benefit would be minimal. + trace_body.append( + TRACE_DISPATCH.substitute( + assign_return_values=assign_return_values, + unambiguous_name=f.func.name.unambiguous_name(), + unpacked_args=redispatch_args, + ) + ) + + trace_body.append(format_postrecord_trace(f)) + if f.func.returns: + trace_body.append(f"return {get_return_value(f)};") + return trace_body + + +METHOD_DEFINITION = CodeTemplate( + """\ +${return_type} ${type_wrapper_name}(${formals}) { + ${type_definition_body} +} +""" +) + + +def type_wrapper_name(f: NativeFunction, key: str = "Default") -> str: + if f.func.name.overload_name: + name = f"{cpp.name(f.func)}_{f.func.name.overload_name}" + else: + name = cpp.name(f.func) + + # The key argument is only used in gen_variable_type where we need fns per autograd dispatch key. + # In gen_trace_type and gen_inplace_view_type where only one fn per native_fn must be generated, + # the key argument should not be passed. + # We do not append key if it is Default so that generated functions from + # before per-dispatch-key derivatives were added retain the same names. + if key != "Default": + name = name + f"_{key}" + return name + + +@with_native_function +def method_definition(f: NativeFunction) -> str: + if cpp.name(f.func) in MANUAL_TRACER: + raise AssertionError(f"Function {cpp.name(f.func)} is in MANUAL_TRACER") + + formals = ", ".join( + # code-generated tracing kernels plumb and recompute dispatch keys directly through the kernel for performance. + # See Note [Plumbing Keys Through The Dispatcher] for details. + ["c10::DispatchKeySet ks"] + + [ + f"{cpp.argument_type(a, binds='__placeholder__', symint=True).cpp_type()} {a.name}" + for a in f.func.schema_order_arguments() + ] + ) + + return METHOD_DEFINITION.substitute( + return_type=cpp.returns_type(f.func.returns, symint=True).cpp_type(), + type_wrapper_name=type_wrapper_name(f), + formals=formals, + type_definition_body=emit_trace_body(f), + ) + + +WRAPPER_REGISTRATION = CodeTemplate( + """\ +m.impl("${name}", + TORCH_FN(${class_type}::${type_wrapper_name}) +); +""" +) + + +@with_native_function +def method_registration(f: NativeFunction) -> str: + if cpp.name(f.func) in MANUAL_TRACER: + raise AssertionError(f"Function {cpp.name(f.func)} is in MANUAL_TRACER") + + return WRAPPER_REGISTRATION.substitute( + name=f.func.name, + type_wrapper_name=type_wrapper_name(f), + class_type="TraceType", + ) + + +def gen_trace_type_func(fn: NativeFunction) -> dict[str, list[str]]: + return { + "ops_headers": [f"#include "], + "trace_method_definitions": [method_definition(fn)], + "trace_wrapper_registrations": [method_registration(fn)], + } + + +def gen_trace_type( + out: str, native_functions: list[NativeFunction], template_path: str +) -> None: + # NOTE: see Note [Sharded File] at the top of the VariableType.cpp + # template regarding sharding of the generated files. + fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False) + fm.write_sharded( + "TraceType.cpp", + [fn for fn in native_functions if cpp.name(fn.func) not in MANUAL_TRACER], + key_fn=lambda fn: fn.root_name, + base_env={ + "generated_comment": "@" + + f"generated from {fm.template_dir_for_comments()}/TraceType.cpp", + }, + env_callable=gen_trace_type_func, + num_shards=10, + sharded_keys={ + "ops_headers", + "trace_method_definitions", + "trace_wrapper_registrations", + }, + ) diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_variable_factories.py b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_variable_factories.py new file mode 100644 index 0000000000000000000000000000000000000000..9916a77385d38f01e83416d4303cb17ac17de700 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_variable_factories.py @@ -0,0 +1,116 @@ +# Generates C++ functions that wrap ATen tensor factory methods to turn them into Variables. +# +# This writes one file: variable_factories.h + +from __future__ import annotations + +import re + +import torchgen.api.python as python +from torchgen.api import cpp +from torchgen.api.types import CppSignatureGroup +from torchgen.context import with_native_function +from torchgen.gen import parse_native_yaml +from torchgen.model import NativeFunction, TensorOptionsArguments, Variant +from torchgen.utils import FileManager, mapMaybe + + +OPTIONAL_TYPE_PATTERN = re.compile(r"std::optional<(.+)>") +TYPE_PATTERN = re.compile(r"(?:const\s+)?([A-Z]\w+)") + + +# Add 'at::' to types defined in ATen namespace, e.g. Tensor, TensorList, IntArrayRef and etc. +# TODO: maybe update the cpp argument API to take optional namespace argument? +def fully_qualified_type(argument_type: str) -> str: + def maybe_optional_type(type: str, is_opt: bool) -> str: + return f"std::optional<{type}>" if is_opt else type + + opt_match = OPTIONAL_TYPE_PATTERN.match(argument_type) + is_opt = opt_match is not None + if opt_match: + argument_type = argument_type[opt_match.start(1) : opt_match.end(1)] + match = TYPE_PATTERN.match(argument_type) + if match is None: + return maybe_optional_type(argument_type, is_opt) + index = match.start(1) + qualified_type = f"{argument_type[:index]}at::{argument_type[index:]}" + return maybe_optional_type(qualified_type, is_opt) + + +def gen_variable_factories( + out: str, native_yaml_path: str, tags_yaml_path: str, template_path: str +) -> None: + native_functions = parse_native_yaml( + native_yaml_path, tags_yaml_path + ).native_functions + factory_functions = [fn for fn in native_functions if is_factory_function(fn)] + fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False) + fm.write_with_template( + "variable_factories.h", + "variable_factories.h", + lambda: { + "generated_comment": "@" + + f"generated from {fm.template_dir_for_comments()}/variable_factories.h", + "ops_headers": [ + f"#include " for fn in factory_functions + ], + "function_definitions": list(mapMaybe(process_function, factory_functions)), + }, + ) + + +@with_native_function +def is_factory_function(f: NativeFunction) -> bool: + if Variant.function not in f.variants: + return False + + name = cpp.name(f.func) + has_tensor_options = python.has_tensor_options(f) + return has_tensor_options or name.endswith("_like") + + +@with_native_function +def process_function(f: NativeFunction) -> str | None: + name = cpp.name(f.func) + has_tensor_options = python.has_tensor_options(f) + is_factory = has_tensor_options or name.endswith("_like") + + if Variant.function not in f.variants or not is_factory: + return None + + cpp_sigs = CppSignatureGroup.from_native_function(f, method=False) + sigs = [cpp_sigs.signature] + if cpp_sigs.symint_signature is not None: + sigs.append(cpp_sigs.symint_signature) + r = "" + for sig in sigs: + formals: list[str] = [] + exprs: list[str] = [] + requires_grad = "false" + for arg in sig.arguments(): + qualified_type = fully_qualified_type(arg.type) + if arg.default: + formals.append(f"{qualified_type} {arg.name} = {arg.default}") + else: + formals.append(f"{qualified_type} {arg.name}") + + if isinstance(arg.argument, TensorOptionsArguments): + # note: we remove the requires_grad setting from the TensorOptions because + # it is ignored anyways (and we actually have an assertion that it isn't set + # which would fail otherwise). We handle requires_grad explicitly here + # instead of passing it through to the kernel. + exprs.append( + f"at::TensorOptions({arg.name}).requires_grad(::std::nullopt)" + ) + # Manually set the requires_grad bit on the result tensor. + requires_grad = f"{arg.name}.requires_grad()" + else: + exprs.append(arg.name) + + r += f"""\ +inline at::Tensor {sig.name()}({", ".join(formals)}) {{ + at::AutoDispatchBelowADInplaceOrView guard; + return autograd::make_variable(at::{sig.name()}({", ".join(exprs)}), /*requires_grad=*/{requires_grad}); +}} +""" + return r diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_variable_type.py b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_variable_type.py new file mode 100644 index 0000000000000000000000000000000000000000..92133ec8b5cbd9581b90a792b4bea863af6b3f91 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_variable_type.py @@ -0,0 +1,2312 @@ +# Generates VariableType.h/cpp +# +# **If any changes are being made to the VariableType codegen please also check +# if updates are needed in torch/csrc/autograd/autograd_not_implemented_fallback.cpp +# +# VariableType is a subclass of at::Type that provides the binding code +# necessary to provide a differentiable version of ATen operators. There are a +# number of different things we could mean: +# +# - Given a non-differentiable forward implementation, we might +# directly associate it with a backward implementation to make +# it differentiable. This is the common case. +# +# - Some functions don't need a backwards implementation, because +# backpropagation will never propagate beyond them. There are a +# number of different reasons why this may be the case: +# +# - The function has no differentiable inputs +# - The function's output is not differentiable +# - The function has no data dependency on its input +# +# - Some function don't need a backwards implementation because they +# are implemented as a composition of other (differentiable) ATen +# functions. These are dispatched directly to the Type superclass, +# which will in turn dispatch back to VariableType for its +# differentiable subcomponents. +# + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING + +from torchgen.api import cpp +from torchgen.api.autograd import ( + DifferentiableInput, + dispatch_strategy, + ForwardDerivative, + gen_differentiable_outputs, + is_differentiable, + NativeFunctionWithDifferentiabilityInfo, + SavedAttribute, +) +from torchgen.api.types import ( + ArrayRefCType, + BaseCppType, + BaseCType, + Binding, + intArrayRefT, + iTensorListRefT, + ListCType, + MutRefCType, + OptionalCType, + scalarT, + SpecialArgName, + stringT, + symIntArrayRefT, + TENSOR_LIST_LIKE_CTYPES, + tensorListT, + tensorT, + TupleCType, + VectorCType, +) +from torchgen.code_template import CodeTemplate +from torchgen.context import ( + native_function_manager, + with_native_function, + with_native_function_and, +) +from torchgen.model import ( + Argument, + BaseType, + ListType, + NativeFunction, + SchemaKind, + SelfArgument, + TensorOptionsArguments, +) +from torchgen.utils import FileManager, mapMaybe + +from .context import with_native_function_with_differentiability_info_and_key +from .gen_inplace_or_view_type import ( + ALL_VIEW_FUNCTIONS, + ASSIGN_RETURN_VALUE, + AUTOGRAD_NOT_IMPLEMENTED_REGISTRATION, + gen_formals, + get_base_name, + get_view_info, + is_tensor_list_type, + is_tensor_type, + METHOD_DEFINITION, + modifies_arguments, + TMP_VAR, + unpack_args, + unpacked_name, + use_derived, + WRAPPER_REGISTRATION, +) +from .gen_trace_type import ( + get_return_value, + MANUAL_AUTOGRAD_AND_TRACER, + MANUAL_BACKEND, + tie_return_values, + type_wrapper_name, +) + + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + +# We don't set or modify grad_fn on these methods. Generally, they return +# tensors that have requires_grad=False. In-place functions listed here will +# not examine or modify requires_grad or grad_fn. +# NB: this does NOT include overload name +DONT_REQUIRE_DERIVATIVE = { + # These only depend on the input Tensor's shape and device, not the data + "empty_like", + "ones_like", + "full_like", + "zeros_like", + "rand_like", + "randn_like", + "new_empty", + "new_empty_strided", + "new_full", + "new_zeros", + "new_ones", + # These are only implemented on integral types + "__and__", + "__iand__", + "__ilshift__", + "__ior__", + "__irshift__", + "__ixor__", + "__lshift__", + "__or__", + "__rshift__", + "__xor__", + # These work on integral data types, and hence don't require derivative + "_sobol_engine_draw", + "_sobol_engine_ff", + "_sobol_engine_scramble_", + "_sobol_engine_initialize_state_", + # This is an unsafe method that is meant to be out of reach of autograd. + "_coalesced_", + # Quantize functions should not record gradients + "quantize_per_tensor", + "quantize_per_channel", + # Functions that return integers should not have output that require gradients + "argmax", + "argmin", + "argsort", + "searchsorted", + "bucketize", + # Functions that return booleans are not differentiable + "isnan", + "isposinf", + "isneginf", + "isinf", + "signbit", + "isin", + "allclose", + # Functions return none are not differentiable + "record_stream", + # These functions are not differentiable + "logical_and", + "logical_xor", + "logical_not", + "logical_or", + # This function returns nested_tensor shape as a tensor that is non-differentiable + "_nested_tensor_size", + "_nested_tensor_strides", + "_nested_tensor_storage_offsets", +} + +# The C -> R functions at the time of adding this are still being audited and tested +# but will not error out. +# C -> C, R -> C functions for which backward is correctly implemented and tested +GRADIENT_IMPLEMENTED_FOR_COMPLEX = { + "fill", + "t", + "t_copy", + "view", + "reshape", + "reshape_as", + "view_as", + "view_copy", + "roll", + "clone", + "block_diag", + "diag_embed", + "repeat", + "expand", + "expand_copy", + "flip", + "fliplr", + "flipud", + "rot90", + "nanmean", + "nansum", + "transpose", + "transpose_copy", + "permute", + "permute_copy", + "squeeze", + "squeeze_copy", + "unsqueeze", + "unsqueeze_copy", + "resize", + "resize_as", + "tril", + "triu", + "chunk", + "zero_", + "eq_", + "ne_", + "add", + "__radd__", + "sum", + "_conj", + "sin", + "cos", + "mul", + "sinc", + "sinh", + "cosh", + "__rmul__", + "sgn", + "asin", + "acos", + "sub", + "div", + "cat", + "view_as_complex", + "index_put", + "neg", + "complex", + "select", + "where", + "as_strided", + "as_strided_copy", + "as_strided_scatter", + "slice", + "constant_pad_nd", + "unbind", + "unbind_copy", + "split", + "split_with_sizes", + "unsafe_split", + "split_with_sizes_backward", + "dot", + "vdot", + "triangular_solve", + "mm", + "_unsafe_view", + "mv", + "outer", + "bmm", + "diagonal", + "alias", + "atan", + "ldexp", + "linear", + "log", + "log10", + "log1p", + "log2", + "logaddexp", + "logsumexp", + "logcumsumexp", + "reciprocal", + "tan", + "pow", + "rsqrt", + "tanh", + "tanh_backward", + "asinh", + "acosh", + "atanh", + "take", + "fill_", + "exp", + "exp2", + "expm1", + "nonzero", + "mean", + "std_mean", + "var_mean", + "inverse", + "solve", + "linalg_cholesky", + "addcmul", + "addcdiv", + "matrix_exp", + "linalg_matrix_exp", + "linalg_matrix_sqrth", + "linalg_polar", + "_linalg_eigh", + "cholesky_solve", + "linalg_qr", + "_linalg_svd", + "_fft_c2c", + "_fft_r2c", + "linalg_solve", + "sqrt", + "stack", + "gather", + "index_select", + "index_add_", + "linalg_inv", + "linalg_inv_ex", + "baddbmm", + "addbmm", + "addmm", + "addmv", + "addr", + "linalg_householder_product", + "ormqr", + "reflection_pad1d", + "reflection_pad2d", + "reflection_pad3d", + "linalg_cholesky_ex", + "linalg_eig", + "diagonal_copy", + "diagonal_scatter", + "alias_copy", + "select_backward", + "diagonal_backward", + "slice_backward", + "reflection_pad1d_backward", + "reflection_pad2d_backward", + "reflection_pad3d_backward", + "_sparse_sparse_matmul", + "replication_pad1d", + "replication_pad2d", + "replication_pad3d", + "put", + "put_", + "_to_copy", + "replication_pad1d_backward", + "replication_pad2d_backward", + "replication_pad3d_backward", + "diag", + "masked_scatter", + "masked_select", + "index_add", + "index_fill", + "trace", + "polar", + "cumsum", + "rsub", + "eig", + "lerp", + "linalg_vector_norm", + "cumprod", + "prod", + "index_copy", + "lu", + "unfold", + "unfold_backward", + "index", + "masked_fill", + "masked_scatter_backward", + "linalg_cross", + "lu_unpack", + "renorm", + "_conj_physical", + "linalg_lu_factor_ex", + "scatter", + "scatter_add", + "sigmoid", + "sigmoid_backward", + "sparse_mask", + "trapezoid", + "cumulative_trapezoid", + "conj_physical_", + "_neg_view", + "_reshape_alias", + "_reshape_copy", + "narrow_copy", + "_linalg_det", + "lu_solve", + "linalg_solve_triangular", + "linalg_pinv", + "linalg_lstsq", + "unfold_copy", + "col2im", + "im2col", + "cholesky_inverse", + "to_sparse", + "sparse_sampled_addmm", + "linalg_lu", + "pixel_shuffle", + "pixel_unshuffle", + "channel_shuffle", + "linalg_lu_solve", + "_linalg_slogdet", + "_linalg_solve_ex", + "_unsafe_index", + "_unsafe_index_put", + "_unsafe_masked_index", + "_unsafe_masked_index_put_accumulate", +} + +GRADIENT_IMPLEMENTED_FOR_SPARSE_COMPLEX = { + "_to_dense", + "_coalesce", + "coalesce", + "values", + "_sparse_coo_tensor_with_dims_and_tensors", + "_sparse_addmm", +} + +GRADIENT_IMPLEMENTED_FOR_COMPLEX.update(GRADIENT_IMPLEMENTED_FOR_SPARSE_COMPLEX) + +# Some operators invalidate the grad_accumulator. Let's reset it. +RESET_GRAD_ACCUMULATOR = {"set_", "resize_"} + +# NOTE [ TensorImpl and Storage Pointer Sanity Checks ] +# +# We check the following properties: +# 1) A function should never change the input tensors' underlying c10::TensorImpl +# pointers or c10::Storage pointers, even if it modifies its input tensors (via +# inplace or out-variants) +# If the function does not modify its arguments, we also check the following properties +# pertaining to its output: +# 2) Its TensorImpl has use_count of 1 (or 2 if it has a PyObject) +# 3) If the function is a view function, it has the same StorageImpl as that of +# the input it is aliased with. Otherwise, its StorageImpl has use_count of 1 +# +# The following code templates implement the checks for this invariant: +SAVE_TENSOR_STORAGE = CodeTemplate( + """\ +auto ${tensor_name}_storage_saved = + ${tensor_name}.has_storage() ? ::std::optional(${tensor_name}.storage()) : ::std::nullopt; +""" +) + + +# If tensor_name == out_tensor_name, used to enforce (1), otherwise used for (2) +ENFORCE_SAME_TENSOR_STORAGE = CodeTemplate( + """\ +if (${tensor_name}_storage_saved.has_value() && + !at::impl::dispatch_mode_enabled() && + !at::impl::tensor_has_dispatch(${tensor_name}) && + !at::impl::tensor_has_dispatch(${out_tensor_name})) + TORCH_INTERNAL_ASSERT(${tensor_name}_storage_saved.value().is_alias_of(${out_tensor_name}.storage())); +""" +) + +SAVE_TENSORLIST_STORAGE = CodeTemplate( + """\ +std::vector<::std::optional> ${tensorlist_name}_storage_saved(${tensorlist_name}.size()); +for (const Tensor& tensor : ${tensorlist_name}) + ${tensorlist_name}_storage_saved.push_back( + tensor.has_storage() ? ::std::optional(tensor.storage()) : ::std::nullopt); +""" +) + +ENFORCE_SAME_TENSORLIST_STORAGE = CodeTemplate( + """\ +for (size_t i=0; i<${tensorlist_name}.size() && !at::impl::dispatch_mode_enabled(); i++) { + if (${tensorlist_name}_storage_saved[i].has_value() && !at::impl::tensorlist_has_dispatch(${tensorlist_name})) + TORCH_INTERNAL_ASSERT(${tensorlist_name}_storage_saved[i].value().is_alias_of(${tensorlist_name}[i].storage())); +} +""" +) + +SAVE_OPTIONALTENSORLIST_STORAGE = CodeTemplate( + """\ +std::vector<::std::optional> ${tensorlist_name}_storage_saved(${tensorlist_name}.size()); +for (const ::std::optional& tensor : ${tensorlist_name}) + ${tensorlist_name}_storage_saved.push_back( + tensor.has_value() && tensor->has_storage() ? ::std::optional(tensor->storage()) : ::std::nullopt); +""" +) + +ENFORCE_SAME_OPTIONALTENSORLIST_STORAGE = CodeTemplate( + """\ +for (size_t i=0; i<${tensorlist_name}.size() && !at::impl::dispatch_mode_enabled(); i++) { + if (${tensorlist_name}_storage_saved[i].has_value() && !at::impl::tensorlist_has_dispatch(${tensorlist_name})) + TORCH_INTERNAL_ASSERT(${tensorlist_name}_storage_saved[i].value().is_alias_of( + static_cast<::std::optional>(${tensorlist_name}[i])->storage())); +} +""" +) + +SAVE_TENSOR_IMPL = CodeTemplate( + """\ +c10::intrusive_ptr ${tensor_name}_impl_saved; +if (${tensor_name}.defined()) ${tensor_name}_impl_saved = ${tensor_name}.getIntrusivePtr(); +""" +) + +ENFORCE_SAME_TENSOR_IMPL = CodeTemplate( + """\ +if (${tensor_name}_impl_saved && !at::impl::dispatch_mode_enabled() && !at::impl::tensor_has_dispatch(${tensor_name})) + TORCH_INTERNAL_ASSERT(${tensor_name}_impl_saved == ${tensor_name}.getIntrusivePtr()); +""" +) + +ENFORCE_TENSOR_IMPL_USE_COUNT = CodeTemplate( + """\ +if (!at::impl::dispatch_mode_enabled() && !at::impl::tensor_has_dispatch(${tensor_name})) + TORCH_INTERNAL_ASSERT(${tensor_name}.use_count() == expected_fresh_use_count(${tensor_name}), "function: ${fn_name}"); +""" +) + +ENFORCE_TENSOR_STORAGE_USE_COUNT_EQUALS_ONE = CodeTemplate( + """\ +if (${tensor_name}.has_storage() && !at::impl::dispatch_mode_enabled() && !at::impl::tensor_has_dispatch(${tensor_name})) { + TORCH_INTERNAL_ASSERT(${tensor_name}.storage().use_count() == 1, "function: ${fn_name}"); +} +""" +) + +SAVE_TENSORLIST_IMPL = CodeTemplate( + """\ +std::vector> ${tensorlist_name}_impl_saved(${tensorlist_name}.size()); +for (size_t i=0; i<${tensorlist_name}.size(); i++) + if (${tensorlist_name}[i].defined()) ${tensorlist_name}_impl_saved[i] = ${tensorlist_name}[i].getIntrusivePtr(); +""" +) + +ENFORCE_SAME_TENSORLIST_IMPL = CodeTemplate( + """\ +for (size_t i=0; i<${tensorlist_name}.size() && !at::impl::dispatch_mode_enabled(); i++) { + if (${tensorlist_name}_impl_saved[i] && !at::impl::tensorlist_has_dispatch(${tensorlist_name})) + TORCH_INTERNAL_ASSERT(${tensorlist_name}_impl_saved[i] == ${tensorlist_name}[i].getIntrusivePtr()); +} +""" +) + +SAVE_OPTIONALTENSORLIST_IMPL = CodeTemplate( + """\ +std::vector> ${tensorlist_name}_impl_saved(${tensorlist_name}.size()); +for (size_t i=0; i<${tensorlist_name}.size(); i++) { + ::std::optional t = ${tensorlist_name}[i]; + if (t.has_value() && t->defined()) ${tensorlist_name}_impl_saved[i] = t->getIntrusivePtr(); +} +""" +) + +ENFORCE_SAME_OPTIONALTENSORLIST_IMPL = CodeTemplate( + """\ +for (size_t i=0; i<${tensorlist_name}.size() && !at::impl::dispatch_mode_enabled(); i++) { + if (${tensorlist_name}_impl_saved[i]) + TORCH_INTERNAL_ASSERT( + ${tensorlist_name}_impl_saved[i] == static_cast<::std::optional>(${tensorlist_name}[i])->getIntrusivePtr()); +} +""" +) + +# The following list contains functions that we don't enforce the invariant on. +DONT_ENFORCE_SAME_TENSOR_IMPL_OR_STORAGE = { + # These functions are expected to change impl or storage of input tensors + "set_", + "_cudnn_rnn_flatten_weight", + "_unsafe_masked_index", + "_unsafe_masked_index_put_accumulate", +} +DONT_ENFORCE_TENSOR_IMPL_USE_COUNT = { + # These non-inplace, non-out functions return tensors with use_count > 1 + # Therefore, they MAY (but not necessarily) return one of its inputs as-is + # See https://github.com/pytorch/pytorch/issues/60426 for more information + "_embedding_bag", + "_embedding_bag_forward_only", + "q_per_channel_scales", + "q_per_channel_zero_points", + "lu_unpack", + "_cudnn_rnn_backward", + # The below failed StorageImpl use_count check but we skip tensor_impl check + # just in case + "_cudnn_rnn", + "dequantize_self", + # lift() should never actually be called with a requires_grad=True tensor, + "lift", + "lift_fresh", + "lift_fresh_copy", + # Nested Tensors related functions + # _nested_tensor_size() should never actually be called with requires_grad=True tensor + "_nested_tensor_size", + "_nested_tensor_strides", + "_nested_tensor_storage_offsets", +} + +DONT_ENFORCE_STORAGE_IMPL_USE_COUNT = { + # These non-view functions return tensors with storage use_count != 1 + "_slow_conv2d_forward", + "slow_conv3d_forward", + "channel_shuffle", + # If an input is returned as-is in output, we cannot guarantee its storage_impl + # use count to be 1 either. + *DONT_ENFORCE_TENSOR_IMPL_USE_COUNT, +} +# END CHECKS FOR [ TensorImpl and Storage Pointer Sanity Checks ] + +DECLARE_GRAD_FN = CodeTemplate( + """\ +c10::intrusive_ptr<${op}> grad_fn; +""" +) + +DECLARE_VECTOR_OF_GRAD_FN = CodeTemplate( + """\ +std::vector> grad_fns; +""" +) + +SETUP_ANY_REQUIRES_GRAD = CodeTemplate( + """\ +[[maybe_unused]] auto _any_requires_grad = compute_requires_grad( ${args_with_derivatives} ); +${extra_differentiability_conditions} +""" +) + +SETUP_DERIVATIVE = CodeTemplate( + """\ +if (_any_requires_grad) { + ${setup} +} +""" +) + +SETUP_NONE_REQUIRES_GRAD = CodeTemplate( + """\ +if (compute_requires_grad( ${args_to_check} )) { + throw_error_out_requires_grad("${base_name}"); +} +""" +) + +ASSIGN_GRAD_FN = CodeTemplate( + """\ +grad_fn = c10::make_intrusive<${op}>(${op_ctor}); +grad_fn->set_next_edges(collect_next_edges( ${args_with_derivatives} )); +""" +) + +# note(crcrpar): `compute_requires_grad` in the template below is supplied with arguments indexed with `i` +# while the `SETUP_ANY_REQUIRES_GRAD` above takes whole tensors and scalars. +ASSIGN_VECTOR_OF_GRAD_FN = CodeTemplate( + """\ +for (const auto& i : c10::irange( ${irange} )) { + const auto ith_requires_grad = compute_requires_grad(${args_with_derivatives}); + check_inplace(self[i], ith_requires_grad); + grad_fns.push_back([&]() -> c10::intrusive_ptr<${op}> { + if (!ith_requires_grad) { + return nullptr; + } else { + auto grad_fn = c10::make_intrusive<${op}>(${op_ctor}); + grad_fn->set_next_edges(collect_next_edges( ${args_with_derivatives} )); + return grad_fn; + } + }()); +} +""" +) + +CALL_REDISPATCH = CodeTemplate( + """\ +at::redispatch::${api_name}(${unpacked_args})""" +) +# If the non-variable operation has return values, we use the `tmp` variable to hold the +# values temporarily and pass the values to the return variables outside of the +# `at::AutoDispatchBelowAutograd` guard block. +DISPATCH_TO_NON_VAR_TYPE_WITH_TMP_RETURN_VALUES_JVP_DECOMP = CodeTemplate( + """\ +auto ${tmp_var} = ([&]() { + if (${any_has_forward_grad}) { + static c10::OperatorName full_name("aten::${op_name}", "${op_overload}"); + static ::std::optional opt_op = c10::Dispatcher::singleton().findSchema(full_name); + return impl::run_jit_decomposition_with_args_for_jvp<${return_types}>("${op_name}", *opt_op, ks, ${arg_names}); + } else { + ${guard} + return ${base_type_call}; + } +})(); +""" +) + +DISPATCH_TO_NON_VAR_TYPE_WITH_TMP_RETURN_VALUES = CodeTemplate( + """\ +auto ${tmp_var} = ([&]() { + ${guard} + return ${base_type_call}; +})(); +""" +) + +DISPATCH_TO_NON_VAR_TYPE_WITHOUT_RETURN_VALUES = CodeTemplate( + """\ +{ + ${guard} + ${base_type_call}; +} +""" +) + +SET_HISTORY = CodeTemplate( + """\ +if (grad_fn) { + ${fn}_history(${differentiable_outputs}, grad_fn); +} +""" +) + +# rebase_history returns the node actually attached as the new history (the +# CopySlices node when rebasing through a view). It is captured so that node +# creation hooks fire on the composed node, not the inner one. +REBASE_HISTORY = CodeTemplate( + """\ +c10::intrusive_ptr _rebased_fn; +if (grad_fn) { + _rebased_fn = rebase_history(${differentiable_outputs}, grad_fn); +} +""" +) + +# Fired at the very end of the function, after saved variables (including +# saved outputs) have been stored on grad_fn. +FIRE_NODE_CREATION_HOOKS = CodeTemplate( + """\ +if (${node}) { + fire_node_creation_hooks(${node}); +} +""" +) + +LOOP_OVER_VECTOR_OF_GRAD_FNS = CodeTemplate( + """\ +if (!grad_fns.empty()) { + ${preamble} + for (const auto& i : c10::irange(grad_fns.size())) { + auto grad_fn = grad_fns[i]; + if (grad_fn != nullptr) { + ${statements} + } + } +} +""" +) + +CONDITIONAL = CodeTemplate( + """\ +if (${cond}) { + ${statements} +} +""" +) + +RUN_ONLY_IN_DEBUG_MODE = CodeTemplate( + """\ +#ifndef NDEBUG +${statements} +#endif +""" +) + +FW_DERIVATIVE_CHECK_TEMPLATE = CodeTemplate( + """\ +isFwGradDefined(${req_inp})\ +""" +) +FW_DERIVATIVE_SIZE_CHECK_TEMPLATE = CodeTemplate( + """\ +TORCH_CHECK( + self.size() == ${inp_name}.size(), + "Tensor lists must have the same number of tensors, got ", + self.size(), + " and ", + ${inp_name}.size()); +""" +) + +FW_DERIVATIVE_TENSORLIST_CHECK_TEMPLATE = CodeTemplate( + """\ +isFwGradDefinedTensorList(${req_inp})\ +""" +) + +FW_DERIVATIVE_DEFINED_GRAD_TEMPLATE = CodeTemplate( + """\ +auto ${inp_name}_t_raw = toNonOptFwGrad(${inp}); +auto ${inp_name}_tensor = toNonOptTensor(${inp}); +auto ${inp_name}_t = (${inp_name}_t_raw.defined() || !${inp_name}_tensor.defined()) + ? ${inp_name}_t_raw : at::${zeros_fn}(${inp_name}_tensor.sym_sizes(), ${inp_name}_tensor.options()); +""" +) + +FW_DERIVATIVE_UPDATE_WRAPPED_NUM_TEMPLATE = CodeTemplate( + """\ +update_wrapped_number(${inp_name}_tensor, ${inp_name}_t); +""" +) + +FW_DERIVATIVE_DEFINED_PRIMAL_TEMPLATE = CodeTemplate( + """\ +auto ${inp_name}_p = toNonOptPrimal(${inp}); +""" +) + +FW_DERIVATIVE_SETTER_TENSOR = CodeTemplate( + """\ +if (${out_arg}_new_fw_grad_opt.has_value() && ${out_arg}_new_fw_grad_opt.value().defined() && ${out_arg}.defined()) { + // The hardcoded 0 here will need to be updated once we support multiple levels. + ${out_arg}._set_fw_grad(${out_arg}_new_fw_grad_opt.value(), /* level */ 0, /* is_inplace_op */ ${is_inplace}); +} +""" +) + +FW_DERIVATIVE_SETTER_TENSOR_FOREACH = CodeTemplate( + """\ +for (const auto& i : c10::irange(${out_arg}_new_fw_grad_opts.size())) { + auto& ${out_arg}_new_fw_grad_opt = ${out_arg}_new_fw_grad_opts[i]; + if (${out_arg}_new_fw_grad_opt.has_value() && ${out_arg}_new_fw_grad_opt.value().defined() && ${out_arg}[i].defined()) { + // The hardcoded 0 here will need to be updated once we support multiple levels. + ${out_arg}[i]._set_fw_grad(${out_arg}_new_fw_grad_opt.value(), /* level */ 0, /* is_inplace_op */ ${is_inplace}); + } +} +""" +) + +FW_DERIVATIVE_SETTER_MULTI_OUTPUT = CodeTemplate( + """\ +if (${all_res}_new_fw_grad_opt.has_value() && std::get<${idx}>(${all_res}_new_fw_grad_opt.value()).defined() + && ${out_arg}.defined()) { + ${out_arg}._set_fw_grad(std::get<${idx}>(${all_res}_new_fw_grad_opt.value()), /* level */ 0, /* is_inplace_op */ false); +} +""" +) + +FW_DERIVATIVE_SETTER_TENSOR_LIST = CodeTemplate( + """\ +if (${out_arg}_new_fw_grad_opt.has_value()) { + auto ${out_arg}_new_fw_grad = ${out_arg}_new_fw_grad_opt.value(); + TORCH_INTERNAL_ASSERT(${out_arg}.size() == ${out_arg}_new_fw_grad.size()); + for (const auto i : c10::irange(${out_arg}.size())) { + if (${out_arg}_new_fw_grad[i].defined() && ${out_arg}[i].defined()) { + // The hardcoded 0 here will need to be updated once we support multiple levels. + ${out_arg}[i]._set_fw_grad(${out_arg}_new_fw_grad[i], /* level */ 0, /* is_inplace_op */ ${is_inplace}); + } + } +} +""" +) + +FW_DERIVATIVE_TEMPLATE = CodeTemplate( + """\ +${fw_grad_opt_definition} +if (${requires_fw_grad}) { + ${unpacked_arguments} + ${out_arg}_new_fw_grad_opt = ${formula}; +} +""" +) + +FW_DERIVATIVE_FOREACH_TEMPLATE = CodeTemplate( + """\ +${fw_grad_opt_definition} +for (const auto& i : c10::irange(${vector_of_optional_tensor}.size())) { + if (${any_has_forward_grad_for_current_index}) { + ${unpacked_arguments} + ${vector_of_optional_tensor}[i] = ${formula}; + } +} +""" +) + +FW_DERIVATIVE_FORBID_TEMPLATE = CodeTemplate( + """\ +TORCH_CHECK_NOT_IMPLEMENTED(!(${cond}), "Trying to use forward AD with ${name} that does not support it ${msg}"); +""" +) + +FW_DERIVATIVE_FORBID_LIST_TEMPLATE = CodeTemplate( + """\ +for (const auto& _t: ${arg}) { + TORCH_CHECK_NOT_IMPLEMENTED(!(${cond}), "Trying to use forward AD with ${name} that does not support it ${msg}"); +} +""" +) + + +def gen_variable_type( + out: str, + native_yaml_path: str, + tags_yaml_path: str, + fns_with_diff_infos: list[NativeFunctionWithDifferentiabilityInfo], + template_path: str, + used_keys: set[str], +) -> None: + """VariableType.h and VariableType.cpp body + + This is the at::Type subclass for differentiable tensors. The + implementation of each function dispatches to the base tensor type to + compute the output. The grad_fn is attached to differentiable functions. + """ + fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False) + fm.write( + "VariableType.h", + lambda: { + "generated_comment": "@" + + f"generated from {fm.template_dir_for_comments()}/VariableType.h" + }, + ) + + # helper that generates a TORCH_LIBRARY_IMPL macro for each + # dispatch key that appears in derivatives.yaml + def wrapper_registrations(used_keys: set[str]) -> str: + library_impl_macro_list: list[str] = [] + for key in sorted(used_keys): + dispatch_key = key + if key == "Default": + dispatch_key = "Autograd" + library_impl_macro = ( + f"TORCH_LIBRARY_IMPL(aten, {dispatch_key}, m) " + + "{\n" + + "${" + + f"wrapper_registrations_{key}" + + "}\n}" + ) + library_impl_macro_list += [library_impl_macro] + return "\n\n".join(library_impl_macro_list) + + # Generate a new template from VariableType.cpp which replaces ${wrapper_registrations} + # with per key TORCH_LIBRARY_IMPL macros for each key that appears in derivatives.yaml + fm1 = FileManager( + install_dir=out + "/templates", template_dir=template_path, dry_run=False + ) + fm1.write( + "VariableType.cpp", + lambda: { + "type_derived_method_definitions": "\n\n".join( + [ + "${" + f"type_derived_method_definitions_{key}" + "}" + for key in sorted(used_keys) + ] + ), + "wrapper_registrations": wrapper_registrations(used_keys), + }, + ) + + # Generate final VariableType_*.cpp files from the generated template + fm2 = FileManager(install_dir=out, template_dir=out + "/templates", dry_run=False) + + sharded_keys = set( + [f"type_derived_method_definitions_{key}" for key in sorted(used_keys)] + + [f"wrapper_registrations_{key}" for key in sorted(used_keys)] + ) + # NOTE: see Note [Sharded File] at the top of the VariableType.cpp + # template regarding sharding of the generated files. + fm2.write_sharded( + "VariableType.cpp", + [fn for fn in fns_with_diff_infos if use_derived(fn)], + key_fn=lambda fn: cpp.name(fn.func.func), + base_env={ + "generated_comment": "@" + + f"generated from {fm.template_dir_for_comments()}/VariableType.cpp", + }, + env_callable=gen_variable_type_func, + num_shards=10, + sharded_keys=sharded_keys, + ) + + +@with_native_function_and +def gen_wrapper_registration(f: NativeFunction, key: str = "Default") -> str: + return WRAPPER_REGISTRATION.substitute( + unqual_operator_name_with_overload=f.func.name, + type_wrapper_name=type_wrapper_name(f, key), + class_type="VariableType", + ) + + +def gen_variable_type_func( + fn: NativeFunctionWithDifferentiabilityInfo, +) -> dict[str, list[str]]: + f = fn.func + result = {} + with native_function_manager(f): + name = cpp.name(f.func) + formals = gen_formals(f) + + if ( + fn.info is None + and str(f.func.name.name) not in RESET_GRAD_ACCUMULATOR + and get_base_name(f) not in DONT_REQUIRE_DERIVATIVE + and len(gen_differentiable_outputs(fn)) > 0 + and cpp.name(f.func) not in DONT_ENFORCE_SAME_TENSOR_IMPL_OR_STORAGE + and type_wrapper_name(f) not in DONT_ENFORCE_STORAGE_IMPL_USE_COUNT + and type_wrapper_name(f) not in DONT_ENFORCE_TENSOR_IMPL_USE_COUNT + ): + # NOTE: [ Registering AutogradNotImplemented boxed kernel ] + # + # When there is no derivatives.yaml entry, we register a generic boxed + # NotImplemented kernel to set grad_fn to be NotImplemented, so that forward + # proceeds as usual but an error is properly produced on backward. + # TODO: it would be nice to not have these special cases + # + # There are several cases where still let codegen handle it: + # 1) ops that need to reset grad accumulator (we let codegen handle this case + # because) the list is (currently) only accessible in Python. + # 2) User explicitly specifies DONT_REQUIRE_DERIVATIVE. This basically makes + # autograd a fallthrough with NDEBUG checks. This can be useful for when all + # outputs are integral. + # 3) When there are no differentiable outputs. This is similar to (2). + # 4) There are certain ops where we skip certain NDEBUG checks. this is similar + # to (1). + type_definition = "" + wrapper_registration = AUTOGRAD_NOT_IMPLEMENTED_REGISTRATION.substitute( + unqual_operator_name_with_overload=f.func.name + ) + result["type_derived_method_definitions_Default"] = [type_definition] + result["wrapper_registrations_Default"] = [wrapper_registration] + else: + if not fn.info: + key = "Default" + type_definition = METHOD_DEFINITION.substitute( + return_type=cpp.returns_type( + f.func.returns, symint=True + ).cpp_type(), + type_wrapper_name=type_wrapper_name(f, key), + type_definition_body=emit_body(fn, key), + formals=formals, + ) + wrapper_registration = gen_wrapper_registration(f, key) + result[f"type_derived_method_definitions_{key}"] = [type_definition] + result[f"wrapper_registrations_{key}"] = [wrapper_registration] + else: + for key in fn.info: + type_definition = METHOD_DEFINITION.substitute( + return_type=cpp.returns_type( + f.func.returns, symint=True + ).cpp_type(), + type_wrapper_name=type_wrapper_name(f, key), + type_definition_body=emit_body(fn, key), + formals=formals, + ) + wrapper_registration = gen_wrapper_registration(f, key) + result[f"type_derived_method_definitions_{key}"] = [type_definition] + result[f"wrapper_registrations_{key}"] = [wrapper_registration] + # See Note [Manual Backend kernels] + if (name in MANUAL_BACKEND) != f.manual_kernel_registration: + raise AssertionError( + f"(name in MANUAL_BACKEND) != f.manual_kernel_registration: {name in MANUAL_BACKEND} != {f.manual_kernel_registration}" + ) + # If you want to register a kernel to Autograd, you must make the op abstract. + # In other words, this op must have dispatch section in native_functions.yaml. + if name in MANUAL_AUTOGRAD_AND_TRACER or ( + fn.info and any(info.has_derivatives for info in fn.info.values()) + ): + if not f.is_abstract: + raise AssertionError( + f"There's a formula for {name}(or its functional variant) in derivatives.yaml. " + f"It's required to add a dispatch section for it with explicit supported backends e.g CPU/CUDA " + f"or CompositeExplicitAutograd in native_functions.yaml. Please see " + f"https://github.com/pytorch/pytorch/tree/master/aten/src/ATen/native#choosing-the-right-dispatch-keyword " + f"for instructions to choose the right dispatch keyword." + ) + + return result + + +_foreach_ops_without_differentiability_info = { + # No reference backward available due to the lack of `{maximum, minimum}(tensor, scalar)`. + ("_foreach_maximum", "Scalar"), + ("_foreach_maximum", "ScalarList"), + ("_foreach_minimum", "Scalar"), + ("_foreach_minimum", "ScalarList"), + # No reference backward available as addcdiv/addcmul don't support Tensor as scaling factor. + ("_foreach_addcdiv", "Tensor"), + ("_foreach_addcmul", "Tensor"), + ("_foreach_copy", ""), +} + +_foreach_ops_with_different_arity = { + # These ops lack `alpha` of scaling factor to applied to the right hand side argument. + ("_foreach_add", "Scalar"), + ("_foreach_add", "ScalarList"), + ("_foreach_sub", "Scalar"), + ("_foreach_sub", "ScalarList"), +} + + +@with_native_function_with_differentiability_info_and_key +def emit_body( + fn: NativeFunctionWithDifferentiabilityInfo, key: str = "Default" +) -> list[str]: + if dispatch_strategy(fn) != "use_derived": + raise AssertionError( + f"dispatch_strategy(fn) is {dispatch_strategy(fn)}, expected 'use_derived'" + ) + f = fn.func + info = fn.info[key] if fn.info else None + fw_derivatives = fn.fw_derivatives.get(key, []) if fn.fw_derivatives else [] + + name = cpp.name(f.func) + inplace = f.func.kind() == SchemaKind.inplace + is_out_fn = f.func.kind() == SchemaKind.out + returns_void = len(f.func.returns) == 0 + base_name = get_base_name(f) + view_info = get_view_info(f) + + is_foreach = name.startswith("_foreach") + is_inplace_foreach = is_foreach and inplace + if is_inplace_foreach: + inplace_foreacharg2refarg: dict[Argument, Argument] = {} + refargname2inplace_foreacharg: dict[str, Argument] = {} + base_name_and_overload_name = (f.func.name.name.base, f.func.name.overload_name) + if info is None: + if ( + base_name_and_overload_name + not in _foreach_ops_without_differentiability_info + ): + raise AssertionError( + f"{'.'.join(base_name_and_overload_name)} should have a differentiability info" + ) + else: + if not ( + len(f.func.arguments.flat_non_out) + == len(info.func.func.arguments.flat_non_out) + ) and ( + base_name_and_overload_name not in _foreach_ops_with_different_arity + ): + raise AssertionError( + f"{'.'.join(base_name_and_overload_name)} has {len(f.func.arguments.flat_non_out)} args " + f"but the reference has {len(info.func.func.arguments.flat_non_out)}" + ) + for foreach_arg, ref_arg in zip( + f.func.arguments.flat_non_out, info.func.func.arguments.flat_non_out + ): + foreach_arg_type = foreach_arg.type + if isinstance(foreach_arg_type, ListType): + foreach_arg_type = foreach_arg_type.elem + if foreach_arg_type != ref_arg.type: + raise AssertionError( + f"foreach_arg_type ({foreach_arg_type}) != ref_arg.type ({ref_arg.type})" + ) + inplace_foreacharg2refarg[foreach_arg] = ref_arg + refargname2inplace_foreacharg[ref_arg.name] = foreach_arg + + def gen_differentiable_input( + arg: Argument | SelfArgument | TensorOptionsArguments, + ) -> DifferentiableInput | None: + if isinstance(arg, TensorOptionsArguments): + return None + a: Argument = arg.argument if isinstance(arg, SelfArgument) else arg + + # TODO: `cpp_type` is only to keep it byte-for-byte compatible with the old codegen, should remove. + # NB: This is not a clone of cpp.argument() - TensorOptionsArguments / faithful / binds are + # not handled properly as they are irrelevant for this codegen. + cpp_type = cpp.argument_type(a, binds=a.name, symint=True).cpp_type() + + if not is_differentiable(a.name, a.type, info): + return None + return DifferentiableInput( + name=a.name, + type=a.type, + cpp_type=cpp_type, + ) + + @with_native_function + def gen_differentiable_inputs(f: NativeFunction) -> list[DifferentiableInput]: + arguments = list(f.func.arguments.non_out) + if is_inplace_foreach and info is not None: + for i, arg in enumerate(f.func.arguments.flat_non_out): + if arg in inplace_foreacharg2refarg: + # note(crcrpar): From what I understand, what matters is only the name. + # Thus originally I only replace argument only when the names are different. + # TODO(crcrpar): Make it simpler. + mapped_arg = inplace_foreacharg2refarg[arg] + arguments[i] = Argument( + mapped_arg.name, + mapped_arg.type, + mapped_arg.default, + mapped_arg.annotation, + ) + return list(mapMaybe(gen_differentiable_input, arguments)) + + def find_args_with_derivatives( + differentiable_inputs: list[DifferentiableInput], + ) -> list[DifferentiableInput]: + """Find arguments that have derivative definitions""" + if info is None or not info.has_derivatives: + return differentiable_inputs + names = {name for d in info.derivatives for name in d.var_names} + differentiable = [arg for arg in differentiable_inputs if arg.name in names] + if len(differentiable) != len(names): + missing = names - {arg.name for arg in differentiable} + raise RuntimeError( + f"Missing arguments for derivatives: {missing} in {info.name}" + ) + return differentiable + + differentiable_inputs = gen_differentiable_inputs(f) + args_with_derivatives = find_args_with_derivatives(differentiable_inputs) + differentiable_outputs = gen_differentiable_outputs(fn, key) + + undifferentiable = (base_name in DONT_REQUIRE_DERIVATIVE) or ( + name in DONT_REQUIRE_DERIVATIVE + ) + + requires_derivative = ( + (not undifferentiable) + and (len(differentiable_inputs) > 0) + and ( + (len(differentiable_outputs) > 0) + # note(crcrpar): In-place foreach functions are a void function. + or is_inplace_foreach + ) + ) + + if ( + info is not None + and info.has_derivatives + and not requires_derivative + # out= ops are allowed to have zero returns which cause requires_derivative to be False + # we shouldn't error out though (out= ops for autograd just redispatch) + and len(f.func.returns) > 0 + ): + raise RuntimeError( + f"ERROR: derivative ignored for {name} -- specified an autograd function without derivative" + ) + + # note(crcrpar): In-place foreach functions do not support forward AD + if requires_derivative and len(fw_derivatives) > 0 and not is_inplace_foreach: + num_fw_derivative_var_names = sum( + len(derivative.var_names) for derivative in fw_derivatives + ) + if num_fw_derivative_var_names != len(differentiable_outputs): + raise AssertionError( + f"Expected the number of forward derivatives implemented ({num_fw_derivative_var_names}) to match the " + f"number of differentiable outputs ({len(differentiable_outputs)}). NB: This only applies when at least " + "one forward derivative is implemented. Not implementing any forward " + "derivatives is also okay, and we would require inputs to the op to " + "not have associated tangents in that case." + ) + + try_jit_decomposition = ( + requires_derivative + and len(fw_derivatives) == 0 + and (not modifies_arguments(f)) + and (not returns_void) + ) + + def emit_save_inputs() -> list[str]: + setup: list[str] = [] + if info is None or not info.has_derivatives: + return setup + + has_tensorlist_arg = any( + is_tensor_list_type(arg.type) for arg in args_with_derivatives + ) + + # We don't want to save tensors if we know that they will never be used + # when computing the derivative, so we add guards to those statements + def guard_for(arg: SavedAttribute) -> str | None: + if info is None: + raise AssertionError("info is None in guard_for") + + # It's hard to determine the edge offset if we have TensorLists + # NOTE(crcrpar): in-place foreach functions' arguments include tensorlist + # but their derivatives don't use it, so let them bypass this check. + if has_tensorlist_arg and (not is_inplace_foreach): + return None + + # Empirical evaluation of the cases where we insert those guards in + # backward show that they are somewhat useless. E.g. there's no need + # to guard on some values captured from forward, because they had to + # require_grad if the backward function even gets executed. I don't + # have any good ideas for detecting those cases, so I simply disabled the + # checks. + if "backward" in info.name: + return None + + # If there's a single derivative we could compute, we already have + # a requires_grad check that is sufficient + if len(args_with_derivatives) <= 1: + return None + + # We really only care about trimming down the amount of tensors we save + if arg.nctype.type != BaseCType(tensorT): + return None + + # We want to emit simple guards, so we only allow that if checking one + # input is enough to determine whether we need that value + used_in = [d for d in info.derivatives if arg in d.saved_inputs] + if len(used_in) == 0: + raise AssertionError(f"used_in is empty for arg {arg.nctype.name}") + if len(used_in) != 1: + return None + derivative = used_in[0] + + # Case with multioutput formulas + # TODO: process all derivative formulas!!! + if len(derivative.var_names) != 1: + wrap_opt_if_start = derivative.formula.find( + f"wrap_opt_if({arg.nctype.name}" + ) + if wrap_opt_if_start == -1: + return None + + wrap_opt_if_match = re.match( + rf"wrap_opt_if\({arg.nctype.name},(.*?)\)", + derivative.formula[wrap_opt_if_start:], + ) + if wrap_opt_if_match is None: + raise AssertionError( + f"wrap_opt_if_match is None for {arg.nctype.name} in {derivative.formula}" + ) + + # Condition is between 'wrap_opt_if(var_name,' and ')'. + condition_slice = slice(len(rf"wrap_opt_if\({arg.nctype.name},"), -1) + wrap_opt_if_condition = wrap_opt_if_match.group(0)[ + condition_slice + ].strip() + # replace 'grad_input_mask[num]' with 'grad_fn->should_compute_output(num)' + wrap_opt_if_condition = re.sub( + r"grad_input_mask\[(\d+)\]", + r"grad_fn->should_compute_output(\1)", + wrap_opt_if_condition, + ) + return f"{wrap_opt_if_condition}" + + # Figure out the offset of the edge that uses this variable + derivative_var_name = derivative.var_names[0] + for edge_off, a in enumerate(args_with_derivatives): + if a.name == derivative_var_name: + break + else: + raise AssertionError + return f"grad_fn->should_compute_output({edge_off})" + + if is_inplace_foreach: + save_input_stmts = save_variables(info.all_saved_inputs, False, guard_for) + if save_input_stmts: + setup.append( + LOOP_OVER_VECTOR_OF_GRAD_FNS.substitute( + preamble="", statements=save_input_stmts + ) + ) + else: + setup.extend(save_variables(info.all_saved_inputs, False, guard_for)) + for arg in args_with_derivatives: + if is_tensor_list_type(arg.type): + setup.append(f"grad_fn->{arg.name}_size_ = {arg.name}.size();") + return setup + + def setup_derivative(differentiable_inputs: list[DifferentiableInput]) -> list[str]: + body: list[str] = [] + if is_out_fn: + # For out functions, ensure that no input or output requires grad + body.append(DECLARE_GRAD_FN.substitute(op="Node")) + body.append( + SETUP_NONE_REQUIRES_GRAD.substitute( + base_name=base_name, + args_to_check=[arg.name for arg in differentiable_inputs], + ) + ) + body.append( + SETUP_NONE_REQUIRES_GRAD.substitute( + base_name=base_name, + args_to_check=[arg.name for arg in differentiable_outputs], + ) + ) + return body + + op = info.op if info is not None and info.has_derivatives else "NotImplemented" + setup = [] + if not is_inplace_foreach: + setup.extend( + ASSIGN_GRAD_FN.substitute( + op=op, + op_ctor="" + if info is not None and info.has_derivatives + else f'"{cpp.name(f.func)}"', + args_with_derivatives=[arg.name for arg in args_with_derivatives], + ).split("\n") + ) + else: + # note(crcrpar): Assuming in-place foreach function's self_arg is always TensorList. + list_like_arg = "self" + args = [arg.name for arg in args_with_derivatives] + for i, arg in enumerate(args): + if is_inplace_foreach and info is not None: + if arg in refargname2inplace_foreacharg: + foreach_arg = refargname2inplace_foreacharg[arg] + args[i] = foreach_arg.name + ( + "[i]" if isinstance(foreach_arg.type, ListType) else "" + ) + else: + if arg == list_like_arg: + args[i] = arg + "[i]" + setup.extend( + ASSIGN_VECTOR_OF_GRAD_FN.substitute( + op=op, + op_ctor="" + if info is not None and info.has_derivatives + else f'"{cpp.name(f.func)}"', + args_with_derivatives=args, + irange=f"{list_like_arg}.size()", + ).split("\n") + ) + setup.extend(emit_save_inputs()) + + body.extend( + emit_check_no_requires_grad(differentiable_inputs, args_with_derivatives) + ) + declare_grad_fn_template = ( + DECLARE_GRAD_FN if not is_inplace_foreach else DECLARE_VECTOR_OF_GRAD_FN + ) + body.append(declare_grad_fn_template.substitute(op=op)) + body.append(SETUP_DERIVATIVE.substitute(setup=setup)) + return body + + def emit_check_if_in_complex_autograd_allowlist() -> list[str]: + body: list[str] = [] + if base_name in GRADIENT_IMPLEMENTED_FOR_COMPLEX: + return body + for arg in differentiable_outputs: + name = arg.name + # TODO: should be `arg.type.is_tensor_like()`? + if arg.cpp_type == "at::Tensor" or arg.cpp_type in TENSOR_LIST_LIKE_CTYPES: + body.append(f'throw_error_for_complex_autograd({name}, "{base_name}");') + return body + + def emit_check_no_requires_grad( + tensor_args: list[DifferentiableInput], + args_with_derivatives: list[DifferentiableInput], + ) -> list[str]: + """Checks that arguments without derivatives don't require grad""" + body: list[str] = [] + for arg in tensor_args: + if arg in args_with_derivatives: + continue + arg_name = arg.name + if info and arg_name in info.non_differentiable_arg_names: + continue + if arg_name == "output": + # Double-backwards definitions sometimes take in 'input' and + # 'output', but only define the derivative for input. + continue + body.append(f'check_no_requires_grad({arg_name}, "{arg_name}", "{name}");') + return body + + def emit_original_self_definition() -> list[str]: + body: list[str] = [] + if inplace: + if is_inplace_foreach: + body.append( + "std::vector<::std::optional> original_selfs(self.size());" + ) + else: + body.append("::std::optional original_self;") + + all_forward_grad_cond = [] + for derivative in fw_derivatives: + if derivative.required_original_self_value: + all_forward_grad_cond.append( + get_any_has_forward_grad_name(derivative.var_names) + ) + + if all_forward_grad_cond: + if not is_inplace_foreach: + body.append(f"if ({' || '.join(all_forward_grad_cond)}) {{") + body.append(" original_self = self.clone();") + body.append("}") + else: + current_all_forward_grad_cond = [ + f"{cond}[i]" for cond in all_forward_grad_cond + ] + body.append("for (const auto& i : c10::irange(self.size())) {") + body.append( + f" if ({' || '.join(current_all_forward_grad_cond)}) {{" + ) + body.append(" original_selfs[i] = self[i].clone();") + body.append(" }") + body.append("}") + + return body + + def save_variables( + saved_variables: Sequence[SavedAttribute], + is_output: bool, + guard_for: Callable[[SavedAttribute], str | None] = lambda name: None, + ) -> Sequence[str]: + # assign the saved variables to the generated grad_fn + stmts: list[str] = [] + for arg in sorted(saved_variables, key=lambda sa: str(sa.nctype.name)): + name = ( + arg.nctype.name.name + if isinstance(arg.nctype.name, SpecialArgName) + else arg.nctype.name + ) + foreacharg: Argument | None = None + is_foreacharg_list_type: bool = False + type = arg.nctype.type + expr = arg.expr + stmts_prepend = None + if is_inplace_foreach and info is not None: + # todo(crcrpar): See if we can add some check e.g. `assert foreacharg is not None`. + # for now the example assert would fail. + name_to_query = name.split("_scalar_type")[0] + if name_to_query in refargname2inplace_foreacharg: + foreacharg = refargname2inplace_foreacharg[name_to_query] + is_foreacharg_list_type = isinstance(foreacharg.type, ListType) + if foreacharg is not None: + name_in_expr = ( + f"{foreacharg.name}{'[i]' if is_foreacharg_list_type else ''}" + ) + src_name = name + if "_scalar_type" in src_name: + split_src_name = src_name.split("_scalar_type") + if len(split_src_name) != 2: + raise AssertionError( + f"expected 2 parts after split, got {len(split_src_name)}: {split_src_name}" + ) + src_name = split_src_name[0] + expr = expr.replace(src_name, name_in_expr) + if ( + type == BaseCType(tensorT) + or type == OptionalCType(BaseCType(tensorT)) + or type == MutRefCType(OptionalCType(BaseCType(tensorT))) + or (is_output and type == BaseCType(scalarT)) + ): + # note(crcrpar): Here `expr` is generated from scratch, `arg.expr` is ignored. + var = name + name += "_" + if var == "self" and inplace: + original_self_var = ( + "original_self" + if not is_inplace_foreach + else "original_selfs[i]" + ) + self_var = var if not is_inplace_foreach else var + "[i]" + stmts_prepend = f"if (!{original_self_var}.has_value()) {original_self_var} = {self_var}.clone()" + var = f"{original_self_var}.value()" + if is_output: + raise AssertionError( + "is_output should be False when var == 'self' and inplace" + ) + if inplace and is_output: + if name != "result_": + raise AssertionError( + f"expected name to be 'result_' for inplace output, got {name}" + ) + var = ( + "self[i]" + if is_inplace_foreach or is_foreacharg_list_type + else "self" + ) + is_inplace_view = f"{var}.is_view()" + expr = f"SavedVariable({var}, {str(is_output).lower()}, {is_inplace_view})" + else: + expr = f"SavedVariable({var}, {str(is_output).lower()})" + if foreacharg is not None and "original_selfs" not in expr: + # pyrefly: ignore [unbound-name] + expr = expr.replace(src_name, name_in_expr) + elif ( + type == BaseCType(tensorListT) + or type == ListCType(OptionalCType(BaseCType(tensorT))) + or type == BaseCType(iTensorListRefT) + or type == VectorCType(BaseCType(tensorT)) + ): + # See Note [nuanced return type of out-of-place foreach functions] + if type == VectorCType(BaseCType(tensorT)): + if not (is_foreach and is_output): + raise AssertionError( + f"VectorCType(BaseCType(tensorT)) requires is_foreach and is_output, " + f"got is_foreach={is_foreach}, is_output={is_output}" + ) + expr = f"make_saved_variable_list({name}, {str(is_foreach and is_output).lower()})" + name += "_" + elif type == BaseCType(intArrayRefT): + expr = expr + ".vec()" + elif type == BaseCType(symIntArrayRefT): + expr = expr + ".vec()" + elif type == BaseCType(stringT): + expr = f"std::string({expr})" + elif type == OptionalCType(BaseCType(stringT)): + expr = f"{expr}.has_value() ? ::std::optional(std::string({expr}.value())) : ::std::nullopt" + elif type == ArrayRefCType( + elem=BaseCType(type=BaseCppType(ns="at", name="Scalar")) + ): + expr = expr + ".vec()" + + guard = guard_for(arg) + if guard is None: + if stmts_prepend: + stmts.append(f"{stmts_prepend};") + stmts.append(f"grad_fn->{name} = {expr};") + else: + stmts.append(f"if ({guard}) {{") + if stmts_prepend: + stmts.append(f" {stmts_prepend};") + stmts.append(f" grad_fn->{name} = {expr};") + stmts.append("}") + return stmts + + # Generates a Dispatcher::redispatch() call into the dispatcher. We do this mainly for performance reasons: + # - Pre-compute the full DispatchKeySet. This saves the dispatcher from having to read from TLS. + # - redispatch() avoids a redundant call to RecordFunction, which was already called right before + # we entered this autograd kernel. + def emit_dispatch_call( + f: NativeFunction, input_base: str, unpacked_args: Sequence[str] + ) -> str: + """Dispatch call via function in a namespace or method on Tensor.""" + # code-generated autograd kernels plumb and recompute dispatch keys directly through the kernel for performance. + # Ops also always have a function variant of the redispatch API. + # See Note [Plumbing Keys Through The Dispatcher] for details. + dispatch_key_set = "ks & c10::after_autograd_keyset" + call = CALL_REDISPATCH.substitute( + api_name=cpp.name( + f.func, + faithful_name_for_out_overloads=True, + symint_overload=f.func.has_symint(), + ), + unpacked_args=[dispatch_key_set] + list(unpacked_args), + ) + return call + + def wrap_output( + f: NativeFunction, unpacked_bindings: list[Binding], var: str + ) -> str: + call = "" + rhs_value: str | None = None + if not any(r.type.is_tensor_like() for r in f.func.returns): + rhs_value = var + else: + rhs_value = f"std::move({var})" + if rhs_value is None: + raise AssertionError("rhs_value is None") + call += ASSIGN_RETURN_VALUE.substitute( + return_values=tie_return_values(f), rhs_value=rhs_value + ) + return call + + def check_tensorimpl_and_storage( + call: str, unpacked_bindings: list[Binding] + ) -> str: + # See NOTE [ TensorImpl and Storage Pointer Sanity Checks ] + stmts_before_call: list[str] = [] + stmts_after_call: list[str] = [] + + if cpp.name(f.func) in DONT_ENFORCE_SAME_TENSOR_IMPL_OR_STORAGE: + return call + + # Check properties of inputs (enforce (1)) + for unpacked_binding in unpacked_bindings: + arg = unpacked_binding.name + noref_cpp_type = unpacked_binding.nctype.type.remove_const_ref() + if noref_cpp_type == BaseCType(tensorListT) or noref_cpp_type == BaseCType( + iTensorListRefT + ): + stmts_before_call += [ + SAVE_TENSORLIST_STORAGE.substitute(tensorlist_name=arg), + SAVE_TENSORLIST_IMPL.substitute(tensorlist_name=arg), + ] + stmts_after_call += [ + ENFORCE_SAME_TENSORLIST_STORAGE.substitute(tensorlist_name=arg), + ENFORCE_SAME_TENSORLIST_IMPL.substitute(tensorlist_name=arg), + ] + elif noref_cpp_type == ListCType(OptionalCType(BaseCType(tensorT))): + stmts_before_call += [ + SAVE_OPTIONALTENSORLIST_STORAGE.substitute(tensorlist_name=arg), + SAVE_OPTIONALTENSORLIST_IMPL.substitute(tensorlist_name=arg), + ] + stmts_after_call += [ + ENFORCE_SAME_OPTIONALTENSORLIST_STORAGE.substitute( + tensorlist_name=arg + ), + ENFORCE_SAME_OPTIONALTENSORLIST_IMPL.substitute( + tensorlist_name=arg + ), + ] + elif noref_cpp_type == BaseCType(tensorT): + stmts_before_call += [ + SAVE_TENSOR_STORAGE.substitute(tensor_name=arg), + SAVE_TENSOR_IMPL.substitute(tensor_name=arg), + ] + stmts_after_call += [ + ENFORCE_SAME_TENSOR_STORAGE.substitute( + tensor_name=arg, out_tensor_name=arg + ), + ENFORCE_SAME_TENSOR_IMPL.substitute(tensor_name=arg), + ] + + if not ( + (stmts_before_call and stmts_after_call) + or (not stmts_before_call and not stmts_after_call) + ): + raise AssertionError( + "stmts_before_call and stmts_after_call must be both empty or both non-empty" + ) + + # Check properties of outputs (enforce (2), (3)) + if f.func.kind() not in (SchemaKind.inplace, SchemaKind.out): + base_name = f.func.name.name.base # TODO: should be str(f.func.name.name)? + aliased_arg_name = ALL_VIEW_FUNCTIONS.get(base_name, None) + if aliased_arg_name is not None: + aliased_arg_name = unpacked_name(aliased_arg_name) + for i, (ret, ret_name) in enumerate( + zip(f.func.returns, cpp.return_names(f)) + ): + noref_cpp_type = cpp.return_type(ret, symint=True).remove_const_ref() + if noref_cpp_type == BaseCType(tensorT): + if aliased_arg_name is not None: + if i != 0: + raise AssertionError( + f"Expect non-CompositeImplicitAutograd view function {base_name} " + f"to return single output, got index {i}" + ) + stmts_after_call += [ + ENFORCE_SAME_TENSOR_STORAGE.substitute( + tensor_name=aliased_arg_name, out_tensor_name=ret_name + ) + ] + else: + if ( + type_wrapper_name(f) + not in DONT_ENFORCE_STORAGE_IMPL_USE_COUNT + ): + stmts_after_call += [ + ENFORCE_TENSOR_STORAGE_USE_COUNT_EQUALS_ONE.substitute( + tensor_name=ret_name, fn_name=type_wrapper_name(f) + ) + ] + + if type_wrapper_name(f) not in DONT_ENFORCE_TENSOR_IMPL_USE_COUNT: + stmts_after_call += [ + ENFORCE_TENSOR_IMPL_USE_COUNT.substitute( + tensor_name=ret_name, fn_name=type_wrapper_name(f) + ) + ] + + # Currently we don't have any functions that return the following types, but + # we should update the checks once we do + elif noref_cpp_type == ListCType(OptionalCType(BaseCType(tensorT))): + raise AssertionError( + f"Please add use_count checks for {noref_cpp_type}" + ) + elif noref_cpp_type == BaseCType(tensorListT): + raise AssertionError( + f"Please add use_count checks for {noref_cpp_type}" + ) + + if stmts_before_call and stmts_after_call: + call = ( + RUN_ONLY_IN_DEBUG_MODE.substitute(statements=stmts_before_call) + + call + + RUN_ONLY_IN_DEBUG_MODE.substitute(statements=stmts_after_call) + ) + return call + + def emit_call( + f: NativeFunction, unpacked_bindings: list[Binding], try_jit_decomposition: bool + ) -> str: + # We only care about adding `at::AutoDispatchBelowAutograd` guard for non-variable dispatch + # (which corresponds to 'use_derived' strategy). The purpose of this guard is to make sure + # the baseType operations still dispatch to non-Variable type, even if the arguments passed + # in are now Variables. + # See NOTE [ Treating Variables as non-Variables in type dispatch ] for details. + unpacked_args = [b.name for b in unpacked_bindings] + base_type_call = emit_dispatch_call(f, "self_", unpacked_args) + + if get_view_info(f) is not None or modifies_arguments(f): + guard = "at::AutoDispatchBelowAutograd guard;" + else: + guard = "at::AutoDispatchBelowADInplaceOrView guard;" + + any_has_forward_grad = ( + get_any_has_fw_grad_cond(derivative=None) + if requires_derivative + else "false" + ) + return_types = ", ".join( + [cpp.return_type(a, symint=True).cpp_type() for a in f.func.returns] + ) + if len(f.func.returns) > 1: + return_types = f"std::tuple<{return_types}>" + + arg_names = [ + a.name + for a in cpp.arguments( + f.func.arguments, + faithful=True, + symint=True, + method=False, + cpp_no_default_args=set(), + ) + ] + + if not modifies_arguments(f) and not returns_void: + if try_jit_decomposition: + call = DISPATCH_TO_NON_VAR_TYPE_WITH_TMP_RETURN_VALUES_JVP_DECOMP.substitute( + base_type_call=base_type_call, + tmp_var=TMP_VAR, + guard=guard, + any_has_forward_grad=any_has_forward_grad, + op_name=cpp.name(f.func), + op_overload=f.func.name.overload_name, + return_types=return_types, + arg_names=arg_names, + ) + else: + call = DISPATCH_TO_NON_VAR_TYPE_WITH_TMP_RETURN_VALUES.substitute( + base_type_call=base_type_call, + tmp_var=TMP_VAR, + guard=guard, + ) + + call += wrap_output(f, unpacked_bindings, TMP_VAR) + else: + if try_jit_decomposition: + raise AssertionError( + "try_jit_decomposition should be False for functions with no return values or that modify arguments" + ) + call = DISPATCH_TO_NON_VAR_TYPE_WITHOUT_RETURN_VALUES.substitute( + base_type_call=base_type_call, guard=guard + ) + call = check_tensorimpl_and_storage(call, unpacked_bindings) + return call + + def emit_history() -> str: + fn = "rebase" if modifies_arguments(f) and view_info is None else "set" + output_names = [r.name for r in differentiable_outputs] + # TODO: flatten allocates a std::vector, which could be expensive + outs = CodeTemplate("flatten_tensor_args( ${outs} )").substitute( + outs=output_names if not is_inplace_foreach else "self" + ) + if not is_inplace_foreach: + if fn == "rebase": + return REBASE_HISTORY.substitute(differentiable_outputs=outs) + return SET_HISTORY.substitute(fn=fn, differentiable_outputs=outs) + else: + decl = "" + capture = "" + if fn == "rebase": + decl = "c10::SmallVector, 8> _rebased_fns(grad_fns.size());\n" + capture = "_rebased_fns[i] = " + return decl + LOOP_OVER_VECTOR_OF_GRAD_FNS.substitute( + preamble=( + f"auto differentiable_outputs = {outs};\n" + f"TORCH_INTERNAL_ASSERT(differentiable_outputs.size() == grad_fns.size());" + ), + statements=f"{capture}{fn}_history(differentiable_outputs[i], grad_fns[i]);", + ) + + def emit_fire_creation_hooks() -> str: + rebase = modifies_arguments(f) and view_info is None + if not is_inplace_foreach: + node = "_rebased_fn" if rebase else "grad_fn" + return FIRE_NODE_CREATION_HOOKS.substitute(node=node) + else: + node = "_rebased_fns[i]" if rebase else "grad_fns[i]" + return ( + "for (const auto& i : c10::irange(grad_fns.size())) {\n" + f" if ({node}) {{\n" + f" fire_node_creation_hooks({node});\n" + " }\n" + "}\n" + ) + + def emit_save_outputs() -> str: + if is_out_fn: + # out functions don't currently support differentiation + return "" + if info is not None and info.has_derivatives: + stmts = save_variables(info.all_saved_outputs, True) + if len(stmts) == 0: + return "" + if not is_inplace_foreach: + return CONDITIONAL.substitute(cond="grad_fn", statements=stmts) + else: + return LOOP_OVER_VECTOR_OF_GRAD_FNS.substitute( + preamble="", statements=stmts + ) + return "" + + def emit_any_requires_grad() -> list[str]: + extra_condition = "" + if info and info.output_differentiability_conditions: + if len(info.output_differentiability_conditions) != 1: + raise AssertionError( + f"expected 1 output_differentiability_condition, got {len(info.output_differentiability_conditions)}" + ) + extra_condition = f"_any_requires_grad &= ({info.output_differentiability_conditions[0]});" + names_of_args_with_derivatives = [arg.name for arg in args_with_derivatives] + if is_inplace_foreach and info is not None: + for i, arg in enumerate(names_of_args_with_derivatives): + for f_arg, r_arg in inplace_foreacharg2refarg.items(): + if arg == r_arg.name: + names_of_args_with_derivatives[i] = f_arg.name + return [ + SETUP_ANY_REQUIRES_GRAD.substitute( + args_with_derivatives=names_of_args_with_derivatives, + extra_differentiability_conditions=extra_condition, + ) + ] + + def get_any_has_forward_grad_name(var_names: tuple[str, ...]) -> str: + if len(var_names) == 1: + return f"_any_has_forward_grad_{var_names[0]}" + else: + return f"_any_has_forward_grad_{'_'.join(var_names)}" + + def emit_any_has_forward_grad() -> list[str]: + content: list[str] = [] + if not is_foreach: + for derivative in fw_derivatives: + requires_fw_grad = get_any_has_fw_grad_cond(derivative=derivative) + if info and info.output_differentiability_conditions: + if len(info.output_differentiability_conditions) != 1: + raise AssertionError( + f"expected 1 output_differentiability_condition, got {len(info.output_differentiability_conditions)}" + ) + requires_fw_grad = f"({info.output_differentiability_conditions[0]}) && {requires_fw_grad}" + content.append( + f"[[maybe_unused]] auto {get_any_has_forward_grad_name(derivative.var_names)} = {requires_fw_grad};" + ) + else: + for derivative in fw_derivatives: + bool_vector_name = get_any_has_forward_grad_name(derivative.var_names) + cur_derivative_conditions = [] + for inp in differentiable_inputs: + if derivative.required_inputs_fw_grad is None: + continue + if inp.name not in derivative.required_inputs_fw_grad: + continue + inp_name = ( + inp.name + if not inplace + else refargname2inplace_foreacharg[inp.name].name + ) + inp_type = ( + inp.type + if not inplace + else refargname2inplace_foreacharg[inp.name].type + ) + is_list_type = is_tensor_list_type(inp_type) + if is_list_type: + if inp_name != "self": + content.append( + FW_DERIVATIVE_SIZE_CHECK_TEMPLATE.substitute( + inp_name=inp_name + ) + ) + cur_derivative_conditions.append( + FW_DERIVATIVE_CHECK_TEMPLATE.substitute( + req_inp=inp_name + "[i]" + ) + ) + else: + cur_derivative_conditions.append( + FW_DERIVATIVE_CHECK_TEMPLATE.substitute(req_inp=inp_name) + ) + + content.append(f"std::vector {bool_vector_name}(self.size());") + content.append("for (const auto& i : c10::irange(self.size())) {") + content.append( + f" {bool_vector_name}[i] = {' || '.join(cur_derivative_conditions)};" + ) + content.append("}") + return content + + def emit_check_inplace() -> list[str]: + if not inplace: + return [] + return [ + f"check_inplace({arg.name}, _any_requires_grad);" + for arg in differentiable_outputs + ] + + def emit_fw_derivatives() -> list[str]: + content: list[str] = [] + fw_grad_setters: list[str] = [] + for derivative in fw_derivatives: + res = derivative.var_names + if f.func.name.name.inplace: + if len(res) != 1: + raise AssertionError( + f"Expected number of outputs to be 1 if function is inplace, got {len(res)}" + ) + # TODO update this when inplace namings are unified + res = ("self",) + + if derivative.required_inputs_fw_grad is None: + raise AssertionError("derivative.required_inputs_fw_grad is None") + + unpacked_arguments = "" + for inp in differentiable_inputs: + inp_name = inp.name + is_input_tensorlist = is_foreach and is_tensor_list_type( + inp.type + if not inplace + else refargname2inplace_foreacharg[inp.name].type + ) + input_suffix = "[i]" if is_input_tensorlist else "" + if is_inplace_foreach: + if inp.name in refargname2inplace_foreacharg: + inp_name = refargname2inplace_foreacharg[inp.name].name + zeros_fn = ( + "zeros_symint" + if inplace and inp.name == "self" + else "_efficientzerotensor_symint" + ) + if inp.name in derivative.required_inputs_fw_grad: + unpacked_arguments += ( + FW_DERIVATIVE_DEFINED_GRAD_TEMPLATE.substitute( + inp_name=inp.name, + inp=inp_name + input_suffix, + zeros_fn=zeros_fn, + ) + ) + if zeros_fn == "_efficientzerotensor_symint": + unpacked_arguments += ( + FW_DERIVATIVE_UPDATE_WRAPPED_NUM_TEMPLATE.substitute( + inp_name=inp.name + ) + ) + + if inp.name in (derivative.required_inputs_primal or []): + unpacked_arguments += ( + FW_DERIVATIVE_DEFINED_PRIMAL_TEMPLATE.substitute( + inp_name=inp.name, + inp=inp_name + input_suffix, + ) + ) + if derivative.required_original_self_value: + input_suffix = "s[i]" if is_inplace_foreach else "" + unpacked_arguments += FW_DERIVATIVE_DEFINED_GRAD_TEMPLATE.substitute( + inp_name="original_self", + inp="original_self" + input_suffix, + # pyrefly: ignore [unbound-name] + zeros_fn=zeros_fn, + ) + unpacked_arguments += FW_DERIVATIVE_DEFINED_PRIMAL_TEMPLATE.substitute( + inp_name="original_self", + inp="original_self" + input_suffix, + ) + elif inplace and derivative.is_reusing_outplace_formula: + # The gradient wasn't already cloned, do it if grad mode is enabled + unpacked_arguments += ( + "self_t = GradMode::is_enabled() ? self_t.clone() : self_t;" + ) + + if inplace: + is_inplace_str = "true" + else: + is_inplace_str = "false" + + requires_fw_grad = get_any_has_forward_grad_name(derivative.var_names) + + if all( + (isinstance(var_type, BaseType) and var_type.is_tensor_like()) + for var_type in derivative.var_types + ): + # Is there a way to get from BaseType to BaseCType + if len(derivative.var_types) == 1: + opt_res_grad_type = OptionalCType(BaseCType(tensorT)).cpp_type() + if not is_foreach: + fw_grad_setters.append( + FW_DERIVATIVE_SETTER_TENSOR.substitute( + out_arg=res[0], is_inplace=is_inplace_str + ) + ) + else: + expected_res = "result" if not inplace else "self" + if res[0] != expected_res: + raise AssertionError( + f"res[0] is {res[0]}, expected {expected_res}" + ) + fw_grad_setters.append( + FW_DERIVATIVE_SETTER_TENSOR_FOREACH.substitute( + out_arg=res[0], is_inplace=is_inplace_str + ) + ) + requires_fw_grad += f" && ({derivative.var_names[0]}.defined())" + else: + tuple_type = TupleCType( + [BaseCType(tensorT)] * len(derivative.var_types) + ) + opt_res_grad_type = OptionalCType(tuple_type).cpp_type() + for idx, single_res in enumerate(res): + fw_grad_setters.append( + FW_DERIVATIVE_SETTER_MULTI_OUTPUT.substitute( + idx=idx, all_res="_".join(res), out_arg=single_res + ) + ) + elif ( + isinstance(derivative.var_types[0], ListType) + and derivative.var_types[0].is_tensor_like() + ): + if len(derivative.var_types) != 1: + raise AssertionError( + f"Expected number of outputs to be 1 if function returns ListType, got {len(derivative.var_types)}" + ) + if not is_foreach: + opt_res_grad_type = OptionalCType( + VectorCType(BaseCType(tensorT)) + ).cpp_type() + fw_grad_setters.append( + FW_DERIVATIVE_SETTER_TENSOR_LIST.substitute( + out_arg=res[0], is_inplace=is_inplace_str + ) + ) + else: + # TODO(crcrpar): Should this (= the foreach specific logic) be refactored somehow? + # Only out-place foreach functions that have entries in `tools/autograd/derivatives.yaml` + # can reach here. + opt_res_grad_type = OptionalCType(BaseCType(tensorT)).cpp_type() + fw_grad_setters.append( + FW_DERIVATIVE_SETTER_TENSOR_FOREACH.substitute( + out_arg=res[0], is_inplace=is_inplace_str + ) + ) + else: + raise RuntimeError("Unsupported output type for forward derivative") + + if not is_foreach: + fw_grad_opt_definition = f"{opt_res_grad_type} {'_'.join(res)}_new_fw_grad_opt = ::std::nullopt;" + # View ops create fw_grad that already is a view of the base's fw_grad so just use that + content.append( + FW_DERIVATIVE_TEMPLATE.substitute( + fw_grad_opt_definition=fw_grad_opt_definition, + requires_fw_grad=requires_fw_grad, + formula=derivative.formula, + out_arg="_".join(res), + unpacked_arguments=unpacked_arguments, + ) + ) + else: + # note(crcrpar): Assuming `self` is TensorList. + fw_grad_opt_definition = ( + f"std::vector<{opt_res_grad_type}> {'_'.join(res)}_new_fw_grad_opts" + "(self.size(), ::std::nullopt);" + ) + foreach_forward_grad_formula = derivative.formula + _foreach_arg: Argument | DifferentiableInput + if inplace: + for _foreach_arg, _ref_arg in inplace_foreacharg2refarg.items(): + # note(crcrpar): Massage only Scalar and ArrayRef here. + if not ( + is_tensor_type(_foreach_arg.type) + or is_tensor_list_type(_foreach_arg.type) + ): + pattern = _foreach_arg.name + if isinstance(_foreach_arg.type, ListType): + pattern += "[i]" + foreach_forward_grad_formula = ( + foreach_forward_grad_formula.replace( + _ref_arg.name, pattern + ) + ) + else: + if ( + "result" in foreach_forward_grad_formula + and "result[i]" not in foreach_forward_grad_formula + ): + foreach_forward_grad_formula = ( + foreach_forward_grad_formula.replace("result", "result[i]") + ) + + content.append( + FW_DERIVATIVE_FOREACH_TEMPLATE.substitute( + fw_grad_opt_definition=fw_grad_opt_definition, + vector_of_optional_tensor=f"{'_'.join(res)}_new_fw_grad_opts", + any_has_forward_grad_for_current_index=" || ".join( + get_any_has_forward_grad_name(derivative.var_names) + "[i]" + for derivative in fw_derivatives + ), + formula=foreach_forward_grad_formula, + unpacked_arguments=unpacked_arguments, + ) + ) + + # Set all the grads at the end to avoid: https://github.com/pytorch/pytorch/issues/67367 + content.append("\n".join(fw_grad_setters)) + return content + + def get_any_has_fw_grad_cond(derivative: ForwardDerivative | None) -> str: + # + # Produces a condition string (e.g, "isFwGradDefined(grad_output) || isFwGradDefined(output)") + # + if derivative is None: + # (1) If a derivative is NOT provided, cond will check fw_grad of ALL differentiable inputs + # - Used in the out_fn case when we want to forbid fw derivatives + # - Used in the case where the fw_derivative is not defined, but we want + # To check if there is a decomposition registered for jvp + to_check: list[str] = [] + for inp in list( + mapMaybe( + gen_differentiable_input, + f.func.arguments.non_out + list(f.func.arguments.out), # type: ignore[operator] + ) + ): + if is_tensor_type(inp.type): + to_check.append( + FW_DERIVATIVE_CHECK_TEMPLATE.substitute(req_inp=inp.name) + ) + elif is_tensor_list_type(inp.type): + to_check.append( + FW_DERIVATIVE_TENSORLIST_CHECK_TEMPLATE.substitute( + req_inp=inp.name + ) + ) + else: + raise RuntimeError( + f'Unsupported input type for "{name}" when forbidding forward AD usage.' + ) + return f"({' || '.join(to_check)})" + else: + # (2) If derivative is provided, use that information to determine which inputs + # to check fw_grad for + if derivative.required_inputs_fw_grad is None: + raise AssertionError("derivative.required_inputs_fw_grad is None") + + if len(derivative.required_inputs_fw_grad) == 0: + # Handle functions like stack + # For these, we don't unpack anything and always call the user function + if not ( + len(differentiable_inputs) == 1 + and is_tensor_list_type(differentiable_inputs[0].type) + ): + raise RuntimeError( + f'No differentiable input to "{name}" is a differentiable Tensor (as the provided ' + "forward AD formula does not use any input tangent) even though a forward gradient " + "formula has been defined for it. This case should only happen for function that " + "take a single TensorList as input. All other cases are not supported right now." + ) + any_has_fw_grad = "true" + else: + any_has_fw_grad = " || ".join( + [ + ( + FW_DERIVATIVE_TENSORLIST_CHECK_TEMPLATE + if is_tensor_list_type(inp.type) + else FW_DERIVATIVE_CHECK_TEMPLATE + ).substitute(req_inp=inp.name) + for inp in differentiable_inputs + if inp.name in derivative.required_inputs_fw_grad + ] + ) + any_has_fw_grad = f"({any_has_fw_grad})" + + return any_has_fw_grad + + def emit_forbid_fw_derivatives(is_out_fn: bool = False) -> str: + if is_out_fn: + msg = "because it is an out= function" + else: + msg = ( + "because it has not been implemented yet.\\nPlease file an issue " + "to PyTorch at https://github.com/pytorch/pytorch/issues/new?template=feature-request.yml " + "so that we can prioritize its implementation." + ) + cond = get_any_has_fw_grad_cond(derivative=None) + return ( + FW_DERIVATIVE_FORBID_TEMPLATE.substitute(cond=cond, name=name, msg=msg) + if cond != "" + else "" + ) + + body: list[str] = [] + unpack_args_stats, unpacked_bindings = unpack_args(f) + + body.extend(unpack_args_stats) + if requires_derivative: + body.extend(emit_any_requires_grad()) + body.extend(emit_any_has_forward_grad()) + body.extend(emit_check_inplace()) + body.extend(emit_original_self_definition()) + body.extend(setup_derivative(differentiable_inputs)) + + body.append(emit_call(f, unpacked_bindings, try_jit_decomposition)) + if requires_derivative: + # set_flags has to appear after version_counter, because rebase_history + # requires that the counter is incremented before it is called + body.append(emit_history()) + body.extend(emit_check_if_in_complex_autograd_allowlist()) + + if is_out_fn: + body.append(emit_forbid_fw_derivatives(is_out_fn=True)) + else: + if requires_derivative and not try_jit_decomposition: + if len(fw_derivatives) > 0: + body.extend(emit_fw_derivatives()) + else: + body.append(emit_forbid_fw_derivatives()) + + if requires_derivative: + # Save only after the forward AD has been set up + body.append(emit_save_outputs()) + # Fire node creation hooks only once the node is fully populated, + # including saved outputs above. + body.append(emit_fire_creation_hooks()) + + if str(f.func.name.name) in RESET_GRAD_ACCUMULATOR: + # `inplace` implies that there is exactly one output named `self`, + # so we can keep the generated code easy. If you need to + # `reset_grad_accumulator` in an operator that's not `inplace`, you can + # remove this check but the code generation will get more elaborate + if not inplace: + raise AssertionError( + f"expected inplace=True for {f.func.name.name} which is in RESET_GRAD_ACCUMULATOR" + ) + body.append("reset_grad_accumulator(self);") + if not returns_void: + body.append(f"return {get_return_value(f)};") + return body diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_view_funcs.py b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_view_funcs.py new file mode 100644 index 0000000000000000000000000000000000000000..146bee193a6c9cb6abb86582f75fb660dc1d67ea --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/gen_view_funcs.py @@ -0,0 +1,342 @@ +# Generates ViewFuncs.h/cpp +# +# NOTE: If any changes are being made to the ViewFunc codegen please also check +# if updates are needed in torch/csrc/autograd/autograd_not_implemented_fallback.cpp +# The fallback is expected to mimic this codegen, so we should keep the two in sync. + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torchgen.api.dispatcher as dispatcher +from torchgen.api.translate import translate +from torchgen.api.types import ( + BaseCType, + Binding, + NamedCType, + SymIntT, + tensorT, + VectorCType, +) +from torchgen.code_template import CodeTemplate +from torchgen.model import Argument, NativeFunction, OptionalType +from torchgen.utils import FileManager + +from .gen_inplace_or_view_type import ( + CALL_DISPATCH, + extract_bindings, + get_view_info, + modifies_arguments, + use_derived, +) + + +if TYPE_CHECKING: + from torchgen.api.autograd import NativeFunctionWithDifferentiabilityInfo + + +FUNCTION_DECLARATION = CodeTemplate( + """\ +#define ${uppercase_op}_AVAILABLE +struct ${op} : public ${superclass} { + ${op}(${constructor_args}) ${initializer_list} + {} + virtual ~${op}() override = default; + virtual std::vector get_symints() const override; + virtual size_t num_symints() const override; + virtual std::vector get_tensors() const override; + virtual size_t num_tensors() const override; + virtual at::Tensor operator()(const at::Tensor&) const override; + virtual std::unique_ptr clone_and_set( + std::optional> = ::std::nullopt, + std::optional> = ::std::nullopt) const override; + +protected: + virtual void set_symints(std::vector) override; + virtual void set_tensors(std::vector) override; + +private: + ${state} +}; + +""" +) + +FUNCTION_DEFINITION = CodeTemplate( + """\ +std::vector ${op}::get_symints() const { + ${get_symints} +} + +size_t ${op}::num_symints() const { + return static_cast(${num_symints}); +} + +void ${op}::set_symints(std::vector ${symints_vec}) { + TORCH_INTERNAL_ASSERT(${symints_vec}.size() == num_symints()); + ${set_symints} +} + +std::vector ${op}::get_tensors() const { + ${get_tensors} +} + +size_t ${op}::num_tensors() const { + return static_cast(${num_tensors}); +} + +void ${op}::set_tensors(std::vector ${tensors_vec}) { + TORCH_INTERNAL_ASSERT(${tensors_vec}.size() == num_tensors()); + ${set_tensors} +} + +at::Tensor ${op}::operator()(const at::Tensor& ${call_input_name}) const { + return ${op_call}; +} + +std::unique_ptr ${op}::clone_and_set( + std::optional> ${symints_vec}, + std::optional> ${tensors_vec}) const { + auto output = std::make_unique<${op}>(${clone_args}); + if (${symints_vec}.has_value()) { + output->set_symints(std::move(*(${symints_vec}))); + } + if (${tensors_vec}.has_value()) { + output->set_tensors(std::move(*(${tensors_vec}))); + } + return output; +} + +""" +) + + +# e.g. as_strided -> AsStridedViewFunc for camel case or +# as_strided_view_func otherwise +def view_func_name( + f: NativeFunction, include_namespace: bool = False, camel_case: bool = True +) -> str: + name = f.func.name.unambiguous_name() + view_func_name = f"{name.replace('.', '_')}_view_func" + if camel_case: + is_private = view_func_name.startswith("_") + view_func_name = "".join( + [p.title() for p in view_func_name.replace(".", "_").split("_")] + ) + if is_private: + # put the leading underscore back in + view_func_name = f"_{view_func_name}" + namespace = "torch::autograd::generated::" if include_namespace else "" + return f"{namespace}{view_func_name}" + + +def is_symint_or_tensor(arg: Argument) -> bool: + return arg.type.is_tensor_like() or arg.type.is_symint_like() + + +def remove_const_ref(binding: Binding) -> Binding: + return Binding( + name=binding.name, + nctype=binding.nctype.remove_const_ref(), + argument=binding.argument, + default=binding.default, + ) + + +def returns_multi_tensor(fn: NativeFunction) -> bool: + returns = fn.func.returns + if len(returns) != 1: + raise AssertionError(f"Expected 1 return, got {len(returns)}") + returns_list_like = returns[0].type.is_list_like() is not None + returns_tensor_like = returns[0].type.is_tensor_like() + return returns_list_like and returns_tensor_like + + +# Generates strings with logic for getting / setting state of a particular type. +# +# Args: +# bindings (list): List of state bindings of interest (may be empty) +# state_vec_type (NamedCType): Type of vector to either return or copy from +# +# Returns: +# tuple: (list of getter logic strings, list of setter logic strings, string +# with num items expression) +def generate_state_getter_setter( + bindings: list[Binding], + state_vec_type: NamedCType, +) -> tuple[list[str], list[str], str]: + getter_logic = [] + setter_logic = [] + + state_vec = state_vec_type.name + getter_logic.append(f"{state_vec_type.cpp_type()} {state_vec};") + if len(bindings) > 0: + setter_logic.append("auto i = 0;") + + num_exprs = [] + for i, b in enumerate(bindings): + if not isinstance(b.argument, Argument): + raise AssertionError(f"Expected Argument, got {type(b.argument)}") + if b.argument.type.is_list_like(): + # Handle list-likes. + num_expr = f"{b.name}.size()" + num_exprs.append(num_expr) + getter = f"{state_vec}.insert({state_vec}.end(), {b.name}.begin(), {b.name}.end());" + setter = f"std::copy({state_vec}.begin() + i, {state_vec}.begin() + i + {b.name}.size(), {b.name}.begin());" + elif isinstance(b.argument.type, OptionalType): + # Handle optionals. + num_expr = f"({b.name}.has_value() ? 1 : 0)" + num_exprs.append(num_expr) + conditional = f"if({b.name}.has_value())" + getter = ( + f"{conditional} {state_vec}.insert({state_vec}.end(), *({b.name}));" + ) + setter = f"{conditional} {b.name} = {state_vec}[i];" + else: + num_expr = "1" + num_exprs.append(num_expr) + getter = f"{state_vec}.push_back({b.name});" + setter = f"{b.name} = {state_vec}[i];" + + getter_logic.append(getter) + setter_logic.append(setter) + if i < len(bindings) - 1: + setter_logic.append(f"i += {num_expr};") + + # Reserve / assert based on the total number of items expression. + num_items = "0" if len(num_exprs) == 0 else " + ".join(num_exprs) + if len(bindings) > 0: + getter_logic.insert(1, f"{state_vec}.reserve({num_items});") + + getter_logic.append(f"return {state_vec};") + + return getter_logic, setter_logic, num_items + + +def process_function(fn: NativeFunction, template: CodeTemplate) -> str: + bindings = extract_bindings(fn) + non_self_bindings = [b for b in bindings if b.name != "self"] + + non_self_args = fn.func.arguments.flat_all[1:] + non_self_value_bindings = [ + dispatcher.argument(a, remove_non_owning_ref_types=True) for a in non_self_args + ] + + # Generate constructor / clone args for the generated struct. + constructor_args = [b.defn() for b in non_self_bindings] + clone_args = [b.name for b in non_self_bindings] + + # Generate state variable declarations for the generated struct. + state_variables = [ + f"{remove_const_ref(b).defn()};" for b in non_self_value_bindings + ] + + # Generate initializer list expressions for the generated struct. + # allow_expensive_conversions=True because we need to store e.g. SymIntArrayRefs as + # vectors. + init_exprs = translate( + non_self_bindings, non_self_value_bindings, allow_expensive_conversions=True + ) + initializers = [] + for b, init_expr in zip(non_self_bindings, init_exprs): + name = b.nctype.name + if not isinstance(name, str): + raise AssertionError(f"Expected name to be str, got {type(name)}") + initializers.append(f"{name}({init_expr.expr})") + + # Generate call to underlying view op + call_input_name = "input_base" + op_call_args = [call_input_name, *(b.name for b in non_self_bindings)] + op_call = CALL_DISPATCH.substitute( + unambiguous_name=fn.func.name.unambiguous_name(), + unpacked_args=op_call_args, + ) + + # Multi-output views additionally require a view_idx for disambiguation. + if returns_multi_tensor(fn): + view_idx_name = "view_idx" + view_idx_typename = "int64_t" + view_idx_decl = f"{view_idx_typename} {view_idx_name}" + constructor_args.append(view_idx_decl) + clone_args.append(view_idx_name) + state_variables.append(f"{view_idx_decl};") + initializers.append(f"{view_idx_name}({view_idx_name})") + op_call += f"[{view_idx_name}]" + + # Generate initializer list for the generated struct. + initializer_list = f": {', '.join(initializers)}" if len(initializers) > 0 else "" + + # Generate getter / setter logic for any symints. + symint_bindings = [ + b + for b in non_self_bindings + if isinstance(b.argument, Argument) and b.argument.type.is_symint_like() + ] + symints_vec_type = NamedCType("symints", VectorCType(BaseCType(SymIntT))) + get_symints, set_symints, num_symints = generate_state_getter_setter( + symint_bindings, symints_vec_type + ) + + # Generate getter / setter logic for any tensors. + tensor_bindings = [ + b + for b in non_self_bindings + if isinstance(b.argument, Argument) and b.argument.type.is_tensor_like() + ] + tensors_vec_type = NamedCType("tensors", VectorCType(BaseCType(tensorT))) + get_tensors, set_tensors, num_tensors = generate_state_getter_setter( + tensor_bindings, tensors_vec_type + ) + + return template.substitute( + op=view_func_name(fn), + uppercase_op=view_func_name(fn, camel_case=False).upper(), + superclass="torch::autograd::ViewFunc", + initializer_list=initializer_list, + state=state_variables, + constructor_args=constructor_args, + clone_args=clone_args, + symints_vec=symints_vec_type.name, + get_symints=get_symints, + set_symints=set_symints, + num_symints=num_symints, + tensors_vec=tensors_vec_type.name, + get_tensors=get_tensors, + set_tensors=set_tensors, + num_tensors=num_tensors, + call_input_name=call_input_name, + op_call=op_call, + ) + + +def gen_view_funcs( + out: str, + fns_with_infos: list[NativeFunctionWithDifferentiabilityInfo], + template_path: str, +) -> None: + # don't need the info parts, just the function + fns = [fn.func for fn in fns_with_infos if use_derived(fn)] + # only want out-of-place views + view_fns = [ + fn for fn in fns if get_view_info(fn) is not None and not modifies_arguments(fn) + ] + + declarations = [process_function(fn, FUNCTION_DECLARATION) for fn in view_fns] + definitions = [process_function(fn, FUNCTION_DEFINITION) for fn in view_fns] + ops_headers = [f"#include " for fn in view_fns] + + file_basename = "ViewFuncs" + fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False) + for suffix in [".h", ".cpp"]: + fname = file_basename + suffix + fm.write_with_template( + fname, + fname, + lambda: { + "generated_comment": "@" + + f"generated from {fm.template_dir_for_comments()}/{fname}", + "view_func_declarations": declarations, + "view_func_definitions": definitions, + "ops_headers": ops_headers, + }, + ) diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/load_derivatives.py b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/load_derivatives.py new file mode 100644 index 0000000000000000000000000000000000000000..9aa0093d87f112aa4a2a5433e9ce83c679b568b8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/load_derivatives.py @@ -0,0 +1,1040 @@ +# Parses derivatives.yaml into autograd functions +# +# Each autograd function is represented by `DifferentiabilityInfo` containing +# a list of `Derivative`. See `torchgen.api.autograd` for the data models. + +from __future__ import annotations + +import re +from collections import Counter, defaultdict +from typing import Any, TYPE_CHECKING + +import yaml + +from torchgen.api import cpp +from torchgen.api.autograd import ( + Derivative, + DifferentiabilityInfo, + ForwardDerivative, + SavedAttribute, +) +from torchgen.api.types import ( + BaseCType, + Binding, + boolT, + CppSignatureGroup, + layoutT, + longT, + NamedCType, + OptionalCType, + scalarTypeT, + SpecialArgName, + stringT, + symIntArrayRefT, + SymIntT, + tensorGeometryT, + tensorOptionsT, + typeAndSizeT, + VectorCType, +) +from torchgen.context import with_native_function +from torchgen.gen import get_grouped_by_view_native_functions, parse_native_yaml +from torchgen.model import ( + AUTOGRAD_KEYS, + FunctionSchema, + NativeFunction, + NativeFunctionsViewGroup, + OperatorName, + SchemaKind, + Type, + Variant, +) +from torchgen.utils import concatMap, IDENT_REGEX, split_name_params +from torchgen.yaml_utils import YamlLoader + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +DerivativeRet = tuple[dict[FunctionSchema, dict[str, DifferentiabilityInfo]], set[str]] + +_GLOBAL_LOAD_DERIVATIVE_CACHE: dict[tuple[str, str], DerivativeRet] = {} + +_VALID_AUTOGRAD_KEYS = set(AUTOGRAD_KEYS) + + +# This function directly adds per-dispatchkey derivative entries for {view}_copy variants of each view op. +# Since every {view} and {view}_copy op shares the same derivative formula, +# we generate them here instead of duplicating them in the yaml. +# See Note [Codegen'd {view}_copy Operators] +def add_view_copy_derivatives( + infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]], + view_groups: list[NativeFunctionsViewGroup], +) -> None: + # Get the map from each view op's name to its corresponding view group + view_name_to_group: dict[OperatorName, NativeFunctionsViewGroup] = { + g.view.func.name: g for g in view_groups + } + + view_infos = {} + + for info_dispatch_dict in infos.values(): + # maybe_view_group only needs to be calculated once per info_dispatch_dict + maybe_view_group = None + view_copy_differentiability_infos = {} + for dispatch_key, info in info_dispatch_dict.items(): + maybe_view_group = view_name_to_group.get(info.func.func.name, None) + if maybe_view_group is not None and maybe_view_group.view_copy is not None: + view_copy_info = info.create_view_copy_from_view_derivative( + maybe_view_group + ) + if view_copy_info is not None: + fn_schema = view_copy_info.func.func + view_copy_differentiability_infos[dispatch_key] = view_copy_info + else: + break + # prefer manually-defined derivatives if any + # pyrefly: ignore [unbound-name] + if len(view_copy_differentiability_infos) > 0 and fn_schema not in infos: + if fn_schema is None: + raise AssertionError("Expected fn_schema to be non-None") + view_infos[fn_schema] = view_copy_differentiability_infos + + infos.update(view_infos) + + +def load_derivatives( + derivatives_yaml_path: str, native_yaml_path: str, tags_yaml_path: str +) -> DerivativeRet: + # Do some caching as this is a deterministic function + global _GLOBAL_LOAD_DERIVATIVE_CACHE + key = (derivatives_yaml_path, native_yaml_path) + if key not in _GLOBAL_LOAD_DERIVATIVE_CACHE: + with open(derivatives_yaml_path) as f: + definitions = yaml.load(f, Loader=YamlLoader) + + funcs = parse_native_yaml(native_yaml_path, tags_yaml_path).native_functions + # From the parsed native functions, separate out the (generated) view_copy functions, + # so we can generate derivatives for them separately. + native_functions_with_view_groups = get_grouped_by_view_native_functions(funcs) + native_functions = concatMap( + lambda g: [g] + if isinstance(g, NativeFunction) + else list(g.functions(include_copy=True)), + native_functions_with_view_groups, + ) + view_groups = [ + g + for g in native_functions_with_view_groups + if isinstance(g, NativeFunctionsViewGroup) + ] + + # What's the difference between function schema v.s. signature? + # function schema is the complete declaration including mutability annotation / default value and etc. + # signature is the canonical schema for a group of functions (in-place/out/functional variants) + # that are semantically related. + functions_by_signature: dict[FunctionSchema, list[NativeFunction]] = ( + defaultdict(list) + ) + functions_by_schema: dict[str, NativeFunction] = {} + for function in native_functions: + functions_by_signature[function.func.signature()].append(function) + if str(function.func) in functions_by_schema: + raise AssertionError(f"Duplicate function schema: {str(function.func)}") + functions_by_schema[str(function.func)] = function + + # Keep track of how many of which ops we've seen so we can + # disambiguate them with a numeric suffix. + op_counter = Counter[str]() + + # infos is a dict that maps FunctionSchema -> a dict of per dispatch key DifferentiabilityInfos + # this is useful because in tools/autograd/gen_autograd.py:match_differentiability_info + # we ultimately need to categorize the DifferentiabilityInfos by FunctionSchema + infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]] = {} + used_dispatch_keys: set[str] = set() + for defn_dict in definitions: + # Ensure that the old derivatives.yaml schema with no dispatch key can be loaded. + if "dispatch" not in defn_dict: + specification = defn_dict.pop("name") + output_differentiability = defn_dict.pop( + "output_differentiability", None + ) + defn_dict = {"name": specification, "dispatch": {"Default": defn_dict}} + if output_differentiability: + defn_dict["output_differentiability"] = output_differentiability + name, per_dispatch_diffinfos = create_differentiability_info( + defn_dict, + functions_by_signature, + functions_by_schema, + op_counter, + used_dispatch_keys, + ) + infos[name] = per_dispatch_diffinfos + + add_view_copy_derivatives(infos, view_groups) + + # cache both loaded infos as well as a set of all the dispatch_keys/aliases + # that appear in derivatives.yaml. used_dispatch_keys is useful for generating + # VariableType.cpp where we need a TORCH_LIBRARY_IMPL for every autograd dispatch key used + _GLOBAL_LOAD_DERIVATIVE_CACHE[key] = infos, used_dispatch_keys + + return _GLOBAL_LOAD_DERIVATIVE_CACHE[key] + + +# TODO: Why is this going through CppSignatureGroup, that doesn't make sense... +@with_native_function +def cpp_arguments(f: NativeFunction) -> Sequence[Binding]: + sigs = CppSignatureGroup.from_native_function(f, method=False) + if sigs.symint_signature is not None: + return sigs.symint_signature.arguments() + else: + return sigs.signature.arguments() + + +def create_derivative( + f: NativeFunction, + formula: str, + var_names: tuple[str, ...], + available_named_gradients: Sequence[str], +) -> Derivative: + original_formula = formula + arguments: list[NamedCType] = [ + a.nctype.remove_const_ref() for a in cpp_arguments(f) + ] + + return_names = tuple(n if n != "self" else "result" for n in cpp.return_names(f)) + return_types = tuple( + cpp.return_type(r, symint=True).remove_const_ref() for r in f.func.returns + ) + + named_returns = [ + NamedCType(name, type) for name, type in zip(return_names, return_types) + ] + + formula, saved_inputs = saved_variables(formula, arguments, var_names) + formula, saved_outputs = saved_variables(formula, named_returns, var_names) + + used_named_gradients = { + name + for name in available_named_gradients + if re.search(IDENT_REGEX.format(name), formula) + } + + # Check that the referenced derivatives in the formula are in bounds + for i in used_gradient_indices(formula): + if i >= len(f.func.returns): + raise RuntimeError( + f"Out of bounds grads access: derivative formula for {cpp.name(f.func)} " + f"used grads[{i}], but the forward only returns {len(f.func.returns)} outputs." + ) + + return Derivative( + formula=formula, + original_formula=original_formula, + var_names=var_names, + saved_inputs=saved_inputs, + saved_outputs=saved_outputs, + named_gradients=used_named_gradients, + ) + + +def create_forward_derivative( + f: NativeFunction, formula: str, names: tuple[str, ...] +) -> ForwardDerivative: + var_names = names + var_types: tuple[Type, ...] | None = None + for r in f.func.returns: + if r.name in var_names: + if var_types is None: + var_types = () + var_types = var_types + (r.type,) + + # Handle default return names + if var_types is None: + if var_names == ("result",): + if len(f.func.returns) != 1: + raise AssertionError( + f"Expected 1 return for 'result', got {len(f.func.returns)}" + ) + var_types = (f.func.returns[0].type,) + else: + for var_name in var_names: + res = re.findall(r"^result(\d+)$", var_name) + if len(res) == 1: + if var_types is None: + var_types = () + arg_idx = int(res[0]) + var_types = var_types + (f.func.returns[arg_idx].type,) + + if var_types is None: + raise AssertionError("No matching output for forward derivative definition") + return ForwardDerivative( + formula=formula, + var_names=var_names, + var_types=var_types, + required_inputs_fw_grad=None, + required_inputs_primal=None, + required_original_self_value=False, + is_reusing_outplace_formula=False, + ) + + +def postprocess_forward_derivatives( + f: NativeFunction, + defn_name: str, + all_arg_names: list[str], + derivatives: list[Derivative], + forward_derivatives: list[ForwardDerivative], + args_with_derivatives: Sequence[Binding], +) -> list[ForwardDerivative]: + def find_required_inputs(formula: str, postfix: str) -> tuple[str, ...]: + is_foreach = f.func.name.name.base.startswith("_foreach_") + required_inputs = set() + for arg in args_with_derivatives: + if ( + arg.type in ("at::TensorList", "const at::ITensorListRef &") + and not is_foreach + ): + # The functions taking TensorList handle everything internally + continue + arg_name = arg.name + + found = re.search(IDENT_REGEX.format(arg_name), formula) + if found: + raise RuntimeError( + f"The forward formula for {defn_name} is using the base name of the {arg_name} " + f"argument which is ambiguous. You should use {arg_name}_p to access the primal " + f"value and {arg_name}_t to access the tangent." + ) + + found = re.search(IDENT_REGEX.format(arg_name + postfix), formula) + if found: + required_inputs.add(arg_name) + + return tuple(required_inputs) + + updated_derivatives: list[ForwardDerivative] = [] + + for defn in forward_derivatives: + formula = defn.formula + required_inputs_tangent = find_required_inputs(formula, "_t") + if formula == "auto_element_wise": + if f.func.kind() == SchemaKind.inplace: + raise AssertionError( + f"Cannot use auto_element_wise with {f.func.name} because it is an in-place variant" + ) + if ( + (not len(args_with_derivatives) == 1) + or len(forward_derivatives) > 1 + or len(forward_derivatives[0].var_names) > 1 + ): + raise RuntimeError( + f"Derivative definition of {defn_name} in derivatives.yaml defines the " + "forward definition of gradient as element_wise but this only " + "works for functions with a single differentiable input and a " + "single differentiable output." + ) + if not len(derivatives) == 1: + raise RuntimeError( + f"Derivative definition of {defn_name} in derivatives.yaml defines the " + "forward definition of gradient as element_wise but it does not " + "defines the gradient formula for its argument which is required." + ) + # This transformation is based on the observation that for element-wise functions, the Jacobian + # matrix is diagonal and thus doing J * v is the same as (v^T J)^T (in practice, we ignore the transpositions) + # For the complex case, we use hermitian transpose and get (v.conj() J).conj() + # So here we are going to reuse the backward formula and replace two things: + # 1) all occurrences of "grad" with "foo_t.conj()", where foo is the name of the unique differentiable input. + # 2) all usage of an original input "foo" with its primal value "foo_p". + # 3) conjugate the final result + # For example, for abs, the backward formula is: + # grad * self.sgn() + # And this function generates a forward formula that is: + # (self_t.conj() * self_p.sgn()).conj() + + backward_formula = derivatives[0].original_formula + input_name = args_with_derivatives[0].name + + # Do replacement 1) of the grad + def repl(m: Any) -> str: + return f"{m.group(1)}{input_name}_t.conj(){m.group(2)}" + + fw_formula = re.sub(IDENT_REGEX.format("grad"), repl, backward_formula) + + # Do replacement 2) of the input variables + for arg in args_with_derivatives: + arg_name = arg.name + + def repl(m: Any) -> str: + return f"{m.group(1)}{arg_name}_p{m.group(2)}" + + fw_formula = re.sub(IDENT_REGEX.format(arg_name), repl, fw_formula) + + # Do the final conjugate 3) + fw_formula = f"({fw_formula}).conj()" + + # Since there is a single differentiable inputs and we necessarily need its tangent we can + # simply require all differentiable input's tangent. + required_inputs_tangent = tuple(all_arg_names) + formula = fw_formula + elif formula == "auto_linear": + if ( + len(forward_derivatives) > 1 + or len(forward_derivatives[0].var_names) > 1 + ): + raise RuntimeError( + f"Derivative definition of {defn_name} in derivatives.yaml defines the " + "forward definition of gradient as linear but this only works " + "for functions with a single differentiable output." + ) + # This transformation is based on the observation that linear functions can be written as: + # y = f(x) = A * x + # For some matrix A and the Jacobian of the function f is also A. + # So doing J * v = A * v = f(v). + # Hence to do the jvp, we simply need to evaluate the function at the point v instead of x. + # We do this by calling the forward again by replacing any occurrence of the differentiable + # input "foo" by it's tangent "foo_t". + # Note that multiple inputs are not a problem as long as the function is truly linear wrt to + # the vector where all the differentiable inputs are stacked. + + diff_arg_names = [arg.name for arg in args_with_derivatives] + if len(diff_arg_names) == 0: + raise AssertionError("Expected at least one differentiable argument") + + # Do replacement of input variables + new_args = [] + for arg_name in all_arg_names: + if arg_name in diff_arg_names: + arg_name = arg_name + "_t" + new_args.append(arg_name) + + # TODO we are trolling + if f.func.has_symint(): + defn_name += "_symint" + + # Call into the forward again. We need two cases here to handle both Tensor methods and at:: functions. + if Variant.function in f.variants: + fw_formula = f"at::{defn_name}({', '.join(new_args)})" + else: + if Variant.method not in f.variants: + raise AssertionError( + f"Expected Variant.method in variants for {f.func.name}" + ) + fw_formula = f"{new_args[0]}.{defn_name}({', '.join(new_args[1:])})" + + # All of the input tangents are always used so all of them are required here. + required_inputs_tangent = tuple(diff_arg_names) + formula = fw_formula + + # At this point, the formula is final and is not modified anymore. + + # During forward formula, we use the primal instead of the input Tensors. + # This call inspects the formula to find for which input's primal are used. + required_inputs_primal = find_required_inputs(formula, "_p") + + updated_derivatives.append( + ForwardDerivative( + formula=formula, + var_names=defn.var_names, + var_types=defn.var_types, + required_inputs_fw_grad=required_inputs_tangent, + required_inputs_primal=required_inputs_primal, + required_original_self_value=False, + is_reusing_outplace_formula=False, + ) + ) + + return updated_derivatives + + +def is_forward_derivative_definition( + all_arg_names: list[str], names: tuple[str, ...] +) -> bool: + for name in names: + return name not in all_arg_names + raise RuntimeError("Expected `names` to be non-empty") + + +def create_differentiability_info( + defn_dict: dict[Any, Any], + functions_by_signature: dict[FunctionSchema, list[NativeFunction]], + functions_by_schema: dict[str, NativeFunction], + op_counter: Counter[str], + used_dispatch_keys: set[str], +) -> tuple[FunctionSchema, dict[str, DifferentiabilityInfo]]: + """Processes a single entry `defn` in derivatives.yaml""" + + def canonical_function( + functions: Sequence[NativeFunction], name: str + ) -> NativeFunction: + for f in functions: + if ( + not f.func.is_functional_fn() + and not f.func.is_out_fn() + and name == str(f.func.name.name) + ): + return f + # some functions only have in-place variants + if name + "_" != cpp.name(functions[0].func): + raise AssertionError( + f"Expected inplace function name '{name}_', got '{cpp.name(functions[0].func)}'" + ) + return functions[0] + + def split_names(raw_names: str) -> tuple[str, ...]: + """Given "foo, bar", return ["foo", "bar"].""" + return tuple(x.strip() for x in raw_names.split(",")) + + def check_grad_usage(defn_name: str, derivatives: Sequence[Derivative]) -> None: + """ + Check for some subtle mistakes one might make when writing derivatives. + These mistakes will compile, but will be latent until a function is + used with double backwards. + """ + + uses_grad = False # true if any derivative uses "grad" + num_grads_uses = 0 # count of uses of "grads" or "grads[INDEX]" + uses_named_grads = False # true if any derivative uses "grad_{name}" + used_grads_indices: list[int] = [] # which indices of grads are used + for d in derivatives: + formula = d.formula + uses_grad = uses_grad or bool( + re.findall(IDENT_REGEX.format("grad"), formula) + ) + num_grads_uses += len(re.findall(IDENT_REGEX.format("grads"), formula)) + uses_named_grads = uses_named_grads or bool(d.named_gradients) + used_grads_indices.extend(used_gradient_indices(formula)) + # This is a basic sanity check: the number of places we see + # "grads" should be no fewer than the number of indices we see + # inside "grads". They may not be equal because we may use + # "grads" without an index. + if num_grads_uses < len(used_grads_indices): + raise AssertionError( + f"num_grads_uses ({num_grads_uses}) < len(used_grads_indices) ({len(used_grads_indices)})" + ) + # Thus if the number is equal, every use of grads is also + # indexed. + only_used_grads_indices = num_grads_uses == len(used_grads_indices) + + if uses_grad and num_grads_uses > 0: + raise RuntimeError( + f"Derivative definition of {defn_name} in derivatives.yaml illegally " + "mixes use of 'grad' and 'grads'. Consider replacing " + "occurrences of 'grad' with 'grads[0]'" + ) + + if only_used_grads_indices and set(used_grads_indices) == {0}: + raise RuntimeError( + f"Derivative definition of {defn_name} in derivatives.yaml solely " + "refers to 'grads[0]'. If the first output is indeed the " + "only differentiable output, replace 'grads[0]' with 'grad'; " + "otherwise, there is a likely error in your derivatives " + "declaration." + ) + + if uses_named_grads and (uses_grad or num_grads_uses > 0): + raise RuntimeError( + f"Derivative definition of {defn_name} in derivatives.yaml illegally " + 'mixes use of "grad_RETURN_NAME" and "grad" or "grads[x]". Use ' + "only one method for identifying gradients." + ) + + @with_native_function + def set_up_derivatives( + f: NativeFunction, + ) -> tuple[ + Sequence[Derivative], + Sequence[ForwardDerivative], + Sequence[Binding], + Sequence[str], + Sequence[str], + ]: + # Set up the derivative information + derivatives: list[Derivative] = [] + forward_derivatives: list[ForwardDerivative] = [] + non_differentiable_arg_names: list[str] = [] + args_with_derivatives_set: set[str] = set() + + all_arg_names = [a.name for a in cpp_arguments(f)] + all_ret_names = [ + r.name for r in f.func.returns + ] # only used for the assert below + # output_differentiability is captured from the enclosed + # scope. Don't modify it. + # + # If it is not present, then no output is explicitly + # undifferentiable. + # + # It may be present and shorter than the length of return + # values. If that's the case, any return value that does not + # have a corresponding entry is considered not differentiable. + differentiability = output_differentiability or [True] * len(f.func.returns) + # A return is available as a named gradient ... + available_named_gradients = [ + f"grad_{ret.name}" + for ret, differentiable in zip(f.func.returns, differentiability) + # if it has not been explicitly made undifferentiable + if differentiable + # and if it has a name + and ret.name is not None + # and if its type is differentiable + and ret.type.is_tensor_like() + ] + + for raw_names in sorted(defn.keys()): + formula = defn[raw_names] + names = split_names(raw_names) + + for name in names: + if name in all_arg_names and name in all_ret_names: + raise AssertionError( + f"While processing the derivative formula for '{f.func.name}' wrt '{name}', " + f"expected '{name}' to not be both an input arg and named return." + ) + + if is_forward_derivative_definition(all_arg_names, names): + forward_derivatives.append(create_forward_derivative(f, formula, names)) + else: + if formula.lower().strip() == "non_differentiable": + non_differentiable_arg_names += names + else: + derivative = create_derivative( + f, formula, names, available_named_gradients + ) + derivatives.append(derivative) + args_with_derivatives_set |= set(names) + + overlap = args_with_derivatives_set.intersection(non_differentiable_arg_names) + if overlap: + raise RuntimeError( + f"derivatives definition for {defn} have overlapped non_differentiable " + f"and differentiable variables: {overlap}" + ) + + # Next, let us determine the list of inputs in order. + # TODO: do we need eagerly calculate and save it here? Can it be derived + # from NativeFunction and `derivatives` on callsites instead? + args_with_derivatives = [ + a for a in cpp_arguments(f) if a.name in args_with_derivatives_set + ] + + # Postprocess forward derivatives definitions now that we know the differentiable arguments + forward_derivatives = postprocess_forward_derivatives( + f, + defn_name, + all_arg_names, + derivatives, + forward_derivatives, + args_with_derivatives, + ) + + # Test to see if the use of 'grads' makes sense. + check_grad_usage(defn_name, derivatives) + + return ( + derivatives, + forward_derivatives, + args_with_derivatives, + non_differentiable_arg_names, + available_named_gradients, + ) + + # NB: Removes 'name' from defn dictionary + specification = defn_dict.pop("name") + defn_name, _ = split_name_params(specification) + # NB: Removes 'output_differentiability' from defn dictionary + # `None` means all differentiable. + output_differentiability = defn_dict.pop("output_differentiability", None) + output_differentiability_conditions = None + if output_differentiability and any( + isinstance(diff, str) for diff in output_differentiability + ): + if len(output_differentiability) != 1: + raise RuntimeError( + f"Not supported: for {specification}," + f"output_differentiability must either be " + f"list[bool] or a list[str] where each str is a " + f"condition. In the case where it is a condition, " + f"we only support single-output functions. " + f"Please file us an issue. " + ) + output_differentiability_conditions = output_differentiability + output_differentiability = [True] + + schema_function = functions_by_schema.get(specification) + if not schema_function: + avail = "\n".join( + k for k, v in functions_by_schema.items() if cpp.name(v.func) == defn_name + ) + raise RuntimeError( + f"could not find ATen function for schema: {specification} " + f". Available signatures:\n{avail}" + ) + + # now map this to the legacy schema; this isn't technically necessary, but we'd need some logic here + # to map in-place schemas to the out-of-place variants. + # TODO: maybe the logic to handle the legacy schema is no longer necessary? + signature = schema_function.func.signature() + functions = functions_by_signature[signature] + if len(functions) == 0: + avail = "\n".join( + str(k) + for k, v in functions_by_signature.items() + if cpp.name(k) == defn_name + ) + raise RuntimeError( + f"could not find ATen function for legacy signature: {signature} " + f"corresponding to schema {specification}. Please report a bug to PyTorch. " + f"Available signatures:\n{avail}" + ) + + canonical = canonical_function(functions, defn_name) + if "grad_input_mask" in (a.name for a in cpp_arguments(canonical)): + raise RuntimeError( + f"Schema for {defn_name} has an argument named grad_input_mask, " + "but this name would be shadowed by our codegen. " + "Please use a different name in native_functions.yaml." + ) + + if "result" in (a.name for a in cpp_arguments(canonical)): + raise RuntimeError( + f"Schema for {defn_name} has an argument named result, " + "but this is only allowed for outputs." + "Please use a different name in native_functions.yaml." + ) + + diffinfo_dict = {} + for key, defn in defn_dict["dispatch"].items(): + if key != "Default" and key not in _VALID_AUTOGRAD_KEYS: + raise RuntimeError( + f"Invalid dispatch key {key} in derivatives.yaml for {specification}," + f" expected key to be one of {_VALID_AUTOGRAD_KEYS}" + ) + if key not in used_dispatch_keys: + used_dispatch_keys.add(key) + + ( + derivatives, + forward_derivatives, + args_with_derivatives, + non_differentiable_arg_names, + available_named_gradients, + ) = set_up_derivatives(canonical) + + used_named_gradients: set[str] = set() + for d in derivatives: + used_named_gradients |= d.named_gradients + + # only assign an op name if we are actually going to calculate a derivative + op = None + if args_with_derivatives: + op_prefix = _create_op_prefix(defn_name) + if key != "Default": + op_prefix = op_prefix + key + op = f"{op_prefix}{op_counter[op_prefix]}" + op_counter[op_prefix] += 1 + + diffinfo_dict[key] = DifferentiabilityInfo( + name=defn_name, + func=canonical, + op=op, + derivatives=derivatives, + forward_derivatives=forward_derivatives, + all_saved_inputs=dedup_vars( + [v for d in derivatives for v in d.saved_inputs] + ), + all_saved_outputs=dedup_vars( + [v for d in derivatives for v in d.saved_outputs] + ), + available_named_gradients=available_named_gradients, + used_named_gradients=used_named_gradients, + args_with_derivatives=args_with_derivatives, + non_differentiable_arg_names=non_differentiable_arg_names, + output_differentiability=output_differentiability, + output_differentiability_conditions=output_differentiability_conditions, + ) + + return canonical.func, diffinfo_dict + + +GRAD_INDEX_REGEX = r"(?:^|\W)grads\[(\d+)\]" + + +def used_gradient_indices(formula: str) -> list[int]: + """Determine a list of gradient indices (the i in grads[i]) that + are used by the formula. + + >>> used_gradient_indices("foo(grads[0], grads[1])") + [0, 1] + """ + return [int(i) for i in re.findall(GRAD_INDEX_REGEX, formula)] + + +def saved_variables( + formula: str, + nctypes: list[NamedCType], + var_names: tuple[str, ...], +) -> tuple[str, tuple[SavedAttribute, ...]]: + def stride_expr(name: str) -> str: + if var_names != (name,): + raise AssertionError( + 'Replacement for ".strides()" is currently only supported for single derivatives of the same tensor ' + 'that ".strides()" is being called on.' + ) + return f'strides_or_error({name}, "{name}")' + + REPLACEMENTS: list[tuple[str, dict[str, Any]]] = [ + # replace self.sym_sizes() with self_sym_sizes + ( + r"{}.sym_sizes\(\)", + { + "suffix": "_sym_sizes", + "nctype": lambda name: NamedCType(name, BaseCType(symIntArrayRefT)), + }, + ), + # replace self->sym_sizes() with self_sym_sizes_opt + ( + r"{}->sym_sizes\(\)", + { + "suffix": "_sym_sizes_opt", + "nctype": lambda name: NamedCType( + name, OptionalCType(BaseCType(symIntArrayRefT)) + ), + "expr": lambda name: f"{name}.has_value() ? std::optional({name}->sym_sizes()) : std::nullopt", + }, + ), + # replace self.sym_blocksize() with self_sym_blocksize_opt + ( + r"{}.sym_blocksize\(\)", + { + "suffix": "_self_sym_blocksize_opt", + "nctype": lambda name: NamedCType( + name, OptionalCType(BaseCType(symIntArrayRefT)) + ), + "expr": lambda name: f"at::sparse_csr::getSymIntBlockSize({name})", + }, + ), + # replace self.options() with self_options + ( + r"{}.options\(\)", + { + "suffix": "_options", + "nctype": lambda name: NamedCType(name, BaseCType(tensorOptionsT)), + }, + ), + # replace zeros_like(self) with self_info + ( + r"zeros_like\({}\)", + { + "suffix": "_info", + "nctype": lambda name: NamedCType(name, BaseCType(typeAndSizeT)), + "expr": lambda name: name, # at save-time + "res": lambda name: name + "_info.zeros()", # at eval-time + }, + ), + # replace self.sym_size(2) with self_sym_size_2 + ( + r"{}.sym_size\((-?\w+)\)", + { + "suffix": lambda m: f"_sym_argsize_{m.groups()[0].replace('-', 'minus_')}", + "nctype": lambda name: NamedCType(name, BaseCType(SymIntT)), + }, + ), + # replace self.numel() with self_numel + ( + r"{}.numel\(\)", + { + "suffix": "_numel", + "nctype": lambda name: NamedCType(name, BaseCType(longT)), + }, + ), + # replace self.sym_numel() with self_sym_numel + ( + r"{}.sym_numel\(\)", + { + "suffix": "_sym_numel", + "nctype": lambda name: NamedCType(name, BaseCType(SymIntT)), + }, + ), + # replace to_args_sizes(self) with self_args_sizes + ( + r"to_args_sizes\({}\)", + { + "suffix": "_args_sizes", + "nctype": lambda name: NamedCType( + name, VectorCType(VectorCType(BaseCType(longT))) + ), + }, + ), + # replace to_args_sizes_symint(self) with self_args_sizes + ( + r"to_args_sizes_symint\({}\)", + { + "suffix": "_args_sizes_symint", + "nctype": lambda name: NamedCType( + name, VectorCType(VectorCType(BaseCType(SymIntT))) + ), + }, + ), + # replace to_args_scalartypes(self) with self_args_scalartypes + ( + r"to_args_scalartypes\({}\)", + { + "suffix": "_args_scalartypes", + "nctype": lambda name: NamedCType( + name, VectorCType(BaseCType(scalarTypeT)) + ), + }, + ), + # replace TensorGeometry(self) with self_geometry + ( + r"TensorGeometry\({}\)", + { + "suffix": "_geometry", + "nctype": lambda name: NamedCType(name, BaseCType(tensorGeometryT)), + }, + ), + ( + r"{}.scalar_type\(\)", + { + "suffix": "_scalar_type", + "nctype": lambda name: NamedCType(name, BaseCType(scalarTypeT)), + }, + ), + # replace self.dim() with self_dim + ( + r"{}.dim\(\)", + { + "suffix": "_dim", + "nctype": lambda name: NamedCType(name, BaseCType(longT)), + }, + ), + # replace self.sym_strides() with self_sym_strides + ( + r"{}.sym_strides\(\)", + { + "suffix": "_sym_strides", + "nctype": lambda name: NamedCType(name, BaseCType(symIntArrayRefT)), + "expr": stride_expr, + }, + ), + # replace self.layout() with self_layout + ( + r"{}.layout\(\)", + { + "suffix": "_layout", + "nctype": lambda name: NamedCType(name, BaseCType(layoutT)), + }, + ), + # replace self.is_conj() with self_conjugate + ( + r"{}.is_conj\(\)", + { + "suffix": "_conjugate", + "nctype": lambda name: NamedCType(name, BaseCType(boolT)), + }, + ), + ] + + # find which arguments need to be saved + saved: list[SavedAttribute] = [] + + if ".sizes()" in formula or "->sizes()" in formula: + raise RuntimeError( + ".sizes() is not supported in derivative formulas. Instead, please use the SymInt version," + + f".sym_sizes(), which returned a c10::SymIntArrayRef. formula={formula}" + ) + if re.search(r"\.size\([-]?\d+\)", formula) or re.search( + r"->size\([-]?\d+\)", formula + ): + raise RuntimeError( + ".size(int) is not supported in derivative formulas. Instead, please use the SymInt version," + + f".sym_size(int), which returned a c10::SymIntArrayRef. formula={formula}" + ) + if ".strides()" in formula or "->strides()" in formula: + raise RuntimeError( + ".strides() is not supported in derivative formulas. Instead, please use the SymInt version," + + f".sym_strides(), which returned a c10::SymIntArrayRef. formula={formula}" + ) + for nctype in nctypes: + name = ( + nctype.name.name if isinstance(nctype.name, SpecialArgName) else nctype.name + ) + # First search the formula for expressions which can be evaluated + # when the autograd Function is created to avoid saving variables + for regex, info in REPLACEMENTS: + + def repl(m: re.Match[str]) -> str: + suffix: str = ( + # pyrefly: ignore [bad-assignment] + info["suffix"](m) if callable(info["suffix"]) else info["suffix"] + ) + expr: str = info["expr"](name) if "expr" in info else m.group(0) + saved.append( + SavedAttribute( + nctype=info["nctype"](name + suffix), + expr=expr, + ) + ) + if "res" in info: + replacement: str = info["res"](name) + return replacement + return name + suffix + + formula = re.sub(regex.format(name), repl, formula) + + # std::optional types stored in Backward nodes must be + # converted to std::optional before being passed into + # the backward function + if nctype.type == OptionalCType(BaseCType(stringT)): + formula = re.sub( + rf"\b{name}\b", + f"{name}.has_value() ? std::optional({name}.value()) : std::nullopt", + formula, + ) + + # Find any variables which remain in the formula and save them + if re.search(IDENT_REGEX.format(name), formula): + saved.append( + SavedAttribute( + nctype=nctype, + expr=name, + ) + ) + + return formula, tuple(saved) + + +def _create_op_prefix(name: str) -> str: + r"""Takes a native function name converts to an op prefix name. + + Note that the "name" parameter must be the native function name + without the optional variant suffix, so "add" instead of + "add.out". + + OP names correspond to classes, hence the change to title case. + + Example:: + + >>> _create_op_prefix("add") + 'AddBackward' + """ + camel_case = "".join([p.title() for p in name.split("_")]) + return (camel_case + "Backward").replace("ForwardBackward", "Backward") + + +def dedup_vars(vars: Sequence[SavedAttribute]) -> Sequence[SavedAttribute]: + seen: set[str] = set() + saved: list[SavedAttribute] = [] + for var in vars: + name = ( + var.nctype.name.name + if isinstance(var.nctype.name, SpecialArgName) + else var.nctype.name + ) + if name in seen: + continue + seen.add(name) + saved.append(var) + return saved diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/ADInplaceOrViewType.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/ADInplaceOrViewType.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e8276697eee065a36d1b16e583a5f011f92541c2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/ADInplaceOrViewType.cpp @@ -0,0 +1,38 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include "torch/csrc/autograd/VariableTypeUtils.h" +#include "torch/csrc/autograd/generated/ViewFuncs.h" + +#include +#include +#include + +// ${generated_comment} + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +$ops_headers +#endif + +using namespace at; +using torch::autograd::CreationMeta; +using torch::autograd::as_view; +using torch::autograd::increment_version; + +namespace torch { + +namespace ADInplaceOrView { + +namespace { +${inplace_or_view_method_definitions} +} // namespace +} // namespace ADInplaceOrView + +namespace { + +TORCH_LIBRARY_IMPL(aten, ADInplaceOrView, m) { + ${inplace_or_view_wrapper_registrations}; +} + +} // namespace +} // namespace torch diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/Functions.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/Functions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba5cb3d912c5d7a3bbf31f4b0d38d4413dfc160c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/Functions.cpp @@ -0,0 +1,44 @@ +#include "torch/csrc/autograd/FunctionsManual.h" +#include "torch/csrc/dynamo/compiled_autograd.h" + +// ${generated_comment} + +// The manual function definitions that used to be here are now in torch/csrc/autograd/FunctionsManual.cpp +// This speeds up re-compilation and allow to share these implementations so that they can be +// used for forward mode AD formulas as well. + +using namespace torch::autograd::generated::details; +using at::Tensor; +using at::Scalar; +using at::IntArrayRef; +using at::TensorList; + +namespace torch::autograd::generated { + +static at::IValue compute_output_metadata(const torch::autograd::edge_list& next_edges) { + auto output_metadata = torch::dynamo::autograd::IValuePacker< + std::vector>>::pack( + torch::dynamo::autograd::get_input_metadata(next_edges)); + return output_metadata; +} + +static C10_NOINLINE variable_list compiled_autograd_apply_functional( + const PackedArgs& packed_args, + const edge_list& next_edges, + SwapSavedVariables& saved, + const variable_list& grads, + const std::string& name) { + auto output_metadata = compute_output_metadata(next_edges); + const auto& pyinterface = torch::dynamo::autograd::getPyCompilerInterface(); + return pyinterface->call_function( + saved.get_py_compiler(), + "apply_functional", + name, + grads, + packed_args.vec(), + output_metadata); +} + +${autograd_function_definitions} + +} // namespace torch::autograd::generated diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/Functions.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/Functions.h new file mode 100644 index 0000000000000000000000000000000000000000..cf293acf4b356992d3cf0c56b90a109abc774a90 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/Functions.h @@ -0,0 +1,51 @@ +#pragma once + +// ${generated_comment} + +#include +#include +#include + +#include "torch/csrc/autograd/function.h" +#include "torch/csrc/autograd/variable.h" +#include "torch/csrc/autograd/saved_variable.h" +#include + +#include + +namespace torch::autograd::generated { + +using at::Scalar; +using at::Tensor; +using at::IntArrayRef; +using at::ArrayRef; +using at::Type; +using at::TensorGeometry; +using at::ScalarType; +using std::optional; +using c10::fmap; + +inline std::vector unpack_list(at::ArrayRef xs, c10::intrusive_ptr saved_for = nullptr) { + // NB: we must explicitly do the conversion in the lambda, otherwise template + // deduction will give a Tensor of Variable which is not convertible + return fmap(xs, [&saved_for](const SavedVariable& x) { + // TODO(crcrpar): Use `std::move(saved_for)` to avoid incrementing refcount, which would need refactoring. + return static_cast(x.unpack(saved_for)); + }); +} + +inline c10::List> unpack_opt_list(at::ArrayRef xs, c10::intrusive_ptr saved_for = nullptr) { + torch::List> result; + result.reserve(xs.size()); + for (const SavedVariable& v : xs) { + auto var = v.unpack(saved_for); + result.push_back(var.defined() ? std::optional(var) : ::std::nullopt); + } + return result; +} + +using torch::autograd::TypeAndSize; + +${autograd_function_declarations} + +} // namespace torch::autograd::generated diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/TraceType.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/TraceType.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fb5e7ae44a5353a3cc2a90858fe33b7fc0ef8bfd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/TraceType.cpp @@ -0,0 +1,40 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include "torch/csrc/jit/frontend/tracer.h" + +#include + +#include "torch/csrc/autograd/function.h" + +#include "ATen/quantized/Quantizer.h" + +// ${generated_comment} + +// See the `Tracer` section in `torch/csrc/jit/OVERVIEW.md`. +// NOTE See [Sharded File] comment in VariableType + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +$ops_headers +#endif + +using namespace at; + +namespace torch { + +namespace TraceType { + +namespace { +${trace_method_definitions} +} // namespace +} // namespace TraceType + +namespace { + +TORCH_LIBRARY_IMPL(aten, Tracer, m) { + ${trace_wrapper_registrations}; +} + +} // namespace + +} // namespace torch diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/VariableType.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/VariableType.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d1de108283b1169902a085e4886de7a0113c309c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/VariableType.cpp @@ -0,0 +1,77 @@ +#include "torch/csrc/autograd/VariableTypeUtils.h" +#include "torch/csrc/autograd/generated/VariableType.h" +#include "torch/csrc/autograd/FunctionsManual.h" + +#include +#include +#include +#include + +#include + + +// ${generated_comment} + +// NOTE [Sharded File]: on this file's split-into-shards state +// +// Back in the good old days, VariableType.cpp was generated as one +// file with every function in it, and everything was great and +// simple. +// +// However, this file was also very large (over 36,000 lines), and +// compiling it was very slow, and in fact was a significant +// bottleneck for incremental rebuilds. To address this, we now +// generate the file split across multiple shards, named +// VariableType_0.cpp and so on, which can be compiled in parallel. +// +// For ease of inspection and debugging, so that it's not necessary to +// go rooting around in multiple files, we also generate all the +// functions together in VariableTypeEverything.cpp. This generated +// file is only for convenience; it's not actually used in the +// build. If the file you're looking at now is one of the shards, you +// may want to switch over to the Everything variant to make you +// grepping smoother. + +using namespace at; +using namespace torch::autograd::generated; +using namespace torch::autograd::generated::details; + + +namespace torch::autograd { + +namespace VariableType { +namespace{ +[[maybe_unused]] void reset_grad_accumulator(Variable& self) { + AutogradMeta* meta = torch::autograd::impl::get_autograd_meta(self); + if (meta != nullptr) { + meta->grad_accumulator_.reset(); + } +} +[[maybe_unused]] size_t expected_fresh_use_count(const Variable& self) { + if (!self.defined()) { + // An UndefinedTensorImpl always has a use count of 0 + return 0; + } + if (self.unsafeGetTensorImpl()->pyobj_slot()->load_pyobj() != nullptr) { + // A TensorImpl with a Python object has a use count of 2 + return 2; + } + // A fresh TensorImpl (with no PyObject) has a use count of 1 + return 1; +} +} + +namespace { + + +${type_derived_method_definitions} +} +} + +namespace { + +${wrapper_registrations} + +} + +} // namespace torch::autograd diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/VariableType.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/VariableType.h new file mode 100644 index 0000000000000000000000000000000000000000..a2fd7fda116cc6b653c09c282f0f8e93cf765a2c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/VariableType.h @@ -0,0 +1,53 @@ +#pragma once + +// ${generated_comment} + +#include +#include + +#include + +#include +#include + +#include // for size_t +#include // for function +#include // for unique_ptr +#include +#include + +namespace at { + struct Quantizer; +} + +namespace torch { namespace autograd { + +using Variable = at::Tensor; +using at::Context; +using at::Device; +using at::Generator; +using at::IntArrayRef; +using at::MemoryFormat; +using at::QScheme; +using at::Scalar; +using at::ScalarType; +using at::Storage; +using at::Tensor; +using at::TensorList; +using at::TensorOptions; +using at::Quantizer; +using std::optional; + +namespace VariableType { + TORCH_API std::vector allCUDATypes(); + TORCH_API std::vector allXPUTypes(); + TORCH_API std::vector allCPUTypes(); + TORCH_API std::vector allPrivateUser1Types(); + + at::Tensor & unpack(Tensor & t, const char * name, int pos); + const at::Tensor & unpack(const Tensor & t, const char * name, int pos); + at::Tensor unpack_opt(const Tensor & t, const char * name, int pos); + std::vector unpack(const at::ITensorListRef& tl, const char *name, int pos); +} + +}} // namespace torch::autograd diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.cpp new file mode 100644 index 0000000000000000000000000000000000000000..11b9b194fb46f924e863c4c1dab5cbb8dbb0601b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.cpp @@ -0,0 +1,14 @@ +#include + +// ${generated_comment} + +using at::Tensor; +using at::Scalar; +using at::IntArrayRef; +using at::TensorList; + +namespace torch::autograd::generated { + +${view_func_definitions} + +} // namespace torch::autograd::generated diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.h new file mode 100644 index 0000000000000000000000000000000000000000..1f69c062d344e4cd5f98cf5f34fd4278019fdf8a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.h @@ -0,0 +1,28 @@ +#pragma once + +// ${generated_comment} + +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +$ops_headers +#endif + +namespace torch::autograd::generated { + +using at::Scalar; +using at::Tensor; +using at::IntArrayRef; +using at::ArrayRef; +using at::Type; +using at::ScalarType; +using std::optional; +using c10::fmap; + +${view_func_declarations} + +} // namespace torch::autograd::generated diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/annotated_fn_args.py.in b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/annotated_fn_args.py.in new file mode 100644 index 0000000000000000000000000000000000000000..1012c008451745b8f1ed1454a864f666caf2618a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/annotated_fn_args.py.in @@ -0,0 +1,11 @@ +""" +This file is needed for generating procedural tests required for +testing __torch_function__. See tests/test_overrides.py. +""" + +# flake8: noqa +import torch + +annotated_args = { +${annotated_args} +} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_enum_tag.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_enum_tag.cpp new file mode 100644 index 0000000000000000000000000000000000000000..83cfad1d7ba4d6fc3529caf78e036c5883e7bc23 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_enum_tag.cpp @@ -0,0 +1,15 @@ +#include +#include +#include +#include + +namespace py = pybind11; +namespace torch { + namespace autograd { + void initEnumTag(PyObject* module) { + auto m = py::handle(module).cast(); + py::enum_(m, "Tag") + ${enum_of_valid_tags}; + m.doc() = "An Enum that contains tags that can be assigned to an operator registered in C++."; + } +}} diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_fft_functions.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_fft_functions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..858a5071fdec05f4d7027e0874dfd7b0858feaf9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_fft_functions.cpp @@ -0,0 +1,79 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// ${generated_comment} + +#include "torch/csrc/Device.h" +#include "torch/csrc/DynamicTypes.h" +#include "torch/csrc/Exceptions.h" +#include "torch/csrc/autograd/python_fft_functions.h" +#include "torch/csrc/autograd/generated/python_return_types.h" +#include "torch/csrc/autograd/python_variable.h" +#include "torch/csrc/autograd/utils/wrap_outputs.h" +#include "torch/csrc/autograd/utils/python_arg_parsing.h" +#include "torch/csrc/autograd/generated/variable_factories.h" +#include "torch/csrc/utils/out_types.h" +#include "torch/csrc/utils/pycfunction_helpers.h" +#include "torch/csrc/utils/python_arg_parser.h" +#include "torch/csrc/utils/structseq.h" +#include "torch/csrc/utils/device_lazy_init.h" + +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +$ops_headers +#endif + +using at::Tensor; +using at::Device; +using at::Layout; +using at::Scalar; +using at::ScalarType; +using at::Backend; +using at::OptionalDeviceGuard; +using at::DeviceGuard; +using at::TensorOptions; +using at::IntArrayRef; +using at::Generator; +using at::TensorList; + +using torch::utils::check_out_type_matches; +using namespace torch::autograd::utils; + +namespace torch::autograd { + +// generated forward declarations start here + +${py_forwards} + +static PyMethodDef fft_functions[] = { + ${py_method_defs} + {NULL} +}; + +static PyObject* THPFFTVariableFunctionsModule = NULL; + +void initFFTFunctions(PyObject* module) { + static struct PyModuleDef def = { + PyModuleDef_HEAD_INIT, + "torch._C._fft", + NULL, + -1, + fft_functions + }; + PyObject* fft = PyModule_Create(&def); + THPFFTVariableFunctionsModule = fft; + if (!fft) { + throw python_error(); + } + // steals a reference to fft + if (PyModule_AddObject(module, "_fft", fft) != 0) { + throw python_error(); + } +} + +// generated methods start here + +${py_methods} + +} // namespace torch::autograd diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_functions.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_functions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1522d6cd0f5a2a1fc0188bf9d6d0d59fe1b27d85 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_functions.cpp @@ -0,0 +1,37 @@ +#include + +// ${generated_comment} + +#include +#include + +#include +#include "torch/csrc/autograd/generated/Functions.h" +#include "torch/csrc/autograd/python_cpp_function.h" +#include +#include +#include +#include +#include + +// NOTE: See [Sharded File] comment in VariableType + +namespace torch::autograd::generated { + +template +static void addClass(PyObject* module, PyTypeObject& type, const char* name, + PyGetSetDef* function_properties=NULL, PyMethodDef* function_methods=NULL) +{ + _initFunctionPyTypeObject(type, name, function_properties, function_methods); + Py_INCREF(&type); + PyModule_AddObject(module, name, (PyObject*)&type); + registerCppFunction(typeid(C), &type); +} + +${py_function_props_and_getters} + +void initialize_autogenerated_functions${shard_id}(PyObject* module) { + ${py_function_initializers} +} + +} // namespace torch::autograd::generated diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_functions.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..c63204a2cc853a4004057341e7cfc2250421525c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_functions.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +// ${generated_comment} + +// Python bindings for automatically generated autograd functions + +namespace torch::autograd::generated { + +${shard_forward_declare} + +inline void initialize_autogenerated_functions(PyObject* module) { + ${shard_call} +} + +} // namespace torch::autograd::generated diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_linalg_functions.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_linalg_functions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c93752a3ddbfcf111426f98c3ea68fc625e94def --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_linalg_functions.cpp @@ -0,0 +1,68 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// ${generated_comment} + +#include "torch/csrc/Device.h" +#include "torch/csrc/DynamicTypes.h" +#include "torch/csrc/Exceptions.h" +#include "torch/csrc/autograd/python_linalg_functions.h" +#include "torch/csrc/autograd/generated/python_return_types.h" +#include "torch/csrc/autograd/python_variable.h" +#include "torch/csrc/autograd/utils/wrap_outputs.h" +#include "torch/csrc/autograd/utils/python_arg_parsing.h" +#include "torch/csrc/utils/pycfunction_helpers.h" +#include "torch/csrc/utils/python_arg_parser.h" +#include "torch/csrc/utils/structseq.h" + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +$ops_headers +#endif + +using at::Tensor; +using at::Scalar; +using at::ScalarType; +using at::MemoryFormat; +using at::Generator; +using at::IntArrayRef; +using at::TensorList; + +using namespace torch::autograd::utils; + +namespace torch::autograd { + +// generated forward declarations start here + +${py_forwards} + +static PyMethodDef linalg_functions[] = { + ${py_method_defs} + {NULL} +}; + +static PyObject* THPLinalgVariableFunctionsModule = NULL; + +void initLinalgFunctions(PyObject* module) { + static struct PyModuleDef def = { + PyModuleDef_HEAD_INIT, + "torch._C._linalg", + NULL, + -1, + linalg_functions + }; + PyObject* linalg = PyModule_Create(&def); + THPLinalgVariableFunctionsModule = linalg; + if (!linalg) { + throw python_error(); + } + // steals a reference to linalg + if (PyModule_AddObject(module, "_linalg", linalg) != 0) { + throw python_error(); + } +} + +// generated methods start here + +${py_methods} + +} // namespace torch::autograd diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_nested_functions.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_nested_functions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f1dbf8d174f6838439ce6018a3e890b45f3bb52 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_nested_functions.cpp @@ -0,0 +1,79 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// ${generated_comment} + +#include "torch/csrc/Device.h" +#include "torch/csrc/DynamicTypes.h" +#include "torch/csrc/Exceptions.h" +#include "torch/csrc/autograd/python_nested_functions.h" +#include "torch/csrc/autograd/generated/python_return_types.h" +#include "torch/csrc/autograd/python_variable.h" +#include "torch/csrc/autograd/utils/wrap_outputs.h" +#include "torch/csrc/autograd/utils/python_arg_parsing.h" +#include "torch/csrc/autograd/generated/variable_factories.h" +#include "torch/csrc/utils/out_types.h" +#include "torch/csrc/utils/pycfunction_helpers.h" +#include "torch/csrc/utils/python_arg_parser.h" +#include "torch/csrc/utils/structseq.h" +#include "torch/csrc/utils/device_lazy_init.h" + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +$ops_headers +#endif + +using at::Tensor; +using at::Device; +using at::Layout; +using at::Scalar; +using at::ScalarType; +using at::Backend; +using at::OptionalDeviceGuard; +using at::DeviceGuard; +using at::TensorOptions; +using at::IntArrayRef; +using at::OptionalIntArrayRef; +using at::Generator; +using at::TensorList; + +using namespace torch::autograd::utils; + +namespace torch::autograd { + +// generated forward declarations start here + +${py_forwards} + +static PyMethodDef nested_functions[] = { + {NULL, NULL, 0, NULL}, + ${py_method_defs} + {NULL} +}; + +static PyObject* THPNestedVariableFunctionsModule = NULL; + +void initNestedFunctions(PyObject* module) { + nested_functions[0] = get_nested_functions_manual()[0]; + static struct PyModuleDef def = { + PyModuleDef_HEAD_INIT, + "torch._C._nested", + NULL, + -1, + nested_functions + }; + PyObject* nested = PyModule_Create(&def); + THPNestedVariableFunctionsModule = nested; + if (!nested) { + throw python_error(); + } + // steals a reference to nested + if (PyModule_AddObject(module, "_nested", nested) != 0) { + throw python_error(); + } +} + +// generated methods start here + +${py_methods} + +} // namespace torch::autograd diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_nn_functions.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_nn_functions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8eabb0da2332283a02e98e54dd0a277a83a55ad6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_nn_functions.cpp @@ -0,0 +1,113 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// ${generated_comment} + +#include "torch/csrc/Device.h" +#include "torch/csrc/DynamicTypes.h" +#include "torch/csrc/Exceptions.h" +#include "torch/csrc/autograd/python_nn_functions.h" +#include "torch/csrc/autograd/generated/python_return_types.h" +#include "torch/csrc/autograd/python_variable.h" +#include "torch/csrc/autograd/utils/wrap_outputs.h" +#include "torch/csrc/autograd/utils/python_arg_parsing.h" +#include "torch/csrc/utils/pycfunction_helpers.h" +#include "torch/csrc/utils/python_arg_parser.h" +#include "torch/csrc/utils/structseq.h" +#include "torch/csrc/utils/tensor_memoryformats.h" + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +$ops_headers +#endif + +using at::Tensor; +using at::Scalar; +using at::MemoryFormat; +using at::Generator; +using at::IntArrayRef; +using at::ArrayRef; + +using namespace torch::autograd::utils; + +namespace torch::autograd { + +static PyObject* THPNNVariableFunctionsModule = nullptr; + +static PyObject * THPVariable__parse_to(PyObject* module, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "to(Device device=None, ScalarType dtype=None, bool non_blocking=False, bool copy=False, *, MemoryFormat? memory_format=None)", + "to(ScalarType dtype, bool non_blocking=False, bool copy=False, *, MemoryFormat? memory_format=None)", + "to(Tensor tensor, bool non_blocking=False, bool copy=False, *, MemoryFormat? memory_format=None)", + }); + ParsedArgs<5> parsed_args; + auto r = parser.parse(args, kwargs, parsed_args); + if (r.has_torch_function()) { + return handle_torch_function(r, args, kwargs, THPNNVariableFunctionsModule, "torch.nn", "_parse_to"); + } + auto parsed = parse_to_conversion(r, /*allow_copy*/ false); // we don't want copy for nn.Module.to + auto& device = std::get<0>(parsed); + auto& scalarType = std::get<1>(parsed); + auto non_blocking = std::get<2>(parsed); + auto opt_memory_format = std::get<4>(parsed); + auto tuple = THPObjectPtr{PyTuple_New(4)}; + if (!tuple) throw python_error(); + if (device) { + PyTuple_SET_ITEM(tuple.get(), 0, THPDevice_New(*device)); + } else { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(tuple.get(), 0, Py_None); + } + if (scalarType) { + PyTuple_SET_ITEM(tuple.get(), 1, Py_NewRef(torch::getTHPDtype(*scalarType))); + } else { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(tuple.get(), 1, Py_None); + } + PyTuple_SET_ITEM(tuple.get(), 2, torch::autograd::utils::wrap(non_blocking)); + if (opt_memory_format.has_value()) { + PyTuple_SET_ITEM(tuple.get(), 3, Py_NewRef(torch::utils::getTHPMemoryFormat(opt_memory_format.value()))); + } else { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(tuple.get(), 3, Py_None); + } + return tuple.release(); + END_HANDLE_TH_ERRORS +} + +// generated forward declarations start here + +${py_forwards} + +static PyMethodDef nn_functions[] = { + {"_parse_to", castPyCFunctionWithKeywords(THPVariable__parse_to), + METH_VARARGS | METH_KEYWORDS, nullptr}, + ${py_method_defs} + {nullptr} +}; + +void initNNFunctions(PyObject* module) { + static struct PyModuleDef def = { + PyModuleDef_HEAD_INIT, + "torch._C._nn", + nullptr, + -1, + nn_functions + }; + PyObject* nn = PyModule_Create(&def); + THPNNVariableFunctionsModule = nn; + if (!nn) { + throw python_error(); + } + // steals a reference to nn + if (PyModule_AddObject(module, "_nn", nn) != 0) { + throw python_error(); + } +} + +// generated methods start here + +${py_methods} + +} // namespace torch::autograd diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_return_types.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_return_types.cpp new file mode 100644 index 0000000000000000000000000000000000000000..736cccb7c7130beefabe256ee2063bd857daa64e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_return_types.cpp @@ -0,0 +1,52 @@ +#include + +#include +#include +#include + +#include "torch/csrc/autograd/generated/python_return_types.h" +#include "torch/csrc/utils/structseq.h" +#include "torch/csrc/Exceptions.h" + +namespace torch::autograd::generated { + +${py_return_types} + +} // namespace torch::autograd::generated + +namespace torch::autograd { + +static void addReturnType( + PyObject* module, + const char* name, + PyTypeObject* type) { + // hold onto the TypeObject for the unlikely case of user + // deleting or overriding it. + Py_INCREF(type); + if (PyModule_AddObject( + module, + name, + (PyObject*)type) != 0) { + Py_DECREF(type); + throw python_error(); + } +} + +void initReturnTypes(PyObject* module) { + static struct PyModuleDef def = { + PyModuleDef_HEAD_INIT, "torch._C._return_types", nullptr, -1, {}}; + PyObject* return_types_module = PyModule_Create(&def); + if (!return_types_module) { + throw python_error(); + } + + ${py_return_types_registrations} + + // steals a reference to return_types on success + if (PyModule_AddObject(module, "_return_types", return_types_module) != 0) { + Py_DECREF(return_types_module); + throw python_error(); + } +} + +} // namespace torch::autograd diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_return_types.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_return_types.h new file mode 100644 index 0000000000000000000000000000000000000000..ce6c355ea146a272709255b898603764112168b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_return_types.h @@ -0,0 +1,14 @@ +#pragma once + +namespace torch { +namespace autograd { +namespace generated { + +${py_return_types_declarations} + +} + +void initReturnTypes(PyObject* module); + +} // namespace autograd +} // namespace torch diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_sparse_functions.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_sparse_functions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..648d91442102e9b950cb2ddb8db545c4b4e1100e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_sparse_functions.cpp @@ -0,0 +1,67 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// ${generated_comment} + +#include "torch/csrc/Device.h" +#include "torch/csrc/DynamicTypes.h" +#include "torch/csrc/Exceptions.h" +#include "torch/csrc/autograd/python_sparse_functions.h" +#include "torch/csrc/autograd/python_variable.h" +#include "torch/csrc/autograd/utils/wrap_outputs.h" +#include "torch/csrc/autograd/utils/python_arg_parsing.h" +#include "torch/csrc/utils/pycfunction_helpers.h" +#include "torch/csrc/utils/python_arg_parser.h" +#include "torch/csrc/utils/structseq.h" + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +$ops_headers +#endif + +using at::Tensor; +using at::Scalar; +using at::ScalarType; +using at::MemoryFormat; +using at::Generator; +using at::IntArrayRef; +using at::TensorList; + +using namespace torch::autograd::utils; + +namespace torch::autograd { + +// generated forward declarations start here + +${py_forwards} + +static PyMethodDef sparse_functions[] = { + ${py_method_defs} + {NULL} +}; + +static PyObject* THPSparseVariableFunctionsModule = NULL; + +void initSparseFunctions(PyObject* module) { + static struct PyModuleDef def = { + PyModuleDef_HEAD_INIT, + "torch._C._sparse", + NULL, + -1, + sparse_functions + }; + PyObject* sparse = PyModule_Create(&def); + THPSparseVariableFunctionsModule = sparse; + if (!sparse) { + throw python_error(); + } + // steals a reference to sparse + if (PyModule_AddObject(module, "_sparse", sparse) != 0) { + throw python_error(); + } +} + +// generated methods start here + +${py_methods} + +} // namespace torch::autograd diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_special_functions.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_special_functions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..698583e732a2f740ac6874f1a07f3fca7c56bcc0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_special_functions.cpp @@ -0,0 +1,77 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// ${generated_comment} + +#include "torch/csrc/Device.h" +#include "torch/csrc/DynamicTypes.h" +#include "torch/csrc/Exceptions.h" +#include "torch/csrc/autograd/python_special_functions.h" +#include "torch/csrc/autograd/generated/python_return_types.h" +#include "torch/csrc/autograd/python_variable.h" +#include "torch/csrc/autograd/utils/wrap_outputs.h" +#include "torch/csrc/autograd/utils/python_arg_parsing.h" +#include "torch/csrc/autograd/generated/variable_factories.h" +#include "torch/csrc/utils/out_types.h" +#include "torch/csrc/utils/pycfunction_helpers.h" +#include "torch/csrc/utils/python_arg_parser.h" +#include "torch/csrc/utils/structseq.h" +#include "torch/csrc/utils/device_lazy_init.h" + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +$ops_headers +#endif + +using at::Tensor; +using at::Device; +using at::Layout; +using at::Scalar; +using at::ScalarType; +using at::Backend; +using at::OptionalDeviceGuard; +using at::DeviceGuard; +using at::TensorOptions; +using at::IntArrayRef; +using at::Generator; +using at::TensorList; + +using torch::utils::check_out_type_matches; +using namespace torch::autograd::utils; + +namespace torch::autograd { + +// generated forward declarations start here + +${py_forwards} + +static PyMethodDef special_functions[] = { + ${py_method_defs} + {NULL} +}; + +static PyObject* THPSpecialVariableFunctionsModule = NULL; + +void initSpecialFunctions(PyObject* module) { + static struct PyModuleDef def = { + PyModuleDef_HEAD_INIT, + "torch._C._special", + NULL, + -1, + special_functions + }; + PyObject* special = PyModule_Create(&def); + THPSpecialVariableFunctionsModule = special; + if (!special) { + throw python_error(); + } + // steals a reference to special + if (PyModule_AddObject(module, "_special", special) != 0) { + throw python_error(); + } +} + +// generated methods start here + +${py_methods} + +} // namespace torch::autograd diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_torch_functions.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_torch_functions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c4228d231e734675704bd989c5205233f32f76d2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_torch_functions.cpp @@ -0,0 +1,91 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// ${generated_comment} + +// Python bindings for torch.* functions implemented through ATen. +// +// The functions are bound as static methods on a class +// torch._C._VariableFunctions which is also aliased as Variable._torch +// and also copied into 'torch' module. + +#include + +// Undefine the copysign macro so that at::copysign works as intended with MSVC +// https://github.com/python/cpython/blob/c60394c7fc9cc09b16e9675a3eeb5844b6d8523f/PC/pyconfig.h#L196 +#ifdef _MSC_VER +#undef copysign +#endif // _MSC_VER + +#include "torch/csrc/autograd/python_torch_functions.h" +#include "torch/csrc/autograd/python_variable.h" +#include "torch/csrc/autograd/utils/wrap_outputs.h" +#include "torch/csrc/Dtype.h" +#include "torch/csrc/DynamicTypes.h" +#include "torch/csrc/Exceptions.h" +#include "torch/csrc/utils/out_types.h" +#include "torch/csrc/utils/pybind.h" +#include "torch/csrc/utils/pycfunction_helpers.h" +#include "torch/csrc/utils/python_arg_parser.h" +#include "torch/csrc/utils/tensor_layouts.h" +#include "torch/csrc/utils/tensor_new.h" +#include "torch/csrc/utils/tensor_numpy.h" +#include "torch/csrc/jit/frontend/tracer.h" +#include "torch/csrc/autograd/generated/variable_factories.h" +#include "torch/csrc/utils/structseq.h" +#include "torch/csrc/utils/device_lazy_init.h" +#include "torch/csrc/autograd/generated/python_return_types.h" + +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +$ops_headers +#endif + +#include +#include +#include +#include + +using at::Tensor; +using at::Device; +using at::Layout; +using at::Scalar; +using at::ScalarType; +using at::Backend; +using at::OptionalDeviceGuard; +using at::DeviceGuard; +using at::TensorOptions; +using at::IntArrayRef; +using at::Generator; +using at::TensorList; +using at::ArrayRef; + +using torch::utils::check_out_type_matches; +using namespace torch::autograd::utils; + +// NOTE: See [Sharded File] comment in VariableType + +namespace torch::autograd { + +// generated forward declarations start here + +${py_forwards} + +static PyMethodDef torch_functions_shard[] = { + ${py_method_defs} +}; + +void gatherTorchFunctions${shard_id}(std::vector &torch_functions) { + constexpr size_t num_functions = sizeof(torch_functions_shard) / sizeof(torch_functions_shard[0]); + torch_functions.insert( + torch_functions.end(), + torch_functions_shard, + torch_functions_shard + num_functions); +} + +// generated methods start here + +${py_methods} + +} // namespace torch::autograd diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_variable_methods.cpp b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_variable_methods.cpp new file mode 100644 index 0000000000000000000000000000000000000000..35a6a7d6f721bcb68bacf2ba9415cc021c8a7b5a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/python_variable_methods.cpp @@ -0,0 +1,1327 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +// ${generated_comment} + +#include + +// Undefine the copysign macro so that at::copysign works as intended with MSVC +// https://github.com/python/cpython/blob/c60394c7fc9cc09b16e9675a3eeb5844b6d8523f/PC/pyconfig.h#L196 +#ifdef _MSC_VER +#undef copysign +#endif // _MSC_VER + +#include "torch/csrc/DynamicTypes.h" +#include "torch/csrc/Exceptions.h" +#include "torch/csrc/Size.h" +#include "torch/csrc/autograd/generated/VariableType.h" +#include "torch/csrc/autograd/python_variable.h" +#include "torch/csrc/autograd/utils/python_arg_parsing.h" +#include "torch/csrc/autograd/utils/error_messages.h" +#include "torch/csrc/autograd/utils/wrap_outputs.h" +#include "torch/csrc/jit/frontend/tracer.h" +#ifdef USE_CUDA +#include "torch/csrc/cuda/Event.h" +#endif +#include "torch/csrc/utils/device_lazy_init.h" +#include +#include "torch/csrc/utils/object_ptr.h" +#include "torch/csrc/utils/pycfunction_helpers.h" +#include "torch/csrc/utils/python_arg_parser.h" +#include "torch/csrc/utils/python_numbers.h" +#include "torch/csrc/utils/python_strings.h" +#include "torch/csrc/utils/tensor_apply.h" +#include "torch/csrc/utils/tensor_list.h" +#include "torch/csrc/utils/tensor_new.h" +#include "torch/csrc/utils/tensor_numpy.h" +#include "torch/csrc/utils/tensor_types.h" +#include "torch/csrc/autograd/generated/python_return_types.h" + +#include +#include +#include +#include +#include "c10/core/Stream.h" + +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +$ops_headers +#include +#endif + +using at::device_of; +using at::OptionalDeviceGuard; +using at::Scalar; +using at::ScalarType; +using at::Tensor; +using c10::Stream; +using namespace torch::autograd::utils; + +namespace torch::autograd { + +static PyObject * THPVariable__is_view(PyObject *self, PyObject* args) +{ + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + return handle_torch_function(self, "_is_view", args); + } + auto& self_ = THPVariable_Unpack(self); + if (self_.is_view()) { + Py_RETURN_TRUE; + } else { + Py_RETURN_FALSE; + } + END_HANDLE_TH_ERRORS +} + +// implemented on the python object bc no support for first-class functions in native_functions.yaml +// See: ATen/native/README.md for more context +static PyObject * THPVariable_apply_(PyObject* self, PyObject* arg) +{ + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + auto args = py::make_tuple(py::handle(arg)); + return handle_torch_function(self, "apply_", args.ptr()); + } + auto& self_ = THPVariable_Unpack(self); + if (self_.requires_grad()) { + throw std::runtime_error( + "Can't call apply_() on Variable that requires grad. Use " + "var.detach().apply_() instead."); + } + return THPVariable_Wrap(torch::utils::apply_(self_, arg)); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_size(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "size(int64_t? dim=None)", + }); + auto& self_ = THPVariable_Unpack(self); + ParsedArgs<3> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + if (!r.toInt64Optional(0).has_value()) { + return THPSize_NewFromSymSizes(self_); + } + if (jit::tracer::isTracing()) { + // will error out if a tensor has symints + return wrap(jit::tracer::getSizeOf(self_, r.toInt64(0))); + } else { + return torch::toPyObject(self_.sym_size(r.toInt64(0))); + } + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_stride(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "stride(int64_t? dim=None)", + }); + auto& self_ = THPVariable_Unpack(self); + ParsedArgs<3> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + if (r.toInt64Optional(0).has_value()) { + return torch::toPyObject(self_.sym_stride(r.toInt64(0))); + } + // yes, this is called strides in ATen. + at::SymIntArrayRef strides = self_.sym_strides(); + // we can't do the normal wrapping here because IntArrayRef maps to both + // torch.Size and tuple in python + // TODO: consider factoring this out + THPObjectPtr tuple(PyTuple_New(static_cast(strides.size()))); + if (!tuple) throw python_error(); + for (size_t i = 0; i != strides.size(); i++) { + PyObject* s = torch::toPyObject(strides[i]); + if (!s) throw python_error(); + PyTuple_SET_ITEM(tuple.get(), i, s); + } + return tuple.release(); + END_HANDLE_TH_ERRORS +} + +// implemented on the python object to avoid dispatch overhead +static PyObject * THPVariable_get_device(PyObject* self_, PyObject* args) +{ + HANDLE_TH_ERRORS + if (has_torch_function(self_)) { + return handle_torch_function(self_, "get_device", args, nullptr); + } + auto& self = THPVariable_Unpack(self_); + return wrap(self.get_device()); + END_HANDLE_TH_ERRORS +} + +// implemented on the python object to avoid dispatch overhead +static PyObject * THPVariable_data_ptr(PyObject* self_, PyObject* args) +{ + HANDLE_TH_ERRORS + if (has_torch_function(self_)) { + return handle_torch_function(self_, "data_ptr", args); + } + auto& self = THPVariable_Unpack(self_); + return wrap(self.data_ptr()); + END_HANDLE_TH_ERRORS +} + +// implemented on the python object to avoid dispatch overhead +// Unlike data_ptr(), this is a read-only access that does not trigger +// copy-on-write materialization. +static PyObject * THPVariable_const_data_ptr(PyObject* self_, PyObject* args) +{ + HANDLE_TH_ERRORS + if (check_has_torch_function(self_)) { + return handle_torch_function(self_, "const_data_ptr", args); + } + auto& self = THPVariable_Unpack(self_); + return wrap(const_cast(self.const_data_ptr())); + END_HANDLE_TH_ERRORS +} + +// implemented on the python object to avoid dispatch overhead +static PyObject * THPVariable_storage_offset(PyObject* self_, PyObject* args) +{ + HANDLE_TH_ERRORS + if (has_torch_function(self_)) { + return handle_torch_function(self_, "storage_offset"); + } + auto& self = THPVariable_Unpack(self_); + return py::cast(self.sym_storage_offset()).release().ptr(); + END_HANDLE_TH_ERRORS +} + +// implemented on the python object to avoid dispatch overhead +static PyObject * THPVariable_dim(PyObject* self, PyObject* args) +{ + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + return handle_torch_function(self, "dim", args); + } + auto& self_ = THPVariable_Unpack(self); + return THPUtils_packInt64(self_.dim()); + END_HANDLE_TH_ERRORS +} + +// implemented on the python object to avoid dispatch overhead +static PyObject * THPVariable_numel(PyObject* self, PyObject* args) +{ + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + return handle_torch_function(self, "numel", args); + } + auto& self_ = THPVariable_Unpack(self); + if (jit::tracer::isTracing()) { + return wrap(jit::tracer::getNumelOf(self_)); + } else { + return py::cast(self_.sym_numel()).release().ptr(); + } + END_HANDLE_TH_ERRORS +} + +static Tensor dispatch_contiguous(const Tensor & self, at::MemoryFormat memory_format) { + pybind11::gil_scoped_release no_gil; + OptionalDeviceGuard device_guard(device_of(self)); + return self.contiguous(memory_format); +} + +static PyObject * THPVariable_contiguous(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "contiguous(*, MemoryFormat memory_format=contiguous_format)", + }); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto& self_ = THPVariable_Unpack(self); + auto memory_format = r.memoryformat(0); + // avoids touching the GIL or current device if self is already contiguous + if (self_.is_contiguous_or_false(memory_format)) { + // NOTE: this logic is duplicated from VariableType.cpp. Since we need to + // record this call to contiguous() in the trace regardless of whether + // we actually call contiguous here, we need to record this information + // manually. + if (jit::tracer::isTracing()) { + const auto& tracer_state = jit::tracer::getTracingState(); + auto op_name = c10::Symbol::fromQualString("aten::contiguous"); + auto node = tracer_state->createNode(op_name, /*num_outputs=*/0); + jit::tracer::recordSourceLocation(node); + jit::tracer::addInputs(node, "self", self_); + jit::tracer::addInputs(node, "memory_format", memory_format); + tracer_state->insertNode(node); + jit::tracer::addOutput(node, self_); + } + Py_INCREF(self); + return self; + } + return THPVariable_Wrap(dispatch_contiguous(self_, memory_format)); + END_HANDLE_TH_ERRORS +} + +static Tensor dispatch_copy_(const Tensor & self, const Tensor & other, bool non_blocking) { + pybind11::gil_scoped_release no_gil; + OptionalDeviceGuard device_guard(device_of(self)); + return self.copy_(other, non_blocking); +} + +static void maybe_warn_requires_grad(const Tensor & self) { + if (at::GradMode::is_enabled() && self.requires_grad()) { + TORCH_WARN_ONCE("Converting a tensor with requires_grad=True to a scalar may lead to unexpected behavior.\n" + "Consider using tensor.detach() first."); + } +} + + static PyObject * THPVariable_copy_(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "copy_(Tensor other, bool non_blocking=False)", + "copy_(Tensor other, bool async=False)|deprecated" + }); + auto& self_ = THPVariable_Unpack(self); + ParsedArgs<2> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + return THPVariable_Wrap(dispatch_copy_(self_, r.tensor(0), r.toBool(1))); + END_HANDLE_TH_ERRORS +} + +template +static T dispatch_to(const Tensor & self) { + pybind11::gil_scoped_release no_gil; + OptionalDeviceGuard device_guard(device_of(self)); + TORCH_CHECK_VALUE(self.sym_numel() == 1, "only one element tensors can be converted to Python scalars"); + return self.template item(); +} + +static PyObject * THPVariable_float_scalar(PyObject* self, PyObject* args) { + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + return handle_torch_function(self, "__float__", args); + } + jit::tracer::warn("Converting a tensor to a Python float", jit::tracer::WARN_PYTHON_DATAFLOW); + auto& self_ = THPVariable_Unpack(self); + maybe_warn_requires_grad(self_); + return wrap(dispatch_to(self_)); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_complex_scalar(PyObject* self, PyObject* args) { + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + return handle_torch_function(self, "__complex__", args); + } + jit::tracer::warn("Converting a tensor to a Python complex", jit::tracer::WARN_PYTHON_DATAFLOW); + auto& self_ = THPVariable_Unpack(self); + maybe_warn_requires_grad(self_); + return wrap(dispatch_to>(self_)); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_integral_scalar(PyObject* self, PyObject* args) { + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + return handle_torch_function(self, "__int__", args); + } + jit::tracer::warn("Converting a tensor to a Python integer", jit::tracer::WARN_PYTHON_DATAFLOW); + auto& self_ = THPVariable_Unpack(self); + if (isFloatingType(self_.scalar_type())) { + // we can't dispatch to item here because we want to avoid ATen overflow checks; + // the python integral type (long in python2) can't overflow. + return THPUtils_packDoubleAsInt(dispatch_to(self_)); + } else { + return wrap(dispatch_to(self_)); + } + END_HANDLE_TH_ERRORS +} + +// This is the __index__ function in Python which is similar to __int__, but +// called when used as a slice. +static PyObject * THPVariable_index_scalar(PyObject* self, PyObject* args) { + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + return handle_torch_function(self, "__index__", args); + } + auto& self_ = THPVariable_Unpack(self); + // TODO: change the condition to `self_.dim() != 0` once we expose scalars + // in PyTorch. + if (!isIntegralType(self_.scalar_type(), /*includeBool=*/true) || self_.sym_numel() != 1) { + throw TypeError("only integer tensors of a single element can be converted to an index"); + } + return wrap(dispatch_to(self_)); + END_HANDLE_TH_ERRORS +} + +static Tensor dispatch_invert(const Tensor & self) { + pybind11::gil_scoped_release no_gil; + OptionalDeviceGuard device_guard(device_of(self)); + return self.bitwise_not(); +} + +static PyObject * THPVariable_invert(PyObject* self, PyObject* args) { + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + return handle_torch_function(self, "__invert__", args); + } + auto& self_ = THPVariable_Unpack(self); + if (!isIntegralType(self_.scalar_type(), /*includeBool=*/true)) { + throw TypeError("~ (operator.invert) is only implemented on integer and Boolean-type tensors"); + } + return THPVariable_Wrap(dispatch_invert(self_)); + END_HANDLE_TH_ERRORS +} + +static Tensor dispatch_to(const Tensor & self, Device device, bool non_blocking, bool copy, std::optional optional_memory_format) { + pybind11::gil_scoped_release no_gil; + // NOTE: this is where we record aten::to in the graph during tracing. However, the behavior of aten::to + // is different with respect to TensorOptions fields that are not present: aten::to inherits fields that + // are missing from the self argument while the tracer assumes that they should be populated with the + // default values (eg. float for scalar type). By explicitly copying over the tensor options here we fully + // specify all tensor options and thus record the proper trace + return self.to(self.options().device(device).memory_format(optional_memory_format), non_blocking, copy); +} + +static Tensor dispatch_to(const Tensor & self, bool non_blocking, bool copy, std::optional optional_memory_format) { + pybind11::gil_scoped_release no_gil; + return self.to(self.options().memory_format(optional_memory_format), non_blocking, copy); +} + +static Tensor dispatch_to(const Tensor & self, ScalarType dtype, bool non_blocking, bool copy, std::optional optional_memory_format) { + pybind11::gil_scoped_release no_gil; + // TODO: Make this call the TensorOptions version, maybe? + return self.to(dtype, non_blocking, copy, optional_memory_format); +} + +static Tensor dispatch_to(const Tensor & self, Device device, ScalarType dtype, bool non_blocking, bool copy, std::optional optional_memory_format) { + pybind11::gil_scoped_release no_gil; + // TODO: Make this call the TensorOptions version, maybe? + return self.to(device, dtype, non_blocking, copy, optional_memory_format); +} + +static PyObject * THPVariable_cpu(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "cpu(*, MemoryFormat? memory_format=None)" + }); + auto& self_ = THPVariable_Unpack(self); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto opt_memory_format = r.memoryformatOptional(0); + return THPVariable_Wrap(dispatch_to(self_, at::Device(at::DeviceType::CPU), false, false, opt_memory_format)); + END_HANDLE_TH_ERRORS +} + +static Tensor dispatch_nonzero(const Tensor & self) { + pybind11::gil_scoped_release no_gil; + OptionalDeviceGuard device_guard(device_of(self)); + return self.nonzero(); +} + +static std::vector dispatch_nonzero_numpy(const Tensor & self) { + pybind11::gil_scoped_release no_gil; + OptionalDeviceGuard device_guard(device_of(self)); + return self.nonzero_numpy(); +} + +static PyObject * THPVariable_nonzero(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "nonzero()", + "nonzero(*, bool as_tuple)", + }); + auto& self_ = THPVariable_Unpack(self); + ParsedArgs<2> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + if (r.idx == 0 || (r.idx == 1 && !r.toBool(0))) { + return wrap(dispatch_nonzero(self_)); + } else { + return wrap(dispatch_nonzero_numpy(self_)); + } + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_cuda(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "cuda(Device? device=None, bool non_blocking=False, *, MemoryFormat? memory_format=None)", + "cuda(Device? device=None, bool async=False, *, MemoryFormat? memory_format=None)|deprecated" + }); + auto& self_ = THPVariable_Unpack(self); + ParsedArgs<3> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto device = r.isNone(0) ? at::Device(at::DeviceType::CUDA) : r.device(0); + auto opt_memory_format = r.memoryformatOptional(2); + TORCH_CHECK(device.is_cuda(), "Invalid device, must be cuda device"); + torch::utils::device_lazy_init(at::kCUDA); + return THPVariable_Wrap(dispatch_to(self_, device, r.toBool(1), false, opt_memory_format)); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_mtia(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "mtia(Device? device=None, bool non_blocking=False, *, MemoryFormat? memory_format=None)", + "mtia(Device? device=None, bool async=False, *, MemoryFormat? memory_format=None)|deprecated" + }); + auto& self_ = THPVariable_Unpack(self); + ParsedArgs<3> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if (r.has_torch_function()) { + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto device = r.isNone(0) ? at::Device(at::DeviceType::MTIA) : r.device(0); + auto opt_memory_format = r.memoryformatOptional(2); + TORCH_CHECK(device.is_mtia(), "Invalid device, must be MTIA device"); + torch::utils::device_lazy_init(at::kMTIA); + return THPVariable_Wrap(dispatch_to(self_, device, r.toBool(1), false, opt_memory_format)); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_xpu(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "xpu(Device? device=None, bool non_blocking=False, *, MemoryFormat? memory_format=None)", + "xpu(Device? device=None, bool async=False, *, MemoryFormat? memory_format=None)|deprecated" + }); + auto& self_ = THPVariable_Unpack(self); + ParsedArgs<3> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if (r.has_torch_function()) { + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto device = r.isNone(0) ? at::Device(at::DeviceType::XPU) : r.device(0); + auto opt_memory_format = r.memoryformatOptional(2); + TORCH_CHECK(device.is_xpu(), "Invalid device, must be xpu device"); + torch::utils::device_lazy_init(at::kXPU); + return THPVariable_Wrap(dispatch_to(self_, device, r.toBool(1), false, opt_memory_format)); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_ipu(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "ipu(Device? device=None, bool non_blocking=False, *, MemoryFormat? memory_format=None)", + "ipu(Device? device=None, bool async=False, *, MemoryFormat? memory_format=None)|deprecated" + }); + auto& self_ = THPVariable_Unpack(self); + ParsedArgs<3> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if (r.has_torch_function()) { + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto device = r.isNone(0) ? at::Device(at::DeviceType::IPU) : r.device(0); + auto opt_memory_format = r.memoryformatOptional(2); + TORCH_CHECK(device.is_ipu(), "Invalid device, must be ipu device"); + return THPVariable_Wrap(dispatch_to(self_, device, r.toBool(1), false, opt_memory_format)); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_to_type(PyObject* self, ScalarType scalarType, std::optional optional_memory_format) { + HANDLE_TH_ERRORS + auto& self_ = THPVariable_Unpack(self); + return THPVariable_Wrap(dispatch_to(self_, scalarType, false, false, optional_memory_format)); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_byte(PyObject* self, PyObject* args, PyObject* kwargs) { + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "byte(*, MemoryFormat? memory_format=None)" + }); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto opt_memory_format = r.memoryformatOptional(0); + return THPVariable_to_type(self, ScalarType::Byte, opt_memory_format); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_char(PyObject* self, PyObject* args, PyObject* kwargs) { + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "char(*, MemoryFormat? memory_format=None)" + }); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto opt_memory_format = r.memoryformatOptional(0); + return THPVariable_to_type(self, ScalarType::Char, opt_memory_format); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_double(PyObject* self, PyObject* args, PyObject* kwargs) { + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "double(*, MemoryFormat? memory_format=None)" + }); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto opt_memory_format = r.memoryformatOptional(0); + return THPVariable_to_type(self, ScalarType::Double, opt_memory_format); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_float(PyObject* self, PyObject* args, PyObject* kwargs) { + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "float(*, MemoryFormat? memory_format=None)" + }); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto opt_memory_format = r.memoryformatOptional(0); + return THPVariable_to_type(self, ScalarType::Float, opt_memory_format); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_cdouble(PyObject* self, PyObject* args, PyObject* kwargs) { + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "cdouble(*, MemoryFormat? memory_format=None)" + }); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto opt_memory_format = r.memoryformatOptional(0); + return THPVariable_to_type(self, ScalarType::ComplexDouble, opt_memory_format); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_cfloat(PyObject* self, PyObject* args, PyObject* kwargs) { + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "cfloat(*, MemoryFormat? memory_format=None)" + }); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto opt_memory_format = r.memoryformatOptional(0); + return THPVariable_to_type(self, ScalarType::ComplexFloat, opt_memory_format); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_half(PyObject* self, PyObject* args, PyObject* kwargs) { + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "half(*, MemoryFormat? memory_format=None)" + }); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto opt_memory_format = r.memoryformatOptional(0); + return THPVariable_to_type(self, ScalarType::Half, opt_memory_format); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_int(PyObject* self, PyObject* args, PyObject* kwargs) { + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "int(*, MemoryFormat? memory_format=None)" + }); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto opt_memory_format = r.memoryformatOptional(0); + return THPVariable_to_type(self, ScalarType::Int, opt_memory_format); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_long(PyObject* self, PyObject* args, PyObject* kwargs) { + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "long(*, MemoryFormat? memory_format=None)" + }); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto opt_memory_format = r.memoryformatOptional(0); + return THPVariable_to_type(self, ScalarType::Long, opt_memory_format); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_short(PyObject* self, PyObject* args, PyObject* kwargs) { + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "short(*, MemoryFormat? memory_format=None)" + }); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto opt_memory_format = r.memoryformatOptional(0); + return THPVariable_to_type(self, ScalarType::Short, opt_memory_format); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_bool(PyObject* self, PyObject* args, PyObject* kwargs) { + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "bool(*, MemoryFormat? memory_format=None)" + }); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto opt_memory_format = r.memoryformatOptional(0); + return THPVariable_to_type(self, ScalarType::Bool, opt_memory_format); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_bfloat16(PyObject* self, PyObject* args, PyObject* kwargs) { + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "bfloat16(*, MemoryFormat? memory_format=None)" + }); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + auto opt_memory_format = r.memoryformatOptional(0); + return THPVariable_to_type(self, ScalarType::BFloat16, opt_memory_format); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_element_size(PyObject* self, PyObject* args) +{ + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + return handle_torch_function(self, "element_size", args); + } + auto& self_ = THPVariable_Unpack(self); + return THPUtils_packInt64(self_.element_size()); + END_HANDLE_TH_ERRORS +} + +// implemented on the python object bc PyObjects not declarable in native_functions.yaml +// See: ATen/native/README.md for more context +static PyObject * THPVariable_numpy(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "numpy(*, bool force=False)" + }); + auto& self_ = THPVariable_Unpack(self); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if (r.has_torch_function()) { + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + jit::tracer::warn("Converting a tensor to a NumPy array", jit::tracer::WARN_PYTHON_DATAFLOW); + return torch::utils::tensor_to_numpy(self_, r.toBool(0)); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_requires_grad_(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "requires_grad_(bool requires_grad=True)", + }); + auto& self_ = THPVariable_Unpack(self); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + // temporary hack to improve functorch UX. + const auto& functorch_tls = at::functorch::functorchTLSAccessor(); + if (functorch_tls) { + functorch_tls->checkSupportsInplaceRequiresGrad(); + } + + auto requires_grad = r.toBool(0); + // should we throw if requires_grad is true? var.requires_grad = True throws here + // but it's nice to let this be a no-op. + if (!self_.is_leaf() && !requires_grad) { + throw std::runtime_error(autograd::utils::requires_grad_leaf_error(requires_grad)); + } + if (requires_grad && ! isDifferentiableType(at::typeMetaToScalarType(self_.dtype()))) { + throw std::runtime_error("only Tensors of floating point dtype can require gradients"); + } + self_.set_requires_grad(requires_grad); + return THPVariable_Wrap(self_); + END_HANDLE_TH_ERRORS +} + +static inline bool dispatch_is_contiguous(const Tensor & self, MemoryFormat memory_format) { + return self.is_contiguous(memory_format); +} + +// implemented on the python object to avoid dispatch overhead +static PyObject * THPVariable_is_contiguous(PyObject* self_, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "is_contiguous(*, MemoryFormat memory_format=contiguous_format)", + }); + ParsedArgs<1> parsed_args; + auto r = parser.parse(self_, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self_, args, kwargs, reinterpret_cast(Py_TYPE(self_)), "torch.Tensor"); + } + + auto memory_format = r.memoryformat(0); + auto& self = THPVariable_Unpack(self_); + return wrap(dispatch_is_contiguous(self, memory_format)); + END_HANDLE_TH_ERRORS +} + +// implemented on the python object to avoid dispatch overhead +static PyObject * THPVariable_item(PyObject* self, PyObject* args) +{ + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + return handle_torch_function(self, "item", args); + } + jit::tracer::warn("Converting a tensor to a Python number", jit::tracer::WARN_PYTHON_DATAFLOW); + auto& self_ = THPVariable_Unpack(self); + auto dispatch_item_ = [](const Tensor& self) -> at::Scalar { + pybind11::gil_scoped_release no_gil; + return self.item(); + }; + return py::cast(dispatch_item_(self_)).release().ptr(); + END_HANDLE_TH_ERRORS +} + +// implemented on the python object bc no support for first class functions in native_functions.yaml +// See: ATen/native/README.md for more context +static PyObject * THPVariable_map_(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ "map_(Tensor other, PyObject* callable)" }); + auto& self_ = THPVariable_Unpack(self); + ParsedArgs<2> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + Variable other = r.tensor(0); + if (self_.requires_grad() || other.requires_grad()) { + throw std::runtime_error( + "Can't call map_() on Variable that requires grad. Use " + "var.detach().map_() instead."); + } + TORCH_CHECK( + !self_.unsafeGetTensorImpl()->is_python_dispatch() && !other.unsafeGetTensorImpl()->is_python_dispatch(), + ".map_ is not supported for tensor subclasses."); + + return THPVariable_Wrap(torch::utils::map_(self_, other, r.pyobject(1))); + END_HANDLE_TH_ERRORS +} + +// implemented on the python object bc no support for first class functions in native_functions.yaml +// See: ATen/native/README.md for more context +static PyObject * THPVariable_map2_(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ "map2_(Tensor x, Tensor y, PyObject* callable)" }); + auto& self_ = THPVariable_Unpack(self); + ParsedArgs<3> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + Variable x = r.tensor(0); + Variable y = r.tensor(1); + if (self_.requires_grad() || x.requires_grad() || y.requires_grad()) { + throw std::runtime_error( + "Can't call map2_() on Variable that requires grad. Use " + "var.detach().map2_() instead."); + } + TORCH_CHECK( + !x.unsafeGetTensorImpl()->is_python_dispatch() && !y.unsafeGetTensorImpl()->is_python_dispatch(), + ".map2_ is not supported for tensor subclasses."); + return THPVariable_Wrap(torch::utils::map2_(self_, x, y, r.pyobject(2))); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_new(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + return handle_torch_function(self, "new", args, kwargs); + } + auto& self_ = THPVariable_Unpack(self); + OptionalDeviceGuard device_guard(device_of(self_)); + return THPVariable_Wrap(torch::utils::legacy_tensor_new(legacyExtractDispatchKey(self_), self_.scalar_type(), args, kwargs)); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_new_tensor(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + return handle_torch_function(self, "new_tensor", args, kwargs); + } + auto& self_ = THPVariable_Unpack(self); + OptionalDeviceGuard device_guard(device_of(self_)); + return THPVariable_Wrap(torch::utils::new_tensor(legacyExtractDispatchKey(self_), self_.scalar_type(), args, kwargs)); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_storage(PyObject* self, PyObject* arg) +{ + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + return handle_torch_function(self, "untyped_storage"); + } + auto& self_ = THPVariable_Unpack(self); + return createPyObject(self_.storage()); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_to(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "to(Device device=None, ScalarType dtype=None, bool non_blocking=False, bool copy=False, *, MemoryFormat? memory_format=None)", + "to(ScalarType dtype, bool non_blocking=False, bool copy=False, *, MemoryFormat? memory_format=None)", + "to(Tensor tensor, bool non_blocking=False, bool copy=False, *, MemoryFormat? memory_format=None)", + }); + ParsedArgs<5> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + if (r.has_torch_function()) { + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + auto parsed = parse_to_conversion(r, /*allow_copy*/ true); + auto& device = std::get<0>(parsed); + auto& scalarType = std::get<1>(parsed); + auto non_blocking = std::get<2>(parsed); + auto copy = std::get<3>(parsed); + auto opt_memory_format = std::get<4>(parsed); + auto& self_ = THPVariable_Unpack(self); + torch::utils::maybe_initialize_device(device); + if (!device && !scalarType && !copy && !opt_memory_format.has_value()) { + Py_INCREF(self); + return self; + } else if (!device && !scalarType) { + return THPVariable_Wrap( + dispatch_to(self_, non_blocking, copy, opt_memory_format)); + } else if (!device) { + return THPVariable_Wrap(dispatch_to(self_, *scalarType, non_blocking, copy, opt_memory_format)); + } else if (!scalarType) { + return THPVariable_Wrap(dispatch_to(self_, *device, non_blocking, copy, opt_memory_format)); + } else { + return THPVariable_Wrap(dispatch_to(self_, *device, *scalarType, non_blocking, copy, opt_memory_format)); + } + Py_RETURN_NONE; + END_HANDLE_TH_ERRORS +} + +// implemented on the python object b/c arbitrarily nested list not declarable in native_functions.yaml +// See: ATen/native/README.md for more context +static PyObject * THPVariable_tolist(PyObject* self, PyObject* args) +{ + HANDLE_TH_ERRORS + if (has_torch_function(self)) { + return handle_torch_function(self, "tolist", args); + } + jit::tracer::warn("Converting a tensor to a Python list", jit::tracer::WARN_PYTHON_DATAFLOW); + auto self_ = THPVariable_Unpack(self); + return torch::utils::tensor_to_list(self_); + END_HANDLE_TH_ERRORS +} + +static PyObject * THPVariable_type(PyObject* self, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS + static PythonArgParser parser({ + "type(PyObject* dtype=None, bool non_blocking=False, *, MemoryFormat? memory_format=None)", + "type(PyObject* dtype=None, bool async=False, *, MemoryFormat? memory_format=None)|deprecated" + }); + auto& self_ = THPVariable_Unpack(self); + ParsedArgs<3> parsed_args; + auto r = parser.parse(self, args, kwargs, parsed_args); + + if(r.has_torch_function()){ + return handle_torch_function(r, self, args, kwargs, THPVariableClass, "torch.Tensor"); + } + + if (r.isNone(0)) { + return THPUtils_packString(torch::utils::options_to_string(self_.options())); + } + auto obj = r.pyobject(0); + auto opt_memory_format = r.memoryformatOptional(2); + std::string type_name; + bool is_dtype = false; + if (PyType_Check(obj)) { + if (obj == THPVariableClass) { + type_name = "torch.Tensor"; + } else { + type_name = ((PyTypeObject*)obj)->tp_name; + } + } else if (THPUtils_checkString(obj)) { + type_name = THPUtils_unpackString(obj); + } else if (THPDtype_Check(obj)) { + is_dtype = true; + } else { + throw TypeError("dtype must be a type, str, or dtype object"); + } + Device device = self_.device(); + if (is_dtype) { + auto scalar_type = r.scalartype(0); + return THPVariable_Wrap(dispatch_to(self_, scalar_type, /*non_blocking=*/ r.toBool(1), /*copy=*/ false, opt_memory_format)); + } + at::TensorOptions options = torch::utils::options_from_string(type_name); + auto scalar_type = at::typeMetaToScalarType(options.dtype()); + auto device_type = options.device().type(); + if (device_type != device.type()) { + device = at::Device(device_type); + } + torch::utils::maybe_initialize_device(device); + return THPVariable_Wrap(dispatch_to(self_, device, scalar_type, /*non_blocking=*/ r.toBool(1), /*copy=*/ false, opt_memory_format)); + END_HANDLE_TH_ERRORS +} + +// generated methods start here + +${py_methods} + +static PyObject * THPVariable_bool_scalar(PyObject* self, PyObject* args) { + if (has_torch_function(self)) { + HANDLE_TH_ERRORS + return handle_torch_function(self, "__bool__", args); + END_HANDLE_TH_ERRORS + } + jit::tracer::warn("Converting a tensor to a Python boolean", jit::tracer::WARN_PYTHON_DATAFLOW); + return THPVariable_is_nonzero(self, args); +} + +static PyObject * THPVariable___eq__(PyObject* self_, PyObject* args, PyObject* kwargs) +{ + HANDLE_TH_ERRORS +#ifdef USE_NUMPY + if (torch::utils::is_numpy_available()) { + static PythonArgParser parser({ + "__eq__(PyObject* other)", + }, /*traceable=*/true); + + ParsedArgs<1> parsed_args; + auto _r = parser.parse(self_, args, kwargs, parsed_args); + if(_r.has_torch_function()) { + return handle_torch_function(_r, self_, args, kwargs, THPVariableClass, "torch.Tensor"); + } + switch (_r.idx) { + case 0: { + auto other = _r.pyobject(0); + if (PyArray_Check(other)) { + auto other_tensor = torch::utils::tensor_from_numpy(other); + auto dispatch_eq = [](const at::Tensor & self, const at::Tensor & other) -> at::Tensor { + pybind11::gil_scoped_release no_gil; + return self.eq(other); + }; + const Tensor& self = THPVariable_Unpack(self_); + return wrap(dispatch_eq(self, other_tensor)); + } + } + } + } +#endif + return THPVariable_eq(self_, args, kwargs); + Py_RETURN_NONE; + END_HANDLE_TH_ERRORS +} + +// Wrapper converts a raised TypeError into returning NotImplemented +// Used to implement binary arithmetic operators +template +static PyObject * TypeError_to_NotImplemented_(PyObject* self, PyObject* args, PyObject* kwargs) { + + PyObject* ret = Func(self, args, kwargs); + if (!ret && PyErr_ExceptionMatches(PyExc_TypeError)) { + PyErr_Clear(); + Py_INCREF(Py_NotImplemented); + ret = Py_NotImplemented; + } + return ret; +} + +// set_ has to be defined in the template because the c10::Storage object +// does not have a type, and we need to make sure the Python storage object's +// type matches the tensor's type +static PyObject* THPVariable_set_( + PyObject* self_, + PyObject* args, + PyObject* kwargs) { + HANDLE_TH_ERRORS + const Tensor& self = THPVariable_Unpack(self_); + static PythonArgParser parser( + { + "set_()", + "set_(Storage source)", + "set_(Storage source, SymInt storage_offset, SymIntArrayRef size, SymIntArrayRef stride=None)", + "set_(Tensor source)", + "set_(Tensor source, SymInt storage_offset, SymIntArrayRef size, SymIntArrayRef stride=None)", + }, + /*traceable=*/false); + + ParsedArgs<4> parsed_args; + auto _r = parser.parse(args, kwargs, parsed_args); + + switch (_r.idx) { + case 0: { + // aten::set_(Tensor(a!) self) -> Tensor(a!) + auto dispatch_set_ = [](const Tensor& self) -> Tensor { + pybind11::gil_scoped_release no_gil; + return self.set_(); + }; + return wrap(dispatch_set_(self)); + } + case 1: { + // aten::set_.source_Storage(Tensor(a!) self, Storage source) -> + // Tensor(a!) + at::ScalarType storage_scalar_type{}; + bool is_typed_storage = true; + at::Storage storage = _r.storage(0, storage_scalar_type, is_typed_storage); + TORCH_CHECK(storage_scalar_type == self.dtype() || !is_typed_storage, + "Expected a Storage of type ", self.dtype(), + " or an UntypedStorage, but got type ", storage_scalar_type, + " for argument 1 'storage'"); + auto dispatch_set_ = [](const Tensor& self, Storage source) -> Tensor { + pybind11::gil_scoped_release no_gil; + return self.set_(std::move(source)); + }; + return wrap(dispatch_set_(self, storage)); + } + case 2: { + // aten::set_.source_Storage_storage_offset(Tensor(a!) self, Storage + // source, int storage_offset, int[] size, int[] stride=[]) -> Tensor(a!) + at::ScalarType storage_scalar_type{}; + bool is_typed_storage = true; + at::Storage storage = _r.storage(0, storage_scalar_type, is_typed_storage); + TORCH_CHECK(storage_scalar_type == self.dtype() || !is_typed_storage, + "Expected a Storage of type ", self.dtype(), + " or an UntypedStorage, but got type ", storage_scalar_type, + " for argument 1 'storage'"); + auto dispatch_set_ = [](const Tensor& self, + Storage source, + c10::SymInt storage_offset, + c10::SymIntArrayRef size, + c10::SymIntArrayRef stride) -> Tensor { + pybind11::gil_scoped_release no_gil; + return self.set__symint(std::move(source), std::move(storage_offset), size, stride); + }; + return wrap(dispatch_set_( + self, storage, _r.toSymInt(1), _r.symintlist(2), _r.symintlist(3))); + } + case 3: { + // aten::set_.source_Tensor(Tensor(a!) self, Tensor source) -> Tensor(a!) + auto dispatch_set_ = [](const Tensor& self, const Tensor& source) -> Tensor { + TORCH_CHECK(source.dtype() == self.dtype(), "Could not set tensor of type ", source.dtype(), " to a tensor of type ", self.dtype()); + pybind11::gil_scoped_release no_gil; + return self.set_(source); + }; + return wrap(dispatch_set_(self, _r.tensor(0))); + } + case 4: { + // aten::set_.source_Tensor_storage_offset(Tensor(a!) self, Tensor + // source, int storage_offset, int[] size, int[] stride=[]) -> Tensor(a!) + at::Tensor storage = _r.tensor(0); + auto dispatch_set_ = [](const Tensor& self, + const Tensor& source, + c10::SymInt storage_offset, + c10::SymIntArrayRef size, + c10::SymIntArrayRef stride) -> Tensor { + pybind11::gil_scoped_release no_gil; + return self.set__symint(source, std::move(storage_offset), size, stride); + }; + return wrap(dispatch_set_( + self, storage, _r.toSymInt(1), _r.symintlist(2), _r.symintlist(3))); + } + } + Py_RETURN_NONE; + END_HANDLE_TH_ERRORS +} + +// XXX: ops that are bound here are not exposed to the C++ api nor the JIT. +// Any new ops added here should be accompanied with a comment why they are not +// being registered through native_functions.yaml, and be tagged cpp / JIT +PyMethodDef variable_methods[] = { + // These magic methods are all implemented on python object to wrap NotImplementedError + {"__add__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__radd__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__iadd__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__rmul__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__mul__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__imul__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__sub__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__isub__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__div__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__truediv__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__floordiv__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__idiv__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__ifloordiv__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__mod__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__imod__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__eq__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__ne__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__lt__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__le__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__gt__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__ge__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__rand__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__ror__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__rxor__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"__bool__", THPVariable_bool_scalar, METH_NOARGS, nullptr}, + {"__float__", THPVariable_float_scalar, METH_NOARGS, nullptr}, + {"__complex__", THPVariable_complex_scalar, METH_NOARGS, nullptr}, + {"__int__", THPVariable_integral_scalar, METH_NOARGS, nullptr}, + {"__long__", THPVariable_integral_scalar, METH_NOARGS, nullptr}, + {"__index__", THPVariable_index_scalar, METH_NOARGS, nullptr}, + {"__nonzero__", THPVariable_bool_scalar, METH_NOARGS, nullptr}, + {"__invert__", THPVariable_invert, METH_NOARGS, nullptr}, + {"__matmul__", castPyCFunctionWithKeywords(TypeError_to_NotImplemented_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"_is_view", THPVariable__is_view, METH_NOARGS, nullptr}, + {"apply_", THPVariable_apply_, METH_O, nullptr}, + {"bfloat16", castPyCFunctionWithKeywords(THPVariable_bfloat16), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"byte", castPyCFunctionWithKeywords(THPVariable_byte), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"char", castPyCFunctionWithKeywords(THPVariable_char), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"contiguous", castPyCFunctionWithKeywords(THPVariable_contiguous), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"copy_", castPyCFunctionWithKeywords(THPVariable_copy_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"cpu", castPyCFunctionWithKeywords(THPVariable_cpu), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"cuda", castPyCFunctionWithKeywords(THPVariable_cuda), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"mtia", castPyCFunctionWithKeywords(THPVariable_mtia), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"xpu", castPyCFunctionWithKeywords(THPVariable_xpu), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"ipu", castPyCFunctionWithKeywords(THPVariable_ipu), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"const_data_ptr", THPVariable_const_data_ptr, METH_NOARGS, nullptr}, + {"data_ptr", THPVariable_data_ptr, METH_NOARGS, nullptr}, + {"dim", THPVariable_dim, METH_NOARGS, nullptr}, + {"double", castPyCFunctionWithKeywords(THPVariable_double), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"cdouble", castPyCFunctionWithKeywords(THPVariable_cdouble), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"element_size", THPVariable_element_size, METH_NOARGS, nullptr}, + {"float", castPyCFunctionWithKeywords(THPVariable_float), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"cfloat", castPyCFunctionWithKeywords(THPVariable_cfloat), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"get_device", THPVariable_get_device, METH_NOARGS, nullptr}, + {"bool", castPyCFunctionWithKeywords(THPVariable_bool), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"half", castPyCFunctionWithKeywords(THPVariable_half), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"int", castPyCFunctionWithKeywords(THPVariable_int), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"is_contiguous", castPyCFunctionWithKeywords(THPVariable_is_contiguous), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"item", THPVariable_item, METH_NOARGS, nullptr}, + {"long", castPyCFunctionWithKeywords(THPVariable_long), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"map_", castPyCFunctionWithKeywords(THPVariable_map_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"map2_", castPyCFunctionWithKeywords(THPVariable_map2_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"ndimension", THPVariable_dim, METH_NOARGS, nullptr}, + {"nelement", THPVariable_numel, METH_NOARGS, nullptr}, + {"new", castPyCFunctionWithKeywords(THPVariable_new), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"new_tensor", castPyCFunctionWithKeywords(THPVariable_new_tensor), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"nonzero", castPyCFunctionWithKeywords(THPVariable_nonzero), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"numel", THPVariable_numel, METH_NOARGS, nullptr}, + {"numpy", castPyCFunctionWithKeywords(THPVariable_numpy), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"requires_grad_", castPyCFunctionWithKeywords(THPVariable_requires_grad_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"set_", castPyCFunctionWithKeywords(THPVariable_set_), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"short", castPyCFunctionWithKeywords(THPVariable_short), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"size", castPyCFunctionWithKeywords(THPVariable_size), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"untyped_storage", THPVariable_storage, METH_NOARGS, nullptr}, + {"storage_offset", THPVariable_storage_offset, METH_NOARGS, nullptr}, + {"stride", castPyCFunctionWithKeywords(THPVariable_stride), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"to", castPyCFunctionWithKeywords(THPVariable_to), METH_VARARGS | METH_KEYWORDS, nullptr}, + {"tolist", THPVariable_tolist, METH_NOARGS, nullptr}, + {"type", castPyCFunctionWithKeywords(THPVariable_type), METH_VARARGS | METH_KEYWORDS, nullptr}, + ${py_method_defs} + {nullptr} +}; + +} // namespace torch::autograd diff --git a/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/variable_factories.h b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/variable_factories.h new file mode 100644 index 0000000000000000000000000000000000000000..2b55f441ab6249cb7963c5e4a15070f626f775b7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/packaged/autograd/templates/variable_factories.h @@ -0,0 +1,135 @@ +#pragma once + +// ${generated_comment} + +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +$ops_headers +#endif + +#include +#include +#include + +namespace torch { + +/// NOTE: Currently `torch::tensor(...)` doesn't support mixed data types +/// (i.e. `torch::tensor({{bool, 2.0}})` doesn't work). We might be able to +/// support it in the future by iterating over all sub-lists to find +/// the largest data type that can represent all of the elements, or by using +/// variadic templates. +/// +/// NOTE: C++ `torch::tensor` with a floating-point type or an `at::ArrayRef` / `std::vector` / +/// (nested) braced-init-list of floating-point types always produces a tensor of dtype +/// `torch::get_default_dtype()`, matching Python `torch.tensor` behavior. +/// +/// NOTE: C++ `torch::tensor` with an integer type or an `at::ArrayRef` / `std::vector` / +/// (nested) braced-init-list of integer types always produces a tensor of dtype `at::kLong` +/// (aka. int64_t), matching Python `torch.tensor` behavior. +/// +/// NOTE: The following dtypes are not supported by `torch::tensor` currently: +/// - `unsigned int` +/// - `unsigned long int` +/// - `unsigned long long int` +/// - `long long int` +inline at::Tensor tensor(detail::TensorDataContainer tensor_data_container, const at::TensorOptions& options = {}) { + return autograd::make_variable( + // note: we remove the requires_grad setting from the TensorOptions because + // it is ignored anyways (and we actually have an assertion that it isn't set + // which would fail otherwise). We handle requires_grad explicitly here + // instead of passing it through to the kernel. + tensor_data_container.convert_to_tensor(options.requires_grad(::std::nullopt)), + options.requires_grad()); +} + +/// A generic deleter function. +using Deleter = std::function; +using at::MemoryFormat; + +/// Exposes the given `data` as a `Tensor` without taking ownership of the +/// original data. `sizes` should specify the shape of the tensor, `strides` the +/// stride in each dimension. The `deleter` function (a +/// `std::function`) will be called on the `data` when the Tensor +/// data would normally be deallocated. The `TensorOptions` specify additional +/// configuration options for the returned tensor, such as what type to +/// interpret the `data` as. +inline at::Tensor from_blob( + void* data, + at::IntArrayRef sizes, + at::IntArrayRef strides, + const Deleter& deleter, + const at::TensorOptions& options = at::TensorOptions()) { + at::Tensor tensor = ([&]() { + at::AutoDispatchBelowAutograd guard; // TODO: remove + at::tracer::impl::NoTracerDispatchMode tracer_guard; + return at::from_blob(data, sizes, strides, deleter, options.requires_grad(::std::nullopt)); + })(); + return autograd::make_variable(tensor, options.requires_grad()); +} + +/// Exposes the given `data` as a `Tensor` without taking ownership of the +/// original data. `sizes` should specify the shape of the tensor, `strides` the +/// stride in each dimension. The `TensorOptions` +/// specify additional configuration options for the returned tensor, such as +/// what type to interpret the `data` as. +inline at::Tensor from_blob( + void* data, + at::IntArrayRef sizes, + at::IntArrayRef strides, + const at::TensorOptions& options = at::TensorOptions()) { + at::Tensor tensor = ([&]() { + at::AutoDispatchBelowAutograd guard; // TODO: remove + at::tracer::impl::NoTracerDispatchMode tracer_guard; + return at::from_blob(data, sizes, strides, options.requires_grad(::std::nullopt)); + })(); + return autograd::make_variable(tensor, options.requires_grad()); +} + +/// Exposes the given `data` as a `Tensor` without taking ownership of the +/// original data. `sizes` should specify the shape of the tensor. The `deleter` +/// (a `std::function`) function will be called on the `data` when +/// the Tensor data would normally be deallocated. The `TensorOptions` specify +/// additional configuration options for the returned tensor, such as what type +/// to interpret the `data` as. +inline at::Tensor from_blob( + void* data, + at::IntArrayRef sizes, + const Deleter& deleter, + const at::TensorOptions& options = at::TensorOptions()) { + at::Tensor tensor = ([&]() { + at::AutoDispatchBelowAutograd guard; // TODO: remove + at::tracer::impl::NoTracerDispatchMode tracer_guard; + return at::from_blob(data, sizes, deleter, options.requires_grad(::std::nullopt)); + })(); + return autograd::make_variable(tensor, options.requires_grad()); +} + +/// Exposes the given `data` as a `Tensor` without taking ownership of the +/// original data. `sizes` should specify the shape of the tensor. The +/// `TensorOptions` specify additional configuration options for the returned +/// tensor, such as what type to interpret the `data` as. +inline at::Tensor from_blob( + void* data, + at::IntArrayRef sizes, + const at::TensorOptions& options = at::TensorOptions()) { + at::Tensor tensor = ([&]() { + at::AutoDispatchBelowAutograd guard; // TODO: remove + at::tracer::impl::NoTracerDispatchMode tracer_guard; + return at::from_blob(data, sizes, options.requires_grad(::std::nullopt)); + })(); + return autograd::make_variable(tensor, options.requires_grad()); +} + +${function_definitions} + +} // namespace torch diff --git a/.venv/lib/python3.12/site-packages/torchgen/selective_build/__init__.py b/.venv/lib/python3.12/site-packages/torchgen/selective_build/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torchgen/selective_build/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/selective_build/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94b848c427ce6edcc8a9e5f67a72a03d53d93680 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/selective_build/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/selective_build/__pycache__/operator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/selective_build/__pycache__/operator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..862dc2db80e0ab0e581043275a9bce3a0e0f953b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/selective_build/__pycache__/operator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/selective_build/__pycache__/selector.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/selective_build/__pycache__/selector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3def37ebce81b1dcee5a787d503174325e2882c1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/selective_build/__pycache__/selector.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/selective_build/operator.py b/.venv/lib/python3.12/site-packages/torchgen/selective_build/operator.py new file mode 100644 index 0000000000000000000000000000000000000000..dc53851a80f561bdb4180a3f50a7e71930afaaa1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/selective_build/operator.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +from dataclasses import dataclass + + +# This class holds information about a single operator used to determine +# the outcome of a selective/custom PyTorch build that doesn't include +# registration code for all the supported operators. This is done to +# reduce the size of the generated binary so that it can be deployed in +# situations where binary size comes at a premium. +# +@dataclass(frozen=True) +class SelectiveBuildOperator: + # The name of the operator. This includes the aten::, etc... prefix + # The operator name may or may not have the overload name. If this + # operator name does not specify an overload name, the way to determine + # if this entry refers to the family of operators with this base name + # or just the operator with this name is to look at the value of the + # 'include_all_overloads' flag in this class. + name: str + + # True if this is a root operator (i.e. called directly from a + # TorchScript model, etc...). An operator is considered to be a + # root operator if it is called directly from any one of the models + # that this instance of the pytorch library was built for. Hence, it + # may not be a root operator in all of the models that are used in + # this instance of the pytorch library. + is_root_operator: bool + + # Is this operator used for on-device training? If True, then we need to + # use the information to generate code in VariableType_N.cpp for registration + # of training related operators. Again, this is True if this operator + # is used for training in one or more models used by this instance of the + # pytorch library. + is_used_for_training: bool + + # If True, it indicates that this operator instance (object) refers to an + # operator without the overload name and should apply to all overloads + # which have this operator name as the base name. This flag is applicable + # only for objects that have operator names without a DOT (period) character + # in them. + # + # Note: This flag is a temporary workaround to grandfather in the current + # static selective (custom) build mechanism, which largely ignores overload + # names when determining whether to select operators for registration + # purposes. + include_all_overloads: bool + + # Debug Information at the operator level + _debug_info: tuple[str, ...] | None + + @staticmethod + def from_yaml_dict( + op_name: str, op_info: dict[str, object] + ) -> SelectiveBuildOperator: + allowed_keys = { + "name", + "is_root_operator", + "is_used_for_training", + "include_all_overloads", + "debug_info", + } + + if len(set(op_info.keys()) - allowed_keys) > 0: + raise Exception( # noqa: TRY002 + "Got unexpected top level keys: {}".format( + ",".join(set(op_info.keys()) - allowed_keys), + ) + ) + + if "name" in op_info: + if op_name != op_info["name"]: + raise AssertionError( + f"op_name mismatch: {op_name} != {op_info['name']}" + ) + + is_root_operator = op_info.get("is_root_operator", True) + if not isinstance(is_root_operator, bool): + raise AssertionError( + f"Expected 'is_root_operator' to be bool, got {type(is_root_operator)}" + ) + + is_used_for_training = op_info.get("is_used_for_training", True) + if not isinstance(is_used_for_training, bool): + raise AssertionError( + f"Expected 'is_used_for_training' to be bool, got {type(is_used_for_training)}" + ) + + include_all_overloads = op_info.get("include_all_overloads", True) + if not isinstance(include_all_overloads, bool): + raise AssertionError( + f"Expected 'include_all_overloads' to be bool, got {type(include_all_overloads)}" + ) + + debug_info: tuple[str, ...] | None = None + if "debug_info" in op_info: + di_list = op_info["debug_info"] + if not isinstance(di_list, list): + raise AssertionError( + f"Expected 'debug_info' to be list, got {type(di_list)}" + ) + debug_info = tuple(str(x) for x in di_list) + + return SelectiveBuildOperator( + name=op_name, + is_root_operator=is_root_operator, + is_used_for_training=is_used_for_training, + include_all_overloads=include_all_overloads, + _debug_info=debug_info, + ) + + @staticmethod + def from_legacy_operator_name_without_overload( + name: str, + ) -> SelectiveBuildOperator: + return SelectiveBuildOperator( + name=name, + is_root_operator=True, + is_used_for_training=True, + include_all_overloads=True, + _debug_info=None, + ) + + def to_dict(self) -> dict[str, object]: + ret: dict[str, object] = { + "is_root_operator": self.is_root_operator, + "is_used_for_training": self.is_used_for_training, + "include_all_overloads": self.include_all_overloads, + } + if self._debug_info is not None: + ret["debug_info"] = self._debug_info + + return ret + + +def merge_debug_info( + lhs: tuple[str, ...] | None, + rhs: tuple[str, ...] | None, +) -> tuple[str, ...] | None: + # Ensure that when merging, each entry shows up just once. + if lhs is None and rhs is None: + return None + + return tuple(set((lhs or ()) + (rhs or ()))) + + +def combine_operators( + lhs: SelectiveBuildOperator, rhs: SelectiveBuildOperator +) -> SelectiveBuildOperator: + if str(lhs.name) != str(rhs.name): + raise Exception( # noqa: TRY002 + f"Expected both arguments to have the same name, but got '{str(lhs.name)}' and '{str(rhs.name)}' instead" + ) + + return SelectiveBuildOperator( + name=lhs.name, + # Consider this operator to be a root operator if it is a + # root operator in any of the models used in this instance of + # the pytorch library. + is_root_operator=lhs.is_root_operator or rhs.is_root_operator, + # Consider this operator to be a training operator if it is + # an operator used for training in any of the models used + # in this instance of the pytorch library. + is_used_for_training=lhs.is_used_for_training or rhs.is_used_for_training, + include_all_overloads=lhs.include_all_overloads or rhs.include_all_overloads, + _debug_info=merge_debug_info(lhs._debug_info, rhs._debug_info), + ) + + +def merge_operator_dicts( + lhs: dict[str, SelectiveBuildOperator], + rhs: dict[str, SelectiveBuildOperator], +) -> dict[str, SelectiveBuildOperator]: + operators: dict[str, SelectiveBuildOperator] = {} + for op_name, op in list(lhs.items()) + list(rhs.items()): + new_op = op + if op_name in operators: + new_op = combine_operators(operators[op_name], op) + + operators[op_name] = new_op + + return operators + + +def strip_operator_overload_name(op_name: str) -> str: + return op_name.split(".", maxsplit=1)[0] diff --git a/.venv/lib/python3.12/site-packages/torchgen/selective_build/selector.py b/.venv/lib/python3.12/site-packages/torchgen/selective_build/selector.py new file mode 100644 index 0000000000000000000000000000000000000000..fa48a9df2dd752275513e42423ccd50576aa6cb3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/selective_build/selector.py @@ -0,0 +1,377 @@ +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Iterable +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import yaml + +from torchgen.selective_build.operator import ( + merge_debug_info, + merge_operator_dicts, + SelectiveBuildOperator, + strip_operator_overload_name, +) + + +if TYPE_CHECKING: + from torchgen.model import NativeFunction + + +# A SelectiveBuilder holds information extracted from the selective build +# YAML specification. +# +# It includes information about the build's selectivity, the debug_info +# associated with this selective build (opaque string), and the set of +# operators that should be included in the build. +# +@dataclass(frozen=True) +class SelectiveBuilder: + # If true, then the build is not selective, and includes all + # operators. + include_all_operators: bool + + # Debug Information at the selective/custom build level. + _debug_info: tuple[str, ...] | None + + # A dictionary of operator -> operator metadata. + operators: dict[str, SelectiveBuildOperator] + + # A dictionary of selected kernel tags and dtypes. Typically a + # PyTorch Operator Kernel (function) may have many code paths + # that are specialized for many many Tensor dtypes, so it's not + # one per kernel function, but there could be many per kernel + # function. The tag isn't a kernel function name, but some fragment + # of the kernel function implementation itself. + kernel_metadata: dict[str, list[str]] + + # ExecuTorch only. A dictionary of kernel tag -> list of (list of input + # dtypes for tensor-like input args). + # This is from selective.yaml + et_kernel_metadata: dict[str, list[str]] + + # A set of all the custom torch bind classes used by the selected models + # Stored as a set internally to remove duplicates proactively, but written + # as a list to yamls + custom_classes: set[str] + + # A set of all the build features used by the selected models + # Stored as a set internally to remove duplicates proactively, but written + # as a list to yamls + build_features: set[str] + + # If true, then fragments for all dtypes for all kernel functions + # are included as well as all custom classes. This is typically set when any one of the + # operator lists is generated from a mechanism other than + # tracing based selective build. + include_all_non_op_selectives: bool + + @staticmethod + def get_nop_selector() -> SelectiveBuilder: + return SelectiveBuilder.from_yaml_dict({"include_all_operators": True}) + + @staticmethod + def from_yaml_dict(data: dict[str, object]) -> SelectiveBuilder: + valid_top_level_keys = { + "include_all_non_op_selectives", + "include_all_operators", + "debug_info", + "operators", + "kernel_metadata", + "et_kernel_metadata", + "custom_classes", + "build_features", + } + top_level_keys = set(data.keys()) + if len(top_level_keys - valid_top_level_keys) > 0: + raise Exception( # noqa: TRY002 + "Got unexpected top level keys: {}".format( + ",".join(top_level_keys - valid_top_level_keys), + ) + ) + include_all_operators = data.get("include_all_operators", False) + if not isinstance(include_all_operators, bool): + raise AssertionError( + f"Expected 'include_all_operators' to be bool, got {type(include_all_operators)}" + ) + + debug_info = None + if "debug_info" in data: + di_list = data["debug_info"] + if not isinstance(di_list, list): + raise AssertionError( + f"Expected 'debug_info' to be list, got {type(di_list)}" + ) + + debug_info = tuple(str(x) for x in di_list) + + operators = {} + operators_dict = data.get("operators", {}) + if not isinstance(operators_dict, dict): + raise AssertionError( + f"Expected 'operators' to be dict, got {type(operators_dict)}" + ) + + for k, v in operators_dict.items(): + operators[k] = SelectiveBuildOperator.from_yaml_dict(k, v) + + kernel_metadata = {} + kernel_metadata_dict = data.get("kernel_metadata", {}) + if not isinstance(kernel_metadata_dict, dict): + raise AssertionError( + f"Expected 'kernel_metadata' to be dict, got {type(kernel_metadata_dict)}" + ) + + for k, v in kernel_metadata_dict.items(): + kernel_metadata[str(k)] = [str(dtype) for dtype in v] + + et_kernel_metadata = data.get("et_kernel_metadata", {}) + if not isinstance(et_kernel_metadata, dict): + raise AssertionError( + f"Expected 'et_kernel_metadata' to be dict, got {type(et_kernel_metadata)}" + ) + + custom_classes = data.get("custom_classes", []) + if not isinstance(custom_classes, Iterable): + raise AssertionError( + f"Expected 'custom_classes' to be Iterable, got {type(custom_classes)}" + ) + custom_classes = set(custom_classes) + + build_features = data.get("build_features", []) + if not isinstance(build_features, Iterable): + raise AssertionError( + f"Expected 'build_features' to be Iterable, got {type(build_features)}" + ) + build_features = set(build_features) + + include_all_non_op_selectives = data.get("include_all_non_op_selectives", False) + if not isinstance(include_all_non_op_selectives, bool): + raise AssertionError( + f"Expected 'include_all_non_op_selectives' to be bool, " + f"got {type(include_all_non_op_selectives)}" + ) + + return SelectiveBuilder( + include_all_operators, + debug_info, + operators, + kernel_metadata, + et_kernel_metadata, + custom_classes, # type: ignore[arg-type] + build_features, # type: ignore[arg-type] + include_all_non_op_selectives, + ) + + @staticmethod + def from_yaml_str(config_contents: str) -> SelectiveBuilder: + contents = yaml.safe_load(config_contents) + return SelectiveBuilder.from_yaml_dict(contents) + + @staticmethod + def from_yaml_path(config_path: str) -> SelectiveBuilder: + with open(config_path) as f: + contents = yaml.safe_load(f) + return SelectiveBuilder.from_yaml_dict(contents) + + @staticmethod + def from_legacy_op_registration_allow_list( + allow_list: set[str], is_root_operator: bool, is_used_for_training: bool + ) -> SelectiveBuilder: + operators = {} + for op in allow_list: + operators[op] = { + "name": op, + "is_root_operator": is_root_operator, + "is_used_for_training": is_used_for_training, + "include_all_overloads": True, + } + return SelectiveBuilder.from_yaml_dict( + { + "operators": operators, + "include_all_non_op_selectives": True, + } + ) + + def is_operator_selected(self, name: str) -> bool: + if self.include_all_operators: + return True + + if name in self.operators: + return True + name = strip_operator_overload_name(name) + return name in self.operators and self.operators[name].include_all_overloads + + def is_native_function_selected(self, func: NativeFunction) -> bool: + op_name = op_name_from_native_function(func) + return self.is_operator_selected(op_name) + + def is_operator_selected_for_training(self, name: str) -> bool: + if not self.is_operator_selected(name): + return False + if self.include_all_operators: + return True + + not_training_op = SelectiveBuildOperator( + name="", + is_root_operator=False, + is_used_for_training=False, + include_all_overloads=False, + _debug_info=None, + ) + op = not_training_op + if name in self.operators: + op = self.operators[name] + + name = strip_operator_overload_name(name) + base_op = not_training_op + if name in self.operators: + base_op = self.operators[name] + + return op.is_used_for_training or ( + base_op.include_all_overloads and base_op.is_used_for_training + ) + + def is_native_function_selected_for_training(self, func: NativeFunction) -> bool: + op_name = op_name_from_native_function(func) + return self.is_operator_selected_for_training(op_name) + + def is_root_operator(self, name: str) -> bool: + if not self.is_operator_selected(name): + return False + if self.include_all_operators: + return True + + if name in self.operators: + op: SelectiveBuildOperator = self.operators[name] + return op.is_root_operator + name = strip_operator_overload_name(name) + if name not in self.operators: + return False + base_op: SelectiveBuildOperator = self.operators[name] + return base_op.include_all_overloads and base_op.is_root_operator + + def is_kernel_dtype_selected(self, kernel_tag: str, dtype: str) -> bool: + if self.include_all_operators or self.include_all_non_op_selectives: + return True + + return ( + kernel_tag in self.kernel_metadata + and dtype in self.kernel_metadata[kernel_tag] + ) + + def et_get_selected_kernels(self, op_name: str, kernel_key: list[str]) -> list[str]: + """ + Return a list of kernel keys that cover the used ops + """ + # If no kernel metadata, either it's implied by include_all_operators=True or the op is not used. + if op_name not in self.et_kernel_metadata: + return kernel_key if self.include_all_operators else [] + # Otherwise, only return the specific kernel keys. + + result_set = set() + + for model_kernel_keys in self.et_kernel_metadata[op_name]: + key_found = False + for key in kernel_key: + # Don't compare the version for now + if ( + key != "default" + and key.split("/")[1] == model_kernel_keys.split("/")[1] + ): + result_set.add(key) + key_found = True + break + if not key_found: + if "default" not in kernel_key: + raise Exception("Missing kernel for the model") # noqa: TRY002 + else: + result_set.add("default") + + return list(result_set) + + def to_dict(self) -> dict[str, object]: + ret: dict[str, object] = { + "include_all_non_op_selectives": self.include_all_non_op_selectives, + "include_all_operators": self.include_all_operators, + } + operators = {} + for op_name, op in self.operators.items(): + operators[op_name] = op.to_dict() + ret["operators"] = operators + + if self._debug_info is not None: + ret["debug_info"] = sorted(self._debug_info) + + ret["kernel_metadata"] = { + k: sorted(v) for (k, v) in self.kernel_metadata.items() + } + + ret["et_kernel_metadata"] = self.et_kernel_metadata + + ret["custom_classes"] = sorted(self.custom_classes) + + ret["build_features"] = sorted(self.build_features) + + return ret + + +def merge_kernel_metadata( + lhs: dict[str, list[str]], + rhs: dict[str, list[str]], +) -> dict[str, list[str]]: + kernel_metadata: dict[str, list[str]] = {} + for tag_name, dtypes in list(lhs.items()) + list(rhs.items()): + dtypes_copy = set(dtypes) + if tag_name in kernel_metadata: + dtypes_copy |= set(kernel_metadata[tag_name]) + + kernel_metadata[tag_name] = list(dtypes_copy) + + return kernel_metadata + + +def merge_et_kernel_metadata( + lhs: dict[str, list[str]], + rhs: dict[str, list[str]], +) -> dict[str, list[str]]: + merge_et_kernel_metadata: dict[str, set[str]] = defaultdict(set) + for op in list(lhs.keys()) + list(rhs.keys()): + merge_et_kernel_metadata[op].update(lhs.get(op, [])) + merge_et_kernel_metadata[op].update(rhs.get(op, [])) + + return {op: sorted(val) for op, val in merge_et_kernel_metadata.items()} + + +def combine_selective_builders( + lhs: SelectiveBuilder, rhs: SelectiveBuilder +) -> SelectiveBuilder: + include_all_operators = lhs.include_all_operators or rhs.include_all_operators + debug_info = merge_debug_info(lhs._debug_info, rhs._debug_info) + operators = merge_operator_dicts(lhs.operators, rhs.operators) + kernel_metadata = merge_kernel_metadata(lhs.kernel_metadata, rhs.kernel_metadata) + et_kernel_metadata = merge_et_kernel_metadata( + lhs.et_kernel_metadata, rhs.et_kernel_metadata + ) + include_all_non_op_selectives = ( + lhs.include_all_non_op_selectives or rhs.include_all_non_op_selectives + ) + custom_classes = lhs.custom_classes.union(rhs.custom_classes) + build_features = lhs.build_features.union(rhs.build_features) + return SelectiveBuilder( + include_all_operators, + debug_info, + operators, + kernel_metadata, + et_kernel_metadata, + custom_classes, + build_features, + include_all_non_op_selectives, + ) + + +def op_name_from_native_function(f: NativeFunction) -> str: + # This was originally read from the 'operator_name_with_overload' field in the + # declaration dict, which was the part before the first '(' in 'schema_string'. + return f"{f.namespace}::{f.func.name}" diff --git a/.venv/lib/python3.12/site-packages/torchgen/static_runtime/__init__.py b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torchgen/static_runtime/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b80e7c748e70382b536bd0940666796fd9a0cddf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/static_runtime/__pycache__/config.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..986279840fc30af48a9164e16836a43d3a6053dc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/__pycache__/config.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/static_runtime/__pycache__/gen_static_runtime_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/__pycache__/gen_static_runtime_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7eee14b77e5944195c6ee3a44719d59d48cd71a4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/__pycache__/gen_static_runtime_ops.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/static_runtime/__pycache__/generator.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/__pycache__/generator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e828387895703329d4eac093931a663e13e991f5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/__pycache__/generator.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchgen/static_runtime/config.py b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/config.py new file mode 100644 index 0000000000000000000000000000000000000000..c0993d00702c70532467eb5a190fcf73b6cdd846 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/config.py @@ -0,0 +1,389 @@ +from __future__ import annotations + +from torchgen.model import NativeFunctionsGroup, NativeFunctionsViewGroup + + +def func_name_base_str(g: NativeFunctionsGroup | NativeFunctionsViewGroup) -> str: + if isinstance(g, NativeFunctionsGroup): + return str(g.functional.func.name.name.base) + else: + return str(g.view.root_name) + + +is_hand_written_ops_ = frozenset( + ( + "abs", + "add", + "addmm", + "all", + "any", + "argmin", + "bmm", + "clamp", + "clamp_min", + "cumsum", + "div", + "fmod", + "index_select", + "leaky_relu", + "linear", + "log", + "matmul", + "mul", + "narrow_copy", + "nonzero", + "pow", + "remainder", + "sigmoid", + "sign", + "sub", + "tanh", + "detach", + "expand_as", + "flatten", + "narrow", + "reshape_as", + "select", + "slice", + "softmax", + "split", + "squeeze", + "transpose", + "view", + "where", + ) +) + + +def is_hand_written(g: NativeFunctionsGroup | NativeFunctionsViewGroup) -> bool: + name_base = func_name_base_str(g) + return name_base in is_hand_written_ops_ + + +def override_test_values(arg_map: dict[str, str], op_name: str, index: int) -> None: + if index not in (0, 1): + raise AssertionError(f"index must be 0 or 1, got {index}") + if op_name == "addr": + if index == 0: + arg_map["self"] = "at::rand({6, 6})" + arg_map["vec1"] = "at::rand({6})" + arg_map["vec2"] = "at::rand({6})" + else: + arg_map["self"] = "at::rand({22, 22})" + arg_map["vec1"] = "at::rand({22})" + arg_map["vec2"] = "at::rand({22})" + return + if op_name == "mv": + if index == 0: + arg_map["self"] = "at::rand({6, 6})" + arg_map["vec"] = "at::rand({6})" + else: + arg_map["self"] = "at::rand({22, 22})" + arg_map["vec"] = "at::rand({22})" + return + if op_name == "addbmm": + if index == 0: + arg_map["self"] = "at::rand({6, 6})" + else: + arg_map["self"] = "at::rand({22, 22})" + return + if op_name == "cross": + if index == 0: + arg_map["self"] = "at::rand({3, 3, 3})" + arg_map["other"] = "at::rand({3, 3, 3})" + else: + arg_map["self"] = "at::rand({22, 3, 22})" + arg_map["other"] = "at::rand({22, 3, 22})" + return + if op_name == "take": + if index == 0: + arg_map["index"] = "at::randint(0, 216, {20}, torch::kInt64)" + else: + arg_map["index"] = "at::randint(0, 1000, {100}, torch::kInt64)" + return + if op_name == "take_along_dim": + if index == 0: + arg_map["indices"] = "at::argsort(self0, 1, true)" + else: + arg_map["indices"] = "at::argsort(self1, 1, true)" + return + if op_name == "masked_select": + if index == 0: + arg_map["mask"] = "at::randn({6, 6, 6}) > 0.5" + else: + arg_map["mask"] = "at::rand({22, 22, 22}) > 0.5" + return + if op_name == "orgqr": + if index == 0: + arg_map["input2"] = "at::rand({6, 6})" + else: + arg_map["input2"] = "at::rand({22, 22})" + return + if op_name == "ormqr": + if index == 0: + arg_map["input2"] = "at::rand({6, 6})" + else: + arg_map["input2"] = "at::rand({22, 22})" + return + if op_name == "quantile": + if index == 0: + arg_map["q"] = "at::rand({6})" + arg_map["interpolation"] = '"linear"' + else: + arg_map["q"] = "at::rand({22})" + arg_map["interpolation"] = '"linear"' + return + if op_name == "nanquantile": + if index == 0: + arg_map["q"] = "at::rand({6})" + arg_map["interpolation"] = '"linear"' + else: + arg_map["q"] = "at::rand({22})" + arg_map["interpolation"] = '"linear"' + return + if op_name == "multi_margin_loss": + if index == 0: + arg_map["self"] = "at::rand({6, 6})" + arg_map["target"] = "at::randint(6, {6}, torch::kInt64)" + arg_map["weight"] = "at::rand({6})" + else: + arg_map["self"] = "at::rand({22, 22})" + arg_map["target"] = "at::randint(22, {22}, torch::kInt64)" + arg_map["weight"] = "at::rand({22})" + return + if op_name == "multilabel_margin_loss": + if index == 0: + arg_map["self"] = "at::rand({6, 6})" + arg_map["target"] = "at::randint(6, {6, 6}, torch::kInt64)" + else: + arg_map["self"] = "at::rand({22, 22})" + arg_map["target"] = "at::randint(22, {22, 22}, torch::kInt64)" + return + if op_name == "nll_loss": + if index == 0: + arg_map["self"] = "at::rand({6, 6})" + arg_map["target"] = "at::randint(6, {6}, torch::kInt64)" + arg_map["weight"] = "at::rand({6})" + else: + arg_map["self"] = "at::rand({22, 22})" + arg_map["target"] = "at::randint(22, {22}, torch::kInt64)" + arg_map["weight"] = "at::rand({22})" + return + if op_name == "nll_loss2d": + if index == 0: + arg_map["self"] = "at::rand({6, 6, 6, 6})" + arg_map["target"] = "at::randint(6, {6, 6, 6}, torch::kInt64)" + arg_map["weight"] = "at::rand({6})" + else: + arg_map["self"] = "at::rand({22, 22, 22, 22})" + arg_map["target"] = "at::randint(22, {22, 22, 22}, torch::kInt64)" + arg_map["weight"] = "at::rand({22})" + return + if op_name in ( + "fft_fft", + "fft_ifft", + "fft_rfft", + "fft_irfft", + "fft_hfft", + "fft_ihfft", + ): + arg_map["norm"] = '"forward"' + return + if op_name == "linalg_tensorinv": + if index == 0: + arg_map["self"] = "at::rand({6, 6, 6, 6})" + arg_map["ind"] = "2" + else: + arg_map["self"] = "at::rand({22, 22, 22, 22})" + arg_map["ind"] = "2" + return + if op_name == "addmv": + if index == 0: + arg_map["self"] = "at::rand({2})" + arg_map["mat"] = "at::rand({2, 2})" + arg_map["vec"] = "at::rand({2})" + else: + arg_map["self"] = "at::rand({35})" + arg_map["mat"] = "at::rand({35, 35})" + arg_map["vec"] = "at::rand({35})" + return + if op_name == "acosh": + if index == 0: + arg_map["self"] = "at::rand({2, 2, 2}) + at::ones({2, 2, 2})" + else: + arg_map["self"] = "at::rand({5, 5, 5}) + at::ones({5, 5, 5})" + return + if op_name == "adaptive_max_pool2d_backward": + if index == 0: + arg_map["grad_output"] = "at::rand({2, 2, 2}, at::kFloat)" + arg_map["self"] = "at::rand({2, 2, 2}, at::kFloat)" + arg_map["indices"] = "at::randint(0, 1, {2, 2, 2}, at::kLong)" + else: + arg_map["grad_output"] = "at::rand({3, 3, 3}, at::kFloat)" + arg_map["self"] = "at::rand({3, 3, 3}, at::kFloat)" + arg_map["indices"] = "at::randint(0, 1, {3, 3, 3}, at::kLong)" + return + if op_name == "adaptive_max_pool3d_backward": + if index == 0: + arg_map["grad_output"] = "at::rand({2, 2, 2, 2}, at::kFloat)" + arg_map["self"] = "at::rand({2, 2, 2, 2}, at::kFloat)" + arg_map["indices"] = "at::randint(0, 1, {2, 2, 2, 2}, at::kLong)" + else: + arg_map["grad_output"] = "at::rand({3, 3, 3, 3}, at::kFloat)" + arg_map["self"] = "at::rand({3, 3, 3, 3}, at::kFloat)" + arg_map["indices"] = "at::randint(0, 1, {3, 3, 3, 3}, at::kLong)" + return + if op_name == "bitwise_left_shift": + if index == 0: + arg_map["self"] = "at::randint(1, 1 << 4, {6, 6, 6}, at::kInt)" + arg_map["other"] = "at::randint(1, 26, {6, 6, 6}, at::kInt)" + else: + arg_map["self"] = "at::randint(1, 1 << 4, {22, 22, 22}, at::kInt)" + arg_map["other"] = "at::randint(1, 26, {22, 22, 22}, at::kInt)" + return + if op_name == "bitwise_right_shift": + if index == 0: + arg_map["self"] = "at::randint(1 << 21, 1 << 30, {6, 6, 6}, at::kInt)" + arg_map["other"] = "at::randint(1, 22, {6, 6, 6}, at::kInt)" + else: + arg_map["self"] = "at::randint(1 << 21, 1 << 30, {22, 22, 22}, at::kInt)" + arg_map["other"] = "at::randint(1, 22, {22, 22, 22}, at::kInt)" + return + if op_name == "gather": + if index == 0: + arg_map["self"] = "at::randint(1, 100, {2,2,2}, at::kInt)" + arg_map["dim"] = "1" + arg_map["index"] = "at::randint(0, 1, {2,2,2}, torch::kInt64)" + arg_map["sparse_grad"] = "false" + else: + arg_map["self"] = "at::randint(1, 100, {5,5,5}, at::kInt)" + arg_map["dim"] = "1" + arg_map["index"] = "at::randint(0, 4, {5,5,5}, torch::kInt64)" + arg_map["sparse_grad"] = "false" + return + if op_name == "gelu": + if index == 0: + arg_map["self"] = "at::rand({6, 6, 6})" + arg_map["approximate"] = '"tanh"' + else: + arg_map["self"] = "at::rand({22, 22, 22})" + arg_map["approximate"] = '"tanh"' + return + if op_name == "gelu_backward": + if index == 0: + arg_map["grad_output"] = "at::rand({6, 6, 6})" + arg_map["self"] = "at::rand({6, 6, 6})" + arg_map["approximate"] = '"tanh"' + else: + arg_map["grad_output"] = "at::rand({22, 22, 22})" + arg_map["self"] = "at::rand({22, 22, 22})" + arg_map["approximate"] = '"tanh"' + return + if op_name == "index_add": + if index == 0: + arg_map["self"] = "at::rand({2})" + arg_map["dim"] = "0" + arg_map["index"] = "at::randint(0, 1, {2}, at::kInt)" + arg_map["source"] = "at::rand({2})" + arg_map["alpha"] = "2" + else: + arg_map["self"] = "at::rand({16})" + arg_map["dim"] = "0" + arg_map["index"] = "at::randint(0, 10, {16}, at::kInt)" + arg_map["source"] = "at::rand({16})" + arg_map["alpha"] = "2" + return + if op_name == "index_copy": + if index == 0: + arg_map["self"] = "at::rand({2})" + arg_map["dim"] = "0" + arg_map["index"] = "at::randint(0, 1, {2}, at::kLong)" + arg_map["source"] = "at::rand({2})" + else: + arg_map["self"] = "at::rand({32})" + arg_map["dim"] = "0" + arg_map["index"] = "at::randint(0, 10, {32}, at::kLong)" + arg_map["source"] = "at::rand({32})" + return + if op_name == "linalg_cross": + if index == 0: + arg_map["self"] = "at::rand({6, 3, 6})" + arg_map["other"] = "at::rand({6, 3, 6})" + arg_map["dim"] = "1" + else: + arg_map["self"] = "at::rand({22, 3, 22})" + arg_map["other"] = "at::rand({22, 3, 22})" + arg_map["dim"] = "1" + return + if op_name == "nll_loss_backward": + if index == 0: + arg_map["grad_output"] = "at::rand({})" + arg_map["self"] = "at::rand({6})" + arg_map["target"] = "at::randint(0, 5, {6}, torch::kInt64)" + arg_map["weight"] = "at::rand({6})" + arg_map["reduction"] = "1" + arg_map["ignore_index"] = "1" + arg_map["total_weight"] = "at::rand({})" + else: + arg_map["grad_output"] = "at::rand({})" + arg_map["self"] = "at::rand({36})" + arg_map["target"] = "at::randint(0, 11, {36}, torch::kInt64)" + arg_map["weight"] = "at::rand({36})" + arg_map["reduction"] = "1" + arg_map["ignore_index"] = "1" + arg_map["total_weight"] = "at::rand({})" + return + if op_name in ["scatter", "scatter_add", "_scatter_reduce"]: + if index == 0: + arg_map["self"] = "at::randint(1, 100, {2,2,2}, torch::kInt64)" + arg_map["index"] = "at::randint(0, 1, {2,2,2}, torch::kInt64)" + arg_map["src"] = "at::randint(1, 100, {2,2,2}, torch::kInt64)" + else: + arg_map["self"] = "at::randint(1, 100, {5,5,5}, torch::kInt64)" + arg_map["index"] = "at::randint(0, 1, {5,5,5}, torch::kInt64)" + arg_map["src"] = "at::randint(1, 100, {5,5,5}, torch::kInt64)" + if "reduce" in arg_map: + arg_map["reduce"] = '"sum"' if op_name == "_scatter_reduce" else '"add"' + return + if op_name == "scatter_reduce": + arg_map["reduce"] = '"mean"' + if index == 0: + arg_map["index"] = "at::randint(6, {6, 6, 6}, torch::kInt64)" + else: + arg_map["index"] = "at::randint(22, {22, 22, 22}, torch::kInt64)" + return + if op_name == "special_zeta": + if index == 0: + arg_map["self"] = "at::rand({2,2,2}, at::kDouble) + at::ones({2,2,2})" + arg_map["other"] = "at::rand({2,2,2}, at::kDouble) + at::ones({2,2,2})" + else: + arg_map["self"] = "at::rand({5,5,5}, at::kDouble) + at::ones({5,5,5})" + arg_map["other"] = "at::rand({5,5,5}, at::kDouble) + at::ones({5,5,5})" + return + if op_name == "_convert_indices_from_csr_to_coo": + if index == 0: + arg_map["crow_indices"] = "torch::tensor({1}, torch::kInt32)" + arg_map["col_indices"] = "torch::tensor({0, 1, 0}, torch::kInt32)" + arg_map["out_int32"] = "false" + else: + arg_map["crow_indices"] = "torch::tensor({0}, torch::kInt32)" + arg_map["col_indices"] = ( + "torch::tensor({0, 1, 0, 2, 1, 2, 0, 1, 0, 2, 1, 2}, torch::kInt32)" + ) + arg_map["out_int32"] = "false" + return + if op_name == "_convert_indices_from_coo_to_csr": + if index == 0: + arg_map["self"] = "at::randint(0, 3, {2}, at::kInt)" + arg_map["size"] = "10" + arg_map["out_int32"] = "false" + else: + arg_map["self"] = "at::randint(0, 3, {12}, at::kInt)" + arg_map["size"] = "24" + arg_map["out_int32"] = "false" + return + if op_name in ("diagonal", "linalg_diagonal"): + arg_map["offset"] = "0" + arg_map["dim1"] = "2" + arg_map["dim2"] = "1" + return diff --git a/.venv/lib/python3.12/site-packages/torchgen/static_runtime/gen_static_runtime_ops.py b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/gen_static_runtime_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d6909bc4d7f67fc13fb9f61e00f4709a4ff5ad4e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/gen_static_runtime_ops.py @@ -0,0 +1,231 @@ +from __future__ import annotations + +import argparse +import itertools +import os +from typing import TYPE_CHECKING, TypeVar + +from libfb.py.log import set_simple_logging # type: ignore[import] + +from torchgen import gen +from torchgen.context import native_function_manager +from torchgen.model import DispatchKey, NativeFunctionsGroup, NativeFunctionsViewGroup +from torchgen.static_runtime import config, generator + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +# Given a list of `grouped_native_functions` sorted by their op names, return a list of +# lists each of which groups ops that share the base name. For example, `mean` and +# `mean.dim` are grouped together by this function. + +NativeGroupT = TypeVar( + "NativeGroupT", + bound=NativeFunctionsGroup | NativeFunctionsViewGroup, +) + + +def group_functions_by_op_name( + grouped_native_functions: Sequence[NativeGroupT], +) -> Sequence[Sequence[NativeGroupT]]: + if not grouped_native_functions: + return [] + groups = [] + + def is_supported(g: NativeFunctionsGroup | NativeFunctionsViewGroup) -> bool: + with native_function_manager(g): + return generator.is_supported(g) + + eligible_ops = (g for g in grouped_native_functions if is_supported(g)) + groups = [ + list(group) + for k, group in ( + itertools.groupby( + eligible_ops, + key=config.func_name_base_str, + ) + ) + ] + + return groups + + +def clang_format(cpp_file_path: str) -> None: + import subprocess + + subprocess.check_call(["clang-format", "-i", cpp_file_path]) + + +def write_cpp(cpp_ops: Sequence[str], file_path: str) -> None: + code = "\n".join(cpp_ops) + generated = f"""// @lint-ignore-every CLANGTIDY HOWTOEVEN +// AUTO-GENERATED FROM: torchgen/static_runtime/gen_static_runtime_ops.py +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch {{ +namespace jit {{ + +{code} + +}} // namespace jit +}} // namespace torch +""" + with open(file_path, "w") as f: + f.write(generated) + clang_format(file_path) + + +def write_test_cpp(cpp_ops: Sequence[str], file_path: str) -> None: + code = "\n".join(cpp_ops) + generated = f"""// @lint-ignore-every CLANGTIDY HOWTOEVEN +// AUTO-GENERATED FROM: torchgen/static_runtime/gen_static_runtime_ops.py +#include +#include +#include + +#include "test_utils.h" + +using namespace caffe2; +using namespace torch; +using namespace torch::jit; +using namespace torch::jit::test; +using c10::IValue; + +{code} + +""" + with open(file_path, "w") as f: + f.write(generated) + clang_format(file_path) + + +def main() -> None: + parser = argparse.ArgumentParser(description="Generate ATen source files") + parser.add_argument( + "-s", + "--source-path", + help="path to source directory for ATen", + default="caffe2/aten/src/ATen", + ) + parser.add_argument( + "-p", + "--generated-ops-cpp-path", + help="path to directory to generate op dispatcher .cpp file", + default="caffe2/torch/csrc/jit/runtime/static/generated_ops.cpp", + ) + parser.add_argument( + "-t", + "--generated-ops-test-cpp-path", + help="path to directory to generate op dispatcher .cpp file", + default="caffe2/benchmarks/static_runtime/test_generated_ops.cc", + ) + options = parser.parse_args() + native_yaml_path = os.path.join(options.source_path, "native/native_functions.yaml") + tags_yaml_path = os.path.join(options.source_path, "native/tags.yaml") + parsed_yaml = gen.parse_native_yaml(native_yaml_path, tags_yaml_path) + native_functions, backend_indices = ( + parsed_yaml.native_functions, + parsed_yaml.backend_indices, + ) + + op_generator = generator.GenOpDispatcher() + test_case_generator = generator.GenOpTestCase() + + native_functions_groups = [ + g + for g in gen.get_grouped_native_functions(native_functions) + if isinstance(g, NativeFunctionsGroup) + ] + + supported_functions_groups = group_functions_by_op_name(native_functions_groups) + + out_variant_op_result = [ + op_generator.out_variant(groups, backend_indices[DispatchKey.CPU]) + for groups in supported_functions_groups + ] + out_variant_test_result = [ + test_case_generator.out_variant(groups) for groups in supported_functions_groups + ] + + native_functions_view_groups = [ + g + for g in gen.get_grouped_by_view_native_functions(native_functions) + if isinstance(g, NativeFunctionsViewGroup) + ] + + supported_functions_view_groups = group_functions_by_op_name( + native_functions_view_groups + ) + + view_op_result = [ + op_generator.view(groups, backend_indices[DispatchKey.CPU]) + for groups in supported_functions_view_groups + ] + view_test_result = [ + test_case_generator.view(groups) for groups in supported_functions_view_groups + ] + + op_result = out_variant_op_result + ["\n\n"] + view_op_result + test_result = out_variant_test_result + ["\n\n"] + view_test_result + + write_cpp(op_result, options.generated_ops_cpp_path) + write_test_cpp(test_result, options.generated_ops_test_cpp_path) + + print( + f"\ntotal grouped native ops: {len(gen.get_grouped_native_functions(native_functions)):d}" + ) + + print(f"grouped native ops with out variant: {len(native_functions_groups):d}") + supported_functions_num = sum(len(groups) for groups in supported_functions_groups) + print(f"generated functions groups with out variant: {supported_functions_num:d}") + + print(f"\nview grouped native ops: {len(native_functions_view_groups):d}") + supported_view_functions_num = sum( + len(groups) for groups in supported_functions_view_groups + ) + print(f"generated functions view groups: {supported_view_functions_num:d}") + + print( + f"\noverall generated : {supported_functions_num + supported_view_functions_num:d}" + ) + + +if __name__ == "__main__": + set_simple_logging(escape_newlines=False) + main() diff --git a/.venv/lib/python3.12/site-packages/torchgen/static_runtime/generator.py b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/generator.py new file mode 100644 index 0000000000000000000000000000000000000000..d8aba4d13bcde6cf4a2a4700c93e61237632912c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/static_runtime/generator.py @@ -0,0 +1,859 @@ +from __future__ import annotations + +import json +import logging +import math +from typing import TYPE_CHECKING + +import torchgen.api.cpp as cpp +from torchgen.context import native_function_manager +from torchgen.model import ( + Argument, + BackendIndex, + BaseTy, + BaseType, + FunctionSchema, + NativeFunctionsGroup, + NativeFunctionsViewGroup, + OptionalType, + SelfArgument, + TensorOptionsArguments, + Type, +) +from torchgen.static_runtime import config + + +if TYPE_CHECKING: + from collections.abc import Sequence + + +logger: logging.Logger = logging.getLogger() + + +def has_alias( + arguments: Sequence[Argument | SelfArgument | TensorOptionsArguments], +) -> bool: + for arg in arguments: + annotation = getattr(arg, "annotation", None) + if not annotation: + continue + alias_set = getattr(annotation, "alias_set", ()) + if alias_set: + return True + return False + + +BLOCKED_OPS = frozenset( + ( + # non cpu ops + "sparse_sampled_addmm", + "hspmm", + "linalg_svdvals", + # sparse ops + "sspaddmm", + "coalesce", + "_indices", + "indices", + "_values", + "values", + "crow_indices", + "col_indices", + # deprecated ops + "floor_divide", + "ger", + # buggy ops + "conj_physical", # P495807361 + "binary_cross_entropy", # P496394764 + "arccosh", + # uncommon ops + "cholesky", + "lu_solve", + "linalg_cholesky", + "linalg_householder_product", + "linalg_ldl_solve", + "_compute_linear_combination", + # training related ops + "_make_dual", + # cannot call directly + "_fw_primal", + # no documentation + "_index_reduce", + # TODO: these ones got added recently and need manual inspection + "_new_zeros_with_same_feature_meta", + "_conj_physical", + "binary_cross_entropy_with_logits", + "bincount", + "conv_tbc", + "copy", + "_copy_from", + "_copy_from_and_resize", + "count_nonzero", + "cudnn_affine_grid_generator", + "cudnn_affine_grid_generator_backward", + "cudnn_grid_sampler", + "diag_embed", + "embedding", + "embedding_dense_backward", + "_embedding_bag_dense_backward", + "_embedding_bag_per_sample_weights_backward", + "grid_sampler_2d", + "_grid_sampler_2d_cpu_fallback", + "grid_sampler_3d", + "isnan", + "mkldnn_linear", + "median", + "nanmedian", + "_sparse_sparse_matmul", + "batch_norm_backward_elemt", + "_euclidean_dist", + "pixel_shuffle", + "pixel_unshuffle", + "channel_shuffle", + "_reshape_nested_backward", + "relu", + "prelu", + "celu", + "slice_scatter", + "select_scatter", + "diagonal_scatter", + "sum", + "_mkldnn_transpose", + "_nested_tensor_from_mask", + "_nested_from_padded", + "_nested_tensor_size", + "_nested_from_padded_and_nested_example", + "_standard_gamma_grad", + "_dirichlet_grad", + "native_norm", + "_sparse_softmax", + "_sparse_softmax_backward_data", + "_sparse_log_softmax", + "_sparse_log_softmax_backward_data", + "zero", + "_sparse_addmm", + "sparse_mask", + "_sparse_mask_projection", + "_to_dense", + "_coalesce", + "_coalesced", + "copy_sparse_to_sparse", + "to_sparse", + "to_sparse_csr", + "to_sparse_csc", + "to_mkldnn", + "quantize_per_tensor_dynamic", + "quantize_per_channel", + "q_per_channel_scales", + "q_per_channel_zero_points", + "int_repr", + "_make_per_channel_quantized_tensor", + "set", + "lift", + "lift_fresh", + "lift_fresh_copy", + "masked_scatter", + "_masked_softmax", + "_masked_softmax_backward", + "put", + "index_reduce", + "trace", + "_cholesky_solve_helper", + "dist", + "max", + "_torch_cuda_cu_linker_symbol_op", + "glu_jvp", + "glu_backward_jvp", + "hardswish_backward", + "rrelu_with_noise_backward", + "mkldnn_adaptive_avg_pool2d_backward", + "_adaptive_avg_pool2d_backward", + "_adaptive_avg_pool3d_backward", + "isinf", + "linalg_lu_solve", + "linalg_vecdot", + "linalg_matrix_exp", + "linalg_eigvalsh", + "_test_warn_in_autograd", + "_test_autograd_multiple_dispatch_view", + "_test_autograd_multiple_dispatch_view_copy", + "_segment_reduce", + "_segment_reduce_backward", + "_fw_primal_copy", + "_make_dual_copy", + "view_as_real_copy", + "view_as_complex_copy", + "_conj_copy", + "_neg_view_copy", + "diagonal_copy", + "detach_copy", + "squeeze_copy", + "t_copy", + "unsqueeze_copy", + "_indices_copy", + "_values_copy", + "indices_copy", + "values_copy", + "crow_indices_copy", + "col_indices_copy", + "ccol_indices", + "ccol_indices_copy", + "row_indices", + "row_indices_copy", + "unfold_copy", + "alias_copy", + "_triton_multi_head_attention", + "special_airy_ai", + "special_bessel_j0", + "special_bessel_j1", + "special_bessel_y0", + "special_bessel_y1", + "special_chebyshev_polynomial_t", + "special_chebyshev_polynomial_u", + "special_chebyshev_polynomial_v", + "special_chebyshev_polynomial_w", + "special_hermite_polynomial_h", + "special_hermite_polynomial_he", + "special_laguerre_polynomial_l", + "special_legendre_polynomial_p", + "special_modified_bessel_i0", + "special_modified_bessel_i1", + "special_modified_bessel_k0", + "special_modified_bessel_k1", + "special_scaled_modified_bessel_k0", + "special_scaled_modified_bessel_k1", + "special_shifted_chebyshev_polynomial_t", + "special_shifted_chebyshev_polynomial_u", + "special_shifted_chebyshev_polynomial_v", + "special_shifted_chebyshev_polynomial_w", + "special_spherical_bessel_j0", + "_foobar", + "_nested_tensor_strides", + "_nested_tensor_storage_offsets", + "_nested_get_values", # no CPU backend + "_nested_get_values_copy", # no CPU backend + "_nested_view_from_jagged", # testing needs to be patched + "_nested_view_from_jagged_copy", # testing needs to be patched + "_nested_view_from_buffer", # testing needs to be patched + "_nested_view_from_buffer_copy", # testing needs to be patched + "_int_mm", # testing needs to be patched + "_to_sparse_csc", # testing needs to be patched + "_to_sparse_csr", # testing needs to be patched + "segment_reduce", # testing needs to be patched + ) +) + + +def is_supported(g: NativeFunctionsGroup | NativeFunctionsViewGroup) -> bool: + base_op_name = "" + func = None + if isinstance(g, NativeFunctionsViewGroup): + base_op_name = g.view.root_name + func = g.view.func + else: + base_op_name = g.out.func.name.name.base + func = g.out.func + if config.is_hand_written(g): + logger.info("HAND WRITTEN: %s", base_op_name) + return False + if base_op_name in BLOCKED_OPS: + logger.info("BLOCKED: %s", base_op_name) + return False + for arg in func.schema_order_arguments(): + maybe_method = ivalue_type_conversion_method(arg.type) + if not maybe_method: + # Type converting is unsupported yet. + logger.info("NOT SUPPORTED TYPE CONVERTING: %s", func) + return False + + if isinstance(g, NativeFunctionsViewGroup): + # TODO: stop doing type tests by converting to C++ and then testing + # the string, just test the dang thing directly + if "at::Tensor" != cpp.returns_type(func.returns, symint=False).cpp_type(): + # Returns a non-Tensor value. + logger.info("NON-TENSOR RET TYPE: %s", func) + return False + return True + + # For out variant ops, we need to check the arguments of its functional func. + for arg in g.functional.func.schema_order_arguments(): + maybe_method = ivalue_type_conversion_method(arg.type) + if not maybe_method: + # Type converting is unsupported yet. + logger.info("NOT SUPPORTED TYPE CONVERTING: %s", g.functional.func) + return False + + if not g.structured: + # In case of unstructured op, we check if it has out variant implementation. + # The out variant implementation satisfies the minimum requirement that it has the output tensor as the last + # parameter. + if ( + not hasattr(g, "out") + or not str(func).endswith("Tensor(a!) out) -> Tensor(a!)") + or not str(func.name).endswith(".out") + ): + return False + # TODO: stop type testing by converting to C++ + if "at::Tensor &" != cpp.returns_type(func.returns, symint=False).cpp_type(): + logger.info("NON_TENSOR RET TYPE: %s", func) + return False + if has_alias(func.arguments.non_out): + # This op may create an alias of inputs. + logger.info("INPUTS ALIAS: %s", base_op_name) + return False + return True + + +def ivalue_type_conversion_method( + arg_type: BaseType | OptionalType | Type, +) -> tuple[bool, str] | None: + """ + Return the method call expression of `c10::ivalue' to convert its contained value to + the expected value of `arg_type` type. For example, for `arg_type` == BaseTy.Tensor, + this function returns ".toTensor()", so that it can be appended to the ivalue's + variable name to get the value of the expected type. + """ + type_conversion_methods = { + BaseTy.Tensor: ((True, "toTensor()"), (False, "toOptional()")), + BaseTy.int: ((False, "toInt()"), (False, "toOptional()")), + BaseTy.bool: ((False, "toBool()"), (False, "toOptional()")), + BaseTy.Scalar: ((False, "toScalar()"), (False, "toOptional()")), + BaseTy.ScalarType: ( + (False, "toScalarType()"), + (False, "toOptional()"), + ), + BaseTy.str: ( + (False, "toStringView()"), + (False, "toOptional()"), + (False, "toOptional<::std::string_view>()"), + ), + } + + base_ty_object = None + if isinstance(arg_type, BaseType): + base_ty_object = arg_type.name + elif isinstance(arg_type, OptionalType): + if not isinstance(arg_type.elem, BaseType): + # ListType is currently unsupported. + return None + base_ty_object = arg_type.elem.name + else: + return None + + if base_ty_object not in type_conversion_methods: + return None + methods = type_conversion_methods[base_ty_object] + if isinstance(arg_type, BaseType): + return methods[0] + return methods[1] + + +should_use_int_tensor_ops_ = frozenset( + ( + "bitwise_not", + "bitwise_and", + "bitwise_or", + "bitwise_xor", + "bitwise_left_shift", + "bitwise_right_shift", + "gcd", + "lcm", + "scatter", + "gather", + "_convert_indices_from_coo_to_csr", + "_convert_indices_from_csr_to_coo", + ) +) +should_use_complex_tensor_ops_ = frozenset(("view_as_real", "imag", "_conj")) + + +def should_use_int_tensor(op_name: str) -> bool: + return op_name in should_use_int_tensor_ops_ + + +def should_use_complex_tensor(op_name: str) -> bool: + return op_name in should_use_complex_tensor_ops_ + + +test_tensor_dim_ops_1_ = frozenset( + ( + "addmv", + "index_add", + "_convert_indices_from_coo_to_csr", + "_convert_indices_from_csr_to_coo", + "nll_loss_backward", + "dot", + "vdot", + "outer", + "ger", + ) +) +test_tensor_dim_ops_2_ = frozenset( + ("addmm", "mm", "nuclear_norm", "diag", "_addmm_activation", "matrix_H", "t") +) + + +def test_tensor_dim(op_name: str) -> int: + if op_name in test_tensor_dim_ops_1_: + return 1 + if op_name in test_tensor_dim_ops_2_: + return 2 + return 3 + + +test_tensor_shapes_string = '{"view_as_complex": "{2, 2}"}' +test_tensor_shape_json: dict[str, str] = json.loads(test_tensor_shapes_string) + + +def test_tensor_shape(op_name: str) -> str: + if op_name in test_tensor_shape_json: + return test_tensor_shape_json[op_name] + else: + return "" + + +def test_value_expression( + arg_type: BaseType | OptionalType | Type, index: int, op_name: str +) -> str: + tensor_size_ex = test_tensor_shape(op_name) + if tensor_size_ex == "": + num_tensors = 16 if index == 0 else 64 + num_dim = test_tensor_dim(op_name) + size_per_dim = math.ceil(num_tensors / float(num_dim)) + size_per_dim += size_per_dim % 2 + tensor_size_ex = "{{{}}}".format(",".join([f"{size_per_dim}"] * num_dim)) + if should_use_int_tensor(op_name): + tensor_expression = f"at::randint(1, 100, {tensor_size_ex}, at::kInt)" + elif should_use_complex_tensor(op_name): + tensor_expression = f"at::randn({tensor_size_ex}, at::kComplexFloat)" + else: + tensor_expression = f"at::rand({tensor_size_ex})" + + value_expressions = { + BaseTy.Tensor: tensor_expression, + BaseTy.int: "1", + BaseTy.bool: "false", + BaseTy.Scalar: "2", + BaseTy.ScalarType: "at::ScalarType::Float", + BaseTy.str: '"floor"', + } + + base_ty_object = None + if isinstance(arg_type, BaseType): + base_ty_object = arg_type.name + else: + if not ( + isinstance(arg_type, OptionalType) and isinstance(arg_type.elem, BaseType) + ): + raise AssertionError( + f"Expected OptionalType with BaseType elem, got {type(arg_type)}" + ) + base_ty_object = arg_type.elem.name + if base_ty_object not in value_expressions: + raise AssertionError(f"Unexpected type: {base_ty_object}") + value_expression = value_expressions[base_ty_object] + return value_expression + + +def generate_test_value_definitions(schema: FunctionSchema, index: int) -> str: + if schema.is_out_fn(): + raise AssertionError(f"Expected non-out function, got {schema}") + schema_name = schema.name.name.base + arg_map = {} + for arg in schema.schema_order_arguments(): + test_value_exp = test_value_expression(arg.type, index, schema_name) + arg_map[arg.name] = test_value_exp + config.override_test_values(arg_map, schema_name, index) + arg_populations = [] + for arg_name, arg_value in arg_map.items(): + arg_populations.append(f"auto {arg_name}{index} = {arg_value}") + return ";\n ".join(arg_populations) + ";" + + +def generate_test_value_names(schema: FunctionSchema, index: int) -> str: + if schema.is_out_fn(): + raise AssertionError(f"Expected non-out function, got {schema}") + return ",".join(f"{arg.name}{index}" for arg in schema.schema_order_arguments()) + + +generate_test_ir_arguments_base_ty_to_type_str_ = { + BaseTy.Tensor: "Tensor", + BaseTy.int: "int", + BaseTy.float: "float", + BaseTy.str: "str", + BaseTy.Scalar: "int", + BaseTy.ScalarType: "int", + BaseTy.bool: "bool", +} + + +def generate_test_ir_arguments( + schema: FunctionSchema, +) -> list[tuple[str, str | None]]: + def ir_argument(arg: Argument) -> tuple[str, str | None]: + t = arg.type + add_optional = False + if isinstance(t, OptionalType): + t = t.elem + add_optional = True + if not isinstance(t, BaseType): + raise AssertionError(f"Expected BaseType, got {type(t)}") + type_str = None + if t.name in generate_test_ir_arguments_base_ty_to_type_str_: + type_str = generate_test_ir_arguments_base_ty_to_type_str_[t.name] + if type_str and add_optional: + type_str = f"{type_str}?" + return ("%" + arg.name, type_str) + + return [ir_argument(arg) for arg in schema.schema_order_arguments()] + + +def generate_arg_extraction(schema: FunctionSchema) -> str: + arg_populations = [] + for i, arg in enumerate(schema.schema_order_arguments()): + maybe_method = ivalue_type_conversion_method(arg.type) + if not maybe_method: + raise AssertionError( + f"No type conversion method for {arg.name}: {arg.type}" + ) + is_reference, type_conversion_method = maybe_method + reference = "&" if is_reference else "" + arg_populations.append( + f"const auto{reference} {arg.name} = p_node->Input({i}).{type_conversion_method}" + ) + return ";\n ".join(arg_populations) + ";" + + +def get_kernel_name(g: NativeFunctionsGroup, backend_index: BackendIndex) -> str: + kernel = backend_index.get_kernel(g.functional) + if g.structured or kernel is None: + return cpp.name(g.functional.func) + return kernel.kernel + + +def get_out_kernel_name(g: NativeFunctionsGroup, backend_index: BackendIndex) -> str: + kernel = backend_index.get_kernel(g.out) + if g.structured or kernel is None: + return cpp.name(g.out.func) + return kernel.kernel + + +def generate_non_out_variant_call( + g: NativeFunctionsGroup, backend_index: BackendIndex +) -> str: + schema = g.functional.func + if schema.is_out_fn(): + raise AssertionError(f"Expected non-out function, got {schema}") + kernel_name = get_kernel_name(g, backend_index) + arg_names = (arg.name for arg in schema.schema_order_arguments()) + namespace_name = "cpu" if g.structured else "native" + return f"at::{namespace_name}::{kernel_name}({','.join(arg_names)})" + + +def generate_call_to_view_ops( + g: NativeFunctionsViewGroup, backend_index: BackendIndex +) -> str: + schema = g.view.func + kernel_name = cpp.name(schema) + kernel = backend_index.get_kernel(g.view) + if kernel: + kernel_name = kernel.kernel + arg_names = (arg.name for arg in schema.schema_order_arguments()) + namespace_name = "native" + return f"at::{namespace_name}::{kernel_name}({','.join(arg_names)})" + + +def generate_out_variant_call( + g: NativeFunctionsGroup, backend_index: BackendIndex +) -> str: + schema = g.out.func + if not schema.is_out_fn(): + raise AssertionError(f"Expected out function, got {schema}") + arg_names = [] + kernel_name = get_out_kernel_name(g, backend_index) + if g.structured: + # structured op starts with the output tensor argument. + arg_names = [out_arg.name for out_arg in schema.arguments.out] + else: + arg_names = [] + for arg in schema.arguments.non_out: + if isinstance(arg, SelfArgument): + arg_names.append(arg.argument.name) + else: + if not isinstance(arg, Argument): + raise AssertionError(f"Expected Argument, got {type(arg)}") + arg_names.append(arg.name) + if not g.structured: + if len(schema.arguments.out) != 1: + raise AssertionError( + f"Expected 1 out argument, got {len(schema.arguments.out)}" + ) + arg_names.append(schema.arguments.out[0].name) + cpp_arg_names = ",".join(arg_names) + namespace_name = "cpu" if g.structured else "native" + return f"at::{namespace_name}::{kernel_name}({cpp_arg_names})" + + +no_memory_resize_ops = frozenset( + ( + "isin.Scalar_Tensor", + "index_add", + "dot", + "vdot", + "nuclear_norm", + "histc", + "l1_loss", + "multi_margin_loss", + "multilabel_margin_loss", + "nll_loss", + "nll_loss2d", + "prod", + ) +) + + +def should_check_resize(schema: FunctionSchema) -> bool: + schema_str = str(schema) + type_variant_op_name = schema_str[: schema_str.find("(")] + return type_variant_op_name not in no_memory_resize_ops + + +def op_name_from_group(g: NativeFunctionsGroup) -> str: + return g.functional.func.name.name.base + + +class GenOpDispatcher: + def out_variant( + self, groups: Sequence[NativeFunctionsGroup], backend_index: BackendIndex + ) -> str: + if not groups: + return "" + generated_type_variants = [] + for g in groups: + with native_function_manager(g): + if not is_supported(g): + raise AssertionError(f"Unsupported function group: {g}") + if not isinstance(g, NativeFunctionsGroup): + raise AssertionError( + f"Expected NativeFunctionsGroup, got {type(g)}" + ) + generated_type_variant = self.out_variant_op_generator(g, backend_index) + generated_type_variants.append(generated_type_variant) + op_name = op_name_from_group(groups[0]) + body = "\n".join(generated_type_variants) + generated = f""" +REGISTER_OPERATOR_FUNCTOR( + aten::{op_name}, + aten_{op_name}, + [](Node* n) -> SROperator {{ + {body} + LogAndDumpSchema(n); + return nullptr; + }}) +""" + return generated + + def view( + self, groups: Sequence[NativeFunctionsViewGroup], backend_index: BackendIndex + ) -> str: + if not groups: + return "" + generated_type_variants = [] + for g in groups: + with native_function_manager(g): + if not is_supported(g): + raise AssertionError(f"Unsupported view group: {g}") + if not isinstance(g, NativeFunctionsViewGroup): + raise AssertionError( + f"Expected NativeFunctionsViewGroup, got {type(g)}" + ) + generated_type_variant = self.view_op_generator(g, backend_index) + generated_type_variants.append(generated_type_variant) + op_name = config.func_name_base_str(groups[0]) + body = "\n".join(generated_type_variants) + generated = f""" +REGISTER_NATIVE_OPERATOR_FUNCTOR( + aten::{op_name}, + aten_{op_name}, + [](Node* n) -> SROperator {{ + {body} + LogAndDumpSchema(n); + return nullptr; + }}); +""" + return generated + + def out_variant_op_generator( + self, g: NativeFunctionsGroup, backend_index: BackendIndex + ) -> str: + functional = g.functional + schema = str(functional.func) + populated_argument = generate_arg_extraction(g.functional.func) + functional_variant_call = generate_non_out_variant_call(g, backend_index) + if len(g.out.func.arguments.out) != 1: + raise AssertionError( + f"Expected 1 out argument, got {len(g.out.func.arguments.out)}" + ) + out_variable_name = str(g.out.func.arguments.out[0].name) + out_variant_call = generate_out_variant_call(g, backend_index) + generated = f""" + if (n->matches(torch::schema("aten::{schema}"))) {{ + return [](ProcessedNode* p_node) {{ + {populated_argument} + if (p_node->Output(0).isNone()) {{ + p_node->Output(0) = {functional_variant_call}; + return; + }} + auto& {out_variable_name} = p_node->Output(0).toTensor(); + fastResizeToZero({out_variable_name}); + {out_variant_call}; + }}; + }}""" + return generated + + def view_op_generator( + self, g: NativeFunctionsViewGroup, backend_index: BackendIndex + ) -> str: + schema = str(g.view.func) + populated_argument = generate_arg_extraction(g.view.func) + functional_variant_call = generate_call_to_view_ops(g, backend_index) + generated = f""" + if (n->matches(torch::schema("aten::{schema}"))) {{ + return [](ProcessedNode* p_node) {{ + {populated_argument} + p_node->Output(0) = {functional_variant_call}; + }}; + }}""" + return generated + + +class GenOpTestCase: + def out_variant(self, groups: Sequence[NativeFunctionsGroup]) -> str: + if not groups: + return "" + generated_type_variants = [] + for g in groups: + with native_function_manager(g): + if not is_supported(g): + raise AssertionError(f"Unsupported function group: {g}") + if not isinstance(g, NativeFunctionsGroup): + raise AssertionError( + f"Expected NativeFunctionsGroup, got {type(g)}" + ) + generated_type_variant = self.out_variant_op_test_case_generator(g) + generated_type_variants.append(generated_type_variant) + return "\n".join(generated_type_variants) + + def view(self, groups: Sequence[NativeFunctionsViewGroup]) -> str: + if not groups: + return "" + generated_type_variants = [] + for g in groups: + with native_function_manager(g): + if not is_supported(g): + raise AssertionError(f"Unsupported view group: {g}") + if not isinstance(g, NativeFunctionsViewGroup): + raise AssertionError( + f"Expected NativeFunctionsViewGroup, got {type(g)}" + ) + generated_type_variant = self.view_op_test_case_generator(g) + generated_type_variants.append(generated_type_variant) + return "\n".join(generated_type_variants) + + def out_variant_op_test_case_generator(self, g: NativeFunctionsGroup) -> str: + schema = g.functional.func + schema_str = str(schema) + if schema_str.find("(") <= 0: + raise AssertionError(f"Invalid schema string: {schema_str}") + type_variant_op_name = schema_str[: schema_str.find("(")].replace(".", "_") + op_name = op_name_from_group(g) + if not type_variant_op_name.startswith(op_name): + raise AssertionError( + f"Type variant op name {type_variant_op_name} doesn't start with {op_name}" + ) + + arg_types = generate_test_ir_arguments(schema) + arg_declarations = ", ".join( + ( + arg_name if arg_type is None else f"{arg_name}: {arg_type}" + for arg_name, arg_type in arg_types + ) + ) + arg_names = ", ".join((arg_name for arg_name, _ in arg_types)) + if not ( + len(schema.returns) == 1 + and isinstance(schema.returns[0].type, BaseType) + and schema.returns[0].type.name is BaseTy.Tensor + ): + raise AssertionError(f"Expected single Tensor return, got {schema.returns}") + test_value_definitions = generate_test_value_definitions(schema, 0) + test_value_names = generate_test_value_names(schema, 0) + test_value_definitions2 = generate_test_value_definitions(schema, 1) + test_value_names2 = generate_test_value_names(schema, 1) + check_resize = "true" if should_check_resize(schema) else "false" + generated = f""" +TEST(StaticRuntime, autogen_{type_variant_op_name}) {{ + const std::string script = R"IR( + graph({arg_declarations}): + %bias: None = prim::Constant() + %ret = aten::{op_name}({arg_names}) + %cloned = aten::clone(%ret, %bias) + return (%cloned) + )IR"; + + {test_value_definitions} + std::vector args{{{test_value_names}}}; + testStaticRuntime(script, args, {{}}, /*use_allclose=*/false, /*use_equalnan=*/false, /*check_resize=*/{check_resize}); + + {test_value_definitions2} + std::vector args2{{{test_value_names2}}}; + testStaticRuntime(script, args, args2, /*use_allclose=*/false, /*use_equalnan=*/false, /*check_resize=*/{check_resize}); + +}} +""" + return generated + + def view_op_test_case_generator(self, g: NativeFunctionsViewGroup) -> str: + schema = g.view.func + schema_str = str(schema) + if schema_str.find("(") <= 0: + raise AssertionError(f"Invalid schema string: {schema_str}") + type_variant_op_name = schema_str[: schema_str.find("(")].replace(".", "_") + op_name = g.view.root_name + if not type_variant_op_name.startswith(op_name): + raise AssertionError( + f"Type variant op name {type_variant_op_name} doesn't start with {op_name}" + ) + + arg_types = generate_test_ir_arguments(schema) + arg_declarations = ", ".join( + ( + arg_name if arg_type is None else f"{arg_name}: {arg_type}" + for arg_name, arg_type in arg_types + ) + ) + arg_names = ", ".join((arg_name for arg_name, _ in arg_types)) + if not ( + len(schema.returns) == 1 + and isinstance(schema.returns[0].type, BaseType) + and schema.returns[0].type.name is BaseTy.Tensor + ): + raise AssertionError(f"Expected single Tensor return, got {schema.returns}") + test_value_definitions = generate_test_value_definitions(schema, 0) + test_value_names = generate_test_value_names(schema, 0) + generated = f""" +TEST(StaticRuntime, autogen_{type_variant_op_name}) {{ + const std::string script = R"IR( + graph({arg_declarations}): + %bias: None = prim::Constant() + %ret = aten::{op_name}({arg_names}) + %cloned = aten::clone(%ret, %bias) + return (%cloned) + )IR"; + + {test_value_definitions} + std::vector args{{{test_value_names}}}; + testStaticRuntime(script, args); +}} +""" + + return generated diff --git a/.venv/lib/python3.12/site-packages/torchgen/utils.py b/.venv/lib/python3.12/site-packages/torchgen/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..46deafe41b021ad19ce8ca7322e1a3ba3374c3f4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/utils.py @@ -0,0 +1,523 @@ +from __future__ import annotations + +import contextlib +import functools +import hashlib +import os +import re +import sys +import textwrap +from dataclasses import is_dataclass +from enum import auto, Enum +from pathlib import Path +from pprint import pformat +from typing import Any, Generic, TYPE_CHECKING, TypeVar +from typing_extensions import assert_never, Self + +from torchgen.code_template import CodeTemplate + + +if TYPE_CHECKING: + from argparse import Namespace + from collections.abc import Callable, Iterable, Iterator, Sequence + + +TORCHGEN_ROOT = Path(__file__).absolute().parent +REPO_ROOT = TORCHGEN_ROOT.parent + + +# Many of these functions share logic for defining both the definition +# and declaration (for example, the function signature is the same), so +# we organize them into one function that takes a Target to say which +# code we want. +# +# This is an OPEN enum (we may add more cases to it in the future), so be sure +# to explicitly specify with Literal[Target.XXX] or Literal[Target.XXX, Target.YYY] +# what targets are valid for your use. +class Target(Enum): + # top level namespace (not including at) + DEFINITION = auto() + DECLARATION = auto() + # TORCH_LIBRARY(...) { ... } + REGISTRATION = auto() + # namespace { ... } + ANONYMOUS_DEFINITION = auto() + # namespace cpu { ... } + NAMESPACED_DEFINITION = auto() + NAMESPACED_DECLARATION = auto() + + +# Matches "foo" in "foo, bar" but not "foobar". Used to search for the +# occurrence of a parameter in the derivative formula +IDENT_REGEX = r"(^|\W){}($|\W)" + + +# TODO: Use a real parser here; this will get bamboozled +def split_name_params(schema: str) -> tuple[str, list[str]]: + m = re.match(r"(\w+)(\.\w+)?\((.*)\)", schema) + if m is None: + raise RuntimeError(f"Unsupported function schema: {schema}") + name, _, params = m.groups() + return name, params.split(", ") + + +T = TypeVar("T") +S = TypeVar("S") + +# These two functions purposely return generators in analogy to map() +# so that you don't mix up when you need to list() them + + +# Map over function that may return None; omit Nones from output sequence +def mapMaybe(func: Callable[[T], S | None], xs: Iterable[T]) -> Iterator[S]: + for x in xs: + r = func(x) + if r is not None: + yield r + + +# Map over function that returns sequences and cat them all together +def concatMap(func: Callable[[T], Sequence[S]], xs: Iterable[T]) -> Iterator[S]: + for x in xs: + yield from func(x) + + +# Conveniently add error context to exceptions raised. Lets us +# easily say that an error occurred while processing a specific +# context. +@contextlib.contextmanager +def context(msg_fn: Callable[[], str]) -> Iterator[None]: + try: + yield + except Exception as e: + # TODO: this does the wrong thing with KeyError + msg = msg_fn() + msg = textwrap.indent(msg, " ") + msg = f"{e.args[0]}\n{msg}" if e.args else msg + e.args = (msg,) + e.args[1:] + raise + + +@functools.cache +def _read_template(template_fn: str) -> CodeTemplate: + return CodeTemplate.from_file(template_fn) + + +# String hash that's stable across different executions, unlike builtin hash +def string_stable_hash(s: str) -> int: + sha1 = hashlib.sha1(s.encode("latin1"), usedforsecurity=False).digest() + return int.from_bytes(sha1, byteorder="little") + + +# A small abstraction for writing out generated files and keeping track +# of what files have been written (so you can write out a list of output +# files) +class FileManager: + def __init__( + self, + install_dir: str | Path, + template_dir: str | Path, + dry_run: bool, + ) -> None: + self.install_dir = Path(install_dir) + self.template_dir = Path(template_dir) + self.files: set[Path] = set() + self.dry_run = dry_run + + @property + def filenames(self) -> frozenset[str]: + return frozenset({file.as_posix() for file in self.files}) + + def _write_if_changed(self, filename: str | Path, contents: str) -> None: + file = Path(filename) + old_contents: str | None = None + try: + old_contents = file.read_text(encoding="utf-8") + except OSError: + pass + if contents != old_contents: + # Create output directory if it doesn't exist + file.parent.mkdir(parents=True, exist_ok=True) + file.write_text(contents, encoding="utf-8") + + # Read from template file and replace pattern with callable (type could be dict or str). + def substitute_with_template( + self, + template_fn: str | Path, + env_callable: Callable[[], str | dict[str, Any]], + ) -> str: + if Path(template_fn).is_absolute(): + raise AssertionError(f"template_fn must be relative: {template_fn}") + template_path = self.template_dir / template_fn + env = env_callable() + if isinstance(env, dict): + if "generated_comment" not in env: + generator_default = TORCHGEN_ROOT / "gen.py" + try: + generator = Path( + sys.modules["__main__"].__file__ or generator_default + ).absolute() + except (KeyError, AttributeError): + generator = generator_default.absolute() + + try: + generator_path = generator.relative_to(REPO_ROOT).as_posix() + except ValueError: + generator_path = generator.name + + env = { + **env, # copy the original dict instead of mutating it + "generated_comment": ( + "@" + f"generated by {generator_path} from {template_fn}" + ), + } + template = _read_template(template_path) + substitute_out = template.substitute(env) + # Ensure an extra blank line between the class/function definition + # and the docstring of the previous class/function definition. + # NB: It is generally not recommended to have docstrings in pyi stub + # files. But if there are any, we need to ensure that the file + # is properly formatted. + return re.sub( + r''' + (""")\n+ # match triple quotes + ( + (\s*@.+\n)* # match decorators if any + \s*(class|def) # match class/function definition + ) + ''', + r"\g<1>\n\n\g<2>", + substitute_out, + flags=re.VERBOSE, + ) + if isinstance(env, str): + return env + assert_never(env) + + def write_with_template( + self, + filename: str | Path, + template_fn: str | Path, + env_callable: Callable[[], str | dict[str, Any]], + ) -> None: + filename = Path(filename) + if filename.is_absolute(): + raise AssertionError(f"filename must be relative: {filename}") + file = self.install_dir / filename + if file in self.files: + raise AssertionError(f"duplicate file write {file}") + self.files.add(file) + if not self.dry_run: + substitute_out = self.substitute_with_template( + template_fn=template_fn, + env_callable=env_callable, + ) + self._write_if_changed(filename=file, contents=substitute_out) + + def write( + self, + filename: str | Path, + env_callable: Callable[[], str | dict[str, Any]], + ) -> None: + self.write_with_template(filename, filename, env_callable) + + def write_sharded( + self, + filename: str | Path, + items: Iterable[T], + *, + key_fn: Callable[[T], str], + env_callable: Callable[[T], dict[str, list[str]]], + num_shards: int, + base_env: dict[str, Any] | None = None, + sharded_keys: set[str], + ) -> None: + self.write_sharded_with_template( + filename, + filename, + items, + key_fn=key_fn, + env_callable=env_callable, + num_shards=num_shards, + base_env=base_env, + sharded_keys=sharded_keys, + ) + + def write_sharded_with_template( + self, + filename: str | Path, + template_fn: str | Path, + items: Iterable[T], + *, + key_fn: Callable[[T], str], + env_callable: Callable[[T], dict[str, list[str]]], + num_shards: int, + base_env: dict[str, Any] | None = None, + sharded_keys: set[str], + ) -> None: + file = Path(filename) + if file.is_absolute(): + raise AssertionError(f"filename must be relative: {filename}") + everything: dict[str, Any] = {"shard_id": "Everything"} + shards: list[dict[str, Any]] = [ + {"shard_id": f"_{i}"} for i in range(num_shards) + ] + all_shards = [everything] + shards + + if base_env is not None: + for shard in all_shards: + shard.update(base_env) + + for key in sharded_keys: + for shard in all_shards: + if key in shard: + if not isinstance(shard[key], list): + raise AssertionError("sharded keys in base_env must be a list") + shard[key] = shard[key].copy() + else: + shard[key] = [] + + def merge_env(into: dict[str, list[str]], from_: dict[str, list[str]]) -> None: + for k, v in from_.items(): + if k not in sharded_keys: + raise AssertionError(f"undeclared sharded key {k}") + into[k] += v + + if self.dry_run: + # Dry runs don't write any templates, so incomplete environments are fine + items = () + + for item in items: + key = key_fn(item) + sid = string_stable_hash(key) % num_shards + env = env_callable(item) + + merge_env(shards[sid], env) + merge_env(everything, env) + + for shard in all_shards: + shard_id = shard["shard_id"] + self.write_with_template( + file.with_stem(f"{file.stem}{shard_id}"), + template_fn, + lambda: shard, + ) + + # filenames is used to track compiled files, but FooEverything.cpp isn't meant to be compiled + self.files.discard(self.install_dir / file.with_stem(f"{file.stem}Everything")) + + def write_outputs(self, variable_name: str, filename: str | Path) -> None: + """Write a file containing the list of all outputs which are generated by this script.""" + content = "\n".join( + ( + "set(", + variable_name, + # Use POSIX paths to avoid invalid escape sequences on Windows + *(f' "{file.as_posix()}"' for file in sorted(self.files)), + ")", + ) + ) + self._write_if_changed(filename, content) + + def template_dir_for_comments(self) -> str: + """ + This needs to be deterministic. The template dir is an absolute path + that varies across builds. So, just use the path relative to this file, + which will point to the codegen source but will be stable. + """ + return os.path.relpath(self.template_dir, os.path.dirname(__file__)) + + +# Helper function to generate file manager +def make_file_manager( + options: Namespace, + install_dir: str | Path | None = None, +) -> FileManager: + template_dir = os.path.join(options.source_path, "templates") + install_dir = install_dir if install_dir else options.install_dir + return FileManager( + install_dir=install_dir, + template_dir=template_dir, + dry_run=options.dry_run, + ) + + +# Helper function to create a pretty representation for dataclasses +def dataclass_repr( + obj: Any, + indent: int = 0, + width: int = 80, +) -> str: + return pformat(obj, indent, width) + + +def _format_dict( + attr: dict[Any, Any], + indent: int, + width: int, + curr_indent: int, +) -> str: + curr_indent += indent + 3 + dict_repr = [] + for k, v in attr.items(): + k_repr = repr(k) + v_str = ( + pformat(v, indent, width, curr_indent + len(k_repr)) + if is_dataclass(v) + else repr(v) + ) + dict_repr.append(f"{k_repr}: {v_str}") + + return _format(dict_repr, indent, width, curr_indent, "{", "}") + + +def _format_list( + attr: list[Any] | set[Any] | tuple[Any, ...], + indent: int, + width: int, + curr_indent: int, +) -> str: + curr_indent += indent + 1 + list_repr = [ + pformat(l, indent, width, curr_indent) if is_dataclass(l) else repr(l) + for l in attr + ] + start, end = ("[", "]") if isinstance(attr, list) else ("(", ")") + return _format(list_repr, indent, width, curr_indent, start, end) + + +def _format( + fields_str: list[str], + indent: int, + width: int, + curr_indent: int, + start: str, + end: str, +) -> str: + delimiter, curr_indent_str = "", "" + # if it exceed the max width then we place one element per line + if len(repr(fields_str)) >= width: + delimiter = "\n" + curr_indent_str = " " * curr_indent + + indent_str = " " * indent + body = f", {delimiter}{curr_indent_str}".join(fields_str) + return f"{start}{indent_str}{body}{end}" + + +class NamespaceHelper: + """A helper for constructing the namespace open and close strings for a nested set of namespaces. + + e.g. for namespace_str torch::lazy, + + prologue: + namespace torch { + namespace lazy { + + epilogue: + } // namespace lazy + } // namespace torch + """ + + def __init__( + self, + namespace_str: str, + entity_name: str = "", + max_level: int = 2, + ) -> None: + # cpp_namespace can be a colon joined string such as torch::lazy + cpp_namespaces = namespace_str.split("::") + if len(cpp_namespaces) > max_level: + raise AssertionError( + f"Codegen doesn't support more than {max_level} level(s) of " + f"custom namespace. Got {namespace_str}." + ) + self.cpp_namespace_ = namespace_str + self.prologue_ = "\n".join([f"namespace {n} {{" for n in cpp_namespaces]) + self.epilogue_ = "\n".join( + [f"}} // namespace {n}" for n in reversed(cpp_namespaces)] + ) + self.namespaces_ = cpp_namespaces + self.entity_name_ = entity_name + + @staticmethod + def from_namespaced_entity( + namespaced_entity: str, + max_level: int = 2, + ) -> NamespaceHelper: + """ + Generate helper from nested namespaces as long as class/function name. E.g.: "torch::lazy::add" + """ + names = namespaced_entity.split("::") + entity_name = names[-1] + namespace_str = "::".join(names[:-1]) + return NamespaceHelper( + namespace_str=namespace_str, entity_name=entity_name, max_level=max_level + ) + + @property + def prologue(self) -> str: + return self.prologue_ + + @property + def epilogue(self) -> str: + return self.epilogue_ + + @property + def entity_name(self) -> str: + return self.entity_name_ + + # Only allow certain level of namespaces + def get_cpp_namespace(self, default: str = "") -> str: + """ + Return the namespace string from joining all the namespaces by "::" (hence no leading "::"). + Return default if namespace string is empty. + """ + return self.cpp_namespace_ if self.cpp_namespace_ else default + + +class OrderedSet(Generic[T]): + storage: dict[T, None] + + def __init__(self, iterable: Iterable[T] | None = None) -> None: + if iterable is None: + self.storage = {} + else: + self.storage = dict.fromkeys(iterable) + + def __contains__(self, item: T) -> bool: + return item in self.storage + + def __iter__(self) -> Iterator[T]: + return iter(self.storage.keys()) + + def update(self, items: OrderedSet[T]) -> None: + self.storage.update(items.storage) + + def add(self, item: T) -> None: + self.storage[item] = None + + def copy(self) -> OrderedSet[T]: + ret: OrderedSet[T] = OrderedSet() + ret.storage = self.storage.copy() + return ret + + @staticmethod + def union(*args: OrderedSet[T]) -> OrderedSet[T]: + ret = args[0].copy() + for s in args[1:]: + ret.update(s) + return ret + + def __or__(self, other: OrderedSet[T]) -> OrderedSet[T]: + return OrderedSet.union(self, other) + + def __ior__(self, other: OrderedSet[T]) -> Self: + self.update(other) + return self + + def __eq__(self, other: object) -> bool: + if isinstance(other, OrderedSet): + return self.storage == other.storage + else: + return set(self.storage.keys()) == other diff --git a/.venv/lib/python3.12/site-packages/torchgen/yaml_utils.py b/.venv/lib/python3.12/site-packages/torchgen/yaml_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..96d67859289c03019964568cd1e15acccc7a0eba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchgen/yaml_utils.py @@ -0,0 +1,27 @@ +# Safely load fast C Yaml loader/dumper if they are available +try: + from yaml import CSafeLoader as Loader +except ImportError: + from yaml import SafeLoader as Loader # type: ignore[assignment, misc] + +try: + from yaml import CSafeDumper as Dumper +except ImportError: + from yaml import SafeDumper as Dumper # type: ignore[assignment, misc] +YamlDumper = Dumper + + +# A custom loader for YAML that errors on duplicate keys. +# This doesn't happen by default: see https://github.com/yaml/pyyaml/issues/165 +class YamlLoader(Loader): + def construct_mapping(self, node, deep=False): # type: ignore[no-untyped-def] + mapping = [] + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) # type: ignore[no-untyped-call] + if key in mapping: + raise AssertionError( + f"Found a duplicate key in the yaml. key={key}, line={node.start_mark.line}" + ) + mapping.append(key) + mapping = super().construct_mapping(node, deep=deep) # type: ignore[no-untyped-call] + return mapping diff --git a/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/INSTALLER b/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/LICENSE b/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1edcf92c3317b90fedd187e2eaad101bd1c1efc5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) Soumith Chintala 2016, +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/METADATA b/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..5f1d41c71b4422dafc67dc68f305ed56e9823cc4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/METADATA @@ -0,0 +1,132 @@ +Metadata-Version: 2.1 +Name: torchvision +Version: 0.29.0+cpu +Summary: image and video datasets and models for torch deep learning +Home-page: https://github.com/pytorch/vision +Author: PyTorch Core Team +Author-email: soumith@pytorch.org +License: BSD +Requires-Python: >=3.10,!=3.14.1 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: numpy +Requires-Dist: torch (==2.14.0) +Requires-Dist: pillow (!=8.3.*,>=5.3.0) +Provides-Extra: gdown +Requires-Dist: gdown (>=4.7.3) ; extra == 'gdown' +Provides-Extra: scipy +Requires-Dist: scipy ; extra == 'scipy' + +# torchvision + +[![total torchvision downloads](https://pepy.tech/badge/torchvision)](https://pepy.tech/project/torchvision) +[![documentation](https://img.shields.io/badge/dynamic/json.svg?label=docs&url=https%3A%2F%2Fpypi.org%2Fpypi%2Ftorchvision%2Fjson&query=%24.info.version&colorB=brightgreen&prefix=v)](https://pytorch.org/vision/stable/index.html) + +The torchvision package consists of popular datasets, model architectures, and common image transformations for computer +vision. + +## Installation + +Please refer to the [official +instructions](https://pytorch.org/get-started/locally/) to install the stable +versions of `torch` and `torchvision` on your system. + +To build source, refer to our [contributing +page](https://github.com/pytorch/vision/blob/main/CONTRIBUTING.md#development-installation). + +The following is the corresponding `torchvision` versions and supported Python +versions. + +| `torch` | `torchvision` | Python | +| ------------------ | ------------------ | ------------------- | +| `main` / `nightly` | `main` / `nightly` | `>=3.10`, `<=3.14` | +| `2.13` | `0.28` | `>=3.10`, `<=3.14` | +| `2.12` | `0.27` | `>=3.10`, `<=3.14` | +| `2.11` | `0.26` | `>=3.10`, `<=3.14` | +| `2.10` | `0.25` | `>=3.10`, `<=3.14` | + + +
+ older versions + +| `torch` | `torchvision` | Python | +|---------|-------------------|---------------------------| +| `2.9` | `0.24` | `>=3.10`, `<=3.14` | +| `2.8` | `0.23` | `>=3.9`, `<=3.13` | +| `2.7` | `0.22` | `>=3.9`, `<=3.13` | +| `2.6` | `0.21` | `>=3.9`, `<=3.12` | +| `2.5` | `0.20` | `>=3.9`, `<=3.12` | +| `2.4` | `0.19` | `>=3.8`, `<=3.12` | +| `2.3` | `0.18` | `>=3.8`, `<=3.12` | +| `2.2` | `0.17` | `>=3.8`, `<=3.11` | +| `2.1` | `0.16` | `>=3.8`, `<=3.11` | +| `2.0` | `0.15` | `>=3.8`, `<=3.11` | +| `1.13` | `0.14` | `>=3.7.2`, `<=3.10` | +| `1.12` | `0.13` | `>=3.7`, `<=3.10` | +| `1.11` | `0.12` | `>=3.7`, `<=3.10` | +| `1.10` | `0.11` | `>=3.6`, `<=3.9` | +| `1.9` | `0.10` | `>=3.6`, `<=3.9` | +| `1.8` | `0.9` | `>=3.6`, `<=3.9` | +| `1.7` | `0.8` | `>=3.6`, `<=3.9` | +| `1.6` | `0.7` | `>=3.6`, `<=3.8` | +| `1.5` | `0.6` | `>=3.5`, `<=3.8` | +| `1.4` | `0.5` | `==2.7`, `>=3.5`, `<=3.8` | +| `1.3` | `0.4.2` / `0.4.3` | `==2.7`, `>=3.5`, `<=3.7` | +| `1.2` | `0.4.1` | `==2.7`, `>=3.5`, `<=3.7` | +| `1.1` | `0.3` | `==2.7`, `>=3.5`, `<=3.7` | +| `<=1.0` | `0.2` | `==2.7`, `>=3.5`, `<=3.7` | + +
+ +## Image Backends + +Torchvision currently supports the following image backends: + +- torch tensors +- PIL images: + - [Pillow](https://python-pillow.org/) + - [Pillow-SIMD](https://github.com/uploadcare/pillow-simd) - a **much faster** drop-in replacement for Pillow with SIMD. + +Read more in in our [docs](https://pytorch.org/vision/stable/transforms.html). + +## Documentation + +You can find the API documentation on the pytorch website: + +## Contributing + +See the [CONTRIBUTING](CONTRIBUTING.md) file for how to help out. + +## Disclaimer on Datasets + +This is a utility library that downloads and prepares public datasets. We do not host or distribute these datasets, +vouch for their quality or fairness, or claim that you have license to use the dataset. It is your responsibility to +determine whether you have permission to use the dataset under the dataset's license. + +If you're a dataset owner and wish to update any part of it (description, citation, etc.), or do not want your dataset +to be included in this library, please get in touch through a GitHub issue. Thanks for your contribution to the ML +community! + +## Pre-trained Model License + +The pre-trained models provided in this library may have their own licenses or terms and conditions derived from the +dataset used for training. It is your responsibility to determine whether you have permission to use the models for your +use case. + +More specifically, SWAG models are released under the CC-BY-NC 4.0 license. See +[SWAG LICENSE](https://github.com/facebookresearch/SWAG/blob/main/LICENSE) for additional details. + +## Citing TorchVision + +If you find TorchVision useful in your work, please consider citing the following BibTeX entry: + +```bibtex +@software{torchvision2016, + title = {TorchVision: PyTorch's Computer Vision library}, + author = {TorchVision maintainers and contributors}, + year = 2016, + journal = {GitHub repository}, + publisher = {GitHub}, + howpublished = {\url{https://github.com/pytorch/vision}} +} +``` diff --git a/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/RECORD b/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..5f9c6d4d3053474b3fbe1ac1ca0e53dbb3f5d8a1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/RECORD @@ -0,0 +1,384 @@ +torchvision-0.29.0+cpu.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +torchvision-0.29.0+cpu.dist-info/LICENSE,sha256=ZQL2doUc_iX4r3VTHfsyN1tzJbc8N-e0N0H6QiiT5x0,1517 +torchvision-0.29.0+cpu.dist-info/METADATA,sha256=SyYngMj0O8US00iHZENLzLMgN_hzE5QxmnZnpmC9G-g,5679 +torchvision-0.29.0+cpu.dist-info/RECORD,, +torchvision-0.29.0+cpu.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +torchvision-0.29.0+cpu.dist-info/WHEEL,sha256=GAEhkxm77H2WVEyE70oaJna7cr1z-ZyZC29APwfwcpg,113 +torchvision-0.29.0+cpu.dist-info/top_level.txt,sha256=ucJZoaluBW9BGYT4TuCE6zoZY_JuSP30wbDh-IRpxUU,12 +torchvision.libs/libjpeg.185109e6.so.8,sha256=lEkg6UOy7yimbDyBltM0R2if_KeRFS97QiyDnxFha0c,877472 +torchvision.libs/libpng16.fdd68bd0.so.16,sha256=HZXXCBUdHTtoobizL-jJzBUaQYTWZdYtaZdSnIxGTCU,288001 +torchvision.libs/libsharpyuv.a0b54fe1.so.0,sha256=7DzMHc2scfXGZRXcY9gzx6xBG9xFzVOxm4F8HVALjPU,46336 +torchvision.libs/libwebp.14e109ad.so.7,sha256=oiHTFC4w4WJLGWEi2QppJLSozyEdy-ThbDlHBtewwlE,790273 +torchvision.libs/libz.1140de3a.so.1,sha256=CQABCZPsueO_Z0RZFH80M7WwAa7qlNW6Q7Ychn5ZbNE,117416 +torchvision/_C_stable.so,sha256=81gf1sJryn8FB1D8SWSM56aAUD9Np4IGpz9YqPoNork,496712 +torchvision/__init__.py,sha256=lBCn5kj_B6aVWHFz0JMB19qZegF82M73tU5bL23Iw0I,1976 +torchvision/__pycache__/__init__.cpython-312.pyc,, +torchvision/__pycache__/_autograd_registrations.cpython-312.pyc,, +torchvision/__pycache__/_internally_replaced_utils.cpython-312.pyc,, +torchvision/__pycache__/_meta_registrations.cpython-312.pyc,, +torchvision/__pycache__/_utils.cpython-312.pyc,, +torchvision/__pycache__/extension.cpython-312.pyc,, +torchvision/__pycache__/utils.cpython-312.pyc,, +torchvision/__pycache__/version.cpython-312.pyc,, +torchvision/_autograd_registrations.py,sha256=j3Yb2Ai_3gKoshJm7NJFLdyyB-A9Duy3AAldrVK2YPY,12051 +torchvision/_internally_replaced_utils.py,sha256=5jM7APG0sSXSQHZvga633rQY26VgSsgH0eOvB5oYxms,1459 +torchvision/_meta_registrations.py,sha256=fFX9uFS7OImZSe36TmjHvWkZDqH-1K5Rv1kyd2Yfy8M,8638 +torchvision/_utils.py,sha256=qH-hF93IwNOyKtDoOA6xOmZfmKeB3j5VYw7bdY0i9k8,800 +torchvision/datasets/__init__.py,sha256=CQfKDHOvjSZ2dBlOLRieEjP9AsB1jJEe3-5vbFNeXOM,3606 +torchvision/datasets/__pycache__/__init__.cpython-312.pyc,, +torchvision/datasets/__pycache__/_optical_flow.cpython-312.pyc,, +torchvision/datasets/__pycache__/_stereo_matching.cpython-312.pyc,, +torchvision/datasets/__pycache__/caltech.cpython-312.pyc,, +torchvision/datasets/__pycache__/celeba.cpython-312.pyc,, +torchvision/datasets/__pycache__/cifar.cpython-312.pyc,, +torchvision/datasets/__pycache__/cityscapes.cpython-312.pyc,, +torchvision/datasets/__pycache__/clevr.cpython-312.pyc,, +torchvision/datasets/__pycache__/coco.cpython-312.pyc,, +torchvision/datasets/__pycache__/country211.cpython-312.pyc,, +torchvision/datasets/__pycache__/dtd.cpython-312.pyc,, +torchvision/datasets/__pycache__/eurosat.cpython-312.pyc,, +torchvision/datasets/__pycache__/fakedata.cpython-312.pyc,, +torchvision/datasets/__pycache__/fer2013.cpython-312.pyc,, +torchvision/datasets/__pycache__/fgvc_aircraft.cpython-312.pyc,, +torchvision/datasets/__pycache__/flickr.cpython-312.pyc,, +torchvision/datasets/__pycache__/flowers102.cpython-312.pyc,, +torchvision/datasets/__pycache__/folder.cpython-312.pyc,, +torchvision/datasets/__pycache__/food101.cpython-312.pyc,, +torchvision/datasets/__pycache__/gtsrb.cpython-312.pyc,, +torchvision/datasets/__pycache__/hmdb51.cpython-312.pyc,, +torchvision/datasets/__pycache__/imagenet.cpython-312.pyc,, +torchvision/datasets/__pycache__/imagenette.cpython-312.pyc,, +torchvision/datasets/__pycache__/inaturalist.cpython-312.pyc,, +torchvision/datasets/__pycache__/kinetics.cpython-312.pyc,, +torchvision/datasets/__pycache__/kitti.cpython-312.pyc,, +torchvision/datasets/__pycache__/lfw.cpython-312.pyc,, +torchvision/datasets/__pycache__/lsun.cpython-312.pyc,, +torchvision/datasets/__pycache__/mnist.cpython-312.pyc,, +torchvision/datasets/__pycache__/moving_mnist.cpython-312.pyc,, +torchvision/datasets/__pycache__/omniglot.cpython-312.pyc,, +torchvision/datasets/__pycache__/oxford_iiit_pet.cpython-312.pyc,, +torchvision/datasets/__pycache__/pcam.cpython-312.pyc,, +torchvision/datasets/__pycache__/phototour.cpython-312.pyc,, +torchvision/datasets/__pycache__/places365.cpython-312.pyc,, +torchvision/datasets/__pycache__/rendered_sst2.cpython-312.pyc,, +torchvision/datasets/__pycache__/sbd.cpython-312.pyc,, +torchvision/datasets/__pycache__/sbu.cpython-312.pyc,, +torchvision/datasets/__pycache__/semeion.cpython-312.pyc,, +torchvision/datasets/__pycache__/stanford_cars.cpython-312.pyc,, +torchvision/datasets/__pycache__/stl10.cpython-312.pyc,, +torchvision/datasets/__pycache__/sun397.cpython-312.pyc,, +torchvision/datasets/__pycache__/svhn.cpython-312.pyc,, +torchvision/datasets/__pycache__/ucf101.cpython-312.pyc,, +torchvision/datasets/__pycache__/usps.cpython-312.pyc,, +torchvision/datasets/__pycache__/utils.cpython-312.pyc,, +torchvision/datasets/__pycache__/video_utils.cpython-312.pyc,, +torchvision/datasets/__pycache__/vision.cpython-312.pyc,, +torchvision/datasets/__pycache__/voc.cpython-312.pyc,, +torchvision/datasets/__pycache__/widerface.cpython-312.pyc,, +torchvision/datasets/_optical_flow.py,sha256=FdTW7QIduFwnofO-1Z9e2azb40pZ0Tuf5Uy6AAl6ayQ,21204 +torchvision/datasets/_stereo_matching.py,sha256=gS4Nhz-1Gbm975ANFVxkNjpeFK01081Jchl045rbXEQ,49040 +torchvision/datasets/caltech.py,sha256=nznD3jbp-m99RElWnqZwky-QdWy9ZNTiS521KM5W0Gs,8929 +torchvision/datasets/celeba.py,sha256=EX73jml3qFO2WzOYMaBJA_dvhmCf1nzZYeeMthf64gA,9047 +torchvision/datasets/cifar.py,sha256=Ci1nhujp0em8fbBmTQGFvBT7IsZzPo7m3edQA4tu2DU,5784 +torchvision/datasets/cityscapes.py,sha256=KD516SRjAjlfdsQ57wPRo76kl8RrMbrQEoTUhNdJJHw,10330 +torchvision/datasets/clevr.py,sha256=YdWTXg2y4ubW3kFyS6RaNgGo-oPWNC37hPjbzMJFLQY,3855 +torchvision/datasets/coco.py,sha256=2N0zCOkhEbuLWPaQjMkJe28nxvO18O65je692Xgv0TU,4345 +torchvision/datasets/country211.py,sha256=-HSUiid5jC7ooNzZ0hYnv2__DmzSp_aQIwW9yvBJ4W4,2889 +torchvision/datasets/dtd.py,sha256=J3jMDI-0yUE9G2jBy7CukPXF-5baOhxdYUXLaUCTuxw,4420 +torchvision/datasets/eurosat.py,sha256=C8Q3a4vF-hSYM-xEfVglewgOJVek6DWBYarGkMB90RQ,2761 +torchvision/datasets/fakedata.py,sha256=b9fUKMRmnwv_aF_k99wSEB953bQtb9NTz9pTk354Eg0,2440 +torchvision/datasets/fer2013.py,sha256=8qRPt6CU7JZ_SqScXLF3tnxWsLPlx57EC8Qe5BQJgtc,5106 +torchvision/datasets/fgvc_aircraft.py,sha256=K6ik7tWzUSRUP2Ed0cIzUH-bozMl8i2_Xh0_2IK97hU,4968 +torchvision/datasets/flickr.py,sha256=rVS8l-xNTEl8r-vFaAnJJyT8T5jHorMXUZaj83xlK7g,6170 +torchvision/datasets/flowers102.py,sha256=NELj-lyuVsvMuin5YVOdZ5Ih-DEErTPZILOrEPrB4RU,7481 +torchvision/datasets/folder.py,sha256=sqNuUgz0UdgrmT5v2qEmbYUm72pALc9AHyPwyc0Kjvo,12985 +torchvision/datasets/food101.py,sha256=8_1Duos86AEelNt2J5I2vbmFA18P4FiL8JICNnNINHg,4145 +torchvision/datasets/gtsrb.py,sha256=zdBkamw8DcfRq8IVIt3tEhSooH53NhI0K-Ojvj3AUVM,3778 +torchvision/datasets/hmdb51.py,sha256=XNSgjA2p4UrQ67-mUR8JgsLvgKAtmwjiR4SfTu5JBW0,5952 +torchvision/datasets/imagenet.py,sha256=r6AzyjPv5TkwxcnXomQZyu4cE0oIiHYdVBXkFX8E_y0,8922 +torchvision/datasets/imagenette.py,sha256=ZN6igkIUReoX01N0LR2wLpAEE3cBeFEASV1NNUkvCNk,4626 +torchvision/datasets/inaturalist.py,sha256=WGnsEaOXyUzgRX5rIpWFHoUufCFhN-nrYu6glQQiOWI,10302 +torchvision/datasets/kinetics.py,sha256=6rMjRvSRckN1I8oSZGRp1Vje-IKXrX6PYWuHer4iXk4,9865 +torchvision/datasets/kitti.py,sha256=6Ntz3XiowAF-iKpjqNK484cQ5WvaseVqt1do97LfqYM,5624 +torchvision/datasets/lfw.py,sha256=avCOlaiU8GGaXY4wUpSQ-847V5KbJWoEZsw-s4FtF0s,11763 +torchvision/datasets/lsun.py,sha256=Cbo_wF_dRo0mgf_4Ua2vvnD1rSunfd5aKOFNZfSwC3c,5730 +torchvision/datasets/mnist.py,sha256=cdh2hq0E9hAnkxWXUP2KyMrHJ5YQvnWVaqErKW_fhuw,21820 +torchvision/datasets/moving_mnist.py,sha256=D7zBXNXU0-w5lZCDGgT1QaTqBVbiegnGeZQYht_ipK4,3644 +torchvision/datasets/omniglot.py,sha256=HPgmjk9bvV2A8DQnyfWP_VUiQFHl8mzQlO5SB8fw49E,4486 +torchvision/datasets/oxford_iiit_pet.py,sha256=cEL3fuVq8Z9jxcDe-_wk18zVO1rhuSaKhl144ue25Uo,5696 +torchvision/datasets/pcam.py,sha256=eFhow5mBwvyRML6JVX5uJ6vE7yy9fcutz1BiMm-GE4A,5278 +torchvision/datasets/phototour.py,sha256=r3IahNs_KDU4RaPBH5-mm29TBO9VxhOcWSkJUJNHxdc,7855 +torchvision/datasets/places365.py,sha256=r7riK2-LsAmx90QptOEQ0_37r9iKymSpi5UKZ7hJPOk,7467 +torchvision/datasets/rendered_sst2.py,sha256=3346Z3irlBVjxoXUrQTMctulwFpBY2aL6UaoSmJ8hYk,3957 +torchvision/datasets/samplers/__init__.py,sha256=W1ZtQpGLG6aoHylo1t8PEsHIVoWwso5bSFk9JzKfH8g,161 +torchvision/datasets/samplers/__pycache__/__init__.cpython-312.pyc,, +torchvision/datasets/samplers/__pycache__/clip_sampler.cpython-312.pyc,, +torchvision/datasets/samplers/clip_sampler.py,sha256=ymUW71YTOrdKs-LQYrY-v85n2SBVbGUnxI1wh1uJros,6265 +torchvision/datasets/sbd.py,sha256=Lh4KCZGVAbOh1F5ue30XhuZy2bugZNjUv_sDV1BZtwA,5407 +torchvision/datasets/sbu.py,sha256=Pxu-XE_oEelysZD2qXf2ek2fNH4fQEd48f_JM76YQqE,4464 +torchvision/datasets/semeion.py,sha256=oPd5XVRcUBWl84yokyRHe81mXubY_nAG0kd6NdYYVx0,3099 +torchvision/datasets/stanford_cars.py,sha256=eXcOmsErj8ZCuzRHLTy0ZNCAfy-a7NyTTbJ7pUAfWm8,4281 +torchvision/datasets/stl10.py,sha256=WLtx6AnSvikS-wJAQhBkz3V1vKXwrJLWXRqmVYKgyXM,7227 +torchvision/datasets/sun397.py,sha256=2wdKxeamU-3BCJWF2gLqxQHZVUap1O4HHrbMH2Rn7VI,3176 +torchvision/datasets/svhn.py,sha256=CeKi4rQh8Mzd3Ohs-qjUQ5MSFLLSECJB_ktHdbICDUI,4821 +torchvision/datasets/ucf101.py,sha256=C4eyBIpDzlCKXtzC2XFntBpXxkL4yXkTtTVHIAccUZI,5514 +torchvision/datasets/usps.py,sha256=TGQvxv1Yp0qtiqMR8bY13BxPVtIWC_bW9y2LNAxU1J4,3509 +torchvision/datasets/utils.py,sha256=Ndj0Ai0xOnc512nx-Sv3VRF144LVC7wzLKfYi2UqnXI,15914 +torchvision/datasets/video_utils.py,sha256=XDO_6kP-pJQKNlCtpBgxDF2iR1hZFh5UceHiYmRcVLc,15334 +torchvision/datasets/vision.py,sha256=9fIM9o_yyqdxcpj_bleYymu7Aoo6p3R730ND4UJaDzs,4292 +torchvision/datasets/voc.py,sha256=fkbarAmVJiwrNL-VfE2M5KXpKgd8vCpwLK7fEi2Asj8,8851 +torchvision/datasets/widerface.py,sha256=plgSlVHybKCvZRLDQRtykU9kY1-lSlSGP8ppW565fWo,8241 +torchvision/extension.py,sha256=ck0bcmp20EjC5o1PteQIZWMd7R0tBDsLz-ZcQI-_FK0,2740 +torchvision/image_stable.so,sha256=L3FJVfsUsWIEuCZVLrIXFSp6cFmkOdxOAIU2VVA6iTQ,228913 +torchvision/io/__init__.py,sha256=F2G1f7akmP5bM_45LaNmm_Sp3tDe-DcZfLCf9yVPZ_8,1336 +torchvision/io/__pycache__/__init__.cpython-312.pyc,, +torchvision/io/__pycache__/_video_deprecation_warning.cpython-312.pyc,, +torchvision/io/__pycache__/image.cpython-312.pyc,, +torchvision/io/__pycache__/video.cpython-312.pyc,, +torchvision/io/_video_deprecation_warning.py,sha256=Q0keR0pnBX77H0HQkc1csXoc3EphqW9uzAcPXm2JVJY,565 +torchvision/io/image.py,sha256=MyDPUzmqVUYPjy-l_06377D6znxsVfOjXhajnB9YOVA,30681 +torchvision/io/video.py,sha256=Yptt4dsVbSYo0EFgG1O--sICeETb7gsi4qGwoDCPQjI,564 +torchvision/models/__init__.py,sha256=A8GQPE1bl3oUHpuD9ND53DV557IPY4459FNLW6sVXGI,865 +torchvision/models/__pycache__/__init__.cpython-312.pyc,, +torchvision/models/__pycache__/_api.cpython-312.pyc,, +torchvision/models/__pycache__/_meta.cpython-312.pyc,, +torchvision/models/__pycache__/_utils.cpython-312.pyc,, +torchvision/models/__pycache__/alexnet.cpython-312.pyc,, +torchvision/models/__pycache__/convnext.cpython-312.pyc,, +torchvision/models/__pycache__/densenet.cpython-312.pyc,, +torchvision/models/__pycache__/efficientnet.cpython-312.pyc,, +torchvision/models/__pycache__/feature_extraction.cpython-312.pyc,, +torchvision/models/__pycache__/googlenet.cpython-312.pyc,, +torchvision/models/__pycache__/inception.cpython-312.pyc,, +torchvision/models/__pycache__/maxvit.cpython-312.pyc,, +torchvision/models/__pycache__/mnasnet.cpython-312.pyc,, +torchvision/models/__pycache__/mobilenet.cpython-312.pyc,, +torchvision/models/__pycache__/mobilenetv2.cpython-312.pyc,, +torchvision/models/__pycache__/mobilenetv3.cpython-312.pyc,, +torchvision/models/__pycache__/regnet.cpython-312.pyc,, +torchvision/models/__pycache__/resnet.cpython-312.pyc,, +torchvision/models/__pycache__/shufflenetv2.cpython-312.pyc,, +torchvision/models/__pycache__/squeezenet.cpython-312.pyc,, +torchvision/models/__pycache__/swin_transformer.cpython-312.pyc,, +torchvision/models/__pycache__/vgg.cpython-312.pyc,, +torchvision/models/__pycache__/vision_transformer.cpython-312.pyc,, +torchvision/models/_api.py,sha256=_cuAByJV_soYsh9D0cuUM2MBGOySXhqJzGbQsqOe_lA,9964 +torchvision/models/_meta.py,sha256=fqpeQBsf9EEYbmApQ8Q0LKyM9_UFwjireII5mwDbwJY,28875 +torchvision/models/_utils.py,sha256=lyKJ7NsrgdLu2rpQs-YvTW4wcEr_zCbhXiAB72JxcDY,10789 +torchvision/models/alexnet.py,sha256=dvBZLVH60TOTHCNNkWg0TFLtuJ5Ghh_xXN73r3Vyq58,4488 +torchvision/models/convnext.py,sha256=XADEErx55cZQ-Iff4NIaqAKJA6O76uGpXDsP372vVcI,15347 +torchvision/models/densenet.py,sha256=dqcXl7eHMIjCfKBFhYiGHBl1KOhkIfV1JdyOOtdxxZo,16812 +torchvision/models/detection/__init__.py,sha256=JwYm_fTGO_FeRg4eTOQLwQPZ9lC9jheZ-QEoJgqKTjg,168 +torchvision/models/detection/__pycache__/__init__.cpython-312.pyc,, +torchvision/models/detection/__pycache__/_utils.cpython-312.pyc,, +torchvision/models/detection/__pycache__/anchor_utils.cpython-312.pyc,, +torchvision/models/detection/__pycache__/backbone_utils.cpython-312.pyc,, +torchvision/models/detection/__pycache__/faster_rcnn.cpython-312.pyc,, +torchvision/models/detection/__pycache__/fcos.cpython-312.pyc,, +torchvision/models/detection/__pycache__/generalized_rcnn.cpython-312.pyc,, +torchvision/models/detection/__pycache__/image_list.cpython-312.pyc,, +torchvision/models/detection/__pycache__/keypoint_rcnn.cpython-312.pyc,, +torchvision/models/detection/__pycache__/mask_rcnn.cpython-312.pyc,, +torchvision/models/detection/__pycache__/retinanet.cpython-312.pyc,, +torchvision/models/detection/__pycache__/roi_heads.cpython-312.pyc,, +torchvision/models/detection/__pycache__/rpn.cpython-312.pyc,, +torchvision/models/detection/__pycache__/ssd.cpython-312.pyc,, +torchvision/models/detection/__pycache__/ssdlite.cpython-312.pyc,, +torchvision/models/detection/__pycache__/transform.cpython-312.pyc,, +torchvision/models/detection/_utils.py,sha256=atlD5LtlCQTI-NNgoWWHUyBKe8qZS45P2ZU-8LECkyU,22107 +torchvision/models/detection/anchor_utils.py,sha256=B4UVJoQUz4SDgSJo4bxHitf_1Bs9zmDFNx0f02X5-0g,11854 +torchvision/models/detection/backbone_utils.py,sha256=Iyg9x1l2dkWbKbEwF31OJ9Q834s13M1oZmzN_sP0250,10536 +torchvision/models/detection/faster_rcnn.py,sha256=VOBTGJVHGMnPJpmWzVb7413JNa4MLfEIpwmLJaUrLcI,36965 +torchvision/models/detection/fcos.py,sha256=sxbbHqDdCEjsgo-oIChwcZesj0u3RzrSh-uij-tpPig,34216 +torchvision/models/detection/generalized_rcnn.py,sha256=ppKLsSiDnLmZXo9fjmTbR8rM7My-V2HN3JTmAEkmqHQ,4929 +torchvision/models/detection/image_list.py,sha256=MZpxox8L4yXk3gdSADP__Xq40OcN75p0dlG2hGIb2EE,751 +torchvision/models/detection/keypoint_rcnn.py,sha256=vzaZlzWlVml7qyXsTxy4tuMsWBeLhugLoEDDcvudAi0,21979 +torchvision/models/detection/mask_rcnn.py,sha256=KK_0MLEZP9GWfCDEl6mJuYBHidWodGYfPxiyRmKWhNE,26713 +torchvision/models/detection/retinanet.py,sha256=K7Vpmmq_09hNG4cZD_xLDCWzbatXZ5VgKrotoXywKOI,37280 +torchvision/models/detection/roi_heads.py,sha256=3fkaHIlgPIbA57MPOtnxYTrfRiPtHBaI7QPpr0dXn_g,34295 +torchvision/models/detection/rpn.py,sha256=F-uTkiSyjENYObeVjGqyV2XwQcFRvhzxN1B90OTV3dU,15818 +torchvision/models/detection/ssd.py,sha256=mXkTRD0XQuVJJ5FAt_ODNcLTyxhX-OeDZ6IxdmBjiXk,28960 +torchvision/models/detection/ssdlite.py,sha256=9p8NaIPICi2A-dbD4oa1yZyKO30x5USGz2XNb_l09Zc,13207 +torchvision/models/detection/transform.py,sha256=j1MUnNk8O8KRzwgVNWhighN64psjYpOOcynyNhMlBh8,12170 +torchvision/models/efficientnet.py,sha256=gtBY4Zie-E5O985D5KSdwQ8bldzQAzA8LAUkON6COxc,43098 +torchvision/models/feature_extraction.py,sha256=7P4xGde3MQt6rvdZUZMwfCk93DZABcEQY7sa7CDQXVw,27914 +torchvision/models/googlenet.py,sha256=zVghxRPGRApc3Lj4l_AzEj16EWR2BcNT7WC-E2Q60lM,12793 +torchvision/models/inception.py,sha256=Z5Hbfi7ot6KTWay20g2eW0dEGLpGwN26W8wV0lO4rYU,18838 +torchvision/models/maxvit.py,sha256=c6vFrELdAhRG1XOrXowTJJp25Fifdqu6TeKgITO4PqY,32110 +torchvision/models/mnasnet.py,sha256=zGRyfEVGuP8AJSPpwbICZ5D-XEfB54scH49taJsCUxQ,17562 +torchvision/models/mobilenet.py,sha256=lSRVxw2TL3LFBwCadvyvH6n3GzqUTnK2-rhX3MOgSrs,211 +torchvision/models/mobilenetv2.py,sha256=fYp06-r4Di7PxqSMLQeSHiaM1d2XtZlNul73AbRtOyQ,9704 +torchvision/models/mobilenetv3.py,sha256=VESQk2JzSrVPB7pkzS1U6QhUll1NHOayszfgVdD8uz4,16300 +torchvision/models/optical_flow/__init__.py,sha256=0zRlMWQJCjFqoUafUXVgO89-z7em7tACo9E8hHSq9RQ,20 +torchvision/models/optical_flow/__pycache__/__init__.cpython-312.pyc,, +torchvision/models/optical_flow/__pycache__/_utils.cpython-312.pyc,, +torchvision/models/optical_flow/__pycache__/raft.cpython-312.pyc,, +torchvision/models/optical_flow/_utils.py,sha256=v-tQJzYmYukrD1sQAE-5j5jxyvComwF1UdGkz5tVTLw,2077 +torchvision/models/optical_flow/raft.py,sha256=HYnzlhbjuOifVsvcgT5nB3k6URazMXRs-AsEUOnozTg,39991 +torchvision/models/quantization/__init__.py,sha256=gqFM7zI4UUHKKBDJAumozOn7xPL0JtvyNS8Ejz6QXp0,125 +torchvision/models/quantization/__pycache__/__init__.cpython-312.pyc,, +torchvision/models/quantization/__pycache__/googlenet.cpython-312.pyc,, +torchvision/models/quantization/__pycache__/inception.cpython-312.pyc,, +torchvision/models/quantization/__pycache__/mobilenet.cpython-312.pyc,, +torchvision/models/quantization/__pycache__/mobilenetv2.cpython-312.pyc,, +torchvision/models/quantization/__pycache__/mobilenetv3.cpython-312.pyc,, +torchvision/models/quantization/__pycache__/resnet.cpython-312.pyc,, +torchvision/models/quantization/__pycache__/shufflenetv2.cpython-312.pyc,, +torchvision/models/quantization/__pycache__/utils.cpython-312.pyc,, +torchvision/models/quantization/googlenet.py,sha256=8WXqjmlVw0sVy4vUkQvoAA1YXOGE3k_tVTkg36SeI4A,8112 +torchvision/models/quantization/inception.py,sha256=i5bUGl4G59SlNOjxffHlJqDikeesgim31GwGHyubMwI,10841 +torchvision/models/quantization/mobilenet.py,sha256=lSRVxw2TL3LFBwCadvyvH6n3GzqUTnK2-rhX3MOgSrs,211 +torchvision/models/quantization/mobilenetv2.py,sha256=SP8uiSC9vwKtIkgzxRt4Avn8HWmfBbHLDB21BkkyuCI,5915 +torchvision/models/quantization/mobilenetv3.py,sha256=BshvE-qRjdDbY0eYep-8T2L3BNHd42dhxFD4QOn3v94,9256 +torchvision/models/quantization/resnet.py,sha256=PBKMdDxaIwEDXmnyIbUvyhG-kt-gmrWOus8TQnfs_TA,18055 +torchvision/models/quantization/shufflenetv2.py,sha256=__r5U8MsNExD-mgyC6moYItAfdaRPt4kr1LtwC-Kwa0,17006 +torchvision/models/quantization/utils.py,sha256=1fsjPdXM0AxcI7LRYWNyLOk52Jte56ekwLMJL9osF08,2052 +torchvision/models/regnet.py,sha256=mHxtyaiGH6n4kfp8weha09VuO6ySMMLGdtV7w0ikl6I,63534 +torchvision/models/resnet.py,sha256=n68vMh_a9-29eRrtxuNhDH7fnIkhEsvXWGG-rh6VGNE,38920 +torchvision/models/segmentation/__init__.py,sha256=TGk6UdVXAMtwBpYalrvdXZnmSwqzTDOT1lgKrfzhHrQ,66 +torchvision/models/segmentation/__pycache__/__init__.cpython-312.pyc,, +torchvision/models/segmentation/__pycache__/_utils.cpython-312.pyc,, +torchvision/models/segmentation/__pycache__/deeplabv3.cpython-312.pyc,, +torchvision/models/segmentation/__pycache__/fcn.cpython-312.pyc,, +torchvision/models/segmentation/__pycache__/lraspp.cpython-312.pyc,, +torchvision/models/segmentation/_utils.py,sha256=dBx3elgggqel7f3qhPvid_ZDBWcC6DcJd601S-ULaz4,1191 +torchvision/models/segmentation/deeplabv3.py,sha256=W93D1mmQuwVeQ6_W7TZn8CEUI5D0GKZ_2auRKhBiB-Q,15042 +torchvision/models/segmentation/fcn.py,sha256=I1FqaZZVPc3Fbg_7E2L5qpumnupxBYc7KYsW03EG_Cs,8973 +torchvision/models/segmentation/lraspp.py,sha256=oVGMcmR6DvG-M8G33xw2QoAFSy_JfHkHEn2HlNlbvvU,7637 +torchvision/models/shufflenetv2.py,sha256=LIe_Ip6jCzbYbQ4zW4zYwWuxJN8qTJobH8SPsMLvydQ,15438 +torchvision/models/squeezenet.py,sha256=apjFPEI5nr_493bAQsR245EorzaMYXVQSqdcveyAfy0,8763 +torchvision/models/swin_transformer.py,sha256=nsc_IzMQg4nhUv2jRrbxlevO0C6c7TZ872D0BQk7QLE,39331 +torchvision/models/vgg.py,sha256=IUpaQh1-VpMxW7kcUIe0dDFmDznJBcl6gGzFSEDfsE8,19213 +torchvision/models/video/__init__.py,sha256=O4HB-RaXgCtnvpMDAuMBaIeKIiYEkNxra_fmAHLUIJM,93 +torchvision/models/video/__pycache__/__init__.cpython-312.pyc,, +torchvision/models/video/__pycache__/mvit.cpython-312.pyc,, +torchvision/models/video/__pycache__/resnet.cpython-312.pyc,, +torchvision/models/video/__pycache__/s3d.cpython-312.pyc,, +torchvision/models/video/__pycache__/swin_transformer.cpython-312.pyc,, +torchvision/models/video/mvit.py,sha256=dspGXyvgu3_5FMpDQmTOtnNkAoVtFk5YEEkdW6d9QhA,33006 +torchvision/models/video/resnet.py,sha256=JvwGBIWc-FN2fPKHFrHN5zu7m3_eomDJdD4MBZqzC-w,16779 +torchvision/models/video/s3d.py,sha256=jx9gMP18Bzb7UO3vjejVBHlrCrJPdWFDfTn7XeU5kMg,7815 +torchvision/models/video/swin_transformer.py,sha256=ZVO7jXANfWM2wOAasFC1C0jL4mWh9Msyi6iGUNbD2uQ,27675 +torchvision/models/vision_transformer.py,sha256=C8WUucp73YSotGMdSt_u6emkCTd24dC0L_d3Nv7a77Y,32124 +torchvision/ops/__init__.py,sha256=eVv16QSBwgKaojOUHMPCy4ou9ZeFh-HoCV4DpqrZG4U,1928 +torchvision/ops/__pycache__/__init__.cpython-312.pyc,, +torchvision/ops/__pycache__/_box_convert.cpython-312.pyc,, +torchvision/ops/__pycache__/_register_onnx_ops.cpython-312.pyc,, +torchvision/ops/__pycache__/_utils.cpython-312.pyc,, +torchvision/ops/__pycache__/boxes.cpython-312.pyc,, +torchvision/ops/__pycache__/ciou_loss.cpython-312.pyc,, +torchvision/ops/__pycache__/deform_conv.cpython-312.pyc,, +torchvision/ops/__pycache__/diou_loss.cpython-312.pyc,, +torchvision/ops/__pycache__/drop_block.cpython-312.pyc,, +torchvision/ops/__pycache__/feature_pyramid_network.cpython-312.pyc,, +torchvision/ops/__pycache__/focal_loss.cpython-312.pyc,, +torchvision/ops/__pycache__/giou_loss.cpython-312.pyc,, +torchvision/ops/__pycache__/misc.cpython-312.pyc,, +torchvision/ops/__pycache__/poolers.cpython-312.pyc,, +torchvision/ops/__pycache__/ps_roi_align.cpython-312.pyc,, +torchvision/ops/__pycache__/ps_roi_pool.cpython-312.pyc,, +torchvision/ops/__pycache__/roi_align.cpython-312.pyc,, +torchvision/ops/__pycache__/roi_pool.cpython-312.pyc,, +torchvision/ops/__pycache__/stochastic_depth.cpython-312.pyc,, +torchvision/ops/_box_convert.py,sha256=QodQcplX74dw9SuP21MiKAOewEipka9uYrO5XSKipGc,6981 +torchvision/ops/_register_onnx_ops.py,sha256=Fyb1kC2m2OqZdfW_M86pt9-S66e1qNUhXNu1EQRa034,4181 +torchvision/ops/_utils.py,sha256=iEpmZ1T1B7KkQvaVOt0tavLAfGbfgU0Y6LvglyfWJK4,3617 +torchvision/ops/boxes.py,sha256=adu2PXbXJAFaOInXCTlvLwNptP4bxyJyqXHUzJ-f-y0,22269 +torchvision/ops/ciou_loss.py,sha256=9Jozu0XjAUdnMNjLu1kjjqJGykNpd7ljGL951pG9EQ4,2755 +torchvision/ops/deform_conv.py,sha256=UXyqaidnD_OFssjpBvG4as5-Fj9r-wInnvA1OZYs56s,6983 +torchvision/ops/diou_loss.py,sha256=Wh9ZjOyDgcBnRk8Htdm6CqaPDz-7T1_jf64n1ksCI7A,3335 +torchvision/ops/drop_block.py,sha256=S4eb09tISLH95i41JjxLoP-KvJmsdusM_NH0zJFBWsA,6087 +torchvision/ops/feature_pyramid_network.py,sha256=6CJ_rt_DstnhOu-U34-SLYatqcNie0WLhJDIJCIk2C0,8683 +torchvision/ops/focal_loss.py,sha256=mWb89_hjWpOAyCK5rykw0KmOjm_0sQ4ukfp5ivhlBCc,2419 +torchvision/ops/giou_loss.py,sha256=eyMV9s0gDqEAFowurcFaR-eHSeT3qP7B6_sHHF8eWjQ,2695 +torchvision/ops/misc.py,sha256=orsfOvHTuFR2HqS8NdC53rXkl3Hw3JGbOQZD8IGhq34,13586 +torchvision/ops/poolers.py,sha256=Y1cjDl42SXrkajAWHr_WXNLc-8OOEpz4KuGQn0S7ReE,11901 +torchvision/ops/ps_roi_align.py,sha256=4iAbeUVTessAcxvJhuARN_aFGUTZC9R4KrKC_mBH3MQ,3625 +torchvision/ops/ps_roi_pool.py,sha256=jOv-2pAZdLFvvt4r4NwiRfxU5WAOy_vi6gxZjMvlusw,2870 +torchvision/ops/roi_align.py,sha256=GTn_Wlu94hzTp_249jJJEyG9NjVD_W42jBqUH17xsmg,12216 +torchvision/ops/roi_pool.py,sha256=5TUv79epZ2ME8mg1_nYSJTAGT-iASEbLd5mKCFyqHp8,2937 +torchvision/ops/stochastic_depth.py,sha256=ISZ9noJyZLxpTG-wa2VmPs66qjhVsP7ZxWHvumWSP3U,2236 +torchvision/transforms/__init__.py,sha256=EMft42B1JAiU11J1rxIN4Znis6EJPbp-bsGjAzH-24M,53 +torchvision/transforms/__pycache__/__init__.cpython-312.pyc,, +torchvision/transforms/__pycache__/_functional_pil.cpython-312.pyc,, +torchvision/transforms/__pycache__/_functional_tensor.cpython-312.pyc,, +torchvision/transforms/__pycache__/_functional_video.cpython-312.pyc,, +torchvision/transforms/__pycache__/_presets.cpython-312.pyc,, +torchvision/transforms/__pycache__/_transforms_video.cpython-312.pyc,, +torchvision/transforms/__pycache__/autoaugment.cpython-312.pyc,, +torchvision/transforms/__pycache__/functional.cpython-312.pyc,, +torchvision/transforms/__pycache__/transforms.cpython-312.pyc,, +torchvision/transforms/_functional_pil.py,sha256=owJiMj7vqTUVQFFbH_ePIY7P8s4_btlXsnGUjMjJonY,12118 +torchvision/transforms/_functional_tensor.py,sha256=moPXZtOKnsqqd3cLpJyVzv_rnvi2UkaPSvnXhnrgA3w,33930 +torchvision/transforms/_functional_video.py,sha256=YcV557YglbJsq9SRGJHFoRbtxawiLSJ1oM5rV75OyqQ,3857 +torchvision/transforms/_presets.py,sha256=Xlp7gLLnPQCjp8eY7w9uRKuQKV6wLs71ZZMIvCghlnA,8504 +torchvision/transforms/_transforms_video.py,sha256=Buz5LCWVPGiEonHE-cXIXfbkBhNc0qxVraxkNdxKp8o,4950 +torchvision/transforms/autoaugment.py,sha256=EbYTgbmv94L0W9xAj4RT4hos2OAToby0YDm_W3DA1-U,28105 +torchvision/transforms/functional.py,sha256=Cy_fjmdk9L4BE6zZW1jTsUFYwT-iN07ZP7vh9LhzDe0,67861 +torchvision/transforms/transforms.py,sha256=Zz87qs3lkbPLciTF-_x601IA29H5ohR_P6C0Im5zUCM,85981 +torchvision/transforms/v2/__init__.py,sha256=7FezWNjXp0YChcoPQ9XZhcEj9YsvzuKpIWAKvswcrD4,1676 +torchvision/transforms/v2/__pycache__/__init__.cpython-312.pyc,, +torchvision/transforms/v2/__pycache__/_augment.cpython-312.pyc,, +torchvision/transforms/v2/__pycache__/_auto_augment.cpython-312.pyc,, +torchvision/transforms/v2/__pycache__/_color.cpython-312.pyc,, +torchvision/transforms/v2/__pycache__/_container.cpython-312.pyc,, +torchvision/transforms/v2/__pycache__/_deprecated.cpython-312.pyc,, +torchvision/transforms/v2/__pycache__/_geometry.cpython-312.pyc,, +torchvision/transforms/v2/__pycache__/_meta.cpython-312.pyc,, +torchvision/transforms/v2/__pycache__/_misc.cpython-312.pyc,, +torchvision/transforms/v2/__pycache__/_temporal.cpython-312.pyc,, +torchvision/transforms/v2/__pycache__/_transform.cpython-312.pyc,, +torchvision/transforms/v2/__pycache__/_type_conversion.cpython-312.pyc,, +torchvision/transforms/v2/__pycache__/_utils.cpython-312.pyc,, +torchvision/transforms/v2/_augment.py,sha256=3iBHa5sehYpAcNLIokPTA06PiIPVD6jjxYWXP8nkkIA,16303 +torchvision/transforms/v2/_auto_augment.py,sha256=lZ6jkpu8x8ACCHPN43l3h2sADBCVb6nqyLgG1UpCmcU,33141 +torchvision/transforms/v2/_color.py,sha256=BP5MdZjkSfl6w9Pqv8uJpKQNA5lYauyKVEEkrSRfOQg,17008 +torchvision/transforms/v2/_container.py,sha256=e9YN9KgMT0SFGmnIkWt5sBXCYTE3PJ3Y8jymsB_D2Y0,6336 +torchvision/transforms/v2/_deprecated.py,sha256=T4MVk-4eFNUc8ryeIJhQwxTM5O1mJLhseRY9ITWHsiY,1940 +torchvision/transforms/v2/_geometry.py,sha256=ErZ__MMNqXeDu3CJKQHEnMVXhsYzvrFDkeY3gvdDlqo,70033 +torchvision/transforms/v2/_meta.py,sha256=lUSxbAW9oZwDnb41Zc-orr-B5laoyOybjnW8BlvzhYE,3165 +torchvision/transforms/v2/_misc.py,sha256=qy6leeBm-bOCArqAzdirrSWa_wQk2g_3EydjN3pxUBQ,24107 +torchvision/transforms/v2/_temporal.py,sha256=ZSmqtMebERMt4fX0RpTPzXMjpIXyLxRsMQx4FgYc2oE,899 +torchvision/transforms/v2/_transform.py,sha256=hhGfXOGaB7QoQ2Ct8uGRiMkAy-DAHd2WCc5mY30zS8A,9653 +torchvision/transforms/v2/_type_conversion.py,sha256=3cnXHFUYXwXcUAkX8LANI4DTu7EIF0BxrkKo9gLo1zE,3153 +torchvision/transforms/v2/_utils.py,sha256=QGODJb7i1JiE-6xXynM7mkqF8fqgfOfI-hvMW9UsHWI,9299 +torchvision/transforms/v2/functional/__init__.py,sha256=gq39_6BAjY_1ezid7SrkDPbBfOwi85yfODiEeljSD4A,3896 +torchvision/transforms/v2/functional/__pycache__/__init__.cpython-312.pyc,, +torchvision/transforms/v2/functional/__pycache__/_augment.cpython-312.pyc,, +torchvision/transforms/v2/functional/__pycache__/_color.cpython-312.pyc,, +torchvision/transforms/v2/functional/__pycache__/_deprecated.cpython-312.pyc,, +torchvision/transforms/v2/functional/__pycache__/_geometry.cpython-312.pyc,, +torchvision/transforms/v2/functional/__pycache__/_meta.cpython-312.pyc,, +torchvision/transforms/v2/functional/__pycache__/_misc.cpython-312.pyc,, +torchvision/transforms/v2/functional/__pycache__/_temporal.cpython-312.pyc,, +torchvision/transforms/v2/functional/__pycache__/_type_conversion.cpython-312.pyc,, +torchvision/transforms/v2/functional/__pycache__/_utils.cpython-312.pyc,, +torchvision/transforms/v2/functional/_augment.py,sha256=45thxTdRQ7IzHJS69IbFnryJ-tm03gDzdof3ybgX5Es,3476 +torchvision/transforms/v2/functional/_color.py,sha256=3t_d7YHsl5xPtkhLSiaTHFOKopQVU6d16e7DLNQUknQ,30377 +torchvision/transforms/v2/functional/_deprecated.py,sha256=veBAiEXVKIdchR6x5a-b_-Kpmum-79tPAuP7kCLpl1U,795 +torchvision/transforms/v2/functional/_geometry.py,sha256=YZ22eKMxjP8lN3T8DRMAby7SY5cbzY68jnU_y9u4sx0,113737 +torchvision/transforms/v2/functional/_meta.py,sha256=zaJV-wkKV3sOIGZQXDiKHlHY-AaXYJPEvoozXf1PkUs,30161 +torchvision/transforms/v2/functional/_misc.py,sha256=H4T13_M2G7EGIz9kdt8uYlZ-11N5zCYa1EpiMCha1NE,21924 +torchvision/transforms/v2/functional/_temporal.py,sha256=24CQCXXO12TnW7aUiUQdrk5DRSpTPONjjC4jaGh3lH4,1136 +torchvision/transforms/v2/functional/_type_conversion.py,sha256=78wl0dNPwX08jOCW6KcZSGy8RAQqyxMtdrTUQVQlUTM,869 +torchvision/transforms/v2/functional/_utils.py,sha256=6TDx4qExFfDO3-jBJisMhr28IdC55XyYMSbwUzge6jw,5488 +torchvision/tv_tensors/__init__.py,sha256=lfrHsCEmgo6qnKHPS2HgEbX1xs_p7kzJyOHTvDtfu3o,1545 +torchvision/tv_tensors/__pycache__/__init__.cpython-312.pyc,, +torchvision/tv_tensors/__pycache__/_bounding_boxes.cpython-312.pyc,, +torchvision/tv_tensors/__pycache__/_dataset_wrapper.cpython-312.pyc,, +torchvision/tv_tensors/__pycache__/_image.cpython-312.pyc,, +torchvision/tv_tensors/__pycache__/_keypoints.cpython-312.pyc,, +torchvision/tv_tensors/__pycache__/_mask.cpython-312.pyc,, +torchvision/tv_tensors/__pycache__/_torch_function_helpers.cpython-312.pyc,, +torchvision/tv_tensors/__pycache__/_tv_tensor.cpython-312.pyc,, +torchvision/tv_tensors/__pycache__/_video.cpython-312.pyc,, +torchvision/tv_tensors/_bounding_boxes.py,sha256=660-ICQdyzwCSQzb3f-xPNYvyv2aOYLjcXcKVL3JcVc,8124 +torchvision/tv_tensors/_dataset_wrapper.py,sha256=fNnk3CSXipBNFsmnsPpa10DRN0I_Ly4Xib2Y5Zng9Ro,24505 +torchvision/tv_tensors/_image.py,sha256=nh-p7Q9RZ3ESLb8gjM70ra0t6pXLg2HCvlA4VVUgvg8,1963 +torchvision/tv_tensors/_keypoints.py,sha256=udbFZ4tfGdFUOHQ3yaCUEVdW7djcWm_t_XTovg9UzvQ,4839 +torchvision/tv_tensors/_mask.py,sha256=k9kholaJt12YOvpyKfXnnilAzqgCt-4THrSCGAJ2GDU,1447 +torchvision/tv_tensors/_torch_function_helpers.py,sha256=XvE6PI3PZLJvQFObVKCaZgyDZ1pVc5bjct27wi8thlM,2324 +torchvision/tv_tensors/_tv_tensor.py,sha256=b4W2bKHzv5zV8cA__qRr9uiNZE6K2S2vNlqjSqka8ys,6361 +torchvision/tv_tensors/_video.py,sha256=hgbtLp9BSYHK4Mb5wqOhdPMDe5pd6gFPEF11YMh7p_k,1385 +torchvision/utils.py,sha256=Wgpdmqawx9dFI7Kfmg_mFhJ6eziv08j1Xwoi-sEBuhw,34563 +torchvision/version.py,sha256=2BUi1MMWBEeqtjad0jCl1cD8PkiqUCnYHWZLJjwOyNE,201 diff --git a/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/REQUESTED b/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/WHEEL b/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..cc9e52b5e838511fd027bbbb4a8f8bc137509e88 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (72.1.0) +Root-Is-Purelib: false +Tag: cp312-cp312-manylinux_2_28_x86_64 + diff --git a/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/top_level.txt b/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e35531e566f2a925d851b9d3b8fa99645838e6e0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision-0.29.0+cpu.dist-info/top_level.txt @@ -0,0 +1 @@ +torchvision diff --git a/.venv/lib/python3.12/site-packages/torchvision.libs/libjpeg.185109e6.so.8 b/.venv/lib/python3.12/site-packages/torchvision.libs/libjpeg.185109e6.so.8 new file mode 100644 index 0000000000000000000000000000000000000000..eb093675910374c8c5a0724781011ce9bee543a7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision.libs/libjpeg.185109e6.so.8 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:944920e943b2ef28a66c3c8196d33447689ffca791152f7b422c839f11616b47 +size 877472 diff --git a/.venv/lib/python3.12/site-packages/torchvision.libs/libpng16.fdd68bd0.so.16 b/.venv/lib/python3.12/site-packages/torchvision.libs/libpng16.fdd68bd0.so.16 new file mode 100644 index 0000000000000000000000000000000000000000..b54b6a26717328f923b60fade49f2075fb95b30f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision.libs/libpng16.fdd68bd0.so.16 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d95d708151d1d3b68a1b8b32fe8c9cc151a4184d665d62d6997529c8c464c25 +size 288001 diff --git a/.venv/lib/python3.12/site-packages/torchvision.libs/libsharpyuv.a0b54fe1.so.0 b/.venv/lib/python3.12/site-packages/torchvision.libs/libsharpyuv.a0b54fe1.so.0 new file mode 100644 index 0000000000000000000000000000000000000000..5e306570cfb6e9b13e8e6df478590021693090d6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision.libs/libsharpyuv.a0b54fe1.so.0 differ diff --git a/.venv/lib/python3.12/site-packages/torchvision.libs/libwebp.14e109ad.so.7 b/.venv/lib/python3.12/site-packages/torchvision.libs/libwebp.14e109ad.so.7 new file mode 100644 index 0000000000000000000000000000000000000000..68b087e3959750507a233d7b9436a368a8eb9340 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision.libs/libwebp.14e109ad.so.7 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a221d3142e30e1624b196122d90a6924b4a8cf211dcbe4e16c394706d7b0c251 +size 790273 diff --git a/.venv/lib/python3.12/site-packages/torchvision.libs/libz.1140de3a.so.1 b/.venv/lib/python3.12/site-packages/torchvision.libs/libz.1140de3a.so.1 new file mode 100644 index 0000000000000000000000000000000000000000..c7e51badab1107f0e1788895fd5ee2bfbdb80abe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision.libs/libz.1140de3a.so.1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0900010993ecb9e3bf674459147f3433b5b001aeea94d5ba43b61c867e596cd1 +size 117416 diff --git a/.venv/lib/python3.12/site-packages/torchvision/_C_stable.so b/.venv/lib/python3.12/site-packages/torchvision/_C_stable.so new file mode 100644 index 0000000000000000000000000000000000000000..ca67804d646ad8da687ca7a12d44fdc485e21e1c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/_C_stable.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f3581fd6c26bca7f050750fc49648ce7a680503f4da78206a73f58a8fa0da2b9 +size 496712 diff --git a/.venv/lib/python3.12/site-packages/torchvision/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e853d3b1be68c6e2c16f7fbdf0d89f3357579340 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/__init__.py @@ -0,0 +1,82 @@ +from modulefinder import Module + +import torch + +# Don't re-order these, we need to load the _C_stable extension (done when importing +# .extension) before entering _meta_registrations. +from . import extension # usort:skip # noqa: F401 +from torchvision import ( + _autograd_registrations, + _meta_registrations, + datasets, + io, + models, + ops, + transforms, + utils, +) # usort:skip + +try: + from .version import __version__ # noqa: F401 +except ImportError: + pass + + +_image_backend = "PIL" + +_video_backend = "pyav" + + +def set_image_backend(backend): + """ + Specifies the package used to load images. + + Args: + backend (string): Name of the image backend. one of {'PIL', 'accimage'}. + The :mod:`accimage` package uses the Intel IPP library. It is + generally faster than PIL, but does not support as many operations. + """ + global _image_backend + if backend not in ["PIL", "accimage"]: + raise ValueError(f"Invalid backend '{backend}'. Options are 'PIL' and 'accimage'") + _image_backend = backend + + +def get_image_backend(): + """ + Gets the name of the package used to load images + """ + return _image_backend + + +def set_video_backend(backend): + """ + Specifies the package used to decode videos. + + Args: + backend (string): Name of the video backend. Only 'pyav' is supported. + The :mod:`pyav` package uses the 3rd party PyAv library. It is a Pythonic + binding for the FFmpeg libraries. + """ + pass + + +def get_video_backend(): + """ + Returns the currently active video backend used to decode videos. + + Returns: + str: Name of the video backend. Currently only 'pyav' is supported. + """ + + return _video_backend + + +def _is_tracing(): + return torch._C._get_tracing_state() + + +def disable_beta_transforms_warning(): + # Noop, only exists to avoid breaking existing code. + # See https://github.com/pytorch/vision/issues/7896 + pass diff --git a/.venv/lib/python3.12/site-packages/torchvision/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5c10a182bbca019fc52fd9d0fbc1acab4a4673f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/__pycache__/_autograd_registrations.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/_autograd_registrations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acc3d2e7b1df226dfdc22d67dadaa7cdbfef1e1e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/_autograd_registrations.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/__pycache__/_internally_replaced_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/_internally_replaced_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d51da7d9cf099bf1b3ea4d982eeb6059942cf1e8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/_internally_replaced_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/__pycache__/_meta_registrations.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/_meta_registrations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d1be5726c1519c1eabc72a1b8c505a93713eb04 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/_meta_registrations.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d2daca49890f9e5723bf00c0816e6c2994361fa Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/__pycache__/extension.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/extension.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..860ef8c1d62169d8c4a151b79b1b62d7ab6cbfbc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/extension.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8594a9d16f0628d928d4bd99ab225a422ab40c7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/__pycache__/version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6da84121fada022a9cfc286eb4c08f3b5941be31 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/__pycache__/version.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/_autograd_registrations.py b/.venv/lib/python3.12/site-packages/torchvision/_autograd_registrations.py new file mode 100644 index 0000000000000000000000000000000000000000..da4cbc358d849f6faccc6503db4bc28d59858a1d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/_autograd_registrations.py @@ -0,0 +1,377 @@ +import torch +import torch.library + +# Ensure that torch.ops.torchvision is visible +import torchvision.extension # noqa: F401 + + +# ===================================================================== +# Autograd registrations +# ===================================================================== + + +# --- roi_align --- +def _roi_align_setup_context(ctx, inputs, output): + input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio, aligned = inputs + ctx.save_for_backward(rois) + ctx.input_shape = input.shape + ctx.spatial_scale = spatial_scale + ctx.pooled_height = pooled_height + ctx.pooled_width = pooled_width + ctx.sampling_ratio = sampling_ratio + ctx.aligned = aligned + + +def _roi_align_backward(ctx, grad_output): + if grad_output.device.type in ("cuda", "mps"): + torch._prims_common.alert_not_deterministic("roi_align_backward_kernel") + (rois,) = ctx.saved_tensors + batch_size, channels, height, width = ctx.input_shape + grad_input = torch.ops.torchvision._roi_align_backward( + grad_output, + rois, + ctx.spatial_scale, + ctx.pooled_height, + ctx.pooled_width, + batch_size, + channels, + height, + width, + ctx.sampling_ratio, + ctx.aligned, + ) + return grad_input, None, None, None, None, None, None + + +# --- roi_pool --- +def _roi_pool_setup_context(ctx, inputs, output): + input, rois, spatial_scale, pooled_height, pooled_width = inputs + pooled, argmax = output + ctx.save_for_backward(rois, argmax) + ctx.input_shape = input.shape + ctx.spatial_scale = spatial_scale + ctx.pooled_height = pooled_height + ctx.pooled_width = pooled_width + + +def _roi_pool_backward(ctx, grad_output, _grad_argmax): + if grad_output.device.type in ("cuda", "mps"): + torch._prims_common.alert_not_deterministic("roi_pool_backward_kernel") + rois, argmax = ctx.saved_tensors + batch_size, channels, height, width = ctx.input_shape + grad_input = torch.ops.torchvision._roi_pool_backward( + grad_output, + rois, + argmax, + ctx.spatial_scale, + ctx.pooled_height, + ctx.pooled_width, + batch_size, + channels, + height, + width, + ) + return grad_input, None, None, None, None + + +# --- ps_roi_align --- +def _ps_roi_align_setup_context(ctx, inputs, output): + input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio = inputs + pooled, channel_mapping = output + ctx.save_for_backward(rois, channel_mapping) + ctx.input_shape = input.shape + ctx.spatial_scale = spatial_scale + ctx.pooled_height = pooled_height + ctx.pooled_width = pooled_width + ctx.sampling_ratio = sampling_ratio + + +def _ps_roi_align_backward(ctx, grad_output, _grad_channel_mapping): + if grad_output.device.type in ("cuda", "mps"): + torch._prims_common.alert_not_deterministic("ps_roi_align_backward_kernel") + rois, channel_mapping = ctx.saved_tensors + batch_size, channels, height, width = ctx.input_shape + grad_input = torch.ops.torchvision._ps_roi_align_backward( + grad_output, + rois, + channel_mapping, + ctx.spatial_scale, + ctx.pooled_height, + ctx.pooled_width, + ctx.sampling_ratio, + batch_size, + channels, + height, + width, + ) + return grad_input, None, None, None, None, None + + +# --- ps_roi_pool --- +def _ps_roi_pool_setup_context(ctx, inputs, output): + input, rois, spatial_scale, pooled_height, pooled_width = inputs + pooled, channel_mapping = output + ctx.save_for_backward(rois, channel_mapping) + ctx.input_shape = input.shape + ctx.spatial_scale = spatial_scale + ctx.pooled_height = pooled_height + ctx.pooled_width = pooled_width + + +def _ps_roi_pool_backward(ctx, grad_output, _grad_channel_mapping): + if grad_output.device.type in ("cuda", "mps"): + torch._prims_common.alert_not_deterministic("ps_roi_pool_backward_kernel") + rois, channel_mapping = ctx.saved_tensors + batch_size, channels, height, width = ctx.input_shape + grad_input = torch.ops.torchvision._ps_roi_pool_backward( + grad_output, + rois, + channel_mapping, + ctx.spatial_scale, + ctx.pooled_height, + ctx.pooled_width, + batch_size, + channels, + height, + width, + ) + return grad_input, None, None, None, None + + +# --- deform_conv2d --- +def _deform_conv2d_setup_context(ctx, inputs, output): + ( + input, + weight, + offset, + mask, + bias, + stride_h, + stride_w, + pad_h, + pad_w, + dilation_h, + dilation_w, + groups, + offset_groups, + use_mask, + ) = inputs + ctx.save_for_backward(input, weight, offset, mask, bias) + ctx.stride_h = stride_h + ctx.stride_w = stride_w + ctx.pad_h = pad_h + ctx.pad_w = pad_w + ctx.dilation_h = dilation_h + ctx.dilation_w = dilation_w + ctx.groups = groups + ctx.offset_groups = offset_groups + ctx.use_mask = use_mask + + +def _deform_conv2d_backward(ctx, grad_output): + if grad_output.device.type == "cuda": + torch._prims_common.alert_not_deterministic("compute_grad_input") + input, weight, offset, mask, bias = ctx.saved_tensors + grad_input, grad_weight, grad_offset, grad_mask, grad_bias = torch.ops.torchvision._deform_conv2d_backward( + grad_output, + input, + weight, + offset, + mask, + bias, + ctx.stride_h, + ctx.stride_w, + ctx.pad_h, + ctx.pad_w, + ctx.dilation_h, + ctx.dilation_w, + ctx.groups, + ctx.offset_groups, + ctx.use_mask, + ) + return ( + grad_input, + grad_weight, + grad_offset, + grad_mask, + grad_bias, + None, + None, + None, + None, + None, + None, + None, + None, + None, + ) + + +# --- Backward op autograd (double-backward blockers) --- +def _no_double_backward(op_name): + def backward(ctx, *grads): + raise RuntimeError(f"double backwards on {op_name} not supported") + + return backward + + +# ===================================================================== +# Autocast registrations +# ===================================================================== + +_all_autocast_keys = ( + torch._C.DispatchKeySet(torch._C.DispatchKey.AutocastCPU) + | torch._C.DispatchKeySet(torch._C.DispatchKey.AutocastCUDA) + | torch._C.DispatchKeySet(torch._C.DispatchKey.AutocastXPU) # type: ignore[attr-defined] +) + + +def _autocast_cast(tensor): + """Cast to float32 matching at::autocast::cached_cast(at::kFloat, ...) behavior. + + Skips non-floating-point tensors and float64 tensors. + """ + if tensor.is_floating_point() and tensor.dtype is not torch.float64: + return tensor.float() + return tensor + + +def _autocast_nms(dets, scores, iou_threshold): + with torch._C._ExcludeDispatchKeyGuard(_all_autocast_keys): + return torch.ops.torchvision.nms( + _autocast_cast(dets), + _autocast_cast(scores), + iou_threshold, + ) + + +def _autocast_roi_align(input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio, aligned): + orig_dtype = input.dtype + with torch._C._ExcludeDispatchKeyGuard(_all_autocast_keys): + return torch.ops.torchvision.roi_align( + _autocast_cast(input), + _autocast_cast(rois), + spatial_scale, + pooled_height, + pooled_width, + sampling_ratio, + aligned, + ).to(orig_dtype) + + +def _autocast_roi_pool(input, rois, spatial_scale, pooled_height, pooled_width): + orig_dtype = input.dtype + with torch._C._ExcludeDispatchKeyGuard(_all_autocast_keys): + output, argmax = torch.ops.torchvision.roi_pool( + _autocast_cast(input), + _autocast_cast(rois), + spatial_scale, + pooled_height, + pooled_width, + ) + return output.to(orig_dtype), argmax.to(orig_dtype) + + +def _autocast_ps_roi_align(input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio): + orig_dtype = input.dtype + with torch._C._ExcludeDispatchKeyGuard(_all_autocast_keys): + output, channel_mapping = torch.ops.torchvision.ps_roi_align( + _autocast_cast(input), + _autocast_cast(rois), + spatial_scale, + pooled_height, + pooled_width, + sampling_ratio, + ) + return output.to(orig_dtype), channel_mapping.to(orig_dtype) + + +def _autocast_ps_roi_pool(input, rois, spatial_scale, pooled_height, pooled_width): + orig_dtype = input.dtype + with torch._C._ExcludeDispatchKeyGuard(_all_autocast_keys): + output, channel_mapping = torch.ops.torchvision.ps_roi_pool( + _autocast_cast(input), + _autocast_cast(rois), + spatial_scale, + pooled_height, + pooled_width, + ) + return output.to(orig_dtype), channel_mapping.to(orig_dtype) + + +def _autocast_deform_conv2d( + input, + weight, + offset, + mask, + bias, + stride_h, + stride_w, + pad_h, + pad_w, + dilation_h, + dilation_w, + groups, + offset_groups, + use_mask, +): + orig_dtype = input.dtype + with torch._C._ExcludeDispatchKeyGuard(_all_autocast_keys): + return torch.ops.torchvision.deform_conv2d( + _autocast_cast(input), + _autocast_cast(weight), + _autocast_cast(offset), + _autocast_cast(mask), + _autocast_cast(bias), + stride_h, + stride_w, + pad_h, + pad_w, + dilation_h, + dilation_w, + groups, + offset_groups, + use_mask, + ).to(orig_dtype) + + +# ===================================================================== +# Perform registrations +# ===================================================================== + +if torchvision.extension._has_ops(): + # --- Autograd: forward ops --- + torch.library.register_autograd( + "torchvision::roi_align", _roi_align_backward, setup_context=_roi_align_setup_context + ) + torch.library.register_autograd("torchvision::roi_pool", _roi_pool_backward, setup_context=_roi_pool_setup_context) + torch.library.register_autograd( + "torchvision::ps_roi_align", _ps_roi_align_backward, setup_context=_ps_roi_align_setup_context + ) + torch.library.register_autograd( + "torchvision::ps_roi_pool", _ps_roi_pool_backward, setup_context=_ps_roi_pool_setup_context + ) + torch.library.register_autograd( + "torchvision::deform_conv2d", _deform_conv2d_backward, setup_context=_deform_conv2d_setup_context + ) + + # --- Autograd: backward ops (block double backward) --- + torch.library.register_autograd("torchvision::_roi_align_backward", _no_double_backward("roi_align")) + torch.library.register_autograd("torchvision::_roi_pool_backward", _no_double_backward("roi_pool")) + torch.library.register_autograd("torchvision::_ps_roi_align_backward", _no_double_backward("ps_roi_align")) + torch.library.register_autograd("torchvision::_ps_roi_pool_backward", _no_double_backward("ps_roi_pool")) + torch.library.register_autograd("torchvision::_deform_conv2d_backward", _no_double_backward("deform_conv2d")) + + # --- Autocast --- + _autocast_lib = torch.library.Library("torchvision", "IMPL") + + # nms and roi_align: registered for all autocast device types + for _key in ("AutocastCUDA", "AutocastCPU", "AutocastXPU"): + _autocast_lib.impl("nms", _autocast_nms, _key) + _autocast_lib.impl("roi_align", _autocast_roi_align, _key) + + # Other ops: CUDA autocast only + _autocast_lib.impl("roi_pool", _autocast_roi_pool, "AutocastCUDA") + _autocast_lib.impl("ps_roi_align", _autocast_ps_roi_align, "AutocastCUDA") + _autocast_lib.impl("ps_roi_pool", _autocast_ps_roi_pool, "AutocastCUDA") + _autocast_lib.impl("deform_conv2d", _autocast_deform_conv2d, "AutocastCUDA") diff --git a/.venv/lib/python3.12/site-packages/torchvision/_internally_replaced_utils.py b/.venv/lib/python3.12/site-packages/torchvision/_internally_replaced_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..253920add718f75378017cfd1d7f78a4fd0b3cc7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/_internally_replaced_utils.py @@ -0,0 +1,51 @@ +import importlib.machinery +import os + +from torch.hub import _get_torch_home + + +_HOME = os.path.join(_get_torch_home(), "datasets", "vision") +_USE_SHARDED_DATASETS = False +IN_FBCODE = False + + +def _download_file_from_remote_location(fpath: str, url: str) -> None: + pass + + +def _is_remote_location_available() -> bool: + return False + + +try: + from torch.hub import load_state_dict_from_url # noqa: 401 +except ImportError: + from torch.utils.model_zoo import load_url as load_state_dict_from_url # noqa: 401 + + +def _get_extension_path(lib_name): + + lib_dir = os.path.dirname(__file__) + if os.name == "nt": + # Register the main torchvision library location on the default DLL path + import ctypes + + kernel32 = ctypes.WinDLL("kernel32.dll", use_last_error=True) + with_load_library_flags = hasattr(kernel32, "AddDllDirectory") + prev_error_mode = kernel32.SetErrorMode(0x0001) + + if with_load_library_flags: + kernel32.AddDllDirectory.restype = ctypes.c_void_p + + os.add_dll_directory(lib_dir) + + kernel32.SetErrorMode(prev_error_mode) + + loader_details = (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES) + + extfinder = importlib.machinery.FileFinder(lib_dir, loader_details) + ext_specs = extfinder.find_spec(lib_name) + if ext_specs is None: + raise ImportError(f"Could not find module '{lib_name}' in {lib_dir}") + + return ext_specs.origin diff --git a/.venv/lib/python3.12/site-packages/torchvision/_meta_registrations.py b/.venv/lib/python3.12/site-packages/torchvision/_meta_registrations.py new file mode 100644 index 0000000000000000000000000000000000000000..cb2602acc7e206b6e4422851a13dbcce9f843610 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/_meta_registrations.py @@ -0,0 +1,266 @@ +import functools + +import torch +import torch._custom_ops +import torch.library + +# Ensure that torch.ops.torchvision is visible +import torchvision.extension # noqa: F401 + + +@functools.lru_cache(None) +def get_meta_lib(): + return torch.library.Library("torchvision", "IMPL", "Meta") + + +def register_meta(op_name, overload_name="default"): + def wrapper(fn): + if torchvision.extension._has_ops(): + get_meta_lib().impl(getattr(getattr(torch.ops.torchvision, op_name), overload_name), fn) + return fn + + return wrapper + + +@register_meta("roi_align") +def meta_roi_align(input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio, aligned): + torch._check(rois.size(1) == 5, lambda: "rois must have shape as Tensor[K, 5]") + torch._check( + input.dtype == rois.dtype, + lambda: ( + "Expected tensor for input to have the same type as tensor for rois; " + f"but type {input.dtype} does not equal {rois.dtype}" + ), + ) + num_rois = rois.size(0) + channels = input.size(1) + return input.new_empty((num_rois, channels, pooled_height, pooled_width)) + + +@register_meta("_roi_align_backward") +def meta_roi_align_backward( + grad, rois, spatial_scale, pooled_height, pooled_width, batch_size, channels, height, width, sampling_ratio, aligned +): + torch._check( + grad.dtype == rois.dtype, + lambda: ( + "Expected tensor for grad to have the same type as tensor for rois; " + f"but type {grad.dtype} does not equal {rois.dtype}" + ), + ) + return grad.new_empty((batch_size, channels, height, width)) + + +@register_meta("ps_roi_align") +def meta_ps_roi_align(input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio): + torch._check(rois.size(1) == 5, lambda: "rois must have shape as Tensor[K, 5]") + torch._check( + input.dtype == rois.dtype, + lambda: ( + "Expected tensor for input to have the same type as tensor for rois; " + f"but type {input.dtype} does not equal {rois.dtype}" + ), + ) + channels = input.size(1) + torch._check( + channels % (pooled_height * pooled_width) == 0, + "input channels must be a multiple of pooling height * pooling width", + ) + + num_rois = rois.size(0) + out_size = (num_rois, channels // (pooled_height * pooled_width), pooled_height, pooled_width) + return input.new_empty(out_size), torch.empty(out_size, dtype=torch.int32, device="meta") + + +@register_meta("_ps_roi_align_backward") +def meta_ps_roi_align_backward( + grad, + rois, + channel_mapping, + spatial_scale, + pooled_height, + pooled_width, + sampling_ratio, + batch_size, + channels, + height, + width, +): + torch._check( + grad.dtype == rois.dtype, + lambda: ( + "Expected tensor for grad to have the same type as tensor for rois; " + f"but type {grad.dtype} does not equal {rois.dtype}" + ), + ) + return grad.new_empty((batch_size, channels, height, width)) + + +@register_meta("roi_pool") +def meta_roi_pool(input, rois, spatial_scale, pooled_height, pooled_width): + torch._check(rois.size(1) == 5, lambda: "rois must have shape as Tensor[K, 5]") + torch._check( + input.dtype == rois.dtype, + lambda: ( + "Expected tensor for input to have the same type as tensor for rois; " + f"but type {input.dtype} does not equal {rois.dtype}" + ), + ) + num_rois = rois.size(0) + channels = input.size(1) + out_size = (num_rois, channels, pooled_height, pooled_width) + return input.new_empty(out_size), torch.empty(out_size, device="meta", dtype=torch.int32) + + +@register_meta("_roi_pool_backward") +def meta_roi_pool_backward( + grad, rois, argmax, spatial_scale, pooled_height, pooled_width, batch_size, channels, height, width +): + torch._check( + grad.dtype == rois.dtype, + lambda: ( + "Expected tensor for grad to have the same type as tensor for rois; " + f"but type {grad.dtype} does not equal {rois.dtype}" + ), + ) + return grad.new_empty((batch_size, channels, height, width)) + + +@register_meta("ps_roi_pool") +def meta_ps_roi_pool(input, rois, spatial_scale, pooled_height, pooled_width): + torch._check(rois.size(1) == 5, lambda: "rois must have shape as Tensor[K, 5]") + torch._check( + input.dtype == rois.dtype, + lambda: ( + "Expected tensor for input to have the same type as tensor for rois; " + f"but type {input.dtype} does not equal {rois.dtype}" + ), + ) + channels = input.size(1) + torch._check( + channels % (pooled_height * pooled_width) == 0, + "input channels must be a multiple of pooling height * pooling width", + ) + num_rois = rois.size(0) + out_size = (num_rois, channels // (pooled_height * pooled_width), pooled_height, pooled_width) + return input.new_empty(out_size), torch.empty(out_size, device="meta", dtype=torch.int32) + + +@register_meta("_ps_roi_pool_backward") +def meta_ps_roi_pool_backward( + grad, rois, channel_mapping, spatial_scale, pooled_height, pooled_width, batch_size, channels, height, width +): + torch._check( + grad.dtype == rois.dtype, + lambda: ( + "Expected tensor for grad to have the same type as tensor for rois; " + f"but type {grad.dtype} does not equal {rois.dtype}" + ), + ) + return grad.new_empty((batch_size, channels, height, width)) + + +@torch.library.register_fake("torchvision::nms") +def meta_nms(dets, scores, iou_threshold): + torch._check(dets.dim() == 2, lambda: f"boxes should be a 2d tensor, got {dets.dim()}D") + torch._check(dets.size(1) == 4, lambda: f"boxes should have 4 elements in dimension 1, got {dets.size(1)}") + torch._check(scores.dim() == 1, lambda: f"scores should be a 1d tensor, got {scores.dim()}") + torch._check( + dets.size(0) == scores.size(0), + lambda: f"boxes and scores should have same number of elements in dimension 0, got {dets.size(0)} and {scores.size(0)}", + ) + ctx = torch._custom_ops.get_ctx() + num_to_keep = ctx.create_unbacked_symint() + return dets.new_empty(num_to_keep, dtype=torch.long) + + +@torch.library.register_fake("torchvision::qnms") +def meta_qnms(dets, scores, iou_threshold): + torch._check(dets.dim() == 2, lambda: f"boxes should be a 2d tensor, got {dets.dim()}D") + torch._check(dets.size(1) == 4, lambda: f"boxes should have 4 elements in dimension 1, got {dets.size(1)}") + torch._check(scores.dim() == 1, lambda: f"scores should be a 1d tensor, got {scores.dim()}") + torch._check( + dets.size(0) == scores.size(0), + lambda: f"boxes and scores should have same number of elements in dimension 0, got {dets.size(0)} and {scores.size(0)}", + ) + ctx = torch._custom_ops.get_ctx() + num_to_keep = ctx.create_unbacked_symint() + return dets.new_empty(num_to_keep, dtype=torch.long) + + +@register_meta("qroi_align") +def meta_qroi_align( + input, + rois, + input_scale, + input_zero_point, + rois_scale, + rois_zero_point, + spatial_scale, + pooled_height, + pooled_width, + sampling_ratio, + aligned, +): + torch._check(rois.size(1) == 5, lambda: "rois must have shape as Tensor[K, 5]") + torch._check( + input.dtype == rois.dtype, + lambda: ( + "Expected tensor for input to have the same type as tensor for rois; " + f"but type {input.dtype} does not equal {rois.dtype}" + ), + ) + num_rois = rois.size(0) + channels = input.size(1) + return input.new_empty((num_rois, channels, pooled_height, pooled_width)) + + +@register_meta("deform_conv2d") +def meta_deform_conv2d( + input, + weight, + offset, + mask, + bias, + stride_h, + stride_w, + pad_h, + pad_w, + dil_h, + dil_w, + n_weight_grps, + n_offset_grps, + use_mask, +): + + out_height, out_width = offset.shape[-2:] + out_channels = weight.shape[0] + batch_size = input.shape[0] + return input.new_empty((batch_size, out_channels, out_height, out_width)) + + +@register_meta("_deform_conv2d_backward") +def meta_deform_conv2d_backward( + grad, + input, + weight, + offset, + mask, + bias, + stride_h, + stride_w, + pad_h, + pad_w, + dilation_h, + dilation_w, + groups, + offset_groups, + use_mask, +): + + grad_input = input.new_empty(input.shape) + grad_weight = weight.new_empty(weight.shape) + grad_offset = offset.new_empty(offset.shape) + grad_mask = mask.new_empty(mask.shape) + grad_bias = bias.new_empty(bias.shape) + return grad_input, grad_weight, grad_offset, grad_mask, grad_bias diff --git a/.venv/lib/python3.12/site-packages/torchvision/_utils.py b/.venv/lib/python3.12/site-packages/torchvision/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..23f479587462dfb604a074395caaec982283b313 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/_utils.py @@ -0,0 +1,31 @@ +import enum +from collections.abc import Sequence +from typing import TypeVar + +T = TypeVar("T", bound=enum.Enum) + + +class StrEnumMeta(enum.EnumMeta): + auto = enum.auto + + def from_str(self: type[T], member: str) -> T: # type: ignore[misc] + try: + return self[member] + except KeyError: + raise ValueError(f"Unknown value '{member}' for {self.__name__}.") from None + + +class StrEnum(enum.Enum, metaclass=StrEnumMeta): + pass + + +def sequence_to_str(seq: Sequence, separate_last: str = "") -> str: + if not seq: + return "" + if len(seq) == 1: + return f"'{seq[0]}'" + + head = "'" + "', '".join([str(item) for item in seq[:-1]]) + "'" + tail = f"{'' if separate_last and len(seq) == 2 else ','} {separate_last}'{seq[-1]}'" + + return head + tail diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4005b4a90729c9fe1b811f7388bd8453998d2322 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/__init__.py @@ -0,0 +1,147 @@ +from ._optical_flow import FlyingChairs, FlyingThings3D, HD1K, KittiFlow, Sintel +from ._stereo_matching import ( + CarlaStereo, + CREStereo, + ETH3DStereo, + FallingThingsStereo, + InStereo2k, + Kitti2012Stereo, + Kitti2015Stereo, + Middlebury2014Stereo, + SceneFlowStereo, + SintelStereo, +) +from .caltech import Caltech101, Caltech256 +from .celeba import CelebA +from .cifar import CIFAR10, CIFAR100 +from .cityscapes import Cityscapes +from .clevr import CLEVRClassification +from .coco import CocoCaptions, CocoDetection +from .country211 import Country211 +from .dtd import DTD +from .eurosat import EuroSAT +from .fakedata import FakeData +from .fer2013 import FER2013 +from .fgvc_aircraft import FGVCAircraft +from .flickr import Flickr30k, Flickr8k +from .flowers102 import Flowers102 +from .folder import DatasetFolder, ImageFolder +from .food101 import Food101 +from .gtsrb import GTSRB +from .hmdb51 import HMDB51 +from .imagenet import ImageNet +from .imagenette import Imagenette +from .inaturalist import INaturalist +from .kinetics import Kinetics +from .kitti import Kitti +from .lfw import LFWPairs, LFWPeople +from .lsun import LSUN, LSUNClass +from .mnist import EMNIST, FashionMNIST, KMNIST, MNIST, QMNIST +from .moving_mnist import MovingMNIST +from .omniglot import Omniglot +from .oxford_iiit_pet import OxfordIIITPet +from .pcam import PCAM +from .phototour import PhotoTour +from .places365 import Places365 +from .rendered_sst2 import RenderedSST2 +from .sbd import SBDataset +from .sbu import SBU +from .semeion import SEMEION +from .stanford_cars import StanfordCars +from .stl10 import STL10 +from .sun397 import SUN397 +from .svhn import SVHN +from .ucf101 import UCF101 +from .usps import USPS +from .vision import VisionDataset +from .voc import VOCDetection, VOCSegmentation +from .widerface import WIDERFace + +__all__ = ( + "LSUN", + "LSUNClass", + "ImageFolder", + "DatasetFolder", + "FakeData", + "CocoCaptions", + "CocoDetection", + "CIFAR10", + "CIFAR100", + "EMNIST", + "FashionMNIST", + "QMNIST", + "MNIST", + "KMNIST", + "MovingMNIST", + "StanfordCars", + "STL10", + "SUN397", + "SVHN", + "PhotoTour", + "SEMEION", + "Omniglot", + "SBU", + "Flickr8k", + "Flickr30k", + "Flowers102", + "VOCSegmentation", + "VOCDetection", + "Cityscapes", + "ImageNet", + "Caltech101", + "Caltech256", + "CelebA", + "WIDERFace", + "SBDataset", + "VisionDataset", + "USPS", + "Kinetics", + "HMDB51", + "UCF101", + "Places365", + "Kitti", + "INaturalist", + "LFWPeople", + "LFWPairs", + "KittiFlow", + "Sintel", + "FlyingChairs", + "FlyingThings3D", + "HD1K", + "Food101", + "DTD", + "FER2013", + "GTSRB", + "CLEVRClassification", + "OxfordIIITPet", + "PCAM", + "Country211", + "FGVCAircraft", + "EuroSAT", + "RenderedSST2", + "Kitti2012Stereo", + "Kitti2015Stereo", + "CarlaStereo", + "Middlebury2014Stereo", + "CREStereo", + "FallingThingsStereo", + "SceneFlowStereo", + "SintelStereo", + "InStereo2k", + "ETH3DStereo", + "wrap_dataset_for_transforms_v2", + "Imagenette", +) + + +# We override current module's attributes to handle the import: +# from torchvision.datasets import wrap_dataset_for_transforms_v2 +# without a cyclic error. +# Ref: https://peps.python.org/pep-0562/ +def __getattr__(name): + if name in ("wrap_dataset_for_transforms_v2",): + from torchvision.tv_tensors._dataset_wrapper import wrap_dataset_for_transforms_v2 + + return wrap_dataset_for_transforms_v2 + + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0f59525440cf80e553340ff41b11195d8bcdbc9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/_optical_flow.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/_optical_flow.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00712a063479d87814ad380e0be1ceffcdec2fe3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/_optical_flow.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/_stereo_matching.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/_stereo_matching.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c4675b38882c816f174db92a120b5ce0da22702 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/_stereo_matching.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/caltech.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/caltech.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0076d9713431af26917bb768b3bcf0e2aed95a08 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/caltech.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/celeba.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/celeba.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7976fa55dd16a369a5ec6ab4029d262185f441fe Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/celeba.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/cifar.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/cifar.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5cf77ad648c470d19469b36a7748dfedb883039 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/cifar.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/cityscapes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/cityscapes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21b12e92e891829509264f4520c4dae838c2f125 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/cityscapes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/clevr.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/clevr.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dfaaf79b64cd0c8b847b2a5234ad64164d9f4b3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/clevr.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/coco.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/coco.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..883f2e98c228e46fa543d552dc235654a28a69ed Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/coco.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/country211.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/country211.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a99df2fe6745b04f7720801b546b6bb7dfa044c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/country211.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/dtd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/dtd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8d27391d564723018ccd719a2fb0b3519098314 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/dtd.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/eurosat.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/eurosat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9952528222e72ef554e3a6f2c3380ae22064956 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/eurosat.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/fakedata.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/fakedata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b47e893cbd9d0e89d978f3bd2a43ddfcb82c1e35 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/fakedata.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/fer2013.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/fer2013.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28f6477357f350c3fc3eed67afa2fb53a8daa331 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/fer2013.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/fgvc_aircraft.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/fgvc_aircraft.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41fc4bc428894271b5bcbc701d9a50c9a0a41bc4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/fgvc_aircraft.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/flickr.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/flickr.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9877d50866bb3a3b08e862357cb22b98238925b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/flickr.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/flowers102.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/flowers102.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d07561ea344f63b69a3e9bcdbc196f2c272a712 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/flowers102.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/folder.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/folder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5730e75df1ceb7da714a7f88fd3611d978dd610c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/folder.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/food101.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/food101.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..425aa439a80b30b527c30c735580ce5432286a67 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/food101.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/gtsrb.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/gtsrb.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e944606fa5c8c952da8fde4820a76c90d504ed7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/gtsrb.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/hmdb51.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/hmdb51.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e47b6b38572cdf0a0a7e92f62f421a8d960b5930 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/hmdb51.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/imagenet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/imagenet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0f2353746013f25177ae86f6b21512d729df8f3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/imagenet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/imagenette.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/imagenette.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b64b01d1670cbb170c128a03c11edf774bcf516a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/imagenette.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/inaturalist.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/inaturalist.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfbf8dd5886f6210525c9d70193b317a8f2cc4a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/inaturalist.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/kinetics.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/kinetics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcdd7ec327b6499becf1481c3dd2513e8b27fe87 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/kinetics.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/kitti.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/kitti.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c345dc3a47586c0a3278f2a5465b111d250d4637 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/kitti.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/lfw.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/lfw.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83ed34bb9307058ec37ac104ffe56f3a07a97c44 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/lfw.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/lsun.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/lsun.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cdf4d71bd9433bccd29239b1f4e823fd908b208 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/lsun.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/mnist.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/mnist.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a1b1fb74b11aa03d04f3799d0d237f51c076d75 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/mnist.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/moving_mnist.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/moving_mnist.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..070c434c3e87fb3f6593083a81da396bab7923cf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/moving_mnist.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/omniglot.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/omniglot.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4ac3ad5153e4f9f6402f0ee5ac22844967f0be1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/omniglot.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/oxford_iiit_pet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/oxford_iiit_pet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9eae70265fed7c25cd69a9529eb22654ff3b9cf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/oxford_iiit_pet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/pcam.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/pcam.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d7f02c3231b347940c461f46a47d32cccccaadd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/pcam.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/phototour.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/phototour.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2f1a1299cbd50444151ddab225648d5f32649d5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/phototour.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/places365.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/places365.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b49e945bc0545062155e7f4eb10d10312eaf0233 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/places365.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/rendered_sst2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/rendered_sst2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..859f50b1bd069744934d389bf961153f306e89d6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/rendered_sst2.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/sbd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/sbd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c466ed27402d68db4b303759bf6a1b2d091982a7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/sbd.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/sbu.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/sbu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aed895b71e22c7350b59d3f2d78a12ac32d92c4d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/sbu.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/semeion.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/semeion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c19274bf662227da8c9c8c9b9b04c3cd1cdb4f1d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/semeion.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/stanford_cars.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/stanford_cars.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4e68266c6c75a2a2af457956ed529f08412add0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/stanford_cars.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/stl10.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/stl10.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..852d7ae05ae74d17064e5eaa0b524d4949e851d4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/stl10.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/sun397.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/sun397.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6101d60fbfbba87fe780fd585c07d1445ef66963 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/sun397.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/svhn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/svhn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..276a7e2ad27ecd11d6b1c50778d2b207ddd1e629 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/svhn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/ucf101.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/ucf101.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7d319b744ad949eb54cfe6e579975287ea26405 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/ucf101.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/usps.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/usps.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d8036abc6f9cd59c7c3875cf14d3d7c40ea2273 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/usps.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4051df64723787a717974544a6ea21e55862a21 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/video_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/video_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03eb1ece46a60ff0aecfc8b5aac84fa05307c381 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/video_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/vision.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/vision.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7482ee7c1c3458c77a24665b1ca79390dc976a39 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/vision.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/voc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/voc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d8ee26cdb810c4ef3c0bf0b5e4e585556e0da7e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/voc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/widerface.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/widerface.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92e08996db2e35d56f5b48d23b38c95ee2ca8170 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/__pycache__/widerface.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/_optical_flow.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/_optical_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..af8e17ad95c937dd679cf5f5c14f5e277ab1b1ab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/_optical_flow.py @@ -0,0 +1,520 @@ +import itertools +import os +from abc import ABC, abstractmethod +from glob import glob +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import numpy as np +import torch +from PIL import Image + +from ..io.image import decode_png, read_file +from .folder import default_loader +from .utils import _read_pfm, verify_str_arg +from .vision import VisionDataset + +T1 = tuple[Image.Image, Image.Image, Optional[np.ndarray], Optional[np.ndarray]] +T2 = tuple[Image.Image, Image.Image, Optional[np.ndarray]] + + +__all__ = ( + "KittiFlow", + "Sintel", + "FlyingThings3D", + "FlyingChairs", + "HD1K", +) + + +class FlowDataset(ABC, VisionDataset): + # Some datasets like Kitti have a built-in valid_flow_mask, indicating which flow values are valid + # For those we return (img1, img2, flow, valid_flow_mask), and for the rest we return (img1, img2, flow), + # and it's up to whatever consumes the dataset to decide what valid_flow_mask should be. + _has_builtin_flow_mask = False + + def __init__( + self, + root: Union[str, Path], + transforms: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + + super().__init__(root=root) + self.transforms = transforms + + self._flow_list: list[str] = [] + self._image_list: list[list[str]] = [] + self._loader = loader + + def _read_img(self, file_name: str) -> Union[Image.Image, torch.Tensor]: + return self._loader(file_name) + + @abstractmethod + def _read_flow(self, file_name: str): + # Return the flow or a tuple with the flow and the valid_flow_mask if _has_builtin_flow_mask is True + pass + + def __getitem__(self, index: int) -> Union[T1, T2]: + + img1 = self._read_img(self._image_list[index][0]) + img2 = self._read_img(self._image_list[index][1]) + + if self._flow_list: # it will be empty for some dataset when split="test" + flow = self._read_flow(self._flow_list[index]) + if self._has_builtin_flow_mask: + flow, valid_flow_mask = flow + else: + valid_flow_mask = None + else: + flow = valid_flow_mask = None + + if self.transforms is not None: + img1, img2, flow, valid_flow_mask = self.transforms(img1, img2, flow, valid_flow_mask) + + if self._has_builtin_flow_mask or valid_flow_mask is not None: + # The `or valid_flow_mask is not None` part is here because the mask can be generated within a transform + return img1, img2, flow, valid_flow_mask # type: ignore[return-value] + else: + return img1, img2, flow # type: ignore[return-value] + + def __len__(self) -> int: + return len(self._image_list) + + def __rmul__(self, v: int) -> torch.utils.data.ConcatDataset: + return torch.utils.data.ConcatDataset([self] * v) + + +class Sintel(FlowDataset): + """`Sintel `_ Dataset for optical flow. + + The dataset is expected to have the following structure: :: + + root + Sintel + testing + clean + scene_1 + scene_2 + ... + final + scene_1 + scene_2 + ... + training + clean + scene_1 + scene_2 + ... + final + scene_1 + scene_2 + ... + flow + scene_1 + scene_2 + ... + + Args: + root (str or ``pathlib.Path``): Root directory of the Sintel Dataset. + split (string, optional): The dataset split, either "train" (default) or "test" + pass_name (string, optional): The pass to use, either "clean" (default), "final", or "both". See link above for + details on the different passes. + transforms (callable, optional): A function/transform that takes in + ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. + ``valid_flow_mask`` is expected for consistency with other datasets which + return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + pass_name: str = "clean", + transforms: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root=root, transforms=transforms, loader=loader) + + verify_str_arg(split, "split", valid_values=("train", "test")) + verify_str_arg(pass_name, "pass_name", valid_values=("clean", "final", "both")) + passes = ["clean", "final"] if pass_name == "both" else [pass_name] + + root = Path(root) / "Sintel" + flow_root = root / "training" / "flow" + + for pass_name in passes: + split_dir = "training" if split == "train" else split + image_root = root / split_dir / pass_name + for scene in os.listdir(image_root): + image_list = sorted(glob(str(image_root / scene / "*.png"))) + for i in range(len(image_list) - 1): + self._image_list += [[image_list[i], image_list[i + 1]]] + + if split == "train": + self._flow_list += sorted(glob(str(flow_root / scene / "*.flo"))) + + def __getitem__(self, index: int) -> Union[T1, T2]: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3-tuple with ``(img1, img2, flow)``. + The flow is a numpy array of shape (2, H, W) and the images are PIL images. + ``flow`` is None if ``split="test"``. + If a valid flow mask is generated within the ``transforms`` parameter, + a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned. + """ + return super().__getitem__(index) + + def _read_flow(self, file_name: str) -> np.ndarray: + return _read_flo(file_name) + + +class KittiFlow(FlowDataset): + """`KITTI `__ dataset for optical flow (2015). + + The dataset is expected to have the following structure: :: + + root + KittiFlow + testing + image_2 + training + image_2 + flow_occ + + Args: + root (str or ``pathlib.Path``): Root directory of the KittiFlow Dataset. + split (string, optional): The dataset split, either "train" (default) or "test" + transforms (callable, optional): A function/transform that takes in + ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _has_builtin_flow_mask = True + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transforms: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root=root, transforms=transforms, loader=loader) + + verify_str_arg(split, "split", valid_values=("train", "test")) + + root = Path(root) / "KittiFlow" / (split + "ing") + images1 = sorted(glob(str(root / "image_2" / "*_10.png"))) + images2 = sorted(glob(str(root / "image_2" / "*_11.png"))) + + if not images1 or not images2: + raise FileNotFoundError( + "Could not find the Kitti flow images. Please make sure the directory structure is correct." + ) + + for img1, img2 in zip(images1, images2): + self._image_list += [[img1, img2]] + + if split == "train": + self._flow_list = sorted(glob(str(root / "flow_occ" / "*_10.png"))) + + def __getitem__(self, index: int) -> Union[T1, T2]: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` + where ``valid_flow_mask`` is a numpy boolean mask of shape (H, W) + indicating which flow values are valid. The flow is a numpy array of + shape (2, H, W) and the images are PIL images. ``flow`` and ``valid_flow_mask`` are None if + ``split="test"``. + """ + return super().__getitem__(index) + + def _read_flow(self, file_name: str) -> tuple[np.ndarray, np.ndarray]: + return _read_16bits_png_with_flow_and_valid_mask(file_name) + + +class FlyingChairs(FlowDataset): + """`FlyingChairs `_ Dataset for optical flow. + + You will also need to download the FlyingChairs_train_val.txt file from the dataset page. + + The dataset is expected to have the following structure: :: + + root + FlyingChairs + data + 00001_flow.flo + 00001_img1.ppm + 00001_img2.ppm + ... + FlyingChairs_train_val.txt + + + Args: + root (str or ``pathlib.Path``): Root directory of the FlyingChairs Dataset. + split (string, optional): The dataset split, either "train" (default) or "val" + transforms (callable, optional): A function/transform that takes in + ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. + ``valid_flow_mask`` is expected for consistency with other datasets which + return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`. + """ + + def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None: + super().__init__(root=root, transforms=transforms) + + verify_str_arg(split, "split", valid_values=("train", "val")) + + root = Path(root) / "FlyingChairs" + images = sorted(glob(str(root / "data" / "*.ppm"))) + flows = sorted(glob(str(root / "data" / "*.flo"))) + + split_file_name = "FlyingChairs_train_val.txt" + + if not os.path.exists(root / split_file_name): + raise FileNotFoundError( + "The FlyingChairs_train_val.txt file was not found - please download it from the dataset page (see docstring)." + ) + + split_list = np.loadtxt(str(root / split_file_name), dtype=np.int32) + for i in range(len(flows)): + split_id = split_list[i] + if (split == "train" and split_id == 1) or (split == "val" and split_id == 2): + self._flow_list += [flows[i]] + self._image_list += [[images[2 * i], images[2 * i + 1]]] + + def __getitem__(self, index: int) -> Union[T1, T2]: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3-tuple with ``(img1, img2, flow)``. + The flow is a numpy array of shape (2, H, W) and the images are PIL images. + ``flow`` is None if ``split="val"``. + If a valid flow mask is generated within the ``transforms`` parameter, + a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned. + """ + return super().__getitem__(index) + + def _read_flow(self, file_name: str) -> np.ndarray: + return _read_flo(file_name) + + +class FlyingThings3D(FlowDataset): + """`FlyingThings3D `_ dataset for optical flow. + + The dataset is expected to have the following structure: :: + + root + FlyingThings3D + frames_cleanpass + TEST + TRAIN + frames_finalpass + TEST + TRAIN + optical_flow + TEST + TRAIN + + Args: + root (str or ``pathlib.Path``): Root directory of the intel FlyingThings3D Dataset. + split (string, optional): The dataset split, either "train" (default) or "test" + pass_name (string, optional): The pass to use, either "clean" (default) or "final" or "both". See link above for + details on the different passes. + camera (string, optional): Which camera to return images from. Can be either "left" (default) or "right" or "both". + transforms (callable, optional): A function/transform that takes in + ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. + ``valid_flow_mask`` is expected for consistency with other datasets which + return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + pass_name: str = "clean", + camera: str = "left", + transforms: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root=root, transforms=transforms, loader=loader) + + verify_str_arg(split, "split", valid_values=("train", "test")) + split = split.upper() + + verify_str_arg(pass_name, "pass_name", valid_values=("clean", "final", "both")) + passes = { + "clean": ["frames_cleanpass"], + "final": ["frames_finalpass"], + "both": ["frames_cleanpass", "frames_finalpass"], + }[pass_name] + + verify_str_arg(camera, "camera", valid_values=("left", "right", "both")) + cameras = ["left", "right"] if camera == "both" else [camera] + + root = Path(root) / "FlyingThings3D" + + directions = ("into_future", "into_past") + for pass_name, camera, direction in itertools.product(passes, cameras, directions): + image_dirs = sorted(glob(str(root / pass_name / split / "*/*"))) + image_dirs = sorted(Path(image_dir) / camera for image_dir in image_dirs) + + flow_dirs = sorted(glob(str(root / "optical_flow" / split / "*/*"))) + flow_dirs = sorted(Path(flow_dir) / direction / camera for flow_dir in flow_dirs) + + if not image_dirs or not flow_dirs: + raise FileNotFoundError( + "Could not find the FlyingThings3D flow images. " + "Please make sure the directory structure is correct." + ) + + for image_dir, flow_dir in zip(image_dirs, flow_dirs): + images = sorted(glob(str(image_dir / "*.png"))) + flows = sorted(glob(str(flow_dir / "*.pfm"))) + for i in range(len(flows) - 1): + if direction == "into_future": + self._image_list += [[images[i], images[i + 1]]] + self._flow_list += [flows[i]] + elif direction == "into_past": + self._image_list += [[images[i + 1], images[i]]] + self._flow_list += [flows[i + 1]] + + def __getitem__(self, index: int) -> Union[T1, T2]: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3-tuple with ``(img1, img2, flow)``. + The flow is a numpy array of shape (2, H, W) and the images are PIL images. + ``flow`` is None if ``split="test"``. + If a valid flow mask is generated within the ``transforms`` parameter, + a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned. + """ + return super().__getitem__(index) + + def _read_flow(self, file_name: str) -> np.ndarray: + return _read_pfm(file_name) + + +class HD1K(FlowDataset): + """`HD1K `__ dataset for optical flow. + + The dataset is expected to have the following structure: :: + + root + hd1k + hd1k_challenge + image_2 + hd1k_flow_gt + flow_occ + hd1k_input + image_2 + + Args: + root (str or ``pathlib.Path``): Root directory of the HD1K Dataset. + split (string, optional): The dataset split, either "train" (default) or "test" + transforms (callable, optional): A function/transform that takes in + ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _has_builtin_flow_mask = True + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transforms: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root=root, transforms=transforms, loader=loader) + + verify_str_arg(split, "split", valid_values=("train", "test")) + + root = Path(root) / "hd1k" + if split == "train": + # There are 36 "sequences" and we don't want seq i to overlap with seq i + 1, so we need this for loop + for seq_idx in range(36): + flows = sorted(glob(str(root / "hd1k_flow_gt" / "flow_occ" / f"{seq_idx:06d}_*.png"))) + images = sorted(glob(str(root / "hd1k_input" / "image_2" / f"{seq_idx:06d}_*.png"))) + for i in range(len(flows) - 1): + self._flow_list += [flows[i]] + self._image_list += [[images[i], images[i + 1]]] + else: + images1 = sorted(glob(str(root / "hd1k_challenge" / "image_2" / "*10.png"))) + images2 = sorted(glob(str(root / "hd1k_challenge" / "image_2" / "*11.png"))) + for image1, image2 in zip(images1, images2): + self._image_list += [[image1, image2]] + + if not self._image_list: + raise FileNotFoundError( + "Could not find the HD1K images. Please make sure the directory structure is correct." + ) + + def _read_flow(self, file_name: str) -> tuple[np.ndarray, np.ndarray]: + return _read_16bits_png_with_flow_and_valid_mask(file_name) + + def __getitem__(self, index: int) -> Union[T1, T2]: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` where ``valid_flow_mask`` + is a numpy boolean mask of shape (H, W) + indicating which flow values are valid. The flow is a numpy array of + shape (2, H, W) and the images are PIL images. ``flow`` and ``valid_flow_mask`` are None if + ``split="test"``. + """ + return super().__getitem__(index) + + +def _read_flo(file_name: str) -> np.ndarray: + """Read .flo file in Middlebury format""" + # Code adapted from: + # http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy + # Everything needs to be in little Endian according to + # https://vision.middlebury.edu/flow/code/flow-code/README.txt + with open(file_name, "rb") as f: + magic = np.fromfile(f, "c", count=4).tobytes() + if magic != b"PIEH": + raise ValueError("Magic number incorrect. Invalid .flo file") + + w = np.fromfile(f, " tuple[np.ndarray, np.ndarray]: + + flow_and_valid = decode_png(read_file(file_name)).to(torch.float32) + flow, valid_flow_mask = flow_and_valid[:2, :, :], flow_and_valid[2, :, :] + flow = (flow - 2**15) / 64 # This conversion is explained somewhere on the kitti archive + valid_flow_mask = valid_flow_mask.bool() + + # For consistency with other datasets, we convert to numpy + return flow.numpy(), valid_flow_mask.numpy() diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/_stereo_matching.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/_stereo_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2236e97b85c7647bf10b507ad83f0f34e83987 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/_stereo_matching.py @@ -0,0 +1,1223 @@ +import functools +import json +import os +import random +import shutil +from abc import ABC, abstractmethod +from glob import glob +from pathlib import Path +from typing import Callable, cast, Optional, Union + +import numpy as np +from PIL import Image + +from .utils import _read_pfm, download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + +T1 = tuple[Image.Image, Image.Image, Optional[np.ndarray], np.ndarray] +T2 = tuple[Image.Image, Image.Image, Optional[np.ndarray]] + +__all__ = () + +_read_pfm_file = functools.partial(_read_pfm, slice_channels=1) + + +class StereoMatchingDataset(ABC, VisionDataset): + """Base interface for Stereo matching datasets""" + + _has_built_in_disparity_mask = False + + def __init__(self, root: Union[str, Path], transforms: Optional[Callable] = None) -> None: + """ + Args: + root(str): Root directory of the dataset. + transforms(callable, optional): A function/transform that takes in Tuples of + (images, disparities, valid_masks) and returns a transformed version of each of them. + images is a Tuple of (``PIL.Image``, ``PIL.Image``) + disparities is a Tuple of (``np.ndarray``, ``np.ndarray``) with shape (1, H, W) + valid_masks is a Tuple of (``np.ndarray``, ``np.ndarray``) with shape (H, W) + In some cases, when a dataset does not provide disparities, the ``disparities`` and + ``valid_masks`` can be Tuples containing None values. + For training splits generally the datasets provide a minimal guarantee of + images: (``PIL.Image``, ``PIL.Image``) + disparities: (``np.ndarray``, ``None``) with shape (1, H, W) + Optionally, based on the dataset, it can return a ``mask`` as well: + valid_masks: (``np.ndarray | None``, ``None``) with shape (H, W) + For some test splits, the datasets provides outputs that look like: + imgaes: (``PIL.Image``, ``PIL.Image``) + disparities: (``None``, ``None``) + Optionally, based on the dataset, it can return a ``mask`` as well: + valid_masks: (``None``, ``None``) + """ + super().__init__(root=root) + self.transforms = transforms + + self._images = [] # type: ignore + self._disparities = [] # type: ignore + + def _read_img(self, file_path: Union[str, Path]) -> Image.Image: + img = Image.open(file_path) + if img.mode != "RGB": + img = img.convert("RGB") # type: ignore [assignment] + return img + + def _scan_pairs( + self, + paths_left_pattern: str, + paths_right_pattern: Optional[str] = None, + ) -> list[tuple[str, Optional[str]]]: + + left_paths = list(sorted(glob(paths_left_pattern))) + + right_paths: list[Union[None, str]] + if paths_right_pattern: + right_paths = list(sorted(glob(paths_right_pattern))) + else: + right_paths = list(None for _ in left_paths) + + if not left_paths: + raise FileNotFoundError(f"Could not find any files matching the patterns: {paths_left_pattern}") + + if not right_paths: + raise FileNotFoundError(f"Could not find any files matching the patterns: {paths_right_pattern}") + + if len(left_paths) != len(right_paths): + raise ValueError( + f"Found {len(left_paths)} left files but {len(right_paths)} right files using:\n " + f"left pattern: {paths_left_pattern}\n" + f"right pattern: {paths_right_pattern}\n" + ) + + paths = list((left, right) for left, right in zip(left_paths, right_paths)) + return paths + + @abstractmethod + def _read_disparity(self, file_path: str) -> tuple[Optional[np.ndarray], Optional[np.ndarray]]: + # function that returns a disparity map and an occlusion map + pass + + def __getitem__(self, index: int) -> Union[T1, T2]: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3 or 4-tuple with ``(img_left, img_right, disparity, Optional[valid_mask])`` where ``valid_mask`` + can be a numpy boolean mask of shape (H, W) if the dataset provides a file + indicating which disparity pixels are valid. The disparity is a numpy array of + shape (1, H, W) and the images are PIL images. ``disparity`` is None for + datasets on which for ``split="test"`` the authors did not provide annotations. + """ + img_left = self._read_img(self._images[index][0]) + img_right = self._read_img(self._images[index][1]) + + dsp_map_left, valid_mask_left = self._read_disparity(self._disparities[index][0]) + dsp_map_right, valid_mask_right = self._read_disparity(self._disparities[index][1]) + + imgs = (img_left, img_right) + dsp_maps = (dsp_map_left, dsp_map_right) + valid_masks = (valid_mask_left, valid_mask_right) + + if self.transforms is not None: + ( + imgs, + dsp_maps, + valid_masks, + ) = self.transforms(imgs, dsp_maps, valid_masks) + + if self._has_built_in_disparity_mask or valid_masks[0] is not None: + return imgs[0], imgs[1], dsp_maps[0], cast(np.ndarray, valid_masks[0]) + else: + return imgs[0], imgs[1], dsp_maps[0] + + def __len__(self) -> int: + return len(self._images) + + +class CarlaStereo(StereoMatchingDataset): + """ + Carla simulator data linked in the `CREStereo github repo `_. + + The dataset is expected to have the following structure: :: + + root + carla-highres + trainingF + scene1 + img0.png + img1.png + disp0GT.pfm + disp1GT.pfm + calib.txt + scene2 + img0.png + img1.png + disp0GT.pfm + disp1GT.pfm + calib.txt + ... + + Args: + root (str or ``pathlib.Path``): Root directory where `carla-highres` is located. + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + def __init__(self, root: Union[str, Path], transforms: Optional[Callable] = None) -> None: + super().__init__(root, transforms) + + root = Path(root) / "carla-highres" + + left_image_pattern = str(root / "trainingF" / "*" / "im0.png") + right_image_pattern = str(root / "trainingF" / "*" / "im1.png") + imgs = self._scan_pairs(left_image_pattern, right_image_pattern) + self._images = imgs + + left_disparity_pattern = str(root / "trainingF" / "*" / "disp0GT.pfm") + right_disparity_pattern = str(root / "trainingF" / "*" / "disp1GT.pfm") + disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern) + self._disparities = disparities + + def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]: + disparity_map = _read_pfm_file(file_path) + disparity_map = np.abs(disparity_map) # ensure that the disparity is positive + valid_mask = None + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T1: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3-tuple with ``(img_left, img_right, disparity)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + If a ``valid_mask`` is generated within the ``transforms`` parameter, + a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned. + """ + return cast(T1, super().__getitem__(index)) + + +class Kitti2012Stereo(StereoMatchingDataset): + """ + KITTI dataset from the `2012 stereo evaluation benchmark `_. + Uses the RGB images for consistency with KITTI 2015. + + The dataset is expected to have the following structure: :: + + root + Kitti2012 + testing + colored_0 + 1_10.png + 2_10.png + ... + colored_1 + 1_10.png + 2_10.png + ... + training + colored_0 + 1_10.png + 2_10.png + ... + colored_1 + 1_10.png + 2_10.png + ... + disp_noc + 1.png + 2.png + ... + calib + + Args: + root (str or ``pathlib.Path``): Root directory where `Kitti2012` is located. + split (string, optional): The dataset split of scenes, either "train" (default) or "test". + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + _has_built_in_disparity_mask = True + + def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None: + super().__init__(root, transforms) + + verify_str_arg(split, "split", valid_values=("train", "test")) + + root = Path(root) / "Kitti2012" / (split + "ing") + + left_img_pattern = str(root / "colored_0" / "*_10.png") + right_img_pattern = str(root / "colored_1" / "*_10.png") + self._images = self._scan_pairs(left_img_pattern, right_img_pattern) + + if split == "train": + disparity_pattern = str(root / "disp_noc" / "*.png") + self._disparities = self._scan_pairs(disparity_pattern, None) + else: + self._disparities = list((None, None) for _ in self._images) + + def _read_disparity(self, file_path: str) -> tuple[Optional[np.ndarray], None]: + # test split has no disparity maps + if file_path is None: + return None, None + + disparity_map = np.asarray(Image.open(file_path)) / 256.0 + # unsqueeze the disparity map into (C, H, W) format + disparity_map = disparity_map[None, :, :] + valid_mask = None + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T1: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not + generate a valid mask. + Both ``disparity`` and ``valid_mask`` are ``None`` if the dataset split is test. + """ + return cast(T1, super().__getitem__(index)) + + +class Kitti2015Stereo(StereoMatchingDataset): + """ + KITTI dataset from the `2015 stereo evaluation benchmark `_. + + The dataset is expected to have the following structure: :: + + root + Kitti2015 + testing + image_2 + img1.png + img2.png + ... + image_3 + img1.png + img2.png + ... + training + image_2 + img1.png + img2.png + ... + image_3 + img1.png + img2.png + ... + disp_occ_0 + img1.png + img2.png + ... + disp_occ_1 + img1.png + img2.png + ... + calib + + Args: + root (str or ``pathlib.Path``): Root directory where `Kitti2015` is located. + split (string, optional): The dataset split of scenes, either "train" (default) or "test". + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + _has_built_in_disparity_mask = True + + def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None: + super().__init__(root, transforms) + + verify_str_arg(split, "split", valid_values=("train", "test")) + + root = Path(root) / "Kitti2015" / (split + "ing") + left_img_pattern = str(root / "image_2" / "*.png") + right_img_pattern = str(root / "image_3" / "*.png") + self._images = self._scan_pairs(left_img_pattern, right_img_pattern) + + if split == "train": + left_disparity_pattern = str(root / "disp_occ_0" / "*.png") + right_disparity_pattern = str(root / "disp_occ_1" / "*.png") + self._disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern) + else: + self._disparities = list((None, None) for _ in self._images) + + def _read_disparity(self, file_path: str) -> tuple[Optional[np.ndarray], None]: + # test split has no disparity maps + if file_path is None: + return None, None + + disparity_map = np.asarray(Image.open(file_path)) / 256.0 + # unsqueeze the disparity map into (C, H, W) format + disparity_map = disparity_map[None, :, :] + valid_mask = None + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T1: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not + generate a valid mask. + Both ``disparity`` and ``valid_mask`` are ``None`` if the dataset split is test. + """ + return cast(T1, super().__getitem__(index)) + + +class Middlebury2014Stereo(StereoMatchingDataset): + """Publicly available scenes from the Middlebury dataset `2014 version `. + + The dataset mostly follows the original format, without containing the ambient subdirectories. : :: + + root + Middlebury2014 + train + scene1-{perfect,imperfect} + calib.txt + im{0,1}.png + im1E.png + im1L.png + disp{0,1}.pfm + disp{0,1}-n.png + disp{0,1}-sd.pfm + disp{0,1}y.pfm + scene2-{perfect,imperfect} + calib.txt + im{0,1}.png + im1E.png + im1L.png + disp{0,1}.pfm + disp{0,1}-n.png + disp{0,1}-sd.pfm + disp{0,1}y.pfm + ... + additional + scene1-{perfect,imperfect} + calib.txt + im{0,1}.png + im1E.png + im1L.png + disp{0,1}.pfm + disp{0,1}-n.png + disp{0,1}-sd.pfm + disp{0,1}y.pfm + ... + test + scene1 + calib.txt + im{0,1}.png + scene2 + calib.txt + im{0,1}.png + ... + + Args: + root (str or ``pathlib.Path``): Root directory of the Middleburry 2014 Dataset. + split (string, optional): The dataset split of scenes, either "train" (default), "test", or "additional" + use_ambient_views (boolean, optional): Whether to use different expose or lightning views when possible. + The dataset samples with equal probability between ``[im1.png, im1E.png, im1L.png]``. + calibration (string, optional): Whether or not to use the calibrated (default) or uncalibrated scenes. + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + download (boolean, optional): Whether or not to download the dataset in the ``root`` directory. + """ + + splits = { + "train": [ + "Adirondack", + "Jadeplant", + "Motorcycle", + "Piano", + "Pipes", + "Playroom", + "Playtable", + "Recycle", + "Shelves", + "Vintage", + ], + "additional": [ + "Backpack", + "Bicycle1", + "Cable", + "Classroom1", + "Couch", + "Flowers", + "Mask", + "Shopvac", + "Sticks", + "Storage", + "Sword1", + "Sword2", + "Umbrella", + ], + "test": [ + "Plants", + "Classroom2E", + "Classroom2", + "Australia", + "DjembeL", + "CrusadeP", + "Crusade", + "Hoops", + "Bicycle2", + "Staircase", + "Newkuba", + "AustraliaP", + "Djembe", + "Livingroom", + "Computer", + ], + } + + _has_built_in_disparity_mask = True + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + calibration: Optional[str] = "perfect", + use_ambient_views: bool = False, + transforms: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transforms) + + verify_str_arg(split, "split", valid_values=("train", "test", "additional")) + self.split = split + + if calibration: + verify_str_arg(calibration, "calibration", valid_values=("perfect", "imperfect", "both", None)) # type: ignore + if split == "test": + raise ValueError("Split 'test' has only no calibration settings, please set `calibration=None`.") + else: + if split != "test": + raise ValueError( + f"Split '{split}' has calibration settings, however None was provided as an argument." + f"\nSetting calibration to 'perfect' for split '{split}'. Available calibration settings are: 'perfect', 'imperfect', 'both'.", + ) + + if download: + self._download_dataset(root) + + root = Path(root) / "Middlebury2014" + + if not os.path.exists(root / split): + raise FileNotFoundError(f"The {split} directory was not found in the provided root directory") + + split_scenes = self.splits[split] + # check that the provided root folder contains the scene splits + if not any( + # using startswith to account for perfect / imperfect calibrartion + scene.startswith(s) + for scene in os.listdir(root / split) + for s in split_scenes + ): + raise FileNotFoundError(f"Provided root folder does not contain any scenes from the {split} split.") + + calibrartion_suffixes = { + None: [""], + "perfect": ["-perfect"], + "imperfect": ["-imperfect"], + "both": ["-perfect", "-imperfect"], + }[calibration] + + for calibration_suffix in calibrartion_suffixes: + scene_pattern = "*" + calibration_suffix + left_img_pattern = str(root / split / scene_pattern / "im0.png") + right_img_pattern = str(root / split / scene_pattern / "im1.png") + self._images += self._scan_pairs(left_img_pattern, right_img_pattern) + + if split == "test": + self._disparities = list((None, None) for _ in self._images) + else: + left_dispartity_pattern = str(root / split / scene_pattern / "disp0.pfm") + right_dispartity_pattern = str(root / split / scene_pattern / "disp1.pfm") + self._disparities += self._scan_pairs(left_dispartity_pattern, right_dispartity_pattern) + + self.use_ambient_views = use_ambient_views + + def _read_img(self, file_path: Union[str, Path]) -> Image.Image: + """ + Function that reads either the original right image or an augmented view when ``use_ambient_views`` is True. + When ``use_ambient_views`` is True, the dataset will return at random one of ``[im1.png, im1E.png, im1L.png]`` + as the right image. + """ + ambient_file_paths: list[Union[str, Path]] # make mypy happy + + if not isinstance(file_path, Path): + file_path = Path(file_path) + + if file_path.name == "im1.png" and self.use_ambient_views: + base_path = file_path.parent + # initialize sampleable container + ambient_file_paths = list(base_path / view_name for view_name in ["im1E.png", "im1L.png"]) + # double check that we're not going to try to read from an invalid file path + ambient_file_paths = list(filter(lambda p: os.path.exists(p), ambient_file_paths)) + # keep the original image as an option as well for uniform sampling between base views + ambient_file_paths.append(file_path) + file_path = random.choice(ambient_file_paths) # type: ignore + return super()._read_img(file_path) + + def _read_disparity(self, file_path: str) -> Union[tuple[None, None], tuple[np.ndarray, np.ndarray]]: + # test split has not disparity maps + if file_path is None: + return None, None + + disparity_map = _read_pfm_file(file_path) + disparity_map = np.abs(disparity_map) # ensure that the disparity is positive + disparity_map[disparity_map == np.inf] = 0 # remove infinite disparities + valid_mask = (disparity_map > 0).squeeze(0) # mask out invalid disparities + return disparity_map, valid_mask + + def _download_dataset(self, root: Union[str, Path]) -> None: + base_url = "https://vision.middlebury.edu/stereo/data/scenes2014/zip" + # train and additional splits have 2 different calibration settings + root = Path(root) / "Middlebury2014" + split_name = self.split + + if split_name != "test": + for split_scene in self.splits[split_name]: + split_root = root / split_name + for calibration in ["perfect", "imperfect"]: + scene_name = f"{split_scene}-{calibration}" + scene_url = f"{base_url}/{scene_name}.zip" + # download the scene only if it doesn't exist + if not (split_root / scene_name).exists(): + download_and_extract_archive( + url=scene_url, + filename=f"{scene_name}.zip", + download_root=str(split_root), + remove_finished=True, + ) + else: + os.makedirs(root / "test") + if any(s not in os.listdir(root / "test") for s in self.splits["test"]): + # test split is downloaded from a different location + test_set_url = "https://vision.middlebury.edu/stereo/submit3/zip/MiddEval3-data-F.zip" + # the unzip is going to produce a directory MiddEval3 with two subdirectories trainingF and testF + # we want to move the contents from testF into the directory + download_and_extract_archive(url=test_set_url, download_root=str(root), remove_finished=True) + for scene_dir, scene_names, _ in os.walk(str(root / "MiddEval3/testF")): + for scene in scene_names: + scene_dst_dir = root / "test" + scene_src_dir = Path(scene_dir) / scene + os.makedirs(scene_dst_dir, exist_ok=True) + shutil.move(str(scene_src_dir), str(scene_dst_dir)) + + # cleanup MiddEval3 directory + shutil.rmtree(str(root / "MiddEval3")) + + def __getitem__(self, index: int) -> T2: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + ``valid_mask`` is implicitly ``None`` for `split=test`. + """ + return cast(T2, super().__getitem__(index)) + + +class CREStereo(StereoMatchingDataset): + """Synthetic dataset used in training the `CREStereo `_ architecture. + Dataset details on the official paper `repo `_. + + The dataset is expected to have the following structure: :: + + root + CREStereo + tree + img1_left.jpg + img1_right.jpg + img1_left.disp.jpg + img1_right.disp.jpg + img2_left.jpg + img2_right.jpg + img2_left.disp.jpg + img2_right.disp.jpg + ... + shapenet + img1_left.jpg + img1_right.jpg + img1_left.disp.jpg + img1_right.disp.jpg + ... + reflective + img1_left.jpg + img1_right.jpg + img1_left.disp.jpg + img1_right.disp.jpg + ... + hole + img1_left.jpg + img1_right.jpg + img1_left.disp.jpg + img1_right.disp.jpg + ... + + Args: + root (str): Root directory of the dataset. + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + _has_built_in_disparity_mask = True + + def __init__( + self, + root: Union[str, Path], + transforms: Optional[Callable] = None, + ) -> None: + super().__init__(root, transforms) + + root = Path(root) / "CREStereo" + + dirs = ["shapenet", "reflective", "tree", "hole"] + + for s in dirs: + left_image_pattern = str(root / s / "*_left.jpg") + right_image_pattern = str(root / s / "*_right.jpg") + imgs = self._scan_pairs(left_image_pattern, right_image_pattern) + self._images += imgs + + left_disparity_pattern = str(root / s / "*_left.disp.png") + right_disparity_pattern = str(root / s / "*_right.disp.png") + disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern) + self._disparities += disparities + + def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]: + disparity_map = np.asarray(Image.open(file_path), dtype=np.float32) + # unsqueeze the disparity map into (C, H, W) format + disparity_map = disparity_map[None, :, :] / 32.0 + valid_mask = None + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T1: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not + generate a valid mask. + """ + return cast(T1, super().__getitem__(index)) + + +class FallingThingsStereo(StereoMatchingDataset): + """`FallingThings `_ dataset. + + The dataset is expected to have the following structure: :: + + root + FallingThings + single + dir1 + scene1 + _object_settings.json + _camera_settings.json + image1.left.depth.png + image1.right.depth.png + image1.left.jpg + image1.right.jpg + image2.left.depth.png + image2.right.depth.png + image2.left.jpg + image2.right + ... + scene2 + ... + mixed + scene1 + _object_settings.json + _camera_settings.json + image1.left.depth.png + image1.right.depth.png + image1.left.jpg + image1.right.jpg + image2.left.depth.png + image2.right.depth.png + image2.left.jpg + image2.right + ... + scene2 + ... + + Args: + root (str or ``pathlib.Path``): Root directory where FallingThings is located. + variant (string): Which variant to use. Either "single", "mixed", or "both". + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + def __init__(self, root: Union[str, Path], variant: str = "single", transforms: Optional[Callable] = None) -> None: + super().__init__(root, transforms) + + root = Path(root) / "FallingThings" + + verify_str_arg(variant, "variant", valid_values=("single", "mixed", "both")) + + variants = { + "single": ["single"], + "mixed": ["mixed"], + "both": ["single", "mixed"], + }[variant] + + split_prefix = { + "single": Path("*") / "*", + "mixed": Path("*"), + } + + for s in variants: + left_img_pattern = str(root / s / split_prefix[s] / "*.left.jpg") + right_img_pattern = str(root / s / split_prefix[s] / "*.right.jpg") + self._images += self._scan_pairs(left_img_pattern, right_img_pattern) + + left_disparity_pattern = str(root / s / split_prefix[s] / "*.left.depth.png") + right_disparity_pattern = str(root / s / split_prefix[s] / "*.right.depth.png") + self._disparities += self._scan_pairs(left_disparity_pattern, right_disparity_pattern) + + def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]: + # (H, W) image + depth = np.asarray(Image.open(file_path)) + # as per https://research.nvidia.com/sites/default/files/pubs/2018-06_Falling-Things/readme_0.txt + # in order to extract disparity from depth maps + camera_settings_path = Path(file_path).parent / "_camera_settings.json" + with open(camera_settings_path) as f: + # inverse of depth-from-disparity equation: depth = (baseline * focal) / (disparity * pixel_constant) + intrinsics = json.load(f) + focal = intrinsics["camera_settings"][0]["intrinsic_settings"]["fx"] + baseline, pixel_constant = 6, 100 # pixel constant is inverted + disparity_map = (baseline * focal * pixel_constant) / depth.astype(np.float32) + # unsqueeze disparity to (C, H, W) + disparity_map = disparity_map[None, :, :] + valid_mask = None + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T1: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3-tuple with ``(img_left, img_right, disparity)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + If a ``valid_mask`` is generated within the ``transforms`` parameter, + a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned. + """ + return cast(T1, super().__getitem__(index)) + + +class SceneFlowStereo(StereoMatchingDataset): + """Dataset interface for `Scene Flow `_ datasets. + This interface provides access to the `FlyingThings3D, `Monkaa` and `Driving` datasets. + + The dataset is expected to have the following structure: :: + + root + SceneFlow + Monkaa + frames_cleanpass + scene1 + left + img1.png + img2.png + right + img1.png + img2.png + scene2 + left + img1.png + img2.png + right + img1.png + img2.png + frames_finalpass + scene1 + left + img1.png + img2.png + right + img1.png + img2.png + ... + ... + disparity + scene1 + left + img1.pfm + img2.pfm + right + img1.pfm + img2.pfm + FlyingThings3D + ... + ... + + Args: + root (str or ``pathlib.Path``): Root directory where SceneFlow is located. + variant (string): Which dataset variant to user, "FlyingThings3D" (default), "Monkaa" or "Driving". + pass_name (string): Which pass to use, "clean" (default), "final" or "both". + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + + """ + + def __init__( + self, + root: Union[str, Path], + variant: str = "FlyingThings3D", + pass_name: str = "clean", + transforms: Optional[Callable] = None, + ) -> None: + super().__init__(root, transforms) + + root = Path(root) / "SceneFlow" + + verify_str_arg(variant, "variant", valid_values=("FlyingThings3D", "Driving", "Monkaa")) + verify_str_arg(pass_name, "pass_name", valid_values=("clean", "final", "both")) + + passes = { + "clean": ["frames_cleanpass"], + "final": ["frames_finalpass"], + "both": ["frames_cleanpass", "frames_finalpass"], + }[pass_name] + + root = root / variant + + prefix_directories = { + "Monkaa": Path("*"), + "FlyingThings3D": Path("*") / "*" / "*", + "Driving": Path("*") / "*" / "*", + } + + for p in passes: + left_image_pattern = str(root / p / prefix_directories[variant] / "left" / "*.png") + right_image_pattern = str(root / p / prefix_directories[variant] / "right" / "*.png") + self._images += self._scan_pairs(left_image_pattern, right_image_pattern) + + left_disparity_pattern = str(root / "disparity" / prefix_directories[variant] / "left" / "*.pfm") + right_disparity_pattern = str(root / "disparity" / prefix_directories[variant] / "right" / "*.pfm") + self._disparities += self._scan_pairs(left_disparity_pattern, right_disparity_pattern) + + def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]: + disparity_map = _read_pfm_file(file_path) + disparity_map = np.abs(disparity_map) # ensure that the disparity is positive + valid_mask = None + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T1: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3-tuple with ``(img_left, img_right, disparity)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + If a ``valid_mask`` is generated within the ``transforms`` parameter, + a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned. + """ + return cast(T1, super().__getitem__(index)) + + +class SintelStereo(StereoMatchingDataset): + """Sintel `Stereo Dataset `_. + + The dataset is expected to have the following structure: :: + + root + Sintel + training + final_left + scene1 + img1.png + img2.png + ... + ... + final_right + scene2 + img1.png + img2.png + ... + ... + disparities + scene1 + img1.png + img2.png + ... + ... + occlusions + scene1 + img1.png + img2.png + ... + ... + outofframe + scene1 + img1.png + img2.png + ... + ... + + Args: + root (str or ``pathlib.Path``): Root directory where Sintel Stereo is located. + pass_name (string): The name of the pass to use, either "final", "clean" or "both". + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + _has_built_in_disparity_mask = True + + def __init__(self, root: Union[str, Path], pass_name: str = "final", transforms: Optional[Callable] = None) -> None: + super().__init__(root, transforms) + + verify_str_arg(pass_name, "pass_name", valid_values=("final", "clean", "both")) + + root = Path(root) / "Sintel" + pass_names = { + "final": ["final"], + "clean": ["clean"], + "both": ["final", "clean"], + }[pass_name] + + for p in pass_names: + left_img_pattern = str(root / "training" / f"{p}_left" / "*" / "*.png") + right_img_pattern = str(root / "training" / f"{p}_right" / "*" / "*.png") + self._images += self._scan_pairs(left_img_pattern, right_img_pattern) + + disparity_pattern = str(root / "training" / "disparities" / "*" / "*.png") + self._disparities += self._scan_pairs(disparity_pattern, None) + + def _get_occlussion_mask_paths(self, file_path: str) -> tuple[str, str]: + # helper function to get the occlusion mask paths + # a path will look like .../.../.../training/disparities/scene1/img1.png + # we want to get something like .../.../.../training/occlusions/scene1/img1.png + fpath = Path(file_path) + basename = fpath.name + scenedir = fpath.parent + # the parent of the scenedir is actually the disparity dir + sampledir = scenedir.parent.parent + + occlusion_path = str(sampledir / "occlusions" / scenedir.name / basename) + outofframe_path = str(sampledir / "outofframe" / scenedir.name / basename) + + if not os.path.exists(occlusion_path): + raise FileNotFoundError(f"Occlusion mask {occlusion_path} does not exist") + + if not os.path.exists(outofframe_path): + raise FileNotFoundError(f"Out of frame mask {outofframe_path} does not exist") + + return occlusion_path, outofframe_path + + def _read_disparity(self, file_path: str) -> Union[tuple[None, None], tuple[np.ndarray, np.ndarray]]: + if file_path is None: + return None, None + + # disparity decoding as per Sintel instructions in the README provided with the dataset + disparity_map = np.asarray(Image.open(file_path), dtype=np.float32) + r, g, b = np.split(disparity_map, 3, axis=-1) + disparity_map = r * 4 + g / (2**6) + b / (2**14) + # reshape into (C, H, W) format + disparity_map = np.transpose(disparity_map, (2, 0, 1)) + # find the appropriate file paths + occlued_mask_path, out_of_frame_mask_path = self._get_occlussion_mask_paths(file_path) + # occlusion masks + valid_mask = np.asarray(Image.open(occlued_mask_path)) == 0 + # out of frame masks + off_mask = np.asarray(Image.open(out_of_frame_mask_path)) == 0 + # combine the masks together + valid_mask = np.logical_and(off_mask, valid_mask) + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T2: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images whilst + the valid_mask is a numpy array of shape (H, W). + """ + return cast(T2, super().__getitem__(index)) + + +class InStereo2k(StereoMatchingDataset): + """`InStereo2k `_ dataset. + + The dataset is expected to have the following structure: :: + + root + InStereo2k + train + scene1 + left.png + right.png + left_disp.png + right_disp.png + ... + scene2 + ... + test + scene1 + left.png + right.png + left_disp.png + right_disp.png + ... + scene2 + ... + + Args: + root (str or ``pathlib.Path``): Root directory where InStereo2k is located. + split (string): Either "train" or "test". + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None: + super().__init__(root, transforms) + + root = Path(root) / "InStereo2k" / split + + verify_str_arg(split, "split", valid_values=("train", "test")) + + left_img_pattern = str(root / "*" / "left.png") + right_img_pattern = str(root / "*" / "right.png") + self._images = self._scan_pairs(left_img_pattern, right_img_pattern) + + left_disparity_pattern = str(root / "*" / "left_disp.png") + right_disparity_pattern = str(root / "*" / "right_disp.png") + self._disparities = self._scan_pairs(left_disparity_pattern, right_disparity_pattern) + + def _read_disparity(self, file_path: str) -> tuple[np.ndarray, None]: + disparity_map = np.asarray(Image.open(file_path), dtype=np.float32) + # unsqueeze disparity to (C, H, W) + disparity_map = disparity_map[None, :, :] / 1024.0 + valid_mask = None + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T1: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 3-tuple with ``(img_left, img_right, disparity)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + If a ``valid_mask`` is generated within the ``transforms`` parameter, + a 4-tuple with ``(img_left, img_right, disparity, valid_mask)`` is returned. + """ + return cast(T1, super().__getitem__(index)) + + +class ETH3DStereo(StereoMatchingDataset): + """ETH3D `Low-Res Two-View `_ dataset. + + The dataset is expected to have the following structure: :: + + root + ETH3D + two_view_training + scene1 + im1.png + im0.png + images.txt + cameras.txt + calib.txt + scene2 + im1.png + im0.png + images.txt + cameras.txt + calib.txt + ... + two_view_training_gt + scene1 + disp0GT.pfm + mask0nocc.png + scene2 + disp0GT.pfm + mask0nocc.png + ... + two_view_testing + scene1 + im1.png + im0.png + images.txt + cameras.txt + calib.txt + scene2 + im1.png + im0.png + images.txt + cameras.txt + calib.txt + ... + + Args: + root (str or ``pathlib.Path``): Root directory of the ETH3D Dataset. + split (string, optional): The dataset split of scenes, either "train" (default) or "test". + transforms (callable, optional): A function/transform that takes in a sample and returns a transformed version. + """ + + _has_built_in_disparity_mask = True + + def __init__(self, root: Union[str, Path], split: str = "train", transforms: Optional[Callable] = None) -> None: + super().__init__(root, transforms) + + verify_str_arg(split, "split", valid_values=("train", "test")) + + root = Path(root) / "ETH3D" + + img_dir = "two_view_training" if split == "train" else "two_view_test" + anot_dir = "two_view_training_gt" + + left_img_pattern = str(root / img_dir / "*" / "im0.png") + right_img_pattern = str(root / img_dir / "*" / "im1.png") + self._images = self._scan_pairs(left_img_pattern, right_img_pattern) + + if split == "test": + self._disparities = list((None, None) for _ in self._images) + else: + disparity_pattern = str(root / anot_dir / "*" / "disp0GT.pfm") + self._disparities = self._scan_pairs(disparity_pattern, None) + + def _read_disparity(self, file_path: str) -> Union[tuple[None, None], tuple[np.ndarray, np.ndarray]]: + # test split has no disparity maps + if file_path is None: + return None, None + + disparity_map = _read_pfm_file(file_path) + disparity_map = np.abs(disparity_map) # ensure that the disparity is positive + mask_path = Path(file_path).parent / "mask0nocc.png" + valid_mask = Image.open(mask_path) + valid_mask = np.asarray(valid_mask).astype(bool) + return disparity_map, valid_mask + + def __getitem__(self, index: int) -> T2: + """Return example at given index. + + Args: + index(int): The index of the example to retrieve + + Returns: + tuple: A 4-tuple with ``(img_left, img_right, disparity, valid_mask)``. + The disparity is a numpy array of shape (1, H, W) and the images are PIL images. + ``valid_mask`` is implicitly ``None`` if the ``transforms`` parameter does not + generate a valid mask. + Both ``disparity`` and ``valid_mask`` are ``None`` if the dataset split is test. + """ + return cast(T2, super().__getitem__(index)) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/caltech.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/caltech.py new file mode 100644 index 0000000000000000000000000000000000000000..7498f67400158f1c0da8a6bb66866153735120ce --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/caltech.py @@ -0,0 +1,241 @@ +import os +import os.path +import shutil +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .utils import download_and_extract_archive, extract_archive, verify_str_arg +from .vision import VisionDataset + + +class Caltech101(VisionDataset): + """`Caltech 101 `_ Dataset. + + .. warning:: + + This class needs `scipy `_ to load target files from `.mat` format. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``caltech101`` exists or will be saved to if download is set to True. + target_type (string or list, optional): Type of target to use, ``category`` or + ``annotation``. Can also be a list to output a tuple with all specified + target types. ``category`` represents the target class, and + ``annotation`` is a list of points from a hand-generated outline. + Defaults to ``category``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + .. warning:: + + To download the dataset `gdown `_ is required. + """ + + def __init__( + self, + root: Union[str, Path], + target_type: Union[list[str], str] = "category", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(os.path.join(root, "caltech101"), transform=transform, target_transform=target_transform) + os.makedirs(self.root, exist_ok=True) + if isinstance(target_type, str): + target_type = [target_type] + self.target_type = [verify_str_arg(t, "target_type", ("category", "annotation")) for t in target_type] + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + self.categories = sorted(os.listdir(os.path.join(self.root, "101_ObjectCategories"))) + self.categories.remove("BACKGROUND_Google") # this is not a real class + + # For some reason, the category names in "101_ObjectCategories" and + # "Annotations" do not always match. This is a manual map between the + # two. Defaults to using same name, since most names are fine. + name_map = { + "Faces": "Faces_2", + "Faces_easy": "Faces_3", + "Motorbikes": "Motorbikes_16", + "airplanes": "Airplanes_Side_2", + } + self.annotation_categories = list(map(lambda x: name_map[x] if x in name_map else x, self.categories)) + + self.index: list[int] = [] + self.y = [] + for i, c in enumerate(self.categories): + n = len(os.listdir(os.path.join(self.root, "101_ObjectCategories", c))) + self.index.extend(range(1, n + 1)) + self.y.extend(n * [i]) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where the type of target specified by target_type. + """ + import scipy.io + + img = Image.open( + os.path.join( + self.root, + "101_ObjectCategories", + self.categories[self.y[index]], + f"image_{self.index[index]:04d}.jpg", + ) + ) + + target: Any = [] + for t in self.target_type: + if t == "category": + target.append(self.y[index]) + elif t == "annotation": + data = scipy.io.loadmat( + os.path.join( + self.root, + "Annotations", + self.annotation_categories[self.y[index]], + f"annotation_{self.index[index]:04d}.mat", + ) + ) + target.append(data["obj_contour"]) + target = tuple(target) if len(target) > 1 else target[0] + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def _check_integrity(self) -> bool: + # can be more robust and check hash of files + return os.path.exists(os.path.join(self.root, "101_ObjectCategories")) + + def __len__(self) -> int: + return len(self.index) + + def download(self) -> None: + if self._check_integrity(): + return + + download_and_extract_archive( + "https://data.caltech.edu/records/mzrjq-6wc02/files/caltech-101.zip", + download_root=self.root, + filename="caltech-101.zip", + md5="3138e1922a9193bfa496528edbbc45d0", + ) + gzip_folder = os.path.join(self.root, "caltech-101") + for gzip_file in os.listdir(gzip_folder): + if gzip_file.endswith(".gz"): + extract_archive(os.path.join(gzip_folder, gzip_file), self.root) + shutil.rmtree(gzip_folder) + os.remove(os.path.join(self.root, "caltech-101.zip")) + + def extra_repr(self) -> str: + return "Target type: {target_type}".format(**self.__dict__) + + +class Caltech256(VisionDataset): + """`Caltech 256 `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``caltech256`` exists or will be saved to if download is set to True. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + """ + + def __init__( + self, + root: str, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(os.path.join(root, "caltech256"), transform=transform, target_transform=target_transform) + os.makedirs(self.root, exist_ok=True) + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + self.categories = sorted(os.listdir(os.path.join(self.root, "256_ObjectCategories"))) + self.index: list[int] = [] + self.y = [] + for i, c in enumerate(self.categories): + n = len( + [ + item + for item in os.listdir(os.path.join(self.root, "256_ObjectCategories", c)) + if item.endswith(".jpg") + ] + ) + self.index.extend(range(1, n + 1)) + self.y.extend(n * [i]) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + img = Image.open( + os.path.join( + self.root, + "256_ObjectCategories", + self.categories[self.y[index]], + f"{self.y[index] + 1:03d}_{self.index[index]:04d}.jpg", + ) + ) + + target = self.y[index] + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def _check_integrity(self) -> bool: + # can be more robust and check hash of files + return os.path.exists(os.path.join(self.root, "256_ObjectCategories")) + + def __len__(self) -> int: + return len(self.index) + + def download(self) -> None: + if self._check_integrity(): + return + + download_and_extract_archive( + "https://data.caltech.edu/records/nyy15-4j048/files/256_ObjectCategories.tar", + self.root, + filename="256_ObjectCategories.tar", + md5="67b4f42ca05d46448c6bb8ecd2220f6d", + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/celeba.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/celeba.py new file mode 100644 index 0000000000000000000000000000000000000000..e3ee8ee62ea24cbbae6c028edc0f0d0254c1d140 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/celeba.py @@ -0,0 +1,210 @@ +import csv +import os +from collections import namedtuple +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import PIL +import torch + +from .utils import check_integrity, download_file_from_google_drive, extract_archive, verify_str_arg +from .vision import VisionDataset + +CSV = namedtuple("CSV", ["header", "index", "data"]) + + +class CelebA(VisionDataset): + """`Large-scale CelebFaces Attributes (CelebA) Dataset `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory where images are downloaded to. + split (string): One of {'train', 'valid', 'test', 'all'}. + Accordingly dataset is selected. + target_type (string or list, optional): Type of target to use, ``attr``, ``identity``, ``bbox``, + or ``landmarks``. Can also be a list to output a tuple with all specified target types. + The targets represent: + + - ``attr`` (Tensor shape=(40,) dtype=int): binary (0, 1) labels for attributes + - ``identity`` (int): label for each person (data points with the same identity are the same person) + - ``bbox`` (Tensor shape=(4,) dtype=int): bounding box (x, y, width, height). + + .. warning:: + + These bounding box coordinates correspond to the original uncropped + CelebA images, not the cropped and aligned images returned by this + dataset. As a result, the coordinates will not match and may fall + outside the image boundaries. + + See `Issue #9008 `_ for + details and potential workarounds. + + - ``landmarks`` (Tensor shape=(10,) dtype=int): landmark points (lefteye_x, lefteye_y, righteye_x, + righteye_y, nose_x, nose_y, leftmouth_x, leftmouth_y, rightmouth_x, rightmouth_y) + + Defaults to ``attr``. If empty, ``None`` will be returned as target. + + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.PILToTensor`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + .. warning:: + + To download the dataset `gdown `_ is required. + """ + + base_folder = "celeba" + # There currently does not appear to be an easy way to extract 7z in python (without introducing additional + # dependencies). The "in-the-wild" (not aligned+cropped) images are only in 7z, so they are not available + # right now. + file_list = [ + # File ID MD5 Hash Filename + ("0B7EVK8r0v71pZjFTYXZWM3FlRnM", "00d2c5bc6d35e252742224ab0c1e8fcb", "img_align_celeba.zip"), + # ("0B7EVK8r0v71pbWNEUjJKdDQ3dGc","b6cd7e93bc7a96c2dc33f819aa3ac651", "img_align_celeba_png.7z"), + # ("0B7EVK8r0v71peklHb0pGdDl6R28", "b6cd7e93bc7a96c2dc33f819aa3ac651", "img_celeba.7z"), + ("0B7EVK8r0v71pblRyaVFSWGxPY0U", "75e246fa4810816ffd6ee81facbd244c", "list_attr_celeba.txt"), + ("1_ee_0u7vcNLOfNLegJRHmolfH5ICW-XS", "32bd1bd63d3c78cd57e08160ec5ed1e2", "identity_CelebA.txt"), + ("0B7EVK8r0v71pbThiMVRxWXZ4dU0", "00566efa6fedff7a56946cd1c10f1c16", "list_bbox_celeba.txt"), + ("0B7EVK8r0v71pd0FJY3Blby1HUTQ", "cc24ecafdb5b50baae59b03474781f8c", "list_landmarks_align_celeba.txt"), + # ("0B7EVK8r0v71pTzJIdlJWdHczRlU", "063ee6ddb681f96bc9ca28c6febb9d1a", "list_landmarks_celeba.txt"), + ("0B7EVK8r0v71pY0NSMzRuSXJEVkk", "d32c9cbf5e040fd4025c592c306e6668", "list_eval_partition.txt"), + ] + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + target_type: Union[list[str], str] = "attr", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.split = split + if isinstance(target_type, list): + self.target_type = target_type + else: + self.target_type = [target_type] + + if not self.target_type and self.target_transform is not None: + raise RuntimeError("target_transform is specified but target_type is empty") + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + split_map = { + "train": 0, + "valid": 1, + "test": 2, + "all": None, + } + split_ = split_map[ + verify_str_arg( + split.lower() if isinstance(split, str) else split, + "split", + ("train", "valid", "test", "all"), + ) + ] + splits = self._load_csv("list_eval_partition.txt") + identity = self._load_csv("identity_CelebA.txt") + bbox = self._load_csv("list_bbox_celeba.txt", header=1) + landmarks_align = self._load_csv("list_landmarks_align_celeba.txt", header=1) + attr = self._load_csv("list_attr_celeba.txt", header=1) + + mask = slice(None) if split_ is None else (splits.data == split_).squeeze() + + if mask == slice(None): # if split == "all" + self.filename = splits.index + else: + self.filename = [splits.index[i] for i in torch.squeeze(torch.nonzero(mask))] # type: ignore[arg-type] + self.identity = identity.data[mask] + self.bbox = bbox.data[mask] + self.landmarks_align = landmarks_align.data[mask] + self.attr = attr.data[mask] + # map from {-1, 1} to {0, 1} + self.attr = torch.div(self.attr + 1, 2, rounding_mode="floor") + self.attr_names = attr.header + + def _load_csv( + self, + filename: str, + header: Optional[int] = None, + ) -> CSV: + with open(os.path.join(self.root, self.base_folder, filename)) as csv_file: + data = list(csv.reader(csv_file, delimiter=" ", skipinitialspace=True)) + + if header is not None: + headers = data[header] + data = data[header + 1 :] + else: + headers = [] + + indices = [row[0] for row in data] + data = [row[1:] for row in data] + data_int = [list(map(int, i)) for i in data] + + return CSV(headers, indices, torch.tensor(data_int)) + + def _check_integrity(self) -> bool: + for _, md5, filename in self.file_list: + fpath = os.path.join(self.root, self.base_folder, filename) + _, ext = os.path.splitext(filename) + # Allow original archive to be deleted (zip and 7z) + # Only need the extracted images + if ext not in [".zip", ".7z"] and not check_integrity(fpath, md5): + return False + + # Should check a hash of the images + return os.path.isdir(os.path.join(self.root, self.base_folder, "img_align_celeba")) + + def download(self) -> None: + if self._check_integrity(): + return + + for file_id, md5, filename in self.file_list: + download_file_from_google_drive(file_id, os.path.join(self.root, self.base_folder), filename, md5) + + extract_archive(os.path.join(self.root, self.base_folder, "img_align_celeba.zip")) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + X = PIL.Image.open(os.path.join(self.root, self.base_folder, "img_align_celeba", self.filename[index])) + + target: Any = [] + for t in self.target_type: + if t == "attr": + target.append(self.attr[index, :]) + elif t == "identity": + target.append(self.identity[index, 0]) + elif t == "bbox": + target.append(self.bbox[index, :]) + elif t == "landmarks": + target.append(self.landmarks_align[index, :]) + else: + # TODO: refactor with utils.verify_str_arg + raise ValueError(f'Target type "{t}" is not recognized.') + + if self.transform is not None: + X = self.transform(X) + + if target: + target = tuple(target) if len(target) > 1 else target[0] + + if self.target_transform is not None: + target = self.target_transform(target) + else: + target = None + + return X, target + + def __len__(self) -> int: + return len(self.attr) + + def extra_repr(self) -> str: + lines = ["Target type: {target_type}", "Split: {split}"] + return "\n".join(lines).format(**self.__dict__) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/cifar.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/cifar.py new file mode 100644 index 0000000000000000000000000000000000000000..45893a4499506a43323bf53d9552adec2a457261 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/cifar.py @@ -0,0 +1,167 @@ +import os.path +import pickle +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import numpy as np +from PIL import Image + +from .utils import check_integrity, download_and_extract_archive +from .vision import VisionDataset + + +class CIFAR10(VisionDataset): + """`CIFAR10 `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``cifar-10-batches-py`` exists or will be saved to if download is set to True. + train (bool, optional): If True, creates dataset from training set, otherwise + creates from test set. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + """ + + base_folder = "cifar-10-batches-py" + url = "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz" + filename = "cifar-10-python.tar.gz" + tgz_md5 = "c58f30108f718f92721af3b95e74349a" + train_list = [ + ["data_batch_1", "c99cafc152244af753f735de768cd75f"], + ["data_batch_2", "d4bba439e000b95fd0a9bffe97cbabec"], + ["data_batch_3", "54ebc095f3ab1f0389bbae665268c751"], + ["data_batch_4", "634d18415352ddfa80567beed471001a"], + ["data_batch_5", "482c414d41f54cd18b22e5b47cb7c3cb"], + ] + + test_list = [ + ["test_batch", "40351d587109b95175f43aff81a1287e"], + ] + meta = { + "filename": "batches.meta", + "key": "label_names", + "md5": "5ff9c542aee3614f3951f8cda6e48888", + } + + def __init__( + self, + root: Union[str, Path], + train: bool = True, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + + super().__init__(root, transform=transform, target_transform=target_transform) + + self.train = train # training set or test set + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + if self.train: + downloaded_list = self.train_list + else: + downloaded_list = self.test_list + + self.data: Any = [] + self.targets = [] + + # now load the picked numpy arrays + for file_name, checksum in downloaded_list: + file_path = os.path.join(self.root, self.base_folder, file_name) + with open(file_path, "rb") as f: + entry = pickle.load(f, encoding="latin1") + self.data.append(entry["data"]) + if "labels" in entry: + self.targets.extend(entry["labels"]) + else: + self.targets.extend(entry["fine_labels"]) + + self.data = np.vstack(self.data).reshape(-1, 3, 32, 32) + self.data = self.data.transpose((0, 2, 3, 1)) # convert to HWC + + self._load_meta() + + def _load_meta(self) -> None: + path = os.path.join(self.root, self.base_folder, self.meta["filename"]) + if not check_integrity(path, self.meta["md5"]): + raise RuntimeError("Dataset metadata file not found or corrupted. You can use download=True to download it") + with open(path, "rb") as infile: + data = pickle.load(infile, encoding="latin1") + self.classes = data[self.meta["key"]] + self.class_to_idx = {_class: i for i, _class in enumerate(self.classes)} + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + img, target = self.data[index], self.targets[index] + + # doing this so that it is consistent with all other datasets + # to return a PIL Image + img = Image.fromarray(img) + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.data) + + def _check_integrity(self) -> bool: + for filename, md5 in self.train_list + self.test_list: + fpath = os.path.join(self.root, self.base_folder, filename) + if not check_integrity(fpath, md5): + return False + return True + + def download(self) -> None: + if self._check_integrity(): + return + download_and_extract_archive(self.url, self.root, filename=self.filename, md5=self.tgz_md5) + + def extra_repr(self) -> str: + split = "Train" if self.train is True else "Test" + return f"Split: {split}" + + +class CIFAR100(CIFAR10): + """`CIFAR100 `_ Dataset. + + This is a subclass of the `CIFAR10` Dataset. + """ + + base_folder = "cifar-100-python" + url = "https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz" + filename = "cifar-100-python.tar.gz" + tgz_md5 = "eb9058c3a382ffc7106e4002c42a8d85" + train_list = [ + ["train", "16019d7e3df5f24257cddd939b257f8d"], + ] + + test_list = [ + ["test", "f0ef6b0ae62326f3e7ffdfab6717acfc"], + ] + meta = { + "filename": "meta", + "key": "fine_label_names", + "md5": "7973b15100ade9c7d40fb424638fde48", + } diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/cityscapes.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/cityscapes.py new file mode 100644 index 0000000000000000000000000000000000000000..a124439932f98b53d88e9ebc1db59068ae910989 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/cityscapes.py @@ -0,0 +1,222 @@ +import json +import os +from collections import namedtuple +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .utils import extract_archive, iterable_to_str, verify_str_arg +from .vision import VisionDataset + + +class Cityscapes(VisionDataset): + """`Cityscapes `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory ``leftImg8bit`` + and ``gtFine`` or ``gtCoarse`` are located. + split (string, optional): The image split to use, ``train``, ``test`` or ``val`` if mode="fine" + otherwise ``train``, ``train_extra`` or ``val`` + mode (string, optional): The quality mode to use, ``fine`` or ``coarse`` + target_type (string or list, optional): Type of target to use, ``instance``, ``semantic``, ``polygon`` + or ``color``. Can also be a list to output a tuple with all specified target types. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + transforms (callable, optional): A function/transform that takes input sample and its target as entry + and returns a transformed version. + + Examples: + + Get semantic segmentation target + + .. code-block:: python + + dataset = Cityscapes('./data/cityscapes', split='train', mode='fine', + target_type='semantic') + + img, smnt = dataset[0] + + Get multiple targets + + .. code-block:: python + + dataset = Cityscapes('./data/cityscapes', split='train', mode='fine', + target_type=['instance', 'color', 'polygon']) + + img, (inst, col, poly) = dataset[0] + + Validate on the "coarse" set + + .. code-block:: python + + dataset = Cityscapes('./data/cityscapes', split='val', mode='coarse', + target_type='semantic') + + img, smnt = dataset[0] + """ + + # Based on https://github.com/mcordts/cityscapesScripts + CityscapesClass = namedtuple( + "CityscapesClass", + ["name", "id", "train_id", "category", "category_id", "has_instances", "ignore_in_eval", "color"], + ) + + classes = [ + CityscapesClass("unlabeled", 0, 255, "void", 0, False, True, (0, 0, 0)), + CityscapesClass("ego vehicle", 1, 255, "void", 0, False, True, (0, 0, 0)), + CityscapesClass("rectification border", 2, 255, "void", 0, False, True, (0, 0, 0)), + CityscapesClass("out of roi", 3, 255, "void", 0, False, True, (0, 0, 0)), + CityscapesClass("static", 4, 255, "void", 0, False, True, (0, 0, 0)), + CityscapesClass("dynamic", 5, 255, "void", 0, False, True, (111, 74, 0)), + CityscapesClass("ground", 6, 255, "void", 0, False, True, (81, 0, 81)), + CityscapesClass("road", 7, 0, "flat", 1, False, False, (128, 64, 128)), + CityscapesClass("sidewalk", 8, 1, "flat", 1, False, False, (244, 35, 232)), + CityscapesClass("parking", 9, 255, "flat", 1, False, True, (250, 170, 160)), + CityscapesClass("rail track", 10, 255, "flat", 1, False, True, (230, 150, 140)), + CityscapesClass("building", 11, 2, "construction", 2, False, False, (70, 70, 70)), + CityscapesClass("wall", 12, 3, "construction", 2, False, False, (102, 102, 156)), + CityscapesClass("fence", 13, 4, "construction", 2, False, False, (190, 153, 153)), + CityscapesClass("guard rail", 14, 255, "construction", 2, False, True, (180, 165, 180)), + CityscapesClass("bridge", 15, 255, "construction", 2, False, True, (150, 100, 100)), + CityscapesClass("tunnel", 16, 255, "construction", 2, False, True, (150, 120, 90)), + CityscapesClass("pole", 17, 5, "object", 3, False, False, (153, 153, 153)), + CityscapesClass("polegroup", 18, 255, "object", 3, False, True, (153, 153, 153)), + CityscapesClass("traffic light", 19, 6, "object", 3, False, False, (250, 170, 30)), + CityscapesClass("traffic sign", 20, 7, "object", 3, False, False, (220, 220, 0)), + CityscapesClass("vegetation", 21, 8, "nature", 4, False, False, (107, 142, 35)), + CityscapesClass("terrain", 22, 9, "nature", 4, False, False, (152, 251, 152)), + CityscapesClass("sky", 23, 10, "sky", 5, False, False, (70, 130, 180)), + CityscapesClass("person", 24, 11, "human", 6, True, False, (220, 20, 60)), + CityscapesClass("rider", 25, 12, "human", 6, True, False, (255, 0, 0)), + CityscapesClass("car", 26, 13, "vehicle", 7, True, False, (0, 0, 142)), + CityscapesClass("truck", 27, 14, "vehicle", 7, True, False, (0, 0, 70)), + CityscapesClass("bus", 28, 15, "vehicle", 7, True, False, (0, 60, 100)), + CityscapesClass("caravan", 29, 255, "vehicle", 7, True, True, (0, 0, 90)), + CityscapesClass("trailer", 30, 255, "vehicle", 7, True, True, (0, 0, 110)), + CityscapesClass("train", 31, 16, "vehicle", 7, True, False, (0, 80, 100)), + CityscapesClass("motorcycle", 32, 17, "vehicle", 7, True, False, (0, 0, 230)), + CityscapesClass("bicycle", 33, 18, "vehicle", 7, True, False, (119, 11, 32)), + CityscapesClass("license plate", -1, -1, "vehicle", 7, False, True, (0, 0, 142)), + ] + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + mode: str = "fine", + target_type: Union[list[str], str] = "instance", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + transforms: Optional[Callable] = None, + ) -> None: + super().__init__(root, transforms, transform, target_transform) + self.mode = "gtFine" if mode == "fine" else "gtCoarse" + self.images_dir = os.path.join(self.root, "leftImg8bit", split) + self.targets_dir = os.path.join(self.root, self.mode, split) + self.target_type = target_type + self.split = split + self.images = [] + self.targets = [] + + verify_str_arg(mode, "mode", ("fine", "coarse")) + if mode == "fine": + valid_modes = ("train", "test", "val") + else: + valid_modes = ("train", "train_extra", "val") + msg = "Unknown value '{}' for argument split if mode is '{}'. Valid values are {{{}}}." + msg = msg.format(split, mode, iterable_to_str(valid_modes)) + verify_str_arg(split, "split", valid_modes, msg) + + if not isinstance(target_type, list): + self.target_type = [target_type] + [ + verify_str_arg(value, "target_type", ("instance", "semantic", "polygon", "color")) + for value in self.target_type + ] + + if not os.path.isdir(self.images_dir) or not os.path.isdir(self.targets_dir): + + if split == "train_extra": + image_dir_zip = os.path.join(self.root, "leftImg8bit_trainextra.zip") + else: + image_dir_zip = os.path.join(self.root, "leftImg8bit_trainvaltest.zip") + + if self.mode == "gtFine": + target_dir_zip = os.path.join(self.root, f"{self.mode}_trainvaltest.zip") + elif self.mode == "gtCoarse": + target_dir_zip = os.path.join(self.root, f"{self.mode}.zip") + + if os.path.isfile(image_dir_zip) and os.path.isfile(target_dir_zip): + extract_archive(from_path=image_dir_zip, to_path=self.root) + extract_archive(from_path=target_dir_zip, to_path=self.root) + else: + raise RuntimeError( + "Dataset not found or incomplete. Please make sure all required folders for the" + ' specified "split" and "mode" are inside the "root" directory' + ) + + for city in os.listdir(self.images_dir): + img_dir = os.path.join(self.images_dir, city) + target_dir = os.path.join(self.targets_dir, city) + for file_name in os.listdir(img_dir): + target_types = [] + for t in self.target_type: + target_name = "{}_{}".format( + file_name.split("_leftImg8bit")[0], self._get_target_suffix(self.mode, t) + ) + target_types.append(os.path.join(target_dir, target_name)) + + self.images.append(os.path.join(img_dir, file_name)) + self.targets.append(target_types) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + Returns: + tuple: (image, target) where target is a tuple of all target types if target_type is a list with more + than one item. Otherwise, target is a json object if target_type="polygon", else the image segmentation. + """ + + image = Image.open(self.images[index]).convert("RGB") + + targets: Any = [] + for i, t in enumerate(self.target_type): + if t == "polygon": + target = self._load_json(self.targets[index][i]) + else: + target = Image.open(self.targets[index][i]) # type: ignore[assignment] + + targets.append(target) + + target = tuple(targets) if len(targets) > 1 else targets[0] # type: ignore[assignment] + + if self.transforms is not None: + image, target = self.transforms(image, target) + + return image, target + + def __len__(self) -> int: + return len(self.images) + + def extra_repr(self) -> str: + lines = ["Split: {split}", "Mode: {mode}", "Type: {target_type}"] + return "\n".join(lines).format(**self.__dict__) + + def _load_json(self, path: str) -> dict[str, Any]: + with open(path) as file: + data = json.load(file) + return data + + def _get_target_suffix(self, mode: str, target_type: str) -> str: + if target_type == "instance": + return f"{mode}_instanceIds.png" + elif target_type == "semantic": + return f"{mode}_labelIds.png" + elif target_type == "color": + return f"{mode}_color.png" + else: + return f"{mode}_polygons.json" diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/clevr.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/clevr.py new file mode 100644 index 0000000000000000000000000000000000000000..2bf24bc3c80a94aa2ca56b26fd0e1495374d03ab --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/clevr.py @@ -0,0 +1,93 @@ +import json +import pathlib +from typing import Any, Callable, Optional, Union +from urllib.parse import urlparse + +from .folder import default_loader + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class CLEVRClassification(VisionDataset): + """`CLEVR `_ classification dataset. + + The number of objects in a scene are used as label. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory ``root/clevr`` exists or will be saved to if download is + set to True. + split (string, optional): The dataset split, supports ``"train"`` (default), ``"val"``, or ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in them target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and puts it in root directory. If + dataset is already downloaded, it is not downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _URL = "https://dl.fbaipublicfiles.com/clevr/CLEVR_v1.0.zip" + _MD5 = "b11922020e72d0cd9154779b2d3d07d2" + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[Union[str, pathlib.Path]], Any] = default_loader, + ) -> None: + self._split = verify_str_arg(split, "split", ("train", "val", "test")) + super().__init__(root, transform=transform, target_transform=target_transform) + self.loader = loader + self._base_folder = pathlib.Path(self.root) / "clevr" + self._data_folder = self._base_folder / pathlib.Path(urlparse(self._URL).path).stem + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + self._image_files = sorted(self._data_folder.joinpath("images", self._split).glob("*")) + + self._labels: list[Optional[int]] + if self._split != "test": + with open(self._data_folder / "scenes" / f"CLEVR_{self._split}_scenes.json") as file: + content = json.load(file) + num_objects = {scene["image_filename"]: len(scene["objects"]) for scene in content["scenes"]} + self._labels = [num_objects[image_file.name] for image_file in self._image_files] + else: + self._labels = [None] * len(self._image_files) + + def __len__(self) -> int: + return len(self._image_files) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_file = self._image_files[idx] + label = self._labels[idx] + + image = self.loader(image_file) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def _check_exists(self) -> bool: + return self._data_folder.exists() and self._data_folder.is_dir() + + def _download(self) -> None: + if self._check_exists(): + return + + download_and_extract_archive(self._URL, str(self._base_folder), md5=self._MD5) + + def extra_repr(self) -> str: + return f"split={self._split}" diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/coco.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/coco.py new file mode 100644 index 0000000000000000000000000000000000000000..8f3b5d2dfe4a9047ef49322501582ed9d09cb5a1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/coco.py @@ -0,0 +1,111 @@ +import os.path +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .vision import VisionDataset + + +class CocoDetection(VisionDataset): + """`MS Coco Detection `_ Dataset. + + It requires `pycocotools `_ to be installed, + which could be installed via ``pip install pycocotools`` or ``conda install conda-forge::pycocotools``. + + Args: + root (str or ``pathlib.Path``): Root directory where images are downloaded to. + annFile (string): Path to json annotation file. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.PILToTensor`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + transforms (callable, optional): A function/transform that takes input sample and its target as entry + and returns a transformed version. + """ + + def __init__( + self, + root: Union[str, Path], + annFile: str, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + transforms: Optional[Callable] = None, + ) -> None: + super().__init__(root, transforms, transform, target_transform) + from pycocotools.coco import COCO + + self.coco = COCO(annFile) + self.ids = list(sorted(self.coco.imgs.keys())) + + def _load_image(self, id: int) -> Image.Image: + path = self.coco.loadImgs(id)[0]["file_name"] + return Image.open(os.path.join(self.root, path)).convert("RGB") + + def _load_target(self, id: int) -> list[Any]: + return self.coco.loadAnns(self.coco.getAnnIds(id)) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + + if not isinstance(index, int): + raise ValueError(f"Index must be of type integer, got {type(index)} instead.") + + id = self.ids[index] + image = self._load_image(id) + target = self._load_target(id) + + if self.transforms is not None: + image, target = self.transforms(image, target) + + return image, target + + def __len__(self) -> int: + return len(self.ids) + + +class CocoCaptions(CocoDetection): + """`MS Coco Captions `_ Dataset. + + It requires `pycocotools `_ to be installed, + which could be installed via ``pip install pycocotools`` or ``conda install conda-forge::pycocotools``. + + Args: + root (str or ``pathlib.Path``): Root directory where images are downloaded to. + annFile (string): Path to json annotation file. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.PILToTensor`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + transforms (callable, optional): A function/transform that takes input sample and its target as entry + and returns a transformed version. + + Example: + + .. code:: python + + import torchvision.datasets as dset + import torchvision.transforms as transforms + cap = dset.CocoCaptions(root = 'dir where images are', + annFile = 'json annotation file', + transform=transforms.PILToTensor()) + + print('Number of samples: ', len(cap)) + img, target = cap[3] # load 4th sample + + print("Image Size: ", img.size()) + print(target) + + Output: :: + + Number of samples: 82783 + Image Size: (3L, 427L, 640L) + [u'A plane emitting smoke stream flying over a mountain.', + u'A plane darts across a bright blue sky behind a mountain covered in snow', + u'A plane leaves a contrail above the snowy mountain top.', + u'A mountain that has a plane flying overheard in the distance.', + u'A mountain view with a plume of smoke in the background'] + + """ + + def _load_target(self, id: int) -> list[str]: + return [ann["caption"] for ann in super()._load_target(id)] diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/country211.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/country211.py new file mode 100644 index 0000000000000000000000000000000000000000..50d49db00a72e2592f15329b70f4f0cdbfa6b128 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/country211.py @@ -0,0 +1,67 @@ +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader, ImageFolder +from .utils import download_and_extract_archive, verify_str_arg + + +class Country211(ImageFolder): + """`The Country211 Data Set `_ from OpenAI. + + This dataset was built by filtering the images from the YFCC100m dataset + that have GPS coordinate corresponding to a ISO-3166 country code. The + dataset is balanced by sampling 150 train images, 50 validation images, and + 100 test images for each country. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), ``"valid"`` and ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and puts it into + ``root/country211/``. If dataset is already downloaded, it is not downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _URL = "https://openaipublic.azureedge.net/clip/data/country211.tgz" + _MD5 = "84988d7644798601126c29e9877aab6a" + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + self._split = verify_str_arg(split, "split", ("train", "valid", "test")) + + root = Path(root).expanduser() + self.root = str(root) + self._base_folder = root / "country211" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + super().__init__( + str(self._base_folder / self._split), + transform=transform, + target_transform=target_transform, + loader=loader, + ) + self.root = str(root) + + def _check_exists(self) -> bool: + return self._base_folder.exists() and self._base_folder.is_dir() + + def _download(self) -> None: + if self._check_exists(): + return + download_and_extract_archive(self._URL, download_root=self.root, md5=self._MD5) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/dtd.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/dtd.py new file mode 100644 index 0000000000000000000000000000000000000000..8fb347955d420e04a68cb7055c46409293235b62 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/dtd.py @@ -0,0 +1,105 @@ +import os +import pathlib +from typing import Any, Callable, Optional, Union + +from .folder import default_loader + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class DTD(VisionDataset): + """`Describable Textures Dataset (DTD) `_. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), ``"val"``, or ``"test"``. + partition (int, optional): The dataset partition. Should be ``1 <= partition <= 10``. Defaults to ``1``. + + .. note:: + + The partition only changes which split each image belongs to. Thus, regardless of the selected + partition, combining all splits will result in all images. + + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. Default is False. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _URL = "https://www.robots.ox.ac.uk/~vgg/data/dtd/download/dtd-r1.0.1.tar.gz" + _MD5 = "fff73e5086ae6bdbea199a49dfb8a4c1" + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "train", + partition: int = 1, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[Union[str, pathlib.Path]], Any] = default_loader, + ) -> None: + self._split = verify_str_arg(split, "split", ("train", "val", "test")) + if not isinstance(partition, int) and not (1 <= partition <= 10): + raise ValueError( + f"Parameter 'partition' should be an integer with `1 <= partition <= 10`, " + f"but got {partition} instead" + ) + self._partition = partition + + super().__init__(root, transform=transform, target_transform=target_transform) + self._base_folder = pathlib.Path(self.root) / type(self).__name__.lower() + self._data_folder = self._base_folder / "dtd" + self._meta_folder = self._data_folder / "labels" + self._images_folder = self._data_folder / "images" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + self._image_files = [] + classes = [] + with open(self._meta_folder / f"{self._split}{self._partition}.txt") as file: + for line in file: + cls, name = line.strip().split("/") + self._image_files.append(self._images_folder.joinpath(cls, name)) + classes.append(cls) + + self.classes = sorted(set(classes)) + self.class_to_idx = dict(zip(self.classes, range(len(self.classes)))) + self._labels = [self.class_to_idx[cls] for cls in classes] + self.loader = loader + + def __len__(self) -> int: + return len(self._image_files) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_file, label = self._image_files[idx], self._labels[idx] + image = self.loader(image_file) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def extra_repr(self) -> str: + return f"split={self._split}, partition={self._partition}" + + def _check_exists(self) -> bool: + return os.path.exists(self._data_folder) and os.path.isdir(self._data_folder) + + def _download(self) -> None: + if self._check_exists(): + return + download_and_extract_archive(self._URL, download_root=str(self._base_folder), md5=self._MD5) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/eurosat.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/eurosat.py new file mode 100644 index 0000000000000000000000000000000000000000..4efec57029f617b04b5822489e396bb60ba9b639 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/eurosat.py @@ -0,0 +1,71 @@ +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader, ImageFolder +from .utils import download_and_extract_archive + + +class EuroSAT(ImageFolder): + """RGB version of the `EuroSAT `_ Dataset. + + For the MS version of the dataset, see + `TorchGeo `__. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where ``root/eurosat`` exists. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. Default is False. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: Union[str, Path], + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + self.root = os.path.expanduser(root) + self._base_folder = os.path.join(self.root, "eurosat") + self._data_folder = os.path.join(self._base_folder, "2750") + + if download: + self.download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + super().__init__( + self._data_folder, + transform=transform, + target_transform=target_transform, + loader=loader, + ) + self.root = os.path.expanduser(root) + + def __len__(self) -> int: + return len(self.samples) + + def _check_exists(self) -> bool: + return os.path.exists(self._data_folder) + + def download(self) -> None: + + if self._check_exists(): + return + + os.makedirs(self._base_folder, exist_ok=True) + download_and_extract_archive( + "https://huggingface.co/datasets/torchgeo/eurosat/resolve/c877bcd43f099cd0196738f714544e355477f3fd/EuroSAT.zip", + download_root=self._base_folder, + md5="c8fa014336c82ac7804f0398fcb19387", + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/fakedata.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/fakedata.py new file mode 100644 index 0000000000000000000000000000000000000000..bcb413cdd32e784d962b9be46d53cf319fd677e3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/fakedata.py @@ -0,0 +1,67 @@ +from typing import Any, Callable, Optional + +import torch + +from .. import transforms +from .vision import VisionDataset + + +class FakeData(VisionDataset): + """A fake dataset that returns randomly generated images and returns them as PIL images + + Args: + size (int, optional): Size of the dataset. Default: 1000 images + image_size(tuple, optional): Size of the returned images. Default: (3, 224, 224) + num_classes(int, optional): Number of classes in the dataset. Default: 10 + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + random_offset (int): Offsets the index-based random seed used to + generate each image. Default: 0 + + """ + + def __init__( + self, + size: int = 1000, + image_size: tuple[int, int, int] = (3, 224, 224), + num_classes: int = 10, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + random_offset: int = 0, + ) -> None: + super().__init__(transform=transform, target_transform=target_transform) + self.size = size + self.num_classes = num_classes + self.image_size = image_size + self.random_offset = random_offset + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is class_index of the target class. + """ + # create random image that is consistent with the index id + if index >= len(self): + raise IndexError(f"{self.__class__.__name__} index out of range") + rng_state = torch.get_rng_state() + torch.manual_seed(index + self.random_offset) + img = torch.randn(*self.image_size) + target = torch.randint(0, self.num_classes, size=(1,), dtype=torch.long)[0] + torch.set_rng_state(rng_state) + + # convert to PIL Image + img = transforms.ToPILImage()(img) + if self.transform is not None: + img = self.transform(img) + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target.item() + + def __len__(self) -> int: + return self.size diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/fer2013.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/fer2013.py new file mode 100644 index 0000000000000000000000000000000000000000..f33afbeebc82e5bc62feb23bdefffe7a1472e22f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/fer2013.py @@ -0,0 +1,120 @@ +import csv +import pathlib +from typing import Any, Callable, Optional, Union + +import torch +from PIL import Image + +from .utils import check_integrity, verify_str_arg +from .vision import VisionDataset + + +class FER2013(VisionDataset): + """`FER2013 + `_ Dataset. + + .. note:: + This dataset can return test labels only if ``fer2013.csv`` OR + ``icml_face_data.csv`` are present in ``root/fer2013/``. If only + ``train.csv`` and ``test.csv`` are present, the test labels are set to + ``None``. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``root/fer2013`` exists. This directory may contain either + ``fer2013.csv``, ``icml_face_data.csv``, or both ``train.csv`` and + ``test.csv``. Precendence is given in that order, i.e. if + ``fer2013.csv`` is present then the rest of the files will be + ignored. All these (combinations of) files contain the same data and + are supported for convenience, but only ``fer2013.csv`` and + ``icml_face_data.csv`` are able to return non-None test labels. + split (string, optional): The dataset split, supports ``"train"`` (default), or ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed + version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + """ + + _RESOURCES = { + "train": ("train.csv", "3f0dfb3d3fd99c811a1299cb947e3131"), + "test": ("test.csv", "b02c2298636a634e8c2faabbf3ea9a23"), + # The fer2013.csv and icml_face_data.csv files contain both train and + # tests instances, and unlike test.csv they contain the labels for the + # test instances. We give these 2 files precedence over train.csv and + # test.csv. And yes, they both contain the same data, but with different + # column names (note the spaces) and ordering: + # $ head -n 1 fer2013.csv icml_face_data.csv train.csv test.csv + # ==> fer2013.csv <== + # emotion,pixels,Usage + # + # ==> icml_face_data.csv <== + # emotion, Usage, pixels + # + # ==> train.csv <== + # emotion,pixels + # + # ==> test.csv <== + # pixels + "fer": ("fer2013.csv", "f8428a1edbd21e88f42c73edd2a14f95"), + "icml": ("icml_face_data.csv", "b114b9e04e6949e5fe8b6a98b3892b1d"), + } + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + ) -> None: + self._split = verify_str_arg(split, "split", ("train", "test")) + super().__init__(root, transform=transform, target_transform=target_transform) + + base_folder = pathlib.Path(self.root) / "fer2013" + use_fer_file = (base_folder / self._RESOURCES["fer"][0]).exists() + use_icml_file = not use_fer_file and (base_folder / self._RESOURCES["icml"][0]).exists() + file_name, md5 = self._RESOURCES["fer" if use_fer_file else "icml" if use_icml_file else self._split] + data_file = base_folder / file_name + if not check_integrity(str(data_file), md5=md5): + raise RuntimeError( + f"{file_name} not found in {base_folder} or corrupted. " + f"You can download it from " + f"https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge" + ) + + pixels_key = " pixels" if use_icml_file else "pixels" + usage_key = " Usage" if use_icml_file else "Usage" + + def get_img(row): + return torch.tensor([int(idx) for idx in row[pixels_key].split()], dtype=torch.uint8).reshape(48, 48) + + def get_label(row): + if use_fer_file or use_icml_file or self._split == "train": + return int(row["emotion"]) + else: + return None + + with open(data_file, newline="") as file: + rows = (row for row in csv.DictReader(file)) + + if use_fer_file or use_icml_file: + valid_keys = ("Training",) if self._split == "train" else ("PublicTest", "PrivateTest") + rows = (row for row in rows if row[usage_key] in valid_keys) + + self._samples = [(get_img(row), get_label(row)) for row in rows] + + def __len__(self) -> int: + return len(self._samples) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_tensor, target = self._samples[idx] + image = Image.fromarray(image_tensor.numpy()) + + if self.transform is not None: + image = self.transform(image) + + if self.target_transform is not None: + target = self.target_transform(target) + + return image, target + + def extra_repr(self) -> str: + return f"split={self._split}" diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/fgvc_aircraft.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/fgvc_aircraft.py new file mode 100644 index 0000000000000000000000000000000000000000..a3f2277b23353fda4191bc1e6df87a805600e10d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/fgvc_aircraft.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import os +from pathlib import Path +from typing import Any, Callable + +from .folder import default_loader + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class FGVCAircraft(VisionDataset): + """`FGVC Aircraft `_ Dataset. + + The dataset contains 10,000 images of aircraft, with 100 images for each of 100 + different aircraft model variants, most of which are airplanes. + Aircraft models are organized in a three-levels hierarchy. The three levels, from + finer to coarser, are: + + - ``variant``, e.g. Boeing 737-700. A variant collapses all the models that are visually + indistinguishable into one class. The dataset comprises 100 different variants. + - ``family``, e.g. Boeing 737. The dataset comprises 70 different families. + - ``manufacturer``, e.g. Boeing. The dataset comprises 30 different manufacturers. + + Args: + root (str or ``pathlib.Path``): Root directory of the FGVC Aircraft dataset. + split (string, optional): The dataset split, supports ``train``, ``val``, + ``trainval`` and ``test``. + annotation_level (str, optional): The annotation level, supports ``variant``, + ``family`` and ``manufacturer``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _URL = "https://www.robots.ox.ac.uk/~vgg/data/fgvc-aircraft/archives/fgvc-aircraft-2013b.tar.gz" + + def __init__( + self, + root: str | Path, + split: str = "trainval", + annotation_level: str = "variant", + transform: Callable | None = None, + target_transform: Callable | None = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self._split = verify_str_arg(split, "split", ("train", "val", "trainval", "test")) + self._annotation_level = verify_str_arg( + annotation_level, "annotation_level", ("variant", "family", "manufacturer") + ) + + self._data_path = os.path.join(self.root, "fgvc-aircraft-2013b") + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + annotation_file = os.path.join( + self._data_path, + "data", + { + "variant": "variants.txt", + "family": "families.txt", + "manufacturer": "manufacturers.txt", + }[self._annotation_level], + ) + with open(annotation_file) as f: + self.classes = [line.strip() for line in f] + + self.class_to_idx = dict(zip(self.classes, range(len(self.classes)))) + + image_data_folder = os.path.join(self._data_path, "data", "images") + labels_file = os.path.join(self._data_path, "data", f"images_{self._annotation_level}_{self._split}.txt") + + self._image_files = [] + self._labels = [] + + with open(labels_file) as f: + for line in f: + image_name, label_name = line.strip().split(" ", 1) + self._image_files.append(os.path.join(image_data_folder, f"{image_name}.jpg")) + self._labels.append(self.class_to_idx[label_name]) + self.loader = loader + + def __len__(self) -> int: + return len(self._image_files) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_file, label = self._image_files[idx], self._labels[idx] + image = self.loader(image_file) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def _download(self) -> None: + """ + Download the FGVC Aircraft dataset archive and extract it under root. + """ + if self._check_exists(): + return + download_and_extract_archive(self._URL, self.root) + + def _check_exists(self) -> bool: + return os.path.exists(self._data_path) and os.path.isdir(self._data_path) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/flickr.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/flickr.py new file mode 100644 index 0000000000000000000000000000000000000000..84f1dc0e1702d0a263d8c8a05dcaad47dde35a14 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/flickr.py @@ -0,0 +1,176 @@ +import glob +import os +from collections import defaultdict +from html.parser import HTMLParser +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader +from .vision import VisionDataset + + +class Flickr8kParser(HTMLParser): + """Parser for extracting captions from the Flickr8k dataset web page.""" + + def __init__(self, root: Union[str, Path]) -> None: + super().__init__() + + self.root = root + + # Data structure to store captions + self.annotations: dict[str, list[str]] = {} + + # State variables + self.in_table = False + self.current_tag: Optional[str] = None + self.current_img: Optional[str] = None + + def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None: + self.current_tag = tag + + if tag == "table": + self.in_table = True + + def handle_endtag(self, tag: str) -> None: + self.current_tag = None + + if tag == "table": + self.in_table = False + + def handle_data(self, data: str) -> None: + if self.in_table: + if data == "Image Not Found": + self.current_img = None + elif self.current_tag == "a": + img_id = data.split("/")[-2] + img_id = os.path.join(self.root, img_id + "_*.jpg") + img_id = glob.glob(img_id)[0] + self.current_img = img_id + self.annotations[img_id] = [] + elif self.current_tag == "li" and self.current_img: + img_id = self.current_img + self.annotations[img_id].append(data.strip()) + + +class Flickr8k(VisionDataset): + """`Flickr8k Entities `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory where images are downloaded to. + ann_file (string): Path to annotation file. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: Union[str, Path], + ann_file: str, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.ann_file = os.path.expanduser(ann_file) + + # Read annotations and store in a dict + parser = Flickr8kParser(self.root) + with open(self.ann_file) as fh: + parser.feed(fh.read()) + self.annotations = parser.annotations + + self.ids = list(sorted(self.annotations.keys())) + self.loader = loader + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: Tuple (image, target). target is a list of captions for the image. + """ + img_id = self.ids[index] + + # Image + img = self.loader(img_id) + if self.transform is not None: + img = self.transform(img) + + # Captions + target = self.annotations[img_id] + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.ids) + + +class Flickr30k(VisionDataset): + """`Flickr30k Entities `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory where images are downloaded to. + ann_file (string): Path to annotation file. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: str, + ann_file: str, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.ann_file = os.path.expanduser(ann_file) + + # Read annotations and store in a dict + self.annotations = defaultdict(list) + with open(self.ann_file) as fh: + for line in fh: + img_id, caption = line.strip().split("\t") + self.annotations[img_id[:-2]].append(caption) + + self.ids = list(sorted(self.annotations.keys())) + self.loader = loader + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: Tuple (image, target). target is a list of captions for the image. + """ + img_id = self.ids[index] + + # Image + filename = os.path.join(self.root, img_id) + img = self.loader(filename) + if self.transform is not None: + img = self.transform(img) + + # Captions + target = self.annotations[img_id] + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.ids) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/flowers102.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/flowers102.py new file mode 100644 index 0000000000000000000000000000000000000000..80bca71e9676869c49a9f9f01d8b6e6df7323a23 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/flowers102.py @@ -0,0 +1,225 @@ +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader + +from .utils import check_integrity, download_and_extract_archive, download_url, verify_str_arg +from .vision import VisionDataset + + +class Flowers102(VisionDataset): + """`Oxford 102 Flower `_ Dataset. + + .. warning:: + + This class needs `scipy `_ to load target files from `.mat` format. + + Oxford 102 Flower is an image classification dataset consisting of 102 flower categories. The + flowers were chosen to be flowers commonly occurring in the United Kingdom. Each class consists of + between 40 and 258 images. + + The images have large scale, pose and light variations. In addition, there are categories that + have large variations within the category, and several very similar categories. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), ``"val"``, or ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _download_url_prefix = "https://www.robots.ox.ac.uk/~vgg/data/flowers/102/" + _file_dict = { # filename, md5 + "image": ("102flowers.tgz", "52808999861908f626f3c1f4e79d11fa"), + "label": ("imagelabels.mat", "e0620be6f572b9609742df49c70aed4d"), + "setid": ("setid.mat", "a5357ecc9cb78c4bef273ce3793fc85c"), + } + _splits_map = {"train": "trnid", "val": "valid", "test": "tstid"} + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[Union[str, Path]], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self._split = verify_str_arg(split, "split", ("train", "val", "test")) + self._base_folder = Path(self.root) / "flowers-102" + self._images_folder = self._base_folder / "jpg" + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + from scipy.io import loadmat + + set_ids = loadmat(self._base_folder / self._file_dict["setid"][0], squeeze_me=True) + image_ids = set_ids[self._splits_map[self._split]].tolist() + + labels = loadmat(self._base_folder / self._file_dict["label"][0], squeeze_me=True) + image_id_to_label = dict(enumerate((labels["labels"] - 1).tolist(), 1)) + + self._labels = [] + self._image_files = [] + for image_id in image_ids: + self._labels.append(image_id_to_label[image_id]) + self._image_files.append(self._images_folder / f"image_{image_id:05d}.jpg") + + self.loader = loader + + def __len__(self) -> int: + return len(self._image_files) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_file, label = self._image_files[idx], self._labels[idx] + image = self.loader(image_file) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def extra_repr(self) -> str: + return f"split={self._split}" + + def _check_integrity(self): + if not (self._images_folder.exists() and self._images_folder.is_dir()): + return False + + for id in ["label", "setid"]: + filename, md5 = self._file_dict[id] + if not check_integrity(str(self._base_folder / filename), md5): + return False + return True + + def download(self): + if self._check_integrity(): + return + download_and_extract_archive( + f"{self._download_url_prefix}{self._file_dict['image'][0]}", + str(self._base_folder), + md5=self._file_dict["image"][1], + ) + for id in ["label", "setid"]: + filename, md5 = self._file_dict[id] + download_url(self._download_url_prefix + filename, str(self._base_folder), md5=md5) + + classes = [ + "pink primrose", + "hard-leaved pocket orchid", + "canterbury bells", + "sweet pea", + "english marigold", + "tiger lily", + "moon orchid", + "bird of paradise", + "monkshood", + "globe thistle", + "snapdragon", + "colt's foot", + "king protea", + "spear thistle", + "yellow iris", + "globe-flower", + "purple coneflower", + "peruvian lily", + "balloon flower", + "giant white arum lily", + "fire lily", + "pincushion flower", + "fritillary", + "red ginger", + "grape hyacinth", + "corn poppy", + "prince of wales feathers", + "stemless gentian", + "artichoke", + "sweet william", + "carnation", + "garden phlox", + "love in the mist", + "mexican aster", + "alpine sea holly", + "ruby-lipped cattleya", + "cape flower", + "great masterwort", + "siam tulip", + "lenten rose", + "barbeton daisy", + "daffodil", + "sword lily", + "poinsettia", + "bolero deep blue", + "wallflower", + "marigold", + "buttercup", + "oxeye daisy", + "common dandelion", + "petunia", + "wild pansy", + "primula", + "sunflower", + "pelargonium", + "bishop of llandaff", + "gaura", + "geranium", + "orange dahlia", + "pink-yellow dahlia?", + "cautleya spicata", + "japanese anemone", + "black-eyed susan", + "silverbush", + "californian poppy", + "osteospermum", + "spring crocus", + "bearded iris", + "windflower", + "tree poppy", + "gazania", + "azalea", + "water lily", + "rose", + "thorn apple", + "morning glory", + "passion flower", + "lotus", + "toad lily", + "anthurium", + "frangipani", + "clematis", + "hibiscus", + "columbine", + "desert-rose", + "tree mallow", + "magnolia", + "cyclamen", + "watercress", + "canna lily", + "hippeastrum", + "bee balm", + "ball moss", + "foxglove", + "bougainvillea", + "camellia", + "mallow", + "mexican petunia", + "bromelia", + "blanket flower", + "trumpet creeper", + "blackberry lily", + ] diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/folder.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/folder.py new file mode 100644 index 0000000000000000000000000000000000000000..387439c0433e8fa9f16163b1ad9629591639d09e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/folder.py @@ -0,0 +1,337 @@ +import os +import os.path +from pathlib import Path +from typing import Any, Callable, cast, Optional, Union + +from PIL import Image + +from .vision import VisionDataset + + +def has_file_allowed_extension(filename: str, extensions: Union[str, tuple[str, ...]]) -> bool: + """Checks if a file is an allowed extension. + + Args: + filename (string): path to a file + extensions (tuple of strings): extensions to consider (lowercase) + + Returns: + bool: True if the filename ends with one of given extensions + """ + return filename.lower().endswith(extensions if isinstance(extensions, str) else tuple(extensions)) + + +def is_image_file(filename: str) -> bool: + """Checks if a file is an allowed image extension. + + Args: + filename (string): path to a file + + Returns: + bool: True if the filename ends with a known image extension + """ + return has_file_allowed_extension(filename, IMG_EXTENSIONS) + + +def find_classes(directory: Union[str, Path]) -> tuple[list[str], dict[str, int]]: + """Finds the class folders in a dataset. + + See :class:`DatasetFolder` for details. + """ + classes = sorted(entry.name for entry in os.scandir(directory) if entry.is_dir()) + if not classes: + raise FileNotFoundError(f"Couldn't find any class folder in {directory}.") + + class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)} + return classes, class_to_idx + + +def make_dataset( + directory: Union[str, Path], + class_to_idx: Optional[dict[str, int]] = None, + extensions: Optional[Union[str, tuple[str, ...]]] = None, + is_valid_file: Optional[Callable[[str], bool]] = None, + allow_empty: bool = False, +) -> list[tuple[str, int]]: + """Generates a list of samples of a form (path_to_sample, class). + + See :class:`DatasetFolder` for details. + + Note: The class_to_idx parameter is here optional and will use the logic of the ``find_classes`` function + by default. + """ + directory = os.path.expanduser(directory) + + if class_to_idx is None: + _, class_to_idx = find_classes(directory) + elif not class_to_idx: + raise ValueError("'class_to_index' must have at least one entry to collect any samples.") + + both_none = extensions is None and is_valid_file is None + both_something = extensions is not None and is_valid_file is not None + if both_none or both_something: + raise ValueError("Both extensions and is_valid_file cannot be None or not None at the same time") + + if extensions is not None: + + def is_valid_file(x: str) -> bool: + return has_file_allowed_extension(x, extensions) # type: ignore[arg-type] + + is_valid_file = cast(Callable[[str], bool], is_valid_file) + + instances = [] + available_classes = set() + for target_class in sorted(class_to_idx.keys()): + class_index = class_to_idx[target_class] + target_dir = os.path.join(directory, target_class) + if not os.path.isdir(target_dir): + continue + for root, _, fnames in sorted(os.walk(target_dir, followlinks=True)): + for fname in sorted(fnames): + path = os.path.join(root, fname) + if is_valid_file(path): + item = path, class_index + instances.append(item) + + if target_class not in available_classes: + available_classes.add(target_class) + + empty_classes = set(class_to_idx.keys()) - available_classes + if empty_classes and not allow_empty: + msg = f"Found no valid file for the classes {', '.join(sorted(empty_classes))}. " + if extensions is not None: + msg += f"Supported extensions are: {extensions if isinstance(extensions, str) else ', '.join(extensions)}" + raise FileNotFoundError(msg) + + return instances + + +class DatasetFolder(VisionDataset): + """A generic data loader. + + This default directory structure can be customized by overriding the + :meth:`find_classes` method. + + Args: + root (str or ``pathlib.Path``): Root directory path. + loader (callable): A function to load a sample given its path. + extensions (tuple[string]): A list of allowed extensions. + both extensions and is_valid_file should not be passed. + transform (callable, optional): A function/transform that takes in + a sample and returns a transformed version. + E.g, ``transforms.RandomCrop`` for images. + target_transform (callable, optional): A function/transform that takes + in the target and transforms it. + is_valid_file (callable, optional): A function that takes path of a file + and check if the file is a valid file (used to check of corrupt files) + both extensions and is_valid_file should not be passed. + allow_empty(bool, optional): If True, empty folders are considered to be valid classes. + An error is raised on empty folders if False (default). + + Attributes: + classes (list): List of the class names sorted alphabetically. + class_to_idx (dict): Dict with items (class_name, class_index). + samples (list): List of (sample path, class_index) tuples + targets (list): The class_index value for each image in the dataset + """ + + def __init__( + self, + root: Union[str, Path], + loader: Callable[[str], Any], + extensions: Optional[tuple[str, ...]] = None, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + is_valid_file: Optional[Callable[[str], bool]] = None, + allow_empty: bool = False, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + classes, class_to_idx = self.find_classes(self.root) + samples = self.make_dataset( + self.root, + class_to_idx=class_to_idx, + extensions=extensions, + is_valid_file=is_valid_file, + allow_empty=allow_empty, + ) + + self.loader = loader + self.extensions = extensions + + self.classes = classes + self.class_to_idx = class_to_idx + self.samples = samples + self.targets = [s[1] for s in samples] + + @staticmethod + def make_dataset( + directory: Union[str, Path], + class_to_idx: dict[str, int], + extensions: Optional[tuple[str, ...]] = None, + is_valid_file: Optional[Callable[[str], bool]] = None, + allow_empty: bool = False, + ) -> list[tuple[str, int]]: + """Generates a list of samples of a form (path_to_sample, class). + + This can be overridden to e.g. read files from a compressed zip file instead of from the disk. + + Args: + directory (str): root dataset directory, corresponding to ``self.root``. + class_to_idx (Dict[str, int]): Dictionary mapping class name to class index. + extensions (optional): A list of allowed extensions. + Either extensions or is_valid_file should be passed. Defaults to None. + is_valid_file (optional): A function that takes path of a file + and checks if the file is a valid file + (used to check of corrupt files) both extensions and + is_valid_file should not be passed. Defaults to None. + allow_empty(bool, optional): If True, empty folders are considered to be valid classes. + An error is raised on empty folders if False (default). + + Raises: + ValueError: In case ``class_to_idx`` is empty. + ValueError: In case ``extensions`` and ``is_valid_file`` are None or both are not None. + FileNotFoundError: In case no valid file was found for any class. + + Returns: + List[Tuple[str, int]]: samples of a form (path_to_sample, class) + """ + if class_to_idx is None: + # prevent potential bug since make_dataset() would use the class_to_idx logic of the + # find_classes() function, instead of using that of the find_classes() method, which + # is potentially overridden and thus could have a different logic. + raise ValueError("The class_to_idx parameter cannot be None.") + return make_dataset( + directory, class_to_idx, extensions=extensions, is_valid_file=is_valid_file, allow_empty=allow_empty + ) + + def find_classes(self, directory: Union[str, Path]) -> tuple[list[str], dict[str, int]]: + """Find the class folders in a dataset structured as follows:: + + directory/ + ├── class_x + │ ├── xxx.ext + │ ├── xxy.ext + │ └── ... + │ └── xxz.ext + └── class_y + ├── 123.ext + ├── nsdf3.ext + └── ... + └── asd932_.ext + + This method can be overridden to only consider + a subset of classes, or to adapt to a different dataset directory structure. + + Args: + directory(str): Root directory path, corresponding to ``self.root`` + + Raises: + FileNotFoundError: If ``dir`` has no class folders. + + Returns: + (Tuple[List[str], Dict[str, int]]): List of all classes and dictionary mapping each class to an index. + """ + return find_classes(directory) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (sample, target) where target is class_index of the target class. + """ + path, target = self.samples[index] + sample = self.loader(path) + if self.transform is not None: + sample = self.transform(sample) + if self.target_transform is not None: + target = self.target_transform(target) + + return sample, target + + def __len__(self) -> int: + return len(self.samples) + + +IMG_EXTENSIONS = (".jpg", ".jpeg", ".png", ".ppm", ".bmp", ".pgm", ".tif", ".tiff", ".webp") + + +def pil_loader(path: Union[str, Path]) -> Image.Image: + # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835) + with open(path, "rb") as f: + img = Image.open(f) + return img.convert("RGB") + + +# TODO: specify the return type +def accimage_loader(path: Union[str, Path]) -> Any: + import accimage + + try: + return accimage.Image(path) + except OSError: + # Potentially a decoding problem, fall back to PIL.Image + return pil_loader(path) + + +def default_loader(path: Union[str, Path]) -> Any: + from torchvision import get_image_backend + + if get_image_backend() == "accimage": + return accimage_loader(path) + else: + return pil_loader(path) + + +class ImageFolder(DatasetFolder): + """A generic data loader where the images are arranged in this way by default: :: + + root/dog/xxx.png + root/dog/xxy.png + root/dog/[...]/xxz.png + + root/cat/123.png + root/cat/nsdf3.png + root/cat/[...]/asd932_.png + + This class inherits from :class:`~torchvision.datasets.DatasetFolder` so + the same methods can be overridden to customize the dataset. + + Args: + root (str or ``pathlib.Path``): Root directory path. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + loader (callable, optional): A function to load an image given its path. + is_valid_file (callable, optional): A function that takes path of an Image file + and check if the file is a valid file (used to check of corrupt files) + allow_empty(bool, optional): If True, empty folders are considered to be valid classes. + An error is raised on empty folders if False (default). + + Attributes: + classes (list): List of the class names sorted alphabetically. + class_to_idx (dict): Dict with items (class_name, class_index). + imgs (list): List of (image path, class_index) tuples + """ + + def __init__( + self, + root: Union[str, Path], + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + is_valid_file: Optional[Callable[[str], bool]] = None, + allow_empty: bool = False, + ): + super().__init__( + root, + loader, + IMG_EXTENSIONS if is_valid_file is None else None, + transform=transform, + target_transform=target_transform, + is_valid_file=is_valid_file, + allow_empty=allow_empty, + ) + self.imgs = self.samples diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/food101.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/food101.py new file mode 100644 index 0000000000000000000000000000000000000000..fee23680b05255029c1e3b433e7890df754f0fe0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/food101.py @@ -0,0 +1,98 @@ +import json +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class Food101(VisionDataset): + """`The Food-101 Data Set `_. + + The Food-101 is a challenging data set of 101 food categories with 101,000 images. + For each class, 250 manually reviewed test images are provided as well as 750 training images. + On purpose, the training images were not cleaned, and thus still contain some amount of noise. + This comes mostly in the form of intense colors and sometimes wrong labels. All images were + rescaled to have a maximum side length of 512 pixels. + + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default) and ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. Default is False. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _URL = "http://data.vision.ee.ethz.ch/cvl/food-101.tar.gz" + _MD5 = "85eeb15f3717b99a5da872d97d918f87" + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[Union[str, Path]], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self._split = verify_str_arg(split, "split", ("train", "test")) + self._base_folder = Path(self.root) / "food-101" + self._meta_folder = self._base_folder / "meta" + self._images_folder = self._base_folder / "images" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + self._labels = [] + self._image_files = [] + with open(self._meta_folder / f"{split}.json") as f: + metadata = json.loads(f.read()) + + self.classes = sorted(metadata.keys()) + self.class_to_idx = dict(zip(self.classes, range(len(self.classes)))) + + for class_label, im_rel_paths in metadata.items(): + self._labels += [self.class_to_idx[class_label]] * len(im_rel_paths) + self._image_files += [ + self._images_folder.joinpath(*f"{im_rel_path}.jpg".split("/")) for im_rel_path in im_rel_paths + ] + self.loader = loader + + def __len__(self) -> int: + return len(self._image_files) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_file, label = self._image_files[idx], self._labels[idx] + image = self.loader(image_file) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def extra_repr(self) -> str: + return f"split={self._split}" + + def _check_exists(self) -> bool: + return all(folder.exists() and folder.is_dir() for folder in (self._meta_folder, self._images_folder)) + + def _download(self) -> None: + if self._check_exists(): + return + download_and_extract_archive(self._URL, download_root=self.root, md5=self._MD5) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/gtsrb.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/gtsrb.py new file mode 100644 index 0000000000000000000000000000000000000000..e6b60116c401dd7819f527f095990dea2193b8ec --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/gtsrb.py @@ -0,0 +1,103 @@ +import csv +import pathlib +from typing import Any, Callable, Optional, Union + +import PIL + +from .folder import make_dataset +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class GTSRB(VisionDataset): + """`German Traffic Sign Recognition Benchmark (GTSRB) `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), or ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed + version. E.g, ``transforms.RandomCrop``. + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + """ + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + + super().__init__(root, transform=transform, target_transform=target_transform) + + self._split = verify_str_arg(split, "split", ("train", "test")) + self._base_folder = pathlib.Path(root) / "gtsrb" + self._target_folder = ( + self._base_folder / "GTSRB" / ("Training" if self._split == "train" else "Final_Test/Images") + ) + + if download: + self.download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + if self._split == "train": + samples = make_dataset(str(self._target_folder), extensions=(".ppm",)) + else: + with open(self._base_folder / "GT-final_test.csv") as csv_file: + samples = [ + (str(self._target_folder / row["Filename"]), int(row["ClassId"])) + for row in csv.DictReader(csv_file, delimiter=";", skipinitialspace=True) + ] + + self._samples = samples + self.transform = transform + self.target_transform = target_transform + + def __len__(self) -> int: + return len(self._samples) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + + path, target = self._samples[index] + sample = PIL.Image.open(path).convert("RGB") + + if self.transform is not None: + sample = self.transform(sample) + + if self.target_transform is not None: + target = self.target_transform(target) + + return sample, target + + def _check_exists(self) -> bool: + return self._target_folder.is_dir() + + def download(self) -> None: + if self._check_exists(): + return + + base_url = "https://sid.erda.dk/public/archives/daaeac0d7ce1152aea9b61d9f1e19370/" + + if self._split == "train": + download_and_extract_archive( + f"{base_url}GTSRB-Training_fixed.zip", + download_root=str(self._base_folder), + md5="513f3c79a4c5141765e10e952eaa2478", + ) + else: + download_and_extract_archive( + f"{base_url}GTSRB_Final_Test_Images.zip", + download_root=str(self._base_folder), + md5="c7e4e6327067d32654124b0fe9e82185", + ) + download_and_extract_archive( + f"{base_url}GTSRB_Final_Test_GT.zip", + download_root=str(self._base_folder), + md5="fe31e9c9270bbcd7b84b7f21a9d9d9e5", + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/hmdb51.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/hmdb51.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b84771cac21e41cc27b2e18f18922ec7e74952 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/hmdb51.py @@ -0,0 +1,152 @@ +import glob +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from torch import Tensor + +from .folder import find_classes, make_dataset +from .video_utils import VideoClips +from .vision import VisionDataset + + +class HMDB51(VisionDataset): + """ + `HMDB51 `_ + dataset. + + HMDB51 is an action recognition video dataset. + This dataset consider every video as a collection of video clips of fixed size, specified + by ``frames_per_clip``, where the step in frames between each clip is given by + ``step_between_clips``. + + To give an example, for 2 videos with 10 and 15 frames respectively, if ``frames_per_clip=5`` + and ``step_between_clips=5``, the dataset size will be (2 + 3) = 5, where the first two + elements will come from video 1, and the next three elements from video 2. + Note that we drop clips which do not have exactly ``frames_per_clip`` elements, so not all + frames in a video might be present. + + Internally, it uses a VideoClips object to handle clip creation. + + Args: + root (str or ``pathlib.Path``): Root directory of the HMDB51 Dataset. + annotation_path (str): Path to the folder containing the split files. + frames_per_clip (int): Number of frames in a clip. + step_between_clips (int): Number of frames between each clip. + fold (int, optional): Which fold to use. Should be between 1 and 3. + train (bool, optional): If ``True``, creates a dataset from the train split, + otherwise from the ``test`` split. + transform (callable, optional): A function/transform that takes in a TxHxWxC video + and returns a transformed version. + output_format (str, optional): The format of the output video tensors (before transforms). + Can be either "THWC" (default) or "TCHW". + + Returns: + tuple: A 3-tuple with the following entries: + + - video (Tensor[T, H, W, C] or Tensor[T, C, H, W]): The `T` video frames + - audio(Tensor[K, L]): the audio frames, where `K` is the number of channels + and `L` is the number of points + - label (int): class of the video clip + """ + + data_url = "https://serre-lab.clps.brown.edu/wp-content/uploads/2013/10/hmdb51_org.rar" + splits = { + "url": "https://serre-lab.clps.brown.edu/wp-content/uploads/2013/10/test_train_splits.rar", + "md5": "15e67781e70dcfbdce2d7dbb9b3344b5", + } + TRAIN_TAG = 1 + TEST_TAG = 2 + + def __init__( + self, + root: Union[str, Path], + annotation_path: str, + frames_per_clip: int, + step_between_clips: int = 1, + frame_rate: Optional[int] = None, + fold: int = 1, + train: bool = True, + transform: Optional[Callable] = None, + _precomputed_metadata: Optional[dict[str, Any]] = None, + num_workers: int = 1, + _video_width: int = 0, + _video_height: int = 0, + _video_min_dimension: int = 0, + _audio_samples: int = 0, + output_format: str = "THWC", + ) -> None: + super().__init__(root) + if fold not in (1, 2, 3): + raise ValueError(f"fold should be between 1 and 3, got {fold}") + + extensions = ("avi",) + self.classes, class_to_idx = find_classes(self.root) + self.samples = make_dataset( + self.root, + class_to_idx, + extensions, + ) + + video_paths = [path for (path, _) in self.samples] + video_clips = VideoClips( + video_paths, + frames_per_clip, + step_between_clips, + frame_rate, + _precomputed_metadata, + num_workers=num_workers, + _video_width=_video_width, + _video_height=_video_height, + _video_min_dimension=_video_min_dimension, + _audio_samples=_audio_samples, + output_format=output_format, + ) + # we bookkeep the full version of video clips because we want to be able + # to return the metadata of full version rather than the subset version of + # video clips + self.full_video_clips = video_clips + self.fold = fold + self.train = train + self.indices = self._select_fold(video_paths, annotation_path, fold, train) + self.video_clips = video_clips.subset(self.indices) + self.transform = transform + + @property + def metadata(self) -> dict[str, Any]: + return self.full_video_clips.metadata + + def _select_fold(self, video_list: list[str], annotations_dir: str, fold: int, train: bool) -> list[int]: + target_tag = self.TRAIN_TAG if train else self.TEST_TAG + split_pattern_name = f"*test_split{fold}.txt" + split_pattern_path = os.path.join(annotations_dir, split_pattern_name) + annotation_paths = glob.glob(split_pattern_path) + selected_files = set() + for filepath in annotation_paths: + with open(filepath) as fid: + lines = fid.readlines() + for line in lines: + video_filename, tag_string = line.split() + tag = int(tag_string) + if tag == target_tag: + selected_files.add(video_filename) + + indices = [] + for video_index, video_path in enumerate(video_list): + if os.path.basename(video_path) in selected_files: + indices.append(video_index) + + return indices + + def __len__(self) -> int: + return self.video_clips.num_clips() + + def __getitem__(self, idx: int) -> tuple[Tensor, Tensor, int]: + video, audio, _, video_idx = self.video_clips.get_clip(idx) + sample_index = self.indices[video_idx] + _, class_index = self.samples[sample_index] + + if self.transform is not None: + video = self.transform(video) + + return video, audio, class_index diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/imagenet.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/imagenet.py new file mode 100644 index 0000000000000000000000000000000000000000..1808dc4f85b0bb77ac2fa469f17b5f903621f608 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/imagenet.py @@ -0,0 +1,222 @@ +import os +import shutil +import tempfile +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Optional, Union + +import torch + +from .folder import ImageFolder +from .utils import check_integrity, extract_archive, verify_str_arg + +ARCHIVE_META = { + "train": ("ILSVRC2012_img_train.tar", "1d675b47d978889d74fa0da5fadfb00e"), + "val": ("ILSVRC2012_img_val.tar", "29b22e2961454d5413ddabcf34fc5622"), + "devkit": ("ILSVRC2012_devkit_t12.tar.gz", "fa75699e90414af021442c21a62c3abf"), +} + +META_FILE = "meta.bin" + + +class ImageNet(ImageFolder): + """`ImageNet `_ 2012 Classification Dataset. + + .. note:: + Before using this class, it is required to download ImageNet 2012 dataset from + `here `_ and + place the files ``ILSVRC2012_devkit_t12.tar.gz`` and ``ILSVRC2012_img_train.tar`` + or ``ILSVRC2012_img_val.tar`` based on ``split`` in the root directory. + + Args: + root (str or ``pathlib.Path``): Root directory of the ImageNet Dataset. + split (string, optional): The dataset split, supports ``train``, or ``val``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + + Attributes: + classes (list): List of the class name tuples. + class_to_idx (dict): Dict with items (class_name, class_index). + wnids (list): List of the WordNet IDs. + wnid_to_idx (dict): Dict with items (wordnet_id, class_index). + imgs (list): List of (image path, class_index) tuples + targets (list): The class_index value for each image in the dataset + """ + + def __init__(self, root: Union[str, Path], split: str = "train", **kwargs: Any) -> None: + root = self.root = os.path.expanduser(root) + self.split = verify_str_arg(split, "split", ("train", "val")) + + self.parse_archives() + wnid_to_classes = load_meta_file(self.root)[0] + + super().__init__(self.split_folder, **kwargs) + self.root = root + + self.wnids = self.classes + self.wnid_to_idx = self.class_to_idx + self.classes = [wnid_to_classes[wnid] for wnid in self.wnids] + self.class_to_idx = {cls: idx for idx, clss in enumerate(self.classes) for cls in clss} + + def parse_archives(self) -> None: + if not check_integrity(os.path.join(self.root, META_FILE)): + parse_devkit_archive(self.root) + + if not os.path.isdir(self.split_folder): + if self.split == "train": + parse_train_archive(self.root) + elif self.split == "val": + parse_val_archive(self.root) + + @property + def split_folder(self) -> str: + return os.path.join(self.root, self.split) + + def extra_repr(self) -> str: + return "Split: {split}".format(**self.__dict__) + + +def load_meta_file(root: Union[str, Path], file: Optional[str] = None) -> tuple[dict[str, str], list[str]]: + if file is None: + file = META_FILE + file = os.path.join(root, file) + + if check_integrity(file): + return torch.load(file, weights_only=True) + else: + msg = ( + "The meta file {} is not present in the root directory or is corrupted. " + "This file is automatically created by the ImageNet dataset." + ) + raise RuntimeError(msg.format(file, root)) + + +def _verify_archive(root: Union[str, Path], file: str, md5: str) -> None: + if not check_integrity(os.path.join(root, file), md5): + msg = ( + "The archive {} is not present in the root directory or is corrupted. " + "You need to download it externally and place it in {}." + ) + raise RuntimeError(msg.format(file, root)) + + +def parse_devkit_archive(root: Union[str, Path], file: Optional[str] = None) -> None: + """Parse the devkit archive of the ImageNet2012 classification dataset and save + the meta information in a binary file. + + Args: + root (str or ``pathlib.Path``): Root directory containing the devkit archive + file (str, optional): Name of devkit archive. Defaults to + 'ILSVRC2012_devkit_t12.tar.gz' + """ + import scipy.io as sio + + def parse_meta_mat(devkit_root: str) -> tuple[dict[int, str], dict[str, tuple[str, ...]]]: + metafile = os.path.join(devkit_root, "data", "meta.mat") + meta = sio.loadmat(metafile, squeeze_me=True)["synsets"] + nums_children = list(zip(*meta))[4] + meta = [meta[idx] for idx, num_children in enumerate(nums_children) if num_children == 0] + idcs, wnids, classes = list(zip(*meta))[:3] + classes = [tuple(clss.split(", ")) for clss in classes] + idx_to_wnid = {idx: wnid for idx, wnid in zip(idcs, wnids)} + wnid_to_classes = {wnid: clss for wnid, clss in zip(wnids, classes)} + return idx_to_wnid, wnid_to_classes + + def parse_val_groundtruth_txt(devkit_root: str) -> list[int]: + file = os.path.join(devkit_root, "data", "ILSVRC2012_validation_ground_truth.txt") + with open(file) as txtfh: + val_idcs = txtfh.readlines() + return [int(val_idx) for val_idx in val_idcs] + + @contextmanager + def get_tmp_dir() -> Iterator[str]: + tmp_dir = tempfile.mkdtemp() + try: + yield tmp_dir + finally: + shutil.rmtree(tmp_dir) + + archive_meta = ARCHIVE_META["devkit"] + if file is None: + file = archive_meta[0] + md5 = archive_meta[1] + + _verify_archive(root, file, md5) + + with get_tmp_dir() as tmp_dir: + extract_archive(os.path.join(root, file), tmp_dir) + + devkit_root = os.path.join(tmp_dir, "ILSVRC2012_devkit_t12") + idx_to_wnid, wnid_to_classes = parse_meta_mat(devkit_root) + val_idcs = parse_val_groundtruth_txt(devkit_root) + val_wnids = [idx_to_wnid[idx] for idx in val_idcs] + + torch.save((wnid_to_classes, val_wnids), os.path.join(root, META_FILE)) + + +def parse_train_archive(root: Union[str, Path], file: Optional[str] = None, folder: str = "train") -> None: + """Parse the train images archive of the ImageNet2012 classification dataset and + prepare it for usage with the ImageNet dataset. + + Args: + root (str or ``pathlib.Path``): Root directory containing the train images archive + file (str, optional): Name of train images archive. Defaults to + 'ILSVRC2012_img_train.tar' + folder (str, optional): Optional name for train images folder. Defaults to + 'train' + """ + archive_meta = ARCHIVE_META["train"] + if file is None: + file = archive_meta[0] + md5 = archive_meta[1] + + _verify_archive(root, file, md5) + + train_root = os.path.join(root, folder) + extract_archive(os.path.join(root, file), train_root) + + archives = [os.path.join(train_root, archive) for archive in os.listdir(train_root)] + for archive in archives: + extract_archive(archive, os.path.splitext(archive)[0], remove_finished=True) + + +def parse_val_archive( + root: Union[str, Path], file: Optional[str] = None, wnids: Optional[list[str]] = None, folder: str = "val" +) -> None: + """Parse the validation images archive of the ImageNet2012 classification dataset + and prepare it for usage with the ImageNet dataset. + + Args: + root (str or ``pathlib.Path``): Root directory containing the validation images archive + file (str, optional): Name of validation images archive. Defaults to + 'ILSVRC2012_img_val.tar' + wnids (list, optional): List of WordNet IDs of the validation images. If None + is given, the IDs are loaded from the meta file in the root directory + folder (str, optional): Optional name for validation images folder. Defaults to + 'val' + """ + archive_meta = ARCHIVE_META["val"] + if file is None: + file = archive_meta[0] + md5 = archive_meta[1] + if wnids is None: + wnids = load_meta_file(root)[1] + + _verify_archive(root, file, md5) + + val_root = os.path.join(root, folder) + extract_archive(os.path.join(root, file), val_root) + + images = sorted(os.path.join(val_root, image) for image in os.listdir(val_root)) + + for wnid in set(wnids): + os.mkdir(os.path.join(val_root, wnid)) + + for wnid, img_file in zip(wnids, images): + shutil.move(img_file, os.path.join(val_root, wnid, os.path.basename(img_file))) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/imagenette.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/imagenette.py new file mode 100644 index 0000000000000000000000000000000000000000..16bac9bfadcb99ebf16736cfa89bebc1dcc32e46 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/imagenette.py @@ -0,0 +1,104 @@ +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader, find_classes, make_dataset +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class Imagenette(VisionDataset): + """`Imagenette `_ image classification dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of the Imagenette dataset. + split (string, optional): The dataset split. Supports ``"train"`` (default), and ``"val"``. + size (string, optional): The image size. Supports ``"full"`` (default), ``"320px"``, and ``"160px"``. + download (bool, optional): If ``True``, downloads the dataset components and places them in ``root``. Already + downloaded archives are not downloaded again. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + + Attributes: + classes (list): List of the class name tuples. + class_to_idx (dict): Dict with items (class name, class index). + wnids (list): List of the WordNet IDs. + wnid_to_idx (dict): Dict with items (WordNet ID, class index). + """ + + _ARCHIVES = { + "full": ("https://s3.amazonaws.com/fast-ai-imageclas/imagenette2.tgz", "fe2fc210e6bb7c5664d602c3cd71e612"), + "320px": ("https://s3.amazonaws.com/fast-ai-imageclas/imagenette2-320.tgz", "3df6f0d01a2c9592104656642f5e78a3"), + "160px": ("https://s3.amazonaws.com/fast-ai-imageclas/imagenette2-160.tgz", "e793b78cc4c9e9a4ccc0c1155377a412"), + } + _WNID_TO_CLASS = { + "n01440764": ("tench", "Tinca tinca"), + "n02102040": ("English springer", "English springer spaniel"), + "n02979186": ("cassette player",), + "n03000684": ("chain saw", "chainsaw"), + "n03028079": ("church", "church building"), + "n03394916": ("French horn", "horn"), + "n03417042": ("garbage truck", "dustcart"), + "n03425413": ("gas pump", "gasoline pump", "petrol pump", "island dispenser"), + "n03445777": ("golf ball",), + "n03888257": ("parachute", "chute"), + } + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + size: str = "full", + download=False, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + + self._split = verify_str_arg(split, "split", ["train", "val"]) + self._size = verify_str_arg(size, "size", ["full", "320px", "160px"]) + + self._url, self._md5 = self._ARCHIVES[self._size] + self._size_root = Path(self.root) / Path(self._url).stem + self._image_root = str(self._size_root / self._split) + + if download: + self._download() + elif not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it.") + + self.wnids, self.wnid_to_idx = find_classes(self._image_root) + self.classes = [self._WNID_TO_CLASS[wnid] for wnid in self.wnids] + self.class_to_idx = { + class_name: idx for wnid, idx in self.wnid_to_idx.items() for class_name in self._WNID_TO_CLASS[wnid] + } + self._samples = make_dataset(self._image_root, self.wnid_to_idx, extensions=".jpeg") + self.loader = loader + + def _check_exists(self) -> bool: + return self._size_root.exists() + + def _download(self): + if self._check_exists(): + return + + download_and_extract_archive(self._url, self.root, md5=self._md5) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + path, label = self._samples[idx] + image = self.loader(path) + + if self.transform is not None: + image = self.transform(image) + + if self.target_transform is not None: + label = self.target_transform(label) + + return image, label + + def __len__(self) -> int: + return len(self._samples) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/inaturalist.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/inaturalist.py new file mode 100644 index 0000000000000000000000000000000000000000..a47483e158d04830b607d2f2cca42650f5b077e7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/inaturalist.py @@ -0,0 +1,245 @@ +import os +import os.path +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + +CATEGORIES_2021 = ["kingdom", "phylum", "class", "order", "family", "genus"] + +DATASET_URLS = { + "2017": "https://ml-inat-competition-datasets.s3.amazonaws.com/2017/train_val_images.tar.gz", + "2018": "https://ml-inat-competition-datasets.s3.amazonaws.com/2018/train_val2018.tar.gz", + "2019": "https://ml-inat-competition-datasets.s3.amazonaws.com/2019/train_val2019.tar.gz", + "2021_train": "https://ml-inat-competition-datasets.s3.amazonaws.com/2021/train.tar.gz", + "2021_train_mini": "https://ml-inat-competition-datasets.s3.amazonaws.com/2021/train_mini.tar.gz", + "2021_valid": "https://ml-inat-competition-datasets.s3.amazonaws.com/2021/val.tar.gz", +} + +DATASET_MD5 = { + "2017": "7c784ea5e424efaec655bd392f87301f", + "2018": "b1c6952ce38f31868cc50ea72d066cc3", + "2019": "c60a6e2962c9b8ccbd458d12c8582644", + "2021_train": "e0526d53c7f7b2e3167b2b43bb2690ed", + "2021_train_mini": "db6ed8330e634445efc8fec83ae81442", + "2021_valid": "f6f6e0e242e3d4c9569ba56400938afc", +} + + +class INaturalist(VisionDataset): + """`iNaturalist `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where the image files are stored. + This class does not require/use annotation files. + version (string, optional): Which version of the dataset to download/use. One of + '2017', '2018', '2019', '2021_train', '2021_train_mini', '2021_valid'. + Default: `2021_train`. + target_type (string or list, optional): Type of target to use, for 2021 versions, one of: + + - ``full``: the full category (species) + - ``kingdom``: e.g. "Animalia" + - ``phylum``: e.g. "Arthropoda" + - ``class``: e.g. "Insecta" + - ``order``: e.g. "Coleoptera" + - ``family``: e.g. "Cleridae" + - ``genus``: e.g. "Trichodes" + + for 2017-2019 versions, one of: + + - ``full``: the full (numeric) category + - ``super``: the super category, e.g. "Amphibians" + + Can also be a list to output a tuple with all specified target types. + Defaults to ``full``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: Union[str, Path], + version: str = "2021_train", + target_type: Union[list[str], str] = "full", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Optional[Callable[[Union[str, Path]], Any]] = None, + ) -> None: + self.version = verify_str_arg(version, "version", DATASET_URLS.keys()) + + super().__init__(os.path.join(root, version), transform=transform, target_transform=target_transform) + + os.makedirs(root, exist_ok=True) + if download: + self.download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + self.all_categories: list[str] = [] + + # map: category type -> name of category -> index + self.categories_index: dict[str, dict[str, int]] = {} + + # list indexed by category id, containing mapping from category type -> index + self.categories_map: list[dict[str, int]] = [] + + if not isinstance(target_type, list): + target_type = [target_type] + if self.version[:4] == "2021": + self.target_type = [verify_str_arg(t, "target_type", ("full", *CATEGORIES_2021)) for t in target_type] + self._init_2021() + else: + self.target_type = [verify_str_arg(t, "target_type", ("full", "super")) for t in target_type] + self._init_pre2021() + + # index of all files: (full category id, filename) + self.index: list[tuple[int, str]] = [] + + for dir_index, dir_name in enumerate(self.all_categories): + files = os.listdir(os.path.join(self.root, dir_name)) + for fname in files: + self.index.append((dir_index, fname)) + + self.loader = loader + + def _init_2021(self) -> None: + """Initialize based on 2021 layout""" + + self.all_categories = sorted(os.listdir(self.root)) + + # map: category type -> name of category -> index + self.categories_index = {k: {} for k in CATEGORIES_2021} + + for dir_index, dir_name in enumerate(self.all_categories): + pieces = dir_name.split("_") + if len(pieces) != 8: + raise RuntimeError(f"Unexpected category name {dir_name}, wrong number of pieces") + if pieces[0] != f"{dir_index:05d}": + raise RuntimeError(f"Unexpected category id {pieces[0]}, expecting {dir_index:05d}") + cat_map = {} + for cat, name in zip(CATEGORIES_2021, pieces[1:7]): + if name in self.categories_index[cat]: + cat_id = self.categories_index[cat][name] + else: + cat_id = len(self.categories_index[cat]) + self.categories_index[cat][name] = cat_id + cat_map[cat] = cat_id + self.categories_map.append(cat_map) + + def _init_pre2021(self) -> None: + """Initialize based on 2017-2019 layout""" + + # map: category type -> name of category -> index + self.categories_index = {"super": {}} + + cat_index = 0 + super_categories = sorted(os.listdir(self.root)) + for sindex, scat in enumerate(super_categories): + self.categories_index["super"][scat] = sindex + subcategories = sorted(os.listdir(os.path.join(self.root, scat))) + for subcat in subcategories: + if self.version == "2017": + # this version does not use ids as directory names + subcat_i = cat_index + cat_index += 1 + else: + try: + subcat_i = int(subcat) + except ValueError: + raise RuntimeError(f"Unexpected non-numeric dir name: {subcat}") + if subcat_i >= len(self.categories_map): + old_len = len(self.categories_map) + self.categories_map.extend([{}] * (subcat_i - old_len + 1)) + self.all_categories.extend([""] * (subcat_i - old_len + 1)) + if self.categories_map[subcat_i]: + raise RuntimeError(f"Duplicate category {subcat}") + self.categories_map[subcat_i] = {"super": sindex} + self.all_categories[subcat_i] = os.path.join(scat, subcat) + + # validate the dictionary + for cindex, c in enumerate(self.categories_map): + if not c: + raise RuntimeError(f"Missing category {cindex}") + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where the type of target specified by target_type. + """ + + cat_id, fname = self.index[index] + image_path = os.path.join(self.root, self.all_categories[cat_id], fname) + img = self.loader(image_path) if self.loader is not None else Image.open(image_path) + + target: Any = [] + for t in self.target_type: + if t == "full": + target.append(cat_id) + else: + target.append(self.categories_map[cat_id][t]) + target = tuple(target) if len(target) > 1 else target[0] + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.index) + + def category_name(self, category_type: str, category_id: int) -> str: + """ + Args: + category_type(str): one of "full", "kingdom", "phylum", "class", "order", "family", "genus" or "super" + category_id(int): an index (class id) from this category + + Returns: + the name of the category + """ + if category_type == "full": + return self.all_categories[category_id] + else: + if category_type not in self.categories_index: + raise ValueError(f"Invalid category type '{category_type}'") + else: + for name, id in self.categories_index[category_type].items(): + if id == category_id: + return name + raise ValueError(f"Invalid category id {category_id} for {category_type}") + + def _check_exists(self) -> bool: + return os.path.exists(self.root) and len(os.listdir(self.root)) > 0 + + def download(self) -> None: + if self._check_exists(): + return + + base_root = os.path.dirname(self.root) + + download_and_extract_archive( + DATASET_URLS[self.version], base_root, filename=f"{self.version}.tgz", md5=DATASET_MD5[self.version] + ) + + orig_dir_name = os.path.join(base_root, os.path.basename(DATASET_URLS[self.version]).rstrip(".tar.gz")) + if not os.path.exists(orig_dir_name): + raise RuntimeError(f"Unable to find downloaded files at {orig_dir_name}") + os.rename(orig_dir_name, self.root) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/kinetics.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/kinetics.py new file mode 100644 index 0000000000000000000000000000000000000000..c568e46a62d5d8f92c0bfcdb7ce79b6b60f234ce --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/kinetics.py @@ -0,0 +1,237 @@ +import csv +import os +import urllib +from functools import partial +from multiprocessing import Pool +from os import path +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from torch import Tensor + +from .folder import find_classes, make_dataset +from .utils import check_integrity, download_and_extract_archive, download_url, verify_str_arg +from .video_utils import VideoClips +from .vision import VisionDataset + + +def _dl_wrap(tarpath: Union[str, Path], videopath: Union[str, Path], line: str) -> None: + download_and_extract_archive(line, tarpath, videopath) + + +class Kinetics(VisionDataset): + """`Generic Kinetics `_ + dataset. + + Kinetics-400/600/700 are action recognition video datasets. + This dataset consider every video as a collection of video clips of fixed size, specified + by ``frames_per_clip``, where the step in frames between each clip is given by + ``step_between_clips``. + + To give an example, for 2 videos with 10 and 15 frames respectively, if ``frames_per_clip=5`` + and ``step_between_clips=5``, the dataset size will be (2 + 3) = 5, where the first two + elements will come from video 1, and the next three elements from video 2. + Note that we drop clips which do not have exactly ``frames_per_clip`` elements, so not all + frames in a video might be present. + + Args: + root (str or ``pathlib.Path``): Root directory of the Kinetics Dataset. + Directory should be structured as follows: + .. code:: + + root/ + ├── split + │ ├── class1 + │ │ ├── vid1.mp4 + │ │ ├── vid2.mp4 + │ │ ├── vid3.mp4 + │ │ ├── ... + │ ├── class2 + │ │ ├── vidx.mp4 + │ │ └── ... + + Note: split is appended automatically using the split argument. + frames_per_clip (int): number of frames in a clip + num_classes (int): select between Kinetics-400 (default), Kinetics-600, and Kinetics-700 + split (str): split of the dataset to consider; supports ``"train"`` (default) ``"val"`` ``"test"`` + frame_rate (float): If omitted, interpolate different frame rate for each clip. + step_between_clips (int): number of frames between each clip + transform (callable, optional): A function/transform that takes in a TxHxWxC video + and returns a transformed version. + download (bool): Download the official version of the dataset to root folder. + num_workers (int): Use multiple workers for VideoClips creation + num_download_workers (int): Use multiprocessing in order to speed up download. + output_format (str, optional): The format of the output video tensors (before transforms). + Can be either "THWC" or "TCHW" (default). + Note that in most other utils and datasets, the default is actually "THWC". + + Returns: + tuple: A 3-tuple with the following entries: + + - video (Tensor[T, C, H, W] or Tensor[T, H, W, C]): the `T` video frames in torch.uint8 tensor + - audio(Tensor[K, L]): the audio frames, where `K` is the number of channels + and `L` is the number of points in torch.float tensor + - label (int): class of the video clip + + Raises: + RuntimeError: If ``download is True`` and the video archives are already extracted. + """ + + _TAR_URLS = { + "400": "https://s3.amazonaws.com/kinetics/400/{split}/k400_{split}_path.txt", + "600": "https://s3.amazonaws.com/kinetics/600/{split}/k600_{split}_path.txt", + "700": "https://s3.amazonaws.com/kinetics/700_2020/{split}/k700_2020_{split}_path.txt", + } + _ANNOTATION_URLS = { + "400": "https://s3.amazonaws.com/kinetics/400/annotations/{split}.csv", + "600": "https://s3.amazonaws.com/kinetics/600/annotations/{split}.csv", + "700": "https://s3.amazonaws.com/kinetics/700_2020/annotations/{split}.csv", + } + + def __init__( + self, + root: Union[str, Path], + frames_per_clip: int, + num_classes: str = "400", + split: str = "train", + frame_rate: Optional[int] = None, + step_between_clips: int = 1, + transform: Optional[Callable] = None, + extensions: tuple[str, ...] = ("avi", "mp4"), + download: bool = False, + num_download_workers: int = 1, + num_workers: int = 1, + _precomputed_metadata: Optional[dict[str, Any]] = None, + _video_width: int = 0, + _video_height: int = 0, + _video_min_dimension: int = 0, + _audio_samples: int = 0, + _audio_channels: int = 0, + _legacy: bool = False, + output_format: str = "TCHW", + ) -> None: + + # TODO: support test + self.num_classes = verify_str_arg(num_classes, arg="num_classes", valid_values=["400", "600", "700"]) + self.extensions = extensions + self.num_download_workers = num_download_workers + + self.root = root + self._legacy = _legacy + + if _legacy: + self.split_folder = root + self.split = "unknown" + output_format = "THWC" + if download: + raise ValueError("Cannot download the videos using legacy_structure.") + else: + self.split_folder = path.join(root, split) + self.split = verify_str_arg(split, arg="split", valid_values=["train", "val", "test"]) + + if download: + self.download_and_process_videos() + + super().__init__(self.root) + + self.classes, class_to_idx = find_classes(self.split_folder) + self.samples = make_dataset(self.split_folder, class_to_idx, extensions, is_valid_file=None) + video_list = [x[0] for x in self.samples] + self.video_clips = VideoClips( + video_list, + frames_per_clip, + step_between_clips, + frame_rate, + _precomputed_metadata, + num_workers=num_workers, + _video_width=_video_width, + _video_height=_video_height, + _video_min_dimension=_video_min_dimension, + _audio_samples=_audio_samples, + _audio_channels=_audio_channels, + output_format=output_format, + ) + self.transform = transform + + def download_and_process_videos(self) -> None: + """Downloads all the videos to the _root_ folder in the expected format.""" + self._download_videos() + self._make_ds_structure() + + def _download_videos(self) -> None: + """download tarballs containing the video to "tars" folder and extract them into the _split_ folder where + split is one of the official dataset splits. + + Raises: + RuntimeError: if download folder exists, break to prevent downloading entire dataset again. + """ + if path.exists(self.split_folder): + return + tar_path = path.join(self.root, "tars") + file_list_path = path.join(self.root, "files") + + split_url = self._TAR_URLS[self.num_classes].format(split=self.split) + split_url_filepath = path.join(file_list_path, path.basename(split_url)) + if not check_integrity(split_url_filepath): + download_url(split_url, file_list_path) + with open(split_url_filepath) as file: + list_video_urls = [urllib.parse.quote(line, safe="/,:") for line in file.read().splitlines()] + + if self.num_download_workers == 1: + for line in list_video_urls: + download_and_extract_archive(line, tar_path, self.split_folder) + else: + part = partial(_dl_wrap, tar_path, self.split_folder) + poolproc = Pool(self.num_download_workers) + poolproc.map(part, list_video_urls) + + def _make_ds_structure(self) -> None: + """move videos from + split_folder/ + ├── clip1.avi + ├── clip2.avi + + to the correct format as described below: + split_folder/ + ├── class1 + │ ├── clip1.avi + + """ + annotation_path = path.join(self.root, "annotations") + if not check_integrity(path.join(annotation_path, f"{self.split}.csv")): + download_url(self._ANNOTATION_URLS[self.num_classes].format(split=self.split), annotation_path) + annotations = path.join(annotation_path, f"{self.split}.csv") + + file_fmtstr = "{ytid}_{start:06}_{end:06}.mp4" + with open(annotations) as csvfile: + reader = csv.DictReader(csvfile) + for row in reader: + f = file_fmtstr.format( + ytid=row["youtube_id"], + start=int(row["time_start"]), + end=int(row["time_end"]), + ) + label = row["label"].replace(" ", "_").replace("'", "").replace("(", "").replace(")", "") + os.makedirs(path.join(self.split_folder, label), exist_ok=True) + downloaded_file = path.join(self.split_folder, f) + if path.isfile(downloaded_file): + os.replace( + downloaded_file, + path.join(self.split_folder, label, f), + ) + + @property + def metadata(self) -> dict[str, Any]: + return self.video_clips.metadata + + def __len__(self) -> int: + return self.video_clips.num_clips() + + def __getitem__(self, idx: int) -> tuple[Tensor, Tensor, int]: + video, audio, info, video_idx = self.video_clips.get_clip(idx) + label = self.samples[video_idx][1] + + if self.transform is not None: + video = self.transform(video) + + return video, audio, label diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/kitti.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/kitti.py new file mode 100644 index 0000000000000000000000000000000000000000..d275248d92a5cad4efe8dfaf7ec89c6dda6dd8ef --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/kitti.py @@ -0,0 +1,158 @@ +import csv +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .utils import download_and_extract_archive +from .vision import VisionDataset + + +class Kitti(VisionDataset): + """`KITTI `_ Dataset. + + It corresponds to the "left color images of object" dataset, for object detection. + + Args: + root (str or ``pathlib.Path``): Root directory where images are downloaded to. + Expects the following folder structure if download=False: + + .. code:: + + + └── Kitti + └─ raw + ├── training + | ├── image_2 + | └── label_2 + └── testing + └── image_2 + train (bool, optional): Use ``train`` split if true, else ``test`` split. + Defaults to ``train``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.PILToTensor`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + transforms (callable, optional): A function/transform that takes input sample + and its target as entry and returns a transformed version. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + """ + + data_url = "https://s3.eu-central-1.amazonaws.com/avg-kitti/" + resources = [ + "data_object_image_2.zip", + "data_object_label_2.zip", + ] + image_dir_name = "image_2" + labels_dir_name = "label_2" + + def __init__( + self, + root: Union[str, Path], + train: bool = True, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + transforms: Optional[Callable] = None, + download: bool = False, + ): + super().__init__( + root, + transform=transform, + target_transform=target_transform, + transforms=transforms, + ) + self.images = [] + self.targets = [] + self.train = train + self._location = "training" if self.train else "testing" + + if download: + self.download() + if not self._check_exists(): + raise RuntimeError("Dataset not found. You may use download=True to download it.") + + image_dir = os.path.join(self._raw_folder, self._location, self.image_dir_name) + if self.train: + labels_dir = os.path.join(self._raw_folder, self._location, self.labels_dir_name) + for img_file in os.listdir(image_dir): + self.images.append(os.path.join(image_dir, img_file)) + if self.train: + self.targets.append(os.path.join(labels_dir, f"{img_file.split('.')[0]}.txt")) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """Get item at a given index. + + Args: + index (int): Index + Returns: + tuple: (image, target), where + target is a list of dictionaries with the following keys: + + - type: str + - truncated: float + - occluded: int + - alpha: float + - bbox: float[4] + - dimensions: float[3] + - locations: float[3] + - rotation_y: float + + """ + image = Image.open(self.images[index]) + target = self._parse_target(index) if self.train else None + if self.transforms: + image, target = self.transforms(image, target) + return image, target + + def _parse_target(self, index: int) -> list: + target = [] + with open(self.targets[index]) as inp: + content = csv.reader(inp, delimiter=" ") + for line in content: + target.append( + { + "type": line[0], + "truncated": float(line[1]), + "occluded": int(line[2]), + "alpha": float(line[3]), + "bbox": [float(x) for x in line[4:8]], + "dimensions": [float(x) for x in line[8:11]], + "location": [float(x) for x in line[11:14]], + "rotation_y": float(line[14]), + } + ) + return target + + def __len__(self) -> int: + return len(self.images) + + @property + def _raw_folder(self) -> str: + return os.path.join(self.root, self.__class__.__name__, "raw") + + def _check_exists(self) -> bool: + """Check if the data directory exists.""" + folders = [self.image_dir_name] + if self.train: + folders.append(self.labels_dir_name) + return all(os.path.isdir(os.path.join(self._raw_folder, self._location, fname)) for fname in folders) + + def download(self) -> None: + """Download the KITTI data if it doesn't exist already.""" + + if self._check_exists(): + return + + os.makedirs(self._raw_folder, exist_ok=True) + + # download files + for fname in self.resources: + download_and_extract_archive( + url=f"{self.data_url}{fname}", + download_root=self._raw_folder, + filename=fname, + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/lfw.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/lfw.py new file mode 100644 index 0000000000000000000000000000000000000000..feb6a9bf5f8509e744823e97b1e634d1ef579a25 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/lfw.py @@ -0,0 +1,272 @@ +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader +from .utils import check_integrity, download_and_extract_archive, download_url, verify_str_arg +from .vision import VisionDataset + + +class _LFW(VisionDataset): + + base_folder = "lfw-py" + download_url_prefix = "http://vis-www.cs.umass.edu/lfw/" + + file_dict = { + "original": ("lfw", "lfw.tgz", "a17d05bd522c52d84eca14327a23d494"), + "funneled": ("lfw_funneled", "lfw-funneled.tgz", "1b42dfed7d15c9b2dd63d5e5840c86ad"), + "deepfunneled": ("lfw-deepfunneled", "lfw-deepfunneled.tgz", "68331da3eb755a505a502b5aacb3c201"), + } + checksums = { + "pairs.txt": "9f1ba174e4e1c508ff7cdf10ac338a7d", + "pairsDevTest.txt": "5132f7440eb68cf58910c8a45a2ac10b", + "pairsDevTrain.txt": "4f27cbf15b2da4a85c1907eb4181ad21", + "people.txt": "450f0863dd89e85e73936a6d71a3474b", + "peopleDevTest.txt": "e4bf5be0a43b5dcd9dc5ccfcb8fb19c5", + "peopleDevTrain.txt": "54eaac34beb6d042ed3a7d883e247a21", + "lfw-names.txt": "a6d0a479bd074669f656265a6e693f6d", + } + annot_file = {"10fold": "", "train": "DevTrain", "test": "DevTest"} + names = "lfw-names.txt" + + def __init__( + self, + root: Union[str, Path], + split: str, + image_set: str, + view: str, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(os.path.join(root, self.base_folder), transform=transform, target_transform=target_transform) + + self.image_set = verify_str_arg(image_set.lower(), "image_set", self.file_dict.keys()) + images_dir, self.filename, self.md5 = self.file_dict[self.image_set] + + self.view = verify_str_arg(view.lower(), "view", ["people", "pairs"]) + self.split = verify_str_arg(split.lower(), "split", ["10fold", "train", "test"]) + self.labels_file = f"{self.view}{self.annot_file[self.split]}.txt" + self.data: list[Any] = [] + + if download: + raise ValueError( + "LFW dataset is no longer available for automatic download." + "Please download the dataset manually and place it in the specified directory." + "A commonly used mirror is available at: " + "https://www.kaggle.com/datasets/jessicali9530/lfw-dataset" + ) + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + self.images_dir = os.path.join(self.root, images_dir) + self._loader = loader + + def _check_integrity(self) -> bool: + st1 = check_integrity(os.path.join(self.root, self.filename), self.md5) + st2 = check_integrity(os.path.join(self.root, self.labels_file), self.checksums[self.labels_file]) + if not st1 or not st2: + return False + if self.view == "people": + return check_integrity(os.path.join(self.root, self.names), self.checksums[self.names]) + return True + + def download(self) -> None: + if self._check_integrity(): + return + url = f"{self.download_url_prefix}{self.filename}" + download_and_extract_archive(url, self.root, filename=self.filename, md5=self.md5) + download_url(f"{self.download_url_prefix}{self.labels_file}", self.root) + if self.view == "people": + download_url(f"{self.download_url_prefix}{self.names}", self.root) + + def _get_path(self, identity: str, no: Union[int, str]) -> str: + return os.path.join(self.images_dir, identity, f"{identity}_{int(no):04d}.jpg") + + def extra_repr(self) -> str: + return f"Alignment: {self.image_set}\nSplit: {self.split}" + + def __len__(self) -> int: + return len(self.data) + + +class LFWPeople(_LFW): + """`LFW `_ Dataset. + + .. warning:: + + The LFW dataset is no longer available for automatic download. Please + download it manually and place it in the specified directory. + A commonly used mirror is available at: https://www.kaggle.com/datasets/jessicali9530/lfw-dataset + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``lfw-py`` exists or will be saved to if download is set to True. + split (string, optional): The image split to use. Can be one of ``train``, ``test``, + ``10fold`` (default). + image_set (str, optional): Type of image funneling to use, ``original``, ``funneled`` or + ``deepfunneled``. Defaults to ``funneled``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): NOT SUPPORTED ANYMORE, leave to False. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: str, + split: str = "10fold", + image_set: str = "funneled", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, split, image_set, "people", transform, target_transform, download, loader=loader) + + self.class_to_idx = self._get_classes() + self.data, self.targets = self._get_people() + + def _get_people(self) -> tuple[list[str], list[int]]: + data, targets = [], [] + with open(os.path.join(self.root, self.labels_file)) as f: + lines = f.readlines() + n_folds, s = (int(lines[0]), 1) if self.split == "10fold" else (1, 0) + + for fold in range(n_folds): + n_lines = int(lines[s]) + people = [line.strip().split("\t") for line in lines[s + 1 : s + n_lines + 1]] + s += n_lines + 1 + for i, (identity, num_imgs) in enumerate(people): + for num in range(1, int(num_imgs) + 1): + img = self._get_path(identity, num) + data.append(img) + targets.append(self.class_to_idx[identity]) + + return data, targets + + def _get_classes(self) -> dict[str, int]: + with open(os.path.join(self.root, self.names)) as f: + lines = f.readlines() + names = [line.strip().split()[0] for line in lines] + class_to_idx = {name: i for i, name in enumerate(names)} + return class_to_idx + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: Tuple (image, target) where target is the identity of the person. + """ + img = self._loader(self.data[index]) + target = self.targets[index] + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def extra_repr(self) -> str: + return super().extra_repr() + f"\nClasses (identities): {len(self.class_to_idx)}" + + +class LFWPairs(_LFW): + """`LFW `_ Dataset. + + .. warning:: + + The LFW dataset is no longer available for automatic download. Please + download it manually and place it in the specified directory. + A commonly used mirror is available at: https://www.kaggle.com/datasets/jessicali9530/lfw-dataset + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``lfw-py`` exists or will be saved to if download is set to True. + split (string, optional): The image split to use. Can be one of ``train``, ``test``, + ``10fold``. Defaults to ``10fold``. + image_set (str, optional): Type of image funneling to use, ``original``, ``funneled`` or + ``deepfunneled``. Defaults to ``funneled``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomRotation`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): NOT SUPPORTED ANYMORE, leave to False. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + + """ + + def __init__( + self, + root: str, + split: str = "10fold", + image_set: str = "funneled", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, split, image_set, "pairs", transform, target_transform, download, loader=loader) + + self.pair_names, self.data, self.targets = self._get_pairs(self.images_dir) + + def _get_pairs(self, images_dir: str) -> tuple[list[tuple[str, str]], list[tuple[str, str]], list[int]]: + pair_names, data, targets = [], [], [] + with open(os.path.join(self.root, self.labels_file)) as f: + lines = f.readlines() + if self.split == "10fold": + n_folds, n_pairs = lines[0].split("\t") + n_folds, n_pairs = int(n_folds), int(n_pairs) + else: + n_folds, n_pairs = 1, int(lines[0]) + s = 1 + + for fold in range(n_folds): + matched_pairs = [line.strip().split("\t") for line in lines[s : s + n_pairs]] + unmatched_pairs = [line.strip().split("\t") for line in lines[s + n_pairs : s + (2 * n_pairs)]] + s += 2 * n_pairs + for pair in matched_pairs: + img1, img2, same = self._get_path(pair[0], pair[1]), self._get_path(pair[0], pair[2]), 1 + pair_names.append((pair[0], pair[0])) + data.append((img1, img2)) + targets.append(same) + for pair in unmatched_pairs: + img1, img2, same = self._get_path(pair[0], pair[1]), self._get_path(pair[2], pair[3]), 0 + pair_names.append((pair[0], pair[2])) + data.append((img1, img2)) + targets.append(same) + + return pair_names, data, targets + + def __getitem__(self, index: int) -> tuple[Any, Any, int]: + """ + Args: + index (int): Index + + Returns: + tuple: (image1, image2, target) where target is `0` for different indentities and `1` for same identities. + """ + img1, img2 = self.data[index] + img1, img2 = self._loader(img1), self._loader(img2) + target = self.targets[index] + + if self.transform is not None: + img1, img2 = self.transform(img1), self.transform(img2) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img1, img2, target diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/lsun.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/lsun.py new file mode 100644 index 0000000000000000000000000000000000000000..6f6c7a5eb63c21e042b4be0e059fa5df581acbaf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/lsun.py @@ -0,0 +1,168 @@ +import io +import os.path +import pickle +import string +from collections.abc import Iterable +from pathlib import Path +from typing import Any, Callable, cast, Optional, Union + +from PIL import Image + +from .utils import iterable_to_str, verify_str_arg +from .vision import VisionDataset + + +class LSUNClass(VisionDataset): + def __init__( + self, root: str, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None + ) -> None: + import lmdb + + super().__init__(root, transform=transform, target_transform=target_transform) + + self.env = lmdb.open(root, max_readers=1, readonly=True, lock=False, readahead=False, meminit=False) + with self.env.begin(write=False) as txn: + self.length = txn.stat()["entries"] + cache_file = "_cache_" + "".join(c for c in root if c in string.ascii_letters) + if os.path.isfile(cache_file): + self.keys = pickle.load(open(cache_file, "rb")) + else: + with self.env.begin(write=False) as txn: + self.keys = [key for key in txn.cursor().iternext(keys=True, values=False)] + pickle.dump(self.keys, open(cache_file, "wb")) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + img, target = None, None + env = self.env + with env.begin(write=False) as txn: + imgbuf = txn.get(self.keys[index]) + + buf = io.BytesIO() + buf.write(imgbuf) + buf.seek(0) + img = Image.open(buf).convert("RGB") + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return self.length + + +class LSUN(VisionDataset): + """`LSUN `_ dataset. + + You will need to install the ``lmdb`` package to use this dataset: run + ``pip install lmdb`` + + Args: + root (str or ``pathlib.Path``): Root directory for the database files. + classes (string or list): One of {'train', 'val', 'test'} or a list of + categories to load. e,g. ['bedroom_train', 'church_outdoor_train']. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + """ + + def __init__( + self, + root: Union[str, Path], + classes: Union[str, list[str]] = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.classes = self._verify_classes(classes) + + # for each class, create an LSUNClassDataset + self.dbs = [] + for c in self.classes: + self.dbs.append(LSUNClass(root=os.path.join(root, f"{c}_lmdb"), transform=transform)) + + self.indices = [] + count = 0 + for db in self.dbs: + count += len(db) + self.indices.append(count) + + self.length = count + + def _verify_classes(self, classes: Union[str, list[str]]) -> list[str]: + categories = [ + "bedroom", + "bridge", + "church_outdoor", + "classroom", + "conference_room", + "dining_room", + "kitchen", + "living_room", + "restaurant", + "tower", + ] + dset_opts = ["train", "val", "test"] + + try: + classes = cast(str, classes) + verify_str_arg(classes, "classes", dset_opts) + if classes == "test": + classes = [classes] + else: + classes = [c + "_" + classes for c in categories] + except ValueError: + if not isinstance(classes, Iterable): + msg = "Expected type str or Iterable for argument classes, but got type {}." + raise ValueError(msg.format(type(classes))) + + classes = list(classes) + msg_fmtstr_type = "Expected type str for elements in argument classes, but got type {}." + for c in classes: + verify_str_arg(c, custom_msg=msg_fmtstr_type.format(type(c))) + c_short = c.split("_") + category, dset_opt = "_".join(c_short[:-1]), c_short[-1] + + msg_fmtstr = "Unknown value '{}' for {}. Valid values are {{{}}}." + msg = msg_fmtstr.format(category, "LSUN class", iterable_to_str(categories)) + verify_str_arg(category, valid_values=categories, custom_msg=msg) + + msg = msg_fmtstr.format(dset_opt, "postfix", iterable_to_str(dset_opts)) + verify_str_arg(dset_opt, valid_values=dset_opts, custom_msg=msg) + + return classes + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: Tuple (image, target) where target is the index of the target category. + """ + target = 0 + sub = 0 + for ind in self.indices: + if index < ind: + break + target += 1 + sub = ind + + db = self.dbs[target] + index = index - sub + + if self.target_transform is not None: + target = self.target_transform(target) + + img, _ = db[index] + return img, target + + def __len__(self) -> int: + return self.length + + def extra_repr(self) -> str: + return "Classes: {classes}".format(**self.__dict__) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/mnist.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/mnist.py new file mode 100644 index 0000000000000000000000000000000000000000..cfa4711834cbb1f9975b71d61bce0a46fed05e11 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/mnist.py @@ -0,0 +1,560 @@ +import codecs +import os +import os.path +import shutil +import string +import sys +import warnings +from pathlib import Path +from typing import Any, Callable, Optional, Union +from urllib.error import URLError + +import numpy as np +import torch + +from ..utils import _Image_fromarray +from .utils import _flip_byte_order, check_integrity, download_and_extract_archive, extract_archive, verify_str_arg +from .vision import VisionDataset + + +class MNIST(VisionDataset): + """`MNIST `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where ``MNIST/raw/train-images-idx3-ubyte`` + and ``MNIST/raw/t10k-images-idx3-ubyte`` exist. + train (bool, optional): If True, creates dataset from ``train-images-idx3-ubyte``, + otherwise from ``t10k-images-idx3-ubyte``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + """ + + mirrors = [ + "https://ossci-datasets.s3.amazonaws.com/mnist/", + "http://yann.lecun.com/exdb/mnist/", + ] + + resources = [ + ("train-images-idx3-ubyte.gz", "f68b3c2dcbeaaa9fbdd348bbdeb94873"), + ("train-labels-idx1-ubyte.gz", "d53e105ee54ea40749a09fcbcd1e9432"), + ("t10k-images-idx3-ubyte.gz", "9fb629c4189551a2d022fa330f9573f3"), + ("t10k-labels-idx1-ubyte.gz", "ec29112dd5afa0611ce80d1b7f02629c"), + ] + + training_file = "training.pt" + test_file = "test.pt" + classes = [ + "0 - zero", + "1 - one", + "2 - two", + "3 - three", + "4 - four", + "5 - five", + "6 - six", + "7 - seven", + "8 - eight", + "9 - nine", + ] + + @property + def train_labels(self): + warnings.warn("train_labels has been renamed targets") + return self.targets + + @property + def test_labels(self): + warnings.warn("test_labels has been renamed targets") + return self.targets + + @property + def train_data(self): + warnings.warn("train_data has been renamed data") + return self.data + + @property + def test_data(self): + warnings.warn("test_data has been renamed data") + return self.data + + def __init__( + self, + root: Union[str, Path], + train: bool = True, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.train = train # training set or test set + + if self._check_legacy_exist(): + self.data, self.targets = self._load_legacy_data() + return + + if download: + self.download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + self.data, self.targets = self._load_data() + + def _check_legacy_exist(self): + processed_folder_exists = os.path.exists(self.processed_folder) + if not processed_folder_exists: + return False + + return all( + check_integrity(os.path.join(self.processed_folder, file)) for file in (self.training_file, self.test_file) + ) + + def _load_legacy_data(self): + # This is for BC only. We no longer cache the data in a custom binary, but simply read from the raw data + # directly. + data_file = self.training_file if self.train else self.test_file + return torch.load(os.path.join(self.processed_folder, data_file), weights_only=True) + + def _load_data(self): + image_file = f"{'train' if self.train else 't10k'}-images-idx3-ubyte" + data = read_image_file(os.path.join(self.raw_folder, image_file)) + + label_file = f"{'train' if self.train else 't10k'}-labels-idx1-ubyte" + targets = read_label_file(os.path.join(self.raw_folder, label_file)) + + return data, targets + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + img, target = self.data[index], int(self.targets[index]) + + # doing this so that it is consistent with all other datasets + # to return a PIL Image + img = _Image_fromarray(img.numpy(), mode="L") + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.data) + + @property + def raw_folder(self) -> str: + return os.path.join(self.root, self.__class__.__name__, "raw") + + @property + def processed_folder(self) -> str: + return os.path.join(self.root, self.__class__.__name__, "processed") + + @property + def class_to_idx(self) -> dict[str, int]: + return {_class: i for i, _class in enumerate(self.classes)} + + def _check_exists(self) -> bool: + return all( + check_integrity(os.path.join(self.raw_folder, os.path.splitext(os.path.basename(url))[0])) + for url, _ in self.resources + ) + + def download(self) -> None: + """Download the MNIST data if it doesn't exist already.""" + + if self._check_exists(): + return + + os.makedirs(self.raw_folder, exist_ok=True) + + # download files + for filename, md5 in self.resources: + errors = [] + for mirror in self.mirrors: + url = f"{mirror}{filename}" + try: + download_and_extract_archive(url, download_root=self.raw_folder, filename=filename, md5=md5) + except (RuntimeError, URLError) as e: + errors.append(e) + continue + break + else: + s = f"Error downloading {filename}:\n" + for mirror, err in zip(self.mirrors, errors): + s += f"Tried {mirror}, got:\n{str(err)}\n" + raise RuntimeError(s) + + def extra_repr(self) -> str: + split = "Train" if self.train is True else "Test" + return f"Split: {split}" + + +class FashionMNIST(MNIST): + """`Fashion-MNIST `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where ``FashionMNIST/raw/train-images-idx3-ubyte`` + and ``FashionMNIST/raw/t10k-images-idx3-ubyte`` exist. + train (bool, optional): If True, creates dataset from ``train-images-idx3-ubyte``, + otherwise from ``t10k-images-idx3-ubyte``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + """ + + mirrors = ["http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/"] + + resources = [ + ("train-images-idx3-ubyte.gz", "8d4fb7e6c68d591d4c3dfef9ec88bf0d"), + ("train-labels-idx1-ubyte.gz", "25c81989df183df01b3e8a0aad5dffbe"), + ("t10k-images-idx3-ubyte.gz", "bef4ecab320f06d8554ea6380940ec79"), + ("t10k-labels-idx1-ubyte.gz", "bb300cfdad3c16e7a12a480ee83cd310"), + ] + classes = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"] + + +class KMNIST(MNIST): + """`Kuzushiji-MNIST `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where ``KMNIST/raw/train-images-idx3-ubyte`` + and ``KMNIST/raw/t10k-images-idx3-ubyte`` exist. + train (bool, optional): If True, creates dataset from ``train-images-idx3-ubyte``, + otherwise from ``t10k-images-idx3-ubyte``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + """ + + mirrors = ["http://codh.rois.ac.jp/kmnist/dataset/kmnist/"] + + resources = [ + ("train-images-idx3-ubyte.gz", "bdb82020997e1d708af4cf47b453dcf7"), + ("train-labels-idx1-ubyte.gz", "e144d726b3acfaa3e44228e80efcd344"), + ("t10k-images-idx3-ubyte.gz", "5c965bf0a639b31b8f53240b1b52f4d7"), + ("t10k-labels-idx1-ubyte.gz", "7320c461ea6c1c855c0b718fb2a4b134"), + ] + classes = ["o", "ki", "su", "tsu", "na", "ha", "ma", "ya", "re", "wo"] + + +class EMNIST(MNIST): + """`EMNIST `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where ``EMNIST/raw/train-images-idx3-ubyte`` + and ``EMNIST/raw/t10k-images-idx3-ubyte`` exist. + split (string): The dataset has 6 different splits: ``byclass``, ``bymerge``, + ``balanced``, ``letters``, ``digits`` and ``mnist``. This argument specifies + which one to use. + train (bool, optional): If True, creates dataset from ``training.pt``, + otherwise from ``test.pt``. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + """ + + url = "https://biometrics.nist.gov/cs_links/EMNIST/gzip.zip" + md5 = "58c8d27c78d21e728a6bc7b3cc06412e" + splits = ("byclass", "bymerge", "balanced", "letters", "digits", "mnist") + # Merged Classes assumes Same structure for both uppercase and lowercase version + _merged_classes = {"c", "i", "j", "k", "l", "m", "o", "p", "s", "u", "v", "w", "x", "y", "z"} + _all_classes = set(string.digits + string.ascii_letters) + classes_split_dict = { + "byclass": sorted(list(_all_classes)), + "bymerge": sorted(list(_all_classes - _merged_classes)), + "balanced": sorted(list(_all_classes - _merged_classes)), + "letters": ["N/A"] + list(string.ascii_lowercase), + "digits": list(string.digits), + "mnist": list(string.digits), + } + + def __init__(self, root: Union[str, Path], split: str, **kwargs: Any) -> None: + self.split = verify_str_arg(split, "split", self.splits) + self.training_file = self._training_file(split) + self.test_file = self._test_file(split) + super().__init__(root, **kwargs) + self.classes = self.classes_split_dict[self.split] + + @staticmethod + def _training_file(split) -> str: + return f"training_{split}.pt" + + @staticmethod + def _test_file(split) -> str: + return f"test_{split}.pt" + + @property + def _file_prefix(self) -> str: + return f"emnist-{self.split}-{'train' if self.train else 'test'}" + + @property + def images_file(self) -> str: + return os.path.join(self.raw_folder, f"{self._file_prefix}-images-idx3-ubyte") + + @property + def labels_file(self) -> str: + return os.path.join(self.raw_folder, f"{self._file_prefix}-labels-idx1-ubyte") + + def _load_data(self): + return read_image_file(self.images_file), read_label_file(self.labels_file) + + def _check_exists(self) -> bool: + return all(check_integrity(file) for file in (self.images_file, self.labels_file)) + + def download(self) -> None: + """Download the EMNIST data if it doesn't exist already.""" + + if self._check_exists(): + return + + os.makedirs(self.raw_folder, exist_ok=True) + + download_and_extract_archive(self.url, download_root=self.raw_folder, md5=self.md5) + gzip_folder = os.path.join(self.raw_folder, "gzip") + for gzip_file in os.listdir(gzip_folder): + if gzip_file.endswith(".gz"): + extract_archive(os.path.join(gzip_folder, gzip_file), self.raw_folder) + shutil.rmtree(gzip_folder) + + +class QMNIST(MNIST): + """`QMNIST `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset whose ``raw`` + subdir contains binary files of the datasets. + what (string,optional): Can be 'train', 'test', 'test10k', + 'test50k', or 'nist' for respectively the mnist compatible + training set, the 60k qmnist testing set, the 10k qmnist + examples that match the mnist testing set, the 50k + remaining qmnist testing examples, or all the nist + digits. The default is to select 'train' or 'test' + according to the compatibility argument 'train'. + compat (bool,optional): A boolean that says whether the target + for each example is class number (for compatibility with + the MNIST dataloader) or a torch vector containing the + full qmnist information. Default=True. + train (bool,optional,compatibility): When argument 'what' is + not specified, this boolean decides whether to load the + training set or the testing set. Default: True. + download (bool, optional): If True, downloads the dataset from + the internet and puts it in root directory. If dataset is + already downloaded, it is not downloaded again. + transform (callable, optional): A function/transform that + takes in a PIL image and returns a transformed + version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform + that takes in the target and transforms it. + """ + + subsets = {"train": "train", "test": "test", "test10k": "test", "test50k": "test", "nist": "nist"} + resources: dict[str, list[tuple[str, str]]] = { # type: ignore[assignment] + "train": [ + ( + "https://raw.githubusercontent.com/facebookresearch/qmnist/master/qmnist-train-images-idx3-ubyte.gz", + "ed72d4157d28c017586c42bc6afe6370", + ), + ( + "https://raw.githubusercontent.com/facebookresearch/qmnist/master/qmnist-train-labels-idx2-int.gz", + "0058f8dd561b90ffdd0f734c6a30e5e4", + ), + ], + "test": [ + ( + "https://raw.githubusercontent.com/facebookresearch/qmnist/master/qmnist-test-images-idx3-ubyte.gz", + "1394631089c404de565df7b7aeaf9412", + ), + ( + "https://raw.githubusercontent.com/facebookresearch/qmnist/master/qmnist-test-labels-idx2-int.gz", + "5b5b05890a5e13444e108efe57b788aa", + ), + ], + "nist": [ + ( + "https://raw.githubusercontent.com/facebookresearch/qmnist/master/xnist-images-idx3-ubyte.xz", + "7f124b3b8ab81486c9d8c2749c17f834", + ), + ( + "https://raw.githubusercontent.com/facebookresearch/qmnist/master/xnist-labels-idx2-int.xz", + "5ed0e788978e45d4a8bd4b7caec3d79d", + ), + ], + } + classes = [ + "0 - zero", + "1 - one", + "2 - two", + "3 - three", + "4 - four", + "5 - five", + "6 - six", + "7 - seven", + "8 - eight", + "9 - nine", + ] + + def __init__( + self, root: Union[str, Path], what: Optional[str] = None, compat: bool = True, train: bool = True, **kwargs: Any + ) -> None: + if what is None: + what = "train" if train else "test" + self.what = verify_str_arg(what, "what", tuple(self.subsets.keys())) + self.compat = compat + self.data_file = what + ".pt" + self.training_file = self.data_file + self.test_file = self.data_file + super().__init__(root, train, **kwargs) + + @property + def images_file(self) -> str: + (url, _), _ = self.resources[self.subsets[self.what]] + return os.path.join(self.raw_folder, os.path.splitext(os.path.basename(url))[0]) + + @property + def labels_file(self) -> str: + _, (url, _) = self.resources[self.subsets[self.what]] + return os.path.join(self.raw_folder, os.path.splitext(os.path.basename(url))[0]) + + def _check_exists(self) -> bool: + return all(check_integrity(file) for file in (self.images_file, self.labels_file)) + + def _load_data(self): + data = read_sn3_pascalvincent_tensor(self.images_file) + if data.dtype != torch.uint8: + raise TypeError(f"data should be of dtype torch.uint8 instead of {data.dtype}") + if data.ndimension() != 3: + raise ValueError("data should have 3 dimensions instead of {data.ndimension()}") + + targets = read_sn3_pascalvincent_tensor(self.labels_file).long() + if targets.ndimension() != 2: + raise ValueError(f"targets should have 2 dimensions instead of {targets.ndimension()}") + + if self.what == "test10k": + data = data[0:10000, :, :].clone() + targets = targets[0:10000, :].clone() + elif self.what == "test50k": + data = data[10000:, :, :].clone() + targets = targets[10000:, :].clone() + + return data, targets + + def download(self) -> None: + """Download the QMNIST data if it doesn't exist already. + Note that we only download what has been asked for (argument 'what'). + """ + if self._check_exists(): + return + + os.makedirs(self.raw_folder, exist_ok=True) + split = self.resources[self.subsets[self.what]] + + for url, md5 in split: + download_and_extract_archive(url, self.raw_folder, md5=md5) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + # redefined to handle the compat flag + img, target = self.data[index], self.targets[index] + img = _Image_fromarray(img.numpy(), mode="L") + if self.transform is not None: + img = self.transform(img) + if self.compat: + target = int(target[0]) + if self.target_transform is not None: + target = self.target_transform(target) + return img, target + + def extra_repr(self) -> str: + return f"Split: {self.what}" + + +def get_int(b: bytes) -> int: + return int(codecs.encode(b, "hex"), 16) + + +SN3_PASCALVINCENT_TYPEMAP = { + 8: torch.uint8, + 9: torch.int8, + 11: torch.int16, + 12: torch.int32, + 13: torch.float32, + 14: torch.float64, +} + + +def read_sn3_pascalvincent_tensor(path: str, strict: bool = True) -> torch.Tensor: + """Read a SN3 file in "Pascal Vincent" format (Lush file 'libidx/idx-io.lsh'). + Argument may be a filename, compressed filename, or file object. + """ + # read + with open(path, "rb") as f: + data = f.read() + + # parse + if sys.byteorder == "little" or sys.platform == "aix": + magic = get_int(data[0:4]) + nd = magic % 256 + ty = magic // 256 + else: + nd = get_int(data[0:1]) + ty = get_int(data[1:2]) + get_int(data[2:3]) * 256 + get_int(data[3:4]) * 256 * 256 + + assert 1 <= nd <= 3 + assert 8 <= ty <= 14 + torch_type = SN3_PASCALVINCENT_TYPEMAP[ty] + s = [get_int(data[4 * (i + 1) : 4 * (i + 2)]) for i in range(nd)] + + if sys.byteorder == "big" and not sys.platform == "aix": + for i in range(len(s)): + s[i] = int.from_bytes(s[i].to_bytes(4, byteorder="little"), byteorder="big", signed=False) + + parsed = torch.frombuffer(bytearray(data), dtype=torch_type, offset=(4 * (nd + 1))) + + # The MNIST format uses the big endian byte order, while `torch.frombuffer` uses whatever the system uses. In case + # that is little endian and the dtype has more than one byte, we need to flip them. + if sys.byteorder == "little" and parsed.element_size() > 1: + parsed = _flip_byte_order(parsed) + + assert parsed.shape[0] == np.prod(s) or not strict + return parsed.view(*s) + + +def read_label_file(path: str) -> torch.Tensor: + x = read_sn3_pascalvincent_tensor(path, strict=False) + if x.dtype != torch.uint8: + raise TypeError(f"x should be of dtype torch.uint8 instead of {x.dtype}") + if x.ndimension() != 1: + raise ValueError(f"x should have 1 dimension instead of {x.ndimension()}") + return x.long() + + +def read_image_file(path: str) -> torch.Tensor: + x = read_sn3_pascalvincent_tensor(path, strict=False) + if x.dtype != torch.uint8: + raise TypeError(f"x should be of dtype torch.uint8 instead of {x.dtype}") + if x.ndimension() != 3: + raise ValueError(f"x should have 3 dimension instead of {x.ndimension()}") + return x diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/moving_mnist.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/moving_mnist.py new file mode 100644 index 0000000000000000000000000000000000000000..4466d82291bfa908aff424bb66ae704289b97274 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/moving_mnist.py @@ -0,0 +1,94 @@ +import os.path +from pathlib import Path +from typing import Callable, Optional, Union + +import numpy as np +import torch +from torchvision.datasets.utils import download_url, verify_str_arg +from torchvision.datasets.vision import VisionDataset + + +class MovingMNIST(VisionDataset): + """`MovingMNIST `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where ``MovingMNIST/mnist_test_seq.npy`` exists. + split (string, optional): The dataset split, supports ``None`` (default), ``"train"`` and ``"test"``. + If ``split=None``, the full data is returned. + split_ratio (int, optional): The split ratio of number of frames. If ``split="train"``, the first split + frames ``data[:, :split_ratio]`` is returned. If ``split="test"``, the last split frames ``data[:, split_ratio:]`` + is returned. If ``split=None``, this parameter is ignored and the all frames data is returned. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + transform (callable, optional): A function/transform that takes in a torch Tensor + and returns a transformed version. E.g, ``transforms.RandomCrop`` + """ + + _URL = "http://www.cs.toronto.edu/~nitish/unsupervised_video/mnist_test_seq.npy" + + def __init__( + self, + root: Union[str, Path], + split: Optional[str] = None, + split_ratio: int = 10, + download: bool = False, + transform: Optional[Callable] = None, + ) -> None: + super().__init__(root, transform=transform) + + self._base_folder = os.path.join(self.root, self.__class__.__name__) + self._filename = self._URL.split("/")[-1] + + if split is not None: + verify_str_arg(split, "split", ("train", "test")) + self.split = split + + if not isinstance(split_ratio, int): + raise TypeError(f"`split_ratio` should be an integer, but got {type(split_ratio)}") + elif not (1 <= split_ratio <= 19): + raise ValueError(f"`split_ratio` should be `1 <= split_ratio <= 19`, but got {split_ratio} instead.") + self.split_ratio = split_ratio + + if download: + self.download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it.") + + data = torch.from_numpy(np.load(os.path.join(self._base_folder, self._filename))) + if self.split == "train": + data = data[: self.split_ratio] + elif self.split == "test": + data = data[self.split_ratio :] + self.data = data.transpose(0, 1).unsqueeze(2).contiguous() + + def __getitem__(self, idx: int) -> torch.Tensor: + """ + Args: + idx (int): Index + Returns: + torch.Tensor: Video frames (torch Tensor[T, C, H, W]). The `T` is the number of frames. + """ + data = self.data[idx] + if self.transform is not None: + data = self.transform(data) + + return data + + def __len__(self) -> int: + return len(self.data) + + def _check_exists(self) -> bool: + return os.path.exists(os.path.join(self._base_folder, self._filename)) + + def download(self) -> None: + if self._check_exists(): + return + + download_url( + url=self._URL, + root=self._base_folder, + filename=self._filename, + md5="be083ec986bfe91a449d63653c411eb2", + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/omniglot.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/omniglot.py new file mode 100644 index 0000000000000000000000000000000000000000..22fd59aa9c2f107864eda6a79f1bea7ac643710c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/omniglot.py @@ -0,0 +1,107 @@ +from os.path import join +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .utils import check_integrity, download_and_extract_archive, list_dir, list_files +from .vision import VisionDataset + + +class Omniglot(VisionDataset): + """`Omniglot `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``omniglot-py`` exists. + background (bool, optional): If True, creates dataset from the "background" set, otherwise + creates from the "evaluation" set. This terminology is defined by the authors. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset zip files from the internet and + puts it in root directory. If the zip files are already downloaded, they are not + downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + folder = "omniglot-py" + download_url_prefix = "https://raw.githubusercontent.com/brendenlake/omniglot/master/python" + zips_md5 = { + "images_background": "68d2efa1b9178cc56df9314c21c6e718", + "images_evaluation": "6b91aef0f799c5bb55b94e3f2daec811", + } + + def __init__( + self, + root: Union[str, Path], + background: bool = True, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Optional[Callable[[Union[str, Path]], Any]] = None, + ) -> None: + super().__init__(join(root, self.folder), transform=transform, target_transform=target_transform) + self.background = background + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + self.target_folder = join(self.root, self._get_target_folder()) + self._alphabets = list_dir(self.target_folder) + self._characters: list[str] = sum( + ([join(a, c) for c in list_dir(join(self.target_folder, a))] for a in self._alphabets), [] + ) + self._character_images = [ + [(image, idx) for image in list_files(join(self.target_folder, character), ".png")] + for idx, character in enumerate(self._characters) + ] + self._flat_character_images: list[tuple[str, int]] = sum(self._character_images, []) + self.loader = loader + + def __len__(self) -> int: + return len(self._flat_character_images) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target character class. + """ + image_name, character_class = self._flat_character_images[index] + image_path = join(self.target_folder, self._characters[character_class], image_name) + image = Image.open(image_path, mode="r").convert("L") if self.loader is None else self.loader(image_path) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + character_class = self.target_transform(character_class) + + return image, character_class + + def _check_integrity(self) -> bool: + zip_filename = self._get_target_folder() + if not check_integrity(join(self.root, zip_filename + ".zip"), self.zips_md5[zip_filename]): + return False + return True + + def download(self) -> None: + if self._check_integrity(): + return + + filename = self._get_target_folder() + zip_filename = filename + ".zip" + url = self.download_url_prefix + "/" + zip_filename + download_and_extract_archive(url, self.root, filename=zip_filename, md5=self.zips_md5[filename]) + + def _get_target_folder(self) -> str: + return "images_background" if self.background else "images_evaluation" diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/oxford_iiit_pet.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/oxford_iiit_pet.py new file mode 100644 index 0000000000000000000000000000000000000000..e598920f8fe392f45a212dc7251ec84d5bb399b4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/oxford_iiit_pet.py @@ -0,0 +1,135 @@ +import os +import os.path +import pathlib +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class OxfordIIITPet(VisionDataset): + """`Oxford-IIIT Pet Dataset `_. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"trainval"`` (default) or ``"test"``. + target_types (string, sequence of strings, optional): Types of target to use. Can be ``category`` (default) or + ``segmentation``. Can also be a list to output a tuple with all specified target types. The types represent: + + - ``category`` (int): Label for one of the 37 pet categories. + - ``binary-category`` (int): Binary label for cat or dog. + - ``segmentation`` (PIL image): Segmentation trimap of the image. + + If empty, ``None`` will be returned as target. + + transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed + version. E.g, ``transforms.RandomCrop``. + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + transforms (callable, optional): A function/transform that takes input sample + and its target as entry and returns a transformed version. + download (bool, optional): If True, downloads the dataset from the internet and puts it into + ``root/oxford-iiit-pet``. If dataset is already downloaded, it is not downloaded again. + """ + + _RESOURCES = ( + ("https://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz", "5c4f3ee8e5d25df40f4fd59a7f44e54c"), + ("https://www.robots.ox.ac.uk/~vgg/data/pets/data/annotations.tar.gz", "95a8c909bbe2e81eed6a22bccdf3f68f"), + ) + _VALID_TARGET_TYPES = ("category", "binary-category", "segmentation") + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "trainval", + target_types: Union[Sequence[str], str] = "category", + transforms: Optional[Callable] = None, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ): + self._split = verify_str_arg(split, "split", ("trainval", "test")) + if isinstance(target_types, str): + target_types = [target_types] + self._target_types = [ + verify_str_arg(target_type, "target_types", self._VALID_TARGET_TYPES) for target_type in target_types + ] + + super().__init__(root, transforms=transforms, transform=transform, target_transform=target_transform) + self._base_folder = pathlib.Path(self.root) / "oxford-iiit-pet" + self._images_folder = self._base_folder / "images" + self._anns_folder = self._base_folder / "annotations" + self._segs_folder = self._anns_folder / "trimaps" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + image_ids = [] + self._labels = [] + self._bin_labels = [] + with open(self._anns_folder / f"{self._split}.txt") as file: + for line in file: + image_id, label, bin_label, _ = line.strip().split() + image_ids.append(image_id) + self._labels.append(int(label) - 1) + self._bin_labels.append(int(bin_label) - 1) + + self.bin_classes = ["Cat", "Dog"] + self.classes = [ + " ".join(part.title() for part in raw_cls.split("_")) + for raw_cls, _ in sorted( + {(image_id.rsplit("_", 1)[0], label) for image_id, label in zip(image_ids, self._labels)}, + key=lambda image_id_and_label: image_id_and_label[1], + ) + ] + self.bin_class_to_idx = dict(zip(self.bin_classes, range(len(self.bin_classes)))) + self.class_to_idx = dict(zip(self.classes, range(len(self.classes)))) + + self._images = [self._images_folder / f"{image_id}.jpg" for image_id in image_ids] + self._segs = [self._segs_folder / f"{image_id}.png" for image_id in image_ids] + + def __len__(self) -> int: + return len(self._images) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image = Image.open(self._images[idx]).convert("RGB") + + target: Any = [] + for target_type in self._target_types: + if target_type == "category": + target.append(self._labels[idx]) + elif target_type == "binary-category": + target.append(self._bin_labels[idx]) + else: # target_type == "segmentation" + target.append(Image.open(self._segs[idx])) + + if not target: + target = None + elif len(target) == 1: + target = target[0] + else: + target = tuple(target) + + if self.transforms: + image, target = self.transforms(image, target) + + return image, target + + def _check_exists(self) -> bool: + for folder in (self._images_folder, self._anns_folder): + if not (os.path.exists(folder) and os.path.isdir(folder)): + return False + else: + return True + + def _download(self) -> None: + if self._check_exists(): + return + + for url, md5 in self._RESOURCES: + download_and_extract_archive(url, download_root=str(self._base_folder), md5=md5) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/pcam.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/pcam.py new file mode 100644 index 0000000000000000000000000000000000000000..00d10f6a01035bf4cafa57231176c826c463c6f3 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/pcam.py @@ -0,0 +1,134 @@ +import pathlib +from typing import Any, Callable, Optional, Union + +from PIL import Image + +from .utils import _decompress, download_file_from_google_drive, verify_str_arg +from .vision import VisionDataset + + +class PCAM(VisionDataset): + """`PCAM Dataset `_. + + The PatchCamelyon dataset is a binary classification dataset with 327,680 + color images (96px x 96px), extracted from histopathologic scans of lymph node + sections. Each image is annotated with a binary label indicating presence of + metastatic tissue. + + This dataset requires the ``h5py`` package which you can install with ``pip install h5py``. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), ``"test"`` or ``"val"``. + transform (callable, optional): A function/transform that takes in a PIL image and returns a transformed + version. E.g, ``transforms.RandomCrop``. + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and puts it into ``root/pcam``. If + dataset is already downloaded, it is not downloaded again. + + .. warning:: + + To download the dataset `gdown `_ is required. + """ + + _FILES = { + "train": { + "images": ( + "camelyonpatch_level_2_split_train_x.h5", # Data file name + "1Ka0XfEMiwgCYPdTI-vv6eUElOBnKFKQ2", # Google Drive ID + "1571f514728f59376b705fc836ff4b63", # md5 hash + ), + "targets": ( + "camelyonpatch_level_2_split_train_y.h5", + "1269yhu3pZDP8UYFQs-NYs3FPwuK-nGSG", + "35c2d7259d906cfc8143347bb8e05be7", + ), + }, + "test": { + "images": ( + "camelyonpatch_level_2_split_test_x.h5", + "1qV65ZqZvWzuIVthK8eVDhIwrbnsJdbg_", + "d8c2d60d490dbd479f8199bdfa0cf6ec", + ), + "targets": ( + "camelyonpatch_level_2_split_test_y.h5", + "17BHrSrwWKjYsOgTMmoqrIjDy6Fa2o_gP", + "60a7035772fbdb7f34eb86d4420cf66a", + ), + }, + "val": { + "images": ( + "camelyonpatch_level_2_split_valid_x.h5", + "1hgshYGWK8V-eGRy8LToWJJgDU_rXWVJ3", + "d5b63470df7cfa627aeec8b9dc0c066e", + ), + "targets": ( + "camelyonpatch_level_2_split_valid_y.h5", + "1bH8ZRbhSVAhScTS0p9-ZzGnX91cHT3uO", + "2b85f58b927af9964a4c15b8f7e8f179", + ), + }, + } + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ): + try: + import h5py + + self.h5py = h5py + except ImportError: + raise RuntimeError( + "h5py is not found. This dataset needs to have h5py installed: please run pip install h5py" + ) + + self._split = verify_str_arg(split, "split", ("train", "test", "val")) + + super().__init__(root, transform=transform, target_transform=target_transform) + self._base_folder = pathlib.Path(self.root) / "pcam" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + def __len__(self) -> int: + images_file = self._FILES[self._split]["images"][0] + with self.h5py.File(self._base_folder / images_file) as images_data: + return images_data["x"].shape[0] + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + images_file = self._FILES[self._split]["images"][0] + with self.h5py.File(self._base_folder / images_file) as images_data: + image = Image.fromarray(images_data["x"][idx]).convert("RGB") + + targets_file = self._FILES[self._split]["targets"][0] + with self.h5py.File(self._base_folder / targets_file) as targets_data: + target = int(targets_data["y"][idx, 0, 0, 0]) # shape is [num_images, 1, 1, 1] + + if self.transform: + image = self.transform(image) + if self.target_transform: + target = self.target_transform(target) + + return image, target + + def _check_exists(self) -> bool: + images_file = self._FILES[self._split]["images"][0] + targets_file = self._FILES[self._split]["targets"][0] + return all(self._base_folder.joinpath(h5_file).exists() for h5_file in (images_file, targets_file)) + + def _download(self) -> None: + if self._check_exists(): + return + + for file_name, file_id, md5 in self._FILES[self._split].values(): + archive_name = file_name + ".gz" + download_file_from_google_drive(file_id, str(self._base_folder), filename=archive_name, md5=md5) + _decompress(str(self._base_folder / archive_name)) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/phototour.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/phototour.py new file mode 100644 index 0000000000000000000000000000000000000000..5d625b51ecef08164b82328ec0d18338eecda31c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/phototour.py @@ -0,0 +1,230 @@ +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import numpy as np +import torch +from PIL import Image + +from .utils import download_url +from .vision import VisionDataset + + +class PhotoTour(VisionDataset): + """`Multi-view Stereo Correspondence `_ Dataset. + + .. note:: + + We only provide the newer version of the dataset, since the authors state that it + + is more suitable for training descriptors based on difference of Gaussian, or Harris corners, as the + patches are centred on real interest point detections, rather than being projections of 3D points as is the + case in the old dataset. + + The original dataset is available under http://phototour.cs.washington.edu/patches/default.htm. + + + Args: + root (str or ``pathlib.Path``): Root directory where images are. + name (string): Name of the dataset to load. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + """ + + urls = { + "notredame_harris": [ + "http://matthewalunbrown.com/patchdata/notredame_harris.zip", + "notredame_harris.zip", + "69f8c90f78e171349abdf0307afefe4d", + ], + "yosemite_harris": [ + "http://matthewalunbrown.com/patchdata/yosemite_harris.zip", + "yosemite_harris.zip", + "a73253d1c6fbd3ba2613c45065c00d46", + ], + "liberty_harris": [ + "http://matthewalunbrown.com/patchdata/liberty_harris.zip", + "liberty_harris.zip", + "c731fcfb3abb4091110d0ae8c7ba182c", + ], + "notredame": [ + "http://icvl.ee.ic.ac.uk/vbalnt/notredame.zip", + "notredame.zip", + "509eda8535847b8c0a90bbb210c83484", + ], + "yosemite": ["http://icvl.ee.ic.ac.uk/vbalnt/yosemite.zip", "yosemite.zip", "533b2e8eb7ede31be40abc317b2fd4f0"], + "liberty": ["http://icvl.ee.ic.ac.uk/vbalnt/liberty.zip", "liberty.zip", "fdd9152f138ea5ef2091746689176414"], + } + means = { + "notredame": 0.4854, + "yosemite": 0.4844, + "liberty": 0.4437, + "notredame_harris": 0.4854, + "yosemite_harris": 0.4844, + "liberty_harris": 0.4437, + } + stds = { + "notredame": 0.1864, + "yosemite": 0.1818, + "liberty": 0.2019, + "notredame_harris": 0.1864, + "yosemite_harris": 0.1818, + "liberty_harris": 0.2019, + } + lens = { + "notredame": 468159, + "yosemite": 633587, + "liberty": 450092, + "liberty_harris": 379587, + "yosemite_harris": 450912, + "notredame_harris": 325295, + } + image_ext = "bmp" + info_file = "info.txt" + matches_files = "m50_100000_100000_0.txt" + + def __init__( + self, + root: Union[str, Path], + name: str, + train: bool = True, + transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transform=transform) + self.name = name + self.data_dir = os.path.join(self.root, name) + self.data_down = os.path.join(self.root, f"{name}.zip") + self.data_file = os.path.join(self.root, f"{name}.pt") + + self.train = train + self.mean = self.means[name] + self.std = self.stds[name] + + if download: + self.download() + + if not self._check_datafile_exists(): + self.cache() + + # load the serialized data + self.data, self.labels, self.matches = torch.load(self.data_file, weights_only=True) + + def __getitem__(self, index: int) -> Union[torch.Tensor, tuple[Any, Any, torch.Tensor]]: + """ + Args: + index (int): Index + + Returns: + tuple: (data1, data2, matches) + """ + if self.train: + data = self.data[index] + if self.transform is not None: + data = self.transform(data) + return data + m = self.matches[index] + data1, data2 = self.data[m[0]], self.data[m[1]] + if self.transform is not None: + data1 = self.transform(data1) + data2 = self.transform(data2) + return data1, data2, m[2] + + def __len__(self) -> int: + return len(self.data if self.train else self.matches) + + def _check_datafile_exists(self) -> bool: + return os.path.exists(self.data_file) + + def _check_downloaded(self) -> bool: + return os.path.exists(self.data_dir) + + def download(self) -> None: + if self._check_datafile_exists(): + return + + if not self._check_downloaded(): + # download files + url = self.urls[self.name][0] + filename = self.urls[self.name][1] + md5 = self.urls[self.name][2] + fpath = os.path.join(self.root, filename) + + download_url(url, self.root, filename, md5) + + import zipfile + + with zipfile.ZipFile(fpath, "r") as z: + z.extractall(self.data_dir) + + os.unlink(fpath) + + def cache(self) -> None: + # process and save as torch files + + dataset = ( + read_image_file(self.data_dir, self.image_ext, self.lens[self.name]), + read_info_file(self.data_dir, self.info_file), + read_matches_files(self.data_dir, self.matches_files), + ) + + with open(self.data_file, "wb") as f: + torch.save(dataset, f) + + def extra_repr(self) -> str: + split = "Train" if self.train is True else "Test" + return f"Split: {split}" + + +def read_image_file(data_dir: str, image_ext: str, n: int) -> torch.Tensor: + """Return a Tensor containing the patches""" + + def PIL2array(_img: Image.Image) -> np.ndarray: + """Convert PIL image type to numpy 2D array""" + return np.array(_img.getdata(), dtype=np.uint8).reshape(64, 64) + + def find_files(_data_dir: str, _image_ext: str) -> list[str]: + """Return a list with the file names of the images containing the patches""" + files = [] + # find those files with the specified extension + for file_dir in os.listdir(_data_dir): + if file_dir.endswith(_image_ext): + files.append(os.path.join(_data_dir, file_dir)) + return sorted(files) # sort files in ascend order to keep relations + + patches = [] + list_files = find_files(data_dir, image_ext) + + for fpath in list_files: + img = Image.open(fpath) + for y in range(0, img.height, 64): + for x in range(0, img.width, 64): + patch = img.crop((x, y, x + 64, y + 64)) + patches.append(PIL2array(patch)) + return torch.ByteTensor(np.array(patches[:n])) + + +def read_info_file(data_dir: str, info_file: str) -> torch.Tensor: + """Return a Tensor containing the list of labels + Read the file and keep only the ID of the 3D point. + """ + with open(os.path.join(data_dir, info_file)) as f: + labels = [int(line.split()[0]) for line in f] + return torch.LongTensor(labels) + + +def read_matches_files(data_dir: str, matches_file: str) -> torch.Tensor: + """Return a Tensor containing the ground truth matches + Read the file and keep only 3D point ID. + Matches are represented with a 1, non matches with a 0. + """ + matches = [] + with open(os.path.join(data_dir, matches_file)) as f: + for line in f: + line_split = line.split() + matches.append([int(line_split[0]), int(line_split[3]), int(line_split[1] == line_split[4])]) + return torch.LongTensor(matches) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/places365.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/places365.py new file mode 100644 index 0000000000000000000000000000000000000000..51b845de7234635a17a6ef87a9649898c9cdc0b2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/places365.py @@ -0,0 +1,176 @@ +import os +from os import path +from pathlib import Path +from typing import Any, Callable, cast, Optional, Union +from urllib.parse import urljoin + +from .folder import default_loader +from .utils import check_integrity, download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class Places365(VisionDataset): + r"""`Places365 `_ classification dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of the Places365 dataset. + split (string, optional): The dataset split. Can be one of ``train-standard`` (default), ``train-challenge``, + ``val``, ``test``. + small (bool, optional): If ``True``, uses the small images, i.e. resized to 256 x 256 pixels, instead of the + high resolution ones. + download (bool, optional): If ``True``, downloads the dataset components and places them in ``root``. Already + downloaded archives are not downloaded again. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + loader (callable, optional): A function to load an image given its path. + + Attributes: + classes (list): List of the class names. + class_to_idx (dict): Dict with items (class_name, class_index). + imgs (list): List of (image path, class_index) tuples + targets (list): The class_index value for each image in the dataset + + Raises: + RuntimeError: If ``download is False`` and the meta files, i.e. the devkit, are not present or corrupted. + RuntimeError: If ``download is True`` and the image archive is already extracted. + """ + + _SPLITS = ("train-standard", "train-challenge", "val", "test") + _BASE_URL = "http://data.csail.mit.edu/places/places365/" + # {variant: (archive, md5)} + _DEVKIT_META = { + "standard": ("filelist_places365-standard.tar", "35a0585fee1fa656440f3ab298f8479c"), + "challenge": ("filelist_places365-challenge.tar", "70a8307e459c3de41690a7c76c931734"), + } + # (file, md5) + _CATEGORIES_META = ("categories_places365.txt", "06c963b85866bd0649f97cb43dd16673") + # {split: (file, md5)} + _FILE_LIST_META = { + "train-standard": ("places365_train_standard.txt", "30f37515461640559006b8329efbed1a"), + "train-challenge": ("places365_train_challenge.txt", "b2931dc997b8c33c27e7329c073a6b57"), + "val": ("places365_val.txt", "e9f2fd57bfd9d07630173f4e8708e4b1"), + "test": ("places365_test.txt", "2fce8233fe493576d724142e45d93653"), + } + # {(split, small): (file, md5)} + _IMAGES_META = { + ("train-standard", False): ("train_large_places365standard.tar", "67e186b496a84c929568076ed01a8aa1"), + ("train-challenge", False): ("train_large_places365challenge.tar", "605f18e68e510c82b958664ea134545f"), + ("val", False): ("val_large.tar", "9b71c4993ad89d2d8bcbdc4aef38042f"), + ("test", False): ("test_large.tar", "41a4b6b724b1d2cd862fb3871ed59913"), + ("train-standard", True): ("train_256_places365standard.tar", "53ca1c756c3d1e7809517cc47c5561c5"), + ("train-challenge", True): ("train_256_places365challenge.tar", "741915038a5e3471ec7332404dfb64ef"), + ("val", True): ("val_256.tar", "e27b17d8d44f4af9a78502beb927f808"), + ("test", True): ("test_256.tar", "f532f6ad7b582262a2ec8009075e186b"), + } + + def __init__( + self, + root: Union[str, Path], + split: str = "train-standard", + small: bool = False, + download: bool = False, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + + self.split = self._verify_split(split) + self.small = small + self.loader = loader + + self.classes, self.class_to_idx = self.load_categories(download) + self.imgs, self.targets = self.load_file_list(download) + + if download: + self.download_images() + + def __getitem__(self, index: int) -> tuple[Any, Any]: + file, target = self.imgs[index] + image = self.loader(file) + + if self.transforms is not None: + image, target = self.transforms(image, target) + + return image, target + + def __len__(self) -> int: + return len(self.imgs) + + @property + def variant(self) -> str: + return "challenge" if "challenge" in self.split else "standard" + + @property + def images_dir(self) -> str: + size = "256" if self.small else "large" + if self.split.startswith("train"): + dir = f"data_{size}_{self.variant}" + else: + dir = f"{self.split}_{size}" + return path.join(self.root, dir) + + def load_categories(self, download: bool = True) -> tuple[list[str], dict[str, int]]: + def process(line: str) -> tuple[str, int]: + cls, idx = line.split() + return cls, int(idx) + + file, md5 = self._CATEGORIES_META + file = path.join(self.root, file) + if not self._check_integrity(file, md5, download): + self.download_devkit() + + with open(file) as fh: + class_to_idx = dict(process(line) for line in fh) + + return sorted(class_to_idx.keys()), class_to_idx + + def load_file_list( + self, download: bool = True + ) -> tuple[list[tuple[str, Union[int, None]]], list[Union[int, None]]]: + def process(line: str, sep="/") -> tuple[str, Union[int, None]]: + image, idx = (line.split() + [None])[:2] + image = cast(str, image) + idx = int(idx) if idx is not None else None + return path.join(self.images_dir, image.lstrip(sep).replace(sep, os.sep)), idx + + file, md5 = self._FILE_LIST_META[self.split] + file = path.join(self.root, file) + if not self._check_integrity(file, md5, download): + self.download_devkit() + + with open(file) as fh: + images = [process(line) for line in fh] + + _, targets = zip(*images) + return images, list(targets) + + def download_devkit(self) -> None: + file, md5 = self._DEVKIT_META[self.variant] + download_and_extract_archive(urljoin(self._BASE_URL, file), self.root, md5=md5) + + def download_images(self) -> None: + if path.exists(self.images_dir): + return + + file, md5 = self._IMAGES_META[(self.split, self.small)] + download_and_extract_archive(urljoin(self._BASE_URL, file), self.root, md5=md5) + + if self.split.startswith("train"): + os.rename(self.images_dir.rsplit("_", 1)[0], self.images_dir) + + def extra_repr(self) -> str: + return "\n".join(("Split: {split}", "Small: {small}")).format(**self.__dict__) + + def _verify_split(self, split: str) -> str: + return verify_str_arg(split, "split", self._SPLITS) + + def _check_integrity(self, file: str, md5: str, download: bool) -> bool: + integrity = check_integrity(file, md5=md5) + if not integrity and not download: + raise RuntimeError( + f"The file {file} does not exist or is corrupted. You can set download=True to download it." + ) + return integrity diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/rendered_sst2.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/rendered_sst2.py new file mode 100644 index 0000000000000000000000000000000000000000..62ad3bc6d0018a3c297607d6ad4e221ed0b7595a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/rendered_sst2.py @@ -0,0 +1,89 @@ +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader, make_dataset +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class RenderedSST2(VisionDataset): + """`The Rendered SST2 Dataset `_. + + Rendered SST2 is an image classification dataset used to evaluate the models capability on optical + character recognition. This dataset was generated by rendering sentences in the Standford Sentiment + Treebank v2 dataset. + + This dataset contains two classes (positive and negative) and is divided in three splits: a train + split containing 6920 images (3610 positive and 3310 negative), a validation split containing 872 images + (444 positive and 428 negative), and a test split containing 1821 images (909 positive and 912 negative). + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + split (string, optional): The dataset split, supports ``"train"`` (default), `"val"` and ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. Default is False. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _URL = "https://openaipublic.azureedge.net/clip/data/rendered-sst2.tgz" + _MD5 = "2384d08e9dcfa4bd55b324e610496ee5" + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self._split = verify_str_arg(split, "split", ("train", "val", "test")) + self._split_to_folder = {"train": "train", "val": "valid", "test": "test"} + self._base_folder = Path(self.root) / "rendered-sst2" + self.classes = ["negative", "positive"] + self.class_to_idx = {"negative": 0, "positive": 1} + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + self._samples = make_dataset(str(self._base_folder / self._split_to_folder[self._split]), extensions=("png",)) + self.loader = loader + + def __len__(self) -> int: + return len(self._samples) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_file, label = self._samples[idx] + image = self.loader(image_file) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def extra_repr(self) -> str: + return f"split={self._split}" + + def _check_exists(self) -> bool: + for class_label in set(self.classes): + if not (self._base_folder / self._split_to_folder[self._split] / class_label).is_dir(): + return False + return True + + def _download(self) -> None: + if self._check_exists(): + return + download_and_extract_archive(self._URL, download_root=self.root, md5=self._MD5) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/samplers/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/samplers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..58b2d2abd936d885221174d194a633a8e413935f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/samplers/__init__.py @@ -0,0 +1,3 @@ +from .clip_sampler import DistributedSampler, RandomClipSampler, UniformClipSampler + +__all__ = ("DistributedSampler", "UniformClipSampler", "RandomClipSampler") diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/samplers/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/samplers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f807a23a9323f3837b8aac29ed5ea7d4e0ce5ac0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/samplers/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/samplers/__pycache__/clip_sampler.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/datasets/samplers/__pycache__/clip_sampler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a368af95fa897724fc3f106ae76464f135c7b4f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/datasets/samplers/__pycache__/clip_sampler.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/samplers/clip_sampler.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/samplers/clip_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..570bc85eee906686a63f114eff6db08480737a8a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/samplers/clip_sampler.py @@ -0,0 +1,173 @@ +import math +from collections.abc import Iterator, Sized +from typing import cast, Optional, Union + +import torch +import torch.distributed as dist +from torch.utils.data import Sampler +from torchvision.datasets.video_utils import VideoClips + + +class DistributedSampler(Sampler): + """ + Extension of DistributedSampler, as discussed in + https://github.com/pytorch/pytorch/issues/23430 + + Example: + dataset: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] + num_replicas: 4 + shuffle: False + + when group_size = 1 + RANK | shard_dataset + ========================= + rank_0 | [0, 4, 8, 12] + rank_1 | [1, 5, 9, 13] + rank_2 | [2, 6, 10, 0] + rank_3 | [3, 7, 11, 1] + + when group_size = 2 + + RANK | shard_dataset + ========================= + rank_0 | [0, 1, 8, 9] + rank_1 | [2, 3, 10, 11] + rank_2 | [4, 5, 12, 13] + rank_3 | [6, 7, 0, 1] + + """ + + def __init__( + self, + dataset: Sized, + num_replicas: Optional[int] = None, + rank: Optional[int] = None, + shuffle: bool = False, + group_size: int = 1, + ) -> None: + if num_replicas is None: + if not dist.is_available(): + raise RuntimeError("Requires distributed package to be available") + num_replicas = dist.get_world_size() + if rank is None: + if not dist.is_available(): + raise RuntimeError("Requires distributed package to be available") + rank = dist.get_rank() + if len(dataset) % group_size != 0: + raise ValueError( + f"dataset length must be a multiplier of group size dataset length: {len(dataset)}, group size: {group_size}" + ) + self.dataset = dataset + self.group_size = group_size + self.num_replicas = num_replicas + self.rank = rank + self.epoch = 0 + dataset_group_length = len(dataset) // group_size + self.num_group_samples = int(math.ceil(dataset_group_length * 1.0 / self.num_replicas)) + self.num_samples = self.num_group_samples * group_size + self.total_size = self.num_samples * self.num_replicas + self.shuffle = shuffle + + def __iter__(self) -> Iterator[int]: + # deterministically shuffle based on epoch + g = torch.Generator() + g.manual_seed(self.epoch) + indices: Union[torch.Tensor, list[int]] + if self.shuffle: + indices = torch.randperm(len(self.dataset), generator=g).tolist() + else: + indices = list(range(len(self.dataset))) + + # add extra samples to make it evenly divisible + indices += indices[: (self.total_size - len(indices))] + assert len(indices) == self.total_size + + total_group_size = self.total_size // self.group_size + indices = torch.reshape(torch.LongTensor(indices), (total_group_size, self.group_size)) + + # subsample + indices = indices[self.rank : total_group_size : self.num_replicas, :] + indices = torch.reshape(indices, (-1,)).tolist() + assert len(indices) == self.num_samples + + if isinstance(self.dataset, Sampler): + orig_indices = list(iter(self.dataset)) + indices = [orig_indices[i] for i in indices] + + return iter(indices) + + def __len__(self) -> int: + return self.num_samples + + def set_epoch(self, epoch: int) -> None: + self.epoch = epoch + + +class UniformClipSampler(Sampler): + """ + Sample `num_video_clips_per_video` clips for each video, equally spaced. + When number of unique clips in the video is fewer than num_video_clips_per_video, + repeat the clips until `num_video_clips_per_video` clips are collected + + Args: + video_clips (VideoClips): video clips to sample from + num_clips_per_video (int): number of clips to be sampled per video + """ + + def __init__(self, video_clips: VideoClips, num_clips_per_video: int) -> None: + if not isinstance(video_clips, VideoClips): + raise TypeError(f"Expected video_clips to be an instance of VideoClips, got {type(video_clips)}") + self.video_clips = video_clips + self.num_clips_per_video = num_clips_per_video + + def __iter__(self) -> Iterator[int]: + idxs = [] + s = 0 + # select num_clips_per_video for each video, uniformly spaced + for c in self.video_clips.clips: + length = len(c) + if length == 0: + # corner case where video decoding fails + continue + + sampled = torch.linspace(s, s + length - 1, steps=self.num_clips_per_video).floor().to(torch.int64) + s += length + idxs.append(sampled) + return iter(cast(list[int], torch.cat(idxs).tolist())) + + def __len__(self) -> int: + return sum(self.num_clips_per_video for c in self.video_clips.clips if len(c) > 0) + + +class RandomClipSampler(Sampler): + """ + Samples at most `max_video_clips_per_video` clips for each video randomly + + Args: + video_clips (VideoClips): video clips to sample from + max_clips_per_video (int): maximum number of clips to be sampled per video + """ + + def __init__(self, video_clips: VideoClips, max_clips_per_video: int) -> None: + if not isinstance(video_clips, VideoClips): + raise TypeError(f"Expected video_clips to be an instance of VideoClips, got {type(video_clips)}") + self.video_clips = video_clips + self.max_clips_per_video = max_clips_per_video + + def __iter__(self) -> Iterator[int]: + idxs = [] + s = 0 + # select at most max_clips_per_video for each video, randomly + for c in self.video_clips.clips: + length = len(c) + size = min(length, self.max_clips_per_video) + sampled = torch.randperm(length)[:size] + s + s += length + idxs.append(sampled) + idxs_ = torch.cat(idxs) + # shuffle all clips randomly + perm = torch.randperm(len(idxs_)) + return iter(idxs_[perm].tolist()) + + def __len__(self) -> int: + return sum(min(len(c), self.max_clips_per_video) for c in self.video_clips.clips) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/sbd.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/sbd.py new file mode 100644 index 0000000000000000000000000000000000000000..091e8698197584064974664474083a87d64f2908 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/sbd.py @@ -0,0 +1,126 @@ +import os +import shutil +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import numpy as np +from PIL import Image + +from .utils import download_and_extract_archive, download_url, verify_str_arg +from .vision import VisionDataset + + +class SBDataset(VisionDataset): + """`Semantic Boundaries Dataset `_ + + The SBD currently contains annotations from 11355 images taken from the PASCAL VOC 2011 dataset. + + .. note :: + + Please note that the train and val splits included with this dataset are different from + the splits in the PASCAL VOC dataset. In particular some "train" images might be part of + VOC2012 val. + If you are interested in testing on VOC 2012 val, then use `image_set='train_noval'`, + which excludes all val images. + + .. warning:: + + This class needs `scipy `_ to load target files from `.mat` format. + + Args: + root (str or ``pathlib.Path``): Root directory of the Semantic Boundaries Dataset + image_set (string, optional): Select the image_set to use, ``train``, ``val`` or ``train_noval``. + Image set ``train_noval`` excludes VOC 2012 val images. + mode (string, optional): Select target type. Possible values 'boundaries' or 'segmentation'. + In case of 'boundaries', the target is an array of shape `[num_classes, H, W]`, + where `num_classes=20`. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + transforms (callable, optional): A function/transform that takes input sample and its target as entry + and returns a transformed version. Input sample is PIL image and target is a numpy array + if `mode='boundaries'` or PIL image if `mode='segmentation'`. + """ + + url = "https://www2.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz" + md5 = "82b4d87ceb2ed10f6038a1cba92111cb" + filename = "benchmark.tgz" + + voc_train_url = "https://www.cs.cornell.edu/~bharathh/train_noval.txt" + voc_split_filename = "train_noval.txt" + voc_split_md5 = "79bff800c5f0b1ec6b21080a3c066722" + + def __init__( + self, + root: Union[str, Path], + image_set: str = "train", + mode: str = "boundaries", + download: bool = False, + transforms: Optional[Callable] = None, + ) -> None: + + try: + from scipy.io import loadmat + + self._loadmat = loadmat + except ImportError: + raise RuntimeError("Scipy is not found. This dataset needs to have scipy installed: pip install scipy") + + super().__init__(root, transforms) + self.image_set = verify_str_arg(image_set, "image_set", ("train", "val", "train_noval")) + self.mode = verify_str_arg(mode, "mode", ("segmentation", "boundaries")) + self.num_classes = 20 + + sbd_root = self.root + image_dir = os.path.join(sbd_root, "img") + mask_dir = os.path.join(sbd_root, "cls") + + if download: + download_and_extract_archive(self.url, self.root, filename=self.filename, md5=self.md5) + extracted_ds_root = os.path.join(self.root, "benchmark_RELEASE", "dataset") + for f in ["cls", "img", "inst", "train.txt", "val.txt"]: + old_path = os.path.join(extracted_ds_root, f) + shutil.move(old_path, sbd_root) + if self.image_set == "train_noval": + # Note: this is failing as of June 2024 https://github.com/pytorch/vision/issues/8471 + download_url(self.voc_train_url, sbd_root, self.voc_split_filename, self.voc_split_md5) + + if not os.path.isdir(sbd_root): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + split_f = os.path.join(sbd_root, image_set.rstrip("\n") + ".txt") + + with open(os.path.join(split_f)) as fh: + file_names = [x.strip() for x in fh.readlines()] + + self.images = [os.path.join(image_dir, x + ".jpg") for x in file_names] + self.masks = [os.path.join(mask_dir, x + ".mat") for x in file_names] + + self._get_target = self._get_segmentation_target if self.mode == "segmentation" else self._get_boundaries_target + + def _get_segmentation_target(self, filepath: str) -> Image.Image: + mat = self._loadmat(filepath) + return Image.fromarray(mat["GTcls"][0]["Segmentation"][0]) + + def _get_boundaries_target(self, filepath: str) -> np.ndarray: + mat = self._loadmat(filepath) + return np.concatenate( + [np.expand_dims(mat["GTcls"][0]["Boundaries"][0][i][0].toarray(), axis=0) for i in range(self.num_classes)], + axis=0, + ) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + img = Image.open(self.images[index]).convert("RGB") + target = self._get_target(self.masks[index]) + + if self.transforms is not None: + img, target = self.transforms(img, target) + + return img, target + + def __len__(self) -> int: + return len(self.images) + + def extra_repr(self) -> str: + lines = ["Image set: {image_set}", "Mode: {mode}"] + return "\n".join(lines).format(**self.__dict__) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/sbu.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/sbu.py new file mode 100644 index 0000000000000000000000000000000000000000..c0c97503eec5f886fe1a188bdd797c710f93daa6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/sbu.py @@ -0,0 +1,114 @@ +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader + +from .utils import check_integrity, download_and_extract_archive, download_url +from .vision import VisionDataset + + +class SBU(VisionDataset): + """`SBU Captioned Photo `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where tarball + ``SBUCaptionedPhotoDataset.tar.gz`` exists. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If True, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + url = "https://www.cs.rice.edu/~vo9/sbucaptions/SBUCaptionedPhotoDataset.tar.gz" + filename = "SBUCaptionedPhotoDataset.tar.gz" + md5_checksum = "9aec147b3488753cf758b4d493422285" + + def __init__( + self, + root: Union[str, Path], + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = True, + loader: Callable[[str], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.loader = loader + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + # Read the caption for each photo + self.photos = [] + self.captions = [] + + file1 = os.path.join(self.root, "dataset", "SBU_captioned_photo_dataset_urls.txt") + file2 = os.path.join(self.root, "dataset", "SBU_captioned_photo_dataset_captions.txt") + + for line1, line2 in zip(open(file1), open(file2)): + url = line1.rstrip() + photo = os.path.basename(url) + filename = os.path.join(self.root, "dataset", photo) + if os.path.exists(filename): + caption = line2.rstrip() + self.photos.append(photo) + self.captions.append(caption) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is a caption for the photo. + """ + filename = os.path.join(self.root, "dataset", self.photos[index]) + img = self.loader(filename) + if self.transform is not None: + img = self.transform(img) + + target = self.captions[index] + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + """The number of photos in the dataset.""" + return len(self.photos) + + def _check_integrity(self) -> bool: + """Check the md5 checksum of the downloaded tarball.""" + root = self.root + fpath = os.path.join(root, self.filename) + if not check_integrity(fpath, self.md5_checksum): + return False + return True + + def download(self) -> None: + """Download and extract the tarball, and download each individual photo.""" + + if self._check_integrity(): + return + + download_and_extract_archive(self.url, self.root, self.root, self.filename, self.md5_checksum) + + # Download individual photos + with open(os.path.join(self.root, "dataset", "SBU_captioned_photo_dataset_urls.txt")) as fh: + for line in fh: + url = line.rstrip() + try: + download_url(url, os.path.join(self.root, "dataset")) + except OSError: + # The images point to public images on Flickr. + # Note: Images might be removed by users at anytime. + pass diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/semeion.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/semeion.py new file mode 100644 index 0000000000000000000000000000000000000000..cd8d139cb21fcd4e2a8157f7071ac43f62b72288 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/semeion.py @@ -0,0 +1,92 @@ +import os.path +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import numpy as np + +from ..utils import _Image_fromarray +from .utils import check_integrity, download_url +from .vision import VisionDataset + + +class SEMEION(VisionDataset): + r"""`SEMEION `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``semeion.py`` exists. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + """ + + url = "http://archive.ics.uci.edu/ml/machine-learning-databases/semeion/semeion.data" + filename = "semeion.data" + md5_checksum = "cb545d371d2ce14ec121470795a77432" + + def __init__( + self, + root: Union[str, Path], + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = True, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + fp = os.path.join(self.root, self.filename) + data = np.loadtxt(fp) + # convert value to 8 bit unsigned integer + # color (white #255) the pixels + self.data = (data[:, :256] * 255).astype("uint8") + self.data = np.reshape(self.data, (-1, 16, 16)) + self.labels = np.nonzero(data[:, 256:])[1] + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + img, target = self.data[index], int(self.labels[index]) + + # doing this so that it is consistent with all other datasets + # to return a PIL Image + img = _Image_fromarray(img, mode="L") + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.data) + + def _check_integrity(self) -> bool: + root = self.root + fpath = os.path.join(root, self.filename) + if not check_integrity(fpath, self.md5_checksum): + return False + return True + + def download(self) -> None: + if self._check_integrity(): + return + + root = self.root + download_url(self.url, root, self.filename, self.md5_checksum) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/stanford_cars.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/stanford_cars.py new file mode 100644 index 0000000000000000000000000000000000000000..e73fb1f3141dad7689ad3ed0ef0a580a2bc02b14 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/stanford_cars.py @@ -0,0 +1,105 @@ +import pathlib +from typing import Any, Callable, Optional, Union + +from .folder import default_loader + +from .utils import verify_str_arg +from .vision import VisionDataset + + +class StanfordCars(VisionDataset): + """Stanford Cars Dataset + + The Cars dataset contains 16,185 images of 196 classes of cars. The data is + split into 8,144 training images and 8,041 testing images, where each class + has been split roughly in a 50-50 split + + The original URL is https://ai.stanford.edu/~jkrause/cars/car_dataset.html, + the dataset isn't available online anymore. + + .. note:: + + This class needs `scipy `_ to load target files from `.mat` format. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset + split (string, optional): The dataset split, supports ``"train"`` (default) or ``"test"``. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): This parameter exists for backward compatibility but it does not + download the dataset, since the original URL is not available anymore. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + def __init__( + self, + root: Union[str, pathlib.Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[str], Any] = default_loader, + ) -> None: + + try: + import scipy.io as sio + except ImportError: + raise RuntimeError("Scipy is not found. This dataset needs to have scipy installed: pip install scipy") + + super().__init__(root, transform=transform, target_transform=target_transform) + + self._split = verify_str_arg(split, "split", ("train", "test")) + self._base_folder = pathlib.Path(root) / "stanford_cars" + devkit = self._base_folder / "devkit" + + if self._split == "train": + self._annotations_mat_path = devkit / "cars_train_annos.mat" + self._images_base_path = self._base_folder / "cars_train" + else: + self._annotations_mat_path = self._base_folder / "cars_test_annos_withlabels.mat" + self._images_base_path = self._base_folder / "cars_test" + + if download: + self.download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found.") + + self._samples = [ + ( + str(self._images_base_path / annotation["fname"]), + annotation["class"] - 1, # Original target mapping starts from 1, hence -1 + ) + for annotation in sio.loadmat(self._annotations_mat_path, squeeze_me=True)["annotations"] + ] + + self.classes = sio.loadmat(str(devkit / "cars_meta.mat"), squeeze_me=True)["class_names"].tolist() + self.class_to_idx = {cls: i for i, cls in enumerate(self.classes)} + self.loader = loader + + def __len__(self) -> int: + return len(self._samples) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + """Returns pil_image and class_id for given index""" + image_path, target = self._samples[idx] + image = self.loader(image_path) + + if self.transform is not None: + image = self.transform(image) + if self.target_transform is not None: + target = self.target_transform(target) + return image, target + + def _check_exists(self) -> bool: + if not (self._base_folder / "devkit").is_dir(): + return False + + return self._annotations_mat_path.exists() and self._images_base_path.is_dir() + + def download(self): + raise ValueError("The original URL is broken so the StanfordCars dataset cannot be downloaded anymore.") diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/stl10.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/stl10.py new file mode 100644 index 0000000000000000000000000000000000000000..6d7212a1b55578334efcfe55861165d4b196326c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/stl10.py @@ -0,0 +1,174 @@ +import os.path +from pathlib import Path +from typing import Any, Callable, cast, Optional, Union + +import numpy as np +from PIL import Image + +from .utils import check_integrity, download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + + +class STL10(VisionDataset): + """`STL10 `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset where directory + ``stl10_binary`` exists. + split (string): One of {'train', 'test', 'unlabeled', 'train+unlabeled'}. + Accordingly, dataset is selected. + folds (int, optional): One of {0-9} or None. + For training, loads one of the 10 pre-defined folds of 1k samples for the + standard evaluation procedure. If no value is passed, loads the 5k samples. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + """ + + base_folder = "stl10_binary" + url = "http://ai.stanford.edu/~acoates/stl10/stl10_binary.tar.gz" + filename = "stl10_binary.tar.gz" + tgz_md5 = "91f7769df0f17e558f3565bffb0c7dfb" + class_names_file = "class_names.txt" + folds_list_file = "fold_indices.txt" + train_list = [ + ["train_X.bin", "918c2871b30a85fa023e0c44e0bee87f"], + ["train_y.bin", "5a34089d4802c674881badbb80307741"], + ["unlabeled_X.bin", "5242ba1fed5e4be9e1e742405eb56ca4"], + ] + + test_list = [["test_X.bin", "7f263ba9f9e0b06b93213547f721ac82"], ["test_y.bin", "36f9794fa4beb8a2c72628de14fa638e"]] + splits = ("train", "train+unlabeled", "unlabeled", "test") + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + folds: Optional[int] = None, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.split = verify_str_arg(split, "split", self.splits) + self.folds = self._verify_folds(folds) + + if download: + self.download() + elif not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + # now load the picked numpy arrays + self.labels: Optional[np.ndarray] + if self.split == "train": + self.data, self.labels = self.__loadfile(self.train_list[0][0], self.train_list[1][0]) + self.labels = cast(np.ndarray, self.labels) + self.__load_folds(folds) + + elif self.split == "train+unlabeled": + self.data, self.labels = self.__loadfile(self.train_list[0][0], self.train_list[1][0]) + self.labels = cast(np.ndarray, self.labels) + self.__load_folds(folds) + unlabeled_data, _ = self.__loadfile(self.train_list[2][0]) + self.data = np.concatenate((self.data, unlabeled_data)) + self.labels = np.concatenate((self.labels, np.asarray([-1] * unlabeled_data.shape[0]))) + + elif self.split == "unlabeled": + self.data, _ = self.__loadfile(self.train_list[2][0]) + self.labels = np.asarray([-1] * self.data.shape[0]) + else: # self.split == 'test': + self.data, self.labels = self.__loadfile(self.test_list[0][0], self.test_list[1][0]) + + class_file = os.path.join(self.root, self.base_folder, self.class_names_file) + if os.path.isfile(class_file): + with open(class_file) as f: + self.classes = f.read().splitlines() + + def _verify_folds(self, folds: Optional[int]) -> Optional[int]: + if folds is None: + return folds + elif isinstance(folds, int): + if folds in range(10): + return folds + msg = "Value for argument folds should be in the range [0, 10), but got {}." + raise ValueError(msg.format(folds)) + else: + msg = "Expected type None or int for argument folds, but got type {}." + raise ValueError(msg.format(type(folds))) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + target: Optional[int] + if self.labels is not None: + img, target = self.data[index], int(self.labels[index]) + else: + img, target = self.data[index], None + + # doing this so that it is consistent with all other datasets + # to return a PIL Image + img = Image.fromarray(np.transpose(img, (1, 2, 0))) + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return self.data.shape[0] + + def __loadfile(self, data_file: str, labels_file: Optional[str] = None) -> tuple[np.ndarray, Optional[np.ndarray]]: + labels = None + if labels_file: + path_to_labels = os.path.join(self.root, self.base_folder, labels_file) + with open(path_to_labels, "rb") as f: + labels = np.fromfile(f, dtype=np.uint8) - 1 # 0-based + + path_to_data = os.path.join(self.root, self.base_folder, data_file) + with open(path_to_data, "rb") as f: + # read whole file in uint8 chunks + everything = np.fromfile(f, dtype=np.uint8) + images = np.reshape(everything, (-1, 3, 96, 96)) + images = np.transpose(images, (0, 1, 3, 2)) + + return images, labels + + def _check_integrity(self) -> bool: + for filename, md5 in self.train_list + self.test_list: + fpath = os.path.join(self.root, self.base_folder, filename) + if not check_integrity(fpath, md5): + return False + return True + + def download(self) -> None: + if self._check_integrity(): + return + download_and_extract_archive(self.url, self.root, filename=self.filename, md5=self.tgz_md5) + self._check_integrity() + + def extra_repr(self) -> str: + return "Split: {split}".format(**self.__dict__) + + def __load_folds(self, folds: Optional[int]) -> None: + # loads one of the folds if specified + if folds is None: + return + path_to_folds = os.path.join(self.root, self.base_folder, self.folds_list_file) + with open(path_to_folds) as f: + str_idx = f.read().splitlines()[folds] + list_idx = np.fromstring(str_idx, dtype=np.int64, sep=" ") + self.data = self.data[list_idx, :, :, :] + if self.labels is not None: + self.labels = self.labels[list_idx] diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/sun397.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/sun397.py new file mode 100644 index 0000000000000000000000000000000000000000..a27f86d95795641c475bbf508c22734e2cf37412 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/sun397.py @@ -0,0 +1,81 @@ +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from .folder import default_loader + +from .utils import download_and_extract_archive +from .vision import VisionDataset + + +class SUN397(VisionDataset): + """`The SUN397 Data Set `_. + + The SUN397 or Scene UNderstanding (SUN) is a dataset for scene recognition consisting of + 397 categories with 108'754 images. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset. + transform (callable, optional): A function/transform that takes in a PIL image or torch.Tensor, depends on the given loader, + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + loader (callable, optional): A function to load an image given its path. + By default, it uses PIL as its image loader, but users could also pass in + ``torchvision.io.decode_image`` for decoding image data into tensors directly. + """ + + _DATASET_URL = "http://vision.princeton.edu/projects/2010/SUN/SUN397.tar.gz" + _DATASET_MD5 = "8ca2778205c41d23104230ba66911c7a" + + def __init__( + self, + root: Union[str, Path], + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + loader: Callable[[Union[str, Path]], Any] = default_loader, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self._data_dir = Path(self.root) / "SUN397" + + if download: + self._download() + + if not self._check_exists(): + raise RuntimeError("Dataset not found. You can use download=True to download it") + + with open(self._data_dir / "ClassName.txt") as f: + self.classes = [c[3:].strip() for c in f] + + self.class_to_idx = dict(zip(self.classes, range(len(self.classes)))) + self._image_files = list(self._data_dir.rglob("sun_*.jpg")) + + self._labels = [ + self.class_to_idx["/".join(path.relative_to(self._data_dir).parts[1:-1])] for path in self._image_files + ] + self.loader = loader + + def __len__(self) -> int: + return len(self._image_files) + + def __getitem__(self, idx: int) -> tuple[Any, Any]: + image_file, label = self._image_files[idx], self._labels[idx] + image = self.loader(image_file) + + if self.transform: + image = self.transform(image) + + if self.target_transform: + label = self.target_transform(label) + + return image, label + + def _check_exists(self) -> bool: + return self._data_dir.is_dir() + + def _download(self) -> None: + if self._check_exists(): + return + download_and_extract_archive(self._DATASET_URL, download_root=self.root, md5=self._DATASET_MD5) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/svhn.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/svhn.py new file mode 100644 index 0000000000000000000000000000000000000000..b59f78ec050d045bbf8099434b8cd579bba12c72 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/svhn.py @@ -0,0 +1,130 @@ +import os.path +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import numpy as np +from PIL import Image + +from .utils import check_integrity, download_url, verify_str_arg +from .vision import VisionDataset + + +class SVHN(VisionDataset): + """`SVHN `_ Dataset. + Note: The SVHN dataset assigns the label `10` to the digit `0`. However, in this Dataset, + we assign the label `0` to the digit `0` to be compatible with PyTorch loss functions which + expect the class labels to be in the range `[0, C-1]` + + .. warning:: + + This class needs `scipy `_ to load data from `.mat` format. + + Args: + root (str or ``pathlib.Path``): Root directory of the dataset where the data is stored. + split (string): One of {'train', 'test', 'extra'}. + Accordingly dataset is selected. 'extra' is Extra training set. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + """ + + split_list = { + "train": [ + "http://ufldl.stanford.edu/housenumbers/train_32x32.mat", + "train_32x32.mat", + "e26dedcc434d2e4c54c9b2d4a06d8373", + ], + "test": [ + "http://ufldl.stanford.edu/housenumbers/test_32x32.mat", + "test_32x32.mat", + "eb5a983be6a315427106f1b164d9cef3", + ], + "extra": [ + "http://ufldl.stanford.edu/housenumbers/extra_32x32.mat", + "extra_32x32.mat", + "a93ce644f1a588dc4d68dda5feec44a7", + ], + } + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + self.split = verify_str_arg(split, "split", tuple(self.split_list.keys())) + self.url = self.split_list[split][0] + self.filename = self.split_list[split][1] + self.file_md5 = self.split_list[split][2] + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + # import here rather than at top of file because this is + # an optional dependency for torchvision + import scipy.io as sio + + # reading(loading) mat file as array + loaded_mat = sio.loadmat(os.path.join(self.root, self.filename)) + + self.data = loaded_mat["X"] + # loading from the .mat file gives an np.ndarray of type np.uint8 + # converting to np.int64, so that we have a LongTensor after + # the conversion from the numpy array + # the squeeze is needed to obtain a 1D tensor + self.labels = loaded_mat["y"].astype(np.int64).squeeze() + + # the svhn dataset assigns the class label "10" to the digit 0 + # this makes it inconsistent with several loss functions + # which expect the class labels to be in the range [0, C-1] + np.place(self.labels, self.labels == 10, 0) + self.data = np.transpose(self.data, (3, 2, 0, 1)) + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + img, target = self.data[index], int(self.labels[index]) + + # doing this so that it is consistent with all other datasets + # to return a PIL Image + img = Image.fromarray(np.transpose(img, (1, 2, 0))) + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.data) + + def _check_integrity(self) -> bool: + root = self.root + md5 = self.split_list[self.split][2] + fpath = os.path.join(root, self.filename) + return check_integrity(fpath, md5) + + def download(self) -> None: + md5 = self.split_list[self.split][2] + download_url(self.url, self.root, self.filename, md5) + + def extra_repr(self) -> str: + return "Split: {split}".format(**self.__dict__) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/ucf101.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/ucf101.py new file mode 100644 index 0000000000000000000000000000000000000000..85930dbc742beb0dcfdac6e515f16966b92b9634 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/ucf101.py @@ -0,0 +1,131 @@ +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from torch import Tensor + +from .folder import find_classes, make_dataset +from .video_utils import VideoClips +from .vision import VisionDataset + + +class UCF101(VisionDataset): + """ + `UCF101 `_ dataset. + + UCF101 is an action recognition video dataset. + This dataset consider every video as a collection of video clips of fixed size, specified + by ``frames_per_clip``, where the step in frames between each clip is given by + ``step_between_clips``. The dataset itself can be downloaded from the dataset website; + annotations that ``annotation_path`` should be pointing to can be downloaded from `here + `_. + + To give an example, for 2 videos with 10 and 15 frames respectively, if ``frames_per_clip=5`` + and ``step_between_clips=5``, the dataset size will be (2 + 3) = 5, where the first two + elements will come from video 1, and the next three elements from video 2. + Note that we drop clips which do not have exactly ``frames_per_clip`` elements, so not all + frames in a video might be present. + + Internally, it uses a VideoClips object to handle clip creation. + + Args: + root (str or ``pathlib.Path``): Root directory of the UCF101 Dataset. + annotation_path (str): path to the folder containing the split files; + see docstring above for download instructions of these files + frames_per_clip (int): number of frames in a clip. + step_between_clips (int, optional): number of frames between each clip. + fold (int, optional): which fold to use. Should be between 1 and 3. + train (bool, optional): if ``True``, creates a dataset from the train split, + otherwise from the ``test`` split. + transform (callable, optional): A function/transform that takes in a TxHxWxC video + and returns a transformed version. + output_format (str, optional): The format of the output video tensors (before transforms). + Can be either "THWC" (default) or "TCHW". + + Returns: + tuple: A 3-tuple with the following entries: + + - video (Tensor[T, H, W, C] or Tensor[T, C, H, W]): The `T` video frames + - audio(Tensor[K, L]): the audio frames, where `K` is the number of channels + and `L` is the number of points + - label (int): class of the video clip + """ + + def __init__( + self, + root: Union[str, Path], + annotation_path: str, + frames_per_clip: int, + step_between_clips: int = 1, + frame_rate: Optional[int] = None, + fold: int = 1, + train: bool = True, + transform: Optional[Callable] = None, + _precomputed_metadata: Optional[dict[str, Any]] = None, + num_workers: int = 1, + _video_width: int = 0, + _video_height: int = 0, + _video_min_dimension: int = 0, + _audio_samples: int = 0, + output_format: str = "THWC", + ) -> None: + super().__init__(root) + if not 1 <= fold <= 3: + raise ValueError(f"fold should be between 1 and 3, got {fold}") + + extensions = ("avi",) + self.fold = fold + self.train = train + + self.classes, class_to_idx = find_classes(self.root) + self.samples = make_dataset(self.root, class_to_idx, extensions, is_valid_file=None) + video_list = [x[0] for x in self.samples] + video_clips = VideoClips( + video_list, + frames_per_clip, + step_between_clips, + frame_rate, + _precomputed_metadata, + num_workers=num_workers, + _video_width=_video_width, + _video_height=_video_height, + _video_min_dimension=_video_min_dimension, + _audio_samples=_audio_samples, + output_format=output_format, + ) + # we bookkeep the full version of video clips because we want to be able + # to return the metadata of full version rather than the subset version of + # video clips + self.full_video_clips = video_clips + self.indices = self._select_fold(video_list, annotation_path, fold, train) + self.video_clips = video_clips.subset(self.indices) + self.transform = transform + + @property + def metadata(self) -> dict[str, Any]: + return self.full_video_clips.metadata + + def _select_fold(self, video_list: list[str], annotation_path: str, fold: int, train: bool) -> list[int]: + name = "train" if train else "test" + name = f"{name}list{fold:02d}.txt" + f = os.path.join(annotation_path, name) + selected_files = set() + with open(f) as fid: + data = fid.readlines() + data = [x.strip().split(" ")[0] for x in data] + data = [os.path.join(self.root, *x.split("/")) for x in data] + selected_files.update(data) + indices = [i for i in range(len(video_list)) if video_list[i] in selected_files] + return indices + + def __len__(self) -> int: + return self.video_clips.num_clips() + + def __getitem__(self, idx: int) -> tuple[Tensor, Tensor, int]: + video, audio, info, video_idx = self.video_clips.get_clip(idx) + label = self.samples[self.indices[video_idx]][1] + + if self.transform is not None: + video = self.transform(video) + + return video, audio, label diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/usps.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/usps.py new file mode 100644 index 0000000000000000000000000000000000000000..e09ac96e45eefd8ae2458a196baa4f07630d3d43 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/usps.py @@ -0,0 +1,96 @@ +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union + +import numpy as np + +from ..utils import _Image_fromarray +from .utils import download_url +from .vision import VisionDataset + + +class USPS(VisionDataset): + """`USPS `_ Dataset. + The data-format is : [label [index:value ]*256 \\n] * num_lines, where ``label`` lies in ``[1, 10]``. + The value for each pixel lies in ``[-1, 1]``. Here we transform the ``label`` into ``[0, 9]`` + and make pixel values in ``[0, 255]``. + + Args: + root (str or ``pathlib.Path``): Root directory of dataset to store``USPS`` data files. + train (bool, optional): If True, creates dataset from ``usps.bz2``, + otherwise from ``usps.t.bz2``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + """ + + split_list = { + "train": [ + "https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/usps.bz2", + "usps.bz2", + "ec16c51db3855ca6c91edd34d0e9b197", + ], + "test": [ + "https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/usps.t.bz2", + "usps.t.bz2", + "8ea070ee2aca1ac39742fdd1ef5ed118", + ], + } + + def __init__( + self, + root: Union[str, Path], + train: bool = True, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__(root, transform=transform, target_transform=target_transform) + split = "train" if train else "test" + url, filename, checksum = self.split_list[split] + full_path = os.path.join(self.root, filename) + + if download and not os.path.exists(full_path): + download_url(url, self.root, filename, md5=checksum) + + import bz2 + + with bz2.open(full_path) as fp: + raw_data = [line.decode().split() for line in fp.readlines()] + tmp_list = [[x.split(":")[-1] for x in data[1:]] for data in raw_data] + imgs = np.asarray(tmp_list, dtype=np.float32).reshape((-1, 16, 16)) + imgs = ((imgs + 1) / 2 * 255).astype(dtype=np.uint8) + targets = [int(d[0]) - 1 for d in raw_data] + + self.data = imgs + self.targets = targets + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is index of the target class. + """ + img, target = self.data[index], int(self.targets[index]) + + # doing this so that it is consistent with all other datasets + # to return a PIL Image + img = _Image_fromarray(img, mode="L") + + if self.transform is not None: + img = self.transform(img) + + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.data) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/utils.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0b6670800d2b012829bdf06b887f82ff3f554108 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/utils.py @@ -0,0 +1,468 @@ +import bz2 +import gzip +import hashlib +import lzma +import os +import os.path +import pathlib +import re +import tarfile +import urllib +import urllib.error +import urllib.request +import zipfile +from collections.abc import Iterable +from typing import Any, Callable, IO, Optional, TypeVar, Union +from urllib.parse import urlparse + +import numpy as np +import torch +from torch.utils.model_zoo import tqdm + +from .._internally_replaced_utils import _download_file_from_remote_location, _is_remote_location_available + +USER_AGENT = "pytorch/vision" + + +def _urlretrieve(url: str, filename: Union[str, pathlib.Path], chunk_size: int = 1024 * 32) -> None: + with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": USER_AGENT})) as response: + with open(filename, "wb") as fh, tqdm(total=response.length, unit="B", unit_scale=True) as pbar: + while chunk := response.read(chunk_size): + fh.write(chunk) + pbar.update(len(chunk)) + + +def calculate_md5(fpath: Union[str, pathlib.Path], chunk_size: int = 1024 * 1024) -> str: + # Setting the `usedforsecurity` flag does not change anything about the functionality, but indicates that we are + # not using the MD5 checksum for cryptography. This enables its usage in restricted environments like FIPS. Without + # it torchvision.datasets is unusable in these environments since we perform a MD5 check everywhere. + md5 = hashlib.md5(usedforsecurity=False) + with open(fpath, "rb") as f: + while chunk := f.read(chunk_size): + md5.update(chunk) + return md5.hexdigest() + + +def check_md5(fpath: Union[str, pathlib.Path], md5: str, **kwargs: Any) -> bool: + return md5 == calculate_md5(fpath, **kwargs) + + +def check_integrity(fpath: Union[str, pathlib.Path], md5: Optional[str] = None) -> bool: + if not os.path.isfile(fpath): + return False + if md5 is None: + return True + return check_md5(fpath, md5) + + +def _get_redirect_url(url: str, max_hops: int = 3) -> str: + initial_url = url + headers = {"Method": "HEAD", "User-Agent": USER_AGENT} + + for _ in range(max_hops + 1): + with urllib.request.urlopen(urllib.request.Request(url, headers=headers)) as response: + if response.url == url or response.url is None: + return url + + url = response.url + else: + raise RecursionError( + f"Request to {initial_url} exceeded {max_hops} redirects. The last redirect points to {url}." + ) + + +def _get_google_drive_file_id(url: str) -> Optional[str]: + parts = urlparse(url) + + if re.match(r"(drive|docs)[.]google[.]com", parts.netloc) is None: + return None + + match = re.match(r"/file/d/(?P[^/]*)", parts.path) + if match is None: + return None + + return match.group("id") + + +def download_url( + url: str, + root: Union[str, pathlib.Path], + filename: Optional[Union[str, pathlib.Path]] = None, + md5: Optional[str] = None, + max_redirect_hops: int = 3, +) -> None: + """Download a file from a url and place it in root. + + Args: + url (str): URL to download file from + root (str): Directory to place downloaded file in + filename (str, optional): Name to save the file under. If None, use the basename of the URL + md5 (str, optional): MD5 checksum of the download. If None, do not check + max_redirect_hops (int, optional): Maximum number of redirect hops allowed + """ + root = os.path.expanduser(root) + if not filename: + filename = os.path.basename(url) + fpath = os.fspath(os.path.join(root, filename)) + + os.makedirs(root, exist_ok=True) + + # check if file is already present locally + if check_integrity(fpath, md5): + return + + if _is_remote_location_available(): + _download_file_from_remote_location(fpath, url) + else: + # expand redirect chain if needed + url = _get_redirect_url(url, max_hops=max_redirect_hops) + + # check if file is located on Google Drive + file_id = _get_google_drive_file_id(url) + if file_id is not None: + return download_file_from_google_drive(file_id, root, filename, md5) + + # download the file + try: + _urlretrieve(url, fpath) + except (urllib.error.URLError, OSError) as e: # type: ignore[attr-defined] + if url[:5] == "https": + url = url.replace("https:", "http:") + _urlretrieve(url, fpath) + else: + raise e + + # check integrity of downloaded file + if not check_integrity(fpath, md5): + raise RuntimeError("File not found or corrupted.") + + +def list_dir(root: Union[str, pathlib.Path], prefix: bool = False) -> list[str]: + """List all directories at a given root + + Args: + root (str): Path to directory whose folders need to be listed + prefix (bool, optional): If true, prepends the path to each result, otherwise + only returns the name of the directories found + """ + root = os.path.expanduser(root) + directories = [p for p in os.listdir(root) if os.path.isdir(os.path.join(root, p))] + if prefix is True: + directories = [os.path.join(root, d) for d in directories] + return directories + + +def list_files(root: Union[str, pathlib.Path], suffix: str, prefix: bool = False) -> list[str]: + """List all files ending with a suffix at a given root + + Args: + root (str): Path to directory whose folders need to be listed + suffix (str or tuple): Suffix of the files to match, e.g. '.png' or ('.jpg', '.png'). + It uses the Python "str.endswith" method and is passed directly + prefix (bool, optional): If true, prepends the path to each result, otherwise + only returns the name of the files found + """ + root = os.path.expanduser(root) + files = [p for p in os.listdir(root) if os.path.isfile(os.path.join(root, p)) and p.endswith(suffix)] + if prefix is True: + files = [os.path.join(root, d) for d in files] + return files + + +def download_file_from_google_drive( + file_id: str, + root: Union[str, pathlib.Path], + filename: Optional[Union[str, pathlib.Path]] = None, + md5: Optional[str] = None, +): + """Download a Google Drive file from and place it in root. + + Args: + file_id (str): id of file to be downloaded + root (str): Directory to place downloaded file in + filename (str, optional): Name to save the file under. If None, use the id of the file. + md5 (str, optional): MD5 checksum of the download. If None, do not check + """ + try: + import gdown + except ModuleNotFoundError: + raise RuntimeError( + "To download files from GDrive, 'gdown' is required. You can install it with 'pip install gdown'." + ) + + root = os.path.expanduser(root) + if not filename: + filename = file_id + fpath = os.fspath(os.path.join(root, filename)) + + os.makedirs(root, exist_ok=True) + + if check_integrity(fpath, md5): + return + + gdown.download(id=file_id, output=fpath, quiet=False, user_agent=USER_AGENT) + + if not check_integrity(fpath, md5): + raise RuntimeError("File not found or corrupted.") + + +def _extract_tar( + from_path: Union[str, pathlib.Path], to_path: Union[str, pathlib.Path], compression: Optional[str] +) -> None: + with tarfile.open(from_path, f"r:{compression[1:]}" if compression else "r") as tar: + tar.extractall(to_path) + + +_ZIP_COMPRESSION_MAP: dict[str, int] = { + ".bz2": zipfile.ZIP_BZIP2, + ".xz": zipfile.ZIP_LZMA, +} + + +def _extract_zip( + from_path: Union[str, pathlib.Path], to_path: Union[str, pathlib.Path], compression: Optional[str] +) -> None: + with zipfile.ZipFile( + from_path, "r", compression=_ZIP_COMPRESSION_MAP[compression] if compression else zipfile.ZIP_STORED + ) as zip: + zip.extractall(to_path) + + +_ARCHIVE_EXTRACTORS: dict[str, Callable[[Union[str, pathlib.Path], Union[str, pathlib.Path], Optional[str]], None]] = { + ".tar": _extract_tar, + ".zip": _extract_zip, +} +_COMPRESSED_FILE_OPENERS: dict[str, Callable[..., IO]] = { + ".bz2": bz2.open, + ".gz": gzip.open, + ".xz": lzma.open, +} +_FILE_TYPE_ALIASES: dict[str, tuple[Optional[str], Optional[str]]] = { + ".tbz": (".tar", ".bz2"), + ".tbz2": (".tar", ".bz2"), + ".tgz": (".tar", ".gz"), +} + + +def _detect_file_type(file: Union[str, pathlib.Path]) -> tuple[str, Optional[str], Optional[str]]: + """Detect the archive type and/or compression of a file. + + Args: + file (str): the filename + + Returns: + (tuple): tuple of suffix, archive type, and compression + + Raises: + RuntimeError: if file has no suffix or suffix is not supported + """ + suffixes = pathlib.Path(file).suffixes + if not suffixes: + raise RuntimeError( + f"File '{file}' has no suffixes that could be used to detect the archive type and compression." + ) + suffix = suffixes[-1] + + # check if the suffix is a known alias + if suffix in _FILE_TYPE_ALIASES: + return (suffix, *_FILE_TYPE_ALIASES[suffix]) + + # check if the suffix is an archive type + if suffix in _ARCHIVE_EXTRACTORS: + return suffix, suffix, None + + # check if the suffix is a compression + if suffix in _COMPRESSED_FILE_OPENERS: + # check for suffix hierarchy + if len(suffixes) > 1: + suffix2 = suffixes[-2] + + # check if the suffix2 is an archive type + if suffix2 in _ARCHIVE_EXTRACTORS: + return suffix2 + suffix, suffix2, suffix + + return suffix, None, suffix + + valid_suffixes = sorted(set(_FILE_TYPE_ALIASES) | set(_ARCHIVE_EXTRACTORS) | set(_COMPRESSED_FILE_OPENERS)) + raise RuntimeError(f"Unknown compression or archive type: '{suffix}'.\nKnown suffixes are: '{valid_suffixes}'.") + + +def _decompress( + from_path: Union[str, pathlib.Path], + to_path: Optional[Union[str, pathlib.Path]] = None, + remove_finished: bool = False, +) -> pathlib.Path: + r"""Decompress a file. + + The compression is automatically detected from the file name. + + Args: + from_path (str): Path to the file to be decompressed. + to_path (str): Path to the decompressed file. If omitted, ``from_path`` without compression extension is used. + remove_finished (bool): If ``True``, remove the file after the extraction. + + Returns: + (str): Path to the decompressed file. + """ + suffix, archive_type, compression = _detect_file_type(from_path) + if not compression: + raise RuntimeError(f"Couldn't detect a compression from suffix {suffix}.") + + if to_path is None: + to_path = pathlib.Path(os.fspath(from_path).replace(suffix, archive_type if archive_type is not None else "")) + + # We don't need to check for a missing key here, since this was already done in _detect_file_type() + compressed_file_opener = _COMPRESSED_FILE_OPENERS[compression] + + with compressed_file_opener(from_path, "rb") as rfh, open(to_path, "wb") as wfh: + wfh.write(rfh.read()) + + if remove_finished: + os.remove(from_path) + + return pathlib.Path(to_path) + + +def extract_archive( + from_path: Union[str, pathlib.Path], + to_path: Optional[Union[str, pathlib.Path]] = None, + remove_finished: bool = False, +) -> Union[str, pathlib.Path]: + """Extract an archive. + + The archive type and a possible compression is automatically detected from the file name. If the file is compressed + but not an archive the call is dispatched to :func:`decompress`. + + Args: + from_path (str): Path to the file to be extracted. + to_path (str): Path to the directory the file will be extracted to. If omitted, the directory of the file is + used. + remove_finished (bool): If ``True``, remove the file after the extraction. + + Returns: + (str): Path to the directory the file was extracted to. + """ + + def path_or_str(ret_path: pathlib.Path) -> Union[str, pathlib.Path]: + if isinstance(from_path, str): + return os.fspath(ret_path) + else: + return ret_path + + if to_path is None: + to_path = os.path.dirname(from_path) + + suffix, archive_type, compression = _detect_file_type(from_path) + if not archive_type: + ret_path = _decompress( + from_path, + os.path.join(to_path, os.path.basename(from_path).replace(suffix, "")), + remove_finished=remove_finished, + ) + return path_or_str(ret_path) + + # We don't need to check for a missing key here, since this was already done in _detect_file_type() + extractor = _ARCHIVE_EXTRACTORS[archive_type] + + extractor(from_path, to_path, compression) + if remove_finished: + os.remove(from_path) + + return path_or_str(pathlib.Path(to_path)) + + +def download_and_extract_archive( + url: str, + download_root: Union[str, pathlib.Path], + extract_root: Optional[Union[str, pathlib.Path]] = None, + filename: Optional[Union[str, pathlib.Path]] = None, + md5: Optional[str] = None, + remove_finished: bool = False, +) -> None: + download_root = os.path.expanduser(download_root) + if extract_root is None: + extract_root = download_root + if not filename: + filename = os.path.basename(url) + + download_url(url, download_root, filename, md5) + + archive = os.path.join(download_root, filename) + extract_archive(archive, extract_root, remove_finished) + + +def iterable_to_str(iterable: Iterable) -> str: + return "'" + "', '".join([str(item) for item in iterable]) + "'" + + +T = TypeVar("T", str, bytes) + + +def verify_str_arg( + value: T, + arg: Optional[str] = None, + valid_values: Optional[Iterable[T]] = None, + custom_msg: Optional[str] = None, +) -> T: + if not isinstance(value, str): + if arg is None: + msg = "Expected type str, but got type {type}." + else: + msg = "Expected type str for argument {arg}, but got type {type}." + msg = msg.format(type=type(value), arg=arg) + raise ValueError(msg) + + if valid_values is None: + return value + + if value not in valid_values: + if custom_msg is not None: + msg = custom_msg + else: + msg = "Unknown value '{value}' for argument {arg}. Valid values are {{{valid_values}}}." + msg = msg.format(value=value, arg=arg, valid_values=iterable_to_str(valid_values)) + raise ValueError(msg) + + return value + + +def _read_pfm(file_name: Union[str, pathlib.Path], slice_channels: int = 2) -> np.ndarray: + """Read file in .pfm format. Might contain either 1 or 3 channels of data. + + Args: + file_name (str): Path to the file. + slice_channels (int): Number of channels to slice out of the file. + Useful for reading different data formats stored in .pfm files: Optical Flows, Stereo Disparity Maps, etc. + """ + + with open(file_name, "rb") as f: + header = f.readline().rstrip() + if header not in [b"PF", b"Pf"]: + raise ValueError("Invalid PFM file") + + dim_match = re.match(rb"^(\d+)\s(\d+)\s$", f.readline()) + if not dim_match: + raise Exception("Malformed PFM header.") + w, h = (int(dim) for dim in dim_match.groups()) + + scale = float(f.readline().rstrip()) + if scale < 0: # little-endian + endian = "<" + scale = -scale + else: + endian = ">" # big-endian + + data = np.fromfile(f, dtype=endian + "f") + + pfm_channels = 3 if header == b"PF" else 1 + + data = data.reshape(h, w, pfm_channels).transpose(2, 0, 1) + data = np.flip(data, axis=1) # flip on h dimension + data = data[:slice_channels, :, :] + return data.astype(np.float32) + + +def _flip_byte_order(t: torch.Tensor) -> torch.Tensor: + return ( + t.contiguous().view(torch.uint8).view(*t.shape, t.element_size()).flip(-1).view(*t.shape[:-1], -1).view(t.dtype) + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/video_utils.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/video_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a95737a571d9803d40049874516f03155dea28f8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/video_utils.py @@ -0,0 +1,384 @@ +import bisect +import math +import warnings +from typing import Any, Optional, TypeVar, Union + +import torch + +from .utils import tqdm + +T = TypeVar("T") + + +def _get_torchcodec(): + try: + import torchcodec # type: ignore[import-not-found] + except ImportError: + raise ImportError( + "Video decoding capabilities were removed from torchvision and migrated " + "to TorchCodec. Please install TorchCodec following instructions at " + "https://github.com/pytorch/torchcodec#installing-torchcodec" + ) + return torchcodec + + +def unfold(tensor: torch.Tensor, size: int, step: int, dilation: int = 1) -> torch.Tensor: + """ + similar to tensor.unfold, but with the dilation + and specialized for 1d tensors + + Returns all consecutive windows of `size` elements, with + `step` between windows. The distance between each element + in a window is given by `dilation`. + """ + if tensor.dim() != 1: + raise ValueError(f"tensor should have 1 dimension instead of {tensor.dim()}") + o_stride = tensor.stride(0) + numel = tensor.numel() + new_stride = (step * o_stride, dilation * o_stride) + new_size = ((numel - (dilation * (size - 1) + 1)) // step + 1, size) + if new_size[0] < 1: + new_size = (0, size) + return torch.as_strided(tensor, new_size, new_stride) + + +class _VideoTimestampsDataset: + """ + Dataset used to parallelize the reading of the timestamps + of a list of videos, given their paths in the filesystem. + + Used in VideoClips and defined at top level, so it can be + pickled when forking. + """ + + def __init__(self, video_paths: list[str]) -> None: + self.video_paths = video_paths + + def __len__(self) -> int: + return len(self.video_paths) + + def __getitem__(self, idx: int) -> tuple[list[int], Optional[float]]: + torchcodec = _get_torchcodec() + decoder = torchcodec.decoders.VideoDecoder(self.video_paths[idx]) + num_frames = decoder.metadata.num_frames + fps = decoder.metadata.average_fps + return list(range(num_frames)), fps + + +def _collate_fn(x: T) -> T: + """ + Dummy collate function to be used with _VideoTimestampsDataset + """ + return x + + +class VideoClips: + """ + Given a list of video files, computes all consecutive subvideos of size + `clip_length_in_frames`, where the distance between each subvideo in the + same video is defined by `frames_between_clips`. + If `frame_rate` is specified, it will also resample all the videos to have + the same frame rate, and the clips will refer to this frame rate. + + Creating this instance the first time is time-consuming, as it needs to + decode all the videos in `video_paths`. It is recommended that you + cache the results after instantiation of the class. + + Recreating the clips for different clip lengths is fast, and can be done + with the `compute_clips` method. + + Args: + video_paths (List[str]): paths to the video files + clip_length_in_frames (int): size of a clip in number of frames + frames_between_clips (int): step (in frames) between each clip + frame_rate (float, optional): if specified, it will resample the video + so that it has `frame_rate`, and then the clips will be defined + on the resampled video + num_workers (int): how many subprocesses to use for data loading. + 0 means that the data will be loaded in the main process. (default: 0) + output_format (str): The format of the output video tensors. Can be either "THWC" (default) or "TCHW". + """ + + def __init__( + self, + video_paths: list[str], + clip_length_in_frames: int = 16, + frames_between_clips: int = 1, + frame_rate: Optional[float] = None, + _precomputed_metadata: Optional[dict[str, Any]] = None, + num_workers: int = 0, + _video_width: int = 0, + _video_height: int = 0, + _video_min_dimension: int = 0, + _video_max_dimension: int = 0, + _audio_samples: int = 0, + _audio_channels: int = 0, + output_format: str = "THWC", + ) -> None: + + self.video_paths = video_paths + self.num_workers = num_workers + + # these options are not valid for pyav backend + self._video_width = _video_width + self._video_height = _video_height + self._video_min_dimension = _video_min_dimension + self._video_max_dimension = _video_max_dimension + self._audio_samples = _audio_samples + self._audio_channels = _audio_channels + self.output_format = output_format.upper() + if self.output_format not in ("THWC", "TCHW"): + raise ValueError(f"output_format should be either 'THWC' or 'TCHW', got {output_format}.") + + if _precomputed_metadata is None: + self._compute_frame_pts() + else: + self._init_from_metadata(_precomputed_metadata) + self.compute_clips(clip_length_in_frames, frames_between_clips, frame_rate) + + def _compute_frame_pts(self) -> None: + self.video_pts = [] # len = num_videos. Each entry is a tensor of shape (num_frames_in_video,) + self.video_fps: list[float] = [] # len = num_videos + + # strategy: use a DataLoader to parallelize read_video_timestamps + # so need to create a dummy dataset first + import torch.utils.data + + dl: torch.utils.data.DataLoader = torch.utils.data.DataLoader( + _VideoTimestampsDataset(self.video_paths), # type: ignore[arg-type] + batch_size=16, + num_workers=self.num_workers, + collate_fn=_collate_fn, + ) + + with tqdm(total=len(dl)) as pbar: + for batch in dl: + pbar.update(1) + batch_pts, batch_fps = list(zip(*batch)) + # we need to specify dtype=torch.long because for empty list, + # torch.as_tensor will use torch.float as default dtype. This + # happens when decoding fails and no pts is returned in the list. + batch_pts = [torch.as_tensor(pts, dtype=torch.long) for pts in batch_pts] + self.video_pts.extend(batch_pts) + self.video_fps.extend(batch_fps) + + def _init_from_metadata(self, metadata: dict[str, Any]) -> None: + self.video_paths = metadata["video_paths"] + assert len(self.video_paths) == len(metadata["video_pts"]) + self.video_pts = metadata["video_pts"] + assert len(self.video_paths) == len(metadata["video_fps"]) + self.video_fps = metadata["video_fps"] + + @property + def metadata(self) -> dict[str, Any]: + _metadata = { + "video_paths": self.video_paths, + "video_pts": self.video_pts, + "video_fps": self.video_fps, + } + return _metadata + + def subset(self, indices: list[int]) -> "VideoClips": + video_paths = [self.video_paths[i] for i in indices] + video_pts = [self.video_pts[i] for i in indices] + video_fps = [self.video_fps[i] for i in indices] + metadata = { + "video_paths": video_paths, + "video_pts": video_pts, + "video_fps": video_fps, + } + return type(self)( + video_paths, + clip_length_in_frames=self.num_frames, + frames_between_clips=self.step, + frame_rate=self.frame_rate, + _precomputed_metadata=metadata, + num_workers=self.num_workers, + _video_width=self._video_width, + _video_height=self._video_height, + _video_min_dimension=self._video_min_dimension, + _video_max_dimension=self._video_max_dimension, + _audio_samples=self._audio_samples, + _audio_channels=self._audio_channels, + output_format=self.output_format, + ) + + @staticmethod + def compute_clips_for_video( + video_pts: torch.Tensor, num_frames: int, step: int, fps: Optional[float], frame_rate: Optional[float] = None + ) -> tuple[torch.Tensor, Union[list[slice], torch.Tensor]]: + if fps is None: + # if for some reason the video doesn't have fps (because doesn't have a video stream) + # set the fps to 1. The value doesn't matter, because video_pts is empty anyway + fps = 1 + if frame_rate is None: + frame_rate = fps + total_frames = len(video_pts) * frame_rate / fps + _idxs = VideoClips._resample_video_idx(int(math.floor(total_frames)), fps, frame_rate) + video_pts = video_pts[_idxs] + clips = unfold(video_pts, num_frames, step) + if not clips.numel(): + warnings.warn( + "There aren't enough frames in the current video to get a clip for the given clip length and " + "frames between clips. The video (and potentially others) will be skipped." + ) + idxs: Union[list[slice], torch.Tensor] + if isinstance(_idxs, slice): + idxs = [_idxs] * len(clips) + else: + idxs = unfold(_idxs, num_frames, step) + return clips, idxs + + def compute_clips(self, num_frames: int, step: int, frame_rate: Optional[float] = None) -> None: + """ + Compute all consecutive sequences of clips from video_pts. + Always returns clips of size `num_frames`, meaning that the + last few frames in a video can potentially be dropped. + + Args: + num_frames (int): number of frames for the clip + step (int): distance between two clips + frame_rate (int, optional): The frame rate + """ + self.num_frames = num_frames + self.step = step + self.frame_rate = frame_rate + self.clips = [] + self.resampling_idxs = [] + for video_pts, fps in zip(self.video_pts, self.video_fps): + clips, idxs = self.compute_clips_for_video(video_pts, num_frames, step, fps, frame_rate) + self.clips.append(clips) + self.resampling_idxs.append(idxs) + clip_lengths = torch.as_tensor([len(v) for v in self.clips]) + self.cumulative_sizes = clip_lengths.cumsum(0).tolist() + + def __len__(self) -> int: + return self.num_clips() + + def num_videos(self) -> int: + return len(self.video_paths) + + def num_clips(self) -> int: + """ + Number of subclips that are available in the video list. + """ + return self.cumulative_sizes[-1] + + def get_clip_location(self, idx: int) -> tuple[int, int]: + """ + Converts a flattened representation of the indices into a video_idx, clip_idx + representation. + """ + video_idx = bisect.bisect_right(self.cumulative_sizes, idx) + if video_idx == 0: + clip_idx = idx + else: + clip_idx = idx - self.cumulative_sizes[video_idx - 1] + return video_idx, clip_idx + + @staticmethod + def _resample_video_idx(num_frames: int, original_fps: float, new_fps: float) -> Union[slice, torch.Tensor]: + step = original_fps / new_fps + if step.is_integer(): + # optimization: if step is integer, don't need to perform + # advanced indexing + step = int(step) + return slice(None, None, step) + idxs = torch.arange(num_frames, dtype=torch.float32) * step + idxs = idxs.floor().to(torch.int64) + return idxs + + def get_clip(self, idx: int) -> tuple[torch.Tensor, torch.Tensor, dict[str, Any], int]: + """ + Gets a subclip from a list of videos. + + Args: + idx (int): index of the subclip. Must be between 0 and num_clips(). + + Returns: + video (Tensor) + audio (Tensor) + info (Dict) + video_idx (int): index of the video in `video_paths` + """ + if idx >= self.num_clips(): + raise IndexError(f"Index {idx} out of range ({self.num_clips()} number of clips)") + video_idx, clip_idx = self.get_clip_location(idx) + video_path = self.video_paths[video_idx] + clip_pts = self.clips[video_idx][clip_idx] + + start_idx = int(clip_pts[0].item()) + end_idx = int(clip_pts[-1].item()) + + torchcodec = _get_torchcodec() + + dimension_order = "NHWC" if self.output_format == "THWC" else "NCHW" + decoder = torchcodec.decoders.VideoDecoder(video_path, dimension_order=dimension_order) + video = decoder.get_frames_at(indices=list(range(start_idx, end_idx + 1))).data + + # Audio via TorchCodec + fps = decoder.metadata.average_fps + start_sec = start_idx / fps + end_sec = (end_idx + 1) / fps + try: + audio_decoder = torchcodec.decoders.AudioDecoder(video_path) + audio_samples = audio_decoder.get_samples_played_in_range(start_seconds=start_sec, stop_seconds=end_sec) + audio = audio_samples.data + except Exception: + audio = torch.empty((1, 0), dtype=torch.float32) + + info = {"video_fps": fps} + + if self.frame_rate is not None: + resampling_idx = self.resampling_idxs[video_idx][clip_idx] + if isinstance(resampling_idx, torch.Tensor): + resampling_idx = resampling_idx - resampling_idx[0] + video = video[resampling_idx] + info["video_fps"] = self.frame_rate + assert len(video) == self.num_frames, f"{video.shape} x {self.num_frames}" + + return video, audio, info, video_idx + + def __getstate__(self) -> dict[str, Any]: + video_pts_sizes = [len(v) for v in self.video_pts] + # To be back-compatible, we convert data to dtype torch.long as needed + # because for empty list, in legacy implementation, torch.as_tensor will + # use torch.float as default dtype. This happens when decoding fails and + # no pts is returned in the list. + video_pts = [x.to(torch.int64) for x in self.video_pts] + # video_pts can be an empty list if no frames have been decoded + if video_pts: + video_pts = torch.cat(video_pts) # type: ignore[assignment] + # avoid bug in https://github.com/pytorch/pytorch/issues/32351 + # TODO: Revert it once the bug is fixed. + video_pts = video_pts.numpy() # type: ignore[attr-defined] + + # make a copy of the fields of self + d = self.__dict__.copy() + d["video_pts_sizes"] = video_pts_sizes + d["video_pts"] = video_pts + # delete the following attributes to reduce the size of dictionary. They + # will be re-computed in "__setstate__()" + del d["clips"] + del d["resampling_idxs"] + del d["cumulative_sizes"] + + # for backwards-compatibility + d["_version"] = 2 + return d + + def __setstate__(self, d: dict[str, Any]) -> None: + # for backwards-compatibility + if "_version" not in d: + self.__dict__ = d + return + + video_pts = torch.as_tensor(d["video_pts"], dtype=torch.int64) + video_pts = torch.split(video_pts, d["video_pts_sizes"], dim=0) + # don't need this info anymore + del d["video_pts_sizes"] + + d["video_pts"] = video_pts + self.__dict__ = d + # recompute attributes "clips", "resampling_idxs" and other derivative ones + self.compute_clips(self.num_frames, self.step, self.frame_rate) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/vision.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/vision.py new file mode 100644 index 0000000000000000000000000000000000000000..d26156f03775c61dfae77987dfb523ba9302709e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/vision.py @@ -0,0 +1,113 @@ +import os +from pathlib import Path +from typing import Any, Callable, Optional, TypeVar, Union + +import torch.utils.data as data + +from ..utils import _log_api_usage_once + +T_co = TypeVar("T_co", covariant=True) + + +class VisionDataset(data.Dataset[T_co]): + """ + Base Class For making datasets which are compatible with torchvision. + It is necessary to override the ``__getitem__`` and ``__len__`` method. + + Args: + root (string, optional): Root directory of dataset. Only used for `__repr__`. + transforms (callable, optional): A function/transforms that takes in + an image and a label and returns the transformed versions of both. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + + .. note:: + + :attr:`transforms` and the combination of :attr:`transform` and :attr:`target_transform` are mutually exclusive. + """ + + _repr_indent = 4 + + def __init__( + self, + root: Union[str, Path] = None, # type: ignore[assignment] + transforms: Optional[Callable] = None, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + ) -> None: + _log_api_usage_once(self) + if isinstance(root, str): + root = os.path.expanduser(root) + self.root = root + + has_transforms = transforms is not None + has_separate_transform = transform is not None or target_transform is not None + if has_transforms and has_separate_transform: + raise ValueError("Only transforms or transform/target_transform can be passed as argument") + + # for backwards-compatibility + self.transform = transform + self.target_transform = target_transform + + if has_separate_transform: + transforms = StandardTransform(transform, target_transform) + self.transforms = transforms + + def __getitem__(self, index: int) -> T_co: + """ + Args: + index (int): Index + + Returns: + (Any): Sample and meta data, optionally transformed by the respective transforms. + """ + raise NotImplementedError + + def __len__(self) -> int: + raise NotImplementedError + + def __repr__(self) -> str: + head = "Dataset " + self.__class__.__name__ + body = [f"Number of datapoints: {self.__len__()}"] + if self.root is not None: + body.append(f"Root location: {self.root}") + body += self.extra_repr().splitlines() + if hasattr(self, "transforms") and self.transforms is not None: + body += [repr(self.transforms)] + lines = [head] + [" " * self._repr_indent + line for line in body] + return "\n".join(lines) + + def _format_transform_repr(self, transform: Callable, head: str) -> list[str]: + lines = transform.__repr__().splitlines() + return [f"{head}{lines[0]}"] + ["{}{}".format(" " * len(head), line) for line in lines[1:]] + + def extra_repr(self) -> str: + return "" + + +class StandardTransform: + def __init__(self, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None) -> None: + self.transform = transform + self.target_transform = target_transform + + def __call__(self, input: Any, target: Any) -> tuple[Any, Any]: + if self.transform is not None: + input = self.transform(input) + if self.target_transform is not None: + target = self.target_transform(target) + return input, target + + def _format_transform_repr(self, transform: Callable, head: str) -> list[str]: + lines = transform.__repr__().splitlines() + return [f"{head}{lines[0]}"] + ["{}{}".format(" " * len(head), line) for line in lines[1:]] + + def __repr__(self) -> str: + body = [self.__class__.__name__] + if self.transform is not None: + body += self._format_transform_repr(self.transform, "Transform: ") + if self.target_transform is not None: + body += self._format_transform_repr(self.target_transform, "Target transform: ") + + return "\n".join(body) diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/voc.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/voc.py new file mode 100644 index 0000000000000000000000000000000000000000..6198a93c117b39616df3b792b12fdacbfd3fdd9f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/voc.py @@ -0,0 +1,224 @@ +import collections +import os +from pathlib import Path +from typing import Any, Callable, Optional, Union +from xml.etree.ElementTree import Element as ET_Element + +try: + from defusedxml.ElementTree import parse as ET_parse +except ImportError: + from xml.etree.ElementTree import parse as ET_parse + +from PIL import Image + +from .utils import download_and_extract_archive, verify_str_arg +from .vision import VisionDataset + +DATASET_YEAR_DICT = { + "2012": { + "url": "https://thor.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar", + "filename": "VOCtrainval_11-May-2012.tar", + "md5": "6cd6e144f989b92b3379bac3b3de84fd", + "base_dir": os.path.join("VOCdevkit", "VOC2012"), + }, + "2011": { + "url": "https://thor.robots.ox.ac.uk/pascal/VOC/voc2011/VOCtrainval_25-May-2011.tar", + "filename": "VOCtrainval_25-May-2011.tar", + "md5": "6c3384ef61512963050cb5d687e5bf1e", + "base_dir": os.path.join("TrainVal", "VOCdevkit", "VOC2011"), + }, + "2010": { + "url": "https://thor.robots.ox.ac.uk/pascal/VOC/voc2010/VOCtrainval_03-May-2010.tar", + "filename": "VOCtrainval_03-May-2010.tar", + "md5": "da459979d0c395079b5c75ee67908abb", + "base_dir": os.path.join("VOCdevkit", "VOC2010"), + }, + "2009": { + "url": "https://thor.robots.ox.ac.uk/pascal/VOC/voc2009/VOCtrainval_11-May-2009.tar", + "filename": "VOCtrainval_11-May-2009.tar", + "md5": "a3e00b113cfcfebf17e343f59da3caa1", + "base_dir": os.path.join("VOCdevkit", "VOC2009"), + }, + "2008": { + "url": "https://thor.robots.ox.ac.uk/pascal/VOC/voc2008/VOCtrainval_14-Jul-2008.tar", + "filename": "VOCtrainval_11-May-2012.tar", + "md5": "2629fa636546599198acfcfbfcf1904a", + "base_dir": os.path.join("VOCdevkit", "VOC2008"), + }, + "2007": { + "url": "https://thor.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtrainval_06-Nov-2007.tar", + "filename": "VOCtrainval_06-Nov-2007.tar", + "md5": "c52e279531787c972589f7e41ab4ae64", + "base_dir": os.path.join("VOCdevkit", "VOC2007"), + }, + "2007-test": { + "url": "https://thor.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtest_06-Nov-2007.tar", + "filename": "VOCtest_06-Nov-2007.tar", + "md5": "b6e924de25625d8de591ea690078ad9f", + "base_dir": os.path.join("VOCdevkit", "VOC2007"), + }, +} + + +class _VOCBase(VisionDataset): + _SPLITS_DIR: str + _TARGET_DIR: str + _TARGET_FILE_EXT: str + + def __init__( + self, + root: Union[str, Path], + year: str = "2012", + image_set: str = "train", + download: bool = False, + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + transforms: Optional[Callable] = None, + ): + super().__init__(root, transforms, transform, target_transform) + + self.year = verify_str_arg(year, "year", valid_values=[str(yr) for yr in range(2007, 2013)]) + + valid_image_sets = ["train", "trainval", "val"] + if year == "2007": + valid_image_sets.append("test") + self.image_set = verify_str_arg(image_set, "image_set", valid_image_sets) + + key = "2007-test" if year == "2007" and image_set == "test" else year + dataset_year_dict = DATASET_YEAR_DICT[key] + + self.url = dataset_year_dict["url"] + self.filename = dataset_year_dict["filename"] + self.md5 = dataset_year_dict["md5"] + + base_dir = dataset_year_dict["base_dir"] + voc_root = os.path.join(self.root, base_dir) + + if download: + download_and_extract_archive(self.url, self.root, filename=self.filename, md5=self.md5) + + if not os.path.isdir(voc_root): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it") + + splits_dir = os.path.join(voc_root, "ImageSets", self._SPLITS_DIR) + split_f = os.path.join(splits_dir, image_set.rstrip("\n") + ".txt") + with open(os.path.join(split_f)) as f: + file_names = [x.strip() for x in f.readlines()] + + image_dir = os.path.join(voc_root, "JPEGImages") + self.images = [os.path.join(image_dir, x + ".jpg") for x in file_names] + + target_dir = os.path.join(voc_root, self._TARGET_DIR) + self.targets = [os.path.join(target_dir, x + self._TARGET_FILE_EXT) for x in file_names] + + assert len(self.images) == len(self.targets) + + def __len__(self) -> int: + return len(self.images) + + +class VOCSegmentation(_VOCBase): + """`Pascal VOC `_ Segmentation Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of the VOC Dataset. + year (string, optional): The dataset year, supports years ``"2007"`` to ``"2012"``. + image_set (string, optional): Select the image_set to use, ``"train"``, ``"trainval"`` or ``"val"``. If + ``year=="2007"``, can also be ``"test"``. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + transforms (callable, optional): A function/transform that takes input sample and its target as entry + and returns a transformed version. + """ + + _SPLITS_DIR = "Segmentation" + _TARGET_DIR = "SegmentationClass" + _TARGET_FILE_EXT = ".png" + + @property + def masks(self) -> list[str]: + return self.targets + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is the image segmentation. + """ + img = Image.open(self.images[index]).convert("RGB") + target = Image.open(self.masks[index]) + + if self.transforms is not None: + img, target = self.transforms(img, target) + + return img, target + + +class VOCDetection(_VOCBase): + """`Pascal VOC `_ Detection Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory of the VOC Dataset. + year (string, optional): The dataset year, supports years ``"2007"`` to ``"2012"``. + image_set (string, optional): Select the image_set to use, ``"train"``, ``"trainval"`` or ``"val"``. If + ``year=="2007"``, can also be ``"test"``. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + (default: alphabetic indexing of VOC's 20 classes). + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, required): A function/transform that takes in the + target and transforms it. + transforms (callable, optional): A function/transform that takes input sample and its target as entry + and returns a transformed version. + """ + + _SPLITS_DIR = "Main" + _TARGET_DIR = "Annotations" + _TARGET_FILE_EXT = ".xml" + + @property + def annotations(self) -> list[str]: + return self.targets + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is a dictionary of the XML tree. + """ + img = Image.open(self.images[index]).convert("RGB") + target = self.parse_voc_xml(ET_parse(self.annotations[index]).getroot()) + + if self.transforms is not None: + img, target = self.transforms(img, target) + + return img, target + + @staticmethod + def parse_voc_xml(node: ET_Element) -> dict[str, Any]: + voc_dict: dict[str, Any] = {} + children = list(node) + if children: + def_dic: dict[str, Any] = collections.defaultdict(list) + for dc in map(VOCDetection.parse_voc_xml, children): + for ind, v in dc.items(): + def_dic[ind].append(v) + if node.tag == "annotation": + def_dic["object"] = [def_dic["object"]] + voc_dict = {node.tag: {ind: v[0] if len(v) == 1 else v for ind, v in def_dic.items()}} + if node.text: + text = node.text.strip() + if not children: + voc_dict[node.tag] = text + return voc_dict diff --git a/.venv/lib/python3.12/site-packages/torchvision/datasets/widerface.py b/.venv/lib/python3.12/site-packages/torchvision/datasets/widerface.py new file mode 100644 index 0000000000000000000000000000000000000000..31ab28ebdba2660ba5ec0a16b19361ad30a8a692 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/datasets/widerface.py @@ -0,0 +1,196 @@ +import os +from os.path import abspath, expanduser +from pathlib import Path + +from typing import Any, Callable, Optional, Union + +import torch +from PIL import Image + +from .utils import download_and_extract_archive, download_file_from_google_drive, extract_archive, verify_str_arg +from .vision import VisionDataset + + +class WIDERFace(VisionDataset): + """`WIDERFace `_ Dataset. + + Args: + root (str or ``pathlib.Path``): Root directory where images and annotations are downloaded to. + Expects the following folder structure if download=False: + + .. code:: + + + └── widerface + ├── wider_face_split ('wider_face_split.zip' if compressed) + ├── WIDER_train ('WIDER_train.zip' if compressed) + ├── WIDER_val ('WIDER_val.zip' if compressed) + └── WIDER_test ('WIDER_test.zip' if compressed) + split (string): The dataset split to use. One of {``train``, ``val``, ``test``}. + Defaults to ``train``. + transform (callable, optional): A function/transform that takes in a PIL image + and returns a transformed version. E.g, ``transforms.RandomCrop`` + target_transform (callable, optional): A function/transform that takes in the + target and transforms it. + download (bool, optional): If true, downloads the dataset from the internet and + puts it in root directory. If dataset is already downloaded, it is not + downloaded again. + + .. warning:: + + To download the dataset `gdown `_ is required. + + """ + + BASE_FOLDER = "widerface" + FILE_LIST = [ + # File ID MD5 Hash Filename + ("15hGDLhsx8bLgLcIRD5DhYt5iBxnjNF1M", "3fedf70df600953d25982bcd13d91ba2", "WIDER_train.zip"), + ("1GUCogbp16PMGa39thoMMeWxp7Rp5oM8Q", "dfa7d7e790efa35df3788964cf0bbaea", "WIDER_val.zip"), + ("1HIfDbVEWKmsYKJZm4lchTBDLW5N7dY5T", "e5d8f4248ed24c334bbd12f49c29dd40", "WIDER_test.zip"), + ] + ANNOTATIONS_FILE = ( + "http://shuoyang1213.me/WIDERFACE/support/bbx_annotation/wider_face_split.zip", + "0e3767bcf0e326556d407bf5bff5d27c", + "wider_face_split.zip", + ) + + def __init__( + self, + root: Union[str, Path], + split: str = "train", + transform: Optional[Callable] = None, + target_transform: Optional[Callable] = None, + download: bool = False, + ) -> None: + super().__init__( + root=os.path.join(root, self.BASE_FOLDER), transform=transform, target_transform=target_transform + ) + # check arguments + self.split = verify_str_arg(split, "split", ("train", "val", "test")) + + if download: + self.download() + + if not self._check_integrity(): + raise RuntimeError("Dataset not found or corrupted. You can use download=True to download and prepare it") + + self.img_info: list[dict[str, Union[str, dict[str, torch.Tensor]]]] = [] + if self.split in ("train", "val"): + self.parse_train_val_annotations_file() + else: + self.parse_test_annotations_file() + + def __getitem__(self, index: int) -> tuple[Any, Any]: + """ + Args: + index (int): Index + + Returns: + tuple: (image, target) where target is a dict of annotations for all faces in the image. + target=None for the test split. + """ + + # stay consistent with other datasets and return a PIL Image + img = Image.open(self.img_info[index]["img_path"]) # type: ignore[arg-type] + + if self.transform is not None: + img = self.transform(img) + + target = None if self.split == "test" else self.img_info[index]["annotations"] + if self.target_transform is not None: + target = self.target_transform(target) + + return img, target + + def __len__(self) -> int: + return len(self.img_info) + + def extra_repr(self) -> str: + lines = ["Split: {split}"] + return "\n".join(lines).format(**self.__dict__) + + def parse_train_val_annotations_file(self) -> None: + filename = "wider_face_train_bbx_gt.txt" if self.split == "train" else "wider_face_val_bbx_gt.txt" + filepath = os.path.join(self.root, "wider_face_split", filename) + + with open(filepath) as f: + lines = f.readlines() + file_name_line, num_boxes_line, box_annotation_line = True, False, False + num_boxes, box_counter = 0, 0 + labels = [] + for line in lines: + line = line.rstrip() + if file_name_line: + img_path = os.path.join(self.root, "WIDER_" + self.split, "images", line) + img_path = abspath(expanduser(img_path)) + file_name_line = False + num_boxes_line = True + elif num_boxes_line: + num_boxes = int(line) + num_boxes_line = False + box_annotation_line = True + elif box_annotation_line: + box_counter += 1 + line_split = line.split(" ") + line_values = [int(x) for x in line_split] + labels.append(line_values) + if box_counter >= num_boxes: + box_annotation_line = False + file_name_line = True + labels_tensor = torch.tensor(labels) + self.img_info.append( + { + "img_path": img_path, + "annotations": { + "bbox": labels_tensor[:, 0:4].clone(), # x, y, width, height + "blur": labels_tensor[:, 4].clone(), + "expression": labels_tensor[:, 5].clone(), + "illumination": labels_tensor[:, 6].clone(), + "occlusion": labels_tensor[:, 7].clone(), + "pose": labels_tensor[:, 8].clone(), + "invalid": labels_tensor[:, 9].clone(), + }, + } + ) + box_counter = 0 + labels.clear() + else: + raise RuntimeError(f"Error parsing annotation file {filepath}") + + def parse_test_annotations_file(self) -> None: + filepath = os.path.join(self.root, "wider_face_split", "wider_face_test_filelist.txt") + filepath = abspath(expanduser(filepath)) + with open(filepath) as f: + lines = f.readlines() + for line in lines: + line = line.rstrip() + img_path = os.path.join(self.root, "WIDER_test", "images", line) + img_path = abspath(expanduser(img_path)) + self.img_info.append({"img_path": img_path}) + + def _check_integrity(self) -> bool: + # Allow original archive to be deleted (zip). Only need the extracted images + all_files = self.FILE_LIST.copy() + all_files.append(self.ANNOTATIONS_FILE) + for _, md5, filename in all_files: + file, ext = os.path.splitext(filename) + extracted_dir = os.path.join(self.root, file) + if not os.path.exists(extracted_dir): + return False + return True + + def download(self) -> None: + if self._check_integrity(): + return + + # download and extract image data + for file_id, md5, filename in self.FILE_LIST: + download_file_from_google_drive(file_id, self.root, filename, md5) + filepath = os.path.join(self.root, filename) + extract_archive(filepath) + + # download and extract annotation files + download_and_extract_archive( + url=self.ANNOTATIONS_FILE[0], download_root=self.root, md5=self.ANNOTATIONS_FILE[1] + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/extension.py b/.venv/lib/python3.12/site-packages/torchvision/extension.py new file mode 100644 index 0000000000000000000000000000000000000000..ddac86e70b6329f9ff50b62284769cdd931411f8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/extension.py @@ -0,0 +1,76 @@ +import os + +import torch + +from ._internally_replaced_utils import _get_extension_path + + +def _load_library(lib_name): + """Load a library, optionally warning on failure based on env variable. + + Returns True if the library was loaded successfully, False otherwise. + """ + try: + lib_path = _get_extension_path(lib_name) + torch.ops.load_library(lib_path) + return True + except (ImportError, OSError) as e: + if os.environ.get("TORCHVISION_WARN_WHEN_EXTENSION_LOADING_FAILS"): + import warnings + + warnings.warn(f"Failed to load '{lib_name}' extension: {type(e).__name__}: {e}") + return False + + +def _has_ops(): + return False + + +if _load_library("_C_stable"): + + def _has_ops(): # noqa: F811 + return True + + +def _assert_has_ops(): + if not _has_ops(): + raise RuntimeError( + "Couldn't load custom C++ ops. This can happen if your PyTorch and " + "torchvision versions are incompatible, or if you had errors while compiling " + "torchvision from source. For further information on the compatible versions, check " + "https://github.com/pytorch/vision#installation for the compatibility matrix. " + "Please check your PyTorch version with torch.__version__ and your torchvision " + "version with torchvision.__version__ and verify if they are compatible, and if not " + "please reinstall torchvision so that it matches your PyTorch install. " + "Set TORCHVISION_WARN_WHEN_EXTENSION_LOADING_FAILS=1 and retry to get more details." + ) + + +def _check_cuda_version(): + """ + Make sure that CUDA versions match between the pytorch install and torchvision install + """ + if not _has_ops(): + return -1 + from torch.version import cuda as torch_version_cuda + + _version = torch.ops.torchvision._cuda_version() + if _version != -1 and torch_version_cuda is not None: + tv_version = str(_version) + assert int(tv_version) >= 12000, f"Unexpected CUDA version {_version}, please file a bug report." + tv_major = int(tv_version[0:2]) + tv_minor = int(tv_version[3]) + t_version = torch_version_cuda.split(".") + t_major = int(t_version[0]) + t_minor = int(t_version[1]) + if t_major != tv_major: + raise RuntimeError( + "Detected that PyTorch and torchvision were compiled with different CUDA major versions. " + f"PyTorch has CUDA Version={t_major}.{t_minor} and torchvision has " + f"CUDA Version={tv_major}.{tv_minor}. " + "Please reinstall the torchvision that matches your PyTorch install." + ) + return _version + + +_check_cuda_version() diff --git a/.venv/lib/python3.12/site-packages/torchvision/image_stable.so b/.venv/lib/python3.12/site-packages/torchvision/image_stable.so new file mode 100644 index 0000000000000000000000000000000000000000..e151a4dc2f73979a2c39af5d6ad24d26eab20593 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/image_stable.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f714955fb14b16204b826552eb217152a7a7059a439dc4e00853655503a8934 +size 228913 diff --git a/.venv/lib/python3.12/site-packages/torchvision/io/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..02e28e107c6068ee5d2b55a2a2278059263e27a9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/io/__init__.py @@ -0,0 +1,65 @@ +# In fbcode, import from the fb-only location +# For OSS, these imports would fail (video_reader not available) +try: + from pytorch.vision.fb.io import ( # type: ignore[import-not-found] + _HAS_CPU_VIDEO_DECODER, + _HAS_VIDEO_OPT, + _probe_video_from_file, + _probe_video_from_memory, + _read_video_from_file, + _read_video_from_memory, + _read_video_timestamps_from_file, + _read_video_timestamps_from_memory, + _video_opt, + Timebase, + VideoMetaData, + VideoReader, + ) +except ImportError: + pass + +try: + from pytorch.vision.fb.io.video import ( # type: ignore[import-not-found] + read_video, + read_video_timestamps, + write_video, + ) +except ImportError: + pass + +from .image import ( + decode_avif, + decode_gif, + decode_heic, + decode_image, + decode_jpeg, + decode_png, + decode_webp, + encode_jpeg, + encode_png, + ImageReadMode, + read_file, + read_image, + write_file, + write_jpeg, + write_png, +) + + +__all__ = [ + "ImageReadMode", + "decode_image", + "decode_jpeg", + "decode_png", + "decode_avif", + "decode_heic", + "decode_webp", + "decode_gif", + "encode_jpeg", + "encode_png", + "read_file", + "read_image", + "write_file", + "write_jpeg", + "write_png", +] diff --git a/.venv/lib/python3.12/site-packages/torchvision/io/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/io/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c966b152587d9fd98588dd562f6a5d00bd8b14fd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/io/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/io/__pycache__/_video_deprecation_warning.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/io/__pycache__/_video_deprecation_warning.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da5a44a640b3d784bd7eb0e58ec05d82aef29f1b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/io/__pycache__/_video_deprecation_warning.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/io/__pycache__/image.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/io/__pycache__/image.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d17b88fcbdc1c2ced41ebcfa128ce8297d2431c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/io/__pycache__/image.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/io/__pycache__/video.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/io/__pycache__/video.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..107f7f647f3332727f10a95ddda3c2916caf71fd Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/io/__pycache__/video.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/io/_video_deprecation_warning.py b/.venv/lib/python3.12/site-packages/torchvision/io/_video_deprecation_warning.py new file mode 100644 index 0000000000000000000000000000000000000000..6e18dc0916d9012a1dc7c5968a4f75c41c0fbd31 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/io/_video_deprecation_warning.py @@ -0,0 +1,16 @@ +import warnings + +import torch + + +def _raise_video_deprecation_warning(): + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + warnings.warn( + "The video decoding and encoding capabilities of torchvision " + "are deprecated from version 0.22 and will be removed in version 0.24. " + "We recommend that you migrate to TorchCodec, where we'll consolidate " + "the future decoding/encoding capabilities of PyTorch: " + "https://github.com/pytorch/torchcodec", + UserWarning, + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/io/image.py b/.venv/lib/python3.12/site-packages/torchvision/io/image.py new file mode 100644 index 0000000000000000000000000000000000000000..a342cad5b2099ee19d33dee3838df4f542c1c336 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/io/image.py @@ -0,0 +1,721 @@ +import warnings +from enum import Enum +from typing import Union + +import torch + +from ..extension import _load_library +from ..utils import _log_api_usage_once + + +def _has_image_ops(): + return False + + +if _load_library("image_stable"): + + def _has_image_ops(): # noqa: F811 + return True + + +_DEPRECATION_MSG = ( + "The image decoding and encoding capabilities of TorchVision are deprecated " + "since torchvision 0.29 and will be removed in a future release. They are " + "superseded by the more complete decoders and encoders of TorchCodec (from " + "torchcodec 0.16). Please see " + "https://meta-pytorch.org/torchcodec/0.16/generated_examples/migration/torchvision_migration.html " + "on how to migrate your code." +) + + +def _warn_deprecated(): + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + warnings.warn(_DEPRECATION_MSG, DeprecationWarning) + + +def _assert_has_image_ops(): + if not _has_image_ops(): + raise RuntimeError( + "Couldn't load the image extension. " + "If you built torchvision from source, make sure libjpeg and libpng were found. " + "Set TORCHVISION_WARN_WHEN_EXTENSION_LOADING_FAILS=1 and retry to get more details." + ) + + +class ImageReadMode(Enum): + """[DEPRECATED] Use TorchCodec instead. + + Allow automatic conversion to RGB, RGBA, etc while decoding. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + .. note:: + + You don't need to use this struct, you can just pass strings to all + ``mode`` parameters, e.g. ``mode="RGB"``. + + The different available modes are the following. + + - UNCHANGED: loads the image as-is + - RGB: converts to RGB + - RGBA: converts to RGB with transparency (also aliased as RGB_ALPHA) + - GRAY: converts to grayscale + - GRAY_ALPHA: converts to grayscale with transparency + + .. note:: + + Some decoders won't support all possible values, e.g. GRAY and + GRAY_ALPHA are only supported for PNG and JPEG images. + """ + + UNCHANGED = 0 + GRAY = 1 + GRAY_ALPHA = 2 + RGB = 3 + RGB_ALPHA = 4 + RGBA = RGB_ALPHA # Alias for convenience + + +def read_file(path: str) -> torch.Tensor: + """[DEPRECATED] Use TorchCodec instead. + + Return the bytes contents of a file as a uint8 1D Tensor. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + Args: + path (str or ``pathlib.Path``): the path to the file to be read + + Returns: + data (Tensor) + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(read_file) + _warn_deprecated() + _assert_has_image_ops() + data = torch.ops.image.read_file(str(path)) + return data + + +def write_file(filename: str, data: torch.Tensor) -> torch.Tensor: + """[DEPRECATED] Use TorchCodec instead. + + Write the content of an uint8 1D tensor to a file. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + Args: + filename (str or ``pathlib.Path``): the path to the file to be written + data (Tensor): the contents to be written to the output file + + Returns: + data (Tensor): the input data, returned as-is. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(write_file) + _warn_deprecated() + _assert_has_image_ops() + return torch.ops.image.write_file(str(filename), data) + + +def decode_png( + input: torch.Tensor, + mode: ImageReadMode = ImageReadMode.UNCHANGED, + apply_exif_orientation: bool = False, +) -> torch.Tensor: + """[DEPRECATED] Use TorchCodec instead. + + Decodes a PNG image into a 3 dimensional RGB or grayscale Tensor. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + The values of the output tensor are in uint8 in [0, 255] for most cases. If + the image is a 16-bit png, then the output tensor is uint16 in [0, 65535] + (supported from torchvision ``0.21``). Since uint16 support is limited in + pytorch, we recommend calling + :func:`torchvision.transforms.v2.functional.to_dtype()` with ``scale=True`` + after this function to convert the decoded image into a uint8 or float + tensor. + + Args: + input (Tensor[1]): a one dimensional uint8 tensor containing + the raw bytes of the PNG image. + mode (str or ImageReadMode): The mode to convert the image to, e.g. "RGB". + Default is "UNCHANGED". See :class:`~torchvision.io.ImageReadMode` + for available modes. + apply_exif_orientation (bool): apply EXIF orientation transformation to the output tensor. + Default: False. + + Returns: + output (Tensor[image_channels, image_height, image_width]) + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(decode_png) + _warn_deprecated() + _assert_has_image_ops() + if isinstance(mode, str): + mode = ImageReadMode[mode.upper()] + output = torch.ops.image.decode_png(input, mode.value, apply_exif_orientation) + return output + + +def encode_png(input: torch.Tensor, compression_level: int = 6) -> torch.Tensor: + """[DEPRECATED] Use TorchCodec instead. + + Takes an input tensor in CHW layout and returns a buffer with the contents + of its corresponding PNG file. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + Args: + input (Tensor[channels, image_height, image_width]): int8 image tensor of + ``c`` channels, where ``c`` must 3 or 1. + compression_level (int): Compression factor for the resulting file, it must be a number + between 0 and 9. Default: 6 + + Returns: + Tensor[1]: A one dimensional int8 tensor that contains the raw bytes of the + PNG file. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(encode_png) + _warn_deprecated() + _assert_has_image_ops() + output = torch.ops.image.encode_png(input, compression_level) + return output + + +def write_png(input: torch.Tensor, filename: str, compression_level: int = 6) -> torch.Tensor: + """[DEPRECATED] Use TorchCodec instead. + + Takes an input tensor in CHW layout (or HW in the case of grayscale images) + and saves it in a PNG file. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + Args: + input (Tensor[channels, image_height, image_width]): int8 image tensor of + ``c`` channels, where ``c`` must be 1 or 3. + filename (str or ``pathlib.Path``): Path to save the image. + compression_level (int): Compression factor for the resulting file, it must be a number + between 0 and 9. Default: 6 + + Returns: + output (Tensor): the PNG-encoded data that was written to the file. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(write_png) + _warn_deprecated() + output = encode_png(input, compression_level) + return write_file(filename, output) + + +def decode_jpeg( + input: Union[torch.Tensor, list[torch.Tensor]], + mode: ImageReadMode = ImageReadMode.UNCHANGED, + device: Union[str, torch.device] = "cpu", + apply_exif_orientation: bool = False, +) -> Union[torch.Tensor, list[torch.Tensor]]: + """[DEPRECATED] Use TorchCodec instead. + + Decode JPEG image(s) into 3D RGB or grayscale Tensor(s), on CPU or CUDA. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + The values of the output tensor are uint8 between 0 and 255. + + .. note:: + When using a CUDA device, passing a list of tensors is more efficient than repeated individual calls to ``decode_jpeg``. + When using CPU the performance is equivalent. + The CUDA version of this function has explicitly been designed with thread-safety in mind. + This function does not return partial results in case of an error. + + Args: + input (Tensor[1] or list[Tensor[1]]): a (list of) one dimensional uint8 tensor(s) containing + the raw bytes of the JPEG image. The tensor(s) must be on CPU, + regardless of the ``device`` parameter. + mode (str or ImageReadMode): The mode to convert the image to, e.g. "RGB". + Default is "UNCHANGED". See :class:`~torchvision.io.ImageReadMode` + for available modes. + device (str or torch.device): The device on which the decoded image will + be stored. If a cuda device is specified, the image will be decoded + with `nvjpeg `_. + + .. betastatus:: device parameter + + apply_exif_orientation (bool): apply EXIF orientation transformation to the output tensor. + Default: False. Only implemented for JPEG format on CPU. + + Returns: + output (Tensor[image_channels, image_height, image_width] or list[Tensor[image_channels, image_height, image_width]]): + The values of the output tensor(s) are uint8 between 0 and 255. + ``output.device`` will be set to the specified ``device`` + + + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(decode_jpeg) + _warn_deprecated() + _assert_has_image_ops() + if isinstance(device, str): + device = torch.device(device) + if isinstance(mode, str): + mode = ImageReadMode[mode.upper()] + + if isinstance(input, list): + if len(input) == 0: + raise ValueError("Input list must contain at least one element") + if not all(isinstance(t, torch.Tensor) for t in input): + raise ValueError("All elements of the input list must be tensors.") + if not all(t.device.type == "cpu" for t in input): + raise ValueError("Input list must contain tensors on CPU.") + if device.type == "cuda": + return torch.ops.image.decode_jpegs_cuda(input, mode.value, device) + else: + return [torch.ops.image.decode_jpeg(img, mode.value, apply_exif_orientation) for img in input] + + else: # input is tensor + if input.device.type != "cpu": + raise ValueError("Input tensor must be a CPU tensor") + if device.type == "cuda": + return torch.ops.image.decode_jpegs_cuda([input], mode.value, device)[0] + else: + return torch.ops.image.decode_jpeg(input, mode.value, apply_exif_orientation) + + +def encode_jpeg( + input: Union[torch.Tensor, list[torch.Tensor]], quality: int = 75 +) -> Union[torch.Tensor, list[torch.Tensor]]: + """[DEPRECATED] Use TorchCodec instead. + + Encode RGB tensor(s) into raw encoded jpeg bytes, on CPU or CUDA. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + .. note:: + Passing a list of CUDA tensors is more efficient than repeated individual calls to ``encode_jpeg``. + For CPU tensors the performance is equivalent. + + Args: + input (Tensor[channels, image_height, image_width] or List[Tensor[channels, image_height, image_width]]): + (list of) uint8 image tensor(s) of ``c`` channels, where ``c`` must be 1 or 3 + quality (int): Quality of the resulting JPEG file(s). Must be a number between + 1 and 100. Default: 75 + + Returns: + output (Tensor[1] or list[Tensor[1]]): A (list of) one dimensional uint8 tensor(s) that contain the raw bytes of the JPEG file. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(encode_jpeg) + _warn_deprecated() + _assert_has_image_ops() + if quality < 1 or quality > 100: + raise ValueError("Image quality should be a positive number between 1 and 100") + if isinstance(input, list): + if not input: + raise ValueError("encode_jpeg requires at least one input tensor when a list is passed") + if input[0].device.type == "cuda": + return torch.ops.image.encode_jpegs_cuda(input, quality) + else: + return [torch.ops.image.encode_jpeg(image, quality) for image in input] + else: # single input tensor + if input.device.type == "cuda": + return torch.ops.image.encode_jpegs_cuda([input], quality)[0] + else: + return torch.ops.image.encode_jpeg(input, quality) + + +def write_jpeg(input: torch.Tensor, filename: str, quality: int = 75) -> torch.Tensor: + """[DEPRECATED] Use TorchCodec instead. + + Takes an input tensor in CHW layout and saves it in a JPEG file. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + Args: + input (Tensor[channels, image_height, image_width]): int8 image tensor of ``c`` + channels, where ``c`` must be 1 or 3. + filename (str or ``pathlib.Path``): Path to save the image. + quality (int): Quality of the resulting JPEG file, it must be a number + between 1 and 100. Default: 75 + + Returns: + output (Tensor): the JPEG-encoded data that was written to the file. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(write_jpeg) + _warn_deprecated() + output = encode_jpeg(input, quality) + assert isinstance(output, torch.Tensor) # Needed for torchscript + return write_file(filename, output) + + +def decode_image( + input: Union[torch.Tensor, str], + mode: ImageReadMode = ImageReadMode.UNCHANGED, + apply_exif_orientation: bool = False, +) -> torch.Tensor: + """[DEPRECATED] Use TorchCodec instead. + + Decode an image into a uint8 tensor, from a path or from raw encoded bytes. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + Currently supported image formats are jpeg, png, gif and webp. + + The values of the output tensor are in uint8 in [0, 255] for most cases. + + If the image is a 16-bit png, then the output tensor is uint16 in [0, 65535] + (supported from torchvision ``0.21``). Since uint16 support is limited in + pytorch, we recommend calling + :func:`torchvision.transforms.v2.functional.to_dtype()` with ``scale=True`` + after this function to convert the decoded image into a uint8 or float + tensor. + + .. note:: + + ``decode_image()`` doesn't work yet on AVIF or HEIC images. For these + formats, directly call :func:`~torchvision.io.decode_avif` or + :func:`~torchvision.io.decode_heic`. + + Args: + input (Tensor or str or ``pathlib.Path``): The image to decode. If a + tensor is passed, it must be one dimensional uint8 tensor containing + the raw bytes of the image. Otherwise, this must be a path to the image file. + mode (str or ImageReadMode): The mode to convert the image to, e.g. "RGB". + Default is "UNCHANGED". See :class:`~torchvision.io.ImageReadMode` + for available modes. + apply_exif_orientation (bool): apply EXIF orientation transformation to the output tensor. + Only applies to JPEG and PNG images. Default: False. + + Returns: + output (Tensor[image_channels, image_height, image_width]) + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(decode_image) + _warn_deprecated() + _assert_has_image_ops() + if not isinstance(input, torch.Tensor): + input = read_file(str(input)) + if isinstance(mode, str): + mode = ImageReadMode[mode.upper()] + output = torch.ops.image.decode_image(input, mode.value, apply_exif_orientation) + return output + + +def read_image( + path: str, + mode: ImageReadMode = ImageReadMode.UNCHANGED, + apply_exif_orientation: bool = False, +) -> torch.Tensor: + """[DEPRECATED] Use TorchCodec instead. + + [OBSOLETE] Use :func:`~torchvision.io.decode_image` instead. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(read_image) + _warn_deprecated() + data = read_file(path) + return decode_image(data, mode, apply_exif_orientation=apply_exif_orientation) + + +def decode_gif(input: torch.Tensor) -> torch.Tensor: + """[DEPRECATED] Use TorchCodec instead. + + Decode a GIF image into a 3 or 4 dimensional RGB Tensor. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + The values of the output tensor are uint8 between 0 and 255. + The output tensor has shape ``(C, H, W)`` if there is only one image in the + GIF, and ``(N, C, H, W)`` if there are ``N`` images. + + Args: + input (Tensor[1]): a one dimensional contiguous uint8 tensor containing + the raw bytes of the GIF image. + + Returns: + output (Tensor[image_channels, image_height, image_width] or Tensor[num_images, image_channels, image_height, image_width]) + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(decode_gif) + _warn_deprecated() + _assert_has_image_ops() + return torch.ops.image.decode_gif(input) + + +def decode_webp( + input: torch.Tensor, + mode: ImageReadMode = ImageReadMode.UNCHANGED, +) -> torch.Tensor: + """[DEPRECATED] Use TorchCodec instead. + + Decode a WEBP image into a 3 dimensional RGB[A] Tensor. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + The values of the output tensor are uint8 between 0 and 255. + + Args: + input (Tensor[1]): a one dimensional contiguous uint8 tensor containing + the raw bytes of the WEBP image. + mode (str or ImageReadMode): The mode to convert the image to, e.g. "RGB". + Default is "UNCHANGED". See :class:`~torchvision.io.ImageReadMode` + for available modes. + + Returns: + Decoded image (Tensor[image_channels, image_height, image_width]) + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(decode_webp) + _warn_deprecated() + _assert_has_image_ops() + if isinstance(mode, str): + mode = ImageReadMode[mode.upper()] + return torch.ops.image.decode_webp(input, mode.value) + + +# TODO_AVIF_HEIC: Better support for torchscript. Scripting decode_avif of +# decode_heic currently fails, mainly because of the logic +# _load_extra_decoders_once() (using global variables, try/except statements, +# etc.). +# The ops (torch.ops.extra_decoders_ns.decode_*) are otherwise torchscript-able, +# and users who need torchscript can always just wrap those. + +# TODO_AVIF_HEIC: decode_image() should work for those. The key technical issue +# we have here is that the format detection logic of decode_image() is +# implemented in torchvision, and torchvision has zero knowledge of +# torchvision-extra-decoders, so we cannot call the AVIF/HEIC C++ decoders +# (those in torchvision-extra-decoders) from there. +# A trivial check that could be done within torchvision would be to check the +# file extension, if a path was passed. We could also just implement the +# AVIF/HEIC detection logic in Python as a fallback, if the file detection +# didn't find any format. In any case: properly determining whether a file is +# HEIC is far from trivial, and relying on libmagic would probably be best + + +_EXTRA_DECODERS_ALREADY_LOADED = False + + +def _load_extra_decoders_once(): + global _EXTRA_DECODERS_ALREADY_LOADED + if _EXTRA_DECODERS_ALREADY_LOADED: + return + + try: + import torchvision_extra_decoders + + # torchvision-extra-decoders only supports linux for now. BUT, users on + # e.g. MacOS can still install it: they will get the pure-python + # 0.0.0.dev version: + # https://pypi.org/project/torchvision-extra-decoders/0.0.0.dev0, which + # is a dummy version that was created to reserve the namespace on PyPI. + # We have to check that expose_extra_decoders() exists for those users, + # so we can properly error on non-Linux archs. + assert hasattr(torchvision_extra_decoders, "expose_extra_decoders") + except (AssertionError, ImportError) as e: + raise RuntimeError( + "In order to enable the AVIF and HEIC decoding capabilities of " + "torchvision, you need to `pip install torchvision-extra-decoders`. " + "Just install the package, you don't need to update your code. " + "This is only supported on Linux, and this feature is still in BETA stage. " + "Please let us know of any issue: https://github.com/pytorch/vision/issues/new/choose. " + "Note that `torchvision-extra-decoders` is released under the LGPL license. " + ) from e + + # This will expose torch.ops.extra_decoders_ns.decode_avif and torch.ops.extra_decoders_ns.decode_heic + torchvision_extra_decoders.expose_extra_decoders() + + _EXTRA_DECODERS_ALREADY_LOADED = True + + +def decode_avif(input: torch.Tensor, mode: ImageReadMode = ImageReadMode.UNCHANGED) -> torch.Tensor: + """[DEPRECATED] Use TorchCodec instead. + + Decode an AVIF image into a 3 dimensional RGB[A] Tensor. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + .. warning:: + In order to enable the AVIF decoding capabilities of torchvision, you + first need to run ``pip install torchvision-extra-decoders``. Just + install the package, you don't need to update your code. This is only + supported on Linux, and this feature is still in BETA stage. Please let + us know of any issue: + https://github.com/pytorch/vision/issues/new/choose. Note that + `torchvision-extra-decoders + `_ is + released under the LGPL license. + + The values of the output tensor are in uint8 in [0, 255] for most images. If + the image has a bit-depth of more than 8, then the output tensor is uint16 + in [0, 65535]. Since uint16 support is limited in pytorch, we recommend + calling :func:`torchvision.transforms.v2.functional.to_dtype()` with + ``scale=True`` after this function to convert the decoded image into a uint8 + or float tensor. + + Args: + input (Tensor[1]): a one dimensional contiguous uint8 tensor containing + the raw bytes of the AVIF image. + mode (str or ImageReadMode): The mode to convert the image to, e.g. "RGB". + Default is "UNCHANGED". See :class:`~torchvision.io.ImageReadMode` + for available modes. + + Returns: + Decoded image (Tensor[image_channels, image_height, image_width]) + """ + _warn_deprecated() + _load_extra_decoders_once() + if input.dtype != torch.uint8: + raise RuntimeError(f"Input tensor must have uint8 data type, got {input.dtype}") + return torch.ops.extra_decoders_ns.decode_avif(input, mode.value) + + +def decode_heic(input: torch.Tensor, mode: ImageReadMode = ImageReadMode.UNCHANGED) -> torch.Tensor: + """[DEPRECATED] Use TorchCodec instead. + + Decode an HEIC image into a 3 dimensional RGB[A] Tensor. + + .. warning:: + + The image decoding and encoding capabilities of TorchVision are + deprecated since torchvision 0.29 and will be removed in a future + release. They are superseded by the more complete decoders and encoders + of TorchCodec (from torchcodec 0.16). Please see `this migration guide + `__ + on how to migrate your code. + + .. warning:: + In order to enable the HEIC decoding capabilities of torchvision, you + first need to run ``pip install torchvision-extra-decoders``. Just + install the package, you don't need to update your code. This is only + supported on Linux, and this feature is still in BETA stage. Please let + us know of any issue: + https://github.com/pytorch/vision/issues/new/choose. Note that + `torchvision-extra-decoders + `_ is + released under the LGPL license. + + The values of the output tensor are in uint8 in [0, 255] for most images. If + the image has a bit-depth of more than 8, then the output tensor is uint16 + in [0, 65535]. Since uint16 support is limited in pytorch, we recommend + calling :func:`torchvision.transforms.v2.functional.to_dtype()` with + ``scale=True`` after this function to convert the decoded image into a uint8 + or float tensor. + + Args: + input (Tensor[1]): a one dimensional contiguous uint8 tensor containing + the raw bytes of the HEIC image. + mode (str or ImageReadMode): The mode to convert the image to, e.g. "RGB". + Default is "UNCHANGED". See :class:`~torchvision.io.ImageReadMode` + for available modes. + + Returns: + Decoded image (Tensor[image_channels, image_height, image_width]) + """ + _warn_deprecated() + _load_extra_decoders_once() + if input.dtype != torch.uint8: + raise RuntimeError(f"Input tensor must have uint8 data type, got {input.dtype}") + return torch.ops.extra_decoders_ns.decode_heic(input, mode.value) diff --git a/.venv/lib/python3.12/site-packages/torchvision/io/video.py b/.venv/lib/python3.12/site-packages/torchvision/io/video.py new file mode 100644 index 0000000000000000000000000000000000000000..87fe36f2caa8c125faa7d0f64e986c7b27278c6e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/io/video.py @@ -0,0 +1,23 @@ +# This module re-exports video utilities from the internal fb location. +# The actual implementation lives in pytorch.vision.fb.io.video +from pytorch.vision.fb.io.video import ( # type: ignore[import-not-found] + _align_audio_frames, + _av_available, + _check_av_available, + _read_from_stream, + av, + read_video, + read_video_timestamps, + write_video, +) + +__all__ = [ + "read_video", + "read_video_timestamps", + "write_video", + "_read_from_stream", + "_align_audio_frames", + "_check_av_available", + "_av_available", + "av", +] diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6ea0a1f7178b6ca03776d58c17411a8ff483f8b2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/__init__.py @@ -0,0 +1,23 @@ +from .alexnet import * +from .convnext import * +from .densenet import * +from .efficientnet import * +from .googlenet import * +from .inception import * +from .mnasnet import * +from .mobilenet import * +from .regnet import * +from .resnet import * +from .shufflenetv2 import * +from .squeezenet import * +from .vgg import * +from .vision_transformer import * +from .swin_transformer import * +from .maxvit import * +from . import detection, optical_flow, quantization, segmentation, video + +# The Weights and WeightsEnum are developer-facing utils that we make public for +# downstream libs like torchgeo https://github.com/pytorch/vision/issues/7094 +# TODO: we could / should document them publicly, but it's not clear where, as +# they're not intended for end users. +from ._api import get_model, get_model_builder, get_model_weights, get_weight, list_models, Weights, WeightsEnum diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddbaa3d455d0916fad17bbe3a222c8378d5ed570 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/_api.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e73220a9336714298494b9ff6407a47d406a7d7a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/_api.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/_meta.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/_meta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7712e77ed6604297d3c8ad40770d0dcc4403dba3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/_meta.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..765b73749a9ad8e11fbe510d78b4307e97564589 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/alexnet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/alexnet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03e2bf2e61439483f1b692e71855a842fb758c1e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/alexnet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/convnext.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/convnext.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f84f4b203ffe9929f5b864dfedd6c84a51d910f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/convnext.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/densenet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/densenet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e41f314fbb845ad7c34817e85ba237ee4c8aff9c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/densenet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/efficientnet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/efficientnet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3d95eec3168592aed7e3c8ea44a324415573eb9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/efficientnet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/feature_extraction.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/feature_extraction.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98b9dfd14cd7b4f5c596000a9083f685d42c1cb3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/feature_extraction.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/googlenet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/googlenet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbdf52b764f710df68d04334ef47506b9837f7e0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/googlenet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/inception.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/inception.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6fa1a2c0f0c8c259d7122a0487fb5d504796091 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/inception.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/maxvit.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/maxvit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a0d663196b00082a42f7259f808bec5b4e27301 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/maxvit.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/mnasnet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/mnasnet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57c84567fd31d4f14b656744c31ad68279d150ef Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/mnasnet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/mobilenet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/mobilenet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f89315e9ac2c3da9cba6df9e0b89517e6e8136b8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/mobilenet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/mobilenetv2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/mobilenetv2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9efea0d5caa5b4ad88fd6cdfc528eeb0d2a41ae2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/mobilenetv2.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/mobilenetv3.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/mobilenetv3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee6f4545f42329b2c6c2fe1c17fee3d8440962de Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/mobilenetv3.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/regnet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/regnet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e9529eb1f1f02a6744a3a9b98b9a0e3b83f1c43 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/regnet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/resnet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/resnet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd466138a99292966bf36d6f1d67dbf36b55caef Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/resnet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/shufflenetv2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/shufflenetv2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1207e8c2d2315a80515b2f292153a76838cad277 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/shufflenetv2.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/squeezenet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/squeezenet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ab2185a8caa7a28ddfe9c552c42ed6c24ceff8e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/squeezenet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/swin_transformer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/swin_transformer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..824dce84d19c37f1d54afac447a127897a86a523 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/swin_transformer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/vgg.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/vgg.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b0b861d050656ce4f0db6d98b3b44da82701ebf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/vgg.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/vision_transformer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/vision_transformer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6d340465e61717718cfd2d137bb0da9da128fcb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/__pycache__/vision_transformer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/_api.py b/.venv/lib/python3.12/site-packages/torchvision/models/_api.py new file mode 100644 index 0000000000000000000000000000000000000000..5f46bcb5cd04cffc11ba84dce94754d61507164b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/_api.py @@ -0,0 +1,277 @@ +import fnmatch +import importlib +import inspect +import sys +from collections.abc import Iterable +from dataclasses import dataclass +from enum import Enum +from functools import partial +from inspect import signature +from types import ModuleType +from typing import Any, Callable, get_args, Optional, TypeVar, Union + +from torch import nn + +from .._internally_replaced_utils import load_state_dict_from_url + + +__all__ = ["WeightsEnum", "Weights", "get_model", "get_model_builder", "get_model_weights", "get_weight", "list_models"] + + +@dataclass +class Weights: + """ + This class is used to group important attributes associated with the pre-trained weights. + + Args: + url (str): The location where we find the weights. + transforms (Callable): A callable that constructs the preprocessing method (or validation preset transforms) + needed to use the model. The reason we attach a constructor method rather than an already constructed + object is because the specific object might have memory and thus we want to delay initialization until + needed. + meta (Dict[str, Any]): Stores meta-data related to the weights of the model and its configuration. These can be + informative attributes (for example the number of parameters/flops, recipe link/methods used in training + etc), configuration parameters (for example the `num_classes`) needed to construct the model or important + meta-data (for example the `classes` of a classification model) needed to use the model. + """ + + url: str + transforms: Callable + meta: dict[str, Any] + + def __eq__(self, other: Any) -> bool: + # We need this custom implementation for correct deep-copy and deserialization behavior. + # TL;DR: After the definition of an enum, creating a new instance, i.e. by deep-copying or deserializing it, + # involves an equality check against the defined members. Unfortunately, the `transforms` attribute is often + # defined with `functools.partial` and `fn = partial(...); assert deepcopy(fn) != fn`. Without custom handling + # for it, the check against the defined members would fail and effectively prevent the weights from being + # deep-copied or deserialized. + # See https://github.com/pytorch/vision/pull/7107 for details. + if not isinstance(other, Weights): + return NotImplemented + + if self.url != other.url: + return False + + if self.meta != other.meta: + return False + + if isinstance(self.transforms, partial) and isinstance(other.transforms, partial): + return ( + self.transforms.func == other.transforms.func + and self.transforms.args == other.transforms.args + and self.transforms.keywords == other.transforms.keywords + ) + else: + return self.transforms == other.transforms + + +class WeightsEnum(Enum): + """ + This class is the parent class of all model weights. Each model building method receives an optional `weights` + parameter with its associated pre-trained weights. It inherits from `Enum` and its values should be of type + `Weights`. + + Args: + value (Weights): The data class entry with the weight information. + """ + + @classmethod + def verify(cls, obj: Any) -> Any: + if obj is not None: + if type(obj) is str: + obj = cls[obj.replace(cls.__name__ + ".", "")] + elif not isinstance(obj, cls): + raise TypeError( + f"Invalid Weight class provided; expected {cls.__name__} but received {obj.__class__.__name__}." + ) + return obj + + def get_state_dict(self, *args: Any, **kwargs: Any) -> dict[str, Any]: + return load_state_dict_from_url(self.url, *args, **kwargs) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}.{self._name_}" + + @property + def url(self): + return self.value.url + + @property + def transforms(self): + return self.value.transforms + + @property + def meta(self): + return self.value.meta + + +def get_weight(name: str) -> WeightsEnum: + """ + Gets the weights enum value by its full name. Example: "ResNet50_Weights.IMAGENET1K_V1" + + Args: + name (str): The name of the weight enum entry. + + Returns: + WeightsEnum: The requested weight enum. + """ + try: + enum_name, value_name = name.split(".") + except ValueError: + raise ValueError(f"Invalid weight name provided: '{name}'.") + + base_module_name = ".".join(sys.modules[__name__].__name__.split(".")[:-1]) + base_module = importlib.import_module(base_module_name) + model_modules = [base_module] + [ + x[1] + for x in inspect.getmembers(base_module, inspect.ismodule) + if x[1].__file__.endswith("__init__.py") # type: ignore[union-attr] + ] + + weights_enum = None + for m in model_modules: + potential_class = m.__dict__.get(enum_name, None) + if potential_class is not None and issubclass(potential_class, WeightsEnum): + weights_enum = potential_class + break + + if weights_enum is None: + raise ValueError(f"The weight enum '{enum_name}' for the specific method couldn't be retrieved.") + + return weights_enum[value_name] + + +def get_model_weights(name: Union[Callable, str]) -> type[WeightsEnum]: + """ + Returns the weights enum class associated to the given model. + + Args: + name (callable or str): The model builder function or the name under which it is registered. + + Returns: + weights_enum (WeightsEnum): The weights enum class associated with the model. + """ + model = get_model_builder(name) if isinstance(name, str) else name + return _get_enum_from_fn(model) + + +def _get_enum_from_fn(fn: Callable) -> type[WeightsEnum]: + """ + Internal method that gets the weight enum of a specific model builder method. + + Args: + fn (Callable): The builder method used to create the model. + Returns: + WeightsEnum: The requested weight enum. + """ + sig = signature(fn) + if "weights" not in sig.parameters: + raise ValueError("The method is missing the 'weights' argument.") + + ann = sig.parameters["weights"].annotation + weights_enum = None + if isinstance(ann, type) and issubclass(ann, WeightsEnum): + weights_enum = ann + else: + # handle cases like Union[Optional, T] + for t in get_args(ann): # type: ignore[union-attr] + if isinstance(t, type) and issubclass(t, WeightsEnum): + weights_enum = t + break + + if weights_enum is None: + raise ValueError( + "The WeightsEnum class for the specific method couldn't be retrieved. Make sure the typing info is correct." + ) + + return weights_enum + + +M = TypeVar("M", bound=nn.Module) + +BUILTIN_MODELS = {} + + +def register_model(name: Optional[str] = None) -> Callable[[Callable[..., M]], Callable[..., M]]: + def wrapper(fn: Callable[..., M]) -> Callable[..., M]: + key = name if name is not None else fn.__name__ + if key in BUILTIN_MODELS: + raise ValueError(f"An entry is already registered under the name '{key}'.") + BUILTIN_MODELS[key] = fn + return fn + + return wrapper + + +def list_models( + module: Optional[ModuleType] = None, + include: Union[Iterable[str], str, None] = None, + exclude: Union[Iterable[str], str, None] = None, +) -> list[str]: + """ + Returns a list with the names of registered models. + + Args: + module (ModuleType, optional): The module from which we want to extract the available models. + include (str or Iterable[str], optional): Filter(s) for including the models from the set of all models. + Filters are passed to `fnmatch `__ to match Unix shell-style + wildcards. In case of many filters, the results is the union of individual filters. + exclude (str or Iterable[str], optional): Filter(s) applied after include_filters to remove models. + Filter are passed to `fnmatch `__ to match Unix shell-style + wildcards. In case of many filters, the results is removal of all the models that match any individual filter. + + Returns: + models (list): A list with the names of available models. + """ + all_models = { + k for k, v in BUILTIN_MODELS.items() if module is None or v.__module__.rsplit(".", 1)[0] == module.__name__ + } + if include: + models: set[str] = set() + if isinstance(include, str): + include = [include] + for include_filter in include: + models = models | set(fnmatch.filter(all_models, include_filter)) + else: + models = all_models + + if exclude: + if isinstance(exclude, str): + exclude = [exclude] + for exclude_filter in exclude: + models = models - set(fnmatch.filter(all_models, exclude_filter)) + return sorted(models) + + +def get_model_builder(name: str) -> Callable[..., nn.Module]: + """ + Gets the model name and returns the model builder method. + + Args: + name (str): The name under which the model is registered. + + Returns: + fn (Callable): The model builder method. + """ + name = name.lower() + try: + fn = BUILTIN_MODELS[name] + except KeyError: + raise ValueError(f"Unknown model {name}") + return fn + + +def get_model(name: str, **config: Any) -> nn.Module: + """ + Gets the model name and configuration and returns an instantiated model. + + Args: + name (str): The name under which the model is registered. + **config (Any): parameters passed to the model builder method. + + Returns: + model (nn.Module): The initialized model. + """ + fn = get_model_builder(name) + return fn(**config) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/_meta.py b/.venv/lib/python3.12/site-packages/torchvision/models/_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..e66f411c287e0f456448315ba4fd0bfcce281d2b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/_meta.py @@ -0,0 +1,1554 @@ +""" +This file is part of the private API. Please do not refer to any variables defined here directly as they will be +removed on future versions without warning. +""" + +# This will eventually be replaced with a call at torchvision.datasets.info("imagenet").categories +_IMAGENET_CATEGORIES = [ + "tench", + "goldfish", + "great white shark", + "tiger shark", + "hammerhead", + "electric ray", + "stingray", + "cock", + "hen", + "ostrich", + "brambling", + "goldfinch", + "house finch", + "junco", + "indigo bunting", + "robin", + "bulbul", + "jay", + "magpie", + "chickadee", + "water ouzel", + "kite", + "bald eagle", + "vulture", + "great grey owl", + "European fire salamander", + "common newt", + "eft", + "spotted salamander", + "axolotl", + "bullfrog", + "tree frog", + "tailed frog", + "loggerhead", + "leatherback turtle", + "mud turtle", + "terrapin", + "box turtle", + "banded gecko", + "common iguana", + "American chameleon", + "whiptail", + "agama", + "frilled lizard", + "alligator lizard", + "Gila monster", + "green lizard", + "African chameleon", + "Komodo dragon", + "African crocodile", + "American alligator", + "triceratops", + "thunder snake", + "ringneck snake", + "hognose snake", + "green snake", + "king snake", + "garter snake", + "water snake", + "vine snake", + "night snake", + "boa constrictor", + "rock python", + "Indian cobra", + "green mamba", + "sea snake", + "horned viper", + "diamondback", + "sidewinder", + "trilobite", + "harvestman", + "scorpion", + "black and gold garden spider", + "barn spider", + "garden spider", + "black widow", + "tarantula", + "wolf spider", + "tick", + "centipede", + "black grouse", + "ptarmigan", + "ruffed grouse", + "prairie chicken", + "peacock", + "quail", + "partridge", + "African grey", + "macaw", + "sulphur-crested cockatoo", + "lorikeet", + "coucal", + "bee eater", + "hornbill", + "hummingbird", + "jacamar", + "toucan", + "drake", + "red-breasted merganser", + "goose", + "black swan", + "tusker", + "echidna", + "platypus", + "wallaby", + "koala", + "wombat", + "jellyfish", + "sea anemone", + "brain coral", + "flatworm", + "nematode", + "conch", + "snail", + "slug", + "sea slug", + "chiton", + "chambered nautilus", + "Dungeness crab", + "rock crab", + "fiddler crab", + "king crab", + "American lobster", + "spiny lobster", + "crayfish", + "hermit crab", + "isopod", + "white stork", + "black stork", + "spoonbill", + "flamingo", + "little blue heron", + "American egret", + "bittern", + "crane bird", + "limpkin", + "European gallinule", + "American coot", + "bustard", + "ruddy turnstone", + "red-backed sandpiper", + "redshank", + "dowitcher", + "oystercatcher", + "pelican", + "king penguin", + "albatross", + "grey whale", + "killer whale", + "dugong", + "sea lion", + "Chihuahua", + "Japanese spaniel", + "Maltese dog", + "Pekinese", + "Shih-Tzu", + "Blenheim spaniel", + "papillon", + "toy terrier", + "Rhodesian ridgeback", + "Afghan hound", + "basset", + "beagle", + "bloodhound", + "bluetick", + "black-and-tan coonhound", + "Walker hound", + "English foxhound", + "redbone", + "borzoi", + "Irish wolfhound", + "Italian greyhound", + "whippet", + "Ibizan hound", + "Norwegian elkhound", + "otterhound", + "Saluki", + "Scottish deerhound", + "Weimaraner", + "Staffordshire bullterrier", + "American Staffordshire terrier", + "Bedlington terrier", + "Border terrier", + "Kerry blue terrier", + "Irish terrier", + "Norfolk terrier", + "Norwich terrier", + "Yorkshire terrier", + "wire-haired fox terrier", + "Lakeland terrier", + "Sealyham terrier", + "Airedale", + "cairn", + "Australian terrier", + "Dandie Dinmont", + "Boston bull", + "miniature schnauzer", + "giant schnauzer", + "standard schnauzer", + "Scotch terrier", + "Tibetan terrier", + "silky terrier", + "soft-coated wheaten terrier", + "West Highland white terrier", + "Lhasa", + "flat-coated retriever", + "curly-coated retriever", + "golden retriever", + "Labrador retriever", + "Chesapeake Bay retriever", + "German short-haired pointer", + "vizsla", + "English setter", + "Irish setter", + "Gordon setter", + "Brittany spaniel", + "clumber", + "English springer", + "Welsh springer spaniel", + "cocker spaniel", + "Sussex spaniel", + "Irish water spaniel", + "kuvasz", + "schipperke", + "groenendael", + "malinois", + "briard", + "kelpie", + "komondor", + "Old English sheepdog", + "Shetland sheepdog", + "collie", + "Border collie", + "Bouvier des Flandres", + "Rottweiler", + "German shepherd", + "Doberman", + "miniature pinscher", + "Greater Swiss Mountain dog", + "Bernese mountain dog", + "Appenzeller", + "EntleBucher", + "boxer", + "bull mastiff", + "Tibetan mastiff", + "French bulldog", + "Great Dane", + "Saint Bernard", + "Eskimo dog", + "malamute", + "Siberian husky", + "dalmatian", + "affenpinscher", + "basenji", + "pug", + "Leonberg", + "Newfoundland", + "Great Pyrenees", + "Samoyed", + "Pomeranian", + "chow", + "keeshond", + "Brabancon griffon", + "Pembroke", + "Cardigan", + "toy poodle", + "miniature poodle", + "standard poodle", + "Mexican hairless", + "timber wolf", + "white wolf", + "red wolf", + "coyote", + "dingo", + "dhole", + "African hunting dog", + "hyena", + "red fox", + "kit fox", + "Arctic fox", + "grey fox", + "tabby", + "tiger cat", + "Persian cat", + "Siamese cat", + "Egyptian cat", + "cougar", + "lynx", + "leopard", + "snow leopard", + "jaguar", + "lion", + "tiger", + "cheetah", + "brown bear", + "American black bear", + "ice bear", + "sloth bear", + "mongoose", + "meerkat", + "tiger beetle", + "ladybug", + "ground beetle", + "long-horned beetle", + "leaf beetle", + "dung beetle", + "rhinoceros beetle", + "weevil", + "fly", + "bee", + "ant", + "grasshopper", + "cricket", + "walking stick", + "cockroach", + "mantis", + "cicada", + "leafhopper", + "lacewing", + "dragonfly", + "damselfly", + "admiral", + "ringlet", + "monarch", + "cabbage butterfly", + "sulphur butterfly", + "lycaenid", + "starfish", + "sea urchin", + "sea cucumber", + "wood rabbit", + "hare", + "Angora", + "hamster", + "porcupine", + "fox squirrel", + "marmot", + "beaver", + "guinea pig", + "sorrel", + "zebra", + "hog", + "wild boar", + "warthog", + "hippopotamus", + "ox", + "water buffalo", + "bison", + "ram", + "bighorn", + "ibex", + "hartebeest", + "impala", + "gazelle", + "Arabian camel", + "llama", + "weasel", + "mink", + "polecat", + "black-footed ferret", + "otter", + "skunk", + "badger", + "armadillo", + "three-toed sloth", + "orangutan", + "gorilla", + "chimpanzee", + "gibbon", + "siamang", + "guenon", + "patas", + "baboon", + "macaque", + "langur", + "colobus", + "proboscis monkey", + "marmoset", + "capuchin", + "howler monkey", + "titi", + "spider monkey", + "squirrel monkey", + "Madagascar cat", + "indri", + "Indian elephant", + "African elephant", + "lesser panda", + "giant panda", + "barracouta", + "eel", + "coho", + "rock beauty", + "anemone fish", + "sturgeon", + "gar", + "lionfish", + "puffer", + "abacus", + "abaya", + "academic gown", + "accordion", + "acoustic guitar", + "aircraft carrier", + "airliner", + "airship", + "altar", + "ambulance", + "amphibian", + "analog clock", + "apiary", + "apron", + "ashcan", + "assault rifle", + "backpack", + "bakery", + "balance beam", + "balloon", + "ballpoint", + "Band Aid", + "banjo", + "bannister", + "barbell", + "barber chair", + "barbershop", + "barn", + "barometer", + "barrel", + "barrow", + "baseball", + "basketball", + "bassinet", + "bassoon", + "bathing cap", + "bath towel", + "bathtub", + "beach wagon", + "beacon", + "beaker", + "bearskin", + "beer bottle", + "beer glass", + "bell cote", + "bib", + "bicycle-built-for-two", + "bikini", + "binder", + "binoculars", + "birdhouse", + "boathouse", + "bobsled", + "bolo tie", + "bonnet", + "bookcase", + "bookshop", + "bottlecap", + "bow", + "bow tie", + "brass", + "brassiere", + "breakwater", + "breastplate", + "broom", + "bucket", + "buckle", + "bulletproof vest", + "bullet train", + "butcher shop", + "cab", + "caldron", + "candle", + "cannon", + "canoe", + "can opener", + "cardigan", + "car mirror", + "carousel", + "carpenter's kit", + "carton", + "car wheel", + "cash machine", + "cassette", + "cassette player", + "castle", + "catamaran", + "CD player", + "cello", + "cellular telephone", + "chain", + "chainlink fence", + "chain mail", + "chain saw", + "chest", + "chiffonier", + "chime", + "china cabinet", + "Christmas stocking", + "church", + "cinema", + "cleaver", + "cliff dwelling", + "cloak", + "clog", + "cocktail shaker", + "coffee mug", + "coffeepot", + "coil", + "combination lock", + "computer keyboard", + "confectionery", + "container ship", + "convertible", + "corkscrew", + "cornet", + "cowboy boot", + "cowboy hat", + "cradle", + "crane", + "crash helmet", + "crate", + "crib", + "Crock Pot", + "croquet ball", + "crutch", + "cuirass", + "dam", + "desk", + "desktop computer", + "dial telephone", + "diaper", + "digital clock", + "digital watch", + "dining table", + "dishrag", + "dishwasher", + "disk brake", + "dock", + "dogsled", + "dome", + "doormat", + "drilling platform", + "drum", + "drumstick", + "dumbbell", + "Dutch oven", + "electric fan", + "electric guitar", + "electric locomotive", + "entertainment center", + "envelope", + "espresso maker", + "face powder", + "feather boa", + "file", + "fireboat", + "fire engine", + "fire screen", + "flagpole", + "flute", + "folding chair", + "football helmet", + "forklift", + "fountain", + "fountain pen", + "four-poster", + "freight car", + "French horn", + "frying pan", + "fur coat", + "garbage truck", + "gasmask", + "gas pump", + "goblet", + "go-kart", + "golf ball", + "golfcart", + "gondola", + "gong", + "gown", + "grand piano", + "greenhouse", + "grille", + "grocery store", + "guillotine", + "hair slide", + "hair spray", + "half track", + "hammer", + "hamper", + "hand blower", + "hand-held computer", + "handkerchief", + "hard disc", + "harmonica", + "harp", + "harvester", + "hatchet", + "holster", + "home theater", + "honeycomb", + "hook", + "hoopskirt", + "horizontal bar", + "horse cart", + "hourglass", + "iPod", + "iron", + "jack-o'-lantern", + "jean", + "jeep", + "jersey", + "jigsaw puzzle", + "jinrikisha", + "joystick", + "kimono", + "knee pad", + "knot", + "lab coat", + "ladle", + "lampshade", + "laptop", + "lawn mower", + "lens cap", + "letter opener", + "library", + "lifeboat", + "lighter", + "limousine", + "liner", + "lipstick", + "Loafer", + "lotion", + "loudspeaker", + "loupe", + "lumbermill", + "magnetic compass", + "mailbag", + "mailbox", + "maillot", + "maillot tank suit", + "manhole cover", + "maraca", + "marimba", + "mask", + "matchstick", + "maypole", + "maze", + "measuring cup", + "medicine chest", + "megalith", + "microphone", + "microwave", + "military uniform", + "milk can", + "minibus", + "miniskirt", + "minivan", + "missile", + "mitten", + "mixing bowl", + "mobile home", + "Model T", + "modem", + "monastery", + "monitor", + "moped", + "mortar", + "mortarboard", + "mosque", + "mosquito net", + "motor scooter", + "mountain bike", + "mountain tent", + "mouse", + "mousetrap", + "moving van", + "muzzle", + "nail", + "neck brace", + "necklace", + "nipple", + "notebook", + "obelisk", + "oboe", + "ocarina", + "odometer", + "oil filter", + "organ", + "oscilloscope", + "overskirt", + "oxcart", + "oxygen mask", + "packet", + "paddle", + "paddlewheel", + "padlock", + "paintbrush", + "pajama", + "palace", + "panpipe", + "paper towel", + "parachute", + "parallel bars", + "park bench", + "parking meter", + "passenger car", + "patio", + "pay-phone", + "pedestal", + "pencil box", + "pencil sharpener", + "perfume", + "Petri dish", + "photocopier", + "pick", + "pickelhaube", + "picket fence", + "pickup", + "pier", + "piggy bank", + "pill bottle", + "pillow", + "ping-pong ball", + "pinwheel", + "pirate", + "pitcher", + "plane", + "planetarium", + "plastic bag", + "plate rack", + "plow", + "plunger", + "Polaroid camera", + "pole", + "police van", + "poncho", + "pool table", + "pop bottle", + "pot", + "potter's wheel", + "power drill", + "prayer rug", + "printer", + "prison", + "projectile", + "projector", + "puck", + "punching bag", + "purse", + "quill", + "quilt", + "racer", + "racket", + "radiator", + "radio", + "radio telescope", + "rain barrel", + "recreational vehicle", + "reel", + "reflex camera", + "refrigerator", + "remote control", + "restaurant", + "revolver", + "rifle", + "rocking chair", + "rotisserie", + "rubber eraser", + "rugby ball", + "rule", + "running shoe", + "safe", + "safety pin", + "saltshaker", + "sandal", + "sarong", + "sax", + "scabbard", + "scale", + "school bus", + "schooner", + "scoreboard", + "screen", + "screw", + "screwdriver", + "seat belt", + "sewing machine", + "shield", + "shoe shop", + "shoji", + "shopping basket", + "shopping cart", + "shovel", + "shower cap", + "shower curtain", + "ski", + "ski mask", + "sleeping bag", + "slide rule", + "sliding door", + "slot", + "snorkel", + "snowmobile", + "snowplow", + "soap dispenser", + "soccer ball", + "sock", + "solar dish", + "sombrero", + "soup bowl", + "space bar", + "space heater", + "space shuttle", + "spatula", + "speedboat", + "spider web", + "spindle", + "sports car", + "spotlight", + "stage", + "steam locomotive", + "steel arch bridge", + "steel drum", + "stethoscope", + "stole", + "stone wall", + "stopwatch", + "stove", + "strainer", + "streetcar", + "stretcher", + "studio couch", + "stupa", + "submarine", + "suit", + "sundial", + "sunglass", + "sunglasses", + "sunscreen", + "suspension bridge", + "swab", + "sweatshirt", + "swimming trunks", + "swing", + "switch", + "syringe", + "table lamp", + "tank", + "tape player", + "teapot", + "teddy", + "television", + "tennis ball", + "thatch", + "theater curtain", + "thimble", + "thresher", + "throne", + "tile roof", + "toaster", + "tobacco shop", + "toilet seat", + "torch", + "totem pole", + "tow truck", + "toyshop", + "tractor", + "trailer truck", + "tray", + "trench coat", + "tricycle", + "trimaran", + "tripod", + "triumphal arch", + "trolleybus", + "trombone", + "tub", + "turnstile", + "typewriter keyboard", + "umbrella", + "unicycle", + "upright", + "vacuum", + "vase", + "vault", + "velvet", + "vending machine", + "vestment", + "viaduct", + "violin", + "volleyball", + "waffle iron", + "wall clock", + "wallet", + "wardrobe", + "warplane", + "washbasin", + "washer", + "water bottle", + "water jug", + "water tower", + "whiskey jug", + "whistle", + "wig", + "window screen", + "window shade", + "Windsor tie", + "wine bottle", + "wing", + "wok", + "wooden spoon", + "wool", + "worm fence", + "wreck", + "yawl", + "yurt", + "web site", + "comic book", + "crossword puzzle", + "street sign", + "traffic light", + "book jacket", + "menu", + "plate", + "guacamole", + "consomme", + "hot pot", + "trifle", + "ice cream", + "ice lolly", + "French loaf", + "bagel", + "pretzel", + "cheeseburger", + "hotdog", + "mashed potato", + "head cabbage", + "broccoli", + "cauliflower", + "zucchini", + "spaghetti squash", + "acorn squash", + "butternut squash", + "cucumber", + "artichoke", + "bell pepper", + "cardoon", + "mushroom", + "Granny Smith", + "strawberry", + "orange", + "lemon", + "fig", + "pineapple", + "banana", + "jackfruit", + "custard apple", + "pomegranate", + "hay", + "carbonara", + "chocolate sauce", + "dough", + "meat loaf", + "pizza", + "potpie", + "burrito", + "red wine", + "espresso", + "cup", + "eggnog", + "alp", + "bubble", + "cliff", + "coral reef", + "geyser", + "lakeside", + "promontory", + "sandbar", + "seashore", + "valley", + "volcano", + "ballplayer", + "groom", + "scuba diver", + "rapeseed", + "daisy", + "yellow lady's slipper", + "corn", + "acorn", + "hip", + "buckeye", + "coral fungus", + "agaric", + "gyromitra", + "stinkhorn", + "earthstar", + "hen-of-the-woods", + "bolete", + "ear", + "toilet tissue", +] + +# To be replaced with torchvision.datasets.info("coco").categories +_COCO_CATEGORIES = [ + "__background__", + "person", + "bicycle", + "car", + "motorcycle", + "airplane", + "bus", + "train", + "truck", + "boat", + "traffic light", + "fire hydrant", + "N/A", + "stop sign", + "parking meter", + "bench", + "bird", + "cat", + "dog", + "horse", + "sheep", + "cow", + "elephant", + "bear", + "zebra", + "giraffe", + "N/A", + "backpack", + "umbrella", + "N/A", + "N/A", + "handbag", + "tie", + "suitcase", + "frisbee", + "skis", + "snowboard", + "sports ball", + "kite", + "baseball bat", + "baseball glove", + "skateboard", + "surfboard", + "tennis racket", + "bottle", + "N/A", + "wine glass", + "cup", + "fork", + "knife", + "spoon", + "bowl", + "banana", + "apple", + "sandwich", + "orange", + "broccoli", + "carrot", + "hot dog", + "pizza", + "donut", + "cake", + "chair", + "couch", + "potted plant", + "bed", + "N/A", + "dining table", + "N/A", + "N/A", + "toilet", + "N/A", + "tv", + "laptop", + "mouse", + "remote", + "keyboard", + "cell phone", + "microwave", + "oven", + "toaster", + "sink", + "refrigerator", + "N/A", + "book", + "clock", + "vase", + "scissors", + "teddy bear", + "hair drier", + "toothbrush", +] + +# To be replaced with torchvision.datasets.info("coco_kp") +_COCO_PERSON_CATEGORIES = ["no person", "person"] +_COCO_PERSON_KEYPOINT_NAMES = [ + "nose", + "left_eye", + "right_eye", + "left_ear", + "right_ear", + "left_shoulder", + "right_shoulder", + "left_elbow", + "right_elbow", + "left_wrist", + "right_wrist", + "left_hip", + "right_hip", + "left_knee", + "right_knee", + "left_ankle", + "right_ankle", +] + +# To be replaced with torchvision.datasets.info("voc").categories +_VOC_CATEGORIES = [ + "__background__", + "aeroplane", + "bicycle", + "bird", + "boat", + "bottle", + "bus", + "car", + "cat", + "chair", + "cow", + "diningtable", + "dog", + "horse", + "motorbike", + "person", + "pottedplant", + "sheep", + "sofa", + "train", + "tvmonitor", +] + +# To be replaced with torchvision.datasets.info("kinetics400").categories +_KINETICS400_CATEGORIES = [ + "abseiling", + "air drumming", + "answering questions", + "applauding", + "applying cream", + "archery", + "arm wrestling", + "arranging flowers", + "assembling computer", + "auctioning", + "baby waking up", + "baking cookies", + "balloon blowing", + "bandaging", + "barbequing", + "bartending", + "beatboxing", + "bee keeping", + "belly dancing", + "bench pressing", + "bending back", + "bending metal", + "biking through snow", + "blasting sand", + "blowing glass", + "blowing leaves", + "blowing nose", + "blowing out candles", + "bobsledding", + "bookbinding", + "bouncing on trampoline", + "bowling", + "braiding hair", + "breading or breadcrumbing", + "breakdancing", + "brush painting", + "brushing hair", + "brushing teeth", + "building cabinet", + "building shed", + "bungee jumping", + "busking", + "canoeing or kayaking", + "capoeira", + "carrying baby", + "cartwheeling", + "carving pumpkin", + "catching fish", + "catching or throwing baseball", + "catching or throwing frisbee", + "catching or throwing softball", + "celebrating", + "changing oil", + "changing wheel", + "checking tires", + "cheerleading", + "chopping wood", + "clapping", + "clay pottery making", + "clean and jerk", + "cleaning floor", + "cleaning gutters", + "cleaning pool", + "cleaning shoes", + "cleaning toilet", + "cleaning windows", + "climbing a rope", + "climbing ladder", + "climbing tree", + "contact juggling", + "cooking chicken", + "cooking egg", + "cooking on campfire", + "cooking sausages", + "counting money", + "country line dancing", + "cracking neck", + "crawling baby", + "crossing river", + "crying", + "curling hair", + "cutting nails", + "cutting pineapple", + "cutting watermelon", + "dancing ballet", + "dancing charleston", + "dancing gangnam style", + "dancing macarena", + "deadlifting", + "decorating the christmas tree", + "digging", + "dining", + "disc golfing", + "diving cliff", + "dodgeball", + "doing aerobics", + "doing laundry", + "doing nails", + "drawing", + "dribbling basketball", + "drinking", + "drinking beer", + "drinking shots", + "driving car", + "driving tractor", + "drop kicking", + "drumming fingers", + "dunking basketball", + "dying hair", + "eating burger", + "eating cake", + "eating carrots", + "eating chips", + "eating doughnuts", + "eating hotdog", + "eating ice cream", + "eating spaghetti", + "eating watermelon", + "egg hunting", + "exercising arm", + "exercising with an exercise ball", + "extinguishing fire", + "faceplanting", + "feeding birds", + "feeding fish", + "feeding goats", + "filling eyebrows", + "finger snapping", + "fixing hair", + "flipping pancake", + "flying kite", + "folding clothes", + "folding napkins", + "folding paper", + "front raises", + "frying vegetables", + "garbage collecting", + "gargling", + "getting a haircut", + "getting a tattoo", + "giving or receiving award", + "golf chipping", + "golf driving", + "golf putting", + "grinding meat", + "grooming dog", + "grooming horse", + "gymnastics tumbling", + "hammer throw", + "headbanging", + "headbutting", + "high jump", + "high kick", + "hitting baseball", + "hockey stop", + "holding snake", + "hopscotch", + "hoverboarding", + "hugging", + "hula hooping", + "hurdling", + "hurling (sport)", + "ice climbing", + "ice fishing", + "ice skating", + "ironing", + "javelin throw", + "jetskiing", + "jogging", + "juggling balls", + "juggling fire", + "juggling soccer ball", + "jumping into pool", + "jumpstyle dancing", + "kicking field goal", + "kicking soccer ball", + "kissing", + "kitesurfing", + "knitting", + "krumping", + "laughing", + "laying bricks", + "long jump", + "lunge", + "making a cake", + "making a sandwich", + "making bed", + "making jewelry", + "making pizza", + "making snowman", + "making sushi", + "making tea", + "marching", + "massaging back", + "massaging feet", + "massaging legs", + "massaging person's head", + "milking cow", + "mopping floor", + "motorcycling", + "moving furniture", + "mowing lawn", + "news anchoring", + "opening bottle", + "opening present", + "paragliding", + "parasailing", + "parkour", + "passing American football (in game)", + "passing American football (not in game)", + "peeling apples", + "peeling potatoes", + "petting animal (not cat)", + "petting cat", + "picking fruit", + "planting trees", + "plastering", + "playing accordion", + "playing badminton", + "playing bagpipes", + "playing basketball", + "playing bass guitar", + "playing cards", + "playing cello", + "playing chess", + "playing clarinet", + "playing controller", + "playing cricket", + "playing cymbals", + "playing didgeridoo", + "playing drums", + "playing flute", + "playing guitar", + "playing harmonica", + "playing harp", + "playing ice hockey", + "playing keyboard", + "playing kickball", + "playing monopoly", + "playing organ", + "playing paintball", + "playing piano", + "playing poker", + "playing recorder", + "playing saxophone", + "playing squash or racquetball", + "playing tennis", + "playing trombone", + "playing trumpet", + "playing ukulele", + "playing violin", + "playing volleyball", + "playing xylophone", + "pole vault", + "presenting weather forecast", + "pull ups", + "pumping fist", + "pumping gas", + "punching bag", + "punching person (boxing)", + "push up", + "pushing car", + "pushing cart", + "pushing wheelchair", + "reading book", + "reading newspaper", + "recording music", + "riding a bike", + "riding camel", + "riding elephant", + "riding mechanical bull", + "riding mountain bike", + "riding mule", + "riding or walking with horse", + "riding scooter", + "riding unicycle", + "ripping paper", + "robot dancing", + "rock climbing", + "rock scissors paper", + "roller skating", + "running on treadmill", + "sailing", + "salsa dancing", + "sanding floor", + "scrambling eggs", + "scuba diving", + "setting table", + "shaking hands", + "shaking head", + "sharpening knives", + "sharpening pencil", + "shaving head", + "shaving legs", + "shearing sheep", + "shining shoes", + "shooting basketball", + "shooting goal (soccer)", + "shot put", + "shoveling snow", + "shredding paper", + "shuffling cards", + "side kick", + "sign language interpreting", + "singing", + "situp", + "skateboarding", + "ski jumping", + "skiing (not slalom or crosscountry)", + "skiing crosscountry", + "skiing slalom", + "skipping rope", + "skydiving", + "slacklining", + "slapping", + "sled dog racing", + "smoking", + "smoking hookah", + "snatch weight lifting", + "sneezing", + "sniffing", + "snorkeling", + "snowboarding", + "snowkiting", + "snowmobiling", + "somersaulting", + "spinning poi", + "spray painting", + "spraying", + "springboard diving", + "squat", + "sticking tongue out", + "stomping grapes", + "stretching arm", + "stretching leg", + "strumming guitar", + "surfing crowd", + "surfing water", + "sweeping floor", + "swimming backstroke", + "swimming breast stroke", + "swimming butterfly stroke", + "swing dancing", + "swinging legs", + "swinging on something", + "sword fighting", + "tai chi", + "taking a shower", + "tango dancing", + "tap dancing", + "tapping guitar", + "tapping pen", + "tasting beer", + "tasting food", + "testifying", + "texting", + "throwing axe", + "throwing ball", + "throwing discus", + "tickling", + "tobogganing", + "tossing coin", + "tossing salad", + "training dog", + "trapezing", + "trimming or shaving beard", + "trimming trees", + "triple jump", + "tying bow tie", + "tying knot (not on a tie)", + "tying tie", + "unboxing", + "unloading truck", + "using computer", + "using remote controller (not gaming)", + "using segway", + "vault", + "waiting in line", + "walking the dog", + "washing dishes", + "washing feet", + "washing hair", + "washing hands", + "water skiing", + "water sliding", + "watering plants", + "waxing back", + "waxing chest", + "waxing eyebrows", + "waxing legs", + "weaving basket", + "welding", + "whistling", + "windsurfing", + "wrapping present", + "wrestling", + "writing", + "yawning", + "yoga", + "zumba", +] diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/_utils.py b/.venv/lib/python3.12/site-packages/torchvision/models/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..395757b62f51d49f96c0d2054fc981c99a63baa2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/_utils.py @@ -0,0 +1,255 @@ +import functools +import inspect +import warnings +from collections import OrderedDict +from typing import Any, Callable, Optional, TypeVar, Union + +from torch import nn + +from .._utils import sequence_to_str +from ._api import WeightsEnum + + +class IntermediateLayerGetter(nn.ModuleDict): + """ + Module wrapper that returns intermediate layers from a model + + It has a strong assumption that the modules have been registered + into the model in the same order as they are used. + This means that one should **not** reuse the same nn.Module + twice in the forward if you want this to work. + + Additionally, it is only able to query submodules that are directly + assigned to the model. So if `model` is passed, `model.feature1` can + be returned, but not `model.feature1.layer2`. + + Args: + model (nn.Module): model on which we will extract the features + return_layers (Dict[name, new_name]): a dict containing the names + of the modules for which the activations will be returned as + the key of the dict, and the value of the dict is the name + of the returned activation (which the user can specify). + + Examples:: + + >>> m = torchvision.models.resnet18(weights=ResNet18_Weights.DEFAULT) + >>> # extract layer1 and layer3, giving as names `feat1` and feat2` + >>> new_m = torchvision.models._utils.IntermediateLayerGetter(m, + >>> {'layer1': 'feat1', 'layer3': 'feat2'}) + >>> out = new_m(torch.rand(1, 3, 224, 224)) + >>> print([(k, v.shape) for k, v in out.items()]) + >>> [('feat1', torch.Size([1, 64, 56, 56])), + >>> ('feat2', torch.Size([1, 256, 14, 14]))] + """ + + _version = 2 + __annotations__ = { + "return_layers": dict[str, str], + } + + def __init__(self, model: nn.Module, return_layers: dict[str, str]) -> None: + if not set(return_layers).issubset([name for name, _ in model.named_children()]): + raise ValueError("return_layers are not present in model") + orig_return_layers = return_layers + return_layers = {str(k): str(v) for k, v in return_layers.items()} + layers = OrderedDict() + for name, module in model.named_children(): + layers[name] = module + if name in return_layers: + del return_layers[name] + if not return_layers: + break + + super().__init__(layers) + self.return_layers = orig_return_layers + + def forward(self, x): + out = OrderedDict() + for name, module in self.items(): + x = module(x) + if name in self.return_layers: + out_name = self.return_layers[name] + out[out_name] = x + return out + + +def _make_divisible(v: float, divisor: int, min_value: Optional[int] = None) -> int: + """ + This function is taken from the original tf repo. + It ensures that all layers have a channel number that is divisible by 8 + It can be seen here: + https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py + """ + if min_value is None: + min_value = divisor + new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) + # Make sure that round down does not go down by more than 10%. + if new_v < 0.9 * v: + new_v += divisor + return new_v + + +D = TypeVar("D") + + +def kwonly_to_pos_or_kw(fn: Callable[..., D]) -> Callable[..., D]: + """Decorates a function that uses keyword only parameters to also allow them being passed as positionals. + + For example, consider the use case of changing the signature of ``old_fn`` into the one from ``new_fn``: + + .. code:: + + def old_fn(foo, bar, baz=None): + ... + + def new_fn(foo, *, bar, baz=None): + ... + + Calling ``old_fn("foo", "bar, "baz")`` was valid, but the same call is no longer valid with ``new_fn``. To keep BC + and at the same time warn the user of the deprecation, this decorator can be used: + + .. code:: + + @kwonly_to_pos_or_kw + def new_fn(foo, *, bar, baz=None): + ... + + new_fn("foo", "bar, "baz") + """ + params = inspect.signature(fn).parameters + + try: + keyword_only_start_idx = next( + idx for idx, param in enumerate(params.values()) if param.kind == param.KEYWORD_ONLY + ) + except StopIteration: + raise TypeError(f"Found no keyword-only parameter on function '{fn.__name__}'") from None + + keyword_only_params = tuple(inspect.signature(fn).parameters)[keyword_only_start_idx:] + + @functools.wraps(fn) + def wrapper(*args: Any, **kwargs: Any) -> D: + args, keyword_only_args = args[:keyword_only_start_idx], args[keyword_only_start_idx:] + if keyword_only_args: + keyword_only_kwargs = dict(zip(keyword_only_params, keyword_only_args)) + warnings.warn( + f"Using {sequence_to_str(tuple(keyword_only_kwargs.keys()), separate_last='and ')} as positional " + f"parameter(s) is deprecated since 0.13 and may be removed in the future. Please use keyword parameter(s) " + f"instead." + ) + kwargs.update(keyword_only_kwargs) + + return fn(*args, **kwargs) + + return wrapper + + +W = TypeVar("W", bound=WeightsEnum) +M = TypeVar("M", bound=nn.Module) +V = TypeVar("V") + + +def handle_legacy_interface(**weights: tuple[str, Union[Optional[W], Callable[[dict[str, Any]], Optional[W]]]]): + """Decorates a model builder with the new interface to make it compatible with the old. + + In particular this handles two things: + + 1. Allows positional parameters again, but emits a deprecation warning in case they are used. + 2. Handles the default value change from ``pretrained=False`` to ``weights=None`` and ``pretrained=True`` to + ``weights=Weights`` and emits a deprecation warning with instructions for the new interface. + + Args: + **weights (Tuple[str, Union[Optional[W], Callable[[Dict[str, Any]], Optional[W]]]]): Deprecated parameter + name and default value for the legacy ``pretrained=True``. The default value can be a callable in which + case it will be called with a dictionary of the keyword arguments. The only key that is guaranteed to be in + the dictionary is the deprecated parameter name passed as first element in the tuple. All other parameters + should be accessed with :meth:`~dict.get`. + """ + + def outer_wrapper(builder: Callable[..., M]) -> Callable[..., M]: + @kwonly_to_pos_or_kw + @functools.wraps(builder) + def inner_wrapper(*args: Any, **kwargs: Any) -> M: + for weights_param, (pretrained_param, default) in weights.items(): # type: ignore[union-attr] + # If neither the weights nor the pretrained parameter as passed, or the weights argument already use + # the new style arguments, there is nothing to do. Note that we cannot use `None` as sentinel for the + # weight argument, since it is a valid value. + sentinel = object() + weights_arg = kwargs.get(weights_param, sentinel) + if ( + (weights_param not in kwargs and pretrained_param not in kwargs) + or isinstance(weights_arg, WeightsEnum) + or (isinstance(weights_arg, str) and weights_arg != "legacy") + or weights_arg is None + ): + continue + + # If the pretrained parameter was passed as positional argument, it is now mapped to + # `kwargs[weights_param]`. This happens because the @kwonly_to_pos_or_kw decorator uses the current + # signature to infer the names of positionally passed arguments and thus has no knowledge that there + # used to be a pretrained parameter. + pretrained_positional = weights_arg is not sentinel + if pretrained_positional: + # We put the pretrained argument under its legacy name in the keyword argument dictionary to have + # unified access to the value if the default value is a callable. + kwargs[pretrained_param] = pretrained_arg = kwargs.pop(weights_param) + else: + pretrained_arg = kwargs[pretrained_param] + + if pretrained_arg: + default_weights_arg = default(kwargs) if callable(default) else default + if not isinstance(default_weights_arg, WeightsEnum): + raise ValueError(f"No weights available for model {builder.__name__}") + else: + default_weights_arg = None + + if not pretrained_positional: + warnings.warn( + f"The parameter '{pretrained_param}' is deprecated since 0.13 and may be removed in the future, " + f"please use '{weights_param}' instead." + ) + + msg = ( + f"Arguments other than a weight enum or `None` for '{weights_param}' are deprecated since 0.13 and " + f"may be removed in the future. " + f"The current behavior is equivalent to passing `{weights_param}={default_weights_arg}`." + ) + if pretrained_arg: + msg = ( + f"{msg} You can also use `{weights_param}={type(default_weights_arg).__name__}.DEFAULT` " + f"to get the most up-to-date weights." + ) + warnings.warn(msg) + + del kwargs[pretrained_param] + kwargs[weights_param] = default_weights_arg + + return builder(*args, **kwargs) + + return inner_wrapper + + return outer_wrapper + + +def _ovewrite_named_param(kwargs: dict[str, Any], param: str, new_value: V) -> None: + if param in kwargs: + if kwargs[param] != new_value: + raise ValueError(f"The parameter '{param}' expected value {new_value} but got {kwargs[param]} instead.") + else: + kwargs[param] = new_value + + +def _ovewrite_value_param(param: str, actual: Optional[V], expected: V) -> V: + if actual is not None: + if actual != expected: + raise ValueError(f"The parameter '{param}' expected value {expected} but got {actual} instead.") + return expected + + +class _ModelURLs(dict): + def __getitem__(self, item): + warnings.warn( + "Accessing the model URLs via the internal dictionary of the module is deprecated since 0.13 and may " + "be removed in the future. Please access them via the appropriate Weights Enum instead." + ) + return super().__getitem__(item) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/alexnet.py b/.venv/lib/python3.12/site-packages/torchvision/models/alexnet.py new file mode 100644 index 0000000000000000000000000000000000000000..f85acbeb2148d2aa8f289808e61aa61e2d68e2f9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/alexnet.py @@ -0,0 +1,119 @@ +from functools import partial +from typing import Any, Optional + +import torch +import torch.nn as nn + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = ["AlexNet", "AlexNet_Weights", "alexnet"] + + +class AlexNet(nn.Module): + def __init__(self, num_classes: int = 1000, dropout: float = 0.5) -> None: + super().__init__() + _log_api_usage_once(self) + self.features = nn.Sequential( + nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2), + nn.Conv2d(64, 192, kernel_size=5, padding=2), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2), + nn.Conv2d(192, 384, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(384, 256, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(256, 256, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2), + ) + self.avgpool = nn.AdaptiveAvgPool2d((6, 6)) + self.classifier = nn.Sequential( + nn.Dropout(p=dropout), + nn.Linear(256 * 6 * 6, 4096), + nn.ReLU(inplace=True), + nn.Dropout(p=dropout), + nn.Linear(4096, 4096), + nn.ReLU(inplace=True), + nn.Linear(4096, num_classes), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.features(x) + x = self.avgpool(x) + x = torch.flatten(x, 1) + x = self.classifier(x) + return x + + +class AlexNet_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/alexnet-owt-7be5be79.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + "num_params": 61100840, + "min_size": (63, 63), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#alexnet-and-vgg", + "_metrics": { + "ImageNet-1K": { + "acc@1": 56.522, + "acc@5": 79.066, + } + }, + "_ops": 0.714, + "_file_size": 233.087, + "_docs": """ + These weights reproduce closely the results of the paper using a simplified training recipe. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", AlexNet_Weights.IMAGENET1K_V1)) +def alexnet(*, weights: Optional[AlexNet_Weights] = None, progress: bool = True, **kwargs: Any) -> AlexNet: + """AlexNet model architecture from `One weird trick for parallelizing convolutional neural networks `__. + + .. note:: + AlexNet was originally introduced in the `ImageNet Classification with + Deep Convolutional Neural Networks + `__ + paper. Our implementation is based instead on the "One weird trick" + paper above. + + Args: + weights (:class:`~torchvision.models.AlexNet_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.AlexNet_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.squeezenet.AlexNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.AlexNet_Weights + :members: + """ + + weights = AlexNet_Weights.verify(weights) + + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = AlexNet(**kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/convnext.py b/.venv/lib/python3.12/site-packages/torchvision/models/convnext.py new file mode 100644 index 0000000000000000000000000000000000000000..3264cb1fd0ce43ca40cad4e8f0ca46e9cf1703db --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/convnext.py @@ -0,0 +1,415 @@ +from collections.abc import Sequence +from functools import partial +from typing import Any, Callable, Optional + +import torch +from torch import nn, Tensor +from torch.nn import functional as F + +from ..ops.misc import Conv2dNormActivation, Permute +from ..ops.stochastic_depth import StochasticDepth +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "ConvNeXt", + "ConvNeXt_Tiny_Weights", + "ConvNeXt_Small_Weights", + "ConvNeXt_Base_Weights", + "ConvNeXt_Large_Weights", + "convnext_tiny", + "convnext_small", + "convnext_base", + "convnext_large", +] + + +class LayerNorm2d(nn.LayerNorm): + def forward(self, x: Tensor) -> Tensor: + x = x.permute(0, 2, 3, 1) + x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps) + x = x.permute(0, 3, 1, 2) + return x + + +class CNBlock(nn.Module): + def __init__( + self, + dim, + layer_scale: float, + stochastic_depth_prob: float, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + if norm_layer is None: + norm_layer = partial(nn.LayerNorm, eps=1e-6) + + self.block = nn.Sequential( + nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim, bias=True), + Permute([0, 2, 3, 1]), + norm_layer(dim), + nn.Linear(in_features=dim, out_features=4 * dim, bias=True), + nn.GELU(), + nn.Linear(in_features=4 * dim, out_features=dim, bias=True), + Permute([0, 3, 1, 2]), + ) + self.layer_scale = nn.Parameter(torch.ones(dim, 1, 1) * layer_scale) + self.stochastic_depth = StochasticDepth(stochastic_depth_prob, "row") + + def forward(self, input: Tensor) -> Tensor: + result = self.layer_scale * self.block(input) + result = self.stochastic_depth(result) + result += input + return result + + +class CNBlockConfig: + # Stores information listed at Section 3 of the ConvNeXt paper + def __init__( + self, + input_channels: int, + out_channels: Optional[int], + num_layers: int, + ) -> None: + self.input_channels = input_channels + self.out_channels = out_channels + self.num_layers = num_layers + + def __repr__(self) -> str: + s = self.__class__.__name__ + "(" + s += "input_channels={input_channels}" + s += ", out_channels={out_channels}" + s += ", num_layers={num_layers}" + s += ")" + return s.format(**self.__dict__) + + +class ConvNeXt(nn.Module): + def __init__( + self, + block_setting: list[CNBlockConfig], + stochastic_depth_prob: float = 0.0, + layer_scale: float = 1e-6, + num_classes: int = 1000, + block: Optional[Callable[..., nn.Module]] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + **kwargs: Any, + ) -> None: + super().__init__() + _log_api_usage_once(self) + + if not block_setting: + raise ValueError("The block_setting should not be empty") + elif not (isinstance(block_setting, Sequence) and all([isinstance(s, CNBlockConfig) for s in block_setting])): + raise TypeError("The block_setting should be List[CNBlockConfig]") + + if block is None: + block = CNBlock + + if norm_layer is None: + norm_layer = partial(LayerNorm2d, eps=1e-6) + + layers: list[nn.Module] = [] + + # Stem + firstconv_output_channels = block_setting[0].input_channels + layers.append( + Conv2dNormActivation( + 3, + firstconv_output_channels, + kernel_size=4, + stride=4, + padding=0, + norm_layer=norm_layer, + activation_layer=None, + bias=True, + ) + ) + + total_stage_blocks = sum(cnf.num_layers for cnf in block_setting) + stage_block_id = 0 + for cnf in block_setting: + # Bottlenecks + stage: list[nn.Module] = [] + for _ in range(cnf.num_layers): + # adjust stochastic depth probability based on the depth of the stage block + sd_prob = stochastic_depth_prob * stage_block_id / (total_stage_blocks - 1.0) + stage.append(block(cnf.input_channels, layer_scale, sd_prob)) + stage_block_id += 1 + layers.append(nn.Sequential(*stage)) + if cnf.out_channels is not None: + # Downsampling + layers.append( + nn.Sequential( + norm_layer(cnf.input_channels), + nn.Conv2d(cnf.input_channels, cnf.out_channels, kernel_size=2, stride=2), + ) + ) + + self.features = nn.Sequential(*layers) + self.avgpool = nn.AdaptiveAvgPool2d(1) + + lastblock = block_setting[-1] + lastconv_output_channels = ( + lastblock.out_channels if lastblock.out_channels is not None else lastblock.input_channels + ) + self.classifier = nn.Sequential( + norm_layer(lastconv_output_channels), nn.Flatten(1), nn.Linear(lastconv_output_channels, num_classes) + ) + + for m in self.modules(): + if isinstance(m, (nn.Conv2d, nn.Linear)): + nn.init.trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.zeros_(m.bias) + + def _forward_impl(self, x: Tensor) -> Tensor: + x = self.features(x) + x = self.avgpool(x) + x = self.classifier(x) + return x + + def forward(self, x: Tensor) -> Tensor: + return self._forward_impl(x) + + +def _convnext( + block_setting: list[CNBlockConfig], + stochastic_depth_prob: float, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> ConvNeXt: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = ConvNeXt(block_setting, stochastic_depth_prob=stochastic_depth_prob, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (32, 32), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#convnext", + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, +} + + +class ConvNeXt_Tiny_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/convnext_tiny-983f1562.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=236), + meta={ + **_COMMON_META, + "num_params": 28589128, + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.520, + "acc@5": 96.146, + } + }, + "_ops": 4.456, + "_file_size": 109.119, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ConvNeXt_Small_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/convnext_small-0c510722.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=230), + meta={ + **_COMMON_META, + "num_params": 50223688, + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.616, + "acc@5": 96.650, + } + }, + "_ops": 8.684, + "_file_size": 191.703, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ConvNeXt_Base_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/convnext_base-6075fbad.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 88591464, + "_metrics": { + "ImageNet-1K": { + "acc@1": 84.062, + "acc@5": 96.870, + } + }, + "_ops": 15.355, + "_file_size": 338.064, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ConvNeXt_Large_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/convnext_large-ea097f82.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 197767336, + "_metrics": { + "ImageNet-1K": { + "acc@1": 84.414, + "acc@5": 96.976, + } + }, + "_ops": 34.361, + "_file_size": 754.537, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ConvNeXt_Tiny_Weights.IMAGENET1K_V1)) +def convnext_tiny(*, weights: Optional[ConvNeXt_Tiny_Weights] = None, progress: bool = True, **kwargs: Any) -> ConvNeXt: + """ConvNeXt Tiny model architecture from the + `A ConvNet for the 2020s `_ paper. + + Args: + weights (:class:`~torchvision.models.convnext.ConvNeXt_Tiny_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.convnext.ConvNeXt_Tiny_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.convnext.ConvNext`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ConvNeXt_Tiny_Weights + :members: + """ + weights = ConvNeXt_Tiny_Weights.verify(weights) + + block_setting = [ + CNBlockConfig(96, 192, 3), + CNBlockConfig(192, 384, 3), + CNBlockConfig(384, 768, 9), + CNBlockConfig(768, None, 3), + ] + stochastic_depth_prob = kwargs.pop("stochastic_depth_prob", 0.1) + return _convnext(block_setting, stochastic_depth_prob, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ConvNeXt_Small_Weights.IMAGENET1K_V1)) +def convnext_small( + *, weights: Optional[ConvNeXt_Small_Weights] = None, progress: bool = True, **kwargs: Any +) -> ConvNeXt: + """ConvNeXt Small model architecture from the + `A ConvNet for the 2020s `_ paper. + + Args: + weights (:class:`~torchvision.models.convnext.ConvNeXt_Small_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.convnext.ConvNeXt_Small_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.convnext.ConvNext`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ConvNeXt_Small_Weights + :members: + """ + weights = ConvNeXt_Small_Weights.verify(weights) + + block_setting = [ + CNBlockConfig(96, 192, 3), + CNBlockConfig(192, 384, 3), + CNBlockConfig(384, 768, 27), + CNBlockConfig(768, None, 3), + ] + stochastic_depth_prob = kwargs.pop("stochastic_depth_prob", 0.4) + return _convnext(block_setting, stochastic_depth_prob, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ConvNeXt_Base_Weights.IMAGENET1K_V1)) +def convnext_base(*, weights: Optional[ConvNeXt_Base_Weights] = None, progress: bool = True, **kwargs: Any) -> ConvNeXt: + """ConvNeXt Base model architecture from the + `A ConvNet for the 2020s `_ paper. + + Args: + weights (:class:`~torchvision.models.convnext.ConvNeXt_Base_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.convnext.ConvNeXt_Base_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.convnext.ConvNext`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ConvNeXt_Base_Weights + :members: + """ + weights = ConvNeXt_Base_Weights.verify(weights) + + block_setting = [ + CNBlockConfig(128, 256, 3), + CNBlockConfig(256, 512, 3), + CNBlockConfig(512, 1024, 27), + CNBlockConfig(1024, None, 3), + ] + stochastic_depth_prob = kwargs.pop("stochastic_depth_prob", 0.5) + return _convnext(block_setting, stochastic_depth_prob, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ConvNeXt_Large_Weights.IMAGENET1K_V1)) +def convnext_large( + *, weights: Optional[ConvNeXt_Large_Weights] = None, progress: bool = True, **kwargs: Any +) -> ConvNeXt: + """ConvNeXt Large model architecture from the + `A ConvNet for the 2020s `_ paper. + + Args: + weights (:class:`~torchvision.models.convnext.ConvNeXt_Large_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.convnext.ConvNeXt_Large_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.convnext.ConvNext`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ConvNeXt_Large_Weights + :members: + """ + weights = ConvNeXt_Large_Weights.verify(weights) + + block_setting = [ + CNBlockConfig(192, 384, 3), + CNBlockConfig(384, 768, 3), + CNBlockConfig(768, 1536, 27), + CNBlockConfig(1536, None, 3), + ] + stochastic_depth_prob = kwargs.pop("stochastic_depth_prob", 0.5) + return _convnext(block_setting, stochastic_depth_prob, weights, progress, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/densenet.py b/.venv/lib/python3.12/site-packages/torchvision/models/densenet.py new file mode 100644 index 0000000000000000000000000000000000000000..06457f7b09e9d383327b0bc41304a412eb6b7839 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/densenet.py @@ -0,0 +1,448 @@ +import re +from collections import OrderedDict +from functools import partial +from typing import Any, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as cp +from torch import Tensor + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + +__all__ = [ + "DenseNet", + "DenseNet121_Weights", + "DenseNet161_Weights", + "DenseNet169_Weights", + "DenseNet201_Weights", + "densenet121", + "densenet161", + "densenet169", + "densenet201", +] + + +class _DenseLayer(nn.Module): + def __init__( + self, num_input_features: int, growth_rate: int, bn_size: int, drop_rate: float, memory_efficient: bool = False + ) -> None: + super().__init__() + self.norm1 = nn.BatchNorm2d(num_input_features) + self.relu1 = nn.ReLU(inplace=True) + self.conv1 = nn.Conv2d(num_input_features, bn_size * growth_rate, kernel_size=1, stride=1, bias=False) + + self.norm2 = nn.BatchNorm2d(bn_size * growth_rate) + self.relu2 = nn.ReLU(inplace=True) + self.conv2 = nn.Conv2d(bn_size * growth_rate, growth_rate, kernel_size=3, stride=1, padding=1, bias=False) + + self.drop_rate = float(drop_rate) + self.memory_efficient = memory_efficient + + def bn_function(self, inputs: list[Tensor]) -> Tensor: + concated_features = torch.cat(inputs, 1) + bottleneck_output = self.conv1(self.relu1(self.norm1(concated_features))) # noqa: T484 + return bottleneck_output + + # todo: rewrite when torchscript supports any + def any_requires_grad(self, input: list[Tensor]) -> bool: + for tensor in input: + if tensor.requires_grad: + return True + return False + + @torch.jit.unused # noqa: T484 + def call_checkpoint_bottleneck(self, input: list[Tensor]) -> Tensor: + def closure(*inputs): + return self.bn_function(inputs) + + return cp.checkpoint(closure, *input, use_reentrant=False) + + @torch.jit._overload_method # noqa: F811 + def forward(self, input: list[Tensor]) -> Tensor: # noqa: F811 + pass + + @torch.jit._overload_method # noqa: F811 + def forward(self, input: Tensor) -> Tensor: # noqa: F811 + pass + + # torchscript does not yet support *args, so we overload method + # allowing it to take either a List[Tensor] or single Tensor + def forward(self, input: Tensor) -> Tensor: # noqa: F811 + if isinstance(input, Tensor): + prev_features = [input] + else: + prev_features = input + + if self.memory_efficient and self.any_requires_grad(prev_features): + if torch.jit.is_scripting(): + raise Exception("Memory Efficient not supported in JIT") + + bottleneck_output = self.call_checkpoint_bottleneck(prev_features) + else: + bottleneck_output = self.bn_function(prev_features) + + new_features = self.conv2(self.relu2(self.norm2(bottleneck_output))) + if self.drop_rate > 0: + new_features = F.dropout(new_features, p=self.drop_rate, training=self.training) + return new_features + + +class _DenseBlock(nn.ModuleDict): + _version = 2 + + def __init__( + self, + num_layers: int, + num_input_features: int, + bn_size: int, + growth_rate: int, + drop_rate: float, + memory_efficient: bool = False, + ) -> None: + super().__init__() + for i in range(num_layers): + layer = _DenseLayer( + num_input_features + i * growth_rate, + growth_rate=growth_rate, + bn_size=bn_size, + drop_rate=drop_rate, + memory_efficient=memory_efficient, + ) + self.add_module("denselayer%d" % (i + 1), layer) + + def forward(self, init_features: Tensor) -> Tensor: + features = [init_features] + for name, layer in self.items(): + new_features = layer(features) + features.append(new_features) + return torch.cat(features, 1) + + +class _Transition(nn.Sequential): + def __init__(self, num_input_features: int, num_output_features: int) -> None: + super().__init__() + self.norm = nn.BatchNorm2d(num_input_features) + self.relu = nn.ReLU(inplace=True) + self.conv = nn.Conv2d(num_input_features, num_output_features, kernel_size=1, stride=1, bias=False) + self.pool = nn.AvgPool2d(kernel_size=2, stride=2) + + +class DenseNet(nn.Module): + r"""Densenet-BC model class, based on + `"Densely Connected Convolutional Networks" `_. + + Args: + growth_rate (int) - how many filters to add each layer (`k` in paper) + block_config (list of 4 ints) - how many layers in each pooling block + num_init_features (int) - the number of filters to learn in the first convolution layer + bn_size (int) - multiplicative factor for number of bottle neck layers + (i.e. bn_size * k features in the bottleneck layer) + drop_rate (float) - dropout rate after each dense layer + num_classes (int) - number of classification classes + memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient, + but slower. Default: *False*. See `"paper" `_. + """ + + def __init__( + self, + growth_rate: int = 32, + block_config: tuple[int, int, int, int] = (6, 12, 24, 16), + num_init_features: int = 64, + bn_size: int = 4, + drop_rate: float = 0, + num_classes: int = 1000, + memory_efficient: bool = False, + ) -> None: + + super().__init__() + _log_api_usage_once(self) + + # First convolution + self.features = nn.Sequential( + OrderedDict( + [ + ("conv0", nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)), + ("norm0", nn.BatchNorm2d(num_init_features)), + ("relu0", nn.ReLU(inplace=True)), + ("pool0", nn.MaxPool2d(kernel_size=3, stride=2, padding=1)), + ] + ) + ) + + # Each denseblock + num_features = num_init_features + for i, num_layers in enumerate(block_config): + block = _DenseBlock( + num_layers=num_layers, + num_input_features=num_features, + bn_size=bn_size, + growth_rate=growth_rate, + drop_rate=drop_rate, + memory_efficient=memory_efficient, + ) + self.features.add_module("denseblock%d" % (i + 1), block) + num_features = num_features + num_layers * growth_rate + if i != len(block_config) - 1: + trans = _Transition(num_input_features=num_features, num_output_features=num_features // 2) + self.features.add_module("transition%d" % (i + 1), trans) + num_features = num_features // 2 + + # Final batch norm + self.features.add_module("norm5", nn.BatchNorm2d(num_features)) + + # Linear layer + self.classifier = nn.Linear(num_features, num_classes) + + # Official init from torch repo. + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.constant_(m.bias, 0) + + def forward(self, x: Tensor) -> Tensor: + features = self.features(x) + out = F.relu(features, inplace=True) + out = F.adaptive_avg_pool2d(out, (1, 1)) + out = torch.flatten(out, 1) + out = self.classifier(out) + return out + + +def _load_state_dict(model: nn.Module, weights: WeightsEnum, progress: bool) -> None: + # '.'s are no longer allowed in module names, but previous _DenseLayer + # has keys 'norm.1', 'relu.1', 'conv.1', 'norm.2', 'relu.2', 'conv.2'. + # They are also in the checkpoints in model_urls. This pattern is used + # to find such keys. + pattern = re.compile( + r"^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$" + ) + + state_dict = weights.get_state_dict(progress=progress, check_hash=True) + for key in list(state_dict.keys()): + res = pattern.match(key) + if res: + new_key = res.group(1) + res.group(2) + state_dict[new_key] = state_dict[key] + del state_dict[key] + model.load_state_dict(state_dict) + + +def _densenet( + growth_rate: int, + block_config: tuple[int, int, int, int], + num_init_features: int, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> DenseNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = DenseNet(growth_rate, block_config, num_init_features, **kwargs) + + if weights is not None: + _load_state_dict(model=model, weights=weights, progress=progress) + + return model + + +_COMMON_META = { + "min_size": (29, 29), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/pull/116", + "_docs": """These weights are ported from LuaTorch.""", +} + + +class DenseNet121_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/densenet121-a639ec97.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 7978856, + "_metrics": { + "ImageNet-1K": { + "acc@1": 74.434, + "acc@5": 91.972, + } + }, + "_ops": 2.834, + "_file_size": 30.845, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class DenseNet161_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/densenet161-8d451a50.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 28681000, + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.138, + "acc@5": 93.560, + } + }, + "_ops": 7.728, + "_file_size": 110.369, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class DenseNet169_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/densenet169-b2777c0a.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 14149480, + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.600, + "acc@5": 92.806, + } + }, + "_ops": 3.36, + "_file_size": 54.708, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class DenseNet201_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/densenet201-c1103571.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 20013928, + "_metrics": { + "ImageNet-1K": { + "acc@1": 76.896, + "acc@5": 93.370, + } + }, + "_ops": 4.291, + "_file_size": 77.373, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", DenseNet121_Weights.IMAGENET1K_V1)) +def densenet121(*, weights: Optional[DenseNet121_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet: + r"""Densenet-121 model from + `Densely Connected Convolutional Networks `_. + + Args: + weights (:class:`~torchvision.models.DenseNet121_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.DenseNet121_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.DenseNet121_Weights + :members: + """ + weights = DenseNet121_Weights.verify(weights) + + return _densenet(32, (6, 12, 24, 16), 64, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", DenseNet161_Weights.IMAGENET1K_V1)) +def densenet161(*, weights: Optional[DenseNet161_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet: + r"""Densenet-161 model from + `Densely Connected Convolutional Networks `_. + + Args: + weights (:class:`~torchvision.models.DenseNet161_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.DenseNet161_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.DenseNet161_Weights + :members: + """ + weights = DenseNet161_Weights.verify(weights) + + return _densenet(48, (6, 12, 36, 24), 96, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", DenseNet169_Weights.IMAGENET1K_V1)) +def densenet169(*, weights: Optional[DenseNet169_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet: + r"""Densenet-169 model from + `Densely Connected Convolutional Networks `_. + + Args: + weights (:class:`~torchvision.models.DenseNet169_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.DenseNet169_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.DenseNet169_Weights + :members: + """ + weights = DenseNet169_Weights.verify(weights) + + return _densenet(32, (6, 12, 32, 32), 64, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", DenseNet201_Weights.IMAGENET1K_V1)) +def densenet201(*, weights: Optional[DenseNet201_Weights] = None, progress: bool = True, **kwargs: Any) -> DenseNet: + r"""Densenet-201 model from + `Densely Connected Convolutional Networks `_. + + Args: + weights (:class:`~torchvision.models.DenseNet201_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.DenseNet201_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.densenet.DenseNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.DenseNet201_Weights + :members: + """ + weights = DenseNet201_Weights.verify(weights) + + return _densenet(32, (6, 12, 48, 32), 64, weights, progress, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4146651c737971cc5a883b6750f2ded3051bc8ea --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__init__.py @@ -0,0 +1,7 @@ +from .faster_rcnn import * +from .fcos import * +from .keypoint_rcnn import * +from .mask_rcnn import * +from .retinanet import * +from .ssd import * +from .ssdlite import * diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..187c51b0e324462c5a93c102d347bde51c151a65 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85003998744ed6e8442f27756c07da553d0ab8fa Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/anchor_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/anchor_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1cadfb31d282812a57ae7593c1288dbb65545df Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/anchor_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/backbone_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/backbone_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..320f5334cd89c02a913d4bffcc72dd24a223dfab Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/backbone_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/faster_rcnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/faster_rcnn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6103afd43ed35f2b8f4eda5e3294abd39a5e114 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/faster_rcnn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/fcos.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/fcos.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bda2989cf50fdc92c89e8147ffac467d9e4cdd3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/fcos.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/generalized_rcnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/generalized_rcnn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35b7013ddbd1d3c431389a46b9a625e4ad1bcac5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/generalized_rcnn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/image_list.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/image_list.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b157665412d9e38f4c80804eb5f6d06270b59b3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/image_list.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/keypoint_rcnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/keypoint_rcnn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a41d6931c32f59b3cb1c91384ada21af47703ec Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/keypoint_rcnn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/mask_rcnn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/mask_rcnn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4151338b062650ec533b9d02650db1a8619c73a9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/mask_rcnn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/retinanet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/retinanet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..336ad0e0cf4d167292dfb47d43868d8fc73d3de7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/retinanet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/roi_heads.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/roi_heads.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68abd9975e66d54a4d68bc72728635a146e41a2e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/roi_heads.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/rpn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/rpn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16f83a5f93437e3406304c8bf9a6265f7c8fb78e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/rpn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/ssd.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/ssd.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b33c03da605911222094ba9555a9f10a3a064cde Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/ssd.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/ssdlite.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/ssdlite.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4501137b12047990382457e405d876f9efd09c3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/ssdlite.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/transform.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/transform.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1f1b1478917351c6f7ee042044a63e0583ce736 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/detection/__pycache__/transform.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/_utils.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..805c05a92ffb074c123540fcd36751d00a454dde --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/_utils.py @@ -0,0 +1,539 @@ +import math +from collections import OrderedDict +from typing import Optional + +import torch +from torch import nn, Tensor +from torch.nn import functional as F +from torchvision.ops import complete_box_iou_loss, distance_box_iou_loss, FrozenBatchNorm2d, generalized_box_iou_loss + + +class BalancedPositiveNegativeSampler: + """ + This class samples batches, ensuring that they contain a fixed proportion of positives + """ + + def __init__(self, batch_size_per_image: int, positive_fraction: float) -> None: + """ + Args: + batch_size_per_image (int): number of elements to be selected per image + positive_fraction (float): percentage of positive elements per batch + """ + self.batch_size_per_image = batch_size_per_image + self.positive_fraction = positive_fraction + + def __call__(self, matched_idxs: list[Tensor]) -> tuple[list[Tensor], list[Tensor]]: + """ + Args: + matched_idxs: list of tensors containing -1, 0 or positive values. + Each tensor corresponds to a specific image. + -1 values are ignored, 0 are considered as negatives and > 0 as + positives. + + Returns: + pos_idx (list[tensor]) + neg_idx (list[tensor]) + + Returns two lists of binary masks for each image. + The first list contains the positive elements that were selected, + and the second list the negative example. + """ + pos_idx = [] + neg_idx = [] + for matched_idxs_per_image in matched_idxs: + positive = torch.where(matched_idxs_per_image >= 1)[0] + negative = torch.where(matched_idxs_per_image == 0)[0] + + num_pos = int(self.batch_size_per_image * self.positive_fraction) + # protect against not enough positive examples + num_pos = min(positive.numel(), num_pos) + num_neg = self.batch_size_per_image - num_pos + # protect against not enough negative examples + num_neg = min(negative.numel(), num_neg) + + # randomly select positive and negative examples + perm1 = torch.randperm(positive.numel(), device=positive.device)[:num_pos] + perm2 = torch.randperm(negative.numel(), device=negative.device)[:num_neg] + + pos_idx_per_image = positive[perm1] + neg_idx_per_image = negative[perm2] + + # create binary mask from indices + pos_idx_per_image_mask = torch.zeros_like(matched_idxs_per_image, dtype=torch.uint8) + neg_idx_per_image_mask = torch.zeros_like(matched_idxs_per_image, dtype=torch.uint8) + + pos_idx_per_image_mask[pos_idx_per_image] = 1 + neg_idx_per_image_mask[neg_idx_per_image] = 1 + + pos_idx.append(pos_idx_per_image_mask) + neg_idx.append(neg_idx_per_image_mask) + + return pos_idx, neg_idx + + +@torch.jit._script_if_tracing +def encode_boxes(reference_boxes: Tensor, proposals: Tensor, weights: Tensor) -> Tensor: + """ + Encode a set of proposals with respect to some + reference boxes + + Args: + reference_boxes (Tensor): reference boxes + proposals (Tensor): boxes to be encoded + weights (Tensor[4]): the weights for ``(x, y, w, h)`` + """ + + # perform some unpacking to make it JIT-fusion friendly + wx = weights[0] + wy = weights[1] + ww = weights[2] + wh = weights[3] + + proposals_x1 = proposals[:, 0].unsqueeze(1) + proposals_y1 = proposals[:, 1].unsqueeze(1) + proposals_x2 = proposals[:, 2].unsqueeze(1) + proposals_y2 = proposals[:, 3].unsqueeze(1) + + reference_boxes_x1 = reference_boxes[:, 0].unsqueeze(1) + reference_boxes_y1 = reference_boxes[:, 1].unsqueeze(1) + reference_boxes_x2 = reference_boxes[:, 2].unsqueeze(1) + reference_boxes_y2 = reference_boxes[:, 3].unsqueeze(1) + + # implementation starts here + ex_widths = proposals_x2 - proposals_x1 + ex_heights = proposals_y2 - proposals_y1 + ex_ctr_x = proposals_x1 + 0.5 * ex_widths + ex_ctr_y = proposals_y1 + 0.5 * ex_heights + + gt_widths = reference_boxes_x2 - reference_boxes_x1 + gt_heights = reference_boxes_y2 - reference_boxes_y1 + gt_ctr_x = reference_boxes_x1 + 0.5 * gt_widths + gt_ctr_y = reference_boxes_y1 + 0.5 * gt_heights + + targets_dx = wx * (gt_ctr_x - ex_ctr_x) / ex_widths + targets_dy = wy * (gt_ctr_y - ex_ctr_y) / ex_heights + targets_dw = ww * torch.log(gt_widths / ex_widths) + targets_dh = wh * torch.log(gt_heights / ex_heights) + + targets = torch.cat((targets_dx, targets_dy, targets_dw, targets_dh), dim=1) + return targets + + +class BoxCoder: + """ + This class encodes and decodes a set of bounding boxes into + the representation used for training the regressors. + """ + + def __init__( + self, weights: tuple[float, float, float, float], bbox_xform_clip: float = math.log(1000.0 / 16) + ) -> None: + """ + Args: + weights (4-element tuple) + bbox_xform_clip (float) + """ + self.weights = weights + self.bbox_xform_clip = bbox_xform_clip + + def encode(self, reference_boxes: list[Tensor], proposals: list[Tensor]) -> list[Tensor]: + boxes_per_image = [len(b) for b in reference_boxes] + reference_boxes = torch.cat(reference_boxes, dim=0) + proposals = torch.cat(proposals, dim=0) + targets = self.encode_single(reference_boxes, proposals) + return targets.split(boxes_per_image, 0) + + def encode_single(self, reference_boxes: Tensor, proposals: Tensor) -> Tensor: + """ + Encode a set of proposals with respect to some + reference boxes + + Args: + reference_boxes (Tensor): reference boxes + proposals (Tensor): boxes to be encoded + """ + dtype = reference_boxes.dtype + device = reference_boxes.device + weights = torch.as_tensor(self.weights, dtype=dtype, device=device) + targets = encode_boxes(reference_boxes, proposals, weights) + + return targets + + def decode(self, rel_codes: Tensor, boxes: list[Tensor]) -> Tensor: + torch._assert( + isinstance(boxes, (list, tuple)), + "This function expects boxes of type list or tuple.", + ) + torch._assert( + isinstance(rel_codes, torch.Tensor), + "This function expects rel_codes of type torch.Tensor.", + ) + boxes_per_image = [b.size(0) for b in boxes] + concat_boxes = torch.cat(boxes, dim=0) + box_sum = 0 + for val in boxes_per_image: + box_sum += val + if box_sum > 0: + rel_codes = rel_codes.reshape(box_sum, -1) + pred_boxes = self.decode_single(rel_codes, concat_boxes) + if box_sum > 0: + pred_boxes = pred_boxes.reshape(box_sum, -1, 4) + return pred_boxes + + def decode_single(self, rel_codes: Tensor, boxes: Tensor) -> Tensor: + """ + From a set of original boxes and encoded relative box offsets, + get the decoded boxes. + + Args: + rel_codes (Tensor): encoded boxes + boxes (Tensor): reference boxes. + """ + + boxes = boxes.to(rel_codes.dtype) + + widths = boxes[:, 2] - boxes[:, 0] + heights = boxes[:, 3] - boxes[:, 1] + ctr_x = boxes[:, 0] + 0.5 * widths + ctr_y = boxes[:, 1] + 0.5 * heights + + wx, wy, ww, wh = self.weights + dx = rel_codes[:, 0::4] / wx + dy = rel_codes[:, 1::4] / wy + dw = rel_codes[:, 2::4] / ww + dh = rel_codes[:, 3::4] / wh + + # Prevent sending too large values into torch.exp() + dw = torch.clamp(dw, max=self.bbox_xform_clip) + dh = torch.clamp(dh, max=self.bbox_xform_clip) + + pred_ctr_x = dx * widths[:, None] + ctr_x[:, None] + pred_ctr_y = dy * heights[:, None] + ctr_y[:, None] + pred_w = torch.exp(dw) * widths[:, None] + pred_h = torch.exp(dh) * heights[:, None] + + # Distance from center to box's corner. + c_to_c_h = torch.tensor(0.5, dtype=pred_ctr_y.dtype, device=pred_h.device) * pred_h + c_to_c_w = torch.tensor(0.5, dtype=pred_ctr_x.dtype, device=pred_w.device) * pred_w + + pred_boxes1 = pred_ctr_x - c_to_c_w + pred_boxes2 = pred_ctr_y - c_to_c_h + pred_boxes3 = pred_ctr_x + c_to_c_w + pred_boxes4 = pred_ctr_y + c_to_c_h + pred_boxes = torch.stack((pred_boxes1, pred_boxes2, pred_boxes3, pred_boxes4), dim=2).flatten(1) + return pred_boxes + + +class BoxLinearCoder: + """ + The linear box-to-box transform defined in FCOS. The transformation is parameterized + by the distance from the center of (square) src box to 4 edges of the target box. + """ + + def __init__(self, normalize_by_size: bool = True) -> None: + """ + Args: + normalize_by_size (bool): normalize deltas by the size of src (anchor) boxes. + """ + self.normalize_by_size = normalize_by_size + + def encode(self, reference_boxes: Tensor, proposals: Tensor) -> Tensor: + """ + Encode a set of proposals with respect to some reference boxes + + Args: + reference_boxes (Tensor): reference boxes + proposals (Tensor): boxes to be encoded + + Returns: + Tensor: the encoded relative box offsets that can be used to + decode the boxes. + + """ + + # get the center of reference_boxes + reference_boxes_ctr_x = 0.5 * (reference_boxes[..., 0] + reference_boxes[..., 2]) + reference_boxes_ctr_y = 0.5 * (reference_boxes[..., 1] + reference_boxes[..., 3]) + + # get box regression transformation deltas + target_l = reference_boxes_ctr_x - proposals[..., 0] + target_t = reference_boxes_ctr_y - proposals[..., 1] + target_r = proposals[..., 2] - reference_boxes_ctr_x + target_b = proposals[..., 3] - reference_boxes_ctr_y + + targets = torch.stack((target_l, target_t, target_r, target_b), dim=-1) + + if self.normalize_by_size: + reference_boxes_w = reference_boxes[..., 2] - reference_boxes[..., 0] + reference_boxes_h = reference_boxes[..., 3] - reference_boxes[..., 1] + reference_boxes_size = torch.stack( + (reference_boxes_w, reference_boxes_h, reference_boxes_w, reference_boxes_h), dim=-1 + ) + targets = targets / reference_boxes_size + return targets + + def decode(self, rel_codes: Tensor, boxes: Tensor) -> Tensor: + """ + From a set of original boxes and encoded relative box offsets, + get the decoded boxes. + + Args: + rel_codes (Tensor): encoded boxes + boxes (Tensor): reference boxes. + + Returns: + Tensor: the predicted boxes with the encoded relative box offsets. + + .. note:: + This method assumes that ``rel_codes`` and ``boxes`` have same size for 0th dimension. i.e. ``len(rel_codes) == len(boxes)``. + + """ + + boxes = boxes.to(dtype=rel_codes.dtype) + + ctr_x = 0.5 * (boxes[..., 0] + boxes[..., 2]) + ctr_y = 0.5 * (boxes[..., 1] + boxes[..., 3]) + + if self.normalize_by_size: + boxes_w = boxes[..., 2] - boxes[..., 0] + boxes_h = boxes[..., 3] - boxes[..., 1] + + list_box_size = torch.stack((boxes_w, boxes_h, boxes_w, boxes_h), dim=-1) + rel_codes = rel_codes * list_box_size + + pred_boxes1 = ctr_x - rel_codes[..., 0] + pred_boxes2 = ctr_y - rel_codes[..., 1] + pred_boxes3 = ctr_x + rel_codes[..., 2] + pred_boxes4 = ctr_y + rel_codes[..., 3] + + pred_boxes = torch.stack((pred_boxes1, pred_boxes2, pred_boxes3, pred_boxes4), dim=-1) + return pred_boxes + + +class Matcher: + """ + This class assigns to each predicted "element" (e.g., a box) a ground-truth + element. Each predicted element will have exactly zero or one matches; each + ground-truth element may be assigned to zero or more predicted elements. + + Matching is based on the MxN match_quality_matrix, that characterizes how well + each (ground-truth, predicted)-pair match. For example, if the elements are + boxes, the matrix may contain box IoU overlap values. + + The matcher returns a tensor of size N containing the index of the ground-truth + element m that matches to prediction n. If there is no match, a negative value + is returned. + """ + + BELOW_LOW_THRESHOLD = -1 + BETWEEN_THRESHOLDS = -2 + + __annotations__ = { + "BELOW_LOW_THRESHOLD": int, + "BETWEEN_THRESHOLDS": int, + } + + def __init__(self, high_threshold: float, low_threshold: float, allow_low_quality_matches: bool = False) -> None: + """ + Args: + high_threshold (float): quality values greater than or equal to + this value are candidate matches. + low_threshold (float): a lower quality threshold used to stratify + matches into three levels: + 1) matches >= high_threshold + 2) BETWEEN_THRESHOLDS matches in [low_threshold, high_threshold) + 3) BELOW_LOW_THRESHOLD matches in [0, low_threshold) + allow_low_quality_matches (bool): if True, produce additional matches + for predictions that have only low-quality match candidates. See + set_low_quality_matches_ for more details. + """ + self.BELOW_LOW_THRESHOLD = -1 + self.BETWEEN_THRESHOLDS = -2 + torch._assert(low_threshold <= high_threshold, "low_threshold should be <= high_threshold") + self.high_threshold = high_threshold + self.low_threshold = low_threshold + self.allow_low_quality_matches = allow_low_quality_matches + + def __call__(self, match_quality_matrix: Tensor) -> Tensor: + """ + Args: + match_quality_matrix (Tensor[float]): an MxN tensor, containing the + pairwise quality between M ground-truth elements and N predicted elements. + + Returns: + matches (Tensor[int64]): an N tensor where N[i] is a matched gt in + [0, M - 1] or a negative value indicating that prediction i could not + be matched. + """ + if match_quality_matrix.numel() == 0: + # empty targets or proposals not supported during training + if match_quality_matrix.shape[0] == 0: + raise ValueError("No ground-truth boxes available for one of the images during training") + else: + raise ValueError("No proposal boxes available for one of the images during training") + + # match_quality_matrix is M (gt) x N (predicted) + # Max over gt elements (dim 0) to find best gt candidate for each prediction + matched_vals, matches = match_quality_matrix.max(dim=0) + if self.allow_low_quality_matches: + all_matches = matches.clone() + else: + all_matches = None # type: ignore[assignment] + + # Assign candidate matches with low quality to negative (unassigned) values + below_low_threshold = matched_vals < self.low_threshold + between_thresholds = (matched_vals >= self.low_threshold) & (matched_vals < self.high_threshold) + matches[below_low_threshold] = self.BELOW_LOW_THRESHOLD + matches[between_thresholds] = self.BETWEEN_THRESHOLDS + + if self.allow_low_quality_matches: + if all_matches is None: + torch._assert(False, "all_matches should not be None") + else: + self.set_low_quality_matches_(matches, all_matches, match_quality_matrix) + + return matches + + def set_low_quality_matches_(self, matches: Tensor, all_matches: Tensor, match_quality_matrix: Tensor) -> None: + """ + Produce additional matches for predictions that have only low-quality matches. + Specifically, for each ground-truth find the set of predictions that have + maximum overlap with it (including ties); for each prediction in that set, if + it is unmatched, then match it to the ground-truth with which it has the highest + quality value. + """ + # For each gt, find the prediction with which it has the highest quality + highest_quality_foreach_gt, _ = match_quality_matrix.max(dim=1) + # Find the highest quality match available, even if it is low, including ties + gt_pred_pairs_of_highest_quality = torch.where(match_quality_matrix == highest_quality_foreach_gt[:, None]) + # Example gt_pred_pairs_of_highest_quality: + # (tensor([0, 1, 1, 2, 2, 3, 3, 4, 5, 5]), + # tensor([39796, 32055, 32070, 39190, 40255, 40390, 41455, 45470, 45325, 46390])) + # Each element in the first tensor is a gt index, and each element in second tensor is a prediction index + # Note how gt items 1, 2, 3, and 5 each have two ties + + pred_inds_to_update = gt_pred_pairs_of_highest_quality[1] + matches[pred_inds_to_update] = all_matches[pred_inds_to_update] + + +class SSDMatcher(Matcher): + def __init__(self, threshold: float) -> None: + super().__init__(threshold, threshold, allow_low_quality_matches=False) + + def __call__(self, match_quality_matrix: Tensor) -> Tensor: + matches = super().__call__(match_quality_matrix) + + # For each gt, find the prediction with which it has the highest quality + _, highest_quality_pred_foreach_gt = match_quality_matrix.max(dim=1) + matches[highest_quality_pred_foreach_gt] = torch.arange( + highest_quality_pred_foreach_gt.size(0), dtype=torch.int64, device=highest_quality_pred_foreach_gt.device + ) + + return matches + + +def overwrite_eps(model: nn.Module, eps: float) -> None: + """ + This method overwrites the default eps values of all the + FrozenBatchNorm2d layers of the model with the provided value. + This is necessary to address the BC-breaking change introduced + by the bug-fix at pytorch/vision#2933. The overwrite is applied + only when the pretrained weights are loaded to maintain compatibility + with previous versions. + + Args: + model (nn.Module): The model on which we perform the overwrite. + eps (float): The new value of eps. + """ + for module in model.modules(): + if isinstance(module, FrozenBatchNorm2d): + module.eps = eps + + +def retrieve_out_channels(model: nn.Module, size: tuple[int, int]) -> list[int]: + """ + This method retrieves the number of output channels of a specific model. + + Args: + model (nn.Module): The model for which we estimate the out_channels. + It should return a single Tensor or an OrderedDict[Tensor]. + size (Tuple[int, int]): The size (wxh) of the input. + + Returns: + out_channels (List[int]): A list of the output channels of the model. + """ + in_training = model.training + model.eval() + + with torch.no_grad(): + # Use dummy data to retrieve the feature map sizes to avoid hard-coding their values + device = next(model.parameters()).device + tmp_img = torch.zeros((1, 3, size[1], size[0]), device=device) + features = model(tmp_img) + if isinstance(features, torch.Tensor): + features = OrderedDict([("0", features)]) + out_channels = [x.size(1) for x in features.values()] + + if in_training: + model.train() + + return out_channels + + +@torch.jit.unused +def _fake_cast_onnx(v: Tensor) -> int: + return v # type: ignore[return-value] + + +def _topk_min(input: Tensor, orig_kval: int, axis: int) -> int: + """ + ONNX spec requires the k-value to be less than or equal to the number of inputs along + provided dim. Certain models use the number of elements along a particular axis instead of K + if K exceeds the number of elements along that axis. Previously, python's min() function was + used to determine whether to use the provided k-value or the specified dim axis value. + + However, in cases where the model is being exported in tracing mode, python min() is + static causing the model to be traced incorrectly and eventually fail at the topk node. + In order to avoid this situation, in tracing mode, torch.min() is used instead. + + Args: + input (Tensor): The original input tensor. + orig_kval (int): The provided k-value. + axis(int): Axis along which we retrieve the input size. + + Returns: + min_kval (int): Appropriately selected k-value. + """ + if not torch.jit.is_tracing(): + return min(orig_kval, input.size(axis)) + axis_dim_val = torch._shape_as_tensor(input)[axis].unsqueeze(0) + min_kval = torch.min(torch.cat((torch.tensor([orig_kval], dtype=axis_dim_val.dtype), axis_dim_val), 0)) + return _fake_cast_onnx(min_kval) + + +def _box_loss( + type: str, + box_coder: BoxCoder, + anchors_per_image: Tensor, + matched_gt_boxes_per_image: Tensor, + bbox_regression_per_image: Tensor, + cnf: Optional[dict[str, float]] = None, +) -> Tensor: + torch._assert(type in ["l1", "smooth_l1", "ciou", "diou", "giou"], f"Unsupported loss: {type}") + + if type == "l1": + target_regression = box_coder.encode_single(matched_gt_boxes_per_image, anchors_per_image) + return F.l1_loss(bbox_regression_per_image, target_regression, reduction="sum") + elif type == "smooth_l1": + target_regression = box_coder.encode_single(matched_gt_boxes_per_image, anchors_per_image) + beta = cnf["beta"] if cnf is not None and "beta" in cnf else 1.0 + return F.smooth_l1_loss(bbox_regression_per_image, target_regression, reduction="sum", beta=beta) + else: + bbox_per_image = box_coder.decode_single(bbox_regression_per_image, anchors_per_image) + eps = cnf["eps"] if cnf is not None and "eps" in cnf else 1e-7 + if type == "ciou": + return complete_box_iou_loss(bbox_per_image, matched_gt_boxes_per_image, reduction="sum", eps=eps) + if type == "diou": + return distance_box_iou_loss(bbox_per_image, matched_gt_boxes_per_image, reduction="sum", eps=eps) + # otherwise giou + return generalized_box_iou_loss(bbox_per_image, matched_gt_boxes_per_image, reduction="sum", eps=eps) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/anchor_utils.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/anchor_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4722e1550c2aa497fc3fbe9e033ddd15a1121cf0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/anchor_utils.py @@ -0,0 +1,268 @@ +import math +from typing import Optional + +import torch +from torch import nn, Tensor + +from .image_list import ImageList + + +class AnchorGenerator(nn.Module): + """ + Module that generates anchors for a set of feature maps and + image sizes. + + The module supports computing anchors at multiple sizes and aspect ratios + per feature map. This module assumes aspect ratio = height / width for + each anchor. + + sizes and aspect_ratios should have the same number of elements, and it should + correspond to the number of feature maps. + + sizes[i] and aspect_ratios[i] can have an arbitrary number of elements, + and AnchorGenerator will output a set of sizes[i] * aspect_ratios[i] anchors + per spatial location for feature map i. + + Args: + sizes (Tuple[Tuple[int]]): + aspect_ratios (Tuple[Tuple[float]]): + """ + + __annotations__ = { + "cell_anchors": list[torch.Tensor], + } + + def __init__( + self, + sizes=((128, 256, 512),), + aspect_ratios=((0.5, 1.0, 2.0),), + ): + super().__init__() + + if not isinstance(sizes[0], (list, tuple)): + # TODO change this + sizes = tuple((s,) for s in sizes) + if not isinstance(aspect_ratios[0], (list, tuple)): + aspect_ratios = (aspect_ratios,) * len(sizes) + + self.sizes = sizes + self.aspect_ratios = aspect_ratios + self.cell_anchors = [ + self.generate_anchors(size, aspect_ratio) for size, aspect_ratio in zip(sizes, aspect_ratios) + ] + + # TODO: https://github.com/pytorch/pytorch/issues/26792 + # For every (aspect_ratios, scales) combination, output a zero-centered anchor with those values. + # (scales, aspect_ratios) are usually an element of zip(self.scales, self.aspect_ratios) + # This method assumes aspect ratio = height / width for an anchor. + def generate_anchors( + self, + scales: list[int], + aspect_ratios: list[float], + dtype: torch.dtype = torch.float32, + device: torch.device = torch.device("cpu"), + ) -> Tensor: + scales = torch.as_tensor(scales, dtype=dtype, device=device) + aspect_ratios = torch.as_tensor(aspect_ratios, dtype=dtype, device=device) + h_ratios = torch.sqrt(aspect_ratios) + w_ratios = 1 / h_ratios + + ws = (w_ratios[:, None] * scales[None, :]).view(-1) + hs = (h_ratios[:, None] * scales[None, :]).view(-1) + + base_anchors = torch.stack([-ws, -hs, ws, hs], dim=1) / 2 + return base_anchors.round() + + def set_cell_anchors(self, dtype: torch.dtype, device: torch.device): + self.cell_anchors = [cell_anchor.to(dtype=dtype, device=device) for cell_anchor in self.cell_anchors] + + def num_anchors_per_location(self) -> list[int]: + return [len(s) * len(a) for s, a in zip(self.sizes, self.aspect_ratios)] + + # For every combination of (a, (g, s), i) in (self.cell_anchors, zip(grid_sizes, strides), 0:2), + # output g[i] anchors that are s[i] distance apart in direction i, with the same dimensions as a. + def grid_anchors(self, grid_sizes: list[list[int]], strides: list[list[Tensor]]) -> list[Tensor]: + anchors = [] + cell_anchors = self.cell_anchors + torch._assert(cell_anchors is not None, "cell_anchors should not be None") + torch._assert( + len(grid_sizes) == len(strides) == len(cell_anchors), + "Anchors should be Tuple[Tuple[int]] because each feature " + "map could potentially have different sizes and aspect ratios. " + "There needs to be a match between the number of " + "feature maps passed and the number of sizes / aspect ratios specified.", + ) + + for size, stride, base_anchors in zip(grid_sizes, strides, cell_anchors): + grid_height, grid_width = size + stride_height, stride_width = stride + device = base_anchors.device + + # For output anchor, compute [x_center, y_center, x_center, y_center] + shifts_x = torch.arange(0, grid_width, dtype=torch.int32, device=device) * stride_width + shifts_y = torch.arange(0, grid_height, dtype=torch.int32, device=device) * stride_height + shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x, indexing="ij") + shift_x = shift_x.reshape(-1) + shift_y = shift_y.reshape(-1) + shifts = torch.stack((shift_x, shift_y, shift_x, shift_y), dim=1) + + # For every (base anchor, output anchor) pair, + # offset each zero-centered base anchor by the center of the output anchor. + anchors.append((shifts.view(-1, 1, 4) + base_anchors.view(1, -1, 4)).reshape(-1, 4)) + + return anchors + + def forward(self, image_list: ImageList, feature_maps: list[Tensor]) -> list[Tensor]: + grid_sizes = [feature_map.shape[-2:] for feature_map in feature_maps] + image_size = image_list.tensors.shape[-2:] + dtype, device = feature_maps[0].dtype, feature_maps[0].device + strides = [ + [ + torch.empty((), dtype=torch.int64, device=device).fill_(image_size[0] // g[0]), + torch.empty((), dtype=torch.int64, device=device).fill_(image_size[1] // g[1]), + ] + for g in grid_sizes + ] + self.set_cell_anchors(dtype, device) + anchors_over_all_feature_maps = self.grid_anchors(grid_sizes, strides) + anchors: list[list[torch.Tensor]] = [] + for _ in range(len(image_list.image_sizes)): + anchors_in_image = [anchors_per_feature_map for anchors_per_feature_map in anchors_over_all_feature_maps] + anchors.append(anchors_in_image) + anchors = [torch.cat(anchors_per_image) for anchors_per_image in anchors] + return anchors + + +class DefaultBoxGenerator(nn.Module): + """ + This module generates the default boxes of SSD for a set of feature maps and image sizes. + + Args: + aspect_ratios (List[List[int]]): A list with all the aspect ratios used in each feature map. + min_ratio (float): The minimum scale :math:`\text{s}_{\text{min}}` of the default boxes used in the estimation + of the scales of each feature map. It is used only if the ``scales`` parameter is not provided. + max_ratio (float): The maximum scale :math:`\text{s}_{\text{max}}` of the default boxes used in the estimation + of the scales of each feature map. It is used only if the ``scales`` parameter is not provided. + scales (List[float]], optional): The scales of the default boxes. If not provided it will be estimated using + the ``min_ratio`` and ``max_ratio`` parameters. + steps (List[int]], optional): It's a hyper-parameter that affects the tiling of default boxes. If not provided + it will be estimated from the data. + clip (bool): Whether the standardized values of default boxes should be clipped between 0 and 1. The clipping + is applied while the boxes are encoded in format ``(cx, cy, w, h)``. + """ + + def __init__( + self, + aspect_ratios: list[list[int]], + min_ratio: float = 0.15, + max_ratio: float = 0.9, + scales: Optional[list[float]] = None, + steps: Optional[list[int]] = None, + clip: bool = True, + ): + super().__init__() + if steps is not None and len(aspect_ratios) != len(steps): + raise ValueError("aspect_ratios and steps should have the same length") + self.aspect_ratios = aspect_ratios + self.steps = steps + self.clip = clip + num_outputs = len(aspect_ratios) + + # Estimation of default boxes scales + if scales is None: + if num_outputs > 1: + range_ratio = max_ratio - min_ratio + self.scales = [min_ratio + range_ratio * k / (num_outputs - 1.0) for k in range(num_outputs)] + self.scales.append(1.0) + else: + self.scales = [min_ratio, max_ratio] + else: + self.scales = scales + + self._wh_pairs = self._generate_wh_pairs(num_outputs) + + def _generate_wh_pairs( + self, num_outputs: int, dtype: torch.dtype = torch.float32, device: torch.device = torch.device("cpu") + ) -> list[Tensor]: + _wh_pairs: list[Tensor] = [] + for k in range(num_outputs): + # Adding the 2 default width-height pairs for aspect ratio 1 and scale s'k + s_k = self.scales[k] + s_prime_k = math.sqrt(self.scales[k] * self.scales[k + 1]) + wh_pairs = [[s_k, s_k], [s_prime_k, s_prime_k]] + + # Adding 2 pairs for each aspect ratio of the feature map k + for ar in self.aspect_ratios[k]: + sq_ar = math.sqrt(ar) + w = self.scales[k] * sq_ar + h = self.scales[k] / sq_ar + wh_pairs.extend([[w, h], [h, w]]) + + _wh_pairs.append(torch.as_tensor(wh_pairs, dtype=dtype, device=device)) + return _wh_pairs + + def num_anchors_per_location(self) -> list[int]: + # Estimate num of anchors based on aspect ratios: 2 default boxes + 2 * ratios of feaure map. + return [2 + 2 * len(r) for r in self.aspect_ratios] + + # Default Boxes calculation based on page 6 of SSD paper + def _grid_default_boxes( + self, grid_sizes: list[list[int]], image_size: list[int], dtype: torch.dtype = torch.float32 + ) -> Tensor: + default_boxes = [] + for k, f_k in enumerate(grid_sizes): + # Now add the default boxes for each width-height pair + if self.steps is not None: + x_f_k = image_size[1] / self.steps[k] + y_f_k = image_size[0] / self.steps[k] + else: + y_f_k, x_f_k = f_k + + shifts_x = ((torch.arange(0, f_k[1]) + 0.5) / x_f_k).to(dtype=dtype) + shifts_y = ((torch.arange(0, f_k[0]) + 0.5) / y_f_k).to(dtype=dtype) + shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x, indexing="ij") + shift_x = shift_x.reshape(-1) + shift_y = shift_y.reshape(-1) + + shifts = torch.stack((shift_x, shift_y) * len(self._wh_pairs[k]), dim=-1).reshape(-1, 2) + # Clipping the default boxes while the boxes are encoded in format (cx, cy, w, h) + _wh_pair = self._wh_pairs[k].clamp(min=0, max=1) if self.clip else self._wh_pairs[k] + wh_pairs = _wh_pair.repeat((f_k[0] * f_k[1]), 1) + + default_box = torch.cat((shifts, wh_pairs), dim=1) + + default_boxes.append(default_box) + + return torch.cat(default_boxes, dim=0) + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"aspect_ratios={self.aspect_ratios}" + f", clip={self.clip}" + f", scales={self.scales}" + f", steps={self.steps}" + ")" + ) + return s + + def forward(self, image_list: ImageList, feature_maps: list[Tensor]) -> list[Tensor]: + grid_sizes = [feature_map.shape[-2:] for feature_map in feature_maps] + image_size = image_list.tensors.shape[-2:] + dtype, device = feature_maps[0].dtype, feature_maps[0].device + default_boxes = self._grid_default_boxes(grid_sizes, image_size, dtype=dtype) + default_boxes = default_boxes.to(device) + + dboxes = [] + x_y_size = torch.tensor([image_size[1], image_size[0]], device=default_boxes.device) + for _ in image_list.image_sizes: + dboxes_in_image = default_boxes + dboxes_in_image = torch.cat( + [ + (dboxes_in_image[:, :2] - 0.5 * dboxes_in_image[:, 2:]) * x_y_size, + (dboxes_in_image[:, :2] + 0.5 * dboxes_in_image[:, 2:]) * x_y_size, + ], + -1, + ) + dboxes.append(dboxes_in_image) + return dboxes diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/backbone_utils.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/backbone_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f24c121d59a06186fc104cdfe5634bcd5615cf7e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/backbone_utils.py @@ -0,0 +1,244 @@ +import warnings +from typing import Callable, Optional, Union + +from torch import nn, Tensor +from torchvision.ops import misc as misc_nn_ops +from torchvision.ops.feature_pyramid_network import ExtraFPNBlock, FeaturePyramidNetwork, LastLevelMaxPool + +from .. import mobilenet, resnet +from .._api import _get_enum_from_fn, WeightsEnum +from .._utils import handle_legacy_interface, IntermediateLayerGetter + + +class BackboneWithFPN(nn.Module): + """ + Adds a FPN on top of a model. + Internally, it uses torchvision.models._utils.IntermediateLayerGetter to + extract a submodel that returns the feature maps specified in return_layers. + The same limitations of IntermediateLayerGetter apply here. + Args: + backbone (nn.Module) + return_layers (Dict[name, new_name]): a dict containing the names + of the modules for which the activations will be returned as + the key of the dict, and the value of the dict is the name + of the returned activation (which the user can specify). + in_channels_list (List[int]): number of channels for each feature map + that is returned, in the order they are present in the OrderedDict + out_channels (int): number of channels in the FPN. + norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None + Attributes: + out_channels (int): the number of channels in the FPN + """ + + def __init__( + self, + backbone: nn.Module, + return_layers: dict[str, str], + in_channels_list: list[int], + out_channels: int, + extra_blocks: Optional[ExtraFPNBlock] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + + if extra_blocks is None: + extra_blocks = LastLevelMaxPool() + + self.body = IntermediateLayerGetter(backbone, return_layers=return_layers) + self.fpn = FeaturePyramidNetwork( + in_channels_list=in_channels_list, + out_channels=out_channels, + extra_blocks=extra_blocks, + norm_layer=norm_layer, + ) + self.out_channels = out_channels + + def forward(self, x: Tensor) -> dict[str, Tensor]: + x = self.body(x) + x = self.fpn(x) + return x + + +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: _get_enum_from_fn(resnet.__dict__[kwargs["backbone_name"]])["IMAGENET1K_V1"], + ), +) +def resnet_fpn_backbone( + *, + backbone_name: str, + weights: Optional[WeightsEnum], + norm_layer: Callable[..., nn.Module] = misc_nn_ops.FrozenBatchNorm2d, + trainable_layers: int = 3, + returned_layers: Optional[list[int]] = None, + extra_blocks: Optional[ExtraFPNBlock] = None, +) -> BackboneWithFPN: + """ + Constructs a specified ResNet backbone with FPN on top. Freezes the specified number of layers in the backbone. + + Examples:: + + >>> import torch + >>> from torchvision.models import ResNet50_Weights + >>> from torchvision.models.detection.backbone_utils import resnet_fpn_backbone + >>> backbone = resnet_fpn_backbone(backbone_name='resnet50', weights=ResNet50_Weights.DEFAULT, trainable_layers=3) + >>> # get some dummy image + >>> x = torch.rand(1,3,64,64) + >>> # compute the output + >>> output = backbone(x) + >>> print([(k, v.shape) for k, v in output.items()]) + >>> # returns + >>> [('0', torch.Size([1, 256, 16, 16])), + >>> ('1', torch.Size([1, 256, 8, 8])), + >>> ('2', torch.Size([1, 256, 4, 4])), + >>> ('3', torch.Size([1, 256, 2, 2])), + >>> ('pool', torch.Size([1, 256, 1, 1]))] + + Args: + backbone_name (string): resnet architecture. Possible values are 'resnet18', 'resnet34', 'resnet50', + 'resnet101', 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d', 'wide_resnet50_2', 'wide_resnet101_2' + weights (WeightsEnum, optional): The pretrained weights for the model + norm_layer (callable): it is recommended to use the default value. For details visit: + (https://github.com/facebookresearch/maskrcnn-benchmark/issues/267) + trainable_layers (int): number of trainable (not frozen) layers starting from final block. + Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. + returned_layers (list of int): The layers of the network to return. Each entry must be in ``[1, 4]``. + By default, all layers are returned. + extra_blocks (ExtraFPNBlock or None): if provided, extra operations will + be performed. It is expected to take the fpn features, the original + features and the names of the original features as input, and returns + a new list of feature maps and their corresponding names. By + default, a ``LastLevelMaxPool`` is used. + """ + backbone = resnet.__dict__[backbone_name](weights=weights, norm_layer=norm_layer) + return _resnet_fpn_extractor(backbone, trainable_layers, returned_layers, extra_blocks) + + +def _resnet_fpn_extractor( + backbone: resnet.ResNet, + trainable_layers: int, + returned_layers: Optional[list[int]] = None, + extra_blocks: Optional[ExtraFPNBlock] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, +) -> BackboneWithFPN: + + # select layers that won't be frozen + if trainable_layers < 0 or trainable_layers > 5: + raise ValueError(f"Trainable layers should be in the range [0,5], got {trainable_layers}") + layers_to_train = ["layer4", "layer3", "layer2", "layer1", "conv1"][:trainable_layers] + if trainable_layers == 5: + layers_to_train.append("bn1") + for name, parameter in backbone.named_parameters(): + if all([not name.startswith(layer) for layer in layers_to_train]): + parameter.requires_grad_(False) + + if extra_blocks is None: + extra_blocks = LastLevelMaxPool() + + if returned_layers is None: + returned_layers = [1, 2, 3, 4] + if min(returned_layers) <= 0 or max(returned_layers) >= 5: + raise ValueError(f"Each returned layer should be in the range [1,4]. Got {returned_layers}") + return_layers = {f"layer{k}": str(v) for v, k in enumerate(returned_layers)} + + in_channels_stage2 = backbone.inplanes // 8 + in_channels_list = [in_channels_stage2 * 2 ** (i - 1) for i in returned_layers] + out_channels = 256 + return BackboneWithFPN( + backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks, norm_layer=norm_layer + ) + + +def _validate_trainable_layers( + is_trained: bool, + trainable_backbone_layers: Optional[int], + max_value: int, + default_value: int, +) -> int: + # don't freeze any layers if pretrained model or backbone is not used + if not is_trained: + if trainable_backbone_layers is not None: + warnings.warn( + "Changing trainable_backbone_layers has no effect if " + "neither pretrained nor pretrained_backbone have been set to True, " + f"falling back to trainable_backbone_layers={max_value} so that all layers are trainable" + ) + trainable_backbone_layers = max_value + + # by default freeze first blocks + if trainable_backbone_layers is None: + trainable_backbone_layers = default_value + if trainable_backbone_layers < 0 or trainable_backbone_layers > max_value: + raise ValueError( + f"Trainable backbone layers should be in the range [0,{max_value}], got {trainable_backbone_layers} " + ) + return trainable_backbone_layers + + +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: _get_enum_from_fn(mobilenet.__dict__[kwargs["backbone_name"]])["IMAGENET1K_V1"], + ), +) +def mobilenet_backbone( + *, + backbone_name: str, + weights: Optional[WeightsEnum], + fpn: bool, + norm_layer: Callable[..., nn.Module] = misc_nn_ops.FrozenBatchNorm2d, + trainable_layers: int = 2, + returned_layers: Optional[list[int]] = None, + extra_blocks: Optional[ExtraFPNBlock] = None, +) -> nn.Module: + backbone = mobilenet.__dict__[backbone_name](weights=weights, norm_layer=norm_layer) + return _mobilenet_extractor(backbone, fpn, trainable_layers, returned_layers, extra_blocks) + + +def _mobilenet_extractor( + backbone: Union[mobilenet.MobileNetV2, mobilenet.MobileNetV3], + fpn: bool, + trainable_layers: int, + returned_layers: Optional[list[int]] = None, + extra_blocks: Optional[ExtraFPNBlock] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, +) -> nn.Module: + backbone = backbone.features + # Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks. + # The first and last blocks are always included because they are the C0 (conv1) and Cn. + stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1] + num_stages = len(stage_indices) + + # find the index of the layer from which we won't freeze + if trainable_layers < 0 or trainable_layers > num_stages: + raise ValueError(f"Trainable layers should be in the range [0,{num_stages}], got {trainable_layers} ") + freeze_before = len(backbone) if trainable_layers == 0 else stage_indices[num_stages - trainable_layers] + + for b in backbone[:freeze_before]: + for parameter in b.parameters(): + parameter.requires_grad_(False) + + out_channels = 256 + if fpn: + if extra_blocks is None: + extra_blocks = LastLevelMaxPool() + + if returned_layers is None: + returned_layers = [num_stages - 2, num_stages - 1] + if min(returned_layers) < 0 or max(returned_layers) >= num_stages: + raise ValueError(f"Each returned layer should be in the range [0,{num_stages - 1}], got {returned_layers} ") + return_layers = {f"{stage_indices[k]}": str(v) for v, k in enumerate(returned_layers)} + + in_channels_list = [backbone[stage_indices[i]].out_channels for i in returned_layers] + return BackboneWithFPN( + backbone, return_layers, in_channels_list, out_channels, extra_blocks=extra_blocks, norm_layer=norm_layer + ) + else: + m = nn.Sequential( + backbone, + # depthwise linear combination of channels to reduce their size + nn.Conv2d(backbone[-1].out_channels, out_channels, 1), + ) + m.out_channels = out_channels # type: ignore[assignment] + return m diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/faster_rcnn.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/faster_rcnn.py new file mode 100644 index 0000000000000000000000000000000000000000..52f6c3eea47a5ffee82f1891604f05c9edc29742 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/faster_rcnn.py @@ -0,0 +1,846 @@ +from typing import Any, Callable, Optional, Union + +import torch +import torch.nn.functional as F +from torch import nn +from torchvision.ops import MultiScaleRoIAlign + +from ...ops import misc as misc_nn_ops +from ...transforms._presets import ObjectDetection +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..mobilenetv3 import mobilenet_v3_large, MobileNet_V3_Large_Weights +from ..resnet import resnet50, ResNet50_Weights +from ._utils import overwrite_eps +from .anchor_utils import AnchorGenerator +from .backbone_utils import _mobilenet_extractor, _resnet_fpn_extractor, _validate_trainable_layers +from .generalized_rcnn import GeneralizedRCNN +from .roi_heads import RoIHeads +from .rpn import RegionProposalNetwork, RPNHead +from .transform import GeneralizedRCNNTransform + + +__all__ = [ + "FasterRCNN", + "FasterRCNN_ResNet50_FPN_Weights", + "FasterRCNN_ResNet50_FPN_V2_Weights", + "FasterRCNN_MobileNet_V3_Large_FPN_Weights", + "FasterRCNN_MobileNet_V3_Large_320_FPN_Weights", + "fasterrcnn_resnet50_fpn", + "fasterrcnn_resnet50_fpn_v2", + "fasterrcnn_mobilenet_v3_large_fpn", + "fasterrcnn_mobilenet_v3_large_320_fpn", +] + + +def _default_anchorgen(): + anchor_sizes = ((32,), (64,), (128,), (256,), (512,)) + aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes) + return AnchorGenerator(anchor_sizes, aspect_ratios) + + +class FasterRCNN(GeneralizedRCNN): + """ + Implements Faster R-CNN. + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + + The model returns a Dict[Tensor] during training, containing the classification and regression + losses for both the RPN and the R-CNN. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows: + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each image + - scores (Tensor[N]): the scores or each prediction + + Args: + backbone (nn.Module): the network used to compute the features for the model. + It should contain an out_channels attribute, which indicates the number of output + channels that each feature map has (and it should be the same for all feature maps). + The backbone should return a single Tensor or and OrderedDict[Tensor]. + num_classes (int): number of output classes of the model (including the background). + If box_predictor is specified, num_classes should be None. + min_size (int): Images are rescaled before feeding them to the backbone: + we attempt to preserve the aspect ratio and scale the shorter edge + to ``min_size``. If the resulting longer edge exceeds ``max_size``, + then downscale so that the longer edge does not exceed ``max_size``. + This may result in the shorter edge being lower than ``min_size``. + max_size (int): See ``min_size``. + image_mean (Tuple[float, float, float]): mean values used for input normalization. + They are generally the mean values of the dataset on which the backbone has been trained + on + image_std (Tuple[float, float, float]): std values used for input normalization. + They are generally the std values of the dataset on which the backbone has been trained on + rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature + maps. + rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN + rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training + rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing + rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training + rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing + rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals + rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be + considered as positive during training of the RPN. + rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be + considered as negative during training of the RPN. + rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN + for computing the loss + rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training + of the RPN + rpn_score_thresh (float): only return proposals with an objectness score greater than rpn_score_thresh + box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in + the locations indicated by the bounding boxes + box_head (nn.Module): module that takes the cropped feature maps as input + box_predictor (nn.Module): module that takes the output of box_head and returns the + classification logits and box regression deltas. + box_score_thresh (float): during inference, only return proposals with a classification score + greater than box_score_thresh + box_nms_thresh (float): NMS threshold for the prediction head. Used during inference + box_detections_per_img (int): maximum number of detections per image, for all classes. + box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be + considered as positive during training of the classification head + box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be + considered as negative during training of the classification head + box_batch_size_per_image (int): number of proposals that are sampled during training of the + classification head + box_positive_fraction (float): proportion of positive proposals in a mini-batch during training + of the classification head + bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the + bounding boxes + + Example:: + + >>> import torch + >>> import torchvision + >>> from torchvision.models.detection import FasterRCNN + >>> from torchvision.models.detection.rpn import AnchorGenerator + >>> # load a pre-trained model for classification and return + >>> # only the features + >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features + >>> # FasterRCNN needs to know the number of + >>> # output channels in a backbone. For mobilenet_v2, it's 1280, + >>> # so we need to add it here + >>> backbone.out_channels = 1280 + >>> + >>> # let's make the RPN generate 5 x 3 anchors per spatial + >>> # location, with 5 different sizes and 3 different aspect + >>> # ratios. We have a Tuple[Tuple[int]] because each feature + >>> # map could potentially have different sizes and + >>> # aspect ratios + >>> anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),), + >>> aspect_ratios=((0.5, 1.0, 2.0),)) + >>> + >>> # let's define what are the feature maps that we will + >>> # use to perform the region of interest cropping, as well as + >>> # the size of the crop after rescaling. + >>> # if your backbone returns a Tensor, featmap_names is expected to + >>> # be ['0']. More generally, the backbone should return an + >>> # OrderedDict[Tensor], and in featmap_names you can choose which + >>> # feature maps to use. + >>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'], + >>> output_size=7, + >>> sampling_ratio=2) + >>> + >>> # put the pieces together inside a FasterRCNN model + >>> model = FasterRCNN(backbone, + >>> num_classes=2, + >>> rpn_anchor_generator=anchor_generator, + >>> box_roi_pool=roi_pooler) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + """ + + def __init__( + self, + backbone, + num_classes=None, + # transform parameters + min_size=800, + max_size=1333, + image_mean=None, + image_std=None, + # RPN parameters + rpn_anchor_generator=None, + rpn_head=None, + rpn_pre_nms_top_n_train=2000, + rpn_pre_nms_top_n_test=1000, + rpn_post_nms_top_n_train=2000, + rpn_post_nms_top_n_test=1000, + rpn_nms_thresh=0.7, + rpn_fg_iou_thresh=0.7, + rpn_bg_iou_thresh=0.3, + rpn_batch_size_per_image=256, + rpn_positive_fraction=0.5, + rpn_score_thresh=0.0, + # Box parameters + box_roi_pool=None, + box_head=None, + box_predictor=None, + box_score_thresh=0.05, + box_nms_thresh=0.5, + box_detections_per_img=100, + box_fg_iou_thresh=0.5, + box_bg_iou_thresh=0.5, + box_batch_size_per_image=512, + box_positive_fraction=0.25, + bbox_reg_weights=None, + **kwargs, + ): + + if not hasattr(backbone, "out_channels"): + raise ValueError( + "backbone should contain an attribute out_channels " + "specifying the number of output channels (assumed to be the " + "same for all the levels)" + ) + + if not isinstance(rpn_anchor_generator, (AnchorGenerator, type(None))): + raise TypeError( + f"rpn_anchor_generator should be of type AnchorGenerator or None instead of {type(rpn_anchor_generator)}" + ) + if not isinstance(box_roi_pool, (MultiScaleRoIAlign, type(None))): + raise TypeError( + f"box_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(box_roi_pool)}" + ) + + if num_classes is not None: + if box_predictor is not None: + raise ValueError("num_classes should be None when box_predictor is specified") + else: + if box_predictor is None: + raise ValueError("num_classes should not be None when box_predictor is not specified") + + out_channels = backbone.out_channels + + if rpn_anchor_generator is None: + rpn_anchor_generator = _default_anchorgen() + if rpn_head is None: + rpn_head = RPNHead(out_channels, rpn_anchor_generator.num_anchors_per_location()[0]) + + rpn_pre_nms_top_n = dict(training=rpn_pre_nms_top_n_train, testing=rpn_pre_nms_top_n_test) + rpn_post_nms_top_n = dict(training=rpn_post_nms_top_n_train, testing=rpn_post_nms_top_n_test) + + rpn = RegionProposalNetwork( + rpn_anchor_generator, + rpn_head, + rpn_fg_iou_thresh, + rpn_bg_iou_thresh, + rpn_batch_size_per_image, + rpn_positive_fraction, + rpn_pre_nms_top_n, + rpn_post_nms_top_n, + rpn_nms_thresh, + score_thresh=rpn_score_thresh, + ) + + if box_roi_pool is None: + box_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=7, sampling_ratio=2) + + if box_head is None: + resolution = box_roi_pool.output_size[0] + representation_size = 1024 + box_head = TwoMLPHead(out_channels * resolution**2, representation_size) + + if box_predictor is None: + representation_size = 1024 + box_predictor = FastRCNNPredictor(representation_size, num_classes) + + roi_heads = RoIHeads( + # Box + box_roi_pool, + box_head, + box_predictor, + box_fg_iou_thresh, + box_bg_iou_thresh, + box_batch_size_per_image, + box_positive_fraction, + bbox_reg_weights, + box_score_thresh, + box_nms_thresh, + box_detections_per_img, + ) + + if image_mean is None: + image_mean = [0.485, 0.456, 0.406] + if image_std is None: + image_std = [0.229, 0.224, 0.225] + transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std, **kwargs) + + super().__init__(backbone, rpn, roi_heads, transform) + + +class TwoMLPHead(nn.Module): + """ + Standard heads for FPN-based models + + Args: + in_channels (int): number of input channels + representation_size (int): size of the intermediate representation + """ + + def __init__(self, in_channels, representation_size): + super().__init__() + + self.fc6 = nn.Linear(in_channels, representation_size) + self.fc7 = nn.Linear(representation_size, representation_size) + + def forward(self, x): + x = x.flatten(start_dim=1) + + x = F.relu(self.fc6(x)) + x = F.relu(self.fc7(x)) + + return x + + +class FastRCNNConvFCHead(nn.Sequential): + def __init__( + self, + input_size: tuple[int, int, int], + conv_layers: list[int], + fc_layers: list[int], + norm_layer: Optional[Callable[..., nn.Module]] = None, + ): + """ + Args: + input_size (Tuple[int, int, int]): the input size in CHW format. + conv_layers (list): feature dimensions of each Convolution layer + fc_layers (list): feature dimensions of each FCN layer + norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None + """ + in_channels, in_height, in_width = input_size + + blocks = [] + previous_channels = in_channels + for current_channels in conv_layers: + blocks.append(misc_nn_ops.Conv2dNormActivation(previous_channels, current_channels, norm_layer=norm_layer)) + previous_channels = current_channels + blocks.append(nn.Flatten()) + previous_channels = previous_channels * in_height * in_width + for current_channels in fc_layers: + blocks.append(nn.Linear(previous_channels, current_channels)) + blocks.append(nn.ReLU(inplace=True)) + previous_channels = current_channels + + super().__init__(*blocks) + for layer in self.modules(): + if isinstance(layer, nn.Conv2d): + nn.init.kaiming_normal_(layer.weight, mode="fan_out", nonlinearity="relu") + if layer.bias is not None: + nn.init.zeros_(layer.bias) + + +class FastRCNNPredictor(nn.Module): + """ + Standard classification + bounding box regression layers + for Fast R-CNN. + + Args: + in_channels (int): number of input channels + num_classes (int): number of output classes (including background) + """ + + def __init__(self, in_channels, num_classes): + super().__init__() + self.cls_score = nn.Linear(in_channels, num_classes) + self.bbox_pred = nn.Linear(in_channels, num_classes * 4) + + def forward(self, x): + if x.dim() == 4: + torch._assert( + list(x.shape[2:]) == [1, 1], + f"x has the wrong shape, expecting the last two dimensions to be [1,1] instead of {list(x.shape[2:])}", + ) + x = x.flatten(start_dim=1) + scores = self.cls_score(x) + bbox_deltas = self.bbox_pred(x) + + return scores, bbox_deltas + + +_COMMON_META = { + "categories": _COCO_CATEGORIES, + "min_size": (1, 1), +} + + +class FasterRCNN_ResNet50_FPN_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/fasterrcnn_resnet50_fpn_coco-258fb6c6.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 41755286, + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-resnet-50-fpn", + "_metrics": { + "COCO-val2017": { + "box_map": 37.0, + } + }, + "_ops": 134.38, + "_file_size": 159.743, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +class FasterRCNN_ResNet50_FPN_V2_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/fasterrcnn_resnet50_fpn_v2_coco-dd69338a.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 43712278, + "recipe": "https://github.com/pytorch/vision/pull/5763", + "_metrics": { + "COCO-val2017": { + "box_map": 46.7, + } + }, + "_ops": 280.371, + "_file_size": 167.104, + "_docs": """These weights were produced using an enhanced training recipe to boost the model accuracy.""", + }, + ) + DEFAULT = COCO_V1 + + +class FasterRCNN_MobileNet_V3_Large_FPN_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/fasterrcnn_mobilenet_v3_large_fpn-fb6a3cc7.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 19386354, + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-mobilenetv3-large-fpn", + "_metrics": { + "COCO-val2017": { + "box_map": 32.8, + } + }, + "_ops": 4.494, + "_file_size": 74.239, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +class FasterRCNN_MobileNet_V3_Large_320_FPN_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/fasterrcnn_mobilenet_v3_large_320_fpn-907ea3f9.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 19386354, + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#faster-r-cnn-mobilenetv3-large-320-fpn", + "_metrics": { + "COCO-val2017": { + "box_map": 22.8, + } + }, + "_ops": 0.719, + "_file_size": 74.239, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", FasterRCNN_ResNet50_FPN_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def fasterrcnn_resnet50_fpn( + *, + weights: Optional[FasterRCNN_ResNet50_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> FasterRCNN: + """ + Faster R-CNN model with a ResNet-50-FPN backbone from the `Faster R-CNN: Towards Real-Time Object + Detection with Region Proposal Networks `__ + paper. + + .. betastatus:: detection module + + The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each + image, and should be in ``0-1`` range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and a targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the class label for each ground-truth box + + The model returns a ``Dict[Tensor]`` during training, containing the classification and regression + losses for both the RPN and the R-CNN. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as + follows, where ``N`` is the number of detections: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the predicted labels for each detection + - scores (``Tensor[N]``): the scores of each detection + + For more details on the output, you may refer to :ref:`instance_seg_output`. + + Faster R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size. + + Example:: + + >>> model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=FasterRCNN_ResNet50_FPN_Weights.DEFAULT) + >>> # For training + >>> images, boxes = torch.rand(4, 3, 600, 1200), torch.rand(4, 11, 4) + >>> boxes[:, :, 2:4] = boxes[:, :, 0:2] + boxes[:, :, 2:4] + >>> labels = torch.randint(1, 91, (4, 11)) + >>> images = list(image for image in images) + >>> targets = [] + >>> for i in range(len(images)): + >>> d = {} + >>> d['boxes'] = boxes[i] + >>> d['labels'] = labels[i] + >>> targets.append(d) + >>> output = model(images, targets) + >>> # For inference + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + >>> + >>> # optionally, if you want to export the model to ONNX: + >>> torch.onnx.export(model, x, "faster_rcnn.onnx", opset_version = 11) + + Args: + weights (:class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from + final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are + trainable. If ``None`` is passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.FasterRCNN_ResNet50_FPN_Weights + :members: + """ + weights = FasterRCNN_ResNet50_FPN_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d + + backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer) + backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers) + model = FasterRCNN(backbone, num_classes=num_classes, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if weights == FasterRCNN_ResNet50_FPN_Weights.COCO_V1: + overwrite_eps(model, 0.0) + + return model + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", FasterRCNN_ResNet50_FPN_V2_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def fasterrcnn_resnet50_fpn_v2( + *, + weights: Optional[FasterRCNN_ResNet50_FPN_V2_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = None, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> FasterRCNN: + """ + Constructs an improved Faster R-CNN model with a ResNet-50-FPN backbone from `Benchmarking Detection + Transfer Learning with Vision Transformers `__ paper. + + .. betastatus:: detection module + + It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See + :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more + details. + + Args: + weights (:class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from + final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are + trainable. If ``None`` is passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.FasterRCNN_ResNet50_FPN_V2_Weights + :members: + """ + weights = FasterRCNN_ResNet50_FPN_V2_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + + backbone = resnet50(weights=weights_backbone, progress=progress) + backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers, norm_layer=nn.BatchNorm2d) + rpn_anchor_generator = _default_anchorgen() + rpn_head = RPNHead(backbone.out_channels, rpn_anchor_generator.num_anchors_per_location()[0], conv_depth=2) + box_head = FastRCNNConvFCHead( + (backbone.out_channels, 7, 7), [256, 256, 256, 256], [1024], norm_layer=nn.BatchNorm2d + ) + model = FasterRCNN( + backbone, + num_classes=num_classes, + rpn_anchor_generator=rpn_anchor_generator, + rpn_head=rpn_head, + box_head=box_head, + **kwargs, + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +def _fasterrcnn_mobilenet_v3_large_fpn( + *, + weights: Optional[Union[FasterRCNN_MobileNet_V3_Large_FPN_Weights, FasterRCNN_MobileNet_V3_Large_320_FPN_Weights]], + progress: bool, + num_classes: Optional[int], + weights_backbone: Optional[MobileNet_V3_Large_Weights], + trainable_backbone_layers: Optional[int], + **kwargs: Any, +) -> FasterRCNN: + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 6, 3) + norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d + + backbone = mobilenet_v3_large(weights=weights_backbone, progress=progress, norm_layer=norm_layer) + backbone = _mobilenet_extractor(backbone, True, trainable_backbone_layers) + anchor_sizes = ( + ( + 32, + 64, + 128, + 256, + 512, + ), + ) * 3 + aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes) + model = FasterRCNN( + backbone, num_classes, rpn_anchor_generator=AnchorGenerator(anchor_sizes, aspect_ratios), **kwargs + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", FasterRCNN_MobileNet_V3_Large_320_FPN_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1), +) +def fasterrcnn_mobilenet_v3_large_320_fpn( + *, + weights: Optional[FasterRCNN_MobileNet_V3_Large_320_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> FasterRCNN: + """ + Low resolution Faster R-CNN model with a MobileNetV3-Large backbone tuned for mobile use cases. + + .. betastatus:: detection module + + It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See + :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more + details. + + Example:: + + >>> model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_320_fpn(weights=FasterRCNN_MobileNet_V3_Large_320_FPN_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + + Args: + weights (:class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from + final block. Valid values are between 0 and 6, with 6 meaning all backbone layers are + trainable. If ``None`` is passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_320_FPN_Weights + :members: + """ + weights = FasterRCNN_MobileNet_V3_Large_320_FPN_Weights.verify(weights) + weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone) + + defaults = { + "min_size": 320, + "max_size": 640, + "rpn_pre_nms_top_n_test": 150, + "rpn_post_nms_top_n_test": 150, + "rpn_score_thresh": 0.05, + } + + kwargs = {**defaults, **kwargs} + return _fasterrcnn_mobilenet_v3_large_fpn( + weights=weights, + progress=progress, + num_classes=num_classes, + weights_backbone=weights_backbone, + trainable_backbone_layers=trainable_backbone_layers, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", FasterRCNN_MobileNet_V3_Large_FPN_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1), +) +def fasterrcnn_mobilenet_v3_large_fpn( + *, + weights: Optional[FasterRCNN_MobileNet_V3_Large_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> FasterRCNN: + """ + Constructs a high resolution Faster R-CNN model with a MobileNetV3-Large FPN backbone. + + .. betastatus:: detection module + + It works similarly to Faster R-CNN with ResNet-50 FPN backbone. See + :func:`~torchvision.models.detection.fasterrcnn_resnet50_fpn` for more + details. + + Example:: + + >>> model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_fpn(weights=FasterRCNN_MobileNet_V3_Large_FPN_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + + Args: + weights (:class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from + final block. Valid values are between 0 and 6, with 6 meaning all backbone layers are + trainable. If ``None`` is passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.faster_rcnn.FasterRCNN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.FasterRCNN_MobileNet_V3_Large_FPN_Weights + :members: + """ + weights = FasterRCNN_MobileNet_V3_Large_FPN_Weights.verify(weights) + weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone) + + defaults = { + "rpn_score_thresh": 0.05, + } + + kwargs = {**defaults, **kwargs} + return _fasterrcnn_mobilenet_v3_large_fpn( + weights=weights, + progress=progress, + num_classes=num_classes, + weights_backbone=weights_backbone, + trainable_backbone_layers=trainable_backbone_layers, + **kwargs, + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/fcos.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/fcos.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbd2496517c33b74a1a1581e0cbf3b3f173bfed --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/fcos.py @@ -0,0 +1,775 @@ +import math +import warnings +from collections import OrderedDict +from functools import partial +from typing import Any, Callable, Optional + +import torch +from torch import nn, Tensor + +from ...ops import boxes as box_ops, generalized_box_iou_loss, misc as misc_nn_ops, sigmoid_focal_loss +from ...ops.feature_pyramid_network import LastLevelP6P7 +from ...transforms._presets import ObjectDetection +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..resnet import resnet50, ResNet50_Weights +from . import _utils as det_utils +from .anchor_utils import AnchorGenerator +from .backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers +from .transform import GeneralizedRCNNTransform + + +__all__ = [ + "FCOS", + "FCOS_ResNet50_FPN_Weights", + "fcos_resnet50_fpn", +] + + +class FCOSHead(nn.Module): + """ + A regression and classification head for use in FCOS. + + Args: + in_channels (int): number of channels of the input feature + num_anchors (int): number of anchors to be predicted + num_classes (int): number of classes to be predicted + num_convs (Optional[int]): number of conv layer of head. Default: 4. + """ + + __annotations__ = { + "box_coder": det_utils.BoxLinearCoder, + } + + def __init__(self, in_channels: int, num_anchors: int, num_classes: int, num_convs: Optional[int] = 4) -> None: + super().__init__() + self.box_coder = det_utils.BoxLinearCoder(normalize_by_size=True) + self.classification_head = FCOSClassificationHead(in_channels, num_anchors, num_classes, num_convs) + self.regression_head = FCOSRegressionHead(in_channels, num_anchors, num_convs) + + def compute_loss( + self, + targets: list[dict[str, Tensor]], + head_outputs: dict[str, Tensor], + anchors: list[Tensor], + matched_idxs: list[Tensor], + ) -> dict[str, Tensor]: + + cls_logits = head_outputs["cls_logits"] # [N, HWA, C] + bbox_regression = head_outputs["bbox_regression"] # [N, HWA, 4] + bbox_ctrness = head_outputs["bbox_ctrness"] # [N, HWA, 1] + + all_gt_classes_targets = [] + all_gt_boxes_targets = [] + for targets_per_image, matched_idxs_per_image in zip(targets, matched_idxs): + if len(targets_per_image["labels"]) == 0: + gt_classes_targets = targets_per_image["labels"].new_zeros((len(matched_idxs_per_image),)) + gt_boxes_targets = targets_per_image["boxes"].new_zeros((len(matched_idxs_per_image), 4)) + else: + gt_classes_targets = targets_per_image["labels"][matched_idxs_per_image.clip(min=0)] + gt_boxes_targets = targets_per_image["boxes"][matched_idxs_per_image.clip(min=0)] + gt_classes_targets[matched_idxs_per_image < 0] = -1 # background + all_gt_classes_targets.append(gt_classes_targets) + all_gt_boxes_targets.append(gt_boxes_targets) + + # List[Tensor] to Tensor conversion of `all_gt_boxes_target`, `all_gt_classes_targets` and `anchors` + all_gt_boxes_targets, all_gt_classes_targets, anchors = ( + torch.stack(all_gt_boxes_targets), + torch.stack(all_gt_classes_targets), + torch.stack(anchors), + ) + + # compute foregroud + foregroud_mask = all_gt_classes_targets >= 0 + num_foreground = foregroud_mask.sum().item() + + # classification loss + gt_classes_targets = torch.zeros_like(cls_logits) + gt_classes_targets[foregroud_mask, all_gt_classes_targets[foregroud_mask]] = 1.0 + loss_cls = sigmoid_focal_loss(cls_logits, gt_classes_targets, reduction="sum") + + # amp issue: pred_boxes need to convert float + pred_boxes = self.box_coder.decode(bbox_regression, anchors) + + # regression loss: GIoU loss + loss_bbox_reg = generalized_box_iou_loss( + pred_boxes[foregroud_mask], + all_gt_boxes_targets[foregroud_mask], + reduction="sum", + ) + + # ctrness loss + + bbox_reg_targets = self.box_coder.encode(anchors, all_gt_boxes_targets) + + if len(bbox_reg_targets) == 0: + gt_ctrness_targets = bbox_reg_targets.new_zeros(bbox_reg_targets.size()[:-1]) + else: + left_right = bbox_reg_targets[:, :, [0, 2]] + top_bottom = bbox_reg_targets[:, :, [1, 3]] + gt_ctrness_targets = torch.sqrt( + (left_right.min(dim=-1)[0] / left_right.max(dim=-1)[0]) + * (top_bottom.min(dim=-1)[0] / top_bottom.max(dim=-1)[0]) + ) + pred_centerness = bbox_ctrness.squeeze(dim=2) + loss_bbox_ctrness = nn.functional.binary_cross_entropy_with_logits( + pred_centerness[foregroud_mask], gt_ctrness_targets[foregroud_mask], reduction="sum" + ) + + return { + "classification": loss_cls / max(1, num_foreground), + "bbox_regression": loss_bbox_reg / max(1, num_foreground), + "bbox_ctrness": loss_bbox_ctrness / max(1, num_foreground), + } + + def forward(self, x: list[Tensor]) -> dict[str, Tensor]: + cls_logits = self.classification_head(x) + bbox_regression, bbox_ctrness = self.regression_head(x) + return { + "cls_logits": cls_logits, + "bbox_regression": bbox_regression, + "bbox_ctrness": bbox_ctrness, + } + + +class FCOSClassificationHead(nn.Module): + """ + A classification head for use in FCOS. + + Args: + in_channels (int): number of channels of the input feature. + num_anchors (int): number of anchors to be predicted. + num_classes (int): number of classes to be predicted. + num_convs (Optional[int]): number of conv layer. Default: 4. + prior_probability (Optional[float]): probability of prior. Default: 0.01. + norm_layer: Module specifying the normalization layer to use. + """ + + def __init__( + self, + in_channels: int, + num_anchors: int, + num_classes: int, + num_convs: int = 4, + prior_probability: float = 0.01, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + + self.num_classes = num_classes + self.num_anchors = num_anchors + + if norm_layer is None: + norm_layer = partial(nn.GroupNorm, 32) + + conv = [] + for _ in range(num_convs): + conv.append(nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)) + conv.append(norm_layer(in_channels)) + conv.append(nn.ReLU()) + self.conv = nn.Sequential(*conv) + + for layer in self.conv.children(): + if isinstance(layer, nn.Conv2d): + torch.nn.init.normal_(layer.weight, std=0.01) + torch.nn.init.constant_(layer.bias, 0) + + self.cls_logits = nn.Conv2d(in_channels, num_anchors * num_classes, kernel_size=3, stride=1, padding=1) + torch.nn.init.normal_(self.cls_logits.weight, std=0.01) + torch.nn.init.constant_(self.cls_logits.bias, -math.log((1 - prior_probability) / prior_probability)) + + def forward(self, x: list[Tensor]) -> Tensor: + all_cls_logits = [] + + for features in x: + cls_logits = self.conv(features) + cls_logits = self.cls_logits(cls_logits) + + # Permute classification output from (N, A * K, H, W) to (N, HWA, K). + N, _, H, W = cls_logits.shape + cls_logits = cls_logits.view(N, -1, self.num_classes, H, W) + cls_logits = cls_logits.permute(0, 3, 4, 1, 2) + cls_logits = cls_logits.reshape(N, -1, self.num_classes) # Size=(N, HWA, 4) + + all_cls_logits.append(cls_logits) + + return torch.cat(all_cls_logits, dim=1) + + +class FCOSRegressionHead(nn.Module): + """ + A regression head for use in FCOS, which combines regression branch and center-ness branch. + This can obtain better performance. + + Reference: `FCOS: A simple and strong anchor-free object detector `_. + + Args: + in_channels (int): number of channels of the input feature + num_anchors (int): number of anchors to be predicted + num_convs (Optional[int]): number of conv layer. Default: 4. + norm_layer: Module specifying the normalization layer to use. + """ + + def __init__( + self, + in_channels: int, + num_anchors: int, + num_convs: int = 4, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ): + super().__init__() + + if norm_layer is None: + norm_layer = partial(nn.GroupNorm, 32) + + conv = [] + for _ in range(num_convs): + conv.append(nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)) + conv.append(norm_layer(in_channels)) + conv.append(nn.ReLU()) + self.conv = nn.Sequential(*conv) + + self.bbox_reg = nn.Conv2d(in_channels, num_anchors * 4, kernel_size=3, stride=1, padding=1) + self.bbox_ctrness = nn.Conv2d(in_channels, num_anchors * 1, kernel_size=3, stride=1, padding=1) + for layer in [self.bbox_reg, self.bbox_ctrness]: + torch.nn.init.normal_(layer.weight, std=0.01) + torch.nn.init.zeros_(layer.bias) + + for layer in self.conv.children(): + if isinstance(layer, nn.Conv2d): + torch.nn.init.normal_(layer.weight, std=0.01) + torch.nn.init.zeros_(layer.bias) + + def forward(self, x: list[Tensor]) -> tuple[Tensor, Tensor]: + all_bbox_regression = [] + all_bbox_ctrness = [] + + for features in x: + bbox_feature = self.conv(features) + bbox_regression = nn.functional.relu(self.bbox_reg(bbox_feature)) + bbox_ctrness = self.bbox_ctrness(bbox_feature) + + # permute bbox regression output from (N, 4 * A, H, W) to (N, HWA, 4). + N, _, H, W = bbox_regression.shape + bbox_regression = bbox_regression.view(N, -1, 4, H, W) + bbox_regression = bbox_regression.permute(0, 3, 4, 1, 2) + bbox_regression = bbox_regression.reshape(N, -1, 4) # Size=(N, HWA, 4) + all_bbox_regression.append(bbox_regression) + + # permute bbox ctrness output from (N, 1 * A, H, W) to (N, HWA, 1). + bbox_ctrness = bbox_ctrness.view(N, -1, 1, H, W) + bbox_ctrness = bbox_ctrness.permute(0, 3, 4, 1, 2) + bbox_ctrness = bbox_ctrness.reshape(N, -1, 1) + all_bbox_ctrness.append(bbox_ctrness) + + return torch.cat(all_bbox_regression, dim=1), torch.cat(all_bbox_ctrness, dim=1) + + +class FCOS(nn.Module): + """ + Implements FCOS. + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + + The model returns a Dict[Tensor] during training, containing the classification, regression + and centerness losses. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows: + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each image + - scores (Tensor[N]): the scores for each prediction + + Args: + backbone (nn.Module): the network used to compute the features for the model. + It should contain an out_channels attribute, which indicates the number of output + channels that each feature map has (and it should be the same for all feature maps). + The backbone should return a single Tensor or an OrderedDict[Tensor]. + num_classes (int): number of output classes of the model (including the background). + min_size (int): Images are rescaled before feeding them to the backbone: + we attempt to preserve the aspect ratio and scale the shorter edge + to ``min_size``. If the resulting longer edge exceeds ``max_size``, + then downscale so that the longer edge does not exceed ``max_size``. + This may result in the shorter edge beeing lower than ``min_size``. + max_size (int): See ``min_size``. + image_mean (Tuple[float, float, float]): mean values used for input normalization. + They are generally the mean values of the dataset on which the backbone has been trained + on + image_std (Tuple[float, float, float]): std values used for input normalization. + They are generally the std values of the dataset on which the backbone has been trained on + anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature + maps. For FCOS, only set one anchor for per position of each level, the width and height equal to + the stride of feature map, and set aspect ratio = 1.0, so the center of anchor is equivalent to the point + in FCOS paper. + head (nn.Module): Module run on top of the feature pyramid. + Defaults to a module containing a classification and regression module. + center_sampling_radius (int): radius of the "center" of a groundtruth box, + within which all anchor points are labeled positive. + score_thresh (float): Score threshold used for postprocessing the detections. + nms_thresh (float): NMS threshold used for postprocessing the detections. + detections_per_img (int): Number of best detections to keep after NMS. + topk_candidates (int): Number of best detections to keep before NMS. + + Example: + + >>> import torch + >>> import torchvision + >>> from torchvision.models.detection import FCOS + >>> from torchvision.models.detection.anchor_utils import AnchorGenerator + >>> # load a pre-trained model for classification and return + >>> # only the features + >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features + >>> # FCOS needs to know the number of + >>> # output channels in a backbone. For mobilenet_v2, it's 1280, + >>> # so we need to add it here + >>> backbone.out_channels = 1280 + >>> + >>> # let's make the network generate 5 x 3 anchors per spatial + >>> # location, with 5 different sizes and 3 different aspect + >>> # ratios. We have a Tuple[Tuple[int]] because each feature + >>> # map could potentially have different sizes and + >>> # aspect ratios + >>> anchor_generator = AnchorGenerator( + >>> sizes=((8,), (16,), (32,), (64,), (128,)), + >>> aspect_ratios=((1.0,),) + >>> ) + >>> + >>> # put the pieces together inside a FCOS model + >>> model = FCOS( + >>> backbone, + >>> num_classes=80, + >>> anchor_generator=anchor_generator, + >>> ) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + """ + + __annotations__ = { + "box_coder": det_utils.BoxLinearCoder, + } + + def __init__( + self, + backbone: nn.Module, + num_classes: int, + # transform parameters + min_size: int = 800, + max_size: int = 1333, + image_mean: Optional[list[float]] = None, + image_std: Optional[list[float]] = None, + # Anchor parameters + anchor_generator: Optional[AnchorGenerator] = None, + head: Optional[nn.Module] = None, + center_sampling_radius: float = 1.5, + score_thresh: float = 0.2, + nms_thresh: float = 0.6, + detections_per_img: int = 100, + topk_candidates: int = 1000, + **kwargs, + ): + super().__init__() + _log_api_usage_once(self) + + if not hasattr(backbone, "out_channels"): + raise ValueError( + "backbone should contain an attribute out_channels " + "specifying the number of output channels (assumed to be the " + "same for all the levels)" + ) + self.backbone = backbone + + if not isinstance(anchor_generator, (AnchorGenerator, type(None))): + raise TypeError( + f"anchor_generator should be of type AnchorGenerator or None, instead got {type(anchor_generator)}" + ) + + if anchor_generator is None: + anchor_sizes = ((8,), (16,), (32,), (64,), (128,)) # equal to strides of multi-level feature map + aspect_ratios = ((1.0,),) * len(anchor_sizes) # set only one anchor + anchor_generator = AnchorGenerator(anchor_sizes, aspect_ratios) + self.anchor_generator = anchor_generator + if self.anchor_generator.num_anchors_per_location()[0] != 1: + raise ValueError( + f"anchor_generator.num_anchors_per_location()[0] should be 1 instead of {anchor_generator.num_anchors_per_location()[0]}" + ) + + if head is None: + head = FCOSHead(backbone.out_channels, anchor_generator.num_anchors_per_location()[0], num_classes) + self.head = head + + self.box_coder = det_utils.BoxLinearCoder(normalize_by_size=True) + + if image_mean is None: + image_mean = [0.485, 0.456, 0.406] + if image_std is None: + image_std = [0.229, 0.224, 0.225] + self.transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std, **kwargs) + + self.center_sampling_radius = center_sampling_radius + self.score_thresh = score_thresh + self.nms_thresh = nms_thresh + self.detections_per_img = detections_per_img + self.topk_candidates = topk_candidates + + # used only on torchscript mode + self._has_warned = False + + @torch.jit.unused + def eager_outputs( + self, losses: dict[str, Tensor], detections: list[dict[str, Tensor]] + ) -> tuple[dict[str, Tensor], list[dict[str, Tensor]]]: + if self.training: + return losses + + return detections + + def compute_loss( + self, + targets: list[dict[str, Tensor]], + head_outputs: dict[str, Tensor], + anchors: list[Tensor], + num_anchors_per_level: list[int], + ) -> dict[str, Tensor]: + matched_idxs = [] + for anchors_per_image, targets_per_image in zip(anchors, targets): + if targets_per_image["boxes"].numel() == 0: + matched_idxs.append( + torch.full((anchors_per_image.size(0),), -1, dtype=torch.int64, device=anchors_per_image.device) + ) + continue + + gt_boxes = targets_per_image["boxes"] + gt_centers = (gt_boxes[:, :2] + gt_boxes[:, 2:]) / 2 # Nx2 + anchor_centers = (anchors_per_image[:, :2] + anchors_per_image[:, 2:]) / 2 # N + anchor_sizes = anchors_per_image[:, 2] - anchors_per_image[:, 0] + # center sampling: anchor point must be close enough to gt center. + pairwise_match = (anchor_centers[:, None, :] - gt_centers[None, :, :]).abs_().max( + dim=2 + ).values < self.center_sampling_radius * anchor_sizes[:, None] + # compute pairwise distance between N points and M boxes + x, y = anchor_centers.unsqueeze(dim=2).unbind(dim=1) # (N, 1) + x0, y0, x1, y1 = gt_boxes.unsqueeze(dim=0).unbind(dim=2) # (1, M) + pairwise_dist = torch.stack([x - x0, y - y0, x1 - x, y1 - y], dim=2) # (N, M) + + # anchor point must be inside gt + pairwise_match &= pairwise_dist.min(dim=2).values > 0 + + # each anchor is only responsible for certain scale range. + lower_bound = anchor_sizes * 4 + lower_bound[: num_anchors_per_level[0]] = 0 + upper_bound = anchor_sizes * 8 + upper_bound[-num_anchors_per_level[-1] :] = float("inf") + pairwise_dist = pairwise_dist.max(dim=2).values + pairwise_match &= (pairwise_dist > lower_bound[:, None]) & (pairwise_dist < upper_bound[:, None]) + + # match the GT box with minimum area, if there are multiple GT matches + gt_areas = (gt_boxes[:, 2] - gt_boxes[:, 0]) * (gt_boxes[:, 3] - gt_boxes[:, 1]) # N + pairwise_match = pairwise_match.to(torch.float32) * (1e8 - gt_areas[None, :]) + min_values, matched_idx = pairwise_match.max(dim=1) # R, per-anchor match + matched_idx[min_values < 1e-5] = -1 # unmatched anchors are assigned -1 + + matched_idxs.append(matched_idx) + + return self.head.compute_loss(targets, head_outputs, anchors, matched_idxs) + + def postprocess_detections( + self, head_outputs: dict[str, list[Tensor]], anchors: list[list[Tensor]], image_shapes: list[tuple[int, int]] + ) -> list[dict[str, Tensor]]: + class_logits = head_outputs["cls_logits"] + box_regression = head_outputs["bbox_regression"] + box_ctrness = head_outputs["bbox_ctrness"] + + num_images = len(image_shapes) + + detections: list[dict[str, Tensor]] = [] + + for index in range(num_images): + box_regression_per_image = [br[index] for br in box_regression] + logits_per_image = [cl[index] for cl in class_logits] + box_ctrness_per_image = [bc[index] for bc in box_ctrness] + anchors_per_image, image_shape = anchors[index], image_shapes[index] + + image_boxes = [] + image_scores = [] + image_labels = [] + + for box_regression_per_level, logits_per_level, box_ctrness_per_level, anchors_per_level in zip( + box_regression_per_image, logits_per_image, box_ctrness_per_image, anchors_per_image + ): + num_classes = logits_per_level.shape[-1] + + # remove low scoring boxes + scores_per_level = torch.sqrt( + torch.sigmoid(logits_per_level) * torch.sigmoid(box_ctrness_per_level) + ).flatten() + keep_idxs = scores_per_level > self.score_thresh + scores_per_level = scores_per_level[keep_idxs] + topk_idxs = torch.where(keep_idxs)[0] + + # keep only topk scoring predictions + num_topk = det_utils._topk_min(topk_idxs, self.topk_candidates, 0) + scores_per_level, idxs = scores_per_level.topk(num_topk) + topk_idxs = topk_idxs[idxs] + + anchor_idxs = torch.div(topk_idxs, num_classes, rounding_mode="floor") + labels_per_level = topk_idxs % num_classes + + boxes_per_level = self.box_coder.decode( + box_regression_per_level[anchor_idxs], anchors_per_level[anchor_idxs] + ) + boxes_per_level = box_ops.clip_boxes_to_image(boxes_per_level, image_shape) + + image_boxes.append(boxes_per_level) + image_scores.append(scores_per_level) + image_labels.append(labels_per_level) + + image_boxes = torch.cat(image_boxes, dim=0) + image_scores = torch.cat(image_scores, dim=0) + image_labels = torch.cat(image_labels, dim=0) + + # non-maximum suppression + keep = box_ops.batched_nms(image_boxes, image_scores, image_labels, self.nms_thresh) + keep = keep[: self.detections_per_img] + + detections.append( + { + "boxes": image_boxes[keep], + "scores": image_scores[keep], + "labels": image_labels[keep], + } + ) + + return detections + + def forward( + self, + images: list[Tensor], + targets: Optional[list[dict[str, Tensor]]] = None, + ) -> tuple[dict[str, Tensor], list[dict[str, Tensor]]]: + """ + Args: + images (list[Tensor]): images to be processed + targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional) + + Returns: + result (list[BoxList] or dict[Tensor]): the output from the model. + During training, it returns a dict[Tensor] which contains the losses. + During testing, it returns list[BoxList] contains additional fields + like `scores`, `labels` and `mask` (for Mask R-CNN models). + """ + if self.training: + + if targets is None: + torch._assert(False, "targets should not be none when in training mode") + else: + for target in targets: + boxes = target["boxes"] + torch._assert(isinstance(boxes, torch.Tensor), "Expected target boxes to be of type Tensor.") + torch._assert( + len(boxes.shape) == 2 and boxes.shape[-1] == 4, + f"Expected target boxes to be a tensor of shape [N, 4], got {boxes.shape}.", + ) + + original_image_sizes: list[tuple[int, int]] = [] + for img in images: + val = img.shape[-2:] + torch._assert( + len(val) == 2, + f"expecting the last two dimensions of the Tensor to be H and W instead got {img.shape[-2:]}", + ) + original_image_sizes.append((val[0], val[1])) + + # transform the input + images, targets = self.transform(images, targets) + + # Check for degenerate boxes + if targets is not None: + for target_idx, target in enumerate(targets): + boxes = target["boxes"] + degenerate_boxes = boxes[:, 2:] <= boxes[:, :2] + if degenerate_boxes.any(): + # print the first degenerate box + bb_idx = torch.where(degenerate_boxes.any(dim=1))[0][0] + degen_bb: list[float] = boxes[bb_idx].tolist() + torch._assert( + False, + f"All bounding boxes should have positive height and width. Found invalid box {degen_bb} for target at index {target_idx}.", + ) + + # get the features from the backbone + features = self.backbone(images.tensors) + if isinstance(features, torch.Tensor): + features = OrderedDict([("0", features)]) + + features = list(features.values()) + + # compute the fcos heads outputs using the features + head_outputs = self.head(features) + + # create the set of anchors + anchors = self.anchor_generator(images, features) + # recover level sizes + num_anchors_per_level = [x.size(2) * x.size(3) for x in features] + + losses = {} + detections: list[dict[str, Tensor]] = [] + if self.training: + if targets is None: + torch._assert(False, "targets should not be none when in training mode") + else: + # compute the losses + losses = self.compute_loss(targets, head_outputs, anchors, num_anchors_per_level) + else: + # split outputs per level + split_head_outputs: dict[str, list[Tensor]] = {} + for k in head_outputs: + split_head_outputs[k] = list(head_outputs[k].split(num_anchors_per_level, dim=1)) + split_anchors = [list(a.split(num_anchors_per_level)) for a in anchors] + + # compute the detections + detections = self.postprocess_detections(split_head_outputs, split_anchors, images.image_sizes) + detections = self.transform.postprocess(detections, images.image_sizes, original_image_sizes) + + if torch.jit.is_scripting(): + if not self._has_warned: + warnings.warn("FCOS always returns a (Losses, Detections) tuple in scripting") + self._has_warned = True + return losses, detections + return self.eager_outputs(losses, detections) + + +class FCOS_ResNet50_FPN_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/fcos_resnet50_fpn_coco-99b0c9b7.pth", + transforms=ObjectDetection, + meta={ + "num_params": 32269600, + "categories": _COCO_CATEGORIES, + "min_size": (1, 1), + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#fcos-resnet-50-fpn", + "_metrics": { + "COCO-val2017": { + "box_map": 39.2, + } + }, + "_ops": 128.207, + "_file_size": 123.608, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", FCOS_ResNet50_FPN_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def fcos_resnet50_fpn( + *, + weights: Optional[FCOS_ResNet50_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> FCOS: + """ + Constructs a FCOS model with a ResNet-50-FPN backbone. + + .. betastatus:: detection module + + Reference: `FCOS: Fully Convolutional One-Stage Object Detection `_. + `FCOS: A simple and strong anchor-free object detector `_. + + The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each + image, and should be in ``0-1`` range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the class label for each ground-truth box + + The model returns a ``Dict[Tensor]`` during training, containing the classification and regression + losses. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as + follows, where ``N`` is the number of detections: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the predicted labels for each detection + - scores (``Tensor[N]``): the scores of each detection + + For more details on the output, you may refer to :ref:`instance_seg_output`. + + Example: + + >>> model = torchvision.models.detection.fcos_resnet50_fpn(weights=FCOS_ResNet50_FPN_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + + Args: + weights (:class:`~torchvision.models.detection.FCOS_ResNet50_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.FCOS_ResNet50_FPN_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained weights for + the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) resnet layers starting + from final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are + trainable. If ``None`` is passed (the default) this value is set to 3. Default: None + **kwargs: parameters passed to the ``torchvision.models.detection.FCOS`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.FCOS_ResNet50_FPN_Weights + :members: + """ + weights = FCOS_ResNet50_FPN_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d + + backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer) + backbone = _resnet_fpn_extractor( + backbone, trainable_backbone_layers, returned_layers=[2, 3, 4], extra_blocks=LastLevelP6P7(256, 256) + ) + model = FCOS(backbone, num_classes, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/generalized_rcnn.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/generalized_rcnn.py new file mode 100644 index 0000000000000000000000000000000000000000..f07fa77aae95042f4997869c9164eb07122dd8de --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/generalized_rcnn.py @@ -0,0 +1,133 @@ +""" +Implements the Generalized R-CNN framework +""" + +import warnings +from collections import OrderedDict +from typing import Optional, Union + +import torch +from torch import nn + +from ...utils import _log_api_usage_once + + +class GeneralizedRCNN(nn.Module): + """ + Main class for Generalized R-CNN. + + Args: + backbone (nn.Module): + rpn (nn.Module): + roi_heads (nn.Module): takes the features + the proposals from the RPN and computes + detections / masks from it. + transform (nn.Module): performs the data transformation from the inputs to feed into + the model + """ + + def __init__( + self, + backbone: nn.Module, + rpn: nn.Module, + roi_heads: nn.Module, + transform: nn.Module, + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.transform = transform + self.backbone = backbone + self.rpn = rpn + self.roi_heads = roi_heads + # used only on torchscript mode + self._has_warned = False + + @torch.jit.unused + def eager_outputs( + self, losses: dict[str, torch.Tensor], detections: list[dict[str, torch.Tensor]] + ) -> Union[dict[str, torch.Tensor], list[dict[str, torch.Tensor]]]: + if self.training: + return losses + + return detections + + def forward( + self, + images: list[torch.Tensor], + targets: Optional[list[dict[str, torch.Tensor]]] = None, + ) -> tuple[dict[str, torch.Tensor], list[dict[str, torch.Tensor]]]: + """ + Args: + images (list[Tensor]): images to be processed + targets (list[dict[str, tensor]]): ground-truth boxes present in the image (optional) + + Returns: + result (list[BoxList] or dict[Tensor]): the output from the model. + During training, it returns a dict[Tensor] which contains the losses. + During testing, it returns list[BoxList] contains additional fields + like `scores`, `labels` and `mask` (for Mask R-CNN models). + + """ + if self.training: + if targets is None: + torch._assert(False, "targets should not be none when in training mode") + else: + for target in targets: + boxes = target["boxes"] + if isinstance(boxes, torch.Tensor): + torch._assert( + len(boxes.shape) == 2 and boxes.shape[-1] == 4, + f"Expected target boxes to be a tensor of shape [N, 4], got {boxes.shape}.", + ) + else: + torch._assert( + False, + f"Expected target boxes to be of type Tensor, got {type(boxes)}.", + ) + + original_image_sizes: list[tuple[int, int]] = [] + for img in images: + val = img.shape[-2:] + torch._assert( + len(val) == 2, + f"expecting the last two dimensions of the Tensor to be H and W instead got {img.shape[-2:]}", + ) + original_image_sizes.append((val[0], val[1])) + + images, targets = self.transform(images, targets) + + # Check for degenerate boxes + # TODO: Move this to a function + if targets is not None: + for target_idx, target in enumerate(targets): + boxes = target["boxes"] + degenerate_boxes = boxes[:, 2:] <= boxes[:, :2] + if degenerate_boxes.any(): + # print the first degenerate box + bb_idx = torch.where(degenerate_boxes.any(dim=1))[0][0] + degen_bb: list[float] = boxes[bb_idx].tolist() + torch._assert( + False, + "All bounding boxes should have positive height and width." + f" Found invalid box {degen_bb} for target at index {target_idx}.", + ) + + features = self.backbone(images.tensors) + if isinstance(features, torch.Tensor): + features = OrderedDict([("0", features)]) + proposals, proposal_losses = self.rpn(images, features, targets) + detections, detector_losses = self.roi_heads(features, proposals, images.image_sizes, targets) + detections = self.transform.postprocess( + detections, images.image_sizes, original_image_sizes + ) # type: ignore[operator] + + losses = {} + losses.update(detector_losses) + losses.update(proposal_losses) + + if torch.jit.is_scripting(): + if not self._has_warned: + warnings.warn("RCNN always returns a (Losses, Detections) tuple in scripting") + self._has_warned = True + return losses, detections + else: + return self.eager_outputs(losses, detections) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/image_list.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/image_list.py new file mode 100644 index 0000000000000000000000000000000000000000..08aabe3a486e2609b53352f2d50a3148c4428066 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/image_list.py @@ -0,0 +1,23 @@ +import torch +from torch import Tensor + + +class ImageList: + """ + Structure that holds a list of images (of possibly + varying sizes) as a single tensor. + This works by padding the images to the same size, + and storing in a field the original sizes of each image + + Args: + tensors (tensor): Tensor containing images. + image_sizes (list[tuple[int, int]]): List of Tuples each containing size of images. + """ + + def __init__(self, tensors: Tensor, image_sizes: list[tuple[int, int]]) -> None: + self.tensors = tensors + self.image_sizes = image_sizes + + def to(self, device: torch.device) -> "ImageList": + cast_tensor = self.tensors.to(device) + return ImageList(cast_tensor, self.image_sizes) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/keypoint_rcnn.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/keypoint_rcnn.py new file mode 100644 index 0000000000000000000000000000000000000000..42b9d65562d81f9ce1be56180c433de44d5e9b4f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/keypoint_rcnn.py @@ -0,0 +1,476 @@ +from typing import Any, Optional + +import torch +from torch import nn +from torchvision.ops import MultiScaleRoIAlign + +from ...ops import misc as misc_nn_ops +from ...transforms._presets import ObjectDetection +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_PERSON_CATEGORIES, _COCO_PERSON_KEYPOINT_NAMES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..resnet import resnet50, ResNet50_Weights +from ._utils import overwrite_eps +from .backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers +from .faster_rcnn import FasterRCNN + + +__all__ = [ + "KeypointRCNN", + "KeypointRCNN_ResNet50_FPN_Weights", + "keypointrcnn_resnet50_fpn", +] + + +class KeypointRCNN(FasterRCNN): + """ + Implements Keypoint R-CNN. + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + - keypoints (FloatTensor[N, K, 3]): the K keypoints location for each of the N instances, in the + format [x, y, visibility], where visibility=0 means that the keypoint is not visible. + + The model returns a Dict[Tensor] during training, containing the classification and regression + losses for both the RPN and the R-CNN, and the keypoint loss. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each image + - scores (Tensor[N]): the scores or each prediction + - keypoints (FloatTensor[N, K, 3]): the locations of the predicted keypoints, in [x, y, v] format. + + Args: + backbone (nn.Module): the network used to compute the features for the model. + It should contain an out_channels attribute, which indicates the number of output + channels that each feature map has (and it should be the same for all feature maps). + The backbone should return a single Tensor or and OrderedDict[Tensor]. + num_classes (int): number of output classes of the model (including the background). + If box_predictor is specified, num_classes should be None. + min_size (int): Images are rescaled before feeding them to the backbone: + we attempt to preserve the aspect ratio and scale the shorter edge + to ``min_size``. If the resulting longer edge exceeds ``max_size``, + then downscale so that the longer edge does not exceed ``max_size``. + This may result in the shorter edge beeing lower than ``min_size``. + max_size (int): See ``min_size``. + image_mean (Tuple[float, float, float]): mean values used for input normalization. + They are generally the mean values of the dataset on which the backbone has been trained + on + image_std (Tuple[float, float, float]): std values used for input normalization. + They are generally the std values of the dataset on which the backbone has been trained on + rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature + maps. + rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN + rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training + rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing + rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training + rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing + rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals + rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be + considered as positive during training of the RPN. + rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be + considered as negative during training of the RPN. + rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN + for computing the loss + rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training + of the RPN + rpn_score_thresh (float): only return proposals with an objectness score greater than rpn_score_thresh + box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in + the locations indicated by the bounding boxes + box_head (nn.Module): module that takes the cropped feature maps as input + box_predictor (nn.Module): module that takes the output of box_head and returns the + classification logits and box regression deltas. + box_score_thresh (float): during inference, only return proposals with a classification score + greater than box_score_thresh + box_nms_thresh (float): NMS threshold for the prediction head. Used during inference + box_detections_per_img (int): maximum number of detections per image, for all classes. + box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be + considered as positive during training of the classification head + box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be + considered as negative during training of the classification head + box_batch_size_per_image (int): number of proposals that are sampled during training of the + classification head + box_positive_fraction (float): proportion of positive proposals in a mini-batch during training + of the classification head + bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the + bounding boxes + keypoint_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in + the locations indicated by the bounding boxes, which will be used for the keypoint head. + keypoint_head (nn.Module): module that takes the cropped feature maps as input + keypoint_predictor (nn.Module): module that takes the output of the keypoint_head and returns the + heatmap logits + + Example:: + + >>> import torch + >>> import torchvision + >>> from torchvision.models.detection import KeypointRCNN + >>> from torchvision.models.detection.anchor_utils import AnchorGenerator + >>> + >>> # load a pre-trained model for classification and return + >>> # only the features + >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features + >>> # KeypointRCNN needs to know the number of + >>> # output channels in a backbone. For mobilenet_v2, it's 1280, + >>> # so we need to add it here + >>> backbone.out_channels = 1280 + >>> + >>> # let's make the RPN generate 5 x 3 anchors per spatial + >>> # location, with 5 different sizes and 3 different aspect + >>> # ratios. We have a Tuple[Tuple[int]] because each feature + >>> # map could potentially have different sizes and + >>> # aspect ratios + >>> anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),), + >>> aspect_ratios=((0.5, 1.0, 2.0),)) + >>> + >>> # let's define what are the feature maps that we will + >>> # use to perform the region of interest cropping, as well as + >>> # the size of the crop after rescaling. + >>> # if your backbone returns a Tensor, featmap_names is expected to + >>> # be ['0']. More generally, the backbone should return an + >>> # OrderedDict[Tensor], and in featmap_names you can choose which + >>> # feature maps to use. + >>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'], + >>> output_size=7, + >>> sampling_ratio=2) + >>> + >>> keypoint_roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'], + >>> output_size=14, + >>> sampling_ratio=2) + >>> # put the pieces together inside a KeypointRCNN model + >>> model = KeypointRCNN(backbone, + >>> num_classes=2, + >>> rpn_anchor_generator=anchor_generator, + >>> box_roi_pool=roi_pooler, + >>> keypoint_roi_pool=keypoint_roi_pooler) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + """ + + def __init__( + self, + backbone, + num_classes=None, + # transform parameters + min_size=None, + max_size=1333, + image_mean=None, + image_std=None, + # RPN parameters + rpn_anchor_generator=None, + rpn_head=None, + rpn_pre_nms_top_n_train=2000, + rpn_pre_nms_top_n_test=1000, + rpn_post_nms_top_n_train=2000, + rpn_post_nms_top_n_test=1000, + rpn_nms_thresh=0.7, + rpn_fg_iou_thresh=0.7, + rpn_bg_iou_thresh=0.3, + rpn_batch_size_per_image=256, + rpn_positive_fraction=0.5, + rpn_score_thresh=0.0, + # Box parameters + box_roi_pool=None, + box_head=None, + box_predictor=None, + box_score_thresh=0.05, + box_nms_thresh=0.5, + box_detections_per_img=100, + box_fg_iou_thresh=0.5, + box_bg_iou_thresh=0.5, + box_batch_size_per_image=512, + box_positive_fraction=0.25, + bbox_reg_weights=None, + # keypoint parameters + keypoint_roi_pool=None, + keypoint_head=None, + keypoint_predictor=None, + num_keypoints=None, + **kwargs, + ): + + if not isinstance(keypoint_roi_pool, (MultiScaleRoIAlign, type(None))): + raise TypeError( + "keypoint_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(keypoint_roi_pool)}" + ) + if min_size is None: + min_size = (640, 672, 704, 736, 768, 800) + + if num_keypoints is not None: + if keypoint_predictor is not None: + raise ValueError("num_keypoints should be None when keypoint_predictor is specified") + else: + num_keypoints = 17 + + out_channels = backbone.out_channels + + if keypoint_roi_pool is None: + keypoint_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=14, sampling_ratio=2) + + if keypoint_head is None: + keypoint_layers = tuple(512 for _ in range(8)) + keypoint_head = KeypointRCNNHeads(out_channels, keypoint_layers) + + if keypoint_predictor is None: + keypoint_dim_reduced = 512 # == keypoint_layers[-1] + keypoint_predictor = KeypointRCNNPredictor(keypoint_dim_reduced, num_keypoints) + + super().__init__( + backbone, + num_classes, + # transform parameters + min_size, + max_size, + image_mean, + image_std, + # RPN-specific parameters + rpn_anchor_generator, + rpn_head, + rpn_pre_nms_top_n_train, + rpn_pre_nms_top_n_test, + rpn_post_nms_top_n_train, + rpn_post_nms_top_n_test, + rpn_nms_thresh, + rpn_fg_iou_thresh, + rpn_bg_iou_thresh, + rpn_batch_size_per_image, + rpn_positive_fraction, + rpn_score_thresh, + # Box parameters + box_roi_pool, + box_head, + box_predictor, + box_score_thresh, + box_nms_thresh, + box_detections_per_img, + box_fg_iou_thresh, + box_bg_iou_thresh, + box_batch_size_per_image, + box_positive_fraction, + bbox_reg_weights, + **kwargs, + ) + + self.roi_heads.keypoint_roi_pool = keypoint_roi_pool + self.roi_heads.keypoint_head = keypoint_head + self.roi_heads.keypoint_predictor = keypoint_predictor + + +class KeypointRCNNHeads(nn.Sequential): + def __init__(self, in_channels, layers): + d = [] + next_feature = in_channels + for out_channels in layers: + d.append(nn.Conv2d(next_feature, out_channels, 3, stride=1, padding=1)) + d.append(nn.ReLU(inplace=True)) + next_feature = out_channels + super().__init__(*d) + for m in self.children(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + nn.init.constant_(m.bias, 0) + + +class KeypointRCNNPredictor(nn.Module): + def __init__(self, in_channels, num_keypoints): + super().__init__() + input_features = in_channels + deconv_kernel = 4 + self.kps_score_lowres = nn.ConvTranspose2d( + input_features, + num_keypoints, + deconv_kernel, + stride=2, + padding=deconv_kernel // 2 - 1, + ) + nn.init.kaiming_normal_(self.kps_score_lowres.weight, mode="fan_out", nonlinearity="relu") + nn.init.constant_(self.kps_score_lowres.bias, 0) + self.up_scale = 2 + self.out_channels = num_keypoints + + def forward(self, x): + x = self.kps_score_lowres(x) + return torch.nn.functional.interpolate( + x, scale_factor=float(self.up_scale), mode="bilinear", align_corners=False, recompute_scale_factor=False + ) + + +_COMMON_META = { + "categories": _COCO_PERSON_CATEGORIES, + "keypoint_names": _COCO_PERSON_KEYPOINT_NAMES, + "min_size": (1, 1), +} + + +class KeypointRCNN_ResNet50_FPN_Weights(WeightsEnum): + COCO_LEGACY = Weights( + url="https://download.pytorch.org/models/keypointrcnn_resnet50_fpn_coco-9f466800.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 59137258, + "recipe": "https://github.com/pytorch/vision/issues/1606", + "_metrics": { + "COCO-val2017": { + "box_map": 50.6, + "kp_map": 61.1, + } + }, + "_ops": 133.924, + "_file_size": 226.054, + "_docs": """ + These weights were produced by following a similar training recipe as on the paper but use a checkpoint + from an early epoch. + """, + }, + ) + COCO_V1 = Weights( + url="https://download.pytorch.org/models/keypointrcnn_resnet50_fpn_coco-fc266e95.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 59137258, + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#keypoint-r-cnn", + "_metrics": { + "COCO-val2017": { + "box_map": 54.6, + "kp_map": 65.0, + } + }, + "_ops": 137.42, + "_file_size": 226.054, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +@register_model() +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + KeypointRCNN_ResNet50_FPN_Weights.COCO_LEGACY + if kwargs["pretrained"] == "legacy" + else KeypointRCNN_ResNet50_FPN_Weights.COCO_V1 + ), + ), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def keypointrcnn_resnet50_fpn( + *, + weights: Optional[KeypointRCNN_ResNet50_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + num_keypoints: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> KeypointRCNN: + """ + Constructs a Keypoint R-CNN model with a ResNet-50-FPN backbone. + + .. betastatus:: detection module + + Reference: `Mask R-CNN `__. + + The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each + image, and should be in ``0-1`` range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the class label for each ground-truth box + - keypoints (``FloatTensor[N, K, 3]``): the ``K`` keypoints location for each of the ``N`` instances, in the + format ``[x, y, visibility]``, where ``visibility=0`` means that the keypoint is not visible. + + The model returns a ``Dict[Tensor]`` during training, containing the classification and regression + losses for both the RPN and the R-CNN, and the keypoint loss. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as + follows, where ``N`` is the number of detected instances: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the predicted labels for each instance + - scores (``Tensor[N]``): the scores or each instance + - keypoints (``FloatTensor[N, K, 3]``): the locations of the predicted keypoints, in ``[x, y, v]`` format. + + For more details on the output, you may refer to :ref:`instance_seg_output`. + + Keypoint R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size. + + Example:: + + >>> model = torchvision.models.detection.keypointrcnn_resnet50_fpn(weights=KeypointRCNN_ResNet50_FPN_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + >>> + >>> # optionally, if you want to export the model to ONNX: + >>> torch.onnx.export(model, x, "keypoint_rcnn.onnx", opset_version = 11) + + Args: + weights (:class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr + num_classes (int, optional): number of output classes of the model (including the background) + num_keypoints (int, optional): number of keypoints + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block. + Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is + passed (the default) this value is set to 3. + + .. autoclass:: torchvision.models.detection.KeypointRCNN_ResNet50_FPN_Weights + :members: + """ + weights = KeypointRCNN_ResNet50_FPN_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + num_keypoints = _ovewrite_value_param("num_keypoints", num_keypoints, len(weights.meta["keypoint_names"])) + else: + if num_classes is None: + num_classes = 2 + if num_keypoints is None: + num_keypoints = 17 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d + + backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer) + backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers) + model = KeypointRCNN(backbone, num_classes, num_keypoints=num_keypoints, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if weights == KeypointRCNN_ResNet50_FPN_Weights.COCO_V1: + overwrite_eps(model, 0.0) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/mask_rcnn.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/mask_rcnn.py new file mode 100644 index 0000000000000000000000000000000000000000..d1668ab423e52fee248d696d9d2f3ad1fcac90b5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/mask_rcnn.py @@ -0,0 +1,590 @@ +from collections import OrderedDict +from typing import Any, Callable, Optional + +from torch import nn +from torchvision.ops import MultiScaleRoIAlign + +from ...ops import misc as misc_nn_ops +from ...transforms._presets import ObjectDetection +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..resnet import resnet50, ResNet50_Weights +from ._utils import overwrite_eps +from .backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers +from .faster_rcnn import _default_anchorgen, FasterRCNN, FastRCNNConvFCHead, RPNHead + + +__all__ = [ + "MaskRCNN", + "MaskRCNN_ResNet50_FPN_Weights", + "MaskRCNN_ResNet50_FPN_V2_Weights", + "maskrcnn_resnet50_fpn", + "maskrcnn_resnet50_fpn_v2", +] + + +class MaskRCNN(FasterRCNN): + """ + Implements Mask R-CNN. + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + - masks (UInt8Tensor[N, H, W]): the segmentation binary masks for each instance + + The model returns a Dict[Tensor] during training, containing the classification and regression + losses for both the RPN and the R-CNN, and the mask loss. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows: + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each image + - scores (Tensor[N]): the scores or each prediction + - masks (FloatTensor[N, 1, H, W]): the predicted masks for each instance, in 0-1 range. In order to + obtain the final segmentation masks, the soft masks can be thresholded, generally + with a value of 0.5 (mask >= 0.5) + + Args: + backbone (nn.Module): the network used to compute the features for the model. + It should contain an out_channels attribute, which indicates the number of output + channels that each feature map has (and it should be the same for all feature maps). + The backbone should return a single Tensor or and OrderedDict[Tensor]. + num_classes (int): number of output classes of the model (including the background). + If box_predictor is specified, num_classes should be None. + min_size (int): Images are rescaled before feeding them to the backbone: + we attempt to preserve the aspect ratio and scale the shorter edge + to ``min_size``. If the resulting longer edge exceeds ``max_size``, + then downscale so that the longer edge does not exceed ``max_size``. + This may result in the shorter edge beeing lower than ``min_size``. + max_size (int): See ``min_size``. + image_mean (Tuple[float, float, float]): mean values used for input normalization. + They are generally the mean values of the dataset on which the backbone has been trained + on + image_std (Tuple[float, float, float]): std values used for input normalization. + They are generally the std values of the dataset on which the backbone has been trained on + rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature + maps. + rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN + rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training + rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing + rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training + rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing + rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals + rpn_fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be + considered as positive during training of the RPN. + rpn_bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be + considered as negative during training of the RPN. + rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN + for computing the loss + rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training + of the RPN + rpn_score_thresh (float): only return proposals with an objectness score greater than rpn_score_thresh + box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in + the locations indicated by the bounding boxes + box_head (nn.Module): module that takes the cropped feature maps as input + box_predictor (nn.Module): module that takes the output of box_head and returns the + classification logits and box regression deltas. + box_score_thresh (float): during inference, only return proposals with a classification score + greater than box_score_thresh + box_nms_thresh (float): NMS threshold for the prediction head. Used during inference + box_detections_per_img (int): maximum number of detections per image, for all classes. + box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be + considered as positive during training of the classification head + box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be + considered as negative during training of the classification head + box_batch_size_per_image (int): number of proposals that are sampled during training of the + classification head + box_positive_fraction (float): proportion of positive proposals in a mini-batch during training + of the classification head + bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the + bounding boxes + mask_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in + the locations indicated by the bounding boxes, which will be used for the mask head. + mask_head (nn.Module): module that takes the cropped feature maps as input + mask_predictor (nn.Module): module that takes the output of the mask_head and returns the + segmentation mask logits + + Example:: + + >>> import torch + >>> import torchvision + >>> from torchvision.models.detection import MaskRCNN + >>> from torchvision.models.detection.anchor_utils import AnchorGenerator + >>> + >>> # load a pre-trained model for classification and return + >>> # only the features + >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features + >>> # MaskRCNN needs to know the number of + >>> # output channels in a backbone. For mobilenet_v2, it's 1280 + >>> # so we need to add it here, + >>> backbone.out_channels = 1280 + >>> + >>> # let's make the RPN generate 5 x 3 anchors per spatial + >>> # location, with 5 different sizes and 3 different aspect + >>> # ratios. We have a Tuple[Tuple[int]] because each feature + >>> # map could potentially have different sizes and + >>> # aspect ratios + >>> anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),), + >>> aspect_ratios=((0.5, 1.0, 2.0),)) + >>> + >>> # let's define what are the feature maps that we will + >>> # use to perform the region of interest cropping, as well as + >>> # the size of the crop after rescaling. + >>> # if your backbone returns a Tensor, featmap_names is expected to + >>> # be ['0']. More generally, the backbone should return an + >>> # OrderedDict[Tensor], and in featmap_names you can choose which + >>> # feature maps to use. + >>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'], + >>> output_size=7, + >>> sampling_ratio=2) + >>> + >>> mask_roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'], + >>> output_size=14, + >>> sampling_ratio=2) + >>> # put the pieces together inside a MaskRCNN model + >>> model = MaskRCNN(backbone, + >>> num_classes=2, + >>> rpn_anchor_generator=anchor_generator, + >>> box_roi_pool=roi_pooler, + >>> mask_roi_pool=mask_roi_pooler) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + """ + + def __init__( + self, + backbone, + num_classes=None, + # transform parameters + min_size=800, + max_size=1333, + image_mean=None, + image_std=None, + # RPN parameters + rpn_anchor_generator=None, + rpn_head=None, + rpn_pre_nms_top_n_train=2000, + rpn_pre_nms_top_n_test=1000, + rpn_post_nms_top_n_train=2000, + rpn_post_nms_top_n_test=1000, + rpn_nms_thresh=0.7, + rpn_fg_iou_thresh=0.7, + rpn_bg_iou_thresh=0.3, + rpn_batch_size_per_image=256, + rpn_positive_fraction=0.5, + rpn_score_thresh=0.0, + # Box parameters + box_roi_pool=None, + box_head=None, + box_predictor=None, + box_score_thresh=0.05, + box_nms_thresh=0.5, + box_detections_per_img=100, + box_fg_iou_thresh=0.5, + box_bg_iou_thresh=0.5, + box_batch_size_per_image=512, + box_positive_fraction=0.25, + bbox_reg_weights=None, + # Mask parameters + mask_roi_pool=None, + mask_head=None, + mask_predictor=None, + **kwargs, + ): + + if not isinstance(mask_roi_pool, (MultiScaleRoIAlign, type(None))): + raise TypeError( + f"mask_roi_pool should be of type MultiScaleRoIAlign or None instead of {type(mask_roi_pool)}" + ) + + if num_classes is not None: + if mask_predictor is not None: + raise ValueError("num_classes should be None when mask_predictor is specified") + + out_channels = backbone.out_channels + + if mask_roi_pool is None: + mask_roi_pool = MultiScaleRoIAlign(featmap_names=["0", "1", "2", "3"], output_size=14, sampling_ratio=2) + + if mask_head is None: + mask_layers = (256, 256, 256, 256) + mask_dilation = 1 + mask_head = MaskRCNNHeads(out_channels, mask_layers, mask_dilation) + + if mask_predictor is None: + mask_predictor_in_channels = 256 # == mask_layers[-1] + mask_dim_reduced = 256 + mask_predictor = MaskRCNNPredictor(mask_predictor_in_channels, mask_dim_reduced, num_classes) + + super().__init__( + backbone, + num_classes, + # transform parameters + min_size, + max_size, + image_mean, + image_std, + # RPN-specific parameters + rpn_anchor_generator, + rpn_head, + rpn_pre_nms_top_n_train, + rpn_pre_nms_top_n_test, + rpn_post_nms_top_n_train, + rpn_post_nms_top_n_test, + rpn_nms_thresh, + rpn_fg_iou_thresh, + rpn_bg_iou_thresh, + rpn_batch_size_per_image, + rpn_positive_fraction, + rpn_score_thresh, + # Box parameters + box_roi_pool, + box_head, + box_predictor, + box_score_thresh, + box_nms_thresh, + box_detections_per_img, + box_fg_iou_thresh, + box_bg_iou_thresh, + box_batch_size_per_image, + box_positive_fraction, + bbox_reg_weights, + **kwargs, + ) + + self.roi_heads.mask_roi_pool = mask_roi_pool + self.roi_heads.mask_head = mask_head + self.roi_heads.mask_predictor = mask_predictor + + +class MaskRCNNHeads(nn.Sequential): + _version = 2 + + def __init__(self, in_channels, layers, dilation, norm_layer: Optional[Callable[..., nn.Module]] = None): + """ + Args: + in_channels (int): number of input channels + layers (list): feature dimensions of each FCN layer + dilation (int): dilation rate of kernel + norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None + """ + blocks = [] + next_feature = in_channels + for layer_features in layers: + blocks.append( + misc_nn_ops.Conv2dNormActivation( + next_feature, + layer_features, + kernel_size=3, + stride=1, + padding=dilation, + dilation=dilation, + norm_layer=norm_layer, + ) + ) + next_feature = layer_features + + super().__init__(*blocks) + for layer in self.modules(): + if isinstance(layer, nn.Conv2d): + nn.init.kaiming_normal_(layer.weight, mode="fan_out", nonlinearity="relu") + if layer.bias is not None: + nn.init.zeros_(layer.bias) + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if version is None or version < 2: + num_blocks = len(self) + for i in range(num_blocks): + for type in ["weight", "bias"]: + old_key = f"{prefix}mask_fcn{i+1}.{type}" + new_key = f"{prefix}{i}.0.{type}" + if old_key in state_dict: + state_dict[new_key] = state_dict.pop(old_key) + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + +class MaskRCNNPredictor(nn.Sequential): + def __init__(self, in_channels, dim_reduced, num_classes): + super().__init__( + OrderedDict( + [ + ("conv5_mask", nn.ConvTranspose2d(in_channels, dim_reduced, 2, 2, 0)), + ("relu", nn.ReLU(inplace=True)), + ("mask_fcn_logits", nn.Conv2d(dim_reduced, num_classes, 1, 1, 0)), + ] + ) + ) + + for name, param in self.named_parameters(): + if "weight" in name: + nn.init.kaiming_normal_(param, mode="fan_out", nonlinearity="relu") + # elif "bias" in name: + # nn.init.constant_(param, 0) + + +_COMMON_META = { + "categories": _COCO_CATEGORIES, + "min_size": (1, 1), +} + + +class MaskRCNN_ResNet50_FPN_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/maskrcnn_resnet50_fpn_coco-bf2d0c1e.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 44401393, + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#mask-r-cnn", + "_metrics": { + "COCO-val2017": { + "box_map": 37.9, + "mask_map": 34.6, + } + }, + "_ops": 134.38, + "_file_size": 169.84, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +class MaskRCNN_ResNet50_FPN_V2_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/maskrcnn_resnet50_fpn_v2_coco-73cbd019.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 46359409, + "recipe": "https://github.com/pytorch/vision/pull/5773", + "_metrics": { + "COCO-val2017": { + "box_map": 47.4, + "mask_map": 41.8, + } + }, + "_ops": 333.577, + "_file_size": 177.219, + "_docs": """These weights were produced using an enhanced training recipe to boost the model accuracy.""", + }, + ) + DEFAULT = COCO_V1 + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", MaskRCNN_ResNet50_FPN_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def maskrcnn_resnet50_fpn( + *, + weights: Optional[MaskRCNN_ResNet50_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> MaskRCNN: + """Mask R-CNN model with a ResNet-50-FPN backbone from the `Mask R-CNN + `_ paper. + + .. betastatus:: detection module + + The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each + image, and should be in ``0-1`` range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the class label for each ground-truth box + - masks (``UInt8Tensor[N, H, W]``): the segmentation binary masks for each instance + + The model returns a ``Dict[Tensor]`` during training, containing the classification and regression + losses for both the RPN and the R-CNN, and the mask loss. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as + follows, where ``N`` is the number of detected instances: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the predicted labels for each instance + - scores (``Tensor[N]``): the scores or each instance + - masks (``UInt8Tensor[N, 1, H, W]``): the predicted masks for each instance, in ``0-1`` range. In order to + obtain the final segmentation masks, the soft masks can be thresholded, generally + with a value of 0.5 (``mask >= 0.5``) + + For more details on the output and on how to plot the masks, you may refer to :ref:`instance_seg_output`. + + Mask R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size. + + Example:: + + >>> model = torchvision.models.detection.maskrcnn_resnet50_fpn(weights=MaskRCNN_ResNet50_FPN_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + >>> + >>> # optionally, if you want to export the model to ONNX: + >>> torch.onnx.export(model, x, "mask_rcnn.onnx", opset_version = 11) + + Args: + weights (:class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from + final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are + trainable. If ``None`` is passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.mask_rcnn.MaskRCNN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.MaskRCNN_ResNet50_FPN_Weights + :members: + """ + weights = MaskRCNN_ResNet50_FPN_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d + + backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer) + backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers) + model = MaskRCNN(backbone, num_classes=num_classes, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if weights == MaskRCNN_ResNet50_FPN_Weights.COCO_V1: + overwrite_eps(model, 0.0) + + return model + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", MaskRCNN_ResNet50_FPN_V2_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def maskrcnn_resnet50_fpn_v2( + *, + weights: Optional[MaskRCNN_ResNet50_FPN_V2_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = None, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> MaskRCNN: + """Improved Mask R-CNN model with a ResNet-50-FPN backbone from the `Benchmarking Detection Transfer + Learning with Vision Transformers `_ paper. + + .. betastatus:: detection module + + :func:`~torchvision.models.detection.maskrcnn_resnet50_fpn` for more details. + + Args: + weights (:class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_V2_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_V2_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from + final block. Valid values are between 0 and 5, with 5 meaning all backbone layers are + trainable. If ``None`` is passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.mask_rcnn.MaskRCNN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.MaskRCNN_ResNet50_FPN_V2_Weights + :members: + """ + weights = MaskRCNN_ResNet50_FPN_V2_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + + backbone = resnet50(weights=weights_backbone, progress=progress) + backbone = _resnet_fpn_extractor(backbone, trainable_backbone_layers, norm_layer=nn.BatchNorm2d) + rpn_anchor_generator = _default_anchorgen() + rpn_head = RPNHead(backbone.out_channels, rpn_anchor_generator.num_anchors_per_location()[0], conv_depth=2) + box_head = FastRCNNConvFCHead( + (backbone.out_channels, 7, 7), [256, 256, 256, 256], [1024], norm_layer=nn.BatchNorm2d + ) + mask_head = MaskRCNNHeads(backbone.out_channels, [256, 256, 256, 256], 1, norm_layer=nn.BatchNorm2d) + model = MaskRCNN( + backbone, + num_classes=num_classes, + rpn_anchor_generator=rpn_anchor_generator, + rpn_head=rpn_head, + box_head=box_head, + mask_head=mask_head, + **kwargs, + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/retinanet.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/retinanet.py new file mode 100644 index 0000000000000000000000000000000000000000..807fcd713df5a4607da2df72b98e1dc33e039e85 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/retinanet.py @@ -0,0 +1,903 @@ +import math +import warnings +from collections import OrderedDict +from functools import partial +from typing import Any, Callable, Optional + +import torch +from torch import nn, Tensor + +from ...ops import boxes as box_ops, misc as misc_nn_ops, sigmoid_focal_loss +from ...ops.feature_pyramid_network import LastLevelP6P7 +from ...transforms._presets import ObjectDetection +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..resnet import resnet50, ResNet50_Weights +from . import _utils as det_utils +from ._utils import _box_loss, overwrite_eps +from .anchor_utils import AnchorGenerator +from .backbone_utils import _resnet_fpn_extractor, _validate_trainable_layers +from .transform import GeneralizedRCNNTransform + + +__all__ = [ + "RetinaNet", + "RetinaNet_ResNet50_FPN_Weights", + "RetinaNet_ResNet50_FPN_V2_Weights", + "retinanet_resnet50_fpn", + "retinanet_resnet50_fpn_v2", +] + + +def _sum(x: list[Tensor]) -> Tensor: + res = x[0] + for i in x[1:]: + res = res + i + return res + + +def _v1_to_v2_weights(state_dict, prefix): + for i in range(4): + for type in ["weight", "bias"]: + old_key = f"{prefix}conv.{2*i}.{type}" + new_key = f"{prefix}conv.{i}.0.{type}" + if old_key in state_dict: + state_dict[new_key] = state_dict.pop(old_key) + + +def _default_anchorgen(): + anchor_sizes = tuple((x, int(x * 2 ** (1.0 / 3)), int(x * 2 ** (2.0 / 3))) for x in [32, 64, 128, 256, 512]) + aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes) + anchor_generator = AnchorGenerator(anchor_sizes, aspect_ratios) + return anchor_generator + + +class RetinaNetHead(nn.Module): + """ + A regression and classification head for use in RetinaNet. + + Args: + in_channels (int): number of channels of the input feature + num_anchors (int): number of anchors to be predicted + num_classes (int): number of classes to be predicted + norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None + """ + + def __init__(self, in_channels, num_anchors, num_classes, norm_layer: Optional[Callable[..., nn.Module]] = None): + super().__init__() + self.classification_head = RetinaNetClassificationHead( + in_channels, num_anchors, num_classes, norm_layer=norm_layer + ) + self.regression_head = RetinaNetRegressionHead(in_channels, num_anchors, norm_layer=norm_layer) + + def compute_loss(self, targets, head_outputs, anchors, matched_idxs): + # type: (list[dict[str, Tensor]], dict[str, Tensor], list[Tensor], list[Tensor]) -> dict[str, Tensor] + return { + "classification": self.classification_head.compute_loss(targets, head_outputs, matched_idxs), + "bbox_regression": self.regression_head.compute_loss(targets, head_outputs, anchors, matched_idxs), + } + + def forward(self, x): + # type: (list[Tensor]) -> dict[str, Tensor] + return {"cls_logits": self.classification_head(x), "bbox_regression": self.regression_head(x)} + + +class RetinaNetClassificationHead(nn.Module): + """ + A classification head for use in RetinaNet. + + Args: + in_channels (int): number of channels of the input feature + num_anchors (int): number of anchors to be predicted + num_classes (int): number of classes to be predicted + norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None + """ + + _version = 2 + + def __init__( + self, + in_channels, + num_anchors, + num_classes, + prior_probability=0.01, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ): + super().__init__() + + conv = [] + for _ in range(4): + conv.append(misc_nn_ops.Conv2dNormActivation(in_channels, in_channels, norm_layer=norm_layer)) + self.conv = nn.Sequential(*conv) + + for layer in self.conv.modules(): + if isinstance(layer, nn.Conv2d): + torch.nn.init.normal_(layer.weight, std=0.01) + if layer.bias is not None: + torch.nn.init.constant_(layer.bias, 0) + + self.cls_logits = nn.Conv2d(in_channels, num_anchors * num_classes, kernel_size=3, stride=1, padding=1) + torch.nn.init.normal_(self.cls_logits.weight, std=0.01) + torch.nn.init.constant_(self.cls_logits.bias, -math.log((1 - prior_probability) / prior_probability)) + + self.num_classes = num_classes + self.num_anchors = num_anchors + + # This is to fix using det_utils.Matcher.BETWEEN_THRESHOLDS in TorchScript. + # TorchScript doesn't support class attributes. + # https://github.com/pytorch/vision/pull/1697#issuecomment-630255584 + self.BETWEEN_THRESHOLDS = det_utils.Matcher.BETWEEN_THRESHOLDS + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if version is None or version < 2: + _v1_to_v2_weights(state_dict, prefix) + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + def compute_loss(self, targets, head_outputs, matched_idxs): + # type: (list[dict[str, Tensor]], dict[str, Tensor], list[Tensor]) -> Tensor + losses = [] + + cls_logits = head_outputs["cls_logits"] + + for targets_per_image, cls_logits_per_image, matched_idxs_per_image in zip(targets, cls_logits, matched_idxs): + # determine only the foreground + foreground_idxs_per_image = matched_idxs_per_image >= 0 + num_foreground = foreground_idxs_per_image.sum() + + # create the target classification + gt_classes_target = torch.zeros_like(cls_logits_per_image) + gt_classes_target[ + foreground_idxs_per_image, + targets_per_image["labels"][matched_idxs_per_image[foreground_idxs_per_image]], + ] = 1.0 + + # find indices for which anchors should be ignored + valid_idxs_per_image = matched_idxs_per_image != self.BETWEEN_THRESHOLDS + + # compute the classification loss + losses.append( + sigmoid_focal_loss( + cls_logits_per_image[valid_idxs_per_image], + gt_classes_target[valid_idxs_per_image], + reduction="sum", + ) + / max(1, num_foreground) + ) + + return _sum(losses) / len(targets) + + def forward(self, x): + # type: (list[Tensor]) -> Tensor + all_cls_logits = [] + + for features in x: + cls_logits = self.conv(features) + cls_logits = self.cls_logits(cls_logits) + + # Permute classification output from (N, A * K, H, W) to (N, HWA, K). + N, _, H, W = cls_logits.shape + cls_logits = cls_logits.view(N, -1, self.num_classes, H, W) + cls_logits = cls_logits.permute(0, 3, 4, 1, 2) + cls_logits = cls_logits.reshape(N, -1, self.num_classes) # Size=(N, HWA, 4) + + all_cls_logits.append(cls_logits) + + return torch.cat(all_cls_logits, dim=1) + + +class RetinaNetRegressionHead(nn.Module): + """ + A regression head for use in RetinaNet. + + Args: + in_channels (int): number of channels of the input feature + num_anchors (int): number of anchors to be predicted + norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None + """ + + _version = 2 + + __annotations__ = { + "box_coder": det_utils.BoxCoder, + } + + def __init__(self, in_channels, num_anchors, norm_layer: Optional[Callable[..., nn.Module]] = None): + super().__init__() + + conv = [] + for _ in range(4): + conv.append(misc_nn_ops.Conv2dNormActivation(in_channels, in_channels, norm_layer=norm_layer)) + self.conv = nn.Sequential(*conv) + + self.bbox_reg = nn.Conv2d(in_channels, num_anchors * 4, kernel_size=3, stride=1, padding=1) + torch.nn.init.normal_(self.bbox_reg.weight, std=0.01) + torch.nn.init.zeros_(self.bbox_reg.bias) + + for layer in self.conv.modules(): + if isinstance(layer, nn.Conv2d): + torch.nn.init.normal_(layer.weight, std=0.01) + if layer.bias is not None: + torch.nn.init.zeros_(layer.bias) + + self.box_coder = det_utils.BoxCoder(weights=(1.0, 1.0, 1.0, 1.0)) + self._loss_type = "l1" + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if version is None or version < 2: + _v1_to_v2_weights(state_dict, prefix) + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + def compute_loss(self, targets, head_outputs, anchors, matched_idxs): + # type: (list[dict[str, Tensor]], dict[str, Tensor], list[Tensor], list[Tensor]) -> Tensor + losses = [] + + bbox_regression = head_outputs["bbox_regression"] + + for targets_per_image, bbox_regression_per_image, anchors_per_image, matched_idxs_per_image in zip( + targets, bbox_regression, anchors, matched_idxs + ): + # determine only the foreground indices, ignore the rest + foreground_idxs_per_image = torch.where(matched_idxs_per_image >= 0)[0] + num_foreground = foreground_idxs_per_image.numel() + + # select only the foreground boxes + matched_gt_boxes_per_image = targets_per_image["boxes"][matched_idxs_per_image[foreground_idxs_per_image]] + bbox_regression_per_image = bbox_regression_per_image[foreground_idxs_per_image, :] + anchors_per_image = anchors_per_image[foreground_idxs_per_image, :] + + # compute the loss + losses.append( + _box_loss( + self._loss_type, + self.box_coder, + anchors_per_image, + matched_gt_boxes_per_image, + bbox_regression_per_image, + ) + / max(1, num_foreground) + ) + + return _sum(losses) / max(1, len(targets)) + + def forward(self, x): + # type: (list[Tensor]) -> Tensor + all_bbox_regression = [] + + for features in x: + bbox_regression = self.conv(features) + bbox_regression = self.bbox_reg(bbox_regression) + + # Permute bbox regression output from (N, 4 * A, H, W) to (N, HWA, 4). + N, _, H, W = bbox_regression.shape + bbox_regression = bbox_regression.view(N, -1, 4, H, W) + bbox_regression = bbox_regression.permute(0, 3, 4, 1, 2) + bbox_regression = bbox_regression.reshape(N, -1, 4) # Size=(N, HWA, 4) + + all_bbox_regression.append(bbox_regression) + + return torch.cat(all_bbox_regression, dim=1) + + +class RetinaNet(nn.Module): + """ + Implements RetinaNet. + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + + The model returns a Dict[Tensor] during training, containing the classification and regression + losses. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows: + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each image + - scores (Tensor[N]): the scores for each prediction + + Args: + backbone (nn.Module): the network used to compute the features for the model. + It should contain an out_channels attribute, which indicates the number of output + channels that each feature map has (and it should be the same for all feature maps). + The backbone should return a single Tensor or an OrderedDict[Tensor]. + num_classes (int): number of output classes of the model (including the background). + min_size (int): Images are rescaled before feeding them to the backbone: + we attempt to preserve the aspect ratio and scale the shorter edge + to ``min_size``. If the resulting longer edge exceeds ``max_size``, + then downscale so that the longer edge does not exceed ``max_size``. + This may result in the shorter edge being lower than ``min_size``. + max_size (int): See ``min_size``. + image_mean (Tuple[float, float, float]): mean values used for input normalization. + They are generally the mean values of the dataset on which the backbone has been trained + on + image_std (Tuple[float, float, float]): std values used for input normalization. + They are generally the std values of the dataset on which the backbone has been trained on + anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature + maps. + head (nn.Module): Module run on top of the feature pyramid. + Defaults to a module containing a classification and regression module. + score_thresh (float): Score threshold used for postprocessing the detections. + nms_thresh (float): NMS threshold used for postprocessing the detections. + detections_per_img (int): Number of best detections to keep after NMS. + fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be + considered as positive during training. + bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be + considered as negative during training. + topk_candidates (int): Number of best detections to keep before NMS. + + Example: + + >>> import torch + >>> import torchvision + >>> from torchvision.models.detection import RetinaNet + >>> from torchvision.models.detection.anchor_utils import AnchorGenerator + >>> # load a pre-trained model for classification and return + >>> # only the features + >>> backbone = torchvision.models.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).features + >>> # RetinaNet needs to know the number of + >>> # output channels in a backbone. For mobilenet_v2, it's 1280, + >>> # so we need to add it here + >>> backbone.out_channels = 1280 + >>> + >>> # let's make the network generate 5 x 3 anchors per spatial + >>> # location, with 5 different sizes and 3 different aspect + >>> # ratios. We have a Tuple[Tuple[int]] because each feature + >>> # map could potentially have different sizes and + >>> # aspect ratios + >>> anchor_generator = AnchorGenerator( + >>> sizes=((32, 64, 128, 256, 512),), + >>> aspect_ratios=((0.5, 1.0, 2.0),) + >>> ) + >>> + >>> # put the pieces together inside a RetinaNet model + >>> model = RetinaNet(backbone, + >>> num_classes=2, + >>> anchor_generator=anchor_generator) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + """ + + __annotations__ = { + "box_coder": det_utils.BoxCoder, + "proposal_matcher": det_utils.Matcher, + } + + def __init__( + self, + backbone, + num_classes, + # transform parameters + min_size=800, + max_size=1333, + image_mean=None, + image_std=None, + # Anchor parameters + anchor_generator=None, + head=None, + proposal_matcher=None, + score_thresh=0.05, + nms_thresh=0.5, + detections_per_img=300, + fg_iou_thresh=0.5, + bg_iou_thresh=0.4, + topk_candidates=1000, + **kwargs, + ): + super().__init__() + _log_api_usage_once(self) + + if not hasattr(backbone, "out_channels"): + raise ValueError( + "backbone should contain an attribute out_channels " + "specifying the number of output channels (assumed to be the " + "same for all the levels)" + ) + self.backbone = backbone + + if not isinstance(anchor_generator, (AnchorGenerator, type(None))): + raise TypeError( + f"anchor_generator should be of type AnchorGenerator or None instead of {type(anchor_generator)}" + ) + + if anchor_generator is None: + anchor_generator = _default_anchorgen() + self.anchor_generator = anchor_generator + + if head is None: + head = RetinaNetHead(backbone.out_channels, anchor_generator.num_anchors_per_location()[0], num_classes) + self.head = head + + if proposal_matcher is None: + proposal_matcher = det_utils.Matcher( + fg_iou_thresh, + bg_iou_thresh, + allow_low_quality_matches=True, + ) + self.proposal_matcher = proposal_matcher + + self.box_coder = det_utils.BoxCoder(weights=(1.0, 1.0, 1.0, 1.0)) + + if image_mean is None: + image_mean = [0.485, 0.456, 0.406] + if image_std is None: + image_std = [0.229, 0.224, 0.225] + self.transform = GeneralizedRCNNTransform(min_size, max_size, image_mean, image_std, **kwargs) + + self.score_thresh = score_thresh + self.nms_thresh = nms_thresh + self.detections_per_img = detections_per_img + self.topk_candidates = topk_candidates + + # used only on torchscript mode + self._has_warned = False + + @torch.jit.unused + def eager_outputs(self, losses, detections): + # type: (dict[str, Tensor], list[dict[str, Tensor]]) -> tuple[dict[str, Tensor], list[dict[str, Tensor]]] + if self.training: + return losses + + return detections + + def compute_loss(self, targets, head_outputs, anchors): + # type: (list[dict[str, Tensor]], dict[str, Tensor], list[Tensor]) -> dict[str, Tensor] + matched_idxs = [] + for anchors_per_image, targets_per_image in zip(anchors, targets): + if targets_per_image["boxes"].numel() == 0: + matched_idxs.append( + torch.full((anchors_per_image.size(0),), -1, dtype=torch.int64, device=anchors_per_image.device) + ) + continue + + match_quality_matrix = box_ops.box_iou(targets_per_image["boxes"], anchors_per_image) + matched_idxs.append(self.proposal_matcher(match_quality_matrix)) + + return self.head.compute_loss(targets, head_outputs, anchors, matched_idxs) + + def postprocess_detections(self, head_outputs, anchors, image_shapes): + # type: (dict[str, list[Tensor]], list[list[Tensor]], list[tuple[int, int]]) -> list[dict[str, Tensor]] + class_logits = head_outputs["cls_logits"] + box_regression = head_outputs["bbox_regression"] + + num_images = len(image_shapes) + + detections: list[dict[str, Tensor]] = [] + + for index in range(num_images): + box_regression_per_image = [br[index] for br in box_regression] + logits_per_image = [cl[index] for cl in class_logits] + anchors_per_image, image_shape = anchors[index], image_shapes[index] + + image_boxes = [] + image_scores = [] + image_labels = [] + + for box_regression_per_level, logits_per_level, anchors_per_level in zip( + box_regression_per_image, logits_per_image, anchors_per_image + ): + num_classes = logits_per_level.shape[-1] + + # remove low scoring boxes + scores_per_level = torch.sigmoid(logits_per_level).flatten() + keep_idxs = scores_per_level > self.score_thresh + scores_per_level = scores_per_level[keep_idxs] + topk_idxs = torch.where(keep_idxs)[0] + + # keep only topk scoring predictions + num_topk = det_utils._topk_min(topk_idxs, self.topk_candidates, 0) + scores_per_level, idxs = scores_per_level.topk(num_topk) + topk_idxs = topk_idxs[idxs] + + anchor_idxs = torch.div(topk_idxs, num_classes, rounding_mode="floor") + labels_per_level = topk_idxs % num_classes + + boxes_per_level = self.box_coder.decode_single( + box_regression_per_level[anchor_idxs], anchors_per_level[anchor_idxs] + ) + boxes_per_level = box_ops.clip_boxes_to_image(boxes_per_level, image_shape) + + image_boxes.append(boxes_per_level) + image_scores.append(scores_per_level) + image_labels.append(labels_per_level) + + image_boxes = torch.cat(image_boxes, dim=0) + image_scores = torch.cat(image_scores, dim=0) + image_labels = torch.cat(image_labels, dim=0) + + # non-maximum suppression + keep = box_ops.batched_nms(image_boxes, image_scores, image_labels, self.nms_thresh) + keep = keep[: self.detections_per_img] + + detections.append( + { + "boxes": image_boxes[keep], + "scores": image_scores[keep], + "labels": image_labels[keep], + } + ) + + return detections + + def forward(self, images, targets=None): + # type: (list[Tensor], Optional[list[dict[str, Tensor]]]) -> tuple[dict[str, Tensor], list[dict[str, Tensor]]] + """ + Args: + images (list[Tensor]): images to be processed + targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional) + + Returns: + result (list[BoxList] or dict[Tensor]): the output from the model. + During training, it returns a dict[Tensor] which contains the losses. + During testing, it returns list[BoxList] contains additional fields + like `scores`, `labels` and `mask` (for Mask R-CNN models). + + """ + if self.training: + if targets is None: + torch._assert(False, "targets should not be none when in training mode") + else: + for target in targets: + boxes = target["boxes"] + torch._assert(isinstance(boxes, torch.Tensor), "Expected target boxes to be of type Tensor.") + torch._assert( + len(boxes.shape) == 2 and boxes.shape[-1] == 4, + "Expected target boxes to be a tensor of shape [N, 4].", + ) + + # get the original image sizes + original_image_sizes: list[tuple[int, int]] = [] + for img in images: + val = img.shape[-2:] + torch._assert( + len(val) == 2, + f"expecting the last two dimensions of the Tensor to be H and W instead got {img.shape[-2:]}", + ) + original_image_sizes.append((val[0], val[1])) + + # transform the input + images, targets = self.transform(images, targets) + + # Check for degenerate boxes + # TODO: Move this to a function + if targets is not None: + for target_idx, target in enumerate(targets): + boxes = target["boxes"] + degenerate_boxes = boxes[:, 2:] <= boxes[:, :2] + if degenerate_boxes.any(): + # print the first degenerate box + bb_idx = torch.where(degenerate_boxes.any(dim=1))[0][0] + degen_bb: list[float] = boxes[bb_idx].tolist() + torch._assert( + False, + "All bounding boxes should have positive height and width." + f" Found invalid box {degen_bb} for target at index {target_idx}.", + ) + + # get the features from the backbone + features = self.backbone(images.tensors) + if isinstance(features, torch.Tensor): + features = OrderedDict([("0", features)]) + + # TODO: Do we want a list or a dict? + features = list(features.values()) + + # compute the retinanet heads outputs using the features + head_outputs = self.head(features) + + # create the set of anchors + anchors = self.anchor_generator(images, features) + + losses = {} + detections: list[dict[str, Tensor]] = [] + if self.training: + if targets is None: + torch._assert(False, "targets should not be none when in training mode") + else: + # compute the losses + losses = self.compute_loss(targets, head_outputs, anchors) + else: + # recover level sizes + num_anchors_per_level = [x.size(2) * x.size(3) for x in features] + HW = 0 + for v in num_anchors_per_level: + HW += v + HWA = head_outputs["cls_logits"].size(1) + A = HWA // HW + num_anchors_per_level = [hw * A for hw in num_anchors_per_level] + + # split outputs per level + split_head_outputs: dict[str, list[Tensor]] = {} + for k in head_outputs: + split_head_outputs[k] = list(head_outputs[k].split(num_anchors_per_level, dim=1)) + split_anchors = [list(a.split(num_anchors_per_level)) for a in anchors] + + # compute the detections + detections = self.postprocess_detections(split_head_outputs, split_anchors, images.image_sizes) + detections = self.transform.postprocess(detections, images.image_sizes, original_image_sizes) + + if torch.jit.is_scripting(): + if not self._has_warned: + warnings.warn("RetinaNet always returns a (Losses, Detections) tuple in scripting") + self._has_warned = True + return losses, detections + return self.eager_outputs(losses, detections) + + +_COMMON_META = { + "categories": _COCO_CATEGORIES, + "min_size": (1, 1), +} + + +class RetinaNet_ResNet50_FPN_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/retinanet_resnet50_fpn_coco-eeacb38b.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 34014999, + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#retinanet", + "_metrics": { + "COCO-val2017": { + "box_map": 36.4, + } + }, + "_ops": 151.54, + "_file_size": 130.267, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +class RetinaNet_ResNet50_FPN_V2_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/retinanet_resnet50_fpn_v2_coco-5905b1c5.pth", + transforms=ObjectDetection, + meta={ + **_COMMON_META, + "num_params": 38198935, + "recipe": "https://github.com/pytorch/vision/pull/5756", + "_metrics": { + "COCO-val2017": { + "box_map": 41.5, + } + }, + "_ops": 152.238, + "_file_size": 146.037, + "_docs": """These weights were produced using an enhanced training recipe to boost the model accuracy.""", + }, + ) + DEFAULT = COCO_V1 + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", RetinaNet_ResNet50_FPN_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def retinanet_resnet50_fpn( + *, + weights: Optional[RetinaNet_ResNet50_FPN_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> RetinaNet: + """ + Constructs a RetinaNet model with a ResNet-50-FPN backbone. + + .. betastatus:: detection module + + Reference: `Focal Loss for Dense Object Detection `_. + + The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each + image, and should be in ``0-1`` range. Different images can have different sizes. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the class label for each ground-truth box + + The model returns a ``Dict[Tensor]`` during training, containing the classification and regression + losses. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as + follows, where ``N`` is the number of detections: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (``Int64Tensor[N]``): the predicted labels for each detection + - scores (``Tensor[N]``): the scores of each detection + + For more details on the output, you may refer to :ref:`instance_seg_output`. + + Example:: + + >>> model = torchvision.models.detection.retinanet_resnet50_fpn(weights=RetinaNet_ResNet50_FPN_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)] + >>> predictions = model(x) + + Args: + weights (:class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained weights for + the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block. + Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is + passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.RetinaNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.RetinaNet_ResNet50_FPN_Weights + :members: + """ + weights = RetinaNet_ResNet50_FPN_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + norm_layer = misc_nn_ops.FrozenBatchNorm2d if is_trained else nn.BatchNorm2d + + backbone = resnet50(weights=weights_backbone, progress=progress, norm_layer=norm_layer) + # skip P2 because it generates too many anchors (according to their paper) + backbone = _resnet_fpn_extractor( + backbone, trainable_backbone_layers, returned_layers=[2, 3, 4], extra_blocks=LastLevelP6P7(256, 256) + ) + model = RetinaNet(backbone, num_classes, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if weights == RetinaNet_ResNet50_FPN_Weights.COCO_V1: + overwrite_eps(model, 0.0) + + return model + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", RetinaNet_ResNet50_FPN_V2_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def retinanet_resnet50_fpn_v2( + *, + weights: Optional[RetinaNet_ResNet50_FPN_V2_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[ResNet50_Weights] = None, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> RetinaNet: + """ + Constructs an improved RetinaNet model with a ResNet-50-FPN backbone. + + .. betastatus:: detection module + + Reference: `Bridging the Gap Between Anchor-based and Anchor-free Detection via Adaptive Training Sample Selection + `_. + + :func:`~torchvision.models.detection.retinanet_resnet50_fpn` for more details. + + Args: + weights (:class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_V2_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_V2_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained weights for + the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block. + Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is + passed (the default) this value is set to 3. + **kwargs: parameters passed to the ``torchvision.models.detection.RetinaNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.RetinaNet_ResNet50_FPN_V2_Weights + :members: + """ + weights = RetinaNet_ResNet50_FPN_V2_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + is_trained = weights is not None or weights_backbone is not None + trainable_backbone_layers = _validate_trainable_layers(is_trained, trainable_backbone_layers, 5, 3) + + backbone = resnet50(weights=weights_backbone, progress=progress) + backbone = _resnet_fpn_extractor( + backbone, trainable_backbone_layers, returned_layers=[2, 3, 4], extra_blocks=LastLevelP6P7(2048, 256) + ) + anchor_generator = _default_anchorgen() + head = RetinaNetHead( + backbone.out_channels, + anchor_generator.num_anchors_per_location()[0], + num_classes, + norm_layer=partial(nn.GroupNorm, 32), + ) + head.regression_head._loss_type = "giou" + model = RetinaNet(backbone, num_classes, anchor_generator=anchor_generator, head=head, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/roi_heads.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/roi_heads.py new file mode 100644 index 0000000000000000000000000000000000000000..2d610d91dadefb270e0339ddbde32753ea2d2f32 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/roi_heads.py @@ -0,0 +1,887 @@ +from typing import Optional + +import torch +import torch.nn.functional as F +import torchvision +from torch import nn +from torchvision.ops import boxes as box_ops, roi_align + +from . import _utils as det_utils + + +def fastrcnn_loss( + class_logits: torch.Tensor, + box_regression: torch.Tensor, + labels: list[torch.Tensor], + regression_targets: list[torch.Tensor], +) -> tuple[torch.Tensor, torch.Tensor]: + """ + Computes the loss for Faster R-CNN. + + Args: + class_logits (Tensor) + box_regression (Tensor) + labels (list[BoxList]) + regression_targets (Tensor) + + Returns: + classification_loss (Tensor) + box_loss (Tensor) + """ + + labels = torch.cat(labels, dim=0) + regression_targets = torch.cat(regression_targets, dim=0) + + classification_loss = F.cross_entropy(class_logits, labels) + + # get indices that correspond to the regression targets for + # the corresponding ground truth labels, to be used with + # advanced indexing + sampled_pos_inds_subset = torch.where(labels > 0)[0] + labels_pos = labels[sampled_pos_inds_subset] + N, num_classes = class_logits.shape + box_regression = box_regression.reshape(N, box_regression.size(-1) // 4, 4) + + box_loss = F.smooth_l1_loss( + box_regression[sampled_pos_inds_subset, labels_pos], + regression_targets[sampled_pos_inds_subset], + beta=1 / 9, + reduction="sum", + ) + box_loss = box_loss / labels.numel() + + return classification_loss, box_loss + + +def maskrcnn_inference(x: torch.Tensor, labels: list[torch.Tensor]) -> list[torch.Tensor]: + """ + From the results of the CNN, post process the masks + by taking the mask corresponding to the class with max + probability (which are of fixed size and directly output + by the CNN) and return the masks in the mask field of the BoxList. + + Args: + x (Tensor): the mask logits + labels (list[BoxList]): bounding boxes that are used as + reference, one for each image + + Returns: + results (list[BoxList]): one BoxList for each image, containing + the extra field mask + """ + mask_prob = x.sigmoid() + + # select masks corresponding to the predicted classes + num_masks = x.shape[0] + boxes_per_image = [label.shape[0] for label in labels] + labels = torch.cat(labels) + index = torch.arange(num_masks, device=labels.device) + mask_prob = mask_prob[index, labels][:, None] + mask_prob = mask_prob.split(boxes_per_image, dim=0) + + return mask_prob + + +def project_masks_on_boxes(gt_masks, boxes, matched_idxs, M): + # type: (Tensor, Tensor, Tensor, int) -> Tensor + """ + Given segmentation masks and the bounding boxes corresponding + to the location of the masks in the image, this function + crops and resizes the masks in the position defined by the + boxes. This prepares the masks for them to be fed to the + loss computation as the targets. + """ + matched_idxs = matched_idxs.to(boxes) + rois = torch.cat([matched_idxs[:, None], boxes], dim=1) + gt_masks = gt_masks[:, None].to(rois) + return roi_align(gt_masks, rois, (M, M), 1.0)[:, 0] + + +def maskrcnn_loss(mask_logits, proposals, gt_masks, gt_labels, mask_matched_idxs): + # type: (Tensor, list[Tensor], list[Tensor], list[Tensor], list[Tensor]) -> Tensor + """ + Args: + proposals (list[BoxList]) + mask_logits (Tensor) + targets (list[BoxList]) + + Return: + mask_loss (Tensor): scalar tensor containing the loss + """ + + discretization_size = mask_logits.shape[-1] + labels = [gt_label[idxs] for gt_label, idxs in zip(gt_labels, mask_matched_idxs)] + mask_targets = [ + project_masks_on_boxes(m, p, i, discretization_size) for m, p, i in zip(gt_masks, proposals, mask_matched_idxs) + ] + + labels = torch.cat(labels, dim=0) + mask_targets = torch.cat(mask_targets, dim=0) + + # torch.mean (in binary_cross_entropy_with_logits) doesn't + # accept empty tensors, so handle it separately + if mask_targets.numel() == 0: + return mask_logits.sum() * 0 + + mask_loss = F.binary_cross_entropy_with_logits( + mask_logits[torch.arange(labels.shape[0], device=labels.device), labels], mask_targets + ) + return mask_loss + + +def keypoints_to_heatmap(keypoints, rois, heatmap_size): + # type: (Tensor, Tensor, int) -> tuple[Tensor, Tensor] + offset_x = rois[:, 0] + offset_y = rois[:, 1] + scale_x = heatmap_size / (rois[:, 2] - rois[:, 0]) + scale_y = heatmap_size / (rois[:, 3] - rois[:, 1]) + + offset_x = offset_x[:, None] + offset_y = offset_y[:, None] + scale_x = scale_x[:, None] + scale_y = scale_y[:, None] + + x = keypoints[..., 0] + y = keypoints[..., 1] + + x_boundary_inds = x == rois[:, 2][:, None] + y_boundary_inds = y == rois[:, 3][:, None] + + x = (x - offset_x) * scale_x + x = x.floor().long() + y = (y - offset_y) * scale_y + y = y.floor().long() + + x[x_boundary_inds] = heatmap_size - 1 + y[y_boundary_inds] = heatmap_size - 1 + + valid_loc = (x >= 0) & (y >= 0) & (x < heatmap_size) & (y < heatmap_size) + vis = keypoints[..., 2] > 0 + valid = (valid_loc & vis).long() + + lin_ind = y * heatmap_size + x + heatmaps = lin_ind * valid + + return heatmaps, valid + + +def _onnx_heatmaps_to_keypoints( + maps, maps_i, roi_map_width, roi_map_height, widths_i, heights_i, offset_x_i, offset_y_i +): + num_keypoints = torch.scalar_tensor(maps.size(1), dtype=torch.int64) + + width_correction = widths_i / roi_map_width + height_correction = heights_i / roi_map_height + + roi_map = F.interpolate( + maps_i[:, None], size=(int(roi_map_height), int(roi_map_width)), mode="bicubic", align_corners=False + )[:, 0] + + w = torch.scalar_tensor(roi_map.size(2), dtype=torch.int64) + pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1) + + x_int = pos % w + y_int = (pos - x_int) // w + + x = (torch.tensor(0.5, dtype=torch.float32) + x_int.to(dtype=torch.float32)) * width_correction.to( + dtype=torch.float32 + ) + y = (torch.tensor(0.5, dtype=torch.float32) + y_int.to(dtype=torch.float32)) * height_correction.to( + dtype=torch.float32 + ) + + xy_preds_i_0 = x + offset_x_i.to(dtype=torch.float32) + xy_preds_i_1 = y + offset_y_i.to(dtype=torch.float32) + xy_preds_i_2 = torch.ones(xy_preds_i_1.shape, dtype=torch.float32) + xy_preds_i = torch.stack( + [ + xy_preds_i_0.to(dtype=torch.float32), + xy_preds_i_1.to(dtype=torch.float32), + xy_preds_i_2.to(dtype=torch.float32), + ], + 0, + ) + + # TODO: simplify when indexing without rank will be supported by ONNX + base = num_keypoints * num_keypoints + num_keypoints + 1 + ind = torch.arange(num_keypoints) + ind = ind.to(dtype=torch.int64) * base + end_scores_i = ( + roi_map.index_select(1, y_int.to(dtype=torch.int64)) + .index_select(2, x_int.to(dtype=torch.int64)) + .view(-1) + .index_select(0, ind.to(dtype=torch.int64)) + ) + + return xy_preds_i, end_scores_i + + +@torch.jit._script_if_tracing +def _onnx_heatmaps_to_keypoints_loop( + maps, rois, widths_ceil, heights_ceil, widths, heights, offset_x, offset_y, num_keypoints +): + xy_preds = torch.zeros((0, 3, int(num_keypoints)), dtype=torch.float32, device=maps.device) + end_scores = torch.zeros((0, int(num_keypoints)), dtype=torch.float32, device=maps.device) + + for i in range(int(rois.size(0))): + xy_preds_i, end_scores_i = _onnx_heatmaps_to_keypoints( + maps, maps[i], widths_ceil[i], heights_ceil[i], widths[i], heights[i], offset_x[i], offset_y[i] + ) + xy_preds = torch.cat((xy_preds.to(dtype=torch.float32), xy_preds_i.unsqueeze(0).to(dtype=torch.float32)), 0) + end_scores = torch.cat( + (end_scores.to(dtype=torch.float32), end_scores_i.to(dtype=torch.float32).unsqueeze(0)), 0 + ) + return xy_preds, end_scores + + +def heatmaps_to_keypoints(maps, rois): + """Extract predicted keypoint locations from heatmaps. + + Args: + maps (Tensor[K, N, H, W]): The predicted heatmaps, where K is the number of RoIs, + N is the number of keypoints, and H, W are the heatmap spatial dimensions. + rois (Tensor[K, 4]): The RoI boxes in ``(x1, y1, x2, y2)`` format. + + Returns: + tuple: + - **xy_preds** (Tensor[K, N, 3]): The predicted keypoint locations, where the last + dimension contains ``(x, y, v)`` with x, y being coordinates and v being visibility (always 1). + - **scores** (Tensor[K, N]): The heatmap scores at the predicted keypoint locations. + """ + # This function converts a discrete image coordinate in a HEATMAP_SIZE x + # HEATMAP_SIZE image to a continuous keypoint coordinate. We maintain + # consistency with keypoints_to_heatmap_labels by using the conversion from + # Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a + # continuous coordinate. + offset_x = rois[:, 0] + offset_y = rois[:, 1] + + widths = rois[:, 2] - rois[:, 0] + heights = rois[:, 3] - rois[:, 1] + widths = widths.clamp(min=1) + heights = heights.clamp(min=1) + widths_ceil = widths.ceil() + heights_ceil = heights.ceil() + + num_keypoints = maps.shape[1] + + if torchvision._is_tracing(): + xy_preds, end_scores = _onnx_heatmaps_to_keypoints_loop( + maps, + rois, + widths_ceil, + heights_ceil, + widths, + heights, + offset_x, + offset_y, + torch.scalar_tensor(num_keypoints, dtype=torch.int64), + ) + return xy_preds.permute(0, 2, 1), end_scores + + xy_preds = torch.zeros((len(rois), 3, num_keypoints), dtype=torch.float32, device=maps.device) + end_scores = torch.zeros((len(rois), num_keypoints), dtype=torch.float32, device=maps.device) + for i in range(len(rois)): + roi_map_width = int(widths_ceil[i].item()) + roi_map_height = int(heights_ceil[i].item()) + width_correction = widths[i] / roi_map_width + height_correction = heights[i] / roi_map_height + roi_map = F.interpolate( + maps[i][:, None], size=(roi_map_height, roi_map_width), mode="bicubic", align_corners=False + )[:, 0] + # roi_map_probs = scores_to_probs(roi_map.copy()) + w = roi_map.shape[2] + pos = roi_map.reshape(num_keypoints, -1).argmax(dim=1) + + x_int = pos % w + y_int = torch.div(pos - x_int, w, rounding_mode="floor") + # assert (roi_map_probs[k, y_int, x_int] == + # roi_map_probs[k, :, :].max()) + x = (x_int.float() + 0.5) * width_correction + y = (y_int.float() + 0.5) * height_correction + xy_preds[i, 0, :] = x + offset_x[i] + xy_preds[i, 1, :] = y + offset_y[i] + xy_preds[i, 2, :] = 1 + end_scores[i, :] = roi_map[torch.arange(num_keypoints, device=roi_map.device), y_int, x_int] + + return xy_preds.permute(0, 2, 1), end_scores + + +def keypointrcnn_loss(keypoint_logits, proposals, gt_keypoints, keypoint_matched_idxs): + # type: (Tensor, list[Tensor], list[Tensor], list[Tensor]) -> Tensor + N, K, H, W = keypoint_logits.shape + if H != W: + raise ValueError( + f"keypoint_logits height and width (last two elements of shape) should be equal. Instead got H = {H} and W = {W}" + ) + discretization_size = H + heatmaps = [] + valid = [] + for proposals_per_image, gt_kp_in_image, midx in zip(proposals, gt_keypoints, keypoint_matched_idxs): + kp = gt_kp_in_image[midx] + heatmaps_per_image, valid_per_image = keypoints_to_heatmap(kp, proposals_per_image, discretization_size) + heatmaps.append(heatmaps_per_image.view(-1)) + valid.append(valid_per_image.view(-1)) + + keypoint_targets = torch.cat(heatmaps, dim=0) + valid = torch.cat(valid, dim=0).to(dtype=torch.uint8) + valid = torch.where(valid)[0] + + # torch.mean (in binary_cross_entropy_with_logits) doesn't + # accept empty tensors, so handle it sepaartely + if keypoint_targets.numel() == 0 or len(valid) == 0: + return keypoint_logits.sum() * 0 + + keypoint_logits = keypoint_logits.view(N * K, H * W) + + keypoint_loss = F.cross_entropy(keypoint_logits[valid], keypoint_targets[valid]) + return keypoint_loss + + +def keypointrcnn_inference(x, boxes): + # type: (Tensor, list[Tensor]) -> tuple[list[Tensor], list[Tensor]] + kp_probs = [] + kp_scores = [] + + boxes_per_image = [box.size(0) for box in boxes] + x2 = x.split(boxes_per_image, dim=0) + + for xx, bb in zip(x2, boxes): + kp_prob, scores = heatmaps_to_keypoints(xx, bb) + kp_probs.append(kp_prob) + kp_scores.append(scores) + + return kp_probs, kp_scores + + +def _onnx_expand_boxes(boxes, scale): + # type: (Tensor, float) -> Tensor + w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5 + h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5 + x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5 + y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5 + + w_half = w_half.to(dtype=torch.float32) * scale + h_half = h_half.to(dtype=torch.float32) * scale + + boxes_exp0 = x_c - w_half + boxes_exp1 = y_c - h_half + boxes_exp2 = x_c + w_half + boxes_exp3 = y_c + h_half + boxes_exp = torch.stack((boxes_exp0, boxes_exp1, boxes_exp2, boxes_exp3), 1) + return boxes_exp + + +# the next two functions should be merged inside Masker +# but are kept here for the moment while we need them +# temporarily for paste_mask_in_image +def expand_boxes(boxes, scale): + # type: (Tensor, float) -> Tensor + if torchvision._is_tracing(): + return _onnx_expand_boxes(boxes, scale) + w_half = (boxes[:, 2] - boxes[:, 0]) * 0.5 + h_half = (boxes[:, 3] - boxes[:, 1]) * 0.5 + x_c = (boxes[:, 2] + boxes[:, 0]) * 0.5 + y_c = (boxes[:, 3] + boxes[:, 1]) * 0.5 + + w_half *= scale + h_half *= scale + + boxes_exp = torch.zeros_like(boxes) + boxes_exp[:, 0] = x_c - w_half + boxes_exp[:, 2] = x_c + w_half + boxes_exp[:, 1] = y_c - h_half + boxes_exp[:, 3] = y_c + h_half + return boxes_exp + + +@torch.jit.unused +def expand_masks_tracing_scale(M, padding): + # type: (int, int) -> float + return torch.tensor(M + 2 * padding).to(torch.float32) / torch.tensor(M).to(torch.float32) + + +def expand_masks(mask, padding): + # type: (Tensor, int) -> tuple[Tensor, float] + M = mask.shape[-1] + if torch._C._get_tracing_state(): # could not import is_tracing(), not sure why + scale = expand_masks_tracing_scale(M, padding) + else: + scale = float(M + 2 * padding) / M + padded_mask = F.pad(mask, (padding,) * 4) + return padded_mask, scale + + +def paste_mask_in_image(mask, box, im_h, im_w): + # type: (Tensor, Tensor, int, int) -> Tensor + TO_REMOVE = 1 + w = int(box[2] - box[0] + TO_REMOVE) + h = int(box[3] - box[1] + TO_REMOVE) + w = max(w, 1) + h = max(h, 1) + + # Set shape to [batchxCxHxW] + mask = mask.expand((1, 1, -1, -1)) + + # Resize mask + mask = F.interpolate(mask, size=(h, w), mode="bilinear", align_corners=False) + mask = mask[0][0] + + im_mask = torch.zeros((im_h, im_w), dtype=mask.dtype, device=mask.device) + x_0 = max(box[0], 0) + x_1 = min(box[2] + 1, im_w) + y_0 = max(box[1], 0) + y_1 = min(box[3] + 1, im_h) + + im_mask[y_0:y_1, x_0:x_1] = mask[(y_0 - box[1]) : (y_1 - box[1]), (x_0 - box[0]) : (x_1 - box[0])] + return im_mask + + +def _onnx_paste_mask_in_image(mask, box, im_h, im_w): + one = torch.ones(1, dtype=torch.int64) + zero = torch.zeros(1, dtype=torch.int64) + + w = box[2] - box[0] + one + h = box[3] - box[1] + one + w = torch.max(torch.cat((w, one))) + h = torch.max(torch.cat((h, one))) + + # Set shape to [batchxCxHxW] + mask = mask.expand((1, 1, mask.size(0), mask.size(1))) + + # Resize mask + mask = F.interpolate(mask, size=(int(h), int(w)), mode="bilinear", align_corners=False) + mask = mask[0][0] + + x_0 = torch.max(torch.cat((box[0].unsqueeze(0), zero))) + x_1 = torch.min(torch.cat((box[2].unsqueeze(0) + one, im_w.unsqueeze(0)))) + y_0 = torch.max(torch.cat((box[1].unsqueeze(0), zero))) + y_1 = torch.min(torch.cat((box[3].unsqueeze(0) + one, im_h.unsqueeze(0)))) + + unpaded_im_mask = mask[(y_0 - box[1]) : (y_1 - box[1]), (x_0 - box[0]) : (x_1 - box[0])] + + # TODO : replace below with a dynamic padding when support is added in ONNX + + # pad y + zeros_y0 = torch.zeros(y_0, unpaded_im_mask.size(1)) + zeros_y1 = torch.zeros(im_h - y_1, unpaded_im_mask.size(1)) + concat_0 = torch.cat((zeros_y0, unpaded_im_mask.to(dtype=torch.float32), zeros_y1), 0)[0:im_h, :] + # pad x + zeros_x0 = torch.zeros(concat_0.size(0), x_0) + zeros_x1 = torch.zeros(concat_0.size(0), im_w - x_1) + im_mask = torch.cat((zeros_x0, concat_0, zeros_x1), 1)[:, :im_w] + return im_mask + + +@torch.jit._script_if_tracing +def _onnx_paste_masks_in_image_loop(masks, boxes, im_h, im_w): + res_append = torch.zeros(0, im_h, im_w) + for i in range(masks.size(0)): + mask_res = _onnx_paste_mask_in_image(masks[i][0], boxes[i], im_h, im_w) + mask_res = mask_res.unsqueeze(0) + res_append = torch.cat((res_append, mask_res)) + return res_append + + +def paste_masks_in_image(masks, boxes, img_shape, padding=1): + # type: (Tensor, Tensor, tuple[int, int], int) -> Tensor + masks, scale = expand_masks(masks, padding=padding) + boxes = expand_boxes(boxes, scale).to(dtype=torch.int64) + im_h, im_w = img_shape + + if torchvision._is_tracing(): + return _onnx_paste_masks_in_image_loop( + masks, boxes, torch.scalar_tensor(im_h, dtype=torch.int64), torch.scalar_tensor(im_w, dtype=torch.int64) + )[:, None] + res = [paste_mask_in_image(m[0], b, im_h, im_w) for m, b in zip(masks, boxes)] + if len(res) > 0: + ret = torch.stack(res, dim=0)[:, None] + else: + ret = masks.new_empty((0, 1, im_h, im_w)) + return ret + + +class RoIHeads(nn.Module): + __annotations__ = { + "box_coder": det_utils.BoxCoder, + "proposal_matcher": det_utils.Matcher, + "fg_bg_sampler": det_utils.BalancedPositiveNegativeSampler, + } + + def __init__( + self, + box_roi_pool, + box_head, + box_predictor, + # Faster R-CNN training + fg_iou_thresh, + bg_iou_thresh, + batch_size_per_image, + positive_fraction, + bbox_reg_weights, + # Faster R-CNN inference + score_thresh, + nms_thresh, + detections_per_img, + # Mask + mask_roi_pool=None, + mask_head=None, + mask_predictor=None, + keypoint_roi_pool=None, + keypoint_head=None, + keypoint_predictor=None, + ): + super().__init__() + + self.box_similarity = box_ops.box_iou + # assign ground-truth boxes for each proposal + self.proposal_matcher = det_utils.Matcher(fg_iou_thresh, bg_iou_thresh, allow_low_quality_matches=False) + + self.fg_bg_sampler = det_utils.BalancedPositiveNegativeSampler(batch_size_per_image, positive_fraction) + + if bbox_reg_weights is None: + bbox_reg_weights = (10.0, 10.0, 5.0, 5.0) + self.box_coder = det_utils.BoxCoder(bbox_reg_weights) + + self.box_roi_pool = box_roi_pool + self.box_head = box_head + self.box_predictor = box_predictor + + self.score_thresh = score_thresh + self.nms_thresh = nms_thresh + self.detections_per_img = detections_per_img + + self.mask_roi_pool = mask_roi_pool + self.mask_head = mask_head + self.mask_predictor = mask_predictor + + self.keypoint_roi_pool = keypoint_roi_pool + self.keypoint_head = keypoint_head + self.keypoint_predictor = keypoint_predictor + + def has_mask(self): + if self.mask_roi_pool is None: + return False + if self.mask_head is None: + return False + if self.mask_predictor is None: + return False + return True + + def has_keypoint(self): + if self.keypoint_roi_pool is None: + return False + if self.keypoint_head is None: + return False + if self.keypoint_predictor is None: + return False + return True + + def assign_targets_to_proposals(self, proposals, gt_boxes, gt_labels): + # type: (list[Tensor], list[Tensor], list[Tensor]) -> tuple[list[Tensor], list[Tensor]] + matched_idxs = [] + labels = [] + for proposals_in_image, gt_boxes_in_image, gt_labels_in_image in zip(proposals, gt_boxes, gt_labels): + + if gt_boxes_in_image.numel() == 0: + # Background image + device = proposals_in_image.device + clamped_matched_idxs_in_image = torch.zeros( + (proposals_in_image.shape[0],), dtype=torch.int64, device=device + ) + labels_in_image = torch.zeros((proposals_in_image.shape[0],), dtype=torch.int64, device=device) + else: + # set to self.box_similarity when https://github.com/pytorch/pytorch/issues/27495 lands + match_quality_matrix = box_ops.box_iou(gt_boxes_in_image, proposals_in_image) + matched_idxs_in_image = self.proposal_matcher(match_quality_matrix) + + clamped_matched_idxs_in_image = matched_idxs_in_image.clamp(min=0) + + labels_in_image = gt_labels_in_image[clamped_matched_idxs_in_image] + labels_in_image = labels_in_image.to(dtype=torch.int64) + + # Label background (below the low threshold) + bg_inds = matched_idxs_in_image == self.proposal_matcher.BELOW_LOW_THRESHOLD + labels_in_image[bg_inds] = 0 + + # Label ignore proposals (between low and high thresholds) + ignore_inds = matched_idxs_in_image == self.proposal_matcher.BETWEEN_THRESHOLDS + labels_in_image[ignore_inds] = -1 # -1 is ignored by sampler + + matched_idxs.append(clamped_matched_idxs_in_image) + labels.append(labels_in_image) + return matched_idxs, labels + + def subsample(self, labels): + # type: (list[Tensor]) -> list[Tensor] + sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels) + sampled_inds = [] + for img_idx, (pos_inds_img, neg_inds_img) in enumerate(zip(sampled_pos_inds, sampled_neg_inds)): + img_sampled_inds = torch.where(pos_inds_img | neg_inds_img)[0] + sampled_inds.append(img_sampled_inds) + return sampled_inds + + def add_gt_proposals(self, proposals, gt_boxes): + # type: (list[Tensor], list[Tensor]) -> list[Tensor] + proposals = [torch.cat((proposal, gt_box)) for proposal, gt_box in zip(proposals, gt_boxes)] + + return proposals + + def check_targets(self, targets): + # type: (Optional[list[dict[str, Tensor]]]) -> None + if targets is None: + raise ValueError("targets should not be None") + if not all(["boxes" in t for t in targets]): + raise ValueError("Every element of targets should have a boxes key") + if not all(["labels" in t for t in targets]): + raise ValueError("Every element of targets should have a labels key") + if self.has_mask(): + if not all(["masks" in t for t in targets]): + raise ValueError("Every element of targets should have a masks key") + + def select_training_samples( + self, + proposals, # type: list[Tensor] + targets, # type: Optional[list[dict[str, Tensor]]] + ): + # type: (...) -> tuple[list[Tensor], list[Tensor], list[Tensor], list[Tensor]] + self.check_targets(targets) + if targets is None: + raise ValueError("targets should not be None") + dtype = proposals[0].dtype + device = proposals[0].device + + gt_boxes = [t["boxes"].to(dtype) for t in targets] + gt_labels = [t["labels"] for t in targets] + + # append ground-truth bboxes to propos + proposals = self.add_gt_proposals(proposals, gt_boxes) + + # get matching gt indices for each proposal + matched_idxs, labels = self.assign_targets_to_proposals(proposals, gt_boxes, gt_labels) + # sample a fixed proportion of positive-negative proposals + sampled_inds = self.subsample(labels) + matched_gt_boxes = [] + num_images = len(proposals) + for img_id in range(num_images): + img_sampled_inds = sampled_inds[img_id] + proposals[img_id] = proposals[img_id][img_sampled_inds] + labels[img_id] = labels[img_id][img_sampled_inds] + matched_idxs[img_id] = matched_idxs[img_id][img_sampled_inds] + + gt_boxes_in_image = gt_boxes[img_id] + if gt_boxes_in_image.numel() == 0: + gt_boxes_in_image = torch.zeros((1, 4), dtype=dtype, device=device) + matched_gt_boxes.append(gt_boxes_in_image[matched_idxs[img_id]]) + + regression_targets = self.box_coder.encode(matched_gt_boxes, proposals) + return proposals, matched_idxs, labels, regression_targets + + def postprocess_detections( + self, + class_logits, # type: Tensor + box_regression, # type: Tensor + proposals, # type: list[Tensor] + image_shapes, # type: list[tuple[int, int]] + ): + # type: (...) -> tuple[list[Tensor], list[Tensor], list[Tensor]] + device = class_logits.device + num_classes = class_logits.shape[-1] + + boxes_per_image = [boxes_in_image.shape[0] for boxes_in_image in proposals] + pred_boxes = self.box_coder.decode(box_regression, proposals) + + pred_scores = F.softmax(class_logits, -1) + + pred_boxes_list = pred_boxes.split(boxes_per_image, 0) + pred_scores_list = pred_scores.split(boxes_per_image, 0) + + all_boxes = [] + all_scores = [] + all_labels = [] + for boxes, scores, image_shape in zip(pred_boxes_list, pred_scores_list, image_shapes): + boxes = box_ops.clip_boxes_to_image(boxes, image_shape) + + # create labels for each prediction + labels = torch.arange(num_classes, device=device) + labels = labels.view(1, -1).expand_as(scores) + + # remove predictions with the background label + boxes = boxes[:, 1:] + scores = scores[:, 1:] + labels = labels[:, 1:] + + # batch everything, by making every class prediction be a separate instance + boxes = boxes.reshape(-1, 4) + scores = scores.reshape(-1) + labels = labels.reshape(-1) + + # remove low scoring boxes + inds = torch.where(scores > self.score_thresh)[0] + boxes, scores, labels = boxes[inds], scores[inds], labels[inds] + + # remove empty boxes + keep = box_ops.remove_small_boxes(boxes, min_size=1e-2) + boxes, scores, labels = boxes[keep], scores[keep], labels[keep] + + # non-maximum suppression, independently done per class + keep = box_ops.batched_nms(boxes, scores, labels, self.nms_thresh) + # keep only topk scoring predictions + keep = keep[: self.detections_per_img] + boxes, scores, labels = boxes[keep], scores[keep], labels[keep] + + all_boxes.append(boxes) + all_scores.append(scores) + all_labels.append(labels) + + return all_boxes, all_scores, all_labels + + def forward( + self, + features: dict[str, torch.Tensor], + proposals: list[torch.Tensor], + image_shapes: list[tuple[int, int]], + targets: Optional[list[dict[str, torch.Tensor]]] = None, + ) -> tuple[list[dict[str, torch.Tensor]], dict[str, torch.Tensor]]: + """ + Args: + features (List[Tensor]) + proposals (List[Tensor[N, 4]]) + image_shapes (List[Tuple[H, W]]) + targets (List[Dict]) + """ + if targets is not None: + for t in targets: + # TODO: https://github.com/pytorch/pytorch/issues/26731 + floating_point_types = (torch.float, torch.double, torch.half) + if t["boxes"].dtype not in floating_point_types: + raise TypeError(f"target boxes must of float type, instead got {t['boxes'].dtype}") + if not t["labels"].dtype == torch.int64: + raise TypeError(f"target labels must of int64 type, instead got {t['labels'].dtype}") + if self.has_keypoint(): + if not t["keypoints"].dtype == torch.float32: + raise TypeError(f"target keypoints must of float type, instead got {t['keypoints'].dtype}") + + if self.training: + proposals, matched_idxs, labels, regression_targets = self.select_training_samples(proposals, targets) + else: + labels = None + regression_targets = None + matched_idxs = None + + box_features = self.box_roi_pool(features, proposals, image_shapes) + box_features = self.box_head(box_features) + class_logits, box_regression = self.box_predictor(box_features) + + result: list[dict[str, torch.Tensor]] = [] + losses = {} + if self.training: + if labels is None: + raise ValueError("labels cannot be None") + if regression_targets is None: + raise ValueError("regression_targets cannot be None") + loss_classifier, loss_box_reg = fastrcnn_loss(class_logits, box_regression, labels, regression_targets) + losses = {"loss_classifier": loss_classifier, "loss_box_reg": loss_box_reg} + else: + boxes, scores, labels = self.postprocess_detections(class_logits, box_regression, proposals, image_shapes) + num_images = len(boxes) + for i in range(num_images): + result.append( + { + "boxes": boxes[i], + "labels": labels[i], + "scores": scores[i], + } + ) + + if self.has_mask(): + mask_proposals = [p["boxes"] for p in result] + if self.training: + if matched_idxs is None: + raise ValueError("if in training, matched_idxs should not be None") + + # during training, only focus on positive boxes + num_images = len(proposals) + mask_proposals = [] + pos_matched_idxs = [] + for img_id in range(num_images): + pos = torch.where(labels[img_id] > 0)[0] + mask_proposals.append(proposals[img_id][pos]) + pos_matched_idxs.append(matched_idxs[img_id][pos]) + else: + pos_matched_idxs = None + + if self.mask_roi_pool is not None: + mask_features = self.mask_roi_pool(features, mask_proposals, image_shapes) + mask_features = self.mask_head(mask_features) + mask_logits = self.mask_predictor(mask_features) + else: + raise Exception("Expected mask_roi_pool to be not None") + + loss_mask = {} + if self.training: + if targets is None or pos_matched_idxs is None or mask_logits is None: + raise ValueError("targets, pos_matched_idxs, mask_logits cannot be None when training") + + gt_masks = [t["masks"] for t in targets] + gt_labels = [t["labels"] for t in targets] + rcnn_loss_mask = maskrcnn_loss(mask_logits, mask_proposals, gt_masks, gt_labels, pos_matched_idxs) + loss_mask = {"loss_mask": rcnn_loss_mask} + else: + labels = [r["labels"] for r in result] + masks_probs = maskrcnn_inference(mask_logits, labels) + for mask_prob, r in zip(masks_probs, result): + r["masks"] = mask_prob + + losses.update(loss_mask) + + # keep none checks in if conditional so torchscript will conditionally + # compile each branch + if ( + self.keypoint_roi_pool is not None + and self.keypoint_head is not None + and self.keypoint_predictor is not None + ): + keypoint_proposals = [p["boxes"] for p in result] + if self.training: + # during training, only focus on positive boxes + num_images = len(proposals) + keypoint_proposals = [] + pos_matched_idxs = [] + if matched_idxs is None: + raise ValueError("if in trainning, matched_idxs should not be None") + + for img_id in range(num_images): + pos = torch.where(labels[img_id] > 0)[0] + keypoint_proposals.append(proposals[img_id][pos]) + pos_matched_idxs.append(matched_idxs[img_id][pos]) + else: + pos_matched_idxs = None + + keypoint_features = self.keypoint_roi_pool(features, keypoint_proposals, image_shapes) + keypoint_features = self.keypoint_head(keypoint_features) + keypoint_logits = self.keypoint_predictor(keypoint_features) + + loss_keypoint = {} + if self.training: + if targets is None or pos_matched_idxs is None: + raise ValueError("both targets and pos_matched_idxs should not be None when in training mode") + + gt_keypoints = [t["keypoints"] for t in targets] + rcnn_loss_keypoint = keypointrcnn_loss( + keypoint_logits, keypoint_proposals, gt_keypoints, pos_matched_idxs + ) + loss_keypoint = {"loss_keypoint": rcnn_loss_keypoint} + else: + if keypoint_logits is None or keypoint_proposals is None: + raise ValueError( + "both keypoint_logits and keypoint_proposals should not be None when not in training mode" + ) + + keypoints_probs, kp_scores = keypointrcnn_inference(keypoint_logits, keypoint_proposals) + for keypoint_prob, kps, r in zip(keypoints_probs, kp_scores, result): + r["keypoints"] = keypoint_prob + r["keypoints_scores"] = kps + losses.update(loss_keypoint) + + return result, losses diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/rpn.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/rpn.py new file mode 100644 index 0000000000000000000000000000000000000000..ef5718922cb2cb001a5e47f48731b733ffd808eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/rpn.py @@ -0,0 +1,387 @@ +from typing import Optional + +import torch +from torch import nn, Tensor +from torch.nn import functional as F +from torchvision.ops import boxes as box_ops, Conv2dNormActivation + +from . import _utils as det_utils + +# Import AnchorGenerator to keep compatibility. +from .anchor_utils import AnchorGenerator # noqa: 401 +from .image_list import ImageList + + +class RPNHead(nn.Module): + """ + Adds a simple RPN Head with classification and regression heads + + Args: + in_channels (int): number of channels of the input feature + num_anchors (int): number of anchors to be predicted + conv_depth (int, optional): number of convolutions + """ + + _version = 2 + + def __init__(self, in_channels: int, num_anchors: int, conv_depth=1) -> None: + super().__init__() + convs = [] + for _ in range(conv_depth): + convs.append(Conv2dNormActivation(in_channels, in_channels, kernel_size=3, norm_layer=None)) + self.conv = nn.Sequential(*convs) + self.cls_logits = nn.Conv2d(in_channels, num_anchors, kernel_size=1, stride=1) + self.bbox_pred = nn.Conv2d(in_channels, num_anchors * 4, kernel_size=1, stride=1) + + for layer in self.modules(): + if isinstance(layer, nn.Conv2d): + torch.nn.init.normal_(layer.weight, std=0.01) # type: ignore[arg-type] + if layer.bias is not None: + torch.nn.init.constant_(layer.bias, 0) # type: ignore[arg-type] + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if version is None or version < 2: + for type in ["weight", "bias"]: + old_key = f"{prefix}conv.{type}" + new_key = f"{prefix}conv.0.0.{type}" + if old_key in state_dict: + state_dict[new_key] = state_dict.pop(old_key) + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + def forward(self, x: list[Tensor]) -> tuple[list[Tensor], list[Tensor]]: + logits = [] + bbox_reg = [] + for feature in x: + t = self.conv(feature) + logits.append(self.cls_logits(t)) + bbox_reg.append(self.bbox_pred(t)) + return logits, bbox_reg + + +def permute_and_flatten(layer: Tensor, N: int, A: int, C: int, H: int, W: int) -> Tensor: + layer = layer.view(N, -1, C, H, W) + layer = layer.permute(0, 3, 4, 1, 2) + layer = layer.reshape(N, -1, C) + return layer + + +def concat_box_prediction_layers(box_cls: list[Tensor], box_regression: list[Tensor]) -> tuple[Tensor, Tensor]: + box_cls_flattened = [] + box_regression_flattened = [] + # for each feature level, permute the outputs to make them be in the + # same format as the labels. Note that the labels are computed for + # all feature levels concatenated, so we keep the same representation + # for the objectness and the box_regression + for box_cls_per_level, box_regression_per_level in zip(box_cls, box_regression): + N, AxC, H, W = box_cls_per_level.shape + Ax4 = box_regression_per_level.shape[1] + A = Ax4 // 4 + C = AxC // A + box_cls_per_level = permute_and_flatten(box_cls_per_level, N, A, C, H, W) + box_cls_flattened.append(box_cls_per_level) + + box_regression_per_level = permute_and_flatten(box_regression_per_level, N, A, 4, H, W) + box_regression_flattened.append(box_regression_per_level) + # concatenate on the first dimension (representing the feature levels), to + # take into account the way the labels were generated (with all feature maps + # being concatenated as well) + box_cls = torch.cat(box_cls_flattened, dim=1).flatten(0, -2) + box_regression = torch.cat(box_regression_flattened, dim=1).reshape(-1, 4) + return box_cls, box_regression + + +class RegionProposalNetwork(torch.nn.Module): + """ + Implements Region Proposal Network (RPN). + + Args: + anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature + maps. + head (nn.Module): module that computes the objectness and regression deltas + fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be + considered as positive during training of the RPN. + bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be + considered as negative during training of the RPN. + batch_size_per_image (int): number of anchors that are sampled during training of the RPN + for computing the loss + positive_fraction (float): proportion of positive anchors in a mini-batch during training + of the RPN + pre_nms_top_n (Dict[str, int]): number of proposals to keep before applying NMS. It should + contain two fields: training and testing, to allow for different values depending + on training or evaluation + post_nms_top_n (Dict[str, int]): number of proposals to keep after applying NMS. It should + contain two fields: training and testing, to allow for different values depending + on training or evaluation + nms_thresh (float): NMS threshold used for postprocessing the RPN proposals + score_thresh (float): only return proposals with an objectness score greater than score_thresh + + """ + + __annotations__ = { + "box_coder": det_utils.BoxCoder, + "proposal_matcher": det_utils.Matcher, + "fg_bg_sampler": det_utils.BalancedPositiveNegativeSampler, + } + + def __init__( + self, + anchor_generator: AnchorGenerator, + head: nn.Module, + # Faster-RCNN Training + fg_iou_thresh: float, + bg_iou_thresh: float, + batch_size_per_image: int, + positive_fraction: float, + # Faster-RCNN Inference + pre_nms_top_n: dict[str, int], + post_nms_top_n: dict[str, int], + nms_thresh: float, + score_thresh: float = 0.0, + ) -> None: + super().__init__() + self.anchor_generator = anchor_generator + self.head = head + self.box_coder = det_utils.BoxCoder(weights=(1.0, 1.0, 1.0, 1.0)) + + # used during training + self.box_similarity = box_ops.box_iou + + self.proposal_matcher = det_utils.Matcher( + fg_iou_thresh, + bg_iou_thresh, + allow_low_quality_matches=True, + ) + + self.fg_bg_sampler = det_utils.BalancedPositiveNegativeSampler(batch_size_per_image, positive_fraction) + # used during testing + self._pre_nms_top_n = pre_nms_top_n + self._post_nms_top_n = post_nms_top_n + self.nms_thresh = nms_thresh + self.score_thresh = score_thresh + self.min_size = 1e-3 + + def pre_nms_top_n(self) -> int: + if self.training: + return self._pre_nms_top_n["training"] + return self._pre_nms_top_n["testing"] + + def post_nms_top_n(self) -> int: + if self.training: + return self._post_nms_top_n["training"] + return self._post_nms_top_n["testing"] + + def assign_targets_to_anchors( + self, anchors: list[Tensor], targets: list[dict[str, Tensor]] + ) -> tuple[list[Tensor], list[Tensor]]: + + labels = [] + matched_gt_boxes = [] + for anchors_per_image, targets_per_image in zip(anchors, targets): + gt_boxes = targets_per_image["boxes"] + + if gt_boxes.numel() == 0: + # Background image (negative example) + device = anchors_per_image.device + matched_gt_boxes_per_image = torch.zeros(anchors_per_image.shape, dtype=torch.float32, device=device) + labels_per_image = torch.zeros((anchors_per_image.shape[0],), dtype=torch.float32, device=device) + else: + match_quality_matrix = self.box_similarity(gt_boxes, anchors_per_image) + matched_idxs = self.proposal_matcher(match_quality_matrix) + # get the targets corresponding GT for each proposal + # NB: need to clamp the indices because we can have a single + # GT in the image, and matched_idxs can be -2, which goes + # out of bounds + matched_gt_boxes_per_image = gt_boxes[matched_idxs.clamp(min=0)] + + labels_per_image = matched_idxs >= 0 + labels_per_image = labels_per_image.to(dtype=torch.float32) + + # Background (negative examples) + bg_indices = matched_idxs == self.proposal_matcher.BELOW_LOW_THRESHOLD + labels_per_image[bg_indices] = 0.0 + + # discard indices that are between thresholds + inds_to_discard = matched_idxs == self.proposal_matcher.BETWEEN_THRESHOLDS + labels_per_image[inds_to_discard] = -1.0 + + labels.append(labels_per_image) + matched_gt_boxes.append(matched_gt_boxes_per_image) + return labels, matched_gt_boxes + + def _get_top_n_idx(self, objectness: Tensor, num_anchors_per_level: list[int]) -> Tensor: + r = [] + offset = 0 + for ob in objectness.split(num_anchors_per_level, 1): + num_anchors = ob.shape[1] + pre_nms_top_n = det_utils._topk_min(ob, self.pre_nms_top_n(), 1) + _, top_n_idx = ob.topk(pre_nms_top_n, dim=1) + r.append(top_n_idx + offset) + offset += num_anchors + return torch.cat(r, dim=1) + + def filter_proposals( + self, + proposals: Tensor, + objectness: Tensor, + image_shapes: list[tuple[int, int]], + num_anchors_per_level: list[int], + ) -> tuple[list[Tensor], list[Tensor]]: + + num_images = proposals.shape[0] + device = proposals.device + # do not backprop through objectness + objectness = objectness.detach() + objectness = objectness.reshape(num_images, -1) + + levels = [ + torch.full((n,), idx, dtype=torch.int64, device=device) for idx, n in enumerate(num_anchors_per_level) + ] + levels = torch.cat(levels, 0) + levels = levels.reshape(1, -1).expand_as(objectness) + + # select top_n boxes independently per level before applying nms + top_n_idx = self._get_top_n_idx(objectness, num_anchors_per_level) + + image_range = torch.arange(num_images, device=device) + batch_idx = image_range[:, None] + + objectness = objectness[batch_idx, top_n_idx] + levels = levels[batch_idx, top_n_idx] + proposals = proposals[batch_idx, top_n_idx] + + objectness_prob = torch.sigmoid(objectness) + + final_boxes = [] + final_scores = [] + for boxes, scores, lvl, img_shape in zip(proposals, objectness_prob, levels, image_shapes): + boxes = box_ops.clip_boxes_to_image(boxes, img_shape) + + # remove small boxes + keep = box_ops.remove_small_boxes(boxes, self.min_size) + boxes, scores, lvl = boxes[keep], scores[keep], lvl[keep] + + # remove low scoring boxes + # use >= for Backwards compatibility + keep = torch.where(scores >= self.score_thresh)[0] + boxes, scores, lvl = boxes[keep], scores[keep], lvl[keep] + + # non-maximum suppression, independently done per level + keep = box_ops.batched_nms(boxes, scores, lvl, self.nms_thresh) + + # keep only topk scoring predictions + keep = keep[: self.post_nms_top_n()] + boxes, scores = boxes[keep], scores[keep] + + final_boxes.append(boxes) + final_scores.append(scores) + return final_boxes, final_scores + + def compute_loss( + self, objectness: Tensor, pred_bbox_deltas: Tensor, labels: list[Tensor], regression_targets: list[Tensor] + ) -> tuple[Tensor, Tensor]: + """ + Args: + objectness (Tensor) + pred_bbox_deltas (Tensor) + labels (List[Tensor]) + regression_targets (List[Tensor]) + + Returns: + objectness_loss (Tensor) + box_loss (Tensor) + """ + + sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels) + sampled_pos_inds = torch.where(torch.cat(sampled_pos_inds, dim=0))[0] + sampled_neg_inds = torch.where(torch.cat(sampled_neg_inds, dim=0))[0] + + sampled_inds = torch.cat([sampled_pos_inds, sampled_neg_inds], dim=0) + + objectness = objectness.flatten() + + labels = torch.cat(labels, dim=0) + regression_targets = torch.cat(regression_targets, dim=0) + + box_loss = F.smooth_l1_loss( + pred_bbox_deltas[sampled_pos_inds], + regression_targets[sampled_pos_inds], + beta=1 / 9, + reduction="sum", + ) / (sampled_inds.numel()) + + objectness_loss = F.binary_cross_entropy_with_logits(objectness[sampled_inds], labels[sampled_inds]) + + return objectness_loss, box_loss + + def forward( + self, + images: ImageList, + features: dict[str, Tensor], + targets: Optional[list[dict[str, Tensor]]] = None, + ) -> tuple[list[Tensor], dict[str, Tensor]]: + """ + Args: + images (ImageList): images for which we want to compute the predictions + features (Dict[str, Tensor]): features computed from the images that are + used for computing the predictions. Each tensor in the list + correspond to different feature levels + targets (List[Dict[str, Tensor]]): ground-truth boxes present in the image (optional). + If provided, each element in the dict should contain a field `boxes`, + with the locations of the ground-truth boxes. + + Returns: + boxes (List[Tensor]): the predicted boxes from the RPN, one Tensor per + image. + losses (Dict[str, Tensor]): the losses for the model during training. During + testing, it is an empty dict. + """ + # RPN uses all feature maps that are available + features = list(features.values()) + objectness, pred_bbox_deltas = self.head(features) + anchors = self.anchor_generator(images, features) + + num_images = len(anchors) + num_anchors_per_level_shape_tensors = [o[0].shape for o in objectness] + num_anchors_per_level = [s[0] * s[1] * s[2] for s in num_anchors_per_level_shape_tensors] + objectness, pred_bbox_deltas = concat_box_prediction_layers(objectness, pred_bbox_deltas) + # apply pred_bbox_deltas to anchors to obtain the decoded proposals + # note that we detach the deltas because Faster R-CNN do not backprop through + # the proposals + proposals = self.box_coder.decode(pred_bbox_deltas.detach(), anchors) + proposals = proposals.view(num_images, -1, 4) + boxes, scores = self.filter_proposals(proposals, objectness, images.image_sizes, num_anchors_per_level) + + losses = {} + if self.training: + if targets is None: + raise ValueError("targets should not be None") + labels, matched_gt_boxes = self.assign_targets_to_anchors(anchors, targets) + regression_targets = self.box_coder.encode(matched_gt_boxes, anchors) + loss_objectness, loss_rpn_box_reg = self.compute_loss( + objectness, pred_bbox_deltas, labels, regression_targets + ) + losses = { + "loss_objectness": loss_objectness, + "loss_rpn_box_reg": loss_rpn_box_reg, + } + return boxes, losses diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/ssd.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/ssd.py new file mode 100644 index 0000000000000000000000000000000000000000..8cd43d04c7520965a8e9eed11d7d184e9991f805 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/ssd.py @@ -0,0 +1,682 @@ +import warnings +from collections import OrderedDict +from typing import Any, Optional + +import torch +import torch.nn.functional as F +from torch import nn, Tensor + +from ...ops import boxes as box_ops +from ...transforms._presets import ObjectDetection +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..vgg import VGG, vgg16, VGG16_Weights +from . import _utils as det_utils +from .anchor_utils import DefaultBoxGenerator +from .backbone_utils import _validate_trainable_layers +from .transform import GeneralizedRCNNTransform + + +__all__ = [ + "SSD300_VGG16_Weights", + "ssd300_vgg16", +] + + +class SSD300_VGG16_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/ssd300_vgg16_coco-b556d3b4.pth", + transforms=ObjectDetection, + meta={ + "num_params": 35641826, + "categories": _COCO_CATEGORIES, + "min_size": (1, 1), + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#ssd300-vgg16", + "_metrics": { + "COCO-val2017": { + "box_map": 25.1, + } + }, + "_ops": 34.858, + "_file_size": 135.988, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +def _xavier_init(conv: nn.Module): + for layer in conv.modules(): + if isinstance(layer, nn.Conv2d): + torch.nn.init.xavier_uniform_(layer.weight) + if layer.bias is not None: + torch.nn.init.constant_(layer.bias, 0.0) + + +class SSDHead(nn.Module): + def __init__(self, in_channels: list[int], num_anchors: list[int], num_classes: int): + super().__init__() + self.classification_head = SSDClassificationHead(in_channels, num_anchors, num_classes) + self.regression_head = SSDRegressionHead(in_channels, num_anchors) + + def forward(self, x: list[Tensor]) -> dict[str, Tensor]: + return { + "bbox_regression": self.regression_head(x), + "cls_logits": self.classification_head(x), + } + + +class SSDScoringHead(nn.Module): + def __init__(self, module_list: nn.ModuleList, num_columns: int): + super().__init__() + self.module_list = module_list + self.num_columns = num_columns + + def _get_result_from_module_list(self, x: Tensor, idx: int) -> Tensor: + """ + This is equivalent to self.module_list[idx](x), + but torchscript doesn't support this yet + """ + num_blocks = len(self.module_list) + if idx < 0: + idx += num_blocks + out = x + for i, module in enumerate(self.module_list): + if i == idx: + out = module(x) + return out + + def forward(self, x: list[Tensor]) -> Tensor: + all_results = [] + + for i, features in enumerate(x): + results = self._get_result_from_module_list(features, i) + + # Permute output from (N, A * K, H, W) to (N, HWA, K). + N, _, H, W = results.shape + results = results.view(N, -1, self.num_columns, H, W) + results = results.permute(0, 3, 4, 1, 2) + results = results.reshape(N, -1, self.num_columns) # Size=(N, HWA, K) + + all_results.append(results) + + return torch.cat(all_results, dim=1) + + +class SSDClassificationHead(SSDScoringHead): + def __init__(self, in_channels: list[int], num_anchors: list[int], num_classes: int): + cls_logits = nn.ModuleList() + for channels, anchors in zip(in_channels, num_anchors): + cls_logits.append(nn.Conv2d(channels, num_classes * anchors, kernel_size=3, padding=1)) + _xavier_init(cls_logits) + super().__init__(cls_logits, num_classes) + + +class SSDRegressionHead(SSDScoringHead): + def __init__(self, in_channels: list[int], num_anchors: list[int]): + bbox_reg = nn.ModuleList() + for channels, anchors in zip(in_channels, num_anchors): + bbox_reg.append(nn.Conv2d(channels, 4 * anchors, kernel_size=3, padding=1)) + _xavier_init(bbox_reg) + super().__init__(bbox_reg, 4) + + +class SSD(nn.Module): + """ + Implements SSD architecture from `"SSD: Single Shot MultiBox Detector" `_. + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes, but they will be resized + to a fixed size before passing it to the backbone. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + + The model returns a Dict[Tensor] during training, containing the classification and regression + losses. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows, where ``N`` is the number of detections: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each detection + - scores (Tensor[N]): the scores for each detection + + Args: + backbone (nn.Module): the network used to compute the features for the model. + It should contain an out_channels attribute with the list of the output channels of + each feature map. The backbone should return a single Tensor or an OrderedDict[Tensor]. + anchor_generator (DefaultBoxGenerator): module that generates the default boxes for a + set of feature maps. + size (Tuple[int, int]): the width and height to which images will be rescaled before feeding them + to the backbone. + num_classes (int): number of output classes of the model (including the background). + image_mean (Tuple[float, float, float]): mean values used for input normalization. + They are generally the mean values of the dataset on which the backbone has been trained + on + image_std (Tuple[float, float, float]): std values used for input normalization. + They are generally the std values of the dataset on which the backbone has been trained on + head (nn.Module, optional): Module run on top of the backbone features. Defaults to a module containing + a classification and regression module. + score_thresh (float): Score threshold used for postprocessing the detections. + nms_thresh (float): NMS threshold used for postprocessing the detections. + detections_per_img (int): Number of best detections to keep after NMS. + iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be + considered as positive during training. + topk_candidates (int): Number of best detections to keep before NMS. + positive_fraction (float): a number between 0 and 1 which indicates the proportion of positive + proposals used during the training of the classification head. It is used to estimate the negative to + positive ratio. + """ + + __annotations__ = { + "box_coder": det_utils.BoxCoder, + "proposal_matcher": det_utils.Matcher, + } + + def __init__( + self, + backbone: nn.Module, + anchor_generator: DefaultBoxGenerator, + size: tuple[int, int], + num_classes: int, + image_mean: Optional[list[float]] = None, + image_std: Optional[list[float]] = None, + head: Optional[nn.Module] = None, + score_thresh: float = 0.01, + nms_thresh: float = 0.45, + detections_per_img: int = 200, + iou_thresh: float = 0.5, + topk_candidates: int = 400, + positive_fraction: float = 0.25, + **kwargs: Any, + ): + super().__init__() + _log_api_usage_once(self) + + self.backbone = backbone + + self.anchor_generator = anchor_generator + + self.box_coder = det_utils.BoxCoder(weights=(10.0, 10.0, 5.0, 5.0)) + + if head is None: + if hasattr(backbone, "out_channels"): + out_channels = backbone.out_channels + else: + out_channels = det_utils.retrieve_out_channels(backbone, size) + + if len(out_channels) != len(anchor_generator.aspect_ratios): + raise ValueError( + f"The length of the output channels from the backbone ({len(out_channels)}) do not match the length of the anchor generator aspect ratios ({len(anchor_generator.aspect_ratios)})" + ) + + num_anchors = self.anchor_generator.num_anchors_per_location() + head = SSDHead(out_channels, num_anchors, num_classes) + self.head = head + + self.proposal_matcher = det_utils.SSDMatcher(iou_thresh) + + if image_mean is None: + image_mean = [0.485, 0.456, 0.406] + if image_std is None: + image_std = [0.229, 0.224, 0.225] + self.transform = GeneralizedRCNNTransform( + min(size), max(size), image_mean, image_std, size_divisible=1, fixed_size=size, **kwargs + ) + + self.score_thresh = score_thresh + self.nms_thresh = nms_thresh + self.detections_per_img = detections_per_img + self.topk_candidates = topk_candidates + self.neg_to_pos_ratio = (1.0 - positive_fraction) / positive_fraction + + # used only on torchscript mode + self._has_warned = False + + @torch.jit.unused + def eager_outputs( + self, losses: dict[str, Tensor], detections: list[dict[str, Tensor]] + ) -> tuple[dict[str, Tensor], list[dict[str, Tensor]]]: + if self.training: + return losses + + return detections + + def compute_loss( + self, + targets: list[dict[str, Tensor]], + head_outputs: dict[str, Tensor], + anchors: list[Tensor], + matched_idxs: list[Tensor], + ) -> dict[str, Tensor]: + bbox_regression = head_outputs["bbox_regression"] + cls_logits = head_outputs["cls_logits"] + + # Match original targets with default boxes + num_foreground = 0 + bbox_loss = [] + cls_targets = [] + for ( + targets_per_image, + bbox_regression_per_image, + cls_logits_per_image, + anchors_per_image, + matched_idxs_per_image, + ) in zip(targets, bbox_regression, cls_logits, anchors, matched_idxs): + # produce the matching between boxes and targets + foreground_idxs_per_image = torch.where(matched_idxs_per_image >= 0)[0] + foreground_matched_idxs_per_image = matched_idxs_per_image[foreground_idxs_per_image] + num_foreground += foreground_matched_idxs_per_image.numel() + + # Calculate regression loss + matched_gt_boxes_per_image = targets_per_image["boxes"][foreground_matched_idxs_per_image] + bbox_regression_per_image = bbox_regression_per_image[foreground_idxs_per_image, :] + anchors_per_image = anchors_per_image[foreground_idxs_per_image, :] + target_regression = self.box_coder.encode_single(matched_gt_boxes_per_image, anchors_per_image) + bbox_loss.append( + torch.nn.functional.smooth_l1_loss(bbox_regression_per_image, target_regression, reduction="sum") + ) + + # Estimate ground truth for class targets + gt_classes_target = torch.zeros( + (cls_logits_per_image.size(0),), + dtype=targets_per_image["labels"].dtype, + device=targets_per_image["labels"].device, + ) + gt_classes_target[foreground_idxs_per_image] = targets_per_image["labels"][ + foreground_matched_idxs_per_image + ] + cls_targets.append(gt_classes_target) + + bbox_loss = torch.stack(bbox_loss) + cls_targets = torch.stack(cls_targets) + + # Calculate classification loss + num_classes = cls_logits.size(-1) + cls_loss = F.cross_entropy(cls_logits.view(-1, num_classes), cls_targets.view(-1), reduction="none").view( + cls_targets.size() + ) + + # Hard Negative Sampling + foreground_idxs = cls_targets > 0 + num_negative = self.neg_to_pos_ratio * foreground_idxs.sum(1, keepdim=True) + # num_negative[num_negative < self.neg_to_pos_ratio] = self.neg_to_pos_ratio + negative_loss = cls_loss.clone() + negative_loss[foreground_idxs] = -float("inf") # use -inf to detect positive values that creeped in the sample + values, idx = negative_loss.sort(1, descending=True) + # background_idxs = torch.logical_and(idx.sort(1)[1] < num_negative, torch.isfinite(values)) + background_idxs = idx.sort(1)[1] < num_negative + + N = max(1, num_foreground) + return { + "bbox_regression": bbox_loss.sum() / N, + "classification": (cls_loss[foreground_idxs].sum() + cls_loss[background_idxs].sum()) / N, + } + + def forward( + self, images: list[Tensor], targets: Optional[list[dict[str, Tensor]]] = None + ) -> tuple[dict[str, Tensor], list[dict[str, Tensor]]]: + if self.training: + if targets is None: + torch._assert(False, "targets should not be none when in training mode") + else: + for target in targets: + boxes = target["boxes"] + if isinstance(boxes, torch.Tensor): + torch._assert( + len(boxes.shape) == 2 and boxes.shape[-1] == 4, + f"Expected target boxes to be a tensor of shape [N, 4], got {boxes.shape}.", + ) + else: + torch._assert(False, f"Expected target boxes to be of type Tensor, got {type(boxes)}.") + + # get the original image sizes + original_image_sizes: list[tuple[int, int]] = [] + for img in images: + val = img.shape[-2:] + torch._assert( + len(val) == 2, + f"expecting the last two dimensions of the Tensor to be H and W instead got {img.shape[-2:]}", + ) + original_image_sizes.append((val[0], val[1])) + + # transform the input + images, targets = self.transform(images, targets) + + # Check for degenerate boxes + if targets is not None: + for target_idx, target in enumerate(targets): + boxes = target["boxes"] + degenerate_boxes = boxes[:, 2:] <= boxes[:, :2] + if degenerate_boxes.any(): + bb_idx = torch.where(degenerate_boxes.any(dim=1))[0][0] + degen_bb: list[float] = boxes[bb_idx].tolist() + torch._assert( + False, + "All bounding boxes should have positive height and width." + f" Found invalid box {degen_bb} for target at index {target_idx}.", + ) + + # get the features from the backbone + features = self.backbone(images.tensors) + if isinstance(features, torch.Tensor): + features = OrderedDict([("0", features)]) + + features = list(features.values()) + + # compute the ssd heads outputs using the features + head_outputs = self.head(features) + + # create the set of anchors + anchors = self.anchor_generator(images, features) + + losses = {} + detections: list[dict[str, Tensor]] = [] + if self.training: + matched_idxs = [] + if targets is None: + torch._assert(False, "targets should not be none when in training mode") + else: + for anchors_per_image, targets_per_image in zip(anchors, targets): + if targets_per_image["boxes"].numel() == 0: + matched_idxs.append( + torch.full( + (anchors_per_image.size(0),), -1, dtype=torch.int64, device=anchors_per_image.device + ) + ) + continue + + match_quality_matrix = box_ops.box_iou(targets_per_image["boxes"], anchors_per_image) + matched_idxs.append(self.proposal_matcher(match_quality_matrix)) + + losses = self.compute_loss(targets, head_outputs, anchors, matched_idxs) + else: + detections = self.postprocess_detections(head_outputs, anchors, images.image_sizes) + detections = self.transform.postprocess(detections, images.image_sizes, original_image_sizes) + + if torch.jit.is_scripting(): + if not self._has_warned: + warnings.warn("SSD always returns a (Losses, Detections) tuple in scripting") + self._has_warned = True + return losses, detections + return self.eager_outputs(losses, detections) + + def postprocess_detections( + self, head_outputs: dict[str, Tensor], image_anchors: list[Tensor], image_shapes: list[tuple[int, int]] + ) -> list[dict[str, Tensor]]: + bbox_regression = head_outputs["bbox_regression"] + pred_scores = F.softmax(head_outputs["cls_logits"], dim=-1) + + num_classes = pred_scores.size(-1) + device = pred_scores.device + + detections: list[dict[str, Tensor]] = [] + + for boxes, scores, anchors, image_shape in zip(bbox_regression, pred_scores, image_anchors, image_shapes): + boxes = self.box_coder.decode_single(boxes, anchors) + boxes = box_ops.clip_boxes_to_image(boxes, image_shape) + + image_boxes = [] + image_scores = [] + image_labels = [] + for label in range(1, num_classes): + score = scores[:, label] + + keep_idxs = score > self.score_thresh + score = score[keep_idxs] + box = boxes[keep_idxs] + + # keep only topk scoring predictions + num_topk = det_utils._topk_min(score, self.topk_candidates, 0) + score, idxs = score.topk(num_topk) + box = box[idxs] + + image_boxes.append(box) + image_scores.append(score) + image_labels.append(torch.full_like(score, fill_value=label, dtype=torch.int64, device=device)) + + image_boxes = torch.cat(image_boxes, dim=0) + image_scores = torch.cat(image_scores, dim=0) + image_labels = torch.cat(image_labels, dim=0) + + # non-maximum suppression + keep = box_ops.batched_nms(image_boxes, image_scores, image_labels, self.nms_thresh) + keep = keep[: self.detections_per_img] + + detections.append( + { + "boxes": image_boxes[keep], + "scores": image_scores[keep], + "labels": image_labels[keep], + } + ) + return detections + + +class SSDFeatureExtractorVGG(nn.Module): + def __init__(self, backbone: nn.Module, highres: bool): + super().__init__() + + _, _, maxpool3_pos, maxpool4_pos, _ = (i for i, layer in enumerate(backbone) if isinstance(layer, nn.MaxPool2d)) + + # Patch ceil_mode for maxpool3 to get the same WxH output sizes as the paper + backbone[maxpool3_pos].ceil_mode = True + + # parameters used for L2 regularization + rescaling + self.scale_weight = nn.Parameter(torch.ones(512) * 20) + + # Multiple Feature maps - page 4, Fig 2 of SSD paper + self.features = nn.Sequential(*backbone[:maxpool4_pos]) # until conv4_3 + + # SSD300 case - page 4, Fig 2 of SSD paper + extra = nn.ModuleList( + [ + nn.Sequential( + nn.Conv2d(1024, 256, kernel_size=1), + nn.ReLU(inplace=True), + nn.Conv2d(256, 512, kernel_size=3, padding=1, stride=2), # conv8_2 + nn.ReLU(inplace=True), + ), + nn.Sequential( + nn.Conv2d(512, 128, kernel_size=1), + nn.ReLU(inplace=True), + nn.Conv2d(128, 256, kernel_size=3, padding=1, stride=2), # conv9_2 + nn.ReLU(inplace=True), + ), + nn.Sequential( + nn.Conv2d(256, 128, kernel_size=1), + nn.ReLU(inplace=True), + nn.Conv2d(128, 256, kernel_size=3), # conv10_2 + nn.ReLU(inplace=True), + ), + nn.Sequential( + nn.Conv2d(256, 128, kernel_size=1), + nn.ReLU(inplace=True), + nn.Conv2d(128, 256, kernel_size=3), # conv11_2 + nn.ReLU(inplace=True), + ), + ] + ) + if highres: + # Additional layers for the SSD512 case. See page 11, footernote 5. + extra.append( + nn.Sequential( + nn.Conv2d(256, 128, kernel_size=1), + nn.ReLU(inplace=True), + nn.Conv2d(128, 256, kernel_size=4), # conv12_2 + nn.ReLU(inplace=True), + ) + ) + _xavier_init(extra) + + fc = nn.Sequential( + nn.MaxPool2d(kernel_size=3, stride=1, padding=1, ceil_mode=False), # add modified maxpool5 + nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=3, padding=6, dilation=6), # FC6 with atrous + nn.ReLU(inplace=True), + nn.Conv2d(in_channels=1024, out_channels=1024, kernel_size=1), # FC7 + nn.ReLU(inplace=True), + ) + _xavier_init(fc) + extra.insert( + 0, + nn.Sequential( + *backbone[maxpool4_pos:-1], # until conv5_3, skip maxpool5 + fc, + ), + ) + self.extra = extra + + def forward(self, x: Tensor) -> dict[str, Tensor]: + # L2 regularization + Rescaling of 1st block's feature map + x = self.features(x) + rescaled = self.scale_weight.view(1, -1, 1, 1) * F.normalize(x) + output = [rescaled] + + # Calculating Feature maps for the rest blocks + for block in self.extra: + x = block(x) + output.append(x) + + return OrderedDict([(str(i), v) for i, v in enumerate(output)]) + + +def _vgg_extractor(backbone: VGG, highres: bool, trainable_layers: int): + backbone = backbone.features + # Gather the indices of maxpools. These are the locations of output blocks. + stage_indices = [0] + [i for i, b in enumerate(backbone) if isinstance(b, nn.MaxPool2d)][:-1] + num_stages = len(stage_indices) + + # find the index of the layer from which we won't freeze + torch._assert( + 0 <= trainable_layers <= num_stages, + f"trainable_layers should be in the range [0, {num_stages}]. Instead got {trainable_layers}", + ) + freeze_before = len(backbone) if trainable_layers == 0 else stage_indices[num_stages - trainable_layers] + + for b in backbone[:freeze_before]: + for parameter in b.parameters(): + parameter.requires_grad_(False) + + return SSDFeatureExtractorVGG(backbone, highres) + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", SSD300_VGG16_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", VGG16_Weights.IMAGENET1K_FEATURES), +) +def ssd300_vgg16( + *, + weights: Optional[SSD300_VGG16_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[VGG16_Weights] = VGG16_Weights.IMAGENET1K_FEATURES, + trainable_backbone_layers: Optional[int] = None, + **kwargs: Any, +) -> SSD: + """The SSD300 model is based on the `SSD: Single Shot MultiBox Detector + `_ paper. + + .. betastatus:: detection module + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes, but they will be resized + to a fixed size before passing it to the backbone. + + The behavior of the model changes depending on if it is in training or evaluation mode. + + During training, the model expects both the input tensors and targets (list of dictionary), + containing: + + - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the class label for each ground-truth box + + The model returns a Dict[Tensor] during training, containing the classification and regression + losses. + + During inference, the model requires only the input tensors, and returns the post-processed + predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as + follows, where ``N`` is the number of detections: + + - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with + ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``. + - labels (Int64Tensor[N]): the predicted labels for each detection + - scores (Tensor[N]): the scores for each detection + + Example: + + >>> model = torchvision.models.detection.ssd300_vgg16(weights=SSD300_VGG16_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 300, 300), torch.rand(3, 500, 400)] + >>> predictions = model(x) + + Args: + weights (:class:`~torchvision.models.detection.SSD300_VGG16_Weights`, optional): The pretrained + weights to use. See + :class:`~torchvision.models.detection.SSD300_VGG16_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr + Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + weights_backbone (:class:`~torchvision.models.VGG16_Weights`, optional): The pretrained weights for the + backbone + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block. + Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is + passed (the default) this value is set to 4. + **kwargs: parameters passed to the ``torchvision.models.detection.SSD`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.SSD300_VGG16_Weights + :members: + """ + weights = SSD300_VGG16_Weights.verify(weights) + weights_backbone = VGG16_Weights.verify(weights_backbone) + + if "size" in kwargs: + warnings.warn("The size of the model is already fixed; ignoring the parameter.") + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + trainable_backbone_layers = _validate_trainable_layers( + weights is not None or weights_backbone is not None, trainable_backbone_layers, 5, 4 + ) + + # Use custom backbones more appropriate for SSD + backbone = vgg16(weights=weights_backbone, progress=progress) + backbone = _vgg_extractor(backbone, False, trainable_backbone_layers) + anchor_generator = DefaultBoxGenerator( + [[2], [2, 3], [2, 3], [2, 3], [2], [2]], + scales=[0.07, 0.15, 0.33, 0.51, 0.69, 0.87, 1.05], + steps=[8, 16, 32, 64, 100, 300], + ) + + defaults = { + # Rescale the input in a way compatible to the backbone + "image_mean": [0.48235, 0.45882, 0.40784], + "image_std": [1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0], # undo the 0-1 scaling of toTensor + } + kwargs: Any = {**defaults, **kwargs} + model = SSD(backbone, anchor_generator, (300, 300), num_classes, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/ssdlite.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/ssdlite.py new file mode 100644 index 0000000000000000000000000000000000000000..6b05aae0c0fc38d25388550ce27df35bfc45c3a7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/ssdlite.py @@ -0,0 +1,331 @@ +import warnings +from collections import OrderedDict +from functools import partial +from typing import Any, Callable, Optional, Union + +import torch +from torch import nn, Tensor + +from ...ops.misc import Conv2dNormActivation +from ...transforms._presets import ObjectDetection +from ...utils import _log_api_usage_once +from .. import mobilenet +from .._api import register_model, Weights, WeightsEnum +from .._meta import _COCO_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface +from ..mobilenetv3 import mobilenet_v3_large, MobileNet_V3_Large_Weights +from . import _utils as det_utils +from .anchor_utils import DefaultBoxGenerator +from .backbone_utils import _validate_trainable_layers +from .ssd import SSD, SSDScoringHead + + +__all__ = [ + "SSDLite320_MobileNet_V3_Large_Weights", + "ssdlite320_mobilenet_v3_large", +] + + +# Building blocks of SSDlite as described in section 6.2 of MobileNetV2 paper +def _prediction_block( + in_channels: int, out_channels: int, kernel_size: int, norm_layer: Callable[..., nn.Module] +) -> nn.Sequential: + return nn.Sequential( + # 3x3 depthwise with stride 1 and padding 1 + Conv2dNormActivation( + in_channels, + in_channels, + kernel_size=kernel_size, + groups=in_channels, + norm_layer=norm_layer, + activation_layer=nn.ReLU6, + ), + # 1x1 projetion to output channels + nn.Conv2d(in_channels, out_channels, 1), + ) + + +def _extra_block(in_channels: int, out_channels: int, norm_layer: Callable[..., nn.Module]) -> nn.Sequential: + activation = nn.ReLU6 + intermediate_channels = out_channels // 2 + return nn.Sequential( + # 1x1 projection to half output channels + Conv2dNormActivation( + in_channels, intermediate_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=activation + ), + # 3x3 depthwise with stride 2 and padding 1 + Conv2dNormActivation( + intermediate_channels, + intermediate_channels, + kernel_size=3, + stride=2, + groups=intermediate_channels, + norm_layer=norm_layer, + activation_layer=activation, + ), + # 1x1 projetion to output channels + Conv2dNormActivation( + intermediate_channels, out_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=activation + ), + ) + + +def _normal_init(conv: nn.Module): + for layer in conv.modules(): + if isinstance(layer, nn.Conv2d): + torch.nn.init.normal_(layer.weight, mean=0.0, std=0.03) + if layer.bias is not None: + torch.nn.init.constant_(layer.bias, 0.0) + + +class SSDLiteHead(nn.Module): + def __init__( + self, in_channels: list[int], num_anchors: list[int], num_classes: int, norm_layer: Callable[..., nn.Module] + ): + super().__init__() + self.classification_head = SSDLiteClassificationHead(in_channels, num_anchors, num_classes, norm_layer) + self.regression_head = SSDLiteRegressionHead(in_channels, num_anchors, norm_layer) + + def forward(self, x: list[Tensor]) -> dict[str, Tensor]: + return { + "bbox_regression": self.regression_head(x), + "cls_logits": self.classification_head(x), + } + + +class SSDLiteClassificationHead(SSDScoringHead): + def __init__( + self, in_channels: list[int], num_anchors: list[int], num_classes: int, norm_layer: Callable[..., nn.Module] + ): + cls_logits = nn.ModuleList() + for channels, anchors in zip(in_channels, num_anchors): + cls_logits.append(_prediction_block(channels, num_classes * anchors, 3, norm_layer)) + _normal_init(cls_logits) + super().__init__(cls_logits, num_classes) + + +class SSDLiteRegressionHead(SSDScoringHead): + def __init__(self, in_channels: list[int], num_anchors: list[int], norm_layer: Callable[..., nn.Module]): + bbox_reg = nn.ModuleList() + for channels, anchors in zip(in_channels, num_anchors): + bbox_reg.append(_prediction_block(channels, 4 * anchors, 3, norm_layer)) + _normal_init(bbox_reg) + super().__init__(bbox_reg, 4) + + +class SSDLiteFeatureExtractorMobileNet(nn.Module): + def __init__( + self, + backbone: nn.Module, + c4_pos: int, + norm_layer: Callable[..., nn.Module], + width_mult: float = 1.0, + min_depth: int = 16, + ): + super().__init__() + _log_api_usage_once(self) + + if backbone[c4_pos].use_res_connect: + raise ValueError("backbone[c4_pos].use_res_connect should be False") + + self.features = nn.Sequential( + # As described in section 6.3 of MobileNetV3 paper + nn.Sequential(*backbone[:c4_pos], backbone[c4_pos].block[0]), # from start until C4 expansion layer + nn.Sequential(backbone[c4_pos].block[1:], *backbone[c4_pos + 1 :]), # from C4 depthwise until end + ) + + get_depth = lambda d: max(min_depth, int(d * width_mult)) # noqa: E731 + extra = nn.ModuleList( + [ + _extra_block(backbone[-1].out_channels, get_depth(512), norm_layer), + _extra_block(get_depth(512), get_depth(256), norm_layer), + _extra_block(get_depth(256), get_depth(256), norm_layer), + _extra_block(get_depth(256), get_depth(128), norm_layer), + ] + ) + _normal_init(extra) + + self.extra = extra + + def forward(self, x: Tensor) -> dict[str, Tensor]: + # Get feature maps from backbone and extra. Can't be refactored due to JIT limitations. + output = [] + for block in self.features: + x = block(x) + output.append(x) + + for block in self.extra: + x = block(x) + output.append(x) + + return OrderedDict([(str(i), v) for i, v in enumerate(output)]) + + +def _mobilenet_extractor( + backbone: Union[mobilenet.MobileNetV2, mobilenet.MobileNetV3], + trainable_layers: int, + norm_layer: Callable[..., nn.Module], +): + backbone = backbone.features + # Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks. + # The first and last blocks are always included because they are the C0 (conv1) and Cn. + stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1] + num_stages = len(stage_indices) + + # find the index of the layer from which we won't freeze + if not 0 <= trainable_layers <= num_stages: + raise ValueError("trainable_layers should be in the range [0, {num_stages}], instead got {trainable_layers}") + freeze_before = len(backbone) if trainable_layers == 0 else stage_indices[num_stages - trainable_layers] + + for b in backbone[:freeze_before]: + for parameter in b.parameters(): + parameter.requires_grad_(False) + + return SSDLiteFeatureExtractorMobileNet(backbone, stage_indices[-2], norm_layer) + + +class SSDLite320_MobileNet_V3_Large_Weights(WeightsEnum): + COCO_V1 = Weights( + url="https://download.pytorch.org/models/ssdlite320_mobilenet_v3_large_coco-a79551df.pth", + transforms=ObjectDetection, + meta={ + "num_params": 3440060, + "categories": _COCO_CATEGORIES, + "min_size": (1, 1), + "recipe": "https://github.com/pytorch/vision/tree/main/references/detection#ssdlite320-mobilenetv3-large", + "_metrics": { + "COCO-val2017": { + "box_map": 21.3, + } + }, + "_ops": 0.583, + "_file_size": 13.418, + "_docs": """These weights were produced by following a similar training recipe as on the paper.""", + }, + ) + DEFAULT = COCO_V1 + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", SSDLite320_MobileNet_V3_Large_Weights.COCO_V1), + weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1), +) +def ssdlite320_mobilenet_v3_large( + *, + weights: Optional[SSDLite320_MobileNet_V3_Large_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1, + trainable_backbone_layers: Optional[int] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + **kwargs: Any, +) -> SSD: + """SSDlite model architecture with input size 320x320 and a MobileNetV3 Large backbone, as + described at `Searching for MobileNetV3 `__ and + `MobileNetV2: Inverted Residuals and Linear Bottlenecks `__. + + .. betastatus:: detection module + + See :func:`~torchvision.models.detection.ssd300_vgg16` for more details. + + Example: + + >>> model = torchvision.models.detection.ssdlite320_mobilenet_v3_large(weights=SSDLite320_MobileNet_V3_Large_Weights.DEFAULT) + >>> model.eval() + >>> x = [torch.rand(3, 320, 320), torch.rand(3, 500, 400)] + >>> predictions = model(x) + + Args: + weights (:class:`~torchvision.models.detection.SSDLite320_MobileNet_V3_Large_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.detection.SSDLite320_MobileNet_V3_Large_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model + (including the background). + weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The pretrained + weights for the backbone. + trainable_backbone_layers (int, optional): number of trainable (not frozen) layers + starting from final block. Valid values are between 0 and 6, with 6 meaning all + backbone layers are trainable. If ``None`` is passed (the default) this value is + set to 6. + norm_layer (callable, optional): Module specifying the normalization layer to use. + **kwargs: parameters passed to the ``torchvision.models.detection.ssd.SSD`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.detection.SSDLite320_MobileNet_V3_Large_Weights + :members: + """ + + weights = SSDLite320_MobileNet_V3_Large_Weights.verify(weights) + weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone) + + if "size" in kwargs: + warnings.warn("The size of the model is already fixed; ignoring the parameter.") + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 91 + + trainable_backbone_layers = _validate_trainable_layers( + weights is not None or weights_backbone is not None, trainable_backbone_layers, 6, 6 + ) + + # Enable reduced tail if no pretrained backbone is selected. See Table 6 of MobileNetV3 paper. + reduce_tail = weights_backbone is None + + if norm_layer is None: + norm_layer = partial(nn.BatchNorm2d, eps=0.001, momentum=0.03) + + backbone = mobilenet_v3_large( + weights=weights_backbone, progress=progress, norm_layer=norm_layer, reduced_tail=reduce_tail, **kwargs + ) + if weights_backbone is None: + # Change the default initialization scheme if not pretrained + _normal_init(backbone) + backbone = _mobilenet_extractor( + backbone, + trainable_backbone_layers, + norm_layer, + ) + + size = (320, 320) + anchor_generator = DefaultBoxGenerator([[2, 3] for _ in range(6)], min_ratio=0.2, max_ratio=0.95) + out_channels = det_utils.retrieve_out_channels(backbone, size) + num_anchors = anchor_generator.num_anchors_per_location() + if len(out_channels) != len(anchor_generator.aspect_ratios): + raise ValueError( + f"The length of the output channels from the backbone {len(out_channels)} do not match the length of the anchor generator aspect ratios {len(anchor_generator.aspect_ratios)}" + ) + + defaults = { + "score_thresh": 0.001, + "nms_thresh": 0.55, + "detections_per_img": 300, + "topk_candidates": 300, + # Rescale the input in a way compatible to the backbone: + # The following mean/std rescale the data from [0, 1] to [-1, 1] + "image_mean": [0.5, 0.5, 0.5], + "image_std": [0.5, 0.5, 0.5], + } + kwargs: Any = {**defaults, **kwargs} + model = SSD( + backbone, + anchor_generator, + size, + num_classes, + head=SSDLiteHead(out_channels, num_anchors, num_classes, norm_layer), + **kwargs, + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/detection/transform.py b/.venv/lib/python3.12/site-packages/torchvision/models/detection/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..ac54873dee8b798761db2b00f407d24bdafec33f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/detection/transform.py @@ -0,0 +1,319 @@ +import math +from typing import Any, Optional + +import torch +import torchvision +from torch import nn, Tensor + +from .image_list import ImageList +from .roi_heads import paste_masks_in_image + + +@torch.jit.unused +def _get_shape_onnx(image: Tensor) -> Tensor: + from torch.onnx import operators + + return operators.shape_as_tensor(image)[-2:] + + +@torch.jit.unused +def _fake_cast_onnx(v: Tensor) -> float: + # ONNX requires a tensor but here we fake its type for JIT. + return v + + +def _resize_image_and_masks( + image: Tensor, + self_min_size: int, + self_max_size: int, + target: Optional[dict[str, Tensor]] = None, + fixed_size: Optional[tuple[int, int]] = None, +) -> tuple[Tensor, Optional[dict[str, Tensor]]]: + if torchvision._is_tracing(): + im_shape = _get_shape_onnx(image) + elif torch.jit.is_scripting(): + im_shape = torch.tensor(image.shape[-2:]) + else: + im_shape = image.shape[-2:] + + size: Optional[list[int]] = None + scale_factor: Optional[float] = None + recompute_scale_factor: Optional[bool] = None + if fixed_size is not None: + size = [fixed_size[1], fixed_size[0]] + else: + if torch.jit.is_scripting() or torchvision._is_tracing(): + min_size = torch.min(im_shape).to(dtype=torch.float32) + max_size = torch.max(im_shape).to(dtype=torch.float32) + self_min_size_f = float(self_min_size) + self_max_size_f = float(self_max_size) + scale = torch.min(self_min_size_f / min_size, self_max_size_f / max_size) + + if torchvision._is_tracing(): + scale_factor = _fake_cast_onnx(scale) + else: + scale_factor = scale.item() + + else: + # Do it the normal way + min_size = min(im_shape) + max_size = max(im_shape) + scale_factor = min(self_min_size / min_size, self_max_size / max_size) + + recompute_scale_factor = True + + image = torch.nn.functional.interpolate( + image[None], + size=size, + scale_factor=scale_factor, + mode="bilinear", + recompute_scale_factor=recompute_scale_factor, + align_corners=False, + )[0] + + if target is None: + return image, target + + if "masks" in target: + mask = target["masks"] + mask = torch.nn.functional.interpolate( + mask[:, None].float(), size=size, scale_factor=scale_factor, recompute_scale_factor=recompute_scale_factor + )[:, 0].byte() + target["masks"] = mask + return image, target + + +class GeneralizedRCNNTransform(nn.Module): + """ + Performs input / target transformation before feeding the data to a GeneralizedRCNN + model. + + The transformations it performs are: + - input normalization (mean subtraction and std division) + - input / target resizing to match min_size / max_size + + It returns a ImageList for the inputs, and a List[Dict[Tensor]] for the targets + """ + + def __init__( + self, + min_size: int, + max_size: int, + image_mean: list[float], + image_std: list[float], + size_divisible: int = 32, + fixed_size: Optional[tuple[int, int]] = None, + **kwargs: Any, + ): + super().__init__() + if not isinstance(min_size, (list, tuple)): + min_size = (min_size,) + self.min_size = min_size + self.max_size = max_size + self.image_mean = image_mean + self.image_std = image_std + self.size_divisible = size_divisible + self.fixed_size = fixed_size + self._skip_resize = kwargs.pop("_skip_resize", False) + + def forward( + self, images: list[Tensor], targets: Optional[list[dict[str, Tensor]]] = None + ) -> tuple[ImageList, Optional[list[dict[str, Tensor]]]]: + images = [img for img in images] + if targets is not None: + # make a copy of targets to avoid modifying it in-place + # once torchscript supports dict comprehension + # this can be simplified as follows + # targets = [{k: v for k,v in t.items()} for t in targets] + targets_copy: list[dict[str, Tensor]] = [] + for t in targets: + data: dict[str, Tensor] = {} + for k, v in t.items(): + data[k] = v + targets_copy.append(data) + targets = targets_copy + for i in range(len(images)): + image = images[i] + target_index = targets[i] if targets is not None else None + + if image.dim() != 3: + raise ValueError(f"images is expected to be a list of 3d tensors of shape [C, H, W], got {image.shape}") + image = self.normalize(image) + image, target_index = self.resize(image, target_index) + images[i] = image + if targets is not None and target_index is not None: + targets[i] = target_index + + image_sizes = [img.shape[-2:] for img in images] + images = self.batch_images(images, size_divisible=self.size_divisible) + image_sizes_list: list[tuple[int, int]] = [] + for image_size in image_sizes: + torch._assert( + len(image_size) == 2, + f"Input tensors expected to have in the last two elements H and W, instead got {image_size}", + ) + image_sizes_list.append((image_size[0], image_size[1])) + + image_list = ImageList(images, image_sizes_list) + return image_list, targets + + def normalize(self, image: Tensor) -> Tensor: + if not image.is_floating_point(): + raise TypeError( + f"Expected input images to be of floating type (in range [0, 1]), " + f"but found type {image.dtype} instead" + ) + dtype, device = image.dtype, image.device + mean = torch.as_tensor(self.image_mean, dtype=dtype, device=device) + std = torch.as_tensor(self.image_std, dtype=dtype, device=device) + return (image - mean[:, None, None]) / std[:, None, None] + + def torch_choice(self, k: list[int]) -> int: + """ + Implements `random.choice` via torch ops, so it can be compiled with + TorchScript and we use PyTorch's RNG (not native RNG) + """ + index = int(torch.empty(1).uniform_(0.0, float(len(k))).item()) + return k[index] + + def resize( + self, + image: Tensor, + target: Optional[dict[str, Tensor]] = None, + ) -> tuple[Tensor, Optional[dict[str, Tensor]]]: + h, w = image.shape[-2:] + if self.training: + if self._skip_resize: + return image, target + size = self.torch_choice(self.min_size) + else: + size = self.min_size[-1] + image, target = _resize_image_and_masks(image, size, self.max_size, target, self.fixed_size) + + if target is None: + return image, target + + bbox = target["boxes"] + bbox = resize_boxes(bbox, (h, w), image.shape[-2:]) + target["boxes"] = bbox + + if "keypoints" in target: + keypoints = target["keypoints"] + keypoints = resize_keypoints(keypoints, (h, w), image.shape[-2:]) + target["keypoints"] = keypoints + return image, target + + # _onnx_batch_images() is an implementation of + # batch_images() that is supported by ONNX tracing. + @torch.jit.unused + def _onnx_batch_images(self, images: list[Tensor], size_divisible: int = 32) -> Tensor: + max_size = [] + for i in range(images[0].dim()): + max_size_i = torch.max(torch.stack([img.shape[i] for img in images]).to(torch.float32)).to(torch.int64) + max_size.append(max_size_i) + stride = size_divisible + max_size[1] = (torch.ceil((max_size[1].to(torch.float32)) / stride) * stride).to(torch.int64) + max_size[2] = (torch.ceil((max_size[2].to(torch.float32)) / stride) * stride).to(torch.int64) + max_size = tuple(max_size) + + # work around for + # pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) + # which is not yet supported in onnx + padded_imgs = [] + for img in images: + padding = [(s1 - s2) for s1, s2 in zip(max_size, tuple(img.shape))] + padded_img = torch.nn.functional.pad(img, (0, padding[2], 0, padding[1], 0, padding[0])) + padded_imgs.append(padded_img) + + return torch.stack(padded_imgs) + + def max_by_axis(self, the_list: list[list[int]]) -> list[int]: + maxes = the_list[0] + for sublist in the_list[1:]: + for index, item in enumerate(sublist): + maxes[index] = max(maxes[index], item) + return maxes + + def batch_images(self, images: list[Tensor], size_divisible: int = 32) -> Tensor: + if torchvision._is_tracing(): + # batch_images() does not export well to ONNX + # call _onnx_batch_images() instead + return self._onnx_batch_images(images, size_divisible) + + max_size = self.max_by_axis([list(img.shape) for img in images]) + stride = float(size_divisible) + max_size = list(max_size) + max_size[1] = int(math.ceil(float(max_size[1]) / stride) * stride) + max_size[2] = int(math.ceil(float(max_size[2]) / stride) * stride) + + batch_shape = [len(images)] + max_size + batched_imgs = images[0].new_full(batch_shape, 0) + for i in range(batched_imgs.shape[0]): + img = images[i] + batched_imgs[i, : img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) + + return batched_imgs + + def postprocess( + self, + result: list[dict[str, Tensor]], + image_shapes: list[tuple[int, int]], + original_image_sizes: list[tuple[int, int]], + ) -> list[dict[str, Tensor]]: + if self.training: + return result + for i, (pred, im_s, o_im_s) in enumerate(zip(result, image_shapes, original_image_sizes)): + boxes = pred["boxes"] + boxes = resize_boxes(boxes, im_s, o_im_s) + result[i]["boxes"] = boxes + if "masks" in pred: + masks = pred["masks"] + masks = paste_masks_in_image(masks, boxes, o_im_s) + result[i]["masks"] = masks + if "keypoints" in pred: + keypoints = pred["keypoints"] + keypoints = resize_keypoints(keypoints, im_s, o_im_s) + result[i]["keypoints"] = keypoints + return result + + def __repr__(self) -> str: + format_string = f"{self.__class__.__name__}(" + _indent = "\n " + format_string += f"{_indent}Normalize(mean={self.image_mean}, std={self.image_std})" + format_string += f"{_indent}Resize(min_size={self.min_size}, max_size={self.max_size}, mode='bilinear')" + format_string += "\n)" + return format_string + + +def resize_keypoints(keypoints: Tensor, original_size: list[int], new_size: list[int]) -> Tensor: + ratios = [ + torch.tensor(s, dtype=torch.float32, device=keypoints.device) + / torch.tensor(s_orig, dtype=torch.float32, device=keypoints.device) + for s, s_orig in zip(new_size, original_size) + ] + ratio_h, ratio_w = ratios + resized_data = keypoints.clone() + if torch._C._get_tracing_state(): + resized_data_0 = resized_data[:, :, 0] * ratio_w + resized_data_1 = resized_data[:, :, 1] * ratio_h + resized_data = torch.stack((resized_data_0, resized_data_1, resized_data[:, :, 2]), dim=2) + else: + resized_data[..., 0] *= ratio_w + resized_data[..., 1] *= ratio_h + return resized_data + + +def resize_boxes(boxes: Tensor, original_size: list[int], new_size: list[int]) -> Tensor: + ratios = [ + torch.tensor(s, dtype=torch.float32, device=boxes.device) + / torch.tensor(s_orig, dtype=torch.float32, device=boxes.device) + for s, s_orig in zip(new_size, original_size) + ] + ratio_height, ratio_width = ratios + xmin, ymin, xmax, ymax = boxes.unbind(1) + + xmin = xmin * ratio_width + xmax = xmax * ratio_width + ymin = ymin * ratio_height + ymax = ymax * ratio_height + return torch.stack((xmin, ymin, xmax, ymax), dim=1) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/efficientnet.py b/.venv/lib/python3.12/site-packages/torchvision/models/efficientnet.py new file mode 100644 index 0000000000000000000000000000000000000000..4b755a3e20751631993eedade35ec549a5b917c4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/efficientnet.py @@ -0,0 +1,1132 @@ +import copy +import math +from collections.abc import Sequence +from dataclasses import dataclass +from functools import partial +from typing import Any, Callable, Optional, Union + +import torch +from torch import nn, Tensor +from torchvision.ops import StochasticDepth + +from ..ops.misc import Conv2dNormActivation, SqueezeExcitation +from ..transforms._presets import ImageClassification, InterpolationMode +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _make_divisible, _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "EfficientNet", + "EfficientNet_B0_Weights", + "EfficientNet_B1_Weights", + "EfficientNet_B2_Weights", + "EfficientNet_B3_Weights", + "EfficientNet_B4_Weights", + "EfficientNet_B5_Weights", + "EfficientNet_B6_Weights", + "EfficientNet_B7_Weights", + "EfficientNet_V2_S_Weights", + "EfficientNet_V2_M_Weights", + "EfficientNet_V2_L_Weights", + "efficientnet_b0", + "efficientnet_b1", + "efficientnet_b2", + "efficientnet_b3", + "efficientnet_b4", + "efficientnet_b5", + "efficientnet_b6", + "efficientnet_b7", + "efficientnet_v2_s", + "efficientnet_v2_m", + "efficientnet_v2_l", +] + + +@dataclass +class _MBConvConfig: + expand_ratio: float + kernel: int + stride: int + input_channels: int + out_channels: int + num_layers: int + block: Callable[..., nn.Module] + + @staticmethod + def adjust_channels(channels: int, width_mult: float, min_value: Optional[int] = None) -> int: + return _make_divisible(channels * width_mult, 8, min_value) + + +class MBConvConfig(_MBConvConfig): + # Stores information listed at Table 1 of the EfficientNet paper & Table 4 of the EfficientNetV2 paper + def __init__( + self, + expand_ratio: float, + kernel: int, + stride: int, + input_channels: int, + out_channels: int, + num_layers: int, + width_mult: float = 1.0, + depth_mult: float = 1.0, + block: Optional[Callable[..., nn.Module]] = None, + ) -> None: + input_channels = self.adjust_channels(input_channels, width_mult) + out_channels = self.adjust_channels(out_channels, width_mult) + num_layers = self.adjust_depth(num_layers, depth_mult) + if block is None: + block = MBConv + super().__init__(expand_ratio, kernel, stride, input_channels, out_channels, num_layers, block) + + @staticmethod + def adjust_depth(num_layers: int, depth_mult: float): + return int(math.ceil(num_layers * depth_mult)) + + +class FusedMBConvConfig(_MBConvConfig): + # Stores information listed at Table 4 of the EfficientNetV2 paper + def __init__( + self, + expand_ratio: float, + kernel: int, + stride: int, + input_channels: int, + out_channels: int, + num_layers: int, + block: Optional[Callable[..., nn.Module]] = None, + ) -> None: + if block is None: + block = FusedMBConv + super().__init__(expand_ratio, kernel, stride, input_channels, out_channels, num_layers, block) + + +class MBConv(nn.Module): + def __init__( + self, + cnf: MBConvConfig, + stochastic_depth_prob: float, + norm_layer: Callable[..., nn.Module], + se_layer: Callable[..., nn.Module] = SqueezeExcitation, + ) -> None: + super().__init__() + + if not (1 <= cnf.stride <= 2): + raise ValueError("illegal stride value") + + self.use_res_connect = cnf.stride == 1 and cnf.input_channels == cnf.out_channels + + layers: list[nn.Module] = [] + activation_layer = nn.SiLU + + # expand + expanded_channels = cnf.adjust_channels(cnf.input_channels, cnf.expand_ratio) + if expanded_channels != cnf.input_channels: + layers.append( + Conv2dNormActivation( + cnf.input_channels, + expanded_channels, + kernel_size=1, + norm_layer=norm_layer, + activation_layer=activation_layer, + ) + ) + + # depthwise + layers.append( + Conv2dNormActivation( + expanded_channels, + expanded_channels, + kernel_size=cnf.kernel, + stride=cnf.stride, + groups=expanded_channels, + norm_layer=norm_layer, + activation_layer=activation_layer, + ) + ) + + # squeeze and excitation + squeeze_channels = max(1, cnf.input_channels // 4) + layers.append(se_layer(expanded_channels, squeeze_channels, activation=partial(nn.SiLU, inplace=True))) + + # project + layers.append( + Conv2dNormActivation( + expanded_channels, cnf.out_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=None + ) + ) + + self.block = nn.Sequential(*layers) + self.stochastic_depth = StochasticDepth(stochastic_depth_prob, "row") + self.out_channels = cnf.out_channels + + def forward(self, input: Tensor) -> Tensor: + result = self.block(input) + if self.use_res_connect: + result = self.stochastic_depth(result) + result += input + return result + + +class FusedMBConv(nn.Module): + def __init__( + self, + cnf: FusedMBConvConfig, + stochastic_depth_prob: float, + norm_layer: Callable[..., nn.Module], + ) -> None: + super().__init__() + + if not (1 <= cnf.stride <= 2): + raise ValueError("illegal stride value") + + self.use_res_connect = cnf.stride == 1 and cnf.input_channels == cnf.out_channels + + layers: list[nn.Module] = [] + activation_layer = nn.SiLU + + expanded_channels = cnf.adjust_channels(cnf.input_channels, cnf.expand_ratio) + if expanded_channels != cnf.input_channels: + # fused expand + layers.append( + Conv2dNormActivation( + cnf.input_channels, + expanded_channels, + kernel_size=cnf.kernel, + stride=cnf.stride, + norm_layer=norm_layer, + activation_layer=activation_layer, + ) + ) + + # project + layers.append( + Conv2dNormActivation( + expanded_channels, cnf.out_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=None + ) + ) + else: + layers.append( + Conv2dNormActivation( + cnf.input_channels, + cnf.out_channels, + kernel_size=cnf.kernel, + stride=cnf.stride, + norm_layer=norm_layer, + activation_layer=activation_layer, + ) + ) + + self.block = nn.Sequential(*layers) + self.stochastic_depth = StochasticDepth(stochastic_depth_prob, "row") + self.out_channels = cnf.out_channels + + def forward(self, input: Tensor) -> Tensor: + result = self.block(input) + if self.use_res_connect: + result = self.stochastic_depth(result) + result += input + return result + + +class EfficientNet(nn.Module): + def __init__( + self, + inverted_residual_setting: Sequence[Union[MBConvConfig, FusedMBConvConfig]], + dropout: float, + stochastic_depth_prob: float = 0.2, + num_classes: int = 1000, + norm_layer: Optional[Callable[..., nn.Module]] = None, + last_channel: Optional[int] = None, + ) -> None: + """ + EfficientNet V1 and V2 main class + + Args: + inverted_residual_setting (Sequence[Union[MBConvConfig, FusedMBConvConfig]]): Network structure + dropout (float): The droupout probability + stochastic_depth_prob (float): The stochastic depth probability + num_classes (int): Number of classes + norm_layer (Optional[Callable[..., nn.Module]]): Module specifying the normalization layer to use + last_channel (int): The number of channels on the penultimate layer + """ + super().__init__() + _log_api_usage_once(self) + + if not inverted_residual_setting: + raise ValueError("The inverted_residual_setting should not be empty") + elif not ( + isinstance(inverted_residual_setting, Sequence) + and all([isinstance(s, _MBConvConfig) for s in inverted_residual_setting]) + ): + raise TypeError("The inverted_residual_setting should be List[MBConvConfig]") + + if norm_layer is None: + norm_layer = nn.BatchNorm2d + + layers: list[nn.Module] = [] + + # building first layer + firstconv_output_channels = inverted_residual_setting[0].input_channels + layers.append( + Conv2dNormActivation( + 3, firstconv_output_channels, kernel_size=3, stride=2, norm_layer=norm_layer, activation_layer=nn.SiLU + ) + ) + + # building inverted residual blocks + total_stage_blocks = sum(cnf.num_layers for cnf in inverted_residual_setting) + stage_block_id = 0 + for cnf in inverted_residual_setting: + stage: list[nn.Module] = [] + for _ in range(cnf.num_layers): + # copy to avoid modifications. shallow copy is enough + block_cnf = copy.copy(cnf) + + # overwrite info if not the first conv in the stage + if stage: + block_cnf.input_channels = block_cnf.out_channels + block_cnf.stride = 1 + + # adjust stochastic depth probability based on the depth of the stage block + sd_prob = stochastic_depth_prob * float(stage_block_id) / total_stage_blocks + + stage.append(block_cnf.block(block_cnf, sd_prob, norm_layer)) + stage_block_id += 1 + + layers.append(nn.Sequential(*stage)) + + # building last several layers + lastconv_input_channels = inverted_residual_setting[-1].out_channels + lastconv_output_channels = last_channel if last_channel is not None else 4 * lastconv_input_channels + layers.append( + Conv2dNormActivation( + lastconv_input_channels, + lastconv_output_channels, + kernel_size=1, + norm_layer=norm_layer, + activation_layer=nn.SiLU, + ) + ) + + self.features = nn.Sequential(*layers) + self.avgpool = nn.AdaptiveAvgPool2d(1) + self.classifier = nn.Sequential( + nn.Dropout(p=dropout, inplace=True), + nn.Linear(lastconv_output_channels, num_classes), + ) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out") + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + init_range = 1.0 / math.sqrt(m.out_features) + nn.init.uniform_(m.weight, -init_range, init_range) + nn.init.zeros_(m.bias) + + def _forward_impl(self, x: Tensor) -> Tensor: + x = self.features(x) + + x = self.avgpool(x) + x = torch.flatten(x, 1) + + x = self.classifier(x) + + return x + + def forward(self, x: Tensor) -> Tensor: + return self._forward_impl(x) + + +def _efficientnet( + inverted_residual_setting: Sequence[Union[MBConvConfig, FusedMBConvConfig]], + dropout: float, + last_channel: Optional[int], + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> EfficientNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = EfficientNet(inverted_residual_setting, dropout, last_channel=last_channel, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +def _efficientnet_conf( + arch: str, + **kwargs: Any, +) -> tuple[Sequence[Union[MBConvConfig, FusedMBConvConfig]], Optional[int]]: + inverted_residual_setting: Sequence[Union[MBConvConfig, FusedMBConvConfig]] + if arch.startswith("efficientnet_b"): + bneck_conf = partial(MBConvConfig, width_mult=kwargs.pop("width_mult"), depth_mult=kwargs.pop("depth_mult")) + inverted_residual_setting = [ + bneck_conf(1, 3, 1, 32, 16, 1), + bneck_conf(6, 3, 2, 16, 24, 2), + bneck_conf(6, 5, 2, 24, 40, 2), + bneck_conf(6, 3, 2, 40, 80, 3), + bneck_conf(6, 5, 1, 80, 112, 3), + bneck_conf(6, 5, 2, 112, 192, 4), + bneck_conf(6, 3, 1, 192, 320, 1), + ] + last_channel = None + elif arch.startswith("efficientnet_v2_s"): + inverted_residual_setting = [ + FusedMBConvConfig(1, 3, 1, 24, 24, 2), + FusedMBConvConfig(4, 3, 2, 24, 48, 4), + FusedMBConvConfig(4, 3, 2, 48, 64, 4), + MBConvConfig(4, 3, 2, 64, 128, 6), + MBConvConfig(6, 3, 1, 128, 160, 9), + MBConvConfig(6, 3, 2, 160, 256, 15), + ] + last_channel = 1280 + elif arch.startswith("efficientnet_v2_m"): + inverted_residual_setting = [ + FusedMBConvConfig(1, 3, 1, 24, 24, 3), + FusedMBConvConfig(4, 3, 2, 24, 48, 5), + FusedMBConvConfig(4, 3, 2, 48, 80, 5), + MBConvConfig(4, 3, 2, 80, 160, 7), + MBConvConfig(6, 3, 1, 160, 176, 14), + MBConvConfig(6, 3, 2, 176, 304, 18), + MBConvConfig(6, 3, 1, 304, 512, 5), + ] + last_channel = 1280 + elif arch.startswith("efficientnet_v2_l"): + inverted_residual_setting = [ + FusedMBConvConfig(1, 3, 1, 32, 32, 4), + FusedMBConvConfig(4, 3, 2, 32, 64, 7), + FusedMBConvConfig(4, 3, 2, 64, 96, 7), + MBConvConfig(4, 3, 2, 96, 192, 10), + MBConvConfig(6, 3, 1, 192, 224, 19), + MBConvConfig(6, 3, 2, 224, 384, 25), + MBConvConfig(6, 3, 1, 384, 640, 7), + ] + last_channel = 1280 + else: + raise ValueError(f"Unsupported model type {arch}") + + return inverted_residual_setting, last_channel + + +_COMMON_META: dict[str, Any] = { + "categories": _IMAGENET_CATEGORIES, +} + + +_COMMON_META_V1 = { + **_COMMON_META, + "min_size": (1, 1), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#efficientnet-v1", +} + + +_COMMON_META_V2 = { + **_COMMON_META, + "min_size": (33, 33), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#efficientnet-v2", +} + + +class EfficientNet_B0_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/rwightman/pytorch-image-models/ + url="https://download.pytorch.org/models/efficientnet_b0_rwightman-7f5810bc.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=256, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 5288548, + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.692, + "acc@5": 93.532, + } + }, + "_ops": 0.386, + "_file_size": 20.451, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_B1_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/rwightman/pytorch-image-models/ + url="https://download.pytorch.org/models/efficientnet_b1_rwightman-bac287d4.pth", + transforms=partial( + ImageClassification, crop_size=240, resize_size=256, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 7794184, + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.642, + "acc@5": 94.186, + } + }, + "_ops": 0.687, + "_file_size": 30.134, + "_docs": """These weights are ported from the original paper.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/efficientnet_b1-c27df63c.pth", + transforms=partial( + ImageClassification, crop_size=240, resize_size=255, interpolation=InterpolationMode.BILINEAR + ), + meta={ + **_COMMON_META_V1, + "num_params": 7794184, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-lr-wd-crop-tuning", + "_metrics": { + "ImageNet-1K": { + "acc@1": 79.838, + "acc@5": 94.934, + } + }, + "_ops": 0.687, + "_file_size": 30.136, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class EfficientNet_B2_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/rwightman/pytorch-image-models/ + url="https://download.pytorch.org/models/efficientnet_b2_rwightman-c35c1473.pth", + transforms=partial( + ImageClassification, crop_size=288, resize_size=288, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 9109994, + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.608, + "acc@5": 95.310, + } + }, + "_ops": 1.088, + "_file_size": 35.174, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_B3_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/rwightman/pytorch-image-models/ + url="https://download.pytorch.org/models/efficientnet_b3_rwightman-b3899882.pth", + transforms=partial( + ImageClassification, crop_size=300, resize_size=320, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 12233232, + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.008, + "acc@5": 96.054, + } + }, + "_ops": 1.827, + "_file_size": 47.184, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_B4_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/rwightman/pytorch-image-models/ + url="https://download.pytorch.org/models/efficientnet_b4_rwightman-23ab8bcd.pth", + transforms=partial( + ImageClassification, crop_size=380, resize_size=384, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 19341616, + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.384, + "acc@5": 96.594, + } + }, + "_ops": 4.394, + "_file_size": 74.489, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_B5_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/lukemelas/EfficientNet-PyTorch/ + url="https://download.pytorch.org/models/efficientnet_b5_lukemelas-1a07897c.pth", + transforms=partial( + ImageClassification, crop_size=456, resize_size=456, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 30389784, + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.444, + "acc@5": 96.628, + } + }, + "_ops": 10.266, + "_file_size": 116.864, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_B6_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/lukemelas/EfficientNet-PyTorch/ + url="https://download.pytorch.org/models/efficientnet_b6_lukemelas-24a108a5.pth", + transforms=partial( + ImageClassification, crop_size=528, resize_size=528, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 43040704, + "_metrics": { + "ImageNet-1K": { + "acc@1": 84.008, + "acc@5": 96.916, + } + }, + "_ops": 19.068, + "_file_size": 165.362, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_B7_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/lukemelas/EfficientNet-PyTorch/ + url="https://download.pytorch.org/models/efficientnet_b7_lukemelas-c5b4e57e.pth", + transforms=partial( + ImageClassification, crop_size=600, resize_size=600, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META_V1, + "num_params": 66347960, + "_metrics": { + "ImageNet-1K": { + "acc@1": 84.122, + "acc@5": 96.908, + } + }, + "_ops": 37.746, + "_file_size": 254.675, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_V2_S_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/efficientnet_v2_s-dd5fe13b.pth", + transforms=partial( + ImageClassification, + crop_size=384, + resize_size=384, + interpolation=InterpolationMode.BILINEAR, + ), + meta={ + **_COMMON_META_V2, + "num_params": 21458488, + "_metrics": { + "ImageNet-1K": { + "acc@1": 84.228, + "acc@5": 96.878, + } + }, + "_ops": 8.366, + "_file_size": 82.704, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_V2_M_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/efficientnet_v2_m-dc08266a.pth", + transforms=partial( + ImageClassification, + crop_size=480, + resize_size=480, + interpolation=InterpolationMode.BILINEAR, + ), + meta={ + **_COMMON_META_V2, + "num_params": 54139356, + "_metrics": { + "ImageNet-1K": { + "acc@1": 85.112, + "acc@5": 97.156, + } + }, + "_ops": 24.582, + "_file_size": 208.01, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class EfficientNet_V2_L_Weights(WeightsEnum): + # Weights ported from https://github.com/google/automl/tree/master/efficientnetv2 + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/efficientnet_v2_l-59c71312.pth", + transforms=partial( + ImageClassification, + crop_size=480, + resize_size=480, + interpolation=InterpolationMode.BICUBIC, + mean=(0.5, 0.5, 0.5), + std=(0.5, 0.5, 0.5), + ), + meta={ + **_COMMON_META_V2, + "num_params": 118515272, + "_metrics": { + "ImageNet-1K": { + "acc@1": 85.808, + "acc@5": 97.788, + } + }, + "_ops": 56.08, + "_file_size": 454.573, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B0_Weights.IMAGENET1K_V1)) +def efficientnet_b0( + *, weights: Optional[EfficientNet_B0_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B0 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B0_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B0_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B0_Weights + :members: + """ + weights = EfficientNet_B0_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b0", width_mult=1.0, depth_mult=1.0) + return _efficientnet( + inverted_residual_setting, kwargs.pop("dropout", 0.2), last_channel, weights, progress, **kwargs + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B1_Weights.IMAGENET1K_V1)) +def efficientnet_b1( + *, weights: Optional[EfficientNet_B1_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B1 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B1_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B1_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B1_Weights + :members: + """ + weights = EfficientNet_B1_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b1", width_mult=1.0, depth_mult=1.1) + return _efficientnet( + inverted_residual_setting, kwargs.pop("dropout", 0.2), last_channel, weights, progress, **kwargs + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B2_Weights.IMAGENET1K_V1)) +def efficientnet_b2( + *, weights: Optional[EfficientNet_B2_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B2 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B2_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B2_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B2_Weights + :members: + """ + weights = EfficientNet_B2_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b2", width_mult=1.1, depth_mult=1.2) + return _efficientnet( + inverted_residual_setting, kwargs.pop("dropout", 0.3), last_channel, weights, progress, **kwargs + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B3_Weights.IMAGENET1K_V1)) +def efficientnet_b3( + *, weights: Optional[EfficientNet_B3_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B3 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B3_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B3_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B3_Weights + :members: + """ + weights = EfficientNet_B3_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b3", width_mult=1.2, depth_mult=1.4) + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.3), + last_channel, + weights, + progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B4_Weights.IMAGENET1K_V1)) +def efficientnet_b4( + *, weights: Optional[EfficientNet_B4_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B4 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B4_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B4_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B4_Weights + :members: + """ + weights = EfficientNet_B4_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b4", width_mult=1.4, depth_mult=1.8) + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.4), + last_channel, + weights, + progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B5_Weights.IMAGENET1K_V1)) +def efficientnet_b5( + *, weights: Optional[EfficientNet_B5_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B5 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B5_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B5_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B5_Weights + :members: + """ + weights = EfficientNet_B5_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b5", width_mult=1.6, depth_mult=2.2) + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.4), + last_channel, + weights, + progress, + norm_layer=partial(nn.BatchNorm2d, eps=0.001, momentum=0.01), + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B6_Weights.IMAGENET1K_V1)) +def efficientnet_b6( + *, weights: Optional[EfficientNet_B6_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B6 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B6_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B6_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B6_Weights + :members: + """ + weights = EfficientNet_B6_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b6", width_mult=1.8, depth_mult=2.6) + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.5), + last_channel, + weights, + progress, + norm_layer=partial(nn.BatchNorm2d, eps=0.001, momentum=0.01), + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_B7_Weights.IMAGENET1K_V1)) +def efficientnet_b7( + *, weights: Optional[EfficientNet_B7_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """EfficientNet B7 model architecture from the `EfficientNet: Rethinking Model Scaling for Convolutional + Neural Networks `_ paper. + + Args: + weights (:class:`~torchvision.models.EfficientNet_B7_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_B7_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_B7_Weights + :members: + """ + weights = EfficientNet_B7_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_b7", width_mult=2.0, depth_mult=3.1) + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.5), + last_channel, + weights, + progress, + norm_layer=partial(nn.BatchNorm2d, eps=0.001, momentum=0.01), + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_V2_S_Weights.IMAGENET1K_V1)) +def efficientnet_v2_s( + *, weights: Optional[EfficientNet_V2_S_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """ + Constructs an EfficientNetV2-S architecture from + `EfficientNetV2: Smaller Models and Faster Training `_. + + Args: + weights (:class:`~torchvision.models.EfficientNet_V2_S_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_V2_S_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_V2_S_Weights + :members: + """ + weights = EfficientNet_V2_S_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_v2_s") + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.2), + last_channel, + weights, + progress, + norm_layer=partial(nn.BatchNorm2d, eps=1e-03), + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_V2_M_Weights.IMAGENET1K_V1)) +def efficientnet_v2_m( + *, weights: Optional[EfficientNet_V2_M_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """ + Constructs an EfficientNetV2-M architecture from + `EfficientNetV2: Smaller Models and Faster Training `_. + + Args: + weights (:class:`~torchvision.models.EfficientNet_V2_M_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_V2_M_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_V2_M_Weights + :members: + """ + weights = EfficientNet_V2_M_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_v2_m") + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.3), + last_channel, + weights, + progress, + norm_layer=partial(nn.BatchNorm2d, eps=1e-03), + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", EfficientNet_V2_L_Weights.IMAGENET1K_V1)) +def efficientnet_v2_l( + *, weights: Optional[EfficientNet_V2_L_Weights] = None, progress: bool = True, **kwargs: Any +) -> EfficientNet: + """ + Constructs an EfficientNetV2-L architecture from + `EfficientNetV2: Smaller Models and Faster Training `_. + + Args: + weights (:class:`~torchvision.models.EfficientNet_V2_L_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.EfficientNet_V2_L_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.efficientnet.EfficientNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.EfficientNet_V2_L_Weights + :members: + """ + weights = EfficientNet_V2_L_Weights.verify(weights) + + inverted_residual_setting, last_channel = _efficientnet_conf("efficientnet_v2_l") + return _efficientnet( + inverted_residual_setting, + kwargs.pop("dropout", 0.4), + last_channel, + weights, + progress, + norm_layer=partial(nn.BatchNorm2d, eps=1e-03), + **kwargs, + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/feature_extraction.py b/.venv/lib/python3.12/site-packages/torchvision/models/feature_extraction.py new file mode 100644 index 0000000000000000000000000000000000000000..320b1936d6f8897d6f324b6c4938dbe289fd466e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/feature_extraction.py @@ -0,0 +1,607 @@ +import copy +import inspect +import math +import re +import warnings +from collections import OrderedDict +from copy import deepcopy +from itertools import chain +from typing import Any, Callable, Optional, Union + +import torch +import torchvision +from torch import fx, nn +from torch.fx.graph_module import _CodeOnlyModule, _copy_attr, _USER_PRESERVED_ATTRIBUTES_KEY + + +__all__ = ["create_feature_extractor", "get_graph_node_names"] + + +class LeafModuleAwareTracer(fx.Tracer): + """ + An fx.Tracer that allows the user to specify a set of leaf modules, i.e. + modules that are not to be traced through. The resulting graph ends up + having single nodes referencing calls to the leaf modules' forward methods. + """ + + def __init__(self, *args, **kwargs): + self.leaf_modules = {} + if "leaf_modules" in kwargs: + leaf_modules = kwargs.pop("leaf_modules") + self.leaf_modules = leaf_modules + super().__init__(*args, **kwargs) + + def is_leaf_module(self, m: nn.Module, module_qualname: str) -> bool: + if isinstance(m, tuple(self.leaf_modules)): + return True + return super().is_leaf_module(m, module_qualname) + + +class NodePathTracer(LeafModuleAwareTracer): + """ + NodePathTracer is an FX tracer that, for each operation, also records the + name of the Node from which the operation originated. A node name here is + a `.` separated path walking the hierarchy from top level module down to + leaf operation or leaf module. The name of the top level module is not + included as part of the node name. For example, if we trace a module whose + forward method applies a ReLU module, the name for that node will simply + be 'relu'. + + Some notes on the specifics: + - Nodes are recorded to `self.node_to_qualname` which is a dictionary + mapping a given Node object to its node name. + - Nodes are recorded in the order which they are executed during + tracing. + - When a duplicate node name is encountered, a suffix of the form + _{int} is added. The counter starts from 1. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # Track the qualified name of the Node being traced + self.current_module_qualname = "" + # A map from FX Node to the qualified name\# + # NOTE: This is loosely like the "qualified name" mentioned in the + # torch.fx docs https://pytorch.org/docs/stable/fx.html but adapted + # for the purposes of the torchvision feature extractor + self.node_to_qualname = OrderedDict() + + def call_module(self, m: torch.nn.Module, forward: Callable, args, kwargs): + """ + Override of `fx.Tracer.call_module` + This override: + 1) Stores away the qualified name of the caller for restoration later + 2) Adds the qualified name of the caller to + `current_module_qualname` for retrieval by `create_proxy` + 3) Once a leaf module is reached, calls `create_proxy` + 4) Restores the caller's qualified name into current_module_qualname + """ + old_qualname = self.current_module_qualname + try: + module_qualname = self.path_of_module(m) + self.current_module_qualname = module_qualname + if not self.is_leaf_module(m, module_qualname): + out = forward(*args, **kwargs) + return out + return self.create_proxy("call_module", module_qualname, args, kwargs) + finally: + self.current_module_qualname = old_qualname + + def create_proxy( + self, kind: str, target: fx.node.Target, args, kwargs, name=None, type_expr=None, *_ + ) -> fx.proxy.Proxy: + """ + Override of `Tracer.create_proxy`. This override intercepts the recording + of every operation and stores away the current traced module's qualified + name in `node_to_qualname` + """ + proxy = super().create_proxy(kind, target, args, kwargs, name, type_expr) + self.node_to_qualname[proxy.node] = self._get_node_qualname(self.current_module_qualname, proxy.node) + return proxy + + def _get_node_qualname(self, module_qualname: str, node: fx.node.Node) -> str: + node_qualname = module_qualname + + if node.op != "call_module": + # In this case module_qualname from torch.fx doesn't go all the + # way to the leaf function/op, so we need to append it + if len(node_qualname) > 0: + # Only append '.' if we are deeper than the top level module + node_qualname += "." + node_qualname += str(node) + + # Now we need to add an _{index} postfix on any repeated node names + # For modules we do this from scratch + # But for anything else, torch.fx already has a globally scoped + # _{index} postfix. But we want it locally (relative to direct parent) + # scoped. So first we need to undo the torch.fx postfix + if re.match(r".+_[0-9]+$", node_qualname) is not None: + node_qualname = node_qualname.rsplit("_", 1)[0] + + # ... and now we add on our own postfix + for existing_qualname in reversed(self.node_to_qualname.values()): + # Check to see if existing_qualname is of the form + # {node_qualname} or {node_qualname}_{int} + if re.match(rf"{node_qualname}(_[0-9]+)?$", existing_qualname) is not None: + postfix = existing_qualname.replace(node_qualname, "") + if len(postfix): + # existing_qualname is of the form {node_qualname}_{int} + next_index = int(postfix[1:]) + 1 + else: + # existing_qualname is of the form {node_qualname} + next_index = 1 + node_qualname += f"_{next_index}" + break + + return node_qualname + + +def _is_subseq(x, y): + """Check if y is a subsequence of x + https://stackoverflow.com/a/24017747/4391249 + """ + iter_x = iter(x) + return all(any(x_item == y_item for x_item in iter_x) for y_item in y) + + +def _warn_graph_differences(train_tracer: NodePathTracer, eval_tracer: NodePathTracer): + """ + Utility function for warning the user if there are differences between + the train graph nodes and the eval graph nodes. + """ + train_nodes = list(train_tracer.node_to_qualname.values()) + eval_nodes = list(eval_tracer.node_to_qualname.values()) + + if len(train_nodes) == len(eval_nodes) and all(t == e for t, e in zip(train_nodes, eval_nodes)): + return + + suggestion_msg = ( + "When choosing nodes for feature extraction, you may need to specify " + "output nodes for train and eval mode separately." + ) + + if _is_subseq(train_nodes, eval_nodes): + msg = ( + "NOTE: The nodes obtained by tracing the model in eval mode " + "are a subsequence of those obtained in train mode. " + ) + elif _is_subseq(eval_nodes, train_nodes): + msg = ( + "NOTE: The nodes obtained by tracing the model in train mode " + "are a subsequence of those obtained in eval mode. " + ) + else: + msg = "The nodes obtained by tracing the model in train mode are different to those obtained in eval mode. " + warnings.warn(msg + suggestion_msg) + + +def _get_leaf_modules_for_ops() -> list[type]: + members = inspect.getmembers(torchvision.ops) + result = [] + for _, obj in members: + if inspect.isclass(obj) and issubclass(obj, torch.nn.Module): + result.append(obj) + return result + + +def _set_default_tracer_kwargs(original_tr_kwargs: Optional[dict[str, Any]]) -> dict[str, Any]: + default_autowrap_modules = (math, torchvision.ops) + default_leaf_modules = _get_leaf_modules_for_ops() + result_tracer_kwargs = {} if original_tr_kwargs is None else original_tr_kwargs + result_tracer_kwargs["autowrap_modules"] = ( + tuple(set(result_tracer_kwargs["autowrap_modules"] + default_autowrap_modules)) + if "autowrap_modules" in result_tracer_kwargs + else default_autowrap_modules + ) + result_tracer_kwargs["leaf_modules"] = ( + list(set(result_tracer_kwargs["leaf_modules"] + default_leaf_modules)) + if "leaf_modules" in result_tracer_kwargs + else default_leaf_modules + ) + return result_tracer_kwargs + + +def get_graph_node_names( + model: nn.Module, + tracer_kwargs: Optional[dict[str, Any]] = None, + suppress_diff_warning: bool = False, + concrete_args: Optional[dict[str, Any]] = None, +) -> tuple[list[str], list[str]]: + """ + Dev utility to return node names in order of execution. See note on node + names under :func:`create_feature_extractor`. Useful for seeing which node + names are available for feature extraction. There are two reasons that + node names can't easily be read directly from the code for a model: + + 1. Not all submodules are traced through. Modules from ``torch.nn`` all + fall within this category. + 2. Nodes representing the repeated application of the same operation + or leaf module get a ``_{counter}`` postfix. + + The model is traced twice: once in train mode, and once in eval mode. Both + sets of node names are returned. + + For more details on the node naming conventions used here, please see the + :ref:`relevant subheading ` in the + `documentation `_. + + Args: + model (nn.Module): model for which we'd like to print node names + tracer_kwargs (dict, optional): a dictionary of keyword arguments for + ``NodePathTracer`` (they are eventually passed onto + `torch.fx.Tracer `_). + By default, it will be set to wrap and make leaf nodes all torchvision ops: + {"autowrap_modules": (math, torchvision.ops,),"leaf_modules": _get_leaf_modules_for_ops(),} + WARNING: In case the user provides tracer_kwargs, above default arguments will be appended to the user + provided dictionary. + suppress_diff_warning (bool, optional): whether to suppress a warning + when there are discrepancies between the train and eval version of + the graph. Defaults to False. + concrete_args (Optional[Dict[str, any]]): Concrete arguments that should + not be treated as Proxies. According to the `Pytorch docs + `_, + this parameter's API may not be guaranteed. + + Returns: + tuple(list, list): a list of node names from tracing the model in + train mode, and another from tracing the model in eval mode. + + Examples:: + + >>> model = torchvision.models.resnet18() + >>> train_nodes, eval_nodes = get_graph_node_names(model) + """ + tracer_kwargs = _set_default_tracer_kwargs(tracer_kwargs) + is_training = model.training + train_tracer = NodePathTracer(**tracer_kwargs) + train_tracer.trace(model.train(), concrete_args=concrete_args) + eval_tracer = NodePathTracer(**tracer_kwargs) + eval_tracer.trace(model.eval(), concrete_args=concrete_args) + train_nodes = list(train_tracer.node_to_qualname.values()) + eval_nodes = list(eval_tracer.node_to_qualname.values()) + if not suppress_diff_warning: + _warn_graph_differences(train_tracer, eval_tracer) + # Restore training state + model.train(is_training) + return train_nodes, eval_nodes + + +class DualGraphModule(fx.GraphModule): + """ + A derivative of `fx.GraphModule`. Differs in the following ways: + - Requires a train and eval version of the underlying graph + - Copies submodules according to the nodes of both train and eval graphs. + - Calling train(mode) switches between train graph and eval graph. + """ + + def __init__( + self, root: torch.nn.Module, train_graph: fx.Graph, eval_graph: fx.Graph, class_name: str = "GraphModule" + ): + """ + Args: + root (nn.Module): module from which the copied module hierarchy is + built + train_graph (fx.Graph): the graph that should be used in train mode + eval_graph (fx.Graph): the graph that should be used in eval mode + """ + super(fx.GraphModule, self).__init__() + + self.__class__.__name__ = class_name + + self.train_graph = train_graph + self.eval_graph = eval_graph + + # Copy all get_attr and call_module ops (indicated by BOTH train and + # eval graphs) + for node in chain(iter(train_graph.nodes), iter(eval_graph.nodes)): + if node.op in ["get_attr", "call_module"]: + if not isinstance(node.target, str): + raise TypeError(f"node.target should be of type str instead of {type(node.target)}") + _copy_attr(root, self, node.target) + + # train mode by default + self.train() + self.graph = train_graph + + # (borrowed from fx.GraphModule): + # Store the Tracer class responsible for creating a Graph separately as part of the + # GraphModule state, except when the Tracer is defined in a local namespace. + # Locally defined Tracers are not pickleable. This is needed because torch.package will + # serialize a GraphModule without retaining the Graph, and needs to use the correct Tracer + # to re-create the Graph during deserialization. + if self.eval_graph._tracer_cls != self.train_graph._tracer_cls: + raise TypeError( + f"Train mode and eval mode should use the same tracer class. Instead got {self.eval_graph._tracer_cls} for eval vs {self.train_graph._tracer_cls} for train" + ) + self._tracer_cls = None + if self.graph._tracer_cls and "" not in self.graph._tracer_cls.__qualname__: + self._tracer_cls = self.graph._tracer_cls + + def train(self, mode=True): + """ + Swap out the graph depending on the selected training mode. + NOTE this should be safe when calling model.eval() because that just + calls this with mode == False. + """ + # NOTE: Only set self.graph if the current graph is not the desired + # one. This saves us from recompiling the graph where not necessary. + if mode and not self.training: + self.graph = self.train_graph + elif not mode and self.training: + self.graph = self.eval_graph + return super().train(mode=mode) + + def _deepcopy_init(self): + # See __deepcopy__ below + return DualGraphModule.__init__ + + def __deepcopy__(self, memo): + # Same as the base class' __deepcopy__ from pytorch, with minor + # modification to account for train_graph and eval_graph + # https://github.com/pytorch/pytorch/blob/f684dbd0026f98f8fa291cab74dbc4d61ba30580/torch/fx/graph_module.py#L875 + # + # This is using a bunch of private stuff from torch, so if that breaks, + # we'll likely have to remove this, along with the associated + # non-regression test. + res = type(self).__new__(type(self)) + memo[id(self)] = res + fake_mod = _CodeOnlyModule(copy.deepcopy(self.__dict__, memo)) + self._deepcopy_init()(res, fake_mod, fake_mod.__dict__["train_graph"], fake_mod.__dict__["eval_graph"]) + + extra_preserved_attrs = [ + "_state_dict_hooks", + "_load_state_dict_pre_hooks", + "_load_state_dict_post_hooks", + "_replace_hook", + "_create_node_hooks", + "_erase_node_hooks", + ] + for attr in extra_preserved_attrs: + if attr in self.__dict__: + setattr(res, attr, copy.deepcopy(self.__dict__[attr], memo)) + res.meta = copy.deepcopy(getattr(self, "meta", {}), memo) + if _USER_PRESERVED_ATTRIBUTES_KEY in res.meta: + for attr_name, attr in res.meta[_USER_PRESERVED_ATTRIBUTES_KEY].items(): + setattr(res, attr_name, attr) + return res + + +def create_feature_extractor( + model: nn.Module, + return_nodes: Optional[Union[list[str], dict[str, str]]] = None, + train_return_nodes: Optional[Union[list[str], dict[str, str]]] = None, + eval_return_nodes: Optional[Union[list[str], dict[str, str]]] = None, + tracer_kwargs: Optional[dict[str, Any]] = None, + suppress_diff_warning: bool = False, + concrete_args: Optional[dict[str, Any]] = None, +) -> fx.GraphModule: + """ + Creates a new graph module that returns intermediate nodes from a given + model as dictionary with user specified keys as strings, and the requested + outputs as values. This is achieved by re-writing the computation graph of + the model via FX to return the desired nodes as outputs. All unused nodes + are removed, together with their corresponding parameters. + + Desired output nodes must be specified as a ``.`` separated + path walking the module hierarchy from top level module down to leaf + operation or leaf module. For more details on the node naming conventions + used here, please see the :ref:`relevant subheading ` + in the `documentation `_. + + Not all models will be FX traceable, although with some massaging they can + be made to cooperate. Here's a (not exhaustive) list of tips: + + - If you don't need to trace through a particular, problematic + sub-module, turn it into a "leaf module" by passing a list of + ``leaf_modules`` as one of the ``tracer_kwargs`` (see example below). + It will not be traced through, but rather, the resulting graph will + hold a reference to that module's forward method. + - Likewise, you may turn functions into leaf functions by passing a + list of ``autowrap_functions`` as one of the ``tracer_kwargs`` (see + example below). + - Some inbuilt Python functions can be problematic. For instance, + ``int`` will raise an error during tracing. You may wrap them in your + own function and then pass that in ``autowrap_functions`` as one of + the ``tracer_kwargs``. + + For further information on FX see the + `torch.fx documentation `_. + + Args: + model (nn.Module): model on which we will extract the features + return_nodes (list or dict, optional): either a ``List`` or a ``Dict`` + containing the names (or partial names - see note above) + of the nodes for which the activations will be returned. If it is + a ``Dict``, the keys are the node names, and the values + are the user-specified keys for the graph module's returned + dictionary. If it is a ``List``, it is treated as a ``Dict`` mapping + node specification strings directly to output names. In the case + that ``train_return_nodes`` and ``eval_return_nodes`` are specified, + this should not be specified. + train_return_nodes (list or dict, optional): similar to + ``return_nodes``. This can be used if the return nodes + for train mode are different than those from eval mode. + If this is specified, ``eval_return_nodes`` must also be specified, + and ``return_nodes`` should not be specified. + eval_return_nodes (list or dict, optional): similar to + ``return_nodes``. This can be used if the return nodes + for train mode are different than those from eval mode. + If this is specified, ``train_return_nodes`` must also be specified, + and `return_nodes` should not be specified. + tracer_kwargs (dict, optional): a dictionary of keyword arguments for + ``NodePathTracer`` (which passes them onto it's parent class + `torch.fx.Tracer `_). + By default, it will be set to wrap and make leaf nodes all torchvision ops: + {"autowrap_modules": (math, torchvision.ops,),"leaf_modules": _get_leaf_modules_for_ops(),} + WARNING: In case the user provides tracer_kwargs, above default arguments will be appended to the user + provided dictionary. + suppress_diff_warning (bool, optional): whether to suppress a warning + when there are discrepancies between the train and eval version of + the graph. Defaults to False. + concrete_args (Optional[Dict[str, any]]): Concrete arguments that should + not be treated as Proxies. According to the `Pytorch docs + `_, + this parameter's API may not be guaranteed. + + Examples:: + + >>> # Feature extraction with resnet + >>> model = torchvision.models.resnet18() + >>> # extract layer1 and layer3, giving as names `feat1` and feat2` + >>> model = create_feature_extractor( + >>> model, {'layer1': 'feat1', 'layer3': 'feat2'}) + >>> out = model(torch.rand(1, 3, 224, 224)) + >>> print([(k, v.shape) for k, v in out.items()]) + >>> [('feat1', torch.Size([1, 64, 56, 56])), + >>> ('feat2', torch.Size([1, 256, 14, 14]))] + + >>> # Specifying leaf modules and leaf functions + >>> def leaf_function(x): + >>> # This would raise a TypeError if traced through + >>> return int(x) + >>> + >>> class LeafModule(torch.nn.Module): + >>> def forward(self, x): + >>> # This would raise a TypeError if traced through + >>> int(x.shape[0]) + >>> return torch.nn.functional.relu(x + 4) + >>> + >>> class MyModule(torch.nn.Module): + >>> def __init__(self): + >>> super().__init__() + >>> self.conv = torch.nn.Conv2d(3, 1, 3) + >>> self.leaf_module = LeafModule() + >>> + >>> def forward(self, x): + >>> leaf_function(x.shape[0]) + >>> x = self.conv(x) + >>> return self.leaf_module(x) + >>> + >>> model = create_feature_extractor( + >>> MyModule(), return_nodes=['leaf_module'], + >>> tracer_kwargs={'leaf_modules': [LeafModule], + >>> 'autowrap_functions': [leaf_function]}) + + """ + tracer_kwargs = _set_default_tracer_kwargs(tracer_kwargs) + is_training = model.training + + if all(arg is None for arg in [return_nodes, train_return_nodes, eval_return_nodes]): + + raise ValueError( + "Either `return_nodes` or `train_return_nodes` and `eval_return_nodes` together, should be specified" + ) + + if (train_return_nodes is None) ^ (eval_return_nodes is None): + raise ValueError( + "If any of `train_return_nodes` and `eval_return_nodes` are specified, then both should be specified" + ) + + if not ((return_nodes is None) ^ (train_return_nodes is None)): + raise ValueError("If `train_return_nodes` and `eval_return_nodes` are specified, then both should be specified") + + # Put *_return_nodes into Dict[str, str] format + def to_strdict(n) -> dict[str, str]: + if isinstance(n, list): + return {str(i): str(i) for i in n} + return {str(k): str(v) for k, v in n.items()} + + if train_return_nodes is None: + return_nodes = to_strdict(return_nodes) + train_return_nodes = deepcopy(return_nodes) + eval_return_nodes = deepcopy(return_nodes) + else: + train_return_nodes = to_strdict(train_return_nodes) + eval_return_nodes = to_strdict(eval_return_nodes) + + # Repeat the tracing and graph rewriting for train and eval mode + tracers = {} + graphs = {} + mode_return_nodes: dict[str, dict[str, str]] = {"train": train_return_nodes, "eval": eval_return_nodes} + for mode in ["train", "eval"]: + if mode == "train": + model.train() + elif mode == "eval": + model.eval() + + # Instantiate our NodePathTracer and use that to trace the model + tracer = NodePathTracer(**tracer_kwargs) + graph = tracer.trace(model, concrete_args=concrete_args) + + name = model.__class__.__name__ if isinstance(model, nn.Module) else model.__name__ + graph_module = fx.GraphModule(tracer.root, graph, name) + + available_nodes = list(tracer.node_to_qualname.values()) + # FIXME We don't know if we should expect this to happen + if len(set(available_nodes)) != len(available_nodes): + raise ValueError( + "There are duplicate nodes! Please raise an issue https://github.com/pytorch/vision/issues" + ) + # Check that all outputs in return_nodes are present in the model + for query in mode_return_nodes[mode].keys(): + # To check if a query is available we need to check that at least + # one of the available names starts with it up to a . + if not any([re.match(rf"^{query}(\.|$)", n) is not None for n in available_nodes]): + raise ValueError( + f"node: '{query}' is not present in model. Hint: use " + "`get_graph_node_names` to make sure the " + "`return_nodes` you specified are present. It may even " + "be that you need to specify `train_return_nodes` and " + "`eval_return_nodes` separately." + ) + + # Remove existing output nodes (train mode) + orig_output_nodes = [] + for n in reversed(graph_module.graph.nodes): + if n.op == "output": + orig_output_nodes.append(n) + if not orig_output_nodes: + raise ValueError("No output nodes found in graph_module.graph.nodes") + + for n in orig_output_nodes: + graph_module.graph.erase_node(n) + + # Find nodes corresponding to return_nodes and make them into output_nodes + nodes = [n for n in graph_module.graph.nodes] + output_nodes = OrderedDict() + for n in reversed(nodes): + module_qualname = tracer.node_to_qualname.get(n) + if module_qualname is None: + # NOTE - Know cases where this happens: + # - Node representing creation of a tensor constant - probably + # not interesting as a return node + # - When packing outputs into a named tuple like in InceptionV3 + continue + for query in mode_return_nodes[mode]: + depth = query.count(".") + if ".".join(module_qualname.split(".")[: depth + 1]) == query: + output_nodes[mode_return_nodes[mode][query]] = n + mode_return_nodes[mode].pop(query) + break + output_nodes = OrderedDict(reversed(list(output_nodes.items()))) + + # And add them in the end of the graph + with graph_module.graph.inserting_after(nodes[-1]): + graph_module.graph.output(output_nodes) + + # Remove unused modules / parameters + graph_module.graph.eliminate_dead_code() + graph_module.recompile() + + # Keep track of the tracer and graph, so we can choose the main one + tracers[mode] = tracer + graphs[mode] = graph + + # Warn user if there are any discrepancies between the graphs of the + # train and eval modes + if not suppress_diff_warning: + _warn_graph_differences(tracers["train"], tracers["eval"]) + + # Build the final graph module + graph_module = DualGraphModule(model, graphs["train"], graphs["eval"], class_name=name) + + # Restore original training mode + model.train(is_training) + graph_module.train(is_training) + + return graph_module diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/googlenet.py b/.venv/lib/python3.12/site-packages/torchvision/models/googlenet.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb29764951531b2fbfa91ea91e367ba240f05b0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/googlenet.py @@ -0,0 +1,345 @@ +import warnings +from collections import namedtuple +from functools import partial +from typing import Any, Callable, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = ["GoogLeNet", "GoogLeNetOutputs", "_GoogLeNetOutputs", "GoogLeNet_Weights", "googlenet"] + + +GoogLeNetOutputs = namedtuple("GoogLeNetOutputs", ["logits", "aux_logits2", "aux_logits1"]) +GoogLeNetOutputs.__annotations__ = {"logits": Tensor, "aux_logits2": Optional[Tensor], "aux_logits1": Optional[Tensor]} + +# Script annotations failed with _GoogleNetOutputs = namedtuple ... +# _GoogLeNetOutputs set here for backwards compat +_GoogLeNetOutputs = GoogLeNetOutputs + + +class GoogLeNet(nn.Module): + __constants__ = ["aux_logits", "transform_input"] + + def __init__( + self, + num_classes: int = 1000, + aux_logits: bool = True, + transform_input: bool = False, + init_weights: Optional[bool] = None, + blocks: Optional[list[Callable[..., nn.Module]]] = None, + dropout: float = 0.2, + dropout_aux: float = 0.7, + ) -> None: + super().__init__() + _log_api_usage_once(self) + if blocks is None: + blocks = [BasicConv2d, Inception, InceptionAux] + if init_weights is None: + warnings.warn( + "The default weight initialization of GoogleNet will be changed in future releases of " + "torchvision. If you wish to keep the old behavior (which leads to long initialization times" + " due to scipy/scipy#11299), please set init_weights=True.", + FutureWarning, + ) + init_weights = True + if len(blocks) != 3: + raise ValueError(f"blocks length should be 3 instead of {len(blocks)}") + conv_block = blocks[0] + inception_block = blocks[1] + inception_aux_block = blocks[2] + + self.aux_logits = aux_logits + self.transform_input = transform_input + + self.conv1 = conv_block(3, 64, kernel_size=7, stride=2, padding=3) + self.maxpool1 = nn.MaxPool2d(3, stride=2, ceil_mode=True) + self.conv2 = conv_block(64, 64, kernel_size=1) + self.conv3 = conv_block(64, 192, kernel_size=3, padding=1) + self.maxpool2 = nn.MaxPool2d(3, stride=2, ceil_mode=True) + + self.inception3a = inception_block(192, 64, 96, 128, 16, 32, 32) + self.inception3b = inception_block(256, 128, 128, 192, 32, 96, 64) + self.maxpool3 = nn.MaxPool2d(3, stride=2, ceil_mode=True) + + self.inception4a = inception_block(480, 192, 96, 208, 16, 48, 64) + self.inception4b = inception_block(512, 160, 112, 224, 24, 64, 64) + self.inception4c = inception_block(512, 128, 128, 256, 24, 64, 64) + self.inception4d = inception_block(512, 112, 144, 288, 32, 64, 64) + self.inception4e = inception_block(528, 256, 160, 320, 32, 128, 128) + self.maxpool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.inception5a = inception_block(832, 256, 160, 320, 32, 128, 128) + self.inception5b = inception_block(832, 384, 192, 384, 48, 128, 128) + + if aux_logits: + self.aux1 = inception_aux_block(512, num_classes, dropout=dropout_aux) + self.aux2 = inception_aux_block(528, num_classes, dropout=dropout_aux) + else: + self.aux1 = None # type: ignore[assignment] + self.aux2 = None # type: ignore[assignment] + + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) + self.dropout = nn.Dropout(p=dropout) + self.fc = nn.Linear(1024, num_classes) + + if init_weights: + for m in self.modules(): + if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear): + torch.nn.init.trunc_normal_(m.weight, mean=0.0, std=0.01, a=-2, b=2) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + def _transform_input(self, x: Tensor) -> Tensor: + if self.transform_input: + x_ch0 = torch.unsqueeze(x[:, 0], 1) * (0.229 / 0.5) + (0.485 - 0.5) / 0.5 + x_ch1 = torch.unsqueeze(x[:, 1], 1) * (0.224 / 0.5) + (0.456 - 0.5) / 0.5 + x_ch2 = torch.unsqueeze(x[:, 2], 1) * (0.225 / 0.5) + (0.406 - 0.5) / 0.5 + x = torch.cat((x_ch0, x_ch1, x_ch2), 1) + return x + + def _forward(self, x: Tensor) -> tuple[Tensor, Optional[Tensor], Optional[Tensor]]: + # N x 3 x 224 x 224 + x = self.conv1(x) + # N x 64 x 112 x 112 + x = self.maxpool1(x) + # N x 64 x 56 x 56 + x = self.conv2(x) + # N x 64 x 56 x 56 + x = self.conv3(x) + # N x 192 x 56 x 56 + x = self.maxpool2(x) + + # N x 192 x 28 x 28 + x = self.inception3a(x) + # N x 256 x 28 x 28 + x = self.inception3b(x) + # N x 480 x 28 x 28 + x = self.maxpool3(x) + # N x 480 x 14 x 14 + x = self.inception4a(x) + # N x 512 x 14 x 14 + aux1: Optional[Tensor] = None + if self.aux1 is not None: + if self.training: + aux1 = self.aux1(x) + + x = self.inception4b(x) + # N x 512 x 14 x 14 + x = self.inception4c(x) + # N x 512 x 14 x 14 + x = self.inception4d(x) + # N x 528 x 14 x 14 + aux2: Optional[Tensor] = None + if self.aux2 is not None: + if self.training: + aux2 = self.aux2(x) + + x = self.inception4e(x) + # N x 832 x 14 x 14 + x = self.maxpool4(x) + # N x 832 x 7 x 7 + x = self.inception5a(x) + # N x 832 x 7 x 7 + x = self.inception5b(x) + # N x 1024 x 7 x 7 + + x = self.avgpool(x) + # N x 1024 x 1 x 1 + x = torch.flatten(x, 1) + # N x 1024 + x = self.dropout(x) + x = self.fc(x) + # N x 1000 (num_classes) + return x, aux2, aux1 + + @torch.jit.unused + def eager_outputs(self, x: Tensor, aux2: Tensor, aux1: Optional[Tensor]) -> GoogLeNetOutputs: + if self.training and self.aux_logits: + return _GoogLeNetOutputs(x, aux2, aux1) + else: + return x # type: ignore[return-value] + + def forward(self, x: Tensor) -> GoogLeNetOutputs: + x = self._transform_input(x) + x, aux2, aux1 = self._forward(x) + aux_defined = self.training and self.aux_logits + if torch.jit.is_scripting(): + if not aux_defined: + warnings.warn("Scripted GoogleNet always returns GoogleNetOutputs Tuple") + return GoogLeNetOutputs(x, aux2, aux1) + else: + return self.eager_outputs(x, aux2, aux1) + + +class Inception(nn.Module): + def __init__( + self, + in_channels: int, + ch1x1: int, + ch3x3red: int, + ch3x3: int, + ch5x5red: int, + ch5x5: int, + pool_proj: int, + conv_block: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.branch1 = conv_block(in_channels, ch1x1, kernel_size=1) + + self.branch2 = nn.Sequential( + conv_block(in_channels, ch3x3red, kernel_size=1), conv_block(ch3x3red, ch3x3, kernel_size=3, padding=1) + ) + + self.branch3 = nn.Sequential( + conv_block(in_channels, ch5x5red, kernel_size=1), + # Here, kernel_size=3 instead of kernel_size=5 is a known bug. + # Please see https://github.com/pytorch/vision/issues/906 for details. + conv_block(ch5x5red, ch5x5, kernel_size=3, padding=1), + ) + + self.branch4 = nn.Sequential( + nn.MaxPool2d(kernel_size=3, stride=1, padding=1, ceil_mode=True), + conv_block(in_channels, pool_proj, kernel_size=1), + ) + + def _forward(self, x: Tensor) -> list[Tensor]: + branch1 = self.branch1(x) + branch2 = self.branch2(x) + branch3 = self.branch3(x) + branch4 = self.branch4(x) + + outputs = [branch1, branch2, branch3, branch4] + return outputs + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return torch.cat(outputs, 1) + + +class InceptionAux(nn.Module): + def __init__( + self, + in_channels: int, + num_classes: int, + conv_block: Optional[Callable[..., nn.Module]] = None, + dropout: float = 0.7, + ) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.conv = conv_block(in_channels, 128, kernel_size=1) + + self.fc1 = nn.Linear(2048, 1024) + self.fc2 = nn.Linear(1024, num_classes) + self.dropout = nn.Dropout(p=dropout) + + def forward(self, x: Tensor) -> Tensor: + # aux1: N x 512 x 14 x 14, aux2: N x 528 x 14 x 14 + x = F.adaptive_avg_pool2d(x, (4, 4)) + # aux1: N x 512 x 4 x 4, aux2: N x 528 x 4 x 4 + x = self.conv(x) + # N x 128 x 4 x 4 + x = torch.flatten(x, 1) + # N x 2048 + x = F.relu(self.fc1(x), inplace=True) + # N x 1024 + x = self.dropout(x) + # N x 1024 + x = self.fc2(x) + # N x 1000 (num_classes) + + return x + + +class BasicConv2d(nn.Module): + def __init__(self, in_channels: int, out_channels: int, **kwargs: Any) -> None: + super().__init__() + self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs) + self.bn = nn.BatchNorm2d(out_channels, eps=0.001) + + def forward(self, x: Tensor) -> Tensor: + x = self.conv(x) + x = self.bn(x) + return F.relu(x, inplace=True) + + +class GoogLeNet_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/googlenet-1378be20.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + "num_params": 6624904, + "min_size": (15, 15), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#googlenet", + "_metrics": { + "ImageNet-1K": { + "acc@1": 69.778, + "acc@5": 89.530, + } + }, + "_ops": 1.498, + "_file_size": 49.731, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", GoogLeNet_Weights.IMAGENET1K_V1)) +def googlenet(*, weights: Optional[GoogLeNet_Weights] = None, progress: bool = True, **kwargs: Any) -> GoogLeNet: + """GoogLeNet (Inception v1) model architecture from + `Going Deeper with Convolutions `_. + + Args: + weights (:class:`~torchvision.models.GoogLeNet_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.GoogLeNet_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.GoogLeNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.GoogLeNet_Weights + :members: + """ + weights = GoogLeNet_Weights.verify(weights) + + original_aux_logits = kwargs.get("aux_logits", False) + if weights is not None: + if "transform_input" not in kwargs: + _ovewrite_named_param(kwargs, "transform_input", True) + _ovewrite_named_param(kwargs, "aux_logits", True) + _ovewrite_named_param(kwargs, "init_weights", False) + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = GoogLeNet(**kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if not original_aux_logits: + model.aux_logits = False + model.aux1 = None # type: ignore[assignment] + model.aux2 = None # type: ignore[assignment] + else: + warnings.warn( + "auxiliary heads in the pretrained googlenet model are NOT pretrained, so make sure to train them" + ) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/inception.py b/.venv/lib/python3.12/site-packages/torchvision/models/inception.py new file mode 100644 index 0000000000000000000000000000000000000000..7c36ec2a0ad721c0ccfc588fe389eb9c7e810fb5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/inception.py @@ -0,0 +1,478 @@ +import warnings +from collections import namedtuple +from functools import partial +from typing import Any, Callable, Optional + +import torch +import torch.nn.functional as F +from torch import nn, Tensor + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = ["Inception3", "InceptionOutputs", "_InceptionOutputs", "Inception_V3_Weights", "inception_v3"] + + +InceptionOutputs = namedtuple("InceptionOutputs", ["logits", "aux_logits"]) +InceptionOutputs.__annotations__ = {"logits": Tensor, "aux_logits": Optional[Tensor]} + +# Script annotations failed with _GoogleNetOutputs = namedtuple ... +# _InceptionOutputs set here for backwards compat +_InceptionOutputs = InceptionOutputs + + +class Inception3(nn.Module): + def __init__( + self, + num_classes: int = 1000, + aux_logits: bool = True, + transform_input: bool = False, + inception_blocks: Optional[list[Callable[..., nn.Module]]] = None, + init_weights: Optional[bool] = None, + dropout: float = 0.5, + ) -> None: + super().__init__() + _log_api_usage_once(self) + if inception_blocks is None: + inception_blocks = [BasicConv2d, InceptionA, InceptionB, InceptionC, InceptionD, InceptionE, InceptionAux] + if init_weights is None: + warnings.warn( + "The default weight initialization of inception_v3 will be changed in future releases of " + "torchvision. If you wish to keep the old behavior (which leads to long initialization times" + " due to scipy/scipy#11299), please set init_weights=True.", + FutureWarning, + ) + init_weights = True + if len(inception_blocks) != 7: + raise ValueError(f"length of inception_blocks should be 7 instead of {len(inception_blocks)}") + conv_block = inception_blocks[0] + inception_a = inception_blocks[1] + inception_b = inception_blocks[2] + inception_c = inception_blocks[3] + inception_d = inception_blocks[4] + inception_e = inception_blocks[5] + inception_aux = inception_blocks[6] + + self.aux_logits = aux_logits + self.transform_input = transform_input + self.Conv2d_1a_3x3 = conv_block(3, 32, kernel_size=3, stride=2) + self.Conv2d_2a_3x3 = conv_block(32, 32, kernel_size=3) + self.Conv2d_2b_3x3 = conv_block(32, 64, kernel_size=3, padding=1) + self.maxpool1 = nn.MaxPool2d(kernel_size=3, stride=2) + self.Conv2d_3b_1x1 = conv_block(64, 80, kernel_size=1) + self.Conv2d_4a_3x3 = conv_block(80, 192, kernel_size=3) + self.maxpool2 = nn.MaxPool2d(kernel_size=3, stride=2) + self.Mixed_5b = inception_a(192, pool_features=32) + self.Mixed_5c = inception_a(256, pool_features=64) + self.Mixed_5d = inception_a(288, pool_features=64) + self.Mixed_6a = inception_b(288) + self.Mixed_6b = inception_c(768, channels_7x7=128) + self.Mixed_6c = inception_c(768, channels_7x7=160) + self.Mixed_6d = inception_c(768, channels_7x7=160) + self.Mixed_6e = inception_c(768, channels_7x7=192) + self.AuxLogits: Optional[nn.Module] = None + if aux_logits: + self.AuxLogits = inception_aux(768, num_classes) + self.Mixed_7a = inception_d(768) + self.Mixed_7b = inception_e(1280) + self.Mixed_7c = inception_e(2048) + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) + self.dropout = nn.Dropout(p=dropout) + self.fc = nn.Linear(2048, num_classes) + if init_weights: + for m in self.modules(): + if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear): + stddev = float(m.stddev) if hasattr(m, "stddev") else 0.1 # type: ignore + torch.nn.init.trunc_normal_(m.weight, mean=0.0, std=stddev, a=-2, b=2) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + def _transform_input(self, x: Tensor) -> Tensor: + if self.transform_input: + x_ch0 = torch.unsqueeze(x[:, 0], 1) * (0.229 / 0.5) + (0.485 - 0.5) / 0.5 + x_ch1 = torch.unsqueeze(x[:, 1], 1) * (0.224 / 0.5) + (0.456 - 0.5) / 0.5 + x_ch2 = torch.unsqueeze(x[:, 2], 1) * (0.225 / 0.5) + (0.406 - 0.5) / 0.5 + x = torch.cat((x_ch0, x_ch1, x_ch2), 1) + return x + + def _forward(self, x: Tensor) -> tuple[Tensor, Optional[Tensor]]: + # N x 3 x 299 x 299 + x = self.Conv2d_1a_3x3(x) + # N x 32 x 149 x 149 + x = self.Conv2d_2a_3x3(x) + # N x 32 x 147 x 147 + x = self.Conv2d_2b_3x3(x) + # N x 64 x 147 x 147 + x = self.maxpool1(x) + # N x 64 x 73 x 73 + x = self.Conv2d_3b_1x1(x) + # N x 80 x 73 x 73 + x = self.Conv2d_4a_3x3(x) + # N x 192 x 71 x 71 + x = self.maxpool2(x) + # N x 192 x 35 x 35 + x = self.Mixed_5b(x) + # N x 256 x 35 x 35 + x = self.Mixed_5c(x) + # N x 288 x 35 x 35 + x = self.Mixed_5d(x) + # N x 288 x 35 x 35 + x = self.Mixed_6a(x) + # N x 768 x 17 x 17 + x = self.Mixed_6b(x) + # N x 768 x 17 x 17 + x = self.Mixed_6c(x) + # N x 768 x 17 x 17 + x = self.Mixed_6d(x) + # N x 768 x 17 x 17 + x = self.Mixed_6e(x) + # N x 768 x 17 x 17 + aux: Optional[Tensor] = None + if self.AuxLogits is not None: + if self.training: + aux = self.AuxLogits(x) + # N x 768 x 17 x 17 + x = self.Mixed_7a(x) + # N x 1280 x 8 x 8 + x = self.Mixed_7b(x) + # N x 2048 x 8 x 8 + x = self.Mixed_7c(x) + # N x 2048 x 8 x 8 + # Adaptive average pooling + x = self.avgpool(x) + # N x 2048 x 1 x 1 + x = self.dropout(x) + # N x 2048 x 1 x 1 + x = torch.flatten(x, 1) + # N x 2048 + x = self.fc(x) + # N x 1000 (num_classes) + return x, aux + + @torch.jit.unused + def eager_outputs(self, x: Tensor, aux: Optional[Tensor]) -> InceptionOutputs: + if self.training and self.aux_logits: + return InceptionOutputs(x, aux) + else: + return x # type: ignore[return-value] + + def forward(self, x: Tensor) -> InceptionOutputs: + x = self._transform_input(x) + x, aux = self._forward(x) + aux_defined = self.training and self.aux_logits + if torch.jit.is_scripting(): + if not aux_defined: + warnings.warn("Scripted Inception3 always returns Inception3 Tuple") + return InceptionOutputs(x, aux) + else: + return self.eager_outputs(x, aux) + + +class InceptionA(nn.Module): + def __init__( + self, in_channels: int, pool_features: int, conv_block: Optional[Callable[..., nn.Module]] = None + ) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.branch1x1 = conv_block(in_channels, 64, kernel_size=1) + + self.branch5x5_1 = conv_block(in_channels, 48, kernel_size=1) + self.branch5x5_2 = conv_block(48, 64, kernel_size=5, padding=2) + + self.branch3x3dbl_1 = conv_block(in_channels, 64, kernel_size=1) + self.branch3x3dbl_2 = conv_block(64, 96, kernel_size=3, padding=1) + self.branch3x3dbl_3 = conv_block(96, 96, kernel_size=3, padding=1) + + self.branch_pool = conv_block(in_channels, pool_features, kernel_size=1) + + def _forward(self, x: Tensor) -> list[Tensor]: + branch1x1 = self.branch1x1(x) + + branch5x5 = self.branch5x5_1(x) + branch5x5 = self.branch5x5_2(branch5x5) + + branch3x3dbl = self.branch3x3dbl_1(x) + branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) + branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl) + + branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) + branch_pool = self.branch_pool(branch_pool) + + outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool] + return outputs + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return torch.cat(outputs, 1) + + +class InceptionB(nn.Module): + def __init__(self, in_channels: int, conv_block: Optional[Callable[..., nn.Module]] = None) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.branch3x3 = conv_block(in_channels, 384, kernel_size=3, stride=2) + + self.branch3x3dbl_1 = conv_block(in_channels, 64, kernel_size=1) + self.branch3x3dbl_2 = conv_block(64, 96, kernel_size=3, padding=1) + self.branch3x3dbl_3 = conv_block(96, 96, kernel_size=3, stride=2) + + def _forward(self, x: Tensor) -> list[Tensor]: + branch3x3 = self.branch3x3(x) + + branch3x3dbl = self.branch3x3dbl_1(x) + branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) + branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl) + + branch_pool = F.max_pool2d(x, kernel_size=3, stride=2) + + outputs = [branch3x3, branch3x3dbl, branch_pool] + return outputs + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return torch.cat(outputs, 1) + + +class InceptionC(nn.Module): + def __init__( + self, in_channels: int, channels_7x7: int, conv_block: Optional[Callable[..., nn.Module]] = None + ) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.branch1x1 = conv_block(in_channels, 192, kernel_size=1) + + c7 = channels_7x7 + self.branch7x7_1 = conv_block(in_channels, c7, kernel_size=1) + self.branch7x7_2 = conv_block(c7, c7, kernel_size=(1, 7), padding=(0, 3)) + self.branch7x7_3 = conv_block(c7, 192, kernel_size=(7, 1), padding=(3, 0)) + + self.branch7x7dbl_1 = conv_block(in_channels, c7, kernel_size=1) + self.branch7x7dbl_2 = conv_block(c7, c7, kernel_size=(7, 1), padding=(3, 0)) + self.branch7x7dbl_3 = conv_block(c7, c7, kernel_size=(1, 7), padding=(0, 3)) + self.branch7x7dbl_4 = conv_block(c7, c7, kernel_size=(7, 1), padding=(3, 0)) + self.branch7x7dbl_5 = conv_block(c7, 192, kernel_size=(1, 7), padding=(0, 3)) + + self.branch_pool = conv_block(in_channels, 192, kernel_size=1) + + def _forward(self, x: Tensor) -> list[Tensor]: + branch1x1 = self.branch1x1(x) + + branch7x7 = self.branch7x7_1(x) + branch7x7 = self.branch7x7_2(branch7x7) + branch7x7 = self.branch7x7_3(branch7x7) + + branch7x7dbl = self.branch7x7dbl_1(x) + branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl) + branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl) + branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl) + branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl) + + branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) + branch_pool = self.branch_pool(branch_pool) + + outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool] + return outputs + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return torch.cat(outputs, 1) + + +class InceptionD(nn.Module): + def __init__(self, in_channels: int, conv_block: Optional[Callable[..., nn.Module]] = None) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.branch3x3_1 = conv_block(in_channels, 192, kernel_size=1) + self.branch3x3_2 = conv_block(192, 320, kernel_size=3, stride=2) + + self.branch7x7x3_1 = conv_block(in_channels, 192, kernel_size=1) + self.branch7x7x3_2 = conv_block(192, 192, kernel_size=(1, 7), padding=(0, 3)) + self.branch7x7x3_3 = conv_block(192, 192, kernel_size=(7, 1), padding=(3, 0)) + self.branch7x7x3_4 = conv_block(192, 192, kernel_size=3, stride=2) + + def _forward(self, x: Tensor) -> list[Tensor]: + branch3x3 = self.branch3x3_1(x) + branch3x3 = self.branch3x3_2(branch3x3) + + branch7x7x3 = self.branch7x7x3_1(x) + branch7x7x3 = self.branch7x7x3_2(branch7x7x3) + branch7x7x3 = self.branch7x7x3_3(branch7x7x3) + branch7x7x3 = self.branch7x7x3_4(branch7x7x3) + + branch_pool = F.max_pool2d(x, kernel_size=3, stride=2) + outputs = [branch3x3, branch7x7x3, branch_pool] + return outputs + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return torch.cat(outputs, 1) + + +class InceptionE(nn.Module): + def __init__(self, in_channels: int, conv_block: Optional[Callable[..., nn.Module]] = None) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.branch1x1 = conv_block(in_channels, 320, kernel_size=1) + + self.branch3x3_1 = conv_block(in_channels, 384, kernel_size=1) + self.branch3x3_2a = conv_block(384, 384, kernel_size=(1, 3), padding=(0, 1)) + self.branch3x3_2b = conv_block(384, 384, kernel_size=(3, 1), padding=(1, 0)) + + self.branch3x3dbl_1 = conv_block(in_channels, 448, kernel_size=1) + self.branch3x3dbl_2 = conv_block(448, 384, kernel_size=3, padding=1) + self.branch3x3dbl_3a = conv_block(384, 384, kernel_size=(1, 3), padding=(0, 1)) + self.branch3x3dbl_3b = conv_block(384, 384, kernel_size=(3, 1), padding=(1, 0)) + + self.branch_pool = conv_block(in_channels, 192, kernel_size=1) + + def _forward(self, x: Tensor) -> list[Tensor]: + branch1x1 = self.branch1x1(x) + + branch3x3 = self.branch3x3_1(x) + branch3x3 = [ + self.branch3x3_2a(branch3x3), + self.branch3x3_2b(branch3x3), + ] + branch3x3 = torch.cat(branch3x3, 1) + + branch3x3dbl = self.branch3x3dbl_1(x) + branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) + branch3x3dbl = [ + self.branch3x3dbl_3a(branch3x3dbl), + self.branch3x3dbl_3b(branch3x3dbl), + ] + branch3x3dbl = torch.cat(branch3x3dbl, 1) + + branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) + branch_pool = self.branch_pool(branch_pool) + + outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool] + return outputs + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return torch.cat(outputs, 1) + + +class InceptionAux(nn.Module): + def __init__( + self, in_channels: int, num_classes: int, conv_block: Optional[Callable[..., nn.Module]] = None + ) -> None: + super().__init__() + if conv_block is None: + conv_block = BasicConv2d + self.conv0 = conv_block(in_channels, 128, kernel_size=1) + self.conv1 = conv_block(128, 768, kernel_size=5) + self.conv1.stddev = 0.01 # type: ignore[assignment] + self.fc = nn.Linear(768, num_classes) + self.fc.stddev = 0.001 # type: ignore[assignment] + + def forward(self, x: Tensor) -> Tensor: + # N x 768 x 17 x 17 + x = F.avg_pool2d(x, kernel_size=5, stride=3) + # N x 768 x 5 x 5 + x = self.conv0(x) + # N x 128 x 5 x 5 + x = self.conv1(x) + # N x 768 x 1 x 1 + # Adaptive average pooling + x = F.adaptive_avg_pool2d(x, (1, 1)) + # N x 768 x 1 x 1 + x = torch.flatten(x, 1) + # N x 768 + x = self.fc(x) + # N x 1000 + return x + + +class BasicConv2d(nn.Module): + def __init__(self, in_channels: int, out_channels: int, **kwargs: Any) -> None: + super().__init__() + self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs) + self.bn = nn.BatchNorm2d(out_channels, eps=0.001) + + def forward(self, x: Tensor) -> Tensor: + x = self.conv(x) + x = self.bn(x) + return F.relu(x, inplace=True) + + +class Inception_V3_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/inception_v3_google-0cc3c7bd.pth", + transforms=partial(ImageClassification, crop_size=299, resize_size=342), + meta={ + "num_params": 27161264, + "min_size": (75, 75), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#inception-v3", + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.294, + "acc@5": 93.450, + } + }, + "_ops": 5.713, + "_file_size": 103.903, + "_docs": """These weights are ported from the original paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Inception_V3_Weights.IMAGENET1K_V1)) +def inception_v3(*, weights: Optional[Inception_V3_Weights] = None, progress: bool = True, **kwargs: Any) -> Inception3: + """ + Inception v3 model architecture from + `Rethinking the Inception Architecture for Computer Vision `_. + + .. note:: + **Important**: In contrast to the other models the inception_v3 expects tensors with a size of + N x 3 x 299 x 299, so ensure your images are sized accordingly. + + Args: + weights (:class:`~torchvision.models.Inception_V3_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.Inception_V3_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.Inception3`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.Inception_V3_Weights + :members: + """ + weights = Inception_V3_Weights.verify(weights) + + original_aux_logits = kwargs.get("aux_logits", True) + if weights is not None: + if "transform_input" not in kwargs: + _ovewrite_named_param(kwargs, "transform_input", True) + _ovewrite_named_param(kwargs, "aux_logits", True) + _ovewrite_named_param(kwargs, "init_weights", False) + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = Inception3(**kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if not original_aux_logits: + model.aux_logits = False + model.AuxLogits = None + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/maxvit.py b/.venv/lib/python3.12/site-packages/torchvision/models/maxvit.py new file mode 100644 index 0000000000000000000000000000000000000000..53cc53e5ed94019e56e97bfa74d5c32312dfe389 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/maxvit.py @@ -0,0 +1,834 @@ +import math +from collections import OrderedDict +from collections.abc import Sequence +from functools import partial +from typing import Any, Callable, Optional + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn, Tensor +from torchvision.models._api import register_model, Weights, WeightsEnum +from torchvision.models._meta import _IMAGENET_CATEGORIES +from torchvision.models._utils import _ovewrite_named_param, handle_legacy_interface +from torchvision.ops.misc import Conv2dNormActivation, SqueezeExcitation +from torchvision.ops.stochastic_depth import StochasticDepth +from torchvision.transforms._presets import ImageClassification, InterpolationMode +from torchvision.utils import _log_api_usage_once + +__all__ = [ + "MaxVit", + "MaxVit_T_Weights", + "maxvit_t", +] + + +def _get_conv_output_shape(input_size: tuple[int, int], kernel_size: int, stride: int, padding: int) -> tuple[int, int]: + return ( + (input_size[0] - kernel_size + 2 * padding) // stride + 1, + (input_size[1] - kernel_size + 2 * padding) // stride + 1, + ) + + +def _make_block_input_shapes(input_size: tuple[int, int], n_blocks: int) -> list[tuple[int, int]]: + """Util function to check that the input size is correct for a MaxVit configuration.""" + shapes = [] + block_input_shape = _get_conv_output_shape(input_size, 3, 2, 1) + for _ in range(n_blocks): + block_input_shape = _get_conv_output_shape(block_input_shape, 3, 2, 1) + shapes.append(block_input_shape) + return shapes + + +def _get_relative_position_index(height: int, width: int) -> torch.Tensor: + coords = torch.stack(torch.meshgrid([torch.arange(height), torch.arange(width)], indexing="ij")) + coords_flat = torch.flatten(coords, 1) + relative_coords = coords_flat[:, :, None] - coords_flat[:, None, :] + relative_coords = relative_coords.permute(1, 2, 0).contiguous() + relative_coords[:, :, 0] += height - 1 + relative_coords[:, :, 1] += width - 1 + relative_coords[:, :, 0] *= 2 * width - 1 + return relative_coords.sum(-1) + + +class MBConv(nn.Module): + """MBConv: Mobile Inverted Residual Bottleneck. + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + expansion_ratio (float): Expansion ratio in the bottleneck. + squeeze_ratio (float): Squeeze ratio in the SE Layer. + stride (int): Stride of the depthwise convolution. + activation_layer (Callable[..., nn.Module]): Activation function. + norm_layer (Callable[..., nn.Module]): Normalization function. + p_stochastic_dropout (float): Probability of stochastic depth. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + expansion_ratio: float, + squeeze_ratio: float, + stride: int, + activation_layer: Callable[..., nn.Module], + norm_layer: Callable[..., nn.Module], + p_stochastic_dropout: float = 0.0, + ) -> None: + super().__init__() + + proj: Sequence[nn.Module] + self.proj: nn.Module + + should_proj = stride != 1 or in_channels != out_channels + if should_proj: + proj = [nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, bias=True)] + if stride == 2: + proj = [nn.AvgPool2d(kernel_size=3, stride=stride, padding=1)] + proj # type: ignore + self.proj = nn.Sequential(*proj) + else: + self.proj = nn.Identity() # type: ignore + + mid_channels = int(out_channels * expansion_ratio) + sqz_channels = int(out_channels * squeeze_ratio) + + if p_stochastic_dropout: + self.stochastic_depth = StochasticDepth(p_stochastic_dropout, mode="row") # type: ignore + else: + self.stochastic_depth = nn.Identity() # type: ignore + + _layers = OrderedDict() + _layers["pre_norm"] = norm_layer(in_channels) + _layers["conv_a"] = Conv2dNormActivation( + in_channels, + mid_channels, + kernel_size=1, + stride=1, + padding=0, + activation_layer=activation_layer, + norm_layer=norm_layer, + inplace=None, + ) + _layers["conv_b"] = Conv2dNormActivation( + mid_channels, + mid_channels, + kernel_size=3, + stride=stride, + padding=1, + activation_layer=activation_layer, + norm_layer=norm_layer, + groups=mid_channels, + inplace=None, + ) + _layers["squeeze_excitation"] = SqueezeExcitation(mid_channels, sqz_channels, activation=nn.SiLU) + _layers["conv_c"] = nn.Conv2d(in_channels=mid_channels, out_channels=out_channels, kernel_size=1, bias=True) + + self.layers = nn.Sequential(_layers) + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Input tensor with expected layout of [B, C, H, W]. + Returns: + Tensor: Output tensor with expected layout of [B, C, H / stride, W / stride]. + """ + res = self.proj(x) + x = self.stochastic_depth(self.layers(x)) + return res + x + + +class RelativePositionalMultiHeadAttention(nn.Module): + """Relative Positional Multi-Head Attention. + + Args: + feat_dim (int): Number of input features. + head_dim (int): Number of features per head. + max_seq_len (int): Maximum sequence length. + """ + + def __init__( + self, + feat_dim: int, + head_dim: int, + max_seq_len: int, + ) -> None: + super().__init__() + + if feat_dim % head_dim != 0: + raise ValueError(f"feat_dim: {feat_dim} must be divisible by head_dim: {head_dim}") + + self.n_heads = feat_dim // head_dim + self.head_dim = head_dim + self.size = int(math.sqrt(max_seq_len)) + self.max_seq_len = max_seq_len + + self.to_qkv = nn.Linear(feat_dim, self.n_heads * self.head_dim * 3) + self.scale_factor = feat_dim**-0.5 + + self.merge = nn.Linear(self.head_dim * self.n_heads, feat_dim) + self.relative_position_bias_table = nn.parameter.Parameter( + torch.empty(((2 * self.size - 1) * (2 * self.size - 1), self.n_heads), dtype=torch.float32), + ) + + self.register_buffer("relative_position_index", _get_relative_position_index(self.size, self.size)) + # initialize with truncated normal the bias + torch.nn.init.trunc_normal_(self.relative_position_bias_table, std=0.02) + + def get_relative_positional_bias(self) -> torch.Tensor: + bias_index = self.relative_position_index.view(-1) # type: ignore + relative_bias = self.relative_position_bias_table[bias_index].view(self.max_seq_len, self.max_seq_len, -1) # type: ignore + relative_bias = relative_bias.permute(2, 0, 1).contiguous() + return relative_bias.unsqueeze(0) + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Input tensor with expected layout of [B, G, P, D]. + Returns: + Tensor: Output tensor with expected layout of [B, G, P, D]. + """ + B, G, P, D = x.shape + H, DH = self.n_heads, self.head_dim + + qkv = self.to_qkv(x) + q, k, v = torch.chunk(qkv, 3, dim=-1) + + q = q.reshape(B, G, P, H, DH).permute(0, 1, 3, 2, 4) + k = k.reshape(B, G, P, H, DH).permute(0, 1, 3, 2, 4) + v = v.reshape(B, G, P, H, DH).permute(0, 1, 3, 2, 4) + + k = k * self.scale_factor + dot_prod = torch.einsum("B G H I D, B G H J D -> B G H I J", q, k) + pos_bias = self.get_relative_positional_bias() + + dot_prod = F.softmax(dot_prod + pos_bias, dim=-1) + + out = torch.einsum("B G H I J, B G H J D -> B G H I D", dot_prod, v) + out = out.permute(0, 1, 3, 2, 4).reshape(B, G, P, D) + + out = self.merge(out) + return out + + +class SwapAxes(nn.Module): + """Permute the axes of a tensor.""" + + def __init__(self, a: int, b: int) -> None: + super().__init__() + self.a = a + self.b = b + + def forward(self, x: torch.Tensor) -> torch.Tensor: + res = torch.swapaxes(x, self.a, self.b) + return res + + +class WindowPartition(nn.Module): + """ + Partition the input tensor into non-overlapping windows. + """ + + def __init__(self) -> None: + super().__init__() + + def forward(self, x: Tensor, p: int) -> Tensor: + """ + Args: + x (Tensor): Input tensor with expected layout of [B, C, H, W]. + p (int): Number of partitions. + Returns: + Tensor: Output tensor with expected layout of [B, H/P, W/P, P*P, C]. + """ + B, C, H, W = x.shape + P = p + # chunk up H and W dimensions + x = x.reshape(B, C, H // P, P, W // P, P) + x = x.permute(0, 2, 4, 3, 5, 1) + # colapse P * P dimension + x = x.reshape(B, (H // P) * (W // P), P * P, C) + return x + + +class WindowDepartition(nn.Module): + """ + Departition the input tensor of non-overlapping windows into a feature volume of layout [B, C, H, W]. + """ + + def __init__(self) -> None: + super().__init__() + + def forward(self, x: Tensor, p: int, h_partitions: int, w_partitions: int) -> Tensor: + """ + Args: + x (Tensor): Input tensor with expected layout of [B, (H/P * W/P), P*P, C]. + p (int): Number of partitions. + h_partitions (int): Number of vertical partitions. + w_partitions (int): Number of horizontal partitions. + Returns: + Tensor: Output tensor with expected layout of [B, C, H, W]. + """ + B, G, PP, C = x.shape + P = p + HP, WP = h_partitions, w_partitions + # split P * P dimension into 2 P tile dimensionsa + x = x.reshape(B, HP, WP, P, P, C) + # permute into B, C, HP, P, WP, P + x = x.permute(0, 5, 1, 3, 2, 4) + # reshape into B, C, H, W + x = x.reshape(B, C, HP * P, WP * P) + return x + + +class PartitionAttentionLayer(nn.Module): + """ + Layer for partitioning the input tensor into non-overlapping windows and applying attention to each window. + + Args: + in_channels (int): Number of input channels. + head_dim (int): Dimension of each attention head. + partition_size (int): Size of the partitions. + partition_type (str): Type of partitioning to use. Can be either "grid" or "window". + grid_size (Tuple[int, int]): Size of the grid to partition the input tensor into. + mlp_ratio (int): Ratio of the feature size expansion in the MLP layer. + activation_layer (Callable[..., nn.Module]): Activation function to use. + norm_layer (Callable[..., nn.Module]): Normalization function to use. + attention_dropout (float): Dropout probability for the attention layer. + mlp_dropout (float): Dropout probability for the MLP layer. + p_stochastic_dropout (float): Probability of dropping out a partition. + """ + + def __init__( + self, + in_channels: int, + head_dim: int, + # partitioning parameters + partition_size: int, + partition_type: str, + # grid size needs to be known at initialization time + # because we need to know hamy relative offsets there are in the grid + grid_size: tuple[int, int], + mlp_ratio: int, + activation_layer: Callable[..., nn.Module], + norm_layer: Callable[..., nn.Module], + attention_dropout: float, + mlp_dropout: float, + p_stochastic_dropout: float, + ) -> None: + super().__init__() + + self.n_heads = in_channels // head_dim + self.head_dim = head_dim + self.n_partitions = grid_size[0] // partition_size + self.partition_type = partition_type + self.grid_size = grid_size + + if partition_type not in ["grid", "window"]: + raise ValueError("partition_type must be either 'grid' or 'window'") + + if partition_type == "window": + self.p, self.g = partition_size, self.n_partitions + else: + self.p, self.g = self.n_partitions, partition_size + + self.partition_op = WindowPartition() + self.departition_op = WindowDepartition() + self.partition_swap = SwapAxes(-2, -3) if partition_type == "grid" else nn.Identity() + self.departition_swap = SwapAxes(-2, -3) if partition_type == "grid" else nn.Identity() + + self.attn_layer = nn.Sequential( + norm_layer(in_channels), + # it's always going to be partition_size ** 2 because + # of the axis swap in the case of grid partitioning + RelativePositionalMultiHeadAttention(in_channels, head_dim, partition_size**2), + nn.Dropout(attention_dropout), + ) + + # pre-normalization similar to transformer layers + self.mlp_layer = nn.Sequential( + nn.LayerNorm(in_channels), + nn.Linear(in_channels, in_channels * mlp_ratio), + activation_layer(), + nn.Linear(in_channels * mlp_ratio, in_channels), + nn.Dropout(mlp_dropout), + ) + + # layer scale factors + self.stochastic_dropout = StochasticDepth(p_stochastic_dropout, mode="row") + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Input tensor with expected layout of [B, C, H, W]. + Returns: + Tensor: Output tensor with expected layout of [B, C, H, W]. + """ + + # Undefined behavior if H or W are not divisible by p + # https://github.com/google-research/maxvit/blob/da76cf0d8a6ec668cc31b399c4126186da7da944/maxvit/models/maxvit.py#L766 + gh, gw = self.grid_size[0] // self.p, self.grid_size[1] // self.p + torch._assert( + self.grid_size[0] % self.p == 0 and self.grid_size[1] % self.p == 0, + "Grid size must be divisible by partition size. Got grid size of {} and partition size of {}".format( + self.grid_size, self.p + ), + ) + + x = self.partition_op(x, self.p) + x = self.partition_swap(x) + x = x + self.stochastic_dropout(self.attn_layer(x)) + x = x + self.stochastic_dropout(self.mlp_layer(x)) + x = self.departition_swap(x) + x = self.departition_op(x, self.p, gh, gw) + + return x + + +class MaxVitLayer(nn.Module): + """ + MaxVit layer consisting of a MBConv layer followed by a PartitionAttentionLayer with `window` and a PartitionAttentionLayer with `grid`. + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + expansion_ratio (float): Expansion ratio in the bottleneck. + squeeze_ratio (float): Squeeze ratio in the SE Layer. + stride (int): Stride of the depthwise convolution. + activation_layer (Callable[..., nn.Module]): Activation function. + norm_layer (Callable[..., nn.Module]): Normalization function. + head_dim (int): Dimension of the attention heads. + mlp_ratio (int): Ratio of the MLP layer. + mlp_dropout (float): Dropout probability for the MLP layer. + attention_dropout (float): Dropout probability for the attention layer. + p_stochastic_dropout (float): Probability of stochastic depth. + partition_size (int): Size of the partitions. + grid_size (Tuple[int, int]): Size of the input feature grid. + """ + + def __init__( + self, + # conv parameters + in_channels: int, + out_channels: int, + squeeze_ratio: float, + expansion_ratio: float, + stride: int, + # conv + transformer parameters + norm_layer: Callable[..., nn.Module], + activation_layer: Callable[..., nn.Module], + # transformer parameters + head_dim: int, + mlp_ratio: int, + mlp_dropout: float, + attention_dropout: float, + p_stochastic_dropout: float, + # partitioning parameters + partition_size: int, + grid_size: tuple[int, int], + ) -> None: + super().__init__() + + layers: OrderedDict = OrderedDict() + + # convolutional layer + layers["MBconv"] = MBConv( + in_channels=in_channels, + out_channels=out_channels, + expansion_ratio=expansion_ratio, + squeeze_ratio=squeeze_ratio, + stride=stride, + activation_layer=activation_layer, + norm_layer=norm_layer, + p_stochastic_dropout=p_stochastic_dropout, + ) + # attention layers, block -> grid + layers["window_attention"] = PartitionAttentionLayer( + in_channels=out_channels, + head_dim=head_dim, + partition_size=partition_size, + partition_type="window", + grid_size=grid_size, + mlp_ratio=mlp_ratio, + activation_layer=activation_layer, + norm_layer=nn.LayerNorm, + attention_dropout=attention_dropout, + mlp_dropout=mlp_dropout, + p_stochastic_dropout=p_stochastic_dropout, + ) + layers["grid_attention"] = PartitionAttentionLayer( + in_channels=out_channels, + head_dim=head_dim, + partition_size=partition_size, + partition_type="grid", + grid_size=grid_size, + mlp_ratio=mlp_ratio, + activation_layer=activation_layer, + norm_layer=nn.LayerNorm, + attention_dropout=attention_dropout, + mlp_dropout=mlp_dropout, + p_stochastic_dropout=p_stochastic_dropout, + ) + self.layers = nn.Sequential(layers) + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Input tensor of shape (B, C, H, W). + Returns: + Tensor: Output tensor of shape (B, C, H, W). + """ + x = self.layers(x) + return x + + +class MaxVitBlock(nn.Module): + """ + A MaxVit block consisting of `n_layers` MaxVit layers. + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + expansion_ratio (float): Expansion ratio in the bottleneck. + squeeze_ratio (float): Squeeze ratio in the SE Layer. + activation_layer (Callable[..., nn.Module]): Activation function. + norm_layer (Callable[..., nn.Module]): Normalization function. + head_dim (int): Dimension of the attention heads. + mlp_ratio (int): Ratio of the MLP layer. + mlp_dropout (float): Dropout probability for the MLP layer. + attention_dropout (float): Dropout probability for the attention layer. + p_stochastic_dropout (float): Probability of stochastic depth. + partition_size (int): Size of the partitions. + input_grid_size (Tuple[int, int]): Size of the input feature grid. + n_layers (int): Number of layers in the block. + p_stochastic (List[float]): List of probabilities for stochastic depth for each layer. + """ + + def __init__( + self, + # conv parameters + in_channels: int, + out_channels: int, + squeeze_ratio: float, + expansion_ratio: float, + # conv + transformer parameters + norm_layer: Callable[..., nn.Module], + activation_layer: Callable[..., nn.Module], + # transformer parameters + head_dim: int, + mlp_ratio: int, + mlp_dropout: float, + attention_dropout: float, + # partitioning parameters + partition_size: int, + input_grid_size: tuple[int, int], + # number of layers + n_layers: int, + p_stochastic: list[float], + ) -> None: + super().__init__() + if not len(p_stochastic) == n_layers: + raise ValueError(f"p_stochastic must have length n_layers={n_layers}, got p_stochastic={p_stochastic}.") + + self.layers = nn.ModuleList() + # account for the first stride of the first layer + self.grid_size = _get_conv_output_shape(input_grid_size, kernel_size=3, stride=2, padding=1) + + for idx, p in enumerate(p_stochastic): + stride = 2 if idx == 0 else 1 + self.layers += [ + MaxVitLayer( + in_channels=in_channels if idx == 0 else out_channels, + out_channels=out_channels, + squeeze_ratio=squeeze_ratio, + expansion_ratio=expansion_ratio, + stride=stride, + norm_layer=norm_layer, + activation_layer=activation_layer, + head_dim=head_dim, + mlp_ratio=mlp_ratio, + mlp_dropout=mlp_dropout, + attention_dropout=attention_dropout, + partition_size=partition_size, + grid_size=self.grid_size, + p_stochastic_dropout=p, + ), + ] + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Input tensor of shape (B, C, H, W). + Returns: + Tensor: Output tensor of shape (B, C, H, W). + """ + for layer in self.layers: + x = layer(x) + return x + + +class MaxVit(nn.Module): + """ + Implements MaxVit Transformer from the `MaxViT: Multi-Axis Vision Transformer `_ paper. + Args: + input_size (Tuple[int, int]): Size of the input image. + stem_channels (int): Number of channels in the stem. + partition_size (int): Size of the partitions. + block_channels (List[int]): Number of channels in each block. + block_layers (List[int]): Number of layers in each block. + stochastic_depth_prob (float): Probability of stochastic depth. Expands to a list of probabilities for each layer that scales linearly to the specified value. + squeeze_ratio (float): Squeeze ratio in the SE Layer. Default: 0.25. + expansion_ratio (float): Expansion ratio in the MBConv bottleneck. Default: 4. + norm_layer (Callable[..., nn.Module]): Normalization function. Default: None (setting to None will produce a `BatchNorm2d(eps=1e-3, momentum=0.01)`). + activation_layer (Callable[..., nn.Module]): Activation function Default: nn.GELU. + head_dim (int): Dimension of the attention heads. + mlp_ratio (int): Expansion ratio of the MLP layer. Default: 4. + mlp_dropout (float): Dropout probability for the MLP layer. Default: 0.0. + attention_dropout (float): Dropout probability for the attention layer. Default: 0.0. + num_classes (int): Number of classes. Default: 1000. + """ + + def __init__( + self, + # input size parameters + input_size: tuple[int, int], + # stem and task parameters + stem_channels: int, + # partitioning parameters + partition_size: int, + # block parameters + block_channels: list[int], + block_layers: list[int], + # attention head dimensions + head_dim: int, + stochastic_depth_prob: float, + # conv + transformer parameters + # norm_layer is applied only to the conv layers + # activation_layer is applied both to conv and transformer layers + norm_layer: Optional[Callable[..., nn.Module]] = None, + activation_layer: Callable[..., nn.Module] = nn.GELU, + # conv parameters + squeeze_ratio: float = 0.25, + expansion_ratio: float = 4, + # transformer parameters + mlp_ratio: int = 4, + mlp_dropout: float = 0.0, + attention_dropout: float = 0.0, + # task parameters + num_classes: int = 1000, + ) -> None: + super().__init__() + _log_api_usage_once(self) + + input_channels = 3 + + # https://github.com/google-research/maxvit/blob/da76cf0d8a6ec668cc31b399c4126186da7da944/maxvit/models/maxvit.py#L1029-L1030 + # for the exact parameters used in batchnorm + if norm_layer is None: + norm_layer = partial(nn.BatchNorm2d, eps=1e-3, momentum=0.01) + + # Make sure input size will be divisible by the partition size in all blocks + # Undefined behavior if H or W are not divisible by p + # https://github.com/google-research/maxvit/blob/da76cf0d8a6ec668cc31b399c4126186da7da944/maxvit/models/maxvit.py#L766 + block_input_sizes = _make_block_input_shapes(input_size, len(block_channels)) + for idx, block_input_size in enumerate(block_input_sizes): + if block_input_size[0] % partition_size != 0 or block_input_size[1] % partition_size != 0: + raise ValueError( + f"Input size {block_input_size} of block {idx} is not divisible by partition size {partition_size}. " + f"Consider changing the partition size or the input size.\n" + f"Current configuration yields the following block input sizes: {block_input_sizes}." + ) + + # stem + self.stem = nn.Sequential( + Conv2dNormActivation( + input_channels, + stem_channels, + 3, + stride=2, + norm_layer=norm_layer, + activation_layer=activation_layer, + bias=False, + inplace=None, + ), + Conv2dNormActivation( + stem_channels, stem_channels, 3, stride=1, norm_layer=None, activation_layer=None, bias=True + ), + ) + + # account for stem stride + input_size = _get_conv_output_shape(input_size, kernel_size=3, stride=2, padding=1) + self.partition_size = partition_size + + # blocks + self.blocks = nn.ModuleList() + in_channels = [stem_channels] + block_channels[:-1] + out_channels = block_channels + + # precompute the stochastich depth probabilities from 0 to stochastic_depth_prob + # since we have N blocks with L layers, we will have N * L probabilities uniformly distributed + # over the range [0, stochastic_depth_prob] + p_stochastic = np.linspace(0, stochastic_depth_prob, sum(block_layers)).tolist() + + p_idx = 0 + for in_channel, out_channel, num_layers in zip(in_channels, out_channels, block_layers): + self.blocks.append( + MaxVitBlock( + in_channels=in_channel, + out_channels=out_channel, + squeeze_ratio=squeeze_ratio, + expansion_ratio=expansion_ratio, + norm_layer=norm_layer, + activation_layer=activation_layer, + head_dim=head_dim, + mlp_ratio=mlp_ratio, + mlp_dropout=mlp_dropout, + attention_dropout=attention_dropout, + partition_size=partition_size, + input_grid_size=input_size, + n_layers=num_layers, + p_stochastic=p_stochastic[p_idx : p_idx + num_layers], + ), + ) + input_size = self.blocks[-1].grid_size # type: ignore[assignment] + p_idx += num_layers + + # see https://github.com/google-research/maxvit/blob/da76cf0d8a6ec668cc31b399c4126186da7da944/maxvit/models/maxvit.py#L1137-L1158 + # for why there is Linear -> Tanh -> Linear + self.classifier = nn.Sequential( + nn.AdaptiveAvgPool2d(1), + nn.Flatten(), + nn.LayerNorm(block_channels[-1]), + nn.Linear(block_channels[-1], block_channels[-1]), + nn.Tanh(), + nn.Linear(block_channels[-1], num_classes, bias=False), + ) + + self._init_weights() + + def forward(self, x: Tensor) -> Tensor: + x = self.stem(x) + for block in self.blocks: + x = block(x) + x = self.classifier(x) + return x + + def _init_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.zeros_(m.bias) + + +def _maxvit( + # stem parameters + stem_channels: int, + # block parameters + block_channels: list[int], + block_layers: list[int], + stochastic_depth_prob: float, + # partitioning parameters + partition_size: int, + # transformer parameters + head_dim: int, + # Weights API + weights: Optional[WeightsEnum] = None, + progress: bool = False, + # kwargs, + **kwargs: Any, +) -> MaxVit: + + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + assert weights.meta["min_size"][0] == weights.meta["min_size"][1] + _ovewrite_named_param(kwargs, "input_size", weights.meta["min_size"]) + + input_size = kwargs.pop("input_size", (224, 224)) + + model = MaxVit( + stem_channels=stem_channels, + block_channels=block_channels, + block_layers=block_layers, + stochastic_depth_prob=stochastic_depth_prob, + head_dim=head_dim, + partition_size=partition_size, + input_size=input_size, + **kwargs, + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +class MaxVit_T_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # URL empty until official release + url="https://download.pytorch.org/models/maxvit_t-bc5ab103.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=224, interpolation=InterpolationMode.BICUBIC + ), + meta={ + "categories": _IMAGENET_CATEGORIES, + "num_params": 30919624, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#maxvit", + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.700, + "acc@5": 96.722, + } + }, + "_ops": 5.558, + "_file_size": 118.769, + "_docs": """These weights reproduce closely the results of the paper using a similar training recipe. + They were trained with a BatchNorm2D momentum of 0.99 instead of the more correct 0.01.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MaxVit_T_Weights.IMAGENET1K_V1)) +def maxvit_t(*, weights: Optional[MaxVit_T_Weights] = None, progress: bool = True, **kwargs: Any) -> MaxVit: + """ + Constructs a maxvit_t architecture from + `MaxViT: Multi-Axis Vision Transformer `_. + + Args: + weights (:class:`~torchvision.models.MaxVit_T_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MaxVit_T_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.maxvit.MaxVit`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MaxVit_T_Weights + :members: + """ + weights = MaxVit_T_Weights.verify(weights) + + return _maxvit( + stem_channels=64, + block_channels=[64, 128, 256, 512], + block_layers=[2, 2, 5, 2], + head_dim=32, + stochastic_depth_prob=0.2, + partition_size=7, + weights=weights, + progress=progress, + **kwargs, + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/mnasnet.py b/.venv/lib/python3.12/site-packages/torchvision/models/mnasnet.py new file mode 100644 index 0000000000000000000000000000000000000000..0471b19a6d59618385df3e1ab0e9ecf65bb21dcf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/mnasnet.py @@ -0,0 +1,434 @@ +import warnings +from functools import partial +from typing import Any, Optional + +import torch +import torch.nn as nn +from torch import Tensor + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "MNASNet", + "MNASNet0_5_Weights", + "MNASNet0_75_Weights", + "MNASNet1_0_Weights", + "MNASNet1_3_Weights", + "mnasnet0_5", + "mnasnet0_75", + "mnasnet1_0", + "mnasnet1_3", +] + + +# Paper suggests 0.9997 momentum, for TensorFlow. Equivalent PyTorch momentum is +# 1.0 - tensorflow. +_BN_MOMENTUM = 1 - 0.9997 + + +class _InvertedResidual(nn.Module): + def __init__( + self, in_ch: int, out_ch: int, kernel_size: int, stride: int, expansion_factor: int, bn_momentum: float = 0.1 + ) -> None: + super().__init__() + if stride not in [1, 2]: + raise ValueError(f"stride should be 1 or 2 instead of {stride}") + if kernel_size not in [3, 5]: + raise ValueError(f"kernel_size should be 3 or 5 instead of {kernel_size}") + mid_ch = in_ch * expansion_factor + self.apply_residual = in_ch == out_ch and stride == 1 + self.layers = nn.Sequential( + # Pointwise + nn.Conv2d(in_ch, mid_ch, 1, bias=False), + nn.BatchNorm2d(mid_ch, momentum=bn_momentum), + nn.ReLU(inplace=True), + # Depthwise + nn.Conv2d(mid_ch, mid_ch, kernel_size, padding=kernel_size // 2, stride=stride, groups=mid_ch, bias=False), + nn.BatchNorm2d(mid_ch, momentum=bn_momentum), + nn.ReLU(inplace=True), + # Linear pointwise. Note that there's no activation. + nn.Conv2d(mid_ch, out_ch, 1, bias=False), + nn.BatchNorm2d(out_ch, momentum=bn_momentum), + ) + + def forward(self, input: Tensor) -> Tensor: + if self.apply_residual: + return self.layers(input) + input + else: + return self.layers(input) + + +def _stack( + in_ch: int, out_ch: int, kernel_size: int, stride: int, exp_factor: int, repeats: int, bn_momentum: float +) -> nn.Sequential: + """Creates a stack of inverted residuals.""" + if repeats < 1: + raise ValueError(f"repeats should be >= 1, instead got {repeats}") + # First one has no skip, because feature map size changes. + first = _InvertedResidual(in_ch, out_ch, kernel_size, stride, exp_factor, bn_momentum=bn_momentum) + remaining = [] + for _ in range(1, repeats): + remaining.append(_InvertedResidual(out_ch, out_ch, kernel_size, 1, exp_factor, bn_momentum=bn_momentum)) + return nn.Sequential(first, *remaining) + + +def _round_to_multiple_of(val: float, divisor: int, round_up_bias: float = 0.9) -> int: + """Asymmetric rounding to make `val` divisible by `divisor`. With default + bias, will round up, unless the number is no more than 10% greater than the + smaller divisible value, i.e. (83, 8) -> 80, but (84, 8) -> 88.""" + if not 0.0 < round_up_bias < 1.0: + raise ValueError(f"round_up_bias should be greater than 0.0 and smaller than 1.0 instead of {round_up_bias}") + new_val = max(divisor, int(val + divisor / 2) // divisor * divisor) + return new_val if new_val >= round_up_bias * val else new_val + divisor + + +def _get_depths(alpha: float) -> list[int]: + """Scales tensor depths as in reference MobileNet code, prefers rounding up + rather than down.""" + depths = [32, 16, 24, 40, 80, 96, 192, 320] + return [_round_to_multiple_of(depth * alpha, 8) for depth in depths] + + +class MNASNet(torch.nn.Module): + """MNASNet, as described in https://arxiv.org/abs/1807.11626. This + implements the B1 variant of the model. + >>> model = MNASNet(1.0, num_classes=1000) + >>> x = torch.rand(1, 3, 224, 224) + >>> y = model(x) + >>> y.dim() + 2 + >>> y.nelement() + 1000 + """ + + # Version 2 adds depth scaling in the initial stages of the network. + _version = 2 + + def __init__(self, alpha: float, num_classes: int = 1000, dropout: float = 0.2) -> None: + super().__init__() + _log_api_usage_once(self) + if alpha <= 0.0: + raise ValueError(f"alpha should be greater than 0.0 instead of {alpha}") + self.alpha = alpha + self.num_classes = num_classes + depths = _get_depths(alpha) + layers = [ + # First layer: regular conv. + nn.Conv2d(3, depths[0], 3, padding=1, stride=2, bias=False), + nn.BatchNorm2d(depths[0], momentum=_BN_MOMENTUM), + nn.ReLU(inplace=True), + # Depthwise separable, no skip. + nn.Conv2d(depths[0], depths[0], 3, padding=1, stride=1, groups=depths[0], bias=False), + nn.BatchNorm2d(depths[0], momentum=_BN_MOMENTUM), + nn.ReLU(inplace=True), + nn.Conv2d(depths[0], depths[1], 1, padding=0, stride=1, bias=False), + nn.BatchNorm2d(depths[1], momentum=_BN_MOMENTUM), + # MNASNet blocks: stacks of inverted residuals. + _stack(depths[1], depths[2], 3, 2, 3, 3, _BN_MOMENTUM), + _stack(depths[2], depths[3], 5, 2, 3, 3, _BN_MOMENTUM), + _stack(depths[3], depths[4], 5, 2, 6, 3, _BN_MOMENTUM), + _stack(depths[4], depths[5], 3, 1, 6, 2, _BN_MOMENTUM), + _stack(depths[5], depths[6], 5, 2, 6, 4, _BN_MOMENTUM), + _stack(depths[6], depths[7], 3, 1, 6, 1, _BN_MOMENTUM), + # Final mapping to classifier input. + nn.Conv2d(depths[7], 1280, 1, padding=0, stride=1, bias=False), + nn.BatchNorm2d(1280, momentum=_BN_MOMENTUM), + nn.ReLU(inplace=True), + ] + self.layers = nn.Sequential(*layers) + self.classifier = nn.Sequential(nn.Dropout(p=dropout, inplace=True), nn.Linear(1280, num_classes)) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.BatchNorm2d): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + nn.init.kaiming_uniform_(m.weight, mode="fan_out", nonlinearity="sigmoid") + nn.init.zeros_(m.bias) + + def forward(self, x: Tensor) -> Tensor: + x = self.layers(x) + # Equivalent to global avgpool and removing H and W dimensions. + x = x.mean([2, 3]) + return self.classifier(x) + + def _load_from_state_dict( + self, + state_dict: dict, + prefix: str, + local_metadata: dict, + strict: bool, + missing_keys: list[str], + unexpected_keys: list[str], + error_msgs: list[str], + ) -> None: + version = local_metadata.get("version", None) + if version not in [1, 2]: + raise ValueError(f"version should be set to 1 or 2 instead of {version}") + + if version == 1 and not self.alpha == 1.0: + # In the initial version of the model (v1), stem was fixed-size. + # All other layer configurations were the same. This will patch + # the model so that it's identical to v1. Model with alpha 1.0 is + # unaffected. + depths = _get_depths(self.alpha) + v1_stem = [ + nn.Conv2d(3, 32, 3, padding=1, stride=2, bias=False), + nn.BatchNorm2d(32, momentum=_BN_MOMENTUM), + nn.ReLU(inplace=True), + nn.Conv2d(32, 32, 3, padding=1, stride=1, groups=32, bias=False), + nn.BatchNorm2d(32, momentum=_BN_MOMENTUM), + nn.ReLU(inplace=True), + nn.Conv2d(32, 16, 1, padding=0, stride=1, bias=False), + nn.BatchNorm2d(16, momentum=_BN_MOMENTUM), + _stack(16, depths[2], 3, 2, 3, 3, _BN_MOMENTUM), + ] + for idx, layer in enumerate(v1_stem): + self.layers[idx] = layer + + # The model is now identical to v1, and must be saved as such. + self._version = 1 + warnings.warn( + "A new version of MNASNet model has been implemented. " + "Your checkpoint was saved using the previous version. " + "This checkpoint will load and work as before, but " + "you may want to upgrade by training a newer model or " + "transfer learning from an updated ImageNet checkpoint.", + UserWarning, + ) + + super()._load_from_state_dict( + state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ) + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/1e100/mnasnet_trainer", +} + + +class MNASNet0_5_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/mnasnet0.5_top1_67.823-3ffadce67e.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 2218512, + "_metrics": { + "ImageNet-1K": { + "acc@1": 67.734, + "acc@5": 87.490, + } + }, + "_ops": 0.104, + "_file_size": 8.591, + "_docs": """These weights reproduce closely the results of the paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class MNASNet0_75_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/mnasnet0_75-7090bc5f.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/pull/6019", + "num_params": 3170208, + "_metrics": { + "ImageNet-1K": { + "acc@1": 71.180, + "acc@5": 90.496, + } + }, + "_ops": 0.215, + "_file_size": 12.303, + "_docs": """ + These weights were trained from scratch by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class MNASNet1_0_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/mnasnet1.0_top1_73.512-f206786ef8.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 4383312, + "_metrics": { + "ImageNet-1K": { + "acc@1": 73.456, + "acc@5": 91.510, + } + }, + "_ops": 0.314, + "_file_size": 16.915, + "_docs": """These weights reproduce closely the results of the paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class MNASNet1_3_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/mnasnet1_3-a4c69d6f.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/pull/6019", + "num_params": 6282256, + "_metrics": { + "ImageNet-1K": { + "acc@1": 76.506, + "acc@5": 93.522, + } + }, + "_ops": 0.526, + "_file_size": 24.246, + "_docs": """ + These weights were trained from scratch by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +def _mnasnet(alpha: float, weights: Optional[WeightsEnum], progress: bool, **kwargs: Any) -> MNASNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = MNASNet(alpha, **kwargs) + + if weights: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MNASNet0_5_Weights.IMAGENET1K_V1)) +def mnasnet0_5(*, weights: Optional[MNASNet0_5_Weights] = None, progress: bool = True, **kwargs: Any) -> MNASNet: + """MNASNet with depth multiplier of 0.5 from + `MnasNet: Platform-Aware Neural Architecture Search for Mobile + `_ paper. + + Args: + weights (:class:`~torchvision.models.MNASNet0_5_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MNASNet0_5_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.mnasnet.MNASNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MNASNet0_5_Weights + :members: + """ + weights = MNASNet0_5_Weights.verify(weights) + + return _mnasnet(0.5, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MNASNet0_75_Weights.IMAGENET1K_V1)) +def mnasnet0_75(*, weights: Optional[MNASNet0_75_Weights] = None, progress: bool = True, **kwargs: Any) -> MNASNet: + """MNASNet with depth multiplier of 0.75 from + `MnasNet: Platform-Aware Neural Architecture Search for Mobile + `_ paper. + + Args: + weights (:class:`~torchvision.models.MNASNet0_75_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MNASNet0_75_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.mnasnet.MNASNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MNASNet0_75_Weights + :members: + """ + weights = MNASNet0_75_Weights.verify(weights) + + return _mnasnet(0.75, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MNASNet1_0_Weights.IMAGENET1K_V1)) +def mnasnet1_0(*, weights: Optional[MNASNet1_0_Weights] = None, progress: bool = True, **kwargs: Any) -> MNASNet: + """MNASNet with depth multiplier of 1.0 from + `MnasNet: Platform-Aware Neural Architecture Search for Mobile + `_ paper. + + Args: + weights (:class:`~torchvision.models.MNASNet1_0_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MNASNet1_0_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.mnasnet.MNASNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MNASNet1_0_Weights + :members: + """ + weights = MNASNet1_0_Weights.verify(weights) + + return _mnasnet(1.0, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MNASNet1_3_Weights.IMAGENET1K_V1)) +def mnasnet1_3(*, weights: Optional[MNASNet1_3_Weights] = None, progress: bool = True, **kwargs: Any) -> MNASNet: + """MNASNet with depth multiplier of 1.3 from + `MnasNet: Platform-Aware Neural Architecture Search for Mobile + `_ paper. + + Args: + weights (:class:`~torchvision.models.MNASNet1_3_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MNASNet1_3_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.mnasnet.MNASNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MNASNet1_3_Weights + :members: + """ + weights = MNASNet1_3_Weights.verify(weights) + + return _mnasnet(1.3, weights, progress, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/mobilenet.py b/.venv/lib/python3.12/site-packages/torchvision/models/mobilenet.py new file mode 100644 index 0000000000000000000000000000000000000000..0a270d14d3a4ad9eda62b68c2c01e9fdb710ef38 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/mobilenet.py @@ -0,0 +1,6 @@ +from .mobilenetv2 import * # noqa: F401, F403 +from .mobilenetv3 import * # noqa: F401, F403 +from .mobilenetv2 import __all__ as mv2_all +from .mobilenetv3 import __all__ as mv3_all + +__all__ = mv2_all + mv3_all diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/mobilenetv2.py b/.venv/lib/python3.12/site-packages/torchvision/models/mobilenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..97f62e398a3207f59b33ad8609590888364148af --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/mobilenetv2.py @@ -0,0 +1,260 @@ +from functools import partial +from typing import Any, Callable, Optional + +import torch +from torch import nn, Tensor + +from ..ops.misc import Conv2dNormActivation +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _make_divisible, _ovewrite_named_param, handle_legacy_interface + + +__all__ = ["MobileNetV2", "MobileNet_V2_Weights", "mobilenet_v2"] + + +# necessary for backwards compatibility +class InvertedResidual(nn.Module): + def __init__( + self, inp: int, oup: int, stride: int, expand_ratio: int, norm_layer: Optional[Callable[..., nn.Module]] = None + ) -> None: + super().__init__() + self.stride = stride + if stride not in [1, 2]: + raise ValueError(f"stride should be 1 or 2 instead of {stride}") + + if norm_layer is None: + norm_layer = nn.BatchNorm2d + + hidden_dim = int(round(inp * expand_ratio)) + self.use_res_connect = self.stride == 1 and inp == oup + + layers: list[nn.Module] = [] + if expand_ratio != 1: + # pw + layers.append( + Conv2dNormActivation(inp, hidden_dim, kernel_size=1, norm_layer=norm_layer, activation_layer=nn.ReLU6) + ) + layers.extend( + [ + # dw + Conv2dNormActivation( + hidden_dim, + hidden_dim, + stride=stride, + groups=hidden_dim, + norm_layer=norm_layer, + activation_layer=nn.ReLU6, + ), + # pw-linear + nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), + norm_layer(oup), + ] + ) + self.conv = nn.Sequential(*layers) + self.out_channels = oup + self._is_cn = stride > 1 + + def forward(self, x: Tensor) -> Tensor: + if self.use_res_connect: + return x + self.conv(x) + else: + return self.conv(x) + + +class MobileNetV2(nn.Module): + def __init__( + self, + num_classes: int = 1000, + width_mult: float = 1.0, + inverted_residual_setting: Optional[list[list[int]]] = None, + round_nearest: int = 8, + block: Optional[Callable[..., nn.Module]] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + dropout: float = 0.2, + ) -> None: + """ + MobileNet V2 main class + + Args: + num_classes (int): Number of classes + width_mult (float): Width multiplier - adjusts number of channels in each layer by this amount + inverted_residual_setting: Network structure + round_nearest (int): Round the number of channels in each layer to be a multiple of this number + Set to 1 to turn off rounding + block: Module specifying inverted residual building block for mobilenet + norm_layer: Module specifying the normalization layer to use + dropout (float): The droupout probability + + """ + super().__init__() + _log_api_usage_once(self) + + if block is None: + block = InvertedResidual + + if norm_layer is None: + norm_layer = nn.BatchNorm2d + + input_channel = 32 + last_channel = 1280 + + if inverted_residual_setting is None: + inverted_residual_setting = [ + # t, c, n, s + [1, 16, 1, 1], + [6, 24, 2, 2], + [6, 32, 3, 2], + [6, 64, 4, 2], + [6, 96, 3, 1], + [6, 160, 3, 2], + [6, 320, 1, 1], + ] + + # only check the first element, assuming user knows t,c,n,s are required + if len(inverted_residual_setting) == 0 or len(inverted_residual_setting[0]) != 4: + raise ValueError( + f"inverted_residual_setting should be non-empty or a 4-element list, got {inverted_residual_setting}" + ) + + # building first layer + input_channel = _make_divisible(input_channel * width_mult, round_nearest) + self.last_channel = _make_divisible(last_channel * max(1.0, width_mult), round_nearest) + features: list[nn.Module] = [ + Conv2dNormActivation(3, input_channel, stride=2, norm_layer=norm_layer, activation_layer=nn.ReLU6) + ] + # building inverted residual blocks + for t, c, n, s in inverted_residual_setting: + output_channel = _make_divisible(c * width_mult, round_nearest) + for i in range(n): + stride = s if i == 0 else 1 + features.append(block(input_channel, output_channel, stride, expand_ratio=t, norm_layer=norm_layer)) + input_channel = output_channel + # building last several layers + features.append( + Conv2dNormActivation( + input_channel, self.last_channel, kernel_size=1, norm_layer=norm_layer, activation_layer=nn.ReLU6 + ) + ) + # make it nn.Sequential + self.features = nn.Sequential(*features) + + # building classifier + self.classifier = nn.Sequential( + nn.Dropout(p=dropout), + nn.Linear(self.last_channel, num_classes), + ) + + # weight initialization + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out") + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + nn.init.zeros_(m.bias) + + def _forward_impl(self, x: Tensor) -> Tensor: + # This exists since TorchScript doesn't support inheritance, so the superclass method + # (this one) needs to have a name other than `forward` that can be accessed in a subclass + x = self.features(x) + # Cannot use "squeeze" as batch-size can be 1 + x = nn.functional.adaptive_avg_pool2d(x, (1, 1)) + x = torch.flatten(x, 1) + x = self.classifier(x) + return x + + def forward(self, x: Tensor) -> Tensor: + return self._forward_impl(x) + + +_COMMON_META = { + "num_params": 3504872, + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, +} + + +class MobileNet_V2_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/mobilenet_v2-b0353104.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#mobilenetv2", + "_metrics": { + "ImageNet-1K": { + "acc@1": 71.878, + "acc@5": 90.286, + } + }, + "_ops": 0.301, + "_file_size": 13.555, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/mobilenet_v2-7ebf99e0.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-reg-tuning", + "_metrics": { + "ImageNet-1K": { + "acc@1": 72.154, + "acc@5": 90.822, + } + }, + "_ops": 0.301, + "_file_size": 13.598, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MobileNet_V2_Weights.IMAGENET1K_V1)) +def mobilenet_v2( + *, weights: Optional[MobileNet_V2_Weights] = None, progress: bool = True, **kwargs: Any +) -> MobileNetV2: + """MobileNetV2 architecture from the `MobileNetV2: Inverted Residuals and Linear + Bottlenecks `_ paper. + + Args: + weights (:class:`~torchvision.models.MobileNet_V2_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MobileNet_V2_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.mobilenetv2.MobileNetV2`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MobileNet_V2_Weights + :members: + """ + weights = MobileNet_V2_Weights.verify(weights) + + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = MobileNetV2(**kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/mobilenetv3.py b/.venv/lib/python3.12/site-packages/torchvision/models/mobilenetv3.py new file mode 100644 index 0000000000000000000000000000000000000000..e6239d095ba2a0bb4d85a929540de95be4667d67 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/mobilenetv3.py @@ -0,0 +1,424 @@ +from collections.abc import Sequence +from functools import partial +from typing import Any, Callable, Optional + +import torch +from torch import nn, Tensor + +from ..ops.misc import Conv2dNormActivation, SqueezeExcitation as SElayer +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _make_divisible, _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "MobileNetV3", + "MobileNet_V3_Large_Weights", + "MobileNet_V3_Small_Weights", + "mobilenet_v3_large", + "mobilenet_v3_small", +] + + +class InvertedResidualConfig: + # Stores information listed at Tables 1 and 2 of the MobileNetV3 paper + def __init__( + self, + input_channels: int, + kernel: int, + expanded_channels: int, + out_channels: int, + use_se: bool, + activation: str, + stride: int, + dilation: int, + width_mult: float, + ): + self.input_channels = self.adjust_channels(input_channels, width_mult) + self.kernel = kernel + self.expanded_channels = self.adjust_channels(expanded_channels, width_mult) + self.out_channels = self.adjust_channels(out_channels, width_mult) + self.use_se = use_se + self.use_hs = activation == "HS" + self.stride = stride + self.dilation = dilation + + @staticmethod + def adjust_channels(channels: int, width_mult: float): + return _make_divisible(channels * width_mult, 8) + + +class InvertedResidual(nn.Module): + # Implemented as described at section 5 of MobileNetV3 paper + def __init__( + self, + cnf: InvertedResidualConfig, + norm_layer: Callable[..., nn.Module], + se_layer: Callable[..., nn.Module] = partial(SElayer, scale_activation=nn.Hardsigmoid), + ): + super().__init__() + if not (1 <= cnf.stride <= 2): + raise ValueError("illegal stride value") + + self.use_res_connect = cnf.stride == 1 and cnf.input_channels == cnf.out_channels + + layers: list[nn.Module] = [] + activation_layer = nn.Hardswish if cnf.use_hs else nn.ReLU + + # expand + if cnf.expanded_channels != cnf.input_channels: + layers.append( + Conv2dNormActivation( + cnf.input_channels, + cnf.expanded_channels, + kernel_size=1, + norm_layer=norm_layer, + activation_layer=activation_layer, + ) + ) + + # depthwise + stride = 1 if cnf.dilation > 1 else cnf.stride + layers.append( + Conv2dNormActivation( + cnf.expanded_channels, + cnf.expanded_channels, + kernel_size=cnf.kernel, + stride=stride, + dilation=cnf.dilation, + groups=cnf.expanded_channels, + norm_layer=norm_layer, + activation_layer=activation_layer, + ) + ) + if cnf.use_se: + squeeze_channels = _make_divisible(cnf.expanded_channels // 4, 8) + layers.append(se_layer(cnf.expanded_channels, squeeze_channels)) + + # project + layers.append( + Conv2dNormActivation( + cnf.expanded_channels, cnf.out_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=None + ) + ) + + self.block = nn.Sequential(*layers) + self.out_channels = cnf.out_channels + self._is_cn = cnf.stride > 1 + + def forward(self, input: Tensor) -> Tensor: + result = self.block(input) + if self.use_res_connect: + result += input + return result + + +class MobileNetV3(nn.Module): + def __init__( + self, + inverted_residual_setting: list[InvertedResidualConfig], + last_channel: int, + num_classes: int = 1000, + block: Optional[Callable[..., nn.Module]] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + dropout: float = 0.2, + **kwargs: Any, + ) -> None: + """ + MobileNet V3 main class + + Args: + inverted_residual_setting (List[InvertedResidualConfig]): Network structure + last_channel (int): The number of channels on the penultimate layer + num_classes (int): Number of classes + block (Optional[Callable[..., nn.Module]]): Module specifying inverted residual building block for mobilenet + norm_layer (Optional[Callable[..., nn.Module]]): Module specifying the normalization layer to use + dropout (float): The droupout probability + """ + super().__init__() + _log_api_usage_once(self) + + if not inverted_residual_setting: + raise ValueError("The inverted_residual_setting should not be empty") + elif not ( + isinstance(inverted_residual_setting, Sequence) + and all([isinstance(s, InvertedResidualConfig) for s in inverted_residual_setting]) + ): + raise TypeError("The inverted_residual_setting should be List[InvertedResidualConfig]") + + if block is None: + block = InvertedResidual + + if norm_layer is None: + norm_layer = partial(nn.BatchNorm2d, eps=0.001, momentum=0.01) + + layers: list[nn.Module] = [] + + # building first layer + firstconv_output_channels = inverted_residual_setting[0].input_channels + layers.append( + Conv2dNormActivation( + 3, + firstconv_output_channels, + kernel_size=3, + stride=2, + norm_layer=norm_layer, + activation_layer=nn.Hardswish, + ) + ) + + # building inverted residual blocks + for cnf in inverted_residual_setting: + layers.append(block(cnf, norm_layer)) + + # building last several layers + lastconv_input_channels = inverted_residual_setting[-1].out_channels + lastconv_output_channels = 6 * lastconv_input_channels + layers.append( + Conv2dNormActivation( + lastconv_input_channels, + lastconv_output_channels, + kernel_size=1, + norm_layer=norm_layer, + activation_layer=nn.Hardswish, + ) + ) + + self.features = nn.Sequential(*layers) + self.avgpool = nn.AdaptiveAvgPool2d(1) + self.classifier = nn.Sequential( + nn.Linear(lastconv_output_channels, last_channel), + nn.Hardswish(inplace=True), + nn.Dropout(p=dropout, inplace=True), + nn.Linear(last_channel, num_classes), + ) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out") + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + nn.init.zeros_(m.bias) + + def _forward_impl(self, x: Tensor) -> Tensor: + x = self.features(x) + + x = self.avgpool(x) + x = torch.flatten(x, 1) + + x = self.classifier(x) + + return x + + def forward(self, x: Tensor) -> Tensor: + return self._forward_impl(x) + + +def _mobilenet_v3_conf( + arch: str, width_mult: float = 1.0, reduced_tail: bool = False, dilated: bool = False, **kwargs: Any +): + reduce_divider = 2 if reduced_tail else 1 + dilation = 2 if dilated else 1 + + bneck_conf = partial(InvertedResidualConfig, width_mult=width_mult) + adjust_channels = partial(InvertedResidualConfig.adjust_channels, width_mult=width_mult) + + if arch == "mobilenet_v3_large": + inverted_residual_setting = [ + bneck_conf(16, 3, 16, 16, False, "RE", 1, 1), + bneck_conf(16, 3, 64, 24, False, "RE", 2, 1), # C1 + bneck_conf(24, 3, 72, 24, False, "RE", 1, 1), + bneck_conf(24, 5, 72, 40, True, "RE", 2, 1), # C2 + bneck_conf(40, 5, 120, 40, True, "RE", 1, 1), + bneck_conf(40, 5, 120, 40, True, "RE", 1, 1), + bneck_conf(40, 3, 240, 80, False, "HS", 2, 1), # C3 + bneck_conf(80, 3, 200, 80, False, "HS", 1, 1), + bneck_conf(80, 3, 184, 80, False, "HS", 1, 1), + bneck_conf(80, 3, 184, 80, False, "HS", 1, 1), + bneck_conf(80, 3, 480, 112, True, "HS", 1, 1), + bneck_conf(112, 3, 672, 112, True, "HS", 1, 1), + bneck_conf(112, 5, 672, 160 // reduce_divider, True, "HS", 2, dilation), # C4 + bneck_conf(160 // reduce_divider, 5, 960 // reduce_divider, 160 // reduce_divider, True, "HS", 1, dilation), + bneck_conf(160 // reduce_divider, 5, 960 // reduce_divider, 160 // reduce_divider, True, "HS", 1, dilation), + ] + last_channel = adjust_channels(1280 // reduce_divider) # C5 + elif arch == "mobilenet_v3_small": + inverted_residual_setting = [ + bneck_conf(16, 3, 16, 16, True, "RE", 2, 1), # C1 + bneck_conf(16, 3, 72, 24, False, "RE", 2, 1), # C2 + bneck_conf(24, 3, 88, 24, False, "RE", 1, 1), + bneck_conf(24, 5, 96, 40, True, "HS", 2, 1), # C3 + bneck_conf(40, 5, 240, 40, True, "HS", 1, 1), + bneck_conf(40, 5, 240, 40, True, "HS", 1, 1), + bneck_conf(40, 5, 120, 48, True, "HS", 1, 1), + bneck_conf(48, 5, 144, 48, True, "HS", 1, 1), + bneck_conf(48, 5, 288, 96 // reduce_divider, True, "HS", 2, dilation), # C4 + bneck_conf(96 // reduce_divider, 5, 576 // reduce_divider, 96 // reduce_divider, True, "HS", 1, dilation), + bneck_conf(96 // reduce_divider, 5, 576 // reduce_divider, 96 // reduce_divider, True, "HS", 1, dilation), + ] + last_channel = adjust_channels(1024 // reduce_divider) # C5 + else: + raise ValueError(f"Unsupported model type {arch}") + + return inverted_residual_setting, last_channel + + +def _mobilenet_v3( + inverted_residual_setting: list[InvertedResidualConfig], + last_channel: int, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> MobileNetV3: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = MobileNetV3(inverted_residual_setting, last_channel, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, +} + + +class MobileNet_V3_Large_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/mobilenet_v3_large-8738ca79.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 5483032, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#mobilenetv3-large--small", + "_metrics": { + "ImageNet-1K": { + "acc@1": 74.042, + "acc@5": 91.340, + } + }, + "_ops": 0.217, + "_file_size": 21.114, + "_docs": """These weights were trained from scratch by using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/mobilenet_v3_large-5c1a4163.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 5483032, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-reg-tuning", + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.274, + "acc@5": 92.566, + } + }, + "_ops": 0.217, + "_file_size": 21.107, + "_docs": """ + These weights improve marginally upon the results of the original paper by using a modified version of + TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class MobileNet_V3_Small_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/mobilenet_v3_small-047dcff4.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 2542856, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#mobilenetv3-large--small", + "_metrics": { + "ImageNet-1K": { + "acc@1": 67.668, + "acc@5": 87.402, + } + }, + "_ops": 0.057, + "_file_size": 9.829, + "_docs": """ + These weights improve upon the results of the original paper by using a simple training recipe. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MobileNet_V3_Large_Weights.IMAGENET1K_V1)) +def mobilenet_v3_large( + *, weights: Optional[MobileNet_V3_Large_Weights] = None, progress: bool = True, **kwargs: Any +) -> MobileNetV3: + """ + Constructs a large MobileNetV3 architecture from + `Searching for MobileNetV3 `__. + + Args: + weights (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MobileNet_V3_Large_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.mobilenet.MobileNetV3`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MobileNet_V3_Large_Weights + :members: + """ + weights = MobileNet_V3_Large_Weights.verify(weights) + + inverted_residual_setting, last_channel = _mobilenet_v3_conf("mobilenet_v3_large", **kwargs) + return _mobilenet_v3(inverted_residual_setting, last_channel, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MobileNet_V3_Small_Weights.IMAGENET1K_V1)) +def mobilenet_v3_small( + *, weights: Optional[MobileNet_V3_Small_Weights] = None, progress: bool = True, **kwargs: Any +) -> MobileNetV3: + """ + Constructs a small MobileNetV3 architecture from + `Searching for MobileNetV3 `__. + + Args: + weights (:class:`~torchvision.models.MobileNet_V3_Small_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.MobileNet_V3_Small_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.mobilenet.MobileNetV3`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.MobileNet_V3_Small_Weights + :members: + """ + weights = MobileNet_V3_Small_Weights.verify(weights) + + inverted_residual_setting, last_channel = _mobilenet_v3_conf("mobilenet_v3_small", **kwargs) + return _mobilenet_v3(inverted_residual_setting, last_channel, weights, progress, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89d2302f825ff0dbe25d02f6dc7c84d3c0790ad0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/__init__.py @@ -0,0 +1 @@ +from .raft import * diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc20b640bba08ef7e1a085702c8e97393609f77a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfb285f6a0e57dbda87a89f7c142a235cda999c2 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/__pycache__/_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/__pycache__/raft.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/__pycache__/raft.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da4c9274ea5ac1060760040de68baf32a761feb8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/__pycache__/raft.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/_utils.py b/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fa2454a27315d6e560dccb6ea2ce6083da03e256 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/_utils.py @@ -0,0 +1,48 @@ +from typing import Optional + +import torch +import torch.nn.functional as F +from torch import Tensor + + +def grid_sample(img: Tensor, absolute_grid: Tensor, mode: str = "bilinear", align_corners: Optional[bool] = None): + """Same as torch's grid_sample, with absolute pixel coordinates instead of normalized coordinates.""" + h, w = img.shape[-2:] + + xgrid, ygrid = absolute_grid.split([1, 1], dim=-1) + xgrid = 2 * xgrid / (w - 1) - 1 + # Adding condition if h > 1 to enable this function be reused in raft-stereo + if h > 1: + ygrid = 2 * ygrid / (h - 1) - 1 + normalized_grid = torch.cat([xgrid, ygrid], dim=-1) + + return F.grid_sample(img, normalized_grid, mode=mode, align_corners=align_corners) + + +def make_coords_grid(batch_size: int, h: int, w: int, device: str = "cpu"): + device = torch.device(device) + coords = torch.meshgrid(torch.arange(h, device=device), torch.arange(w, device=device), indexing="ij") + coords = torch.stack(coords[::-1], dim=0).float() + return coords[None].repeat(batch_size, 1, 1, 1) + + +def upsample_flow(flow, up_mask: Optional[Tensor] = None, factor: int = 8): + """Upsample flow by the input factor (default 8). + + If up_mask is None we just interpolate. + If up_mask is specified, we upsample using a convex combination of its weights. See paper page 8 and appendix B. + Note that in appendix B the picture assumes a downsample factor of 4 instead of 8. + """ + batch_size, num_channels, h, w = flow.shape + new_h, new_w = h * factor, w * factor + + if up_mask is None: + return factor * F.interpolate(flow, size=(new_h, new_w), mode="bilinear", align_corners=True) + + up_mask = up_mask.view(batch_size, 1, 9, factor, factor, h, w) + up_mask = torch.softmax(up_mask, dim=2) # "convex" == weights sum to 1 + + upsampled_flow = F.unfold(factor * flow, kernel_size=3, padding=1).view(batch_size, num_channels, 9, 1, 1, h, w) + upsampled_flow = torch.sum(up_mask * upsampled_flow, dim=2) + + return upsampled_flow.permute(0, 1, 4, 2, 5, 3).reshape(batch_size, num_channels, new_h, new_w) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/raft.py b/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/raft.py new file mode 100644 index 0000000000000000000000000000000000000000..644adc2dc5c67c3517b697e2c0a3f0e273ea7277 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/optical_flow/raft.py @@ -0,0 +1,947 @@ +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor +from torch.nn.modules.batchnorm import BatchNorm2d +from torch.nn.modules.instancenorm import InstanceNorm2d +from torchvision.ops import Conv2dNormActivation + +from ...transforms._presets import OpticalFlow +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._utils import handle_legacy_interface +from ._utils import grid_sample, make_coords_grid, upsample_flow + + +__all__ = ( + "RAFT", + "raft_large", + "raft_small", + "Raft_Large_Weights", + "Raft_Small_Weights", +) + + +class ResidualBlock(nn.Module): + """Slightly modified Residual block with extra relu and biases.""" + + def __init__(self, in_channels, out_channels, *, norm_layer, stride=1, always_project: bool = False): + super().__init__() + + # Note regarding bias=True: + # Usually we can pass bias=False in conv layers followed by a norm layer. + # But in the RAFT training reference, the BatchNorm2d layers are only activated for the first dataset, + # and frozen for the rest of the training process (i.e. set as eval()). The bias term is thus still useful + # for the rest of the datasets. Technically, we could remove the bias for other norm layers like Instance norm + # because these aren't frozen, but we don't bother (also, we wouldn't be able to load the original weights). + self.convnormrelu1 = Conv2dNormActivation( + in_channels, out_channels, norm_layer=norm_layer, kernel_size=3, stride=stride, bias=True + ) + self.convnormrelu2 = Conv2dNormActivation( + out_channels, out_channels, norm_layer=norm_layer, kernel_size=3, bias=True + ) + + # make mypy happy + self.downsample: nn.Module + + if stride == 1 and not always_project: + self.downsample = nn.Identity() + else: + self.downsample = Conv2dNormActivation( + in_channels, + out_channels, + norm_layer=norm_layer, + kernel_size=1, + stride=stride, + bias=True, + activation_layer=None, + ) + + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + y = x + y = self.convnormrelu1(y) + y = self.convnormrelu2(y) + + x = self.downsample(x) + + return self.relu(x + y) + + +class BottleneckBlock(nn.Module): + """Slightly modified BottleNeck block (extra relu and biases)""" + + def __init__(self, in_channels, out_channels, *, norm_layer, stride=1): + super().__init__() + + # See note in ResidualBlock for the reason behind bias=True + self.convnormrelu1 = Conv2dNormActivation( + in_channels, out_channels // 4, norm_layer=norm_layer, kernel_size=1, bias=True + ) + self.convnormrelu2 = Conv2dNormActivation( + out_channels // 4, out_channels // 4, norm_layer=norm_layer, kernel_size=3, stride=stride, bias=True + ) + self.convnormrelu3 = Conv2dNormActivation( + out_channels // 4, out_channels, norm_layer=norm_layer, kernel_size=1, bias=True + ) + self.relu = nn.ReLU(inplace=True) + + if stride == 1: + self.downsample = nn.Identity() + else: + self.downsample = Conv2dNormActivation( + in_channels, + out_channels, + norm_layer=norm_layer, + kernel_size=1, + stride=stride, + bias=True, + activation_layer=None, + ) + + def forward(self, x): + y = x + y = self.convnormrelu1(y) + y = self.convnormrelu2(y) + y = self.convnormrelu3(y) + + x = self.downsample(x) + + return self.relu(x + y) + + +class FeatureEncoder(nn.Module): + """The feature encoder, used both as the actual feature encoder, and as the context encoder. + + It must downsample its input by 8. + """ + + def __init__( + self, *, block=ResidualBlock, layers=(64, 64, 96, 128, 256), strides=(2, 1, 2, 2), norm_layer=nn.BatchNorm2d + ): + super().__init__() + + if len(layers) != 5: + raise ValueError(f"The expected number of layers is 5, instead got {len(layers)}") + + # See note in ResidualBlock for the reason behind bias=True + self.convnormrelu = Conv2dNormActivation( + 3, layers[0], norm_layer=norm_layer, kernel_size=7, stride=strides[0], bias=True + ) + + self.layer1 = self._make_2_blocks(block, layers[0], layers[1], norm_layer=norm_layer, first_stride=strides[1]) + self.layer2 = self._make_2_blocks(block, layers[1], layers[2], norm_layer=norm_layer, first_stride=strides[2]) + self.layer3 = self._make_2_blocks(block, layers[2], layers[3], norm_layer=norm_layer, first_stride=strides[3]) + + self.conv = nn.Conv2d(layers[3], layers[4], kernel_size=1) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d)): + if m.weight is not None: + nn.init.constant_(m.weight, 1) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + num_downsamples = len(list(filter(lambda s: s == 2, strides))) + self.output_dim = layers[-1] + self.downsample_factor = 2**num_downsamples + + def _make_2_blocks(self, block, in_channels, out_channels, norm_layer, first_stride): + block1 = block(in_channels, out_channels, norm_layer=norm_layer, stride=first_stride) + block2 = block(out_channels, out_channels, norm_layer=norm_layer, stride=1) + return nn.Sequential(block1, block2) + + def forward(self, x): + x = self.convnormrelu(x) + + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + + x = self.conv(x) + + return x + + +class MotionEncoder(nn.Module): + """The motion encoder, part of the update block. + + Takes the current predicted flow and the correlation features as input and returns an encoded version of these. + """ + + def __init__(self, *, in_channels_corr, corr_layers=(256, 192), flow_layers=(128, 64), out_channels=128): + super().__init__() + + if len(flow_layers) != 2: + raise ValueError(f"The expected number of flow_layers is 2, instead got {len(flow_layers)}") + if len(corr_layers) not in (1, 2): + raise ValueError(f"The number of corr_layers should be 1 or 2, instead got {len(corr_layers)}") + + self.convcorr1 = Conv2dNormActivation(in_channels_corr, corr_layers[0], norm_layer=None, kernel_size=1) + if len(corr_layers) == 2: + self.convcorr2 = Conv2dNormActivation(corr_layers[0], corr_layers[1], norm_layer=None, kernel_size=3) + else: + self.convcorr2 = nn.Identity() + + self.convflow1 = Conv2dNormActivation(2, flow_layers[0], norm_layer=None, kernel_size=7) + self.convflow2 = Conv2dNormActivation(flow_layers[0], flow_layers[1], norm_layer=None, kernel_size=3) + + # out_channels - 2 because we cat the flow (2 channels) at the end + self.conv = Conv2dNormActivation( + corr_layers[-1] + flow_layers[-1], out_channels - 2, norm_layer=None, kernel_size=3 + ) + + self.out_channels = out_channels + + def forward(self, flow, corr_features): + corr = self.convcorr1(corr_features) + corr = self.convcorr2(corr) + + flow_orig = flow + flow = self.convflow1(flow) + flow = self.convflow2(flow) + + corr_flow = torch.cat([corr, flow], dim=1) + corr_flow = self.conv(corr_flow) + return torch.cat([corr_flow, flow_orig], dim=1) + + +class ConvGRU(nn.Module): + """Convolutional Gru unit.""" + + def __init__(self, *, input_size, hidden_size, kernel_size, padding): + super().__init__() + self.convz = nn.Conv2d(hidden_size + input_size, hidden_size, kernel_size=kernel_size, padding=padding) + self.convr = nn.Conv2d(hidden_size + input_size, hidden_size, kernel_size=kernel_size, padding=padding) + self.convq = nn.Conv2d(hidden_size + input_size, hidden_size, kernel_size=kernel_size, padding=padding) + + def forward(self, h, x): + hx = torch.cat([h, x], dim=1) + z = torch.sigmoid(self.convz(hx)) + r = torch.sigmoid(self.convr(hx)) + q = torch.tanh(self.convq(torch.cat([r * h, x], dim=1))) + h = (1 - z) * h + z * q + return h + + +def _pass_through_h(h, _): + # Declared here for torchscript + return h + + +class RecurrentBlock(nn.Module): + """Recurrent block, part of the update block. + + Takes the current hidden state and the concatenation of (motion encoder output, context) as input. + Returns an updated hidden state. + """ + + def __init__(self, *, input_size, hidden_size, kernel_size=((1, 5), (5, 1)), padding=((0, 2), (2, 0))): + super().__init__() + + if len(kernel_size) != len(padding): + raise ValueError( + f"kernel_size should have the same length as padding, instead got len(kernel_size) = {len(kernel_size)} and len(padding) = {len(padding)}" + ) + if len(kernel_size) not in (1, 2): + raise ValueError(f"kernel_size should either 1 or 2, instead got {len(kernel_size)}") + + self.convgru1 = ConvGRU( + input_size=input_size, hidden_size=hidden_size, kernel_size=kernel_size[0], padding=padding[0] + ) + if len(kernel_size) == 2: + self.convgru2 = ConvGRU( + input_size=input_size, hidden_size=hidden_size, kernel_size=kernel_size[1], padding=padding[1] + ) + else: + self.convgru2 = _pass_through_h + + self.hidden_size = hidden_size + + def forward(self, h, x): + h = self.convgru1(h, x) + h = self.convgru2(h, x) + return h + + +class FlowHead(nn.Module): + """Flow head, part of the update block. + + Takes the hidden state of the recurrent unit as input, and outputs the predicted "delta flow". + """ + + def __init__(self, *, in_channels, hidden_size): + super().__init__() + self.conv1 = nn.Conv2d(in_channels, hidden_size, 3, padding=1) + self.conv2 = nn.Conv2d(hidden_size, 2, 3, padding=1) + self.relu = nn.ReLU(inplace=True) + + def forward(self, x): + return self.conv2(self.relu(self.conv1(x))) + + +class UpdateBlock(nn.Module): + """The update block which contains the motion encoder, the recurrent block, and the flow head. + + It must expose a ``hidden_state_size`` attribute which is the hidden state size of its recurrent block. + """ + + def __init__(self, *, motion_encoder, recurrent_block, flow_head): + super().__init__() + self.motion_encoder = motion_encoder + self.recurrent_block = recurrent_block + self.flow_head = flow_head + + self.hidden_state_size = recurrent_block.hidden_size + + def forward(self, hidden_state, context, corr_features, flow): + motion_features = self.motion_encoder(flow, corr_features) + x = torch.cat([context, motion_features], dim=1) + + hidden_state = self.recurrent_block(hidden_state, x) + delta_flow = self.flow_head(hidden_state) + return hidden_state, delta_flow + + +class MaskPredictor(nn.Module): + """Mask predictor to be used when upsampling the predicted flow. + + It takes the hidden state of the recurrent unit as input and outputs the mask. + This is not used in the raft-small model. + """ + + def __init__(self, *, in_channels, hidden_size, multiplier=0.25): + super().__init__() + self.convrelu = Conv2dNormActivation(in_channels, hidden_size, norm_layer=None, kernel_size=3) + # 8 * 8 * 9 because the predicted flow is downsampled by 8, from the downsampling of the initial FeatureEncoder, + # and we interpolate with all 9 surrounding neighbors. See paper and appendix B. + self.conv = nn.Conv2d(hidden_size, 8 * 8 * 9, 1, padding=0) + + # In the original code, they use a factor of 0.25 to "downweight the gradients" of that branch. + # See e.g. https://github.com/princeton-vl/RAFT/issues/119#issuecomment-953950419 + # or https://github.com/princeton-vl/RAFT/issues/24. + # It doesn't seem to affect epe significantly and can likely be set to 1. + self.multiplier = multiplier + + def forward(self, x): + x = self.convrelu(x) + x = self.conv(x) + return self.multiplier * x + + +class CorrBlock(nn.Module): + """The correlation block. + + Creates a correlation pyramid with ``num_levels`` levels from the outputs of the feature encoder, + and then indexes from this pyramid to create correlation features. + The "indexing" of a given centroid pixel x' is done by concatenating its surrounding neighbors that + are within a ``radius``, according to the infinity norm (see paper section 3.2). + Note: typo in the paper, it should be infinity norm, not 1-norm. + """ + + def __init__(self, *, num_levels: int = 4, radius: int = 4): + super().__init__() + self.num_levels = num_levels + self.radius = radius + + self.corr_pyramid: list[Tensor] = [torch.tensor(0)] # useless, but torchscript is otherwise confused :') + + # The neighborhood of a centroid pixel x' is {x' + delta, ||delta||_inf <= radius} + # so it's a square surrounding x', and its sides have a length of 2 * radius + 1 + # The paper claims that it's ||.||_1 instead of ||.||_inf but it's a typo: + # https://github.com/princeton-vl/RAFT/issues/122 + self.out_channels = num_levels * (2 * radius + 1) ** 2 + + def build_pyramid(self, fmap1, fmap2): + """Build the correlation pyramid from two feature maps. + + The correlation volume is first computed as the dot product of each pair (pixel_in_fmap1, pixel_in_fmap2) + The last 2 dimensions of the correlation volume are then pooled num_levels times at different resolutions + to build the correlation pyramid. + """ + + if fmap1.shape != fmap2.shape: + raise ValueError( + f"Input feature maps should have the same shape, instead got {fmap1.shape} (fmap1.shape) != {fmap2.shape} (fmap2.shape)" + ) + + # Explaining min_fmap_size below: the fmaps are down-sampled (num_levels - 1) times by a factor of 2. + # The last corr_volume most have at least 2 values (hence the 2* factor), otherwise grid_sample() would + # produce nans in its output. + min_fmap_size = 2 * (2 ** (self.num_levels - 1)) + if any(fmap_size < min_fmap_size for fmap_size in fmap1.shape[-2:]): + raise ValueError( + "Feature maps are too small to be down-sampled by the correlation pyramid. " + f"H and W of feature maps should be at least {min_fmap_size}; got: {fmap1.shape[-2:]}. " + "Remember that input images to the model are downsampled by 8, so that means their " + f"dimensions should be at least 8 * {min_fmap_size} = {8 * min_fmap_size}." + ) + + corr_volume = self._compute_corr_volume(fmap1, fmap2) + + batch_size, h, w, num_channels, _, _ = corr_volume.shape # _, _ = h, w + corr_volume = corr_volume.reshape(batch_size * h * w, num_channels, h, w) + self.corr_pyramid = [corr_volume] + for _ in range(self.num_levels - 1): + corr_volume = F.avg_pool2d(corr_volume, kernel_size=2, stride=2) + self.corr_pyramid.append(corr_volume) + + def index_pyramid(self, centroids_coords): + """Return correlation features by indexing from the pyramid.""" + neighborhood_side_len = 2 * self.radius + 1 # see note in __init__ about out_channels + di = torch.linspace(-self.radius, self.radius, neighborhood_side_len) + dj = torch.linspace(-self.radius, self.radius, neighborhood_side_len) + delta = torch.stack(torch.meshgrid(di, dj, indexing="ij"), dim=-1).to(centroids_coords.device) + delta = delta.view(1, neighborhood_side_len, neighborhood_side_len, 2) + + batch_size, _, h, w = centroids_coords.shape # _ = 2 + centroids_coords = centroids_coords.permute(0, 2, 3, 1).reshape(batch_size * h * w, 1, 1, 2) + + indexed_pyramid = [] + for corr_volume in self.corr_pyramid: + sampling_coords = centroids_coords + delta # end shape is (batch_size * h * w, side_len, side_len, 2) + indexed_corr_volume = grid_sample(corr_volume, sampling_coords, align_corners=True, mode="bilinear").view( + batch_size, h, w, -1 + ) + indexed_pyramid.append(indexed_corr_volume) + centroids_coords = centroids_coords / 2 + + corr_features = torch.cat(indexed_pyramid, dim=-1).permute(0, 3, 1, 2).contiguous() + + expected_output_shape = (batch_size, self.out_channels, h, w) + if corr_features.shape != expected_output_shape: + raise ValueError( + f"Output shape of index pyramid is incorrect. Should be {expected_output_shape}, got {corr_features.shape}" + ) + + return corr_features + + def _compute_corr_volume(self, fmap1, fmap2): + batch_size, num_channels, h, w = fmap1.shape + fmap1 = fmap1.view(batch_size, num_channels, h * w) + fmap2 = fmap2.view(batch_size, num_channels, h * w) + + corr = torch.matmul(fmap1.transpose(1, 2), fmap2) + corr = corr.view(batch_size, h, w, 1, h, w) + return corr / torch.sqrt(torch.tensor(num_channels)) + + +class RAFT(nn.Module): + def __init__(self, *, feature_encoder, context_encoder, corr_block, update_block, mask_predictor=None): + """RAFT model from + `RAFT: Recurrent All Pairs Field Transforms for Optical Flow `_. + + args: + feature_encoder (nn.Module): The feature encoder. It must downsample the input by 8. + Its input is the concatenation of ``image1`` and ``image2``. + context_encoder (nn.Module): The context encoder. It must downsample the input by 8. + Its input is ``image1``. As in the original implementation, its output will be split into 2 parts: + + - one part will be used as the actual "context", passed to the recurrent unit of the ``update_block`` + - one part will be used to initialize the hidden state of the recurrent unit of + the ``update_block`` + + These 2 parts are split according to the ``hidden_state_size`` of the ``update_block``, so the output + of the ``context_encoder`` must be strictly greater than ``hidden_state_size``. + + corr_block (nn.Module): The correlation block, which creates a correlation pyramid from the output of the + ``feature_encoder``, and then indexes from this pyramid to create correlation features. It must expose + 2 methods: + + - a ``build_pyramid`` method that takes ``feature_map_1`` and ``feature_map_2`` as input (these are the + output of the ``feature_encoder``). + - a ``index_pyramid`` method that takes the coordinates of the centroid pixels as input, and returns + the correlation features. See paper section 3.2. + + It must expose an ``out_channels`` attribute. + + update_block (nn.Module): The update block, which contains the motion encoder, the recurrent unit, and the + flow head. It takes as input the hidden state of its recurrent unit, the context, the correlation + features, and the current predicted flow. It outputs an updated hidden state, and the ``delta_flow`` + prediction (see paper appendix A). It must expose a ``hidden_state_size`` attribute. + mask_predictor (nn.Module, optional): Predicts the mask that will be used to upsample the predicted flow. + The output channel must be 8 * 8 * 9 - see paper section 3.3, and Appendix B. + If ``None`` (default), the flow is upsampled using interpolation. + """ + super().__init__() + _log_api_usage_once(self) + + self.feature_encoder = feature_encoder + self.context_encoder = context_encoder + self.corr_block = corr_block + self.update_block = update_block + + self.mask_predictor = mask_predictor + + if not hasattr(self.update_block, "hidden_state_size"): + raise ValueError("The update_block parameter should expose a 'hidden_state_size' attribute.") + + def forward(self, image1, image2, num_flow_updates: int = 12): + + batch_size, _, h, w = image1.shape + if (h, w) != image2.shape[-2:]: + raise ValueError(f"input images should have the same shape, instead got ({h}, {w}) != {image2.shape[-2:]}") + if not ((h % 8 == 0) and (w % 8 == 0)): + raise ValueError(f"input image H and W should be divisible by 8, instead got {h} (h) and {w} (w)") + + fmaps = self.feature_encoder(torch.cat([image1, image2], dim=0)) + fmap1, fmap2 = torch.chunk(fmaps, chunks=2, dim=0) + if fmap1.shape[-2:] != (h // 8, w // 8): + raise ValueError("The feature encoder should downsample H and W by 8") + + self.corr_block.build_pyramid(fmap1, fmap2) + + context_out = self.context_encoder(image1) + if context_out.shape[-2:] != (h // 8, w // 8): + raise ValueError("The context encoder should downsample H and W by 8") + + # As in the original paper, the actual output of the context encoder is split in 2 parts: + # - one part is used to initialize the hidden state of the recurent units of the update block + # - the rest is the "actual" context. + hidden_state_size = self.update_block.hidden_state_size + out_channels_context = context_out.shape[1] - hidden_state_size + if out_channels_context <= 0: + raise ValueError( + f"The context encoder outputs {context_out.shape[1]} channels, but it should have at strictly more than hidden_state={hidden_state_size} channels" + ) + hidden_state, context = torch.split(context_out, [hidden_state_size, out_channels_context], dim=1) + hidden_state = torch.tanh(hidden_state) + context = F.relu(context) + + coords0 = make_coords_grid(batch_size, h // 8, w // 8).to(fmap1.device) + coords1 = make_coords_grid(batch_size, h // 8, w // 8).to(fmap1.device) + + flow_predictions = [] + for _ in range(num_flow_updates): + coords1 = coords1.detach() # Don't backpropagate gradients through this branch, see paper + corr_features = self.corr_block.index_pyramid(centroids_coords=coords1) + + flow = coords1 - coords0 + hidden_state, delta_flow = self.update_block(hidden_state, context, corr_features, flow) + + coords1 = coords1 + delta_flow + + up_mask = None if self.mask_predictor is None else self.mask_predictor(hidden_state) + upsampled_flow = upsample_flow(flow=(coords1 - coords0), up_mask=up_mask) + flow_predictions.append(upsampled_flow) + + return flow_predictions + + +_COMMON_META = { + "min_size": (128, 128), +} + + +class Raft_Large_Weights(WeightsEnum): + """The metrics reported here are as follows. + + ``epe`` is the "end-point-error" and indicates how far (in pixels) the + predicted flow is from its true value. This is averaged over all pixels + of all images. ``per_image_epe`` is similar, but the average is different: + the epe is first computed on each image independently, and then averaged + over all images. This corresponds to "Fl-epe" (sometimes written "F1-epe") + in the original paper, and it's only used on Kitti. ``fl-all`` is also a + Kitti-specific metric, defined by the author of the dataset and used for the + Kitti leaderboard. It corresponds to the average of pixels whose epe is + either <3px, or <5% of flow's 2-norm. + """ + + C_T_V1 = Weights( + # Weights ported from https://github.com/princeton-vl/RAFT + url="https://download.pytorch.org/models/raft_large_C_T_V1-22a6c225.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 5257536, + "recipe": "https://github.com/princeton-vl/RAFT", + "_metrics": { + "Sintel-Train-Cleanpass": {"epe": 1.4411}, + "Sintel-Train-Finalpass": {"epe": 2.7894}, + "Kitti-Train": {"per_image_epe": 5.0172, "fl_all": 17.4506}, + }, + "_ops": 211.007, + "_file_size": 20.129, + "_docs": """These weights were ported from the original paper. They + are trained on :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D`.""", + }, + ) + + C_T_V2 = Weights( + url="https://download.pytorch.org/models/raft_large_C_T_V2-1bb1363a.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 5257536, + "recipe": "https://github.com/pytorch/vision/tree/main/references/optical_flow", + "_metrics": { + "Sintel-Train-Cleanpass": {"epe": 1.3822}, + "Sintel-Train-Finalpass": {"epe": 2.7161}, + "Kitti-Train": {"per_image_epe": 4.5118, "fl_all": 16.0679}, + }, + "_ops": 211.007, + "_file_size": 20.129, + "_docs": """These weights were trained from scratch on + :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D`.""", + }, + ) + + C_T_SKHT_V1 = Weights( + # Weights ported from https://github.com/princeton-vl/RAFT + url="https://download.pytorch.org/models/raft_large_C_T_SKHT_V1-0b8c9e55.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 5257536, + "recipe": "https://github.com/princeton-vl/RAFT", + "_metrics": { + "Sintel-Test-Cleanpass": {"epe": 1.94}, + "Sintel-Test-Finalpass": {"epe": 3.18}, + }, + "_ops": 211.007, + "_file_size": 20.129, + "_docs": """ + These weights were ported from the original paper. They are + trained on :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D` and fine-tuned on + Sintel. The Sintel fine-tuning step is a combination of + :class:`~torchvision.datasets.Sintel`, + :class:`~torchvision.datasets.KittiFlow`, + :class:`~torchvision.datasets.HD1K`, and + :class:`~torchvision.datasets.FlyingThings3D` (clean pass). + """, + }, + ) + + C_T_SKHT_V2 = Weights( + url="https://download.pytorch.org/models/raft_large_C_T_SKHT_V2-ff5fadd5.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 5257536, + "recipe": "https://github.com/pytorch/vision/tree/main/references/optical_flow", + "_metrics": { + "Sintel-Test-Cleanpass": {"epe": 1.819}, + "Sintel-Test-Finalpass": {"epe": 3.067}, + }, + "_ops": 211.007, + "_file_size": 20.129, + "_docs": """ + These weights were trained from scratch. They are + pre-trained on :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D` and then + fine-tuned on Sintel. The Sintel fine-tuning step is a + combination of :class:`~torchvision.datasets.Sintel`, + :class:`~torchvision.datasets.KittiFlow`, + :class:`~torchvision.datasets.HD1K`, and + :class:`~torchvision.datasets.FlyingThings3D` (clean pass). + """, + }, + ) + + C_T_SKHT_K_V1 = Weights( + # Weights ported from https://github.com/princeton-vl/RAFT + url="https://download.pytorch.org/models/raft_large_C_T_SKHT_K_V1-4a6a5039.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 5257536, + "recipe": "https://github.com/princeton-vl/RAFT", + "_metrics": { + "Kitti-Test": {"fl_all": 5.10}, + }, + "_ops": 211.007, + "_file_size": 20.129, + "_docs": """ + These weights were ported from the original paper. They are + pre-trained on :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D`, + fine-tuned on Sintel, and then fine-tuned on + :class:`~torchvision.datasets.KittiFlow`. The Sintel fine-tuning + step was described above. + """, + }, + ) + + C_T_SKHT_K_V2 = Weights( + url="https://download.pytorch.org/models/raft_large_C_T_SKHT_K_V2-b5c70766.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 5257536, + "recipe": "https://github.com/pytorch/vision/tree/main/references/optical_flow", + "_metrics": { + "Kitti-Test": {"fl_all": 5.19}, + }, + "_ops": 211.007, + "_file_size": 20.129, + "_docs": """ + These weights were trained from scratch. They are + pre-trained on :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D`, + fine-tuned on Sintel, and then fine-tuned on + :class:`~torchvision.datasets.KittiFlow`. The Sintel fine-tuning + step was described above. + """, + }, + ) + + DEFAULT = C_T_SKHT_V2 + + +class Raft_Small_Weights(WeightsEnum): + """The metrics reported here are as follows. + + ``epe`` is the "end-point-error" and indicates how far (in pixels) the + predicted flow is from its true value. This is averaged over all pixels + of all images. ``per_image_epe`` is similar, but the average is different: + the epe is first computed on each image independently, and then averaged + over all images. This corresponds to "Fl-epe" (sometimes written "F1-epe") + in the original paper, and it's only used on Kitti. ``fl-all`` is also a + Kitti-specific metric, defined by the author of the dataset and used for the + Kitti leaderboard. It corresponds to the average of pixels whose epe is + either <3px, or <5% of flow's 2-norm. + """ + + C_T_V1 = Weights( + # Weights ported from https://github.com/princeton-vl/RAFT + url="https://download.pytorch.org/models/raft_small_C_T_V1-ad48884c.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 990162, + "recipe": "https://github.com/princeton-vl/RAFT", + "_metrics": { + "Sintel-Train-Cleanpass": {"epe": 2.1231}, + "Sintel-Train-Finalpass": {"epe": 3.2790}, + "Kitti-Train": {"per_image_epe": 7.6557, "fl_all": 25.2801}, + }, + "_ops": 47.655, + "_file_size": 3.821, + "_docs": """These weights were ported from the original paper. They + are trained on :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D`.""", + }, + ) + C_T_V2 = Weights( + url="https://download.pytorch.org/models/raft_small_C_T_V2-01064c6d.pth", + transforms=OpticalFlow, + meta={ + **_COMMON_META, + "num_params": 990162, + "recipe": "https://github.com/pytorch/vision/tree/main/references/optical_flow", + "_metrics": { + "Sintel-Train-Cleanpass": {"epe": 1.9901}, + "Sintel-Train-Finalpass": {"epe": 3.2831}, + "Kitti-Train": {"per_image_epe": 7.5978, "fl_all": 25.2369}, + }, + "_ops": 47.655, + "_file_size": 3.821, + "_docs": """These weights were trained from scratch on + :class:`~torchvision.datasets.FlyingChairs` + + :class:`~torchvision.datasets.FlyingThings3D`.""", + }, + ) + + DEFAULT = C_T_V2 + + +def _raft( + *, + weights=None, + progress=False, + # Feature encoder + feature_encoder_layers, + feature_encoder_block, + feature_encoder_norm_layer, + # Context encoder + context_encoder_layers, + context_encoder_block, + context_encoder_norm_layer, + # Correlation block + corr_block_num_levels, + corr_block_radius, + # Motion encoder + motion_encoder_corr_layers, + motion_encoder_flow_layers, + motion_encoder_out_channels, + # Recurrent block + recurrent_block_hidden_state_size, + recurrent_block_kernel_size, + recurrent_block_padding, + # Flow Head + flow_head_hidden_size, + # Mask predictor + use_mask_predictor, + **kwargs, +): + feature_encoder = kwargs.pop("feature_encoder", None) or FeatureEncoder( + block=feature_encoder_block, layers=feature_encoder_layers, norm_layer=feature_encoder_norm_layer + ) + context_encoder = kwargs.pop("context_encoder", None) or FeatureEncoder( + block=context_encoder_block, layers=context_encoder_layers, norm_layer=context_encoder_norm_layer + ) + + corr_block = kwargs.pop("corr_block", None) or CorrBlock(num_levels=corr_block_num_levels, radius=corr_block_radius) + + update_block = kwargs.pop("update_block", None) + if update_block is None: + motion_encoder = MotionEncoder( + in_channels_corr=corr_block.out_channels, + corr_layers=motion_encoder_corr_layers, + flow_layers=motion_encoder_flow_layers, + out_channels=motion_encoder_out_channels, + ) + + # See comments in forward pass of RAFT class about why we split the output of the context encoder + out_channels_context = context_encoder_layers[-1] - recurrent_block_hidden_state_size + recurrent_block = RecurrentBlock( + input_size=motion_encoder.out_channels + out_channels_context, + hidden_size=recurrent_block_hidden_state_size, + kernel_size=recurrent_block_kernel_size, + padding=recurrent_block_padding, + ) + + flow_head = FlowHead(in_channels=recurrent_block_hidden_state_size, hidden_size=flow_head_hidden_size) + + update_block = UpdateBlock(motion_encoder=motion_encoder, recurrent_block=recurrent_block, flow_head=flow_head) + + mask_predictor = kwargs.pop("mask_predictor", None) + if mask_predictor is None and use_mask_predictor: + mask_predictor = MaskPredictor( + in_channels=recurrent_block_hidden_state_size, + hidden_size=256, + multiplier=0.25, # See comment in MaskPredictor about this + ) + + model = RAFT( + feature_encoder=feature_encoder, + context_encoder=context_encoder, + corr_block=corr_block, + update_block=update_block, + mask_predictor=mask_predictor, + **kwargs, # not really needed, all params should be consumed by now + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Raft_Large_Weights.C_T_SKHT_V2)) +def raft_large(*, weights: Optional[Raft_Large_Weights] = None, progress=True, **kwargs) -> RAFT: + """RAFT model from + `RAFT: Recurrent All Pairs Field Transforms for Optical Flow `_. + + Please see the example below for a tutorial on how to use this model. + + Args: + weights(:class:`~torchvision.models.optical_flow.Raft_Large_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.optical_flow.Raft_Large_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.optical_flow.RAFT`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.optical_flow.Raft_Large_Weights + :members: + """ + + weights = Raft_Large_Weights.verify(weights) + + return _raft( + weights=weights, + progress=progress, + # Feature encoder + feature_encoder_layers=(64, 64, 96, 128, 256), + feature_encoder_block=ResidualBlock, + feature_encoder_norm_layer=InstanceNorm2d, + # Context encoder + context_encoder_layers=(64, 64, 96, 128, 256), + context_encoder_block=ResidualBlock, + context_encoder_norm_layer=BatchNorm2d, + # Correlation block + corr_block_num_levels=4, + corr_block_radius=4, + # Motion encoder + motion_encoder_corr_layers=(256, 192), + motion_encoder_flow_layers=(128, 64), + motion_encoder_out_channels=128, + # Recurrent block + recurrent_block_hidden_state_size=128, + recurrent_block_kernel_size=((1, 5), (5, 1)), + recurrent_block_padding=((0, 2), (2, 0)), + # Flow head + flow_head_hidden_size=256, + # Mask predictor + use_mask_predictor=True, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Raft_Small_Weights.C_T_V2)) +def raft_small(*, weights: Optional[Raft_Small_Weights] = None, progress=True, **kwargs) -> RAFT: + """RAFT "small" model from + `RAFT: Recurrent All Pairs Field Transforms for Optical Flow `__. + + Please see the example below for a tutorial on how to use this model. + + Args: + weights(:class:`~torchvision.models.optical_flow.Raft_Small_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.optical_flow.Raft_Small_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.optical_flow.RAFT`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.optical_flow.Raft_Small_Weights + :members: + """ + weights = Raft_Small_Weights.verify(weights) + + return _raft( + weights=weights, + progress=progress, + # Feature encoder + feature_encoder_layers=(32, 32, 64, 96, 128), + feature_encoder_block=BottleneckBlock, + feature_encoder_norm_layer=InstanceNorm2d, + # Context encoder + context_encoder_layers=(32, 32, 64, 96, 160), + context_encoder_block=BottleneckBlock, + context_encoder_norm_layer=None, + # Correlation block + corr_block_num_levels=4, + corr_block_radius=3, + # Motion encoder + motion_encoder_corr_layers=(96,), + motion_encoder_flow_layers=(64, 32), + motion_encoder_out_channels=82, + # Recurrent block + recurrent_block_hidden_state_size=96, + recurrent_block_kernel_size=(3,), + recurrent_block_padding=(1,), + # Flow head + flow_head_hidden_size=128, + # Mask predictor + use_mask_predictor=False, + **kwargs, + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..da8bbba3567b0b9110429354d89b65ec679a2fd5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__init__.py @@ -0,0 +1,5 @@ +from .googlenet import * +from .inception import * +from .mobilenet import * +from .resnet import * +from .shufflenetv2 import * diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..008d3770d4cd302d78ce9323f04833646a53199e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/googlenet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/googlenet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26cde68eef0316d8f9907fc0d218eab9442070bf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/googlenet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/inception.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/inception.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f985560965d12090f3b363cd34e10968c9ebff31 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/inception.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/mobilenet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/mobilenet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5ced09632208bb41c089c21c7035d6a3054327e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/mobilenet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/mobilenetv2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/mobilenetv2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1280a037711e17d4f89c55fad9717c28cfb448ee Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/mobilenetv2.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/mobilenetv3.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/mobilenetv3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef4253569bc5ef2f722afdba1d752fbc00c08467 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/mobilenetv3.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/resnet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/resnet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71da5484878b9dae7e67d8eb3c70331fb7f24484 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/resnet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/shufflenetv2.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/shufflenetv2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2aeee26ea4f102a9bb90308f2a0f2707eefe8f5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/shufflenetv2.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a6d73aaf14a25359b6431fddc3861d8217c35e6 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/googlenet.py b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/googlenet.py new file mode 100644 index 0000000000000000000000000000000000000000..49ec1a340dd70cf0a03f101e6b4efa6229c5431b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/googlenet.py @@ -0,0 +1,212 @@ +import warnings +from functools import partial +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +from torch import Tensor +from torch.nn import functional as F + +from ...transforms._presets import ImageClassification +from .._api import register_model, Weights, WeightsEnum +from .._meta import _IMAGENET_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from ..googlenet import BasicConv2d, GoogLeNet, GoogLeNet_Weights, GoogLeNetOutputs, Inception, InceptionAux +from .utils import _fuse_modules, _replace_relu, quantize_model + + +__all__ = [ + "QuantizableGoogLeNet", + "GoogLeNet_QuantizedWeights", + "googlenet", +] + + +class QuantizableBasicConv2d(BasicConv2d): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.relu = nn.ReLU() + + def forward(self, x: Tensor) -> Tensor: + x = self.conv(x) + x = self.bn(x) + x = self.relu(x) + return x + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + _fuse_modules(self, ["conv", "bn", "relu"], is_qat, inplace=True) + + +class QuantizableInception(Inception): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + self.cat = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return self.cat.cat(outputs, 1) + + +class QuantizableInceptionAux(InceptionAux): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + self.relu = nn.ReLU() + + def forward(self, x: Tensor) -> Tensor: + # aux1: N x 512 x 14 x 14, aux2: N x 528 x 14 x 14 + x = F.adaptive_avg_pool2d(x, (4, 4)) + # aux1: N x 512 x 4 x 4, aux2: N x 528 x 4 x 4 + x = self.conv(x) + # N x 128 x 4 x 4 + x = torch.flatten(x, 1) + # N x 2048 + x = self.relu(self.fc1(x)) + # N x 1024 + x = self.dropout(x) + # N x 1024 + x = self.fc2(x) + # N x 1000 (num_classes) + + return x + + +class QuantizableGoogLeNet(GoogLeNet): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__( # type: ignore[misc] + *args, blocks=[QuantizableBasicConv2d, QuantizableInception, QuantizableInceptionAux], **kwargs + ) + self.quant = torch.ao.quantization.QuantStub() + self.dequant = torch.ao.quantization.DeQuantStub() + + def forward(self, x: Tensor) -> GoogLeNetOutputs: + x = self._transform_input(x) + x = self.quant(x) + x, aux1, aux2 = self._forward(x) + x = self.dequant(x) + aux_defined = self.training and self.aux_logits + if torch.jit.is_scripting(): + if not aux_defined: + warnings.warn("Scripted QuantizableGoogleNet always returns GoogleNetOutputs Tuple") + return GoogLeNetOutputs(x, aux2, aux1) + else: + return self.eager_outputs(x, aux2, aux1) + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + r"""Fuse conv/bn/relu modules in googlenet model + + Fuse conv+bn+relu/ conv+relu/conv+bn modules to prepare for quantization. + Model is modified in place. Note that this operation does not change numerics + and the model after modification is in floating point + """ + + for m in self.modules(): + if type(m) is QuantizableBasicConv2d: + m.fuse_model(is_qat) + + +class GoogLeNet_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/googlenet_fbgemm-c81f6644.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + "num_params": 6624904, + "min_size": (15, 15), + "categories": _IMAGENET_CATEGORIES, + "backend": "fbgemm", + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models", + "unquantized": GoogLeNet_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 69.826, + "acc@5": 89.404, + } + }, + "_ops": 1.498, + "_file_size": 12.618, + "_docs": """ + These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized + weights listed below. + """, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +@register_model(name="quantized_googlenet") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + GoogLeNet_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else GoogLeNet_Weights.IMAGENET1K_V1 + ), + ) +) +def googlenet( + *, + weights: Optional[Union[GoogLeNet_QuantizedWeights, GoogLeNet_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableGoogLeNet: + """GoogLeNet (Inception v1) model architecture from `Going Deeper with Convolutions `__. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.GoogLeNet_QuantizedWeights` or :class:`~torchvision.models.GoogLeNet_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.GoogLeNet_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + quantize (bool, optional): If True, return a quantized version of the model. Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableGoogLeNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.GoogLeNet_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.GoogLeNet_Weights + :members: + :noindex: + """ + weights = (GoogLeNet_QuantizedWeights if quantize else GoogLeNet_Weights).verify(weights) + + original_aux_logits = kwargs.get("aux_logits", False) + if weights is not None: + if "transform_input" not in kwargs: + _ovewrite_named_param(kwargs, "transform_input", True) + _ovewrite_named_param(kwargs, "aux_logits", True) + _ovewrite_named_param(kwargs, "init_weights", False) + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + if "backend" in weights.meta: + _ovewrite_named_param(kwargs, "backend", weights.meta["backend"]) + backend = kwargs.pop("backend", "fbgemm") + + model = QuantizableGoogLeNet(**kwargs) + _replace_relu(model) + if quantize: + quantize_model(model, backend) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if not original_aux_logits: + model.aux_logits = False + model.aux1 = None # type: ignore[assignment] + model.aux2 = None # type: ignore[assignment] + else: + warnings.warn( + "auxiliary heads in the pretrained googlenet model are NOT pretrained, so make sure to train them" + ) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/inception.py b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/inception.py new file mode 100644 index 0000000000000000000000000000000000000000..a6eb9370d0d6a178f63f76b2acf4266a6ac4556d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/inception.py @@ -0,0 +1,275 @@ +import warnings +from functools import partial +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor +from torchvision.models import inception as inception_module +from torchvision.models.inception import Inception_V3_Weights, InceptionOutputs + +from ...transforms._presets import ImageClassification +from .._api import register_model, Weights, WeightsEnum +from .._meta import _IMAGENET_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from .utils import _fuse_modules, _replace_relu, quantize_model + + +__all__ = [ + "QuantizableInception3", + "Inception_V3_QuantizedWeights", + "inception_v3", +] + + +class QuantizableBasicConv2d(inception_module.BasicConv2d): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.relu = nn.ReLU() + + def forward(self, x: Tensor) -> Tensor: + x = self.conv(x) + x = self.bn(x) + x = self.relu(x) + return x + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + _fuse_modules(self, ["conv", "bn", "relu"], is_qat, inplace=True) + + +class QuantizableInceptionA(inception_module.InceptionA): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + self.myop = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return self.myop.cat(outputs, 1) + + +class QuantizableInceptionB(inception_module.InceptionB): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + self.myop = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return self.myop.cat(outputs, 1) + + +class QuantizableInceptionC(inception_module.InceptionC): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + self.myop = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return self.myop.cat(outputs, 1) + + +class QuantizableInceptionD(inception_module.InceptionD): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + self.myop = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return self.myop.cat(outputs, 1) + + +class QuantizableInceptionE(inception_module.InceptionE): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + self.myop1 = nn.quantized.FloatFunctional() + self.myop2 = nn.quantized.FloatFunctional() + self.myop3 = nn.quantized.FloatFunctional() + + def _forward(self, x: Tensor) -> list[Tensor]: + branch1x1 = self.branch1x1(x) + + branch3x3 = self.branch3x3_1(x) + branch3x3 = [self.branch3x3_2a(branch3x3), self.branch3x3_2b(branch3x3)] + branch3x3 = self.myop1.cat(branch3x3, 1) + + branch3x3dbl = self.branch3x3dbl_1(x) + branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) + branch3x3dbl = [ + self.branch3x3dbl_3a(branch3x3dbl), + self.branch3x3dbl_3b(branch3x3dbl), + ] + branch3x3dbl = self.myop2.cat(branch3x3dbl, 1) + + branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) + branch_pool = self.branch_pool(branch_pool) + + outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool] + return outputs + + def forward(self, x: Tensor) -> Tensor: + outputs = self._forward(x) + return self.myop3.cat(outputs, 1) + + +class QuantizableInceptionAux(inception_module.InceptionAux): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) # type: ignore[misc] + + +class QuantizableInception3(inception_module.Inception3): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__( # type: ignore[misc] + *args, + inception_blocks=[ + QuantizableBasicConv2d, + QuantizableInceptionA, + QuantizableInceptionB, + QuantizableInceptionC, + QuantizableInceptionD, + QuantizableInceptionE, + QuantizableInceptionAux, + ], + **kwargs, + ) + self.quant = torch.ao.quantization.QuantStub() + self.dequant = torch.ao.quantization.DeQuantStub() + + def forward(self, x: Tensor) -> InceptionOutputs: + x = self._transform_input(x) + x = self.quant(x) + x, aux = self._forward(x) + x = self.dequant(x) + aux_defined = self.training and self.aux_logits + if torch.jit.is_scripting(): + if not aux_defined: + warnings.warn("Scripted QuantizableInception3 always returns QuantizableInception3 Tuple") + return InceptionOutputs(x, aux) + else: + return self.eager_outputs(x, aux) + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + r"""Fuse conv/bn/relu modules in inception model + + Fuse conv+bn+relu/ conv+relu/conv+bn modules to prepare for quantization. + Model is modified in place. Note that this operation does not change numerics + and the model after modification is in floating point + """ + + for m in self.modules(): + if type(m) is QuantizableBasicConv2d: + m.fuse_model(is_qat) + + +class Inception_V3_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/inception_v3_google_fbgemm-a2837893.pth", + transforms=partial(ImageClassification, crop_size=299, resize_size=342), + meta={ + "num_params": 27161264, + "min_size": (75, 75), + "categories": _IMAGENET_CATEGORIES, + "backend": "fbgemm", + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models", + "unquantized": Inception_V3_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.176, + "acc@5": 93.354, + } + }, + "_ops": 5.713, + "_file_size": 23.146, + "_docs": """ + These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized + weights listed below. + """, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +@register_model(name="quantized_inception_v3") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + Inception_V3_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else Inception_V3_Weights.IMAGENET1K_V1 + ), + ) +) +def inception_v3( + *, + weights: Optional[Union[Inception_V3_QuantizedWeights, Inception_V3_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableInception3: + r"""Inception v3 model architecture from + `Rethinking the Inception Architecture for Computer Vision `__. + + .. note:: + **Important**: In contrast to the other models the inception_v3 expects tensors with a size of + N x 3 x 299 x 299, so ensure your images are sized accordingly. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.Inception_V3_QuantizedWeights` or :class:`~torchvision.models.Inception_V3_Weights`, optional): The pretrained + weights for the model. See + :class:`~torchvision.models.quantization.Inception_V3_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. + Default is True. + quantize (bool, optional): If True, return a quantized version of the model. + Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableInception3`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.Inception_V3_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.Inception_V3_Weights + :members: + :noindex: + """ + weights = (Inception_V3_QuantizedWeights if quantize else Inception_V3_Weights).verify(weights) + + original_aux_logits = kwargs.get("aux_logits", False) + if weights is not None: + if "transform_input" not in kwargs: + _ovewrite_named_param(kwargs, "transform_input", True) + _ovewrite_named_param(kwargs, "aux_logits", True) + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + if "backend" in weights.meta: + _ovewrite_named_param(kwargs, "backend", weights.meta["backend"]) + backend = kwargs.pop("backend", "fbgemm") + + model = QuantizableInception3(**kwargs) + _replace_relu(model) + if quantize: + quantize_model(model, backend) + + if weights is not None: + if quantize and not original_aux_logits: + model.aux_logits = False + model.AuxLogits = None + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + if not quantize and not original_aux_logits: + model.aux_logits = False + model.AuxLogits = None + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/mobilenet.py b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/mobilenet.py new file mode 100644 index 0000000000000000000000000000000000000000..0a270d14d3a4ad9eda62b68c2c01e9fdb710ef38 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/mobilenet.py @@ -0,0 +1,6 @@ +from .mobilenetv2 import * # noqa: F401, F403 +from .mobilenetv3 import * # noqa: F401, F403 +from .mobilenetv2 import __all__ as mv2_all +from .mobilenetv3 import __all__ as mv3_all + +__all__ = mv2_all + mv3_all diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/mobilenetv2.py b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/mobilenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..d1cef2d94136eecae20cd33d9b1de7f34eece1bc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/mobilenetv2.py @@ -0,0 +1,156 @@ +from functools import partial +from typing import Any, Optional, Union + +from torch import nn, Tensor +from torch.ao.quantization import DeQuantStub, QuantStub +from torchvision.models.mobilenetv2 import InvertedResidual, MobileNet_V2_Weights, MobileNetV2 + +from ...ops.misc import Conv2dNormActivation +from ...transforms._presets import ImageClassification +from .._api import register_model, Weights, WeightsEnum +from .._meta import _IMAGENET_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from .utils import _fuse_modules, _replace_relu, quantize_model + + +__all__ = [ + "QuantizableMobileNetV2", + "MobileNet_V2_QuantizedWeights", + "mobilenet_v2", +] + + +class QuantizableInvertedResidual(InvertedResidual): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + if self.use_res_connect: + return self.skip_add.add(x, self.conv(x)) + else: + return self.conv(x) + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + for idx in range(len(self.conv)): + if type(self.conv[idx]) is nn.Conv2d: + _fuse_modules(self.conv, [str(idx), str(idx + 1)], is_qat, inplace=True) + + +class QuantizableMobileNetV2(MobileNetV2): + def __init__(self, *args: Any, **kwargs: Any) -> None: + """ + MobileNet V2 main class + + Args: + Inherits args from floating point MobileNetV2 + """ + super().__init__(*args, **kwargs) + self.quant = QuantStub() + self.dequant = DeQuantStub() + + def forward(self, x: Tensor) -> Tensor: + x = self.quant(x) + x = self._forward_impl(x) + x = self.dequant(x) + return x + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + for m in self.modules(): + if type(m) is Conv2dNormActivation: + _fuse_modules(m, ["0", "1", "2"], is_qat, inplace=True) + if type(m) is QuantizableInvertedResidual: + m.fuse_model(is_qat) + + +class MobileNet_V2_QuantizedWeights(WeightsEnum): + IMAGENET1K_QNNPACK_V1 = Weights( + url="https://download.pytorch.org/models/quantized/mobilenet_v2_qnnpack_37f702c5.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + "num_params": 3504872, + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, + "backend": "qnnpack", + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#qat-mobilenetv2", + "unquantized": MobileNet_V2_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 71.658, + "acc@5": 90.150, + } + }, + "_ops": 0.301, + "_file_size": 3.423, + "_docs": """ + These weights were produced by doing Quantization Aware Training (eager mode) on top of the unquantized + weights listed below. + """, + }, + ) + DEFAULT = IMAGENET1K_QNNPACK_V1 + + +@register_model(name="quantized_mobilenet_v2") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + MobileNet_V2_QuantizedWeights.IMAGENET1K_QNNPACK_V1 + if kwargs.get("quantize", False) + else MobileNet_V2_Weights.IMAGENET1K_V1 + ), + ) +) +def mobilenet_v2( + *, + weights: Optional[Union[MobileNet_V2_QuantizedWeights, MobileNet_V2_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableMobileNetV2: + """ + Constructs a MobileNetV2 architecture from + `MobileNetV2: Inverted Residuals and Linear Bottlenecks + `_. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.MobileNet_V2_QuantizedWeights` or :class:`~torchvision.models.MobileNet_V2_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.MobileNet_V2_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + quantize (bool, optional): If True, returns a quantized version of the model. Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableMobileNetV2`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.quantization.MobileNet_V2_QuantizedWeights + :members: + .. autoclass:: torchvision.models.MobileNet_V2_Weights + :members: + :noindex: + """ + weights = (MobileNet_V2_QuantizedWeights if quantize else MobileNet_V2_Weights).verify(weights) + + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + if "backend" in weights.meta: + _ovewrite_named_param(kwargs, "backend", weights.meta["backend"]) + backend = kwargs.pop("backend", "qnnpack") + + model = QuantizableMobileNetV2(block=QuantizableInvertedResidual, **kwargs) + _replace_relu(model) + if quantize: + quantize_model(model, backend) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/mobilenetv3.py b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/mobilenetv3.py new file mode 100644 index 0000000000000000000000000000000000000000..7431b07df85d930c411979691c865b160316bd7b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/mobilenetv3.py @@ -0,0 +1,239 @@ +from functools import partial +from typing import Any, Optional, Union + +import torch +from torch import nn, Tensor +from torch.ao.quantization import DeQuantStub, QuantStub + +from ...ops.misc import Conv2dNormActivation, SqueezeExcitation +from ...transforms._presets import ImageClassification +from .._api import register_model, Weights, WeightsEnum +from .._meta import _IMAGENET_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from ..mobilenetv3 import ( + _mobilenet_v3_conf, + InvertedResidual, + InvertedResidualConfig, + MobileNet_V3_Large_Weights, + MobileNetV3, +) +from .utils import _fuse_modules, _replace_relu + + +__all__ = [ + "QuantizableMobileNetV3", + "MobileNet_V3_Large_QuantizedWeights", + "mobilenet_v3_large", +] + + +class QuantizableSqueezeExcitation(SqueezeExcitation): + _version = 2 + + def __init__(self, *args: Any, **kwargs: Any) -> None: + kwargs["scale_activation"] = nn.Hardsigmoid + super().__init__(*args, **kwargs) + self.skip_mul = nn.quantized.FloatFunctional() + + def forward(self, input: Tensor) -> Tensor: + return self.skip_mul.mul(self._scale(input), input) + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + _fuse_modules(self, ["fc1", "activation"], is_qat, inplace=True) + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if hasattr(self, "qconfig") and (version is None or version < 2): + default_state_dict = { + "scale_activation.activation_post_process.scale": torch.tensor([1.0]), + "scale_activation.activation_post_process.activation_post_process.scale": torch.tensor([1.0]), + "scale_activation.activation_post_process.zero_point": torch.tensor([0], dtype=torch.int32), + "scale_activation.activation_post_process.activation_post_process.zero_point": torch.tensor( + [0], dtype=torch.int32 + ), + "scale_activation.activation_post_process.fake_quant_enabled": torch.tensor([1]), + "scale_activation.activation_post_process.observer_enabled": torch.tensor([1]), + } + for k, v in default_state_dict.items(): + full_key = prefix + k + if full_key not in state_dict: + state_dict[full_key] = v + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + +class QuantizableInvertedResidual(InvertedResidual): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, se_layer=QuantizableSqueezeExcitation, **kwargs) # type: ignore[misc] + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + if self.use_res_connect: + return self.skip_add.add(x, self.block(x)) + else: + return self.block(x) + + +class QuantizableMobileNetV3(MobileNetV3): + def __init__(self, *args: Any, **kwargs: Any) -> None: + """ + MobileNet V3 main class + + Args: + Inherits args from floating point MobileNetV3 + """ + super().__init__(*args, **kwargs) + self.quant = QuantStub() + self.dequant = DeQuantStub() + + def forward(self, x: Tensor) -> Tensor: + x = self.quant(x) + x = self._forward_impl(x) + x = self.dequant(x) + return x + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + for m in self.modules(): + if type(m) is Conv2dNormActivation: + modules_to_fuse = ["0", "1"] + if len(m) == 3 and type(m[2]) is nn.ReLU: + modules_to_fuse.append("2") + _fuse_modules(m, modules_to_fuse, is_qat, inplace=True) + elif type(m) is QuantizableSqueezeExcitation: + m.fuse_model(is_qat) + + +def _mobilenet_v3_model( + inverted_residual_setting: list[InvertedResidualConfig], + last_channel: int, + weights: Optional[WeightsEnum], + progress: bool, + quantize: bool, + **kwargs: Any, +) -> QuantizableMobileNetV3: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + if "backend" in weights.meta: + _ovewrite_named_param(kwargs, "backend", weights.meta["backend"]) + backend = kwargs.pop("backend", "qnnpack") + + model = QuantizableMobileNetV3(inverted_residual_setting, last_channel, block=QuantizableInvertedResidual, **kwargs) + _replace_relu(model) + + if quantize: + # Instead of quantizing the model and then loading the quantized weights we take a different approach. + # We prepare the QAT model, load the QAT weights from training and then convert it. + # This is done to avoid extremely low accuracies observed on the specific model. This is rather a workaround + # for an unresolved bug on the eager quantization API detailed at: https://github.com/pytorch/vision/issues/5890 + model.fuse_model(is_qat=True) + model.qconfig = torch.ao.quantization.get_default_qat_qconfig(backend) + torch.ao.quantization.prepare_qat(model, inplace=True) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + if quantize: + torch.ao.quantization.convert(model, inplace=True) + model.eval() + + return model + + +class MobileNet_V3_Large_QuantizedWeights(WeightsEnum): + IMAGENET1K_QNNPACK_V1 = Weights( + url="https://download.pytorch.org/models/quantized/mobilenet_v3_large_qnnpack-5bcacf28.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + "num_params": 5483032, + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, + "backend": "qnnpack", + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#qat-mobilenetv3", + "unquantized": MobileNet_V3_Large_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 73.004, + "acc@5": 90.858, + } + }, + "_ops": 0.217, + "_file_size": 21.554, + "_docs": """ + These weights were produced by doing Quantization Aware Training (eager mode) on top of the unquantized + weights listed below. + """, + }, + ) + DEFAULT = IMAGENET1K_QNNPACK_V1 + + +@register_model(name="quantized_mobilenet_v3_large") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + MobileNet_V3_Large_QuantizedWeights.IMAGENET1K_QNNPACK_V1 + if kwargs.get("quantize", False) + else MobileNet_V3_Large_Weights.IMAGENET1K_V1 + ), + ) +) +def mobilenet_v3_large( + *, + weights: Optional[Union[MobileNet_V3_Large_QuantizedWeights, MobileNet_V3_Large_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableMobileNetV3: + """ + MobileNetV3 (Large) model from + `Searching for MobileNetV3 `_. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.MobileNet_V3_Large_QuantizedWeights` or :class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.MobileNet_V3_Large_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool): If True, displays a progress bar of the + download to stderr. Default is True. + quantize (bool): If True, return a quantized version of the model. Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.MobileNet_V3_Large_QuantizedWeights`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.MobileNet_V3_Large_QuantizedWeights + :members: + .. autoclass:: torchvision.models.MobileNet_V3_Large_Weights + :members: + :noindex: + """ + weights = (MobileNet_V3_Large_QuantizedWeights if quantize else MobileNet_V3_Large_Weights).verify(weights) + + inverted_residual_setting, last_channel = _mobilenet_v3_conf("mobilenet_v3_large", **kwargs) + return _mobilenet_v3_model(inverted_residual_setting, last_channel, weights, progress, quantize, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/resnet.py b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..bc4ba003b6a3cba1e3f2efd9c3f070d439b1f7dd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/resnet.py @@ -0,0 +1,492 @@ +from functools import partial +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +from torch import Tensor +from torchvision.models.resnet import ( + BasicBlock, + Bottleneck, + ResNet, + ResNet18_Weights, + ResNet50_Weights, + ResNeXt101_32X8D_Weights, + ResNeXt101_64X4D_Weights, +) + +from ...transforms._presets import ImageClassification +from .._api import register_model, Weights, WeightsEnum +from .._meta import _IMAGENET_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from .utils import _fuse_modules, _replace_relu, quantize_model + + +__all__ = [ + "QuantizableResNet", + "ResNet18_QuantizedWeights", + "ResNet50_QuantizedWeights", + "ResNeXt101_32X8D_QuantizedWeights", + "ResNeXt101_64X4D_QuantizedWeights", + "resnet18", + "resnet50", + "resnext101_32x8d", + "resnext101_64x4d", +] + + +class QuantizableBasicBlock(BasicBlock): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.add_relu = torch.nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + identity = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + identity = self.downsample(x) + + out = self.add_relu.add_relu(out, identity) + + return out + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + _fuse_modules(self, [["conv1", "bn1", "relu"], ["conv2", "bn2"]], is_qat, inplace=True) + if self.downsample: + _fuse_modules(self.downsample, ["0", "1"], is_qat, inplace=True) + + +class QuantizableBottleneck(Bottleneck): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.skip_add_relu = nn.quantized.FloatFunctional() + self.relu1 = nn.ReLU(inplace=False) + self.relu2 = nn.ReLU(inplace=False) + + def forward(self, x: Tensor) -> Tensor: + identity = x + out = self.conv1(x) + out = self.bn1(out) + out = self.relu1(out) + out = self.conv2(out) + out = self.bn2(out) + out = self.relu2(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + identity = self.downsample(x) + out = self.skip_add_relu.add_relu(out, identity) + + return out + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + _fuse_modules( + self, [["conv1", "bn1", "relu1"], ["conv2", "bn2", "relu2"], ["conv3", "bn3"]], is_qat, inplace=True + ) + if self.downsample: + _fuse_modules(self.downsample, ["0", "1"], is_qat, inplace=True) + + +class QuantizableResNet(ResNet): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + self.quant = torch.ao.quantization.QuantStub() + self.dequant = torch.ao.quantization.DeQuantStub() + + def forward(self, x: Tensor) -> Tensor: + x = self.quant(x) + # Ensure scriptability + # super(QuantizableResNet,self).forward(x) + # is not scriptable + x = self._forward_impl(x) + x = self.dequant(x) + return x + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + r"""Fuse conv/bn/relu modules in resnet models + + Fuse conv+bn+relu/ Conv+relu/conv+Bn modules to prepare for quantization. + Model is modified in place. Note that this operation does not change numerics + and the model after modification is in floating point + """ + _fuse_modules(self, ["conv1", "bn1", "relu"], is_qat, inplace=True) + for m in self.modules(): + if type(m) is QuantizableBottleneck or type(m) is QuantizableBasicBlock: + m.fuse_model(is_qat) + + +def _resnet( + block: type[Union[QuantizableBasicBlock, QuantizableBottleneck]], + layers: list[int], + weights: Optional[WeightsEnum], + progress: bool, + quantize: bool, + **kwargs: Any, +) -> QuantizableResNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + if "backend" in weights.meta: + _ovewrite_named_param(kwargs, "backend", weights.meta["backend"]) + backend = kwargs.pop("backend", "fbgemm") + + model = QuantizableResNet(block, layers, **kwargs) + _replace_relu(model) + if quantize: + quantize_model(model, backend) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, + "backend": "fbgemm", + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models", + "_docs": """ + These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized + weights listed below. + """, +} + + +class ResNet18_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/resnet18_fbgemm_16fa66dd.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 11689512, + "unquantized": ResNet18_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 69.494, + "acc@5": 88.882, + } + }, + "_ops": 1.814, + "_file_size": 11.238, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +class ResNet50_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/resnet50_fbgemm_bf931d71.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 25557032, + "unquantized": ResNet50_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.920, + "acc@5": 92.814, + } + }, + "_ops": 4.089, + "_file_size": 24.759, + }, + ) + IMAGENET1K_FBGEMM_V2 = Weights( + url="https://download.pytorch.org/models/quantized/resnet50_fbgemm-23753f79.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 25557032, + "unquantized": ResNet50_Weights.IMAGENET1K_V2, + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.282, + "acc@5": 94.976, + } + }, + "_ops": 4.089, + "_file_size": 24.953, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V2 + + +class ResNeXt101_32X8D_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/resnext101_32x8_fbgemm_09835ccf.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 88791336, + "unquantized": ResNeXt101_32X8D_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.986, + "acc@5": 94.480, + } + }, + "_ops": 16.414, + "_file_size": 86.034, + }, + ) + IMAGENET1K_FBGEMM_V2 = Weights( + url="https://download.pytorch.org/models/quantized/resnext101_32x8_fbgemm-ee16d00c.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 88791336, + "unquantized": ResNeXt101_32X8D_Weights.IMAGENET1K_V2, + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.574, + "acc@5": 96.132, + } + }, + "_ops": 16.414, + "_file_size": 86.645, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V2 + + +class ResNeXt101_64X4D_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/resnext101_64x4d_fbgemm-605a1cb3.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 83455272, + "recipe": "https://github.com/pytorch/vision/pull/5935", + "unquantized": ResNeXt101_64X4D_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.898, + "acc@5": 96.326, + } + }, + "_ops": 15.46, + "_file_size": 81.556, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +@register_model(name="quantized_resnet18") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ResNet18_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ResNet18_Weights.IMAGENET1K_V1 + ), + ) +) +def resnet18( + *, + weights: Optional[Union[ResNet18_QuantizedWeights, ResNet18_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableResNet: + """ResNet-18 model from + `Deep Residual Learning for Image Recognition `_ + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ResNet18_QuantizedWeights` or :class:`~torchvision.models.ResNet18_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ResNet18_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + quantize (bool, optional): If True, return a quantized version of the model. Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ResNet18_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ResNet18_Weights + :members: + :noindex: + """ + weights = (ResNet18_QuantizedWeights if quantize else ResNet18_Weights).verify(weights) + + return _resnet(QuantizableBasicBlock, [2, 2, 2, 2], weights, progress, quantize, **kwargs) + + +@register_model(name="quantized_resnet50") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ResNet50_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ResNet50_Weights.IMAGENET1K_V1 + ), + ) +) +def resnet50( + *, + weights: Optional[Union[ResNet50_QuantizedWeights, ResNet50_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableResNet: + """ResNet-50 model from + `Deep Residual Learning for Image Recognition `_ + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ResNet50_QuantizedWeights` or :class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ResNet50_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + quantize (bool, optional): If True, return a quantized version of the model. Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ResNet50_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ResNet50_Weights + :members: + :noindex: + """ + weights = (ResNet50_QuantizedWeights if quantize else ResNet50_Weights).verify(weights) + + return _resnet(QuantizableBottleneck, [3, 4, 6, 3], weights, progress, quantize, **kwargs) + + +@register_model(name="quantized_resnext101_32x8d") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ResNeXt101_32X8D_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ResNeXt101_32X8D_Weights.IMAGENET1K_V1 + ), + ) +) +def resnext101_32x8d( + *, + weights: Optional[Union[ResNeXt101_32X8D_QuantizedWeights, ResNeXt101_32X8D_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableResNet: + """ResNeXt-101 32x8d model from + `Aggregated Residual Transformation for Deep Neural Networks `_ + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ResNeXt101_32X8D_QuantizedWeights` or :class:`~torchvision.models.ResNeXt101_32X8D_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ResNet101_32X8D_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + quantize (bool, optional): If True, return a quantized version of the model. Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ResNeXt101_32X8D_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ResNeXt101_32X8D_Weights + :members: + :noindex: + """ + weights = (ResNeXt101_32X8D_QuantizedWeights if quantize else ResNeXt101_32X8D_Weights).verify(weights) + + _ovewrite_named_param(kwargs, "groups", 32) + _ovewrite_named_param(kwargs, "width_per_group", 8) + return _resnet(QuantizableBottleneck, [3, 4, 23, 3], weights, progress, quantize, **kwargs) + + +@register_model(name="quantized_resnext101_64x4d") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ResNeXt101_64X4D_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ResNeXt101_64X4D_Weights.IMAGENET1K_V1 + ), + ) +) +def resnext101_64x4d( + *, + weights: Optional[Union[ResNeXt101_64X4D_QuantizedWeights, ResNeXt101_64X4D_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableResNet: + """ResNeXt-101 64x4d model from + `Aggregated Residual Transformation for Deep Neural Networks `_ + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ResNeXt101_64X4D_QuantizedWeights` or :class:`~torchvision.models.ResNeXt101_64X4D_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ResNet101_64X4D_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + quantize (bool, optional): If True, return a quantized version of the model. Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.QuantizableResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ResNeXt101_64X4D_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ResNeXt101_64X4D_Weights + :members: + :noindex: + """ + weights = (ResNeXt101_64X4D_QuantizedWeights if quantize else ResNeXt101_64X4D_Weights).verify(weights) + + _ovewrite_named_param(kwargs, "groups", 64) + _ovewrite_named_param(kwargs, "width_per_group", 4) + return _resnet(QuantizableBottleneck, [3, 4, 23, 3], weights, progress, quantize, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/shufflenetv2.py b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/shufflenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..d0a2eb8eb1b5ecfcac78729c53f2501688c17a01 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/shufflenetv2.py @@ -0,0 +1,435 @@ +from functools import partial +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +from torch import Tensor +from torchvision.models import shufflenetv2 + +from ...transforms._presets import ImageClassification +from .._api import register_model, Weights, WeightsEnum +from .._meta import _IMAGENET_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from ..shufflenetv2 import ( + ShuffleNet_V2_X0_5_Weights, + ShuffleNet_V2_X1_0_Weights, + ShuffleNet_V2_X1_5_Weights, + ShuffleNet_V2_X2_0_Weights, +) +from .utils import _fuse_modules, _replace_relu, quantize_model + + +__all__ = [ + "QuantizableShuffleNetV2", + "ShuffleNet_V2_X0_5_QuantizedWeights", + "ShuffleNet_V2_X1_0_QuantizedWeights", + "ShuffleNet_V2_X1_5_QuantizedWeights", + "ShuffleNet_V2_X2_0_QuantizedWeights", + "shufflenet_v2_x0_5", + "shufflenet_v2_x1_0", + "shufflenet_v2_x1_5", + "shufflenet_v2_x2_0", +] + + +class QuantizableInvertedResidual(shufflenetv2.InvertedResidual): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.cat = nn.quantized.FloatFunctional() + + def forward(self, x: Tensor) -> Tensor: + if self.stride == 1: + x1, x2 = x.chunk(2, dim=1) + out = self.cat.cat([x1, self.branch2(x2)], dim=1) + else: + out = self.cat.cat([self.branch1(x), self.branch2(x)], dim=1) + + out = shufflenetv2.channel_shuffle(out, 2) + + return out + + +class QuantizableShuffleNetV2(shufflenetv2.ShuffleNetV2): + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, inverted_residual=QuantizableInvertedResidual, **kwargs) # type: ignore[misc] + self.quant = torch.ao.quantization.QuantStub() + self.dequant = torch.ao.quantization.DeQuantStub() + + def forward(self, x: Tensor) -> Tensor: + x = self.quant(x) + x = self._forward_impl(x) + x = self.dequant(x) + return x + + def fuse_model(self, is_qat: Optional[bool] = None) -> None: + r"""Fuse conv/bn/relu modules in shufflenetv2 model + + Fuse conv+bn+relu/ conv+relu/conv+bn modules to prepare for quantization. + Model is modified in place. + + .. note:: + Note that this operation does not change numerics + and the model after modification is in floating point + """ + for name, m in self._modules.items(): + if name in ["conv1", "conv5"] and m is not None: + _fuse_modules(m, [["0", "1", "2"]], is_qat, inplace=True) + for m in self.modules(): + if type(m) is QuantizableInvertedResidual: + if len(m.branch1._modules.items()) > 0: + _fuse_modules(m.branch1, [["0", "1"], ["2", "3", "4"]], is_qat, inplace=True) + _fuse_modules( + m.branch2, + [["0", "1", "2"], ["3", "4"], ["5", "6", "7"]], + is_qat, + inplace=True, + ) + + +def _shufflenetv2( + stages_repeats: list[int], + stages_out_channels: list[int], + *, + weights: Optional[WeightsEnum], + progress: bool, + quantize: bool, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + if "backend" in weights.meta: + _ovewrite_named_param(kwargs, "backend", weights.meta["backend"]) + backend = kwargs.pop("backend", "fbgemm") + + model = QuantizableShuffleNetV2(stages_repeats, stages_out_channels, **kwargs) + _replace_relu(model) + if quantize: + quantize_model(model, backend) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, + "backend": "fbgemm", + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#post-training-quantized-models", + "_docs": """ + These weights were produced by doing Post Training Quantization (eager mode) on top of the unquantized + weights listed below. + """, +} + + +class ShuffleNet_V2_X0_5_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/shufflenetv2_x0.5_fbgemm-00845098.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 1366792, + "unquantized": ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 57.972, + "acc@5": 79.780, + } + }, + "_ops": 0.04, + "_file_size": 1.501, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +class ShuffleNet_V2_X1_0_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/shufflenetv2_x1_fbgemm-1e62bb32.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 2278604, + "unquantized": ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 68.360, + "acc@5": 87.582, + } + }, + "_ops": 0.145, + "_file_size": 2.334, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +class ShuffleNet_V2_X1_5_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/shufflenetv2_x1_5_fbgemm-d7401f05.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/pull/5906", + "num_params": 3503624, + "unquantized": ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 72.052, + "acc@5": 90.700, + } + }, + "_ops": 0.296, + "_file_size": 3.672, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +class ShuffleNet_V2_X2_0_QuantizedWeights(WeightsEnum): + IMAGENET1K_FBGEMM_V1 = Weights( + url="https://download.pytorch.org/models/quantized/shufflenetv2_x2_0_fbgemm-5cac526c.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/pull/5906", + "num_params": 7393996, + "unquantized": ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1, + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.354, + "acc@5": 92.488, + } + }, + "_ops": 0.583, + "_file_size": 7.467, + }, + ) + DEFAULT = IMAGENET1K_FBGEMM_V1 + + +@register_model(name="quantized_shufflenet_v2_x0_5") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ShuffleNet_V2_X0_5_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1 + ), + ) +) +def shufflenet_v2_x0_5( + *, + weights: Optional[Union[ShuffleNet_V2_X0_5_QuantizedWeights, ShuffleNet_V2_X0_5_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + """ + Constructs a ShuffleNetV2 with 0.5x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. + Default is True. + quantize (bool, optional): If True, return a quantized version of the model. + Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X0_5_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ShuffleNet_V2_X0_5_Weights + :members: + :noindex: + """ + weights = (ShuffleNet_V2_X0_5_QuantizedWeights if quantize else ShuffleNet_V2_X0_5_Weights).verify(weights) + return _shufflenetv2( + [4, 8, 4], [24, 48, 96, 192, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs + ) + + +@register_model(name="quantized_shufflenet_v2_x1_0") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ShuffleNet_V2_X1_0_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1 + ), + ) +) +def shufflenet_v2_x1_0( + *, + weights: Optional[Union[ShuffleNet_V2_X1_0_QuantizedWeights, ShuffleNet_V2_X1_0_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + """ + Constructs a ShuffleNetV2 with 1.0x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. + Default is True. + quantize (bool, optional): If True, return a quantized version of the model. + Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X1_0_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ShuffleNet_V2_X1_0_Weights + :members: + :noindex: + """ + weights = (ShuffleNet_V2_X1_0_QuantizedWeights if quantize else ShuffleNet_V2_X1_0_Weights).verify(weights) + return _shufflenetv2( + [4, 8, 4], [24, 116, 232, 464, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs + ) + + +@register_model(name="quantized_shufflenet_v2_x1_5") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ShuffleNet_V2_X1_5_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1 + ), + ) +) +def shufflenet_v2_x1_5( + *, + weights: Optional[Union[ShuffleNet_V2_X1_5_QuantizedWeights, ShuffleNet_V2_X1_5_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + """ + Constructs a ShuffleNetV2 with 1.5x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. + Default is True. + quantize (bool, optional): If True, return a quantized version of the model. + Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X1_5_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ShuffleNet_V2_X1_5_Weights + :members: + :noindex: + """ + weights = (ShuffleNet_V2_X1_5_QuantizedWeights if quantize else ShuffleNet_V2_X1_5_Weights).verify(weights) + return _shufflenetv2( + [4, 8, 4], [24, 176, 352, 704, 1024], weights=weights, progress=progress, quantize=quantize, **kwargs + ) + + +@register_model(name="quantized_shufflenet_v2_x2_0") +@handle_legacy_interface( + weights=( + "pretrained", + lambda kwargs: ( + ShuffleNet_V2_X2_0_QuantizedWeights.IMAGENET1K_FBGEMM_V1 + if kwargs.get("quantize", False) + else ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1 + ), + ) +) +def shufflenet_v2_x2_0( + *, + weights: Optional[Union[ShuffleNet_V2_X2_0_QuantizedWeights, ShuffleNet_V2_X2_0_Weights]] = None, + progress: bool = True, + quantize: bool = False, + **kwargs: Any, +) -> QuantizableShuffleNetV2: + """ + Constructs a ShuffleNetV2 with 2.0x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + .. note:: + Note that ``quantize = True`` returns a quantized model with 8 bit + weights. Quantized models only support inference and run on CPUs. + GPU inference is not yet supported. + + Args: + weights (:class:`~torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights` or :class:`~torchvision.models.ShuffleNet_V2_X2_0_Weights`, optional): The + pretrained weights for the model. See + :class:`~torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. + Default is True. + quantize (bool, optional): If True, return a quantized version of the model. + Default is False. + **kwargs: parameters passed to the ``torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.quantization.ShuffleNet_V2_X2_0_QuantizedWeights + :members: + + .. autoclass:: torchvision.models.ShuffleNet_V2_X2_0_Weights + :members: + :noindex: + """ + weights = (ShuffleNet_V2_X2_0_QuantizedWeights if quantize else ShuffleNet_V2_X2_0_Weights).verify(weights) + return _shufflenetv2( + [4, 8, 4], [24, 244, 488, 976, 2048], weights=weights, progress=progress, quantize=quantize, **kwargs + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/quantization/utils.py b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..71d50bb9b480afef6467a5ae18ed92b167861f99 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/quantization/utils.py @@ -0,0 +1,51 @@ +from typing import Any, Optional, Union + +import torch +from torch import nn + + +def _replace_relu(module: nn.Module) -> None: + reassign = {} + for name, mod in module.named_children(): + _replace_relu(mod) + # Checking for explicit type instead of instance + # as we only want to replace modules of the exact type + # not inherited classes + if type(mod) is nn.ReLU or type(mod) is nn.ReLU6: + reassign[name] = nn.ReLU(inplace=False) + + for key, value in reassign.items(): + module._modules[key] = value + + +def quantize_model(model: nn.Module, backend: str) -> None: + _dummy_input_data = torch.rand(1, 3, 299, 299) + if backend not in torch.backends.quantized.supported_engines: + raise RuntimeError("Quantized backend not supported ") + torch.backends.quantized.engine = backend + model.eval() + # Make sure that weight qconfig matches that of the serialized models + if backend == "fbgemm": + model.qconfig = torch.ao.quantization.QConfig( # type: ignore[assignment] + activation=torch.ao.quantization.default_observer, + weight=torch.ao.quantization.default_per_channel_weight_observer, + ) + elif backend == "qnnpack": + model.qconfig = torch.ao.quantization.QConfig( # type: ignore[assignment] + activation=torch.ao.quantization.default_observer, weight=torch.ao.quantization.default_weight_observer + ) + + # TODO https://github.com/pytorch/vision/pull/4232#pullrequestreview-730461659 + model.fuse_model() # type: ignore[operator] + torch.ao.quantization.prepare(model, inplace=True) + model(_dummy_input_data) + torch.ao.quantization.convert(model, inplace=True) + + +def _fuse_modules( + model: nn.Module, modules_to_fuse: Union[list[str], list[list[str]]], is_qat: Optional[bool], **kwargs: Any +): + if is_qat is None: + is_qat = model.training + method = torch.ao.quantization.fuse_modules_qat if is_qat else torch.ao.quantization.fuse_modules + return method(model, modules_to_fuse, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/regnet.py b/.venv/lib/python3.12/site-packages/torchvision/models/regnet.py new file mode 100644 index 0000000000000000000000000000000000000000..915ef22bf33f1b00d5544b7d04c31a24006ac9df --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/regnet.py @@ -0,0 +1,1571 @@ +import math +from collections import OrderedDict +from functools import partial +from typing import Any, Callable, Optional + +import torch +from torch import nn, Tensor + +from ..ops.misc import Conv2dNormActivation, SqueezeExcitation +from ..transforms._presets import ImageClassification, InterpolationMode +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _make_divisible, _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "RegNet", + "RegNet_Y_400MF_Weights", + "RegNet_Y_800MF_Weights", + "RegNet_Y_1_6GF_Weights", + "RegNet_Y_3_2GF_Weights", + "RegNet_Y_8GF_Weights", + "RegNet_Y_16GF_Weights", + "RegNet_Y_32GF_Weights", + "RegNet_Y_128GF_Weights", + "RegNet_X_400MF_Weights", + "RegNet_X_800MF_Weights", + "RegNet_X_1_6GF_Weights", + "RegNet_X_3_2GF_Weights", + "RegNet_X_8GF_Weights", + "RegNet_X_16GF_Weights", + "RegNet_X_32GF_Weights", + "regnet_y_400mf", + "regnet_y_800mf", + "regnet_y_1_6gf", + "regnet_y_3_2gf", + "regnet_y_8gf", + "regnet_y_16gf", + "regnet_y_32gf", + "regnet_y_128gf", + "regnet_x_400mf", + "regnet_x_800mf", + "regnet_x_1_6gf", + "regnet_x_3_2gf", + "regnet_x_8gf", + "regnet_x_16gf", + "regnet_x_32gf", +] + + +class SimpleStemIN(Conv2dNormActivation): + """Simple stem for ImageNet: 3x3, BN, ReLU.""" + + def __init__( + self, + width_in: int, + width_out: int, + norm_layer: Callable[..., nn.Module], + activation_layer: Callable[..., nn.Module], + ) -> None: + super().__init__( + width_in, width_out, kernel_size=3, stride=2, norm_layer=norm_layer, activation_layer=activation_layer + ) + + +class BottleneckTransform(nn.Sequential): + """Bottleneck transformation: 1x1, 3x3 [+SE], 1x1.""" + + def __init__( + self, + width_in: int, + width_out: int, + stride: int, + norm_layer: Callable[..., nn.Module], + activation_layer: Callable[..., nn.Module], + group_width: int, + bottleneck_multiplier: float, + se_ratio: Optional[float], + ) -> None: + layers: OrderedDict[str, nn.Module] = OrderedDict() + w_b = int(round(width_out * bottleneck_multiplier)) + g = w_b // group_width + + layers["a"] = Conv2dNormActivation( + width_in, w_b, kernel_size=1, stride=1, norm_layer=norm_layer, activation_layer=activation_layer + ) + layers["b"] = Conv2dNormActivation( + w_b, w_b, kernel_size=3, stride=stride, groups=g, norm_layer=norm_layer, activation_layer=activation_layer + ) + + if se_ratio: + # The SE reduction ratio is defined with respect to the + # beginning of the block + width_se_out = int(round(se_ratio * width_in)) + layers["se"] = SqueezeExcitation( + input_channels=w_b, + squeeze_channels=width_se_out, + activation=activation_layer, + ) + + layers["c"] = Conv2dNormActivation( + w_b, width_out, kernel_size=1, stride=1, norm_layer=norm_layer, activation_layer=None + ) + super().__init__(layers) + + +class ResBottleneckBlock(nn.Module): + """Residual bottleneck block: x + F(x), F = bottleneck transform.""" + + def __init__( + self, + width_in: int, + width_out: int, + stride: int, + norm_layer: Callable[..., nn.Module], + activation_layer: Callable[..., nn.Module], + group_width: int = 1, + bottleneck_multiplier: float = 1.0, + se_ratio: Optional[float] = None, + ) -> None: + super().__init__() + + # Use skip connection with projection if shape changes + self.proj = None + should_proj = (width_in != width_out) or (stride != 1) + if should_proj: + self.proj = Conv2dNormActivation( + width_in, width_out, kernel_size=1, stride=stride, norm_layer=norm_layer, activation_layer=None + ) + self.f = BottleneckTransform( + width_in, + width_out, + stride, + norm_layer, + activation_layer, + group_width, + bottleneck_multiplier, + se_ratio, + ) + self.activation = activation_layer(inplace=True) + + def forward(self, x: Tensor) -> Tensor: + if self.proj is not None: + x = self.proj(x) + self.f(x) + else: + x = x + self.f(x) + return self.activation(x) + + +class AnyStage(nn.Sequential): + """AnyNet stage (sequence of blocks w/ the same output shape).""" + + def __init__( + self, + width_in: int, + width_out: int, + stride: int, + depth: int, + block_constructor: Callable[..., nn.Module], + norm_layer: Callable[..., nn.Module], + activation_layer: Callable[..., nn.Module], + group_width: int, + bottleneck_multiplier: float, + se_ratio: Optional[float] = None, + stage_index: int = 0, + ) -> None: + super().__init__() + + for i in range(depth): + block = block_constructor( + width_in if i == 0 else width_out, + width_out, + stride if i == 0 else 1, + norm_layer, + activation_layer, + group_width, + bottleneck_multiplier, + se_ratio, + ) + + self.add_module(f"block{stage_index}-{i}", block) + + +class BlockParams: + def __init__( + self, + depths: list[int], + widths: list[int], + group_widths: list[int], + bottleneck_multipliers: list[float], + strides: list[int], + se_ratio: Optional[float] = None, + ) -> None: + self.depths = depths + self.widths = widths + self.group_widths = group_widths + self.bottleneck_multipliers = bottleneck_multipliers + self.strides = strides + self.se_ratio = se_ratio + + @classmethod + def from_init_params( + cls, + depth: int, + w_0: int, + w_a: float, + w_m: float, + group_width: int, + bottleneck_multiplier: float = 1.0, + se_ratio: Optional[float] = None, + **kwargs: Any, + ) -> "BlockParams": + """ + Programmatically compute all the per-block settings, + given the RegNet parameters. + + The first step is to compute the quantized linear block parameters, + in log space. Key parameters are: + - `w_a` is the width progression slope + - `w_0` is the initial width + - `w_m` is the width stepping in the log space + + In other terms + `log(block_width) = log(w_0) + w_m * block_capacity`, + with `bock_capacity` ramping up following the w_0 and w_a params. + This block width is finally quantized to multiples of 8. + + The second step is to compute the parameters per stage, + taking into account the skip connection and the final 1x1 convolutions. + We use the fact that the output width is constant within a stage. + """ + + QUANT = 8 + STRIDE = 2 + + if w_a < 0 or w_0 <= 0 or w_m <= 1 or w_0 % 8 != 0: + raise ValueError("Invalid RegNet settings") + # Compute the block widths. Each stage has one unique block width + widths_cont = torch.arange(depth) * w_a + w_0 + block_capacity = torch.round(torch.log(widths_cont / w_0) / math.log(w_m)) + block_widths = (torch.round(torch.divide(w_0 * torch.pow(w_m, block_capacity), QUANT)) * QUANT).int().tolist() + num_stages = len(set(block_widths)) + + # Convert to per stage parameters + split_helper = zip( + block_widths + [0], + [0] + block_widths, + block_widths + [0], + [0] + block_widths, + ) + splits = [w != wp or r != rp for w, wp, r, rp in split_helper] + + stage_widths = [w for w, t in zip(block_widths, splits[:-1]) if t] + stage_depths = torch.diff(torch.tensor([d for d, t in enumerate(splits) if t])).int().tolist() + + strides = [STRIDE] * num_stages + bottleneck_multipliers = [bottleneck_multiplier] * num_stages + group_widths = [group_width] * num_stages + + # Adjust the compatibility of stage widths and group widths + stage_widths, group_widths = cls._adjust_widths_groups_compatibilty( + stage_widths, bottleneck_multipliers, group_widths + ) + + return cls( + depths=stage_depths, + widths=stage_widths, + group_widths=group_widths, + bottleneck_multipliers=bottleneck_multipliers, + strides=strides, + se_ratio=se_ratio, + ) + + def _get_expanded_params(self): + return zip(self.widths, self.strides, self.depths, self.group_widths, self.bottleneck_multipliers) + + @staticmethod + def _adjust_widths_groups_compatibilty( + stage_widths: list[int], bottleneck_ratios: list[float], group_widths: list[int] + ) -> tuple[list[int], list[int]]: + """ + Adjusts the compatibility of widths and groups, + depending on the bottleneck ratio. + """ + # Compute all widths for the current settings + widths = [int(w * b) for w, b in zip(stage_widths, bottleneck_ratios)] + group_widths_min = [min(g, w_bot) for g, w_bot in zip(group_widths, widths)] + + # Compute the adjusted widths so that stage and group widths fit + ws_bot = [_make_divisible(w_bot, g) for w_bot, g in zip(widths, group_widths_min)] + stage_widths = [int(w_bot / b) for w_bot, b in zip(ws_bot, bottleneck_ratios)] + return stage_widths, group_widths_min + + +class RegNet(nn.Module): + def __init__( + self, + block_params: BlockParams, + num_classes: int = 1000, + stem_width: int = 32, + stem_type: Optional[Callable[..., nn.Module]] = None, + block_type: Optional[Callable[..., nn.Module]] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + activation: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + _log_api_usage_once(self) + + if stem_type is None: + stem_type = SimpleStemIN + if norm_layer is None: + norm_layer = nn.BatchNorm2d + if block_type is None: + block_type = ResBottleneckBlock + if activation is None: + activation = nn.ReLU + + # Ad hoc stem + self.stem = stem_type( + 3, # width_in + stem_width, + norm_layer, + activation, + ) + + current_width = stem_width + + blocks = [] + for i, ( + width_out, + stride, + depth, + group_width, + bottleneck_multiplier, + ) in enumerate(block_params._get_expanded_params()): + blocks.append( + ( + f"block{i+1}", + AnyStage( + current_width, + width_out, + stride, + depth, + block_type, + norm_layer, + activation, + group_width, + bottleneck_multiplier, + block_params.se_ratio, + stage_index=i + 1, + ), + ) + ) + + current_width = width_out + + self.trunk_output = nn.Sequential(OrderedDict(blocks)) + + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) + self.fc = nn.Linear(in_features=current_width, out_features=num_classes) + + # Performs ResNet-style weight initialization + for m in self.modules(): + if isinstance(m, nn.Conv2d): + # Note that there is no bias due to BN + fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels + nn.init.normal_(m.weight, mean=0.0, std=math.sqrt(2.0 / fan_out)) + elif isinstance(m, nn.BatchNorm2d): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, mean=0.0, std=0.01) + nn.init.zeros_(m.bias) + + def forward(self, x: Tensor) -> Tensor: + x = self.stem(x) + x = self.trunk_output(x) + + x = self.avgpool(x) + x = x.flatten(start_dim=1) + x = self.fc(x) + + return x + + +def _regnet( + block_params: BlockParams, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> RegNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + norm_layer = kwargs.pop("norm_layer", partial(nn.BatchNorm2d, eps=1e-05, momentum=0.1)) + model = RegNet(block_params, norm_layer=norm_layer, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META: dict[str, Any] = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, +} + +_COMMON_SWAG_META = { + **_COMMON_META, + "recipe": "https://github.com/facebookresearch/SWAG", + "license": "https://github.com/facebookresearch/SWAG/blob/main/LICENSE", +} + + +class RegNet_Y_400MF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_400mf-c65dace8.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 4344144, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#small-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 74.046, + "acc@5": 91.716, + } + }, + "_ops": 0.402, + "_file_size": 16.806, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_y_400mf-e6988f5f.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 4344144, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.804, + "acc@5": 92.742, + } + }, + "_ops": 0.402, + "_file_size": 16.806, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_Y_800MF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_800mf-1b27b58c.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 6432512, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#small-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 76.420, + "acc@5": 93.136, + } + }, + "_ops": 0.834, + "_file_size": 24.774, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_y_800mf-58fc7688.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 6432512, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.828, + "acc@5": 94.502, + } + }, + "_ops": 0.834, + "_file_size": 24.774, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_Y_1_6GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_1_6gf-b11a554e.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 11202430, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#small-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.950, + "acc@5": 93.966, + } + }, + "_ops": 1.612, + "_file_size": 43.152, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_y_1_6gf-0d7bc02a.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 11202430, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.876, + "acc@5": 95.444, + } + }, + "_ops": 1.612, + "_file_size": 43.152, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_Y_3_2GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_3_2gf-b5a9779c.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 19436338, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#medium-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.948, + "acc@5": 94.576, + } + }, + "_ops": 3.176, + "_file_size": 74.567, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_y_3_2gf-9180c971.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 19436338, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.982, + "acc@5": 95.972, + } + }, + "_ops": 3.176, + "_file_size": 74.567, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_Y_8GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_8gf-d0d0e4a8.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 39381472, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#medium-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.032, + "acc@5": 95.048, + } + }, + "_ops": 8.473, + "_file_size": 150.701, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_y_8gf-dc2b1b54.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 39381472, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.828, + "acc@5": 96.330, + } + }, + "_ops": 8.473, + "_file_size": 150.701, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_Y_16GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_16gf-9e6ed7dd.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 83590140, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#large-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.424, + "acc@5": 95.240, + } + }, + "_ops": 15.912, + "_file_size": 319.49, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_y_16gf-3e4a00f9.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 83590140, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.886, + "acc@5": 96.328, + } + }, + "_ops": 15.912, + "_file_size": 319.49, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + IMAGENET1K_SWAG_E2E_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_16gf_swag-43afe44d.pth", + transforms=partial( + ImageClassification, crop_size=384, resize_size=384, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_SWAG_META, + "num_params": 83590140, + "_metrics": { + "ImageNet-1K": { + "acc@1": 86.012, + "acc@5": 98.054, + } + }, + "_ops": 46.735, + "_file_size": 319.49, + "_docs": """ + These weights are learnt via transfer learning by end-to-end fine-tuning the original + `SWAG `_ weights on ImageNet-1K data. + """, + }, + ) + IMAGENET1K_SWAG_LINEAR_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_16gf_lc_swag-f3ec0043.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=224, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_SWAG_META, + "recipe": "https://github.com/pytorch/vision/pull/5793", + "num_params": 83590140, + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.976, + "acc@5": 97.244, + } + }, + "_ops": 15.912, + "_file_size": 319.49, + "_docs": """ + These weights are composed of the original frozen `SWAG `_ trunk + weights and a linear classifier learnt on top of them trained on ImageNet-1K data. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_Y_32GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_32gf-4dee3f7a.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 145046770, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#large-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.878, + "acc@5": 95.340, + } + }, + "_ops": 32.28, + "_file_size": 554.076, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_y_32gf-8db6d4b5.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 145046770, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.368, + "acc@5": 96.498, + } + }, + "_ops": 32.28, + "_file_size": 554.076, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + IMAGENET1K_SWAG_E2E_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_32gf_swag-04fdfa75.pth", + transforms=partial( + ImageClassification, crop_size=384, resize_size=384, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_SWAG_META, + "num_params": 145046770, + "_metrics": { + "ImageNet-1K": { + "acc@1": 86.838, + "acc@5": 98.362, + } + }, + "_ops": 94.826, + "_file_size": 554.076, + "_docs": """ + These weights are learnt via transfer learning by end-to-end fine-tuning the original + `SWAG `_ weights on ImageNet-1K data. + """, + }, + ) + IMAGENET1K_SWAG_LINEAR_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_32gf_lc_swag-e1583746.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=224, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_SWAG_META, + "recipe": "https://github.com/pytorch/vision/pull/5793", + "num_params": 145046770, + "_metrics": { + "ImageNet-1K": { + "acc@1": 84.622, + "acc@5": 97.480, + } + }, + "_ops": 32.28, + "_file_size": 554.076, + "_docs": """ + These weights are composed of the original frozen `SWAG `_ trunk + weights and a linear classifier learnt on top of them trained on ImageNet-1K data. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_Y_128GF_Weights(WeightsEnum): + IMAGENET1K_SWAG_E2E_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_128gf_swag-c8ce3e52.pth", + transforms=partial( + ImageClassification, crop_size=384, resize_size=384, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_SWAG_META, + "num_params": 644812894, + "_metrics": { + "ImageNet-1K": { + "acc@1": 88.228, + "acc@5": 98.682, + } + }, + "_ops": 374.57, + "_file_size": 2461.564, + "_docs": """ + These weights are learnt via transfer learning by end-to-end fine-tuning the original + `SWAG `_ weights on ImageNet-1K data. + """, + }, + ) + IMAGENET1K_SWAG_LINEAR_V1 = Weights( + url="https://download.pytorch.org/models/regnet_y_128gf_lc_swag-cbe8ce12.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=224, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_SWAG_META, + "recipe": "https://github.com/pytorch/vision/pull/5793", + "num_params": 644812894, + "_metrics": { + "ImageNet-1K": { + "acc@1": 86.068, + "acc@5": 97.844, + } + }, + "_ops": 127.518, + "_file_size": 2461.564, + "_docs": """ + These weights are composed of the original frozen `SWAG `_ trunk + weights and a linear classifier learnt on top of them trained on ImageNet-1K data. + """, + }, + ) + DEFAULT = IMAGENET1K_SWAG_E2E_V1 + + +class RegNet_X_400MF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_x_400mf-adf1edd5.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 5495976, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#small-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 72.834, + "acc@5": 90.950, + } + }, + "_ops": 0.414, + "_file_size": 21.258, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_x_400mf-62229a5f.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 5495976, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-fixres", + "_metrics": { + "ImageNet-1K": { + "acc@1": 74.864, + "acc@5": 92.322, + } + }, + "_ops": 0.414, + "_file_size": 21.257, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_X_800MF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_x_800mf-ad17e45c.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 7259656, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#small-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.212, + "acc@5": 92.348, + } + }, + "_ops": 0.8, + "_file_size": 27.945, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_x_800mf-94a99ebd.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 7259656, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-fixres", + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.522, + "acc@5": 93.826, + } + }, + "_ops": 0.8, + "_file_size": 27.945, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_X_1_6GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_x_1_6gf-e3633e7f.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 9190136, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#small-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.040, + "acc@5": 93.440, + } + }, + "_ops": 1.603, + "_file_size": 35.339, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_x_1_6gf-a12f2b72.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 9190136, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-fixres", + "_metrics": { + "ImageNet-1K": { + "acc@1": 79.668, + "acc@5": 94.922, + } + }, + "_ops": 1.603, + "_file_size": 35.339, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_X_3_2GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_x_3_2gf-f342aeae.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 15296552, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#medium-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.364, + "acc@5": 93.992, + } + }, + "_ops": 3.177, + "_file_size": 58.756, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_x_3_2gf-7071aa85.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 15296552, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.196, + "acc@5": 95.430, + } + }, + "_ops": 3.177, + "_file_size": 58.756, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_X_8GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_x_8gf-03ceed89.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 39572648, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#medium-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 79.344, + "acc@5": 94.686, + } + }, + "_ops": 7.995, + "_file_size": 151.456, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_x_8gf-2b70d774.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 39572648, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.682, + "acc@5": 95.678, + } + }, + "_ops": 7.995, + "_file_size": 151.456, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_X_16GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_x_16gf-2007eb11.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 54278536, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#medium-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.058, + "acc@5": 94.944, + } + }, + "_ops": 15.941, + "_file_size": 207.627, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_x_16gf-ba3796d7.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 54278536, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.716, + "acc@5": 96.196, + } + }, + "_ops": 15.941, + "_file_size": 207.627, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class RegNet_X_32GF_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/regnet_x_32gf-9d47f8d0.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 107811560, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#large-models", + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.622, + "acc@5": 95.248, + } + }, + "_ops": 31.736, + "_file_size": 412.039, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/regnet_x_32gf-6eb8fdc6.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 107811560, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.014, + "acc@5": 96.288, + } + }, + "_ops": 31.736, + "_file_size": 412.039, + "_docs": """ + These weights improve upon the results of the original paper by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_Y_400MF_Weights.IMAGENET1K_V1)) +def regnet_y_400mf(*, weights: Optional[RegNet_Y_400MF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_400MF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_400MF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_400MF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_400MF_Weights + :members: + """ + weights = RegNet_Y_400MF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=16, w_0=48, w_a=27.89, w_m=2.09, group_width=8, se_ratio=0.25, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_Y_800MF_Weights.IMAGENET1K_V1)) +def regnet_y_800mf(*, weights: Optional[RegNet_Y_800MF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_800MF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_800MF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_800MF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_800MF_Weights + :members: + """ + weights = RegNet_Y_800MF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=14, w_0=56, w_a=38.84, w_m=2.4, group_width=16, se_ratio=0.25, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_Y_1_6GF_Weights.IMAGENET1K_V1)) +def regnet_y_1_6gf(*, weights: Optional[RegNet_Y_1_6GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_1.6GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_1_6GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_1_6GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_1_6GF_Weights + :members: + """ + weights = RegNet_Y_1_6GF_Weights.verify(weights) + + params = BlockParams.from_init_params( + depth=27, w_0=48, w_a=20.71, w_m=2.65, group_width=24, se_ratio=0.25, **kwargs + ) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_Y_3_2GF_Weights.IMAGENET1K_V1)) +def regnet_y_3_2gf(*, weights: Optional[RegNet_Y_3_2GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_3.2GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_3_2GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_3_2GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_3_2GF_Weights + :members: + """ + weights = RegNet_Y_3_2GF_Weights.verify(weights) + + params = BlockParams.from_init_params( + depth=21, w_0=80, w_a=42.63, w_m=2.66, group_width=24, se_ratio=0.25, **kwargs + ) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_Y_8GF_Weights.IMAGENET1K_V1)) +def regnet_y_8gf(*, weights: Optional[RegNet_Y_8GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_8GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_8GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_8GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_8GF_Weights + :members: + """ + weights = RegNet_Y_8GF_Weights.verify(weights) + + params = BlockParams.from_init_params( + depth=17, w_0=192, w_a=76.82, w_m=2.19, group_width=56, se_ratio=0.25, **kwargs + ) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_Y_16GF_Weights.IMAGENET1K_V1)) +def regnet_y_16gf(*, weights: Optional[RegNet_Y_16GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_16GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_16GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_16GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_16GF_Weights + :members: + """ + weights = RegNet_Y_16GF_Weights.verify(weights) + + params = BlockParams.from_init_params( + depth=18, w_0=200, w_a=106.23, w_m=2.48, group_width=112, se_ratio=0.25, **kwargs + ) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_Y_32GF_Weights.IMAGENET1K_V1)) +def regnet_y_32gf(*, weights: Optional[RegNet_Y_32GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_32GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_32GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_32GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_32GF_Weights + :members: + """ + weights = RegNet_Y_32GF_Weights.verify(weights) + + params = BlockParams.from_init_params( + depth=20, w_0=232, w_a=115.89, w_m=2.53, group_width=232, se_ratio=0.25, **kwargs + ) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", None)) +def regnet_y_128gf(*, weights: Optional[RegNet_Y_128GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetY_128GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_Y_128GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_Y_128GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_Y_128GF_Weights + :members: + """ + weights = RegNet_Y_128GF_Weights.verify(weights) + + params = BlockParams.from_init_params( + depth=27, w_0=456, w_a=160.83, w_m=2.52, group_width=264, se_ratio=0.25, **kwargs + ) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_X_400MF_Weights.IMAGENET1K_V1)) +def regnet_x_400mf(*, weights: Optional[RegNet_X_400MF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetX_400MF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_X_400MF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_X_400MF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_X_400MF_Weights + :members: + """ + weights = RegNet_X_400MF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=22, w_0=24, w_a=24.48, w_m=2.54, group_width=16, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_X_800MF_Weights.IMAGENET1K_V1)) +def regnet_x_800mf(*, weights: Optional[RegNet_X_800MF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetX_800MF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_X_800MF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_X_800MF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_X_800MF_Weights + :members: + """ + weights = RegNet_X_800MF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=16, w_0=56, w_a=35.73, w_m=2.28, group_width=16, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_X_1_6GF_Weights.IMAGENET1K_V1)) +def regnet_x_1_6gf(*, weights: Optional[RegNet_X_1_6GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetX_1.6GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_X_1_6GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_X_1_6GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_X_1_6GF_Weights + :members: + """ + weights = RegNet_X_1_6GF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=18, w_0=80, w_a=34.01, w_m=2.25, group_width=24, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_X_3_2GF_Weights.IMAGENET1K_V1)) +def regnet_x_3_2gf(*, weights: Optional[RegNet_X_3_2GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetX_3.2GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_X_3_2GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_X_3_2GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_X_3_2GF_Weights + :members: + """ + weights = RegNet_X_3_2GF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=25, w_0=88, w_a=26.31, w_m=2.25, group_width=48, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_X_8GF_Weights.IMAGENET1K_V1)) +def regnet_x_8gf(*, weights: Optional[RegNet_X_8GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetX_8GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_X_8GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_X_8GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_X_8GF_Weights + :members: + """ + weights = RegNet_X_8GF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=23, w_0=80, w_a=49.56, w_m=2.88, group_width=120, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_X_16GF_Weights.IMAGENET1K_V1)) +def regnet_x_16gf(*, weights: Optional[RegNet_X_16GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetX_16GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_X_16GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_X_16GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_X_16GF_Weights + :members: + """ + weights = RegNet_X_16GF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=22, w_0=216, w_a=55.59, w_m=2.1, group_width=128, **kwargs) + return _regnet(params, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", RegNet_X_32GF_Weights.IMAGENET1K_V1)) +def regnet_x_32gf(*, weights: Optional[RegNet_X_32GF_Weights] = None, progress: bool = True, **kwargs: Any) -> RegNet: + """ + Constructs a RegNetX_32GF architecture from + `Designing Network Design Spaces `_. + + Args: + weights (:class:`~torchvision.models.RegNet_X_32GF_Weights`, optional): The pretrained weights to use. + See :class:`~torchvision.models.RegNet_X_32GF_Weights` below for more details and possible values. + By default, no pretrained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to either ``torchvision.models.regnet.RegNet`` or + ``torchvision.models.regnet.BlockParams`` class. Please refer to the `source code + `_ + for more detail about the classes. + + .. autoclass:: torchvision.models.RegNet_X_32GF_Weights + :members: + """ + weights = RegNet_X_32GF_Weights.verify(weights) + + params = BlockParams.from_init_params(depth=23, w_0=320, w_a=69.86, w_m=2.0, group_width=168, **kwargs) + return _regnet(params, weights, progress, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/resnet.py b/.venv/lib/python3.12/site-packages/torchvision/models/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..47067ec83175a97cc6f6a8721b342128a434d440 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/resnet.py @@ -0,0 +1,985 @@ +from functools import partial +from typing import Any, Callable, Optional, Union + +import torch +import torch.nn as nn +from torch import Tensor + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "ResNet", + "ResNet18_Weights", + "ResNet34_Weights", + "ResNet50_Weights", + "ResNet101_Weights", + "ResNet152_Weights", + "ResNeXt50_32X4D_Weights", + "ResNeXt101_32X8D_Weights", + "ResNeXt101_64X4D_Weights", + "Wide_ResNet50_2_Weights", + "Wide_ResNet101_2_Weights", + "resnet18", + "resnet34", + "resnet50", + "resnet101", + "resnet152", + "resnext50_32x4d", + "resnext101_32x8d", + "resnext101_64x4d", + "wide_resnet50_2", + "wide_resnet101_2", +] + + +def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d: + """3x3 convolution with padding""" + return nn.Conv2d( + in_planes, + out_planes, + kernel_size=3, + stride=stride, + padding=dilation, + groups=groups, + bias=False, + dilation=dilation, + ) + + +def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d: + """1x1 convolution""" + return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) + + +class BasicBlock(nn.Module): + expansion: int = 1 + + def __init__( + self, + inplanes: int, + planes: int, + stride: int = 1, + downsample: Optional[nn.Module] = None, + groups: int = 1, + base_width: int = 64, + dilation: int = 1, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + if norm_layer is None: + norm_layer = nn.BatchNorm2d + if groups != 1 or base_width != 64: + raise ValueError("BasicBlock only supports groups=1 and base_width=64") + if dilation > 1: + raise NotImplementedError("Dilation > 1 not supported in BasicBlock") + # Both self.conv1 and self.downsample layers downsample the input when stride != 1 + self.conv1 = conv3x3(inplanes, planes, stride) + self.bn1 = norm_layer(planes) + self.relu = nn.ReLU(inplace=True) + self.conv2 = conv3x3(planes, planes) + self.bn2 = norm_layer(planes) + self.downsample = downsample + self.stride = stride + + def forward(self, x: Tensor) -> Tensor: + identity = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.relu(out) + + return out + + +class Bottleneck(nn.Module): + # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2) + # while original implementation places the stride at the first 1x1 convolution(self.conv1) + # according to "Deep residual learning for image recognition" https://arxiv.org/abs/1512.03385. + # This variant is also known as ResNet V1.5 and improves accuracy according to + # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch. + + expansion: int = 4 + + def __init__( + self, + inplanes: int, + planes: int, + stride: int = 1, + downsample: Optional[nn.Module] = None, + groups: int = 1, + base_width: int = 64, + dilation: int = 1, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + if norm_layer is None: + norm_layer = nn.BatchNorm2d + width = int(planes * (base_width / 64.0)) * groups + # Both self.conv2 and self.downsample layers downsample the input when stride != 1 + self.conv1 = conv1x1(inplanes, width) + self.bn1 = norm_layer(width) + self.conv2 = conv3x3(width, width, stride, groups, dilation) + self.bn2 = norm_layer(width) + self.conv3 = conv1x1(width, planes * self.expansion) + self.bn3 = norm_layer(planes * self.expansion) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x: Tensor) -> Tensor: + identity = x + + out = self.conv1(x) + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + out = self.bn2(out) + out = self.relu(out) + + out = self.conv3(out) + out = self.bn3(out) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.relu(out) + + return out + + +class ResNet(nn.Module): + def __init__( + self, + block: type[Union[BasicBlock, Bottleneck]], + layers: list[int], + num_classes: int = 1000, + zero_init_residual: bool = False, + groups: int = 1, + width_per_group: int = 64, + replace_stride_with_dilation: Optional[list[bool]] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + _log_api_usage_once(self) + if norm_layer is None: + norm_layer = nn.BatchNorm2d + self._norm_layer = norm_layer + + self.inplanes = 64 + self.dilation = 1 + if replace_stride_with_dilation is None: + # each element in the tuple indicates if we should replace + # the 2x2 stride with a dilated convolution instead + replace_stride_with_dilation = [False, False, False] + if len(replace_stride_with_dilation) != 3: + raise ValueError( + "replace_stride_with_dilation should be None " + f"or a 3-element tuple, got {replace_stride_with_dilation}" + ) + self.groups = groups + self.base_width = width_per_group + self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) + self.bn1 = norm_layer(self.inplanes) + self.relu = nn.ReLU(inplace=True) + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + self.layer1 = self._make_layer(block, 64, layers[0]) + self.layer2 = self._make_layer(block, 128, layers[1], stride=2, dilate=replace_stride_with_dilation[0]) + self.layer3 = self._make_layer(block, 256, layers[2], stride=2, dilate=replace_stride_with_dilation[1]) + self.layer4 = self._make_layer(block, 512, layers[3], stride=2, dilate=replace_stride_with_dilation[2]) + self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) + self.fc = nn.Linear(512 * block.expansion, num_classes) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + # Zero-initialize the last BN in each residual branch, + # so that the residual branch starts with zeros, and each residual block behaves like an identity. + # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 + if zero_init_residual: + for m in self.modules(): + if isinstance(m, Bottleneck) and m.bn3.weight is not None: + nn.init.constant_(m.bn3.weight, 0) # type: ignore[arg-type] + elif isinstance(m, BasicBlock) and m.bn2.weight is not None: + nn.init.constant_(m.bn2.weight, 0) # type: ignore[arg-type] + + def _make_layer( + self, + block: type[Union[BasicBlock, Bottleneck]], + planes: int, + blocks: int, + stride: int = 1, + dilate: bool = False, + ) -> nn.Sequential: + norm_layer = self._norm_layer + downsample = None + previous_dilation = self.dilation + if dilate: + self.dilation *= stride + stride = 1 + if stride != 1 or self.inplanes != planes * block.expansion: + downsample = nn.Sequential( + conv1x1(self.inplanes, planes * block.expansion, stride), + norm_layer(planes * block.expansion), + ) + + layers = [] + layers.append( + block( + self.inplanes, planes, stride, downsample, self.groups, self.base_width, previous_dilation, norm_layer + ) + ) + self.inplanes = planes * block.expansion + for _ in range(1, blocks): + layers.append( + block( + self.inplanes, + planes, + groups=self.groups, + base_width=self.base_width, + dilation=self.dilation, + norm_layer=norm_layer, + ) + ) + + return nn.Sequential(*layers) + + def _forward_impl(self, x: Tensor) -> Tensor: + # See note [TorchScript super()] + x = self.conv1(x) + x = self.bn1(x) + x = self.relu(x) + x = self.maxpool(x) + + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + + x = self.avgpool(x) + x = torch.flatten(x, 1) + x = self.fc(x) + + return x + + def forward(self, x: Tensor) -> Tensor: + return self._forward_impl(x) + + +def _resnet( + block: type[Union[BasicBlock, Bottleneck]], + layers: list[int], + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> ResNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = ResNet(block, layers, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, +} + + +class ResNet18_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnet18-f37072fd.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 11689512, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnet", + "_metrics": { + "ImageNet-1K": { + "acc@1": 69.758, + "acc@5": 89.078, + } + }, + "_ops": 1.814, + "_file_size": 44.661, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ResNet34_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnet34-b627a593.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 21797672, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnet", + "_metrics": { + "ImageNet-1K": { + "acc@1": 73.314, + "acc@5": 91.420, + } + }, + "_ops": 3.664, + "_file_size": 83.275, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ResNet50_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnet50-0676ba61.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 25557032, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnet", + "_metrics": { + "ImageNet-1K": { + "acc@1": 76.130, + "acc@5": 92.862, + } + }, + "_ops": 4.089, + "_file_size": 97.781, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/resnet50-11ad3fa6.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 25557032, + "recipe": "https://github.com/pytorch/vision/issues/3995#issuecomment-1013906621", + "_metrics": { + "ImageNet-1K": { + "acc@1": 80.858, + "acc@5": 95.434, + } + }, + "_ops": 4.089, + "_file_size": 97.79, + "_docs": """ + These weights improve upon the results of the original paper by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class ResNet101_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnet101-63fe2227.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 44549160, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnet", + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.374, + "acc@5": 93.546, + } + }, + "_ops": 7.801, + "_file_size": 170.511, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/resnet101-cd907fc2.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 44549160, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.886, + "acc@5": 95.780, + } + }, + "_ops": 7.801, + "_file_size": 170.53, + "_docs": """ + These weights improve upon the results of the original paper by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class ResNet152_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnet152-394f9c45.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 60192808, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnet", + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.312, + "acc@5": 94.046, + } + }, + "_ops": 11.514, + "_file_size": 230.434, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/resnet152-f82ba261.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 60192808, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.284, + "acc@5": 96.002, + } + }, + "_ops": 11.514, + "_file_size": 230.474, + "_docs": """ + These weights improve upon the results of the original paper by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class ResNeXt50_32X4D_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 25028904, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnext", + "_metrics": { + "ImageNet-1K": { + "acc@1": 77.618, + "acc@5": 93.698, + } + }, + "_ops": 4.23, + "_file_size": 95.789, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/resnext50_32x4d-1a0047aa.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 25028904, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.198, + "acc@5": 95.340, + } + }, + "_ops": 4.23, + "_file_size": 95.833, + "_docs": """ + These weights improve upon the results of the original paper by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class ResNeXt101_32X8D_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 88791336, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnext", + "_metrics": { + "ImageNet-1K": { + "acc@1": 79.312, + "acc@5": 94.526, + } + }, + "_ops": 16.414, + "_file_size": 339.586, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/resnext101_32x8d-110c445d.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 88791336, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-fixres", + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.834, + "acc@5": 96.228, + } + }, + "_ops": 16.414, + "_file_size": 339.673, + "_docs": """ + These weights improve upon the results of the original paper by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class ResNeXt101_64X4D_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/resnext101_64x4d-173b62eb.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 83455272, + "recipe": "https://github.com/pytorch/vision/pull/5935", + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.246, + "acc@5": 96.454, + } + }, + "_ops": 15.46, + "_file_size": 319.318, + "_docs": """ + These weights were trained from scratch by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class Wide_ResNet50_2_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 68883240, + "recipe": "https://github.com/pytorch/vision/pull/912#issue-445437439", + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.468, + "acc@5": 94.086, + } + }, + "_ops": 11.398, + "_file_size": 131.82, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/wide_resnet50_2-9ba9bcbe.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 68883240, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe-with-fixres", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.602, + "acc@5": 95.758, + } + }, + "_ops": 11.398, + "_file_size": 263.124, + "_docs": """ + These weights improve upon the results of the original paper by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +class Wide_ResNet101_2_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 126886696, + "recipe": "https://github.com/pytorch/vision/pull/912#issue-445437439", + "_metrics": { + "ImageNet-1K": { + "acc@1": 78.848, + "acc@5": 94.284, + } + }, + "_ops": 22.753, + "_file_size": 242.896, + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", + }, + ) + IMAGENET1K_V2 = Weights( + url="https://download.pytorch.org/models/wide_resnet101_2-d733dc28.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "num_params": 126886696, + "recipe": "https://github.com/pytorch/vision/issues/3995#new-recipe", + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.510, + "acc@5": 96.020, + } + }, + "_ops": 22.753, + "_file_size": 484.747, + "_docs": """ + These weights improve upon the results of the original paper by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V2 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNet18_Weights.IMAGENET1K_V1)) +def resnet18(*, weights: Optional[ResNet18_Weights] = None, progress: bool = True, **kwargs: Any) -> ResNet: + """ResNet-18 from `Deep Residual Learning for Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.ResNet18_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNet18_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ResNet18_Weights + :members: + """ + weights = ResNet18_Weights.verify(weights) + + return _resnet(BasicBlock, [2, 2, 2, 2], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNet34_Weights.IMAGENET1K_V1)) +def resnet34(*, weights: Optional[ResNet34_Weights] = None, progress: bool = True, **kwargs: Any) -> ResNet: + """ResNet-34 from `Deep Residual Learning for Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.ResNet34_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNet34_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ResNet34_Weights + :members: + """ + weights = ResNet34_Weights.verify(weights) + + return _resnet(BasicBlock, [3, 4, 6, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNet50_Weights.IMAGENET1K_V1)) +def resnet50(*, weights: Optional[ResNet50_Weights] = None, progress: bool = True, **kwargs: Any) -> ResNet: + """ResNet-50 from `Deep Residual Learning for Image Recognition `__. + + .. note:: + The bottleneck of TorchVision places the stride for downsampling to the second 3x3 + convolution while the original paper places it to the first 1x1 convolution. + This variant improves the accuracy and is known as `ResNet V1.5 + `_. + + Args: + weights (:class:`~torchvision.models.ResNet50_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNet50_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ResNet50_Weights + :members: + """ + weights = ResNet50_Weights.verify(weights) + + return _resnet(Bottleneck, [3, 4, 6, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNet101_Weights.IMAGENET1K_V1)) +def resnet101(*, weights: Optional[ResNet101_Weights] = None, progress: bool = True, **kwargs: Any) -> ResNet: + """ResNet-101 from `Deep Residual Learning for Image Recognition `__. + + .. note:: + The bottleneck of TorchVision places the stride for downsampling to the second 3x3 + convolution while the original paper places it to the first 1x1 convolution. + This variant improves the accuracy and is known as `ResNet V1.5 + `_. + + Args: + weights (:class:`~torchvision.models.ResNet101_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNet101_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ResNet101_Weights + :members: + """ + weights = ResNet101_Weights.verify(weights) + + return _resnet(Bottleneck, [3, 4, 23, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNet152_Weights.IMAGENET1K_V1)) +def resnet152(*, weights: Optional[ResNet152_Weights] = None, progress: bool = True, **kwargs: Any) -> ResNet: + """ResNet-152 from `Deep Residual Learning for Image Recognition `__. + + .. note:: + The bottleneck of TorchVision places the stride for downsampling to the second 3x3 + convolution while the original paper places it to the first 1x1 convolution. + This variant improves the accuracy and is known as `ResNet V1.5 + `_. + + Args: + weights (:class:`~torchvision.models.ResNet152_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNet152_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ResNet152_Weights + :members: + """ + weights = ResNet152_Weights.verify(weights) + + return _resnet(Bottleneck, [3, 8, 36, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNeXt50_32X4D_Weights.IMAGENET1K_V1)) +def resnext50_32x4d( + *, weights: Optional[ResNeXt50_32X4D_Weights] = None, progress: bool = True, **kwargs: Any +) -> ResNet: + """ResNeXt-50 32x4d model from + `Aggregated Residual Transformation for Deep Neural Networks `_. + + Args: + weights (:class:`~torchvision.models.ResNeXt50_32X4D_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNext50_32X4D_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.ResNeXt50_32X4D_Weights + :members: + """ + weights = ResNeXt50_32X4D_Weights.verify(weights) + + _ovewrite_named_param(kwargs, "groups", 32) + _ovewrite_named_param(kwargs, "width_per_group", 4) + return _resnet(Bottleneck, [3, 4, 6, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNeXt101_32X8D_Weights.IMAGENET1K_V1)) +def resnext101_32x8d( + *, weights: Optional[ResNeXt101_32X8D_Weights] = None, progress: bool = True, **kwargs: Any +) -> ResNet: + """ResNeXt-101 32x8d model from + `Aggregated Residual Transformation for Deep Neural Networks `_. + + Args: + weights (:class:`~torchvision.models.ResNeXt101_32X8D_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNeXt101_32X8D_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.ResNeXt101_32X8D_Weights + :members: + """ + weights = ResNeXt101_32X8D_Weights.verify(weights) + + _ovewrite_named_param(kwargs, "groups", 32) + _ovewrite_named_param(kwargs, "width_per_group", 8) + return _resnet(Bottleneck, [3, 4, 23, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ResNeXt101_64X4D_Weights.IMAGENET1K_V1)) +def resnext101_64x4d( + *, weights: Optional[ResNeXt101_64X4D_Weights] = None, progress: bool = True, **kwargs: Any +) -> ResNet: + """ResNeXt-101 64x4d model from + `Aggregated Residual Transformation for Deep Neural Networks `_. + + Args: + weights (:class:`~torchvision.models.ResNeXt101_64X4D_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ResNeXt101_64X4D_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.ResNeXt101_64X4D_Weights + :members: + """ + weights = ResNeXt101_64X4D_Weights.verify(weights) + + _ovewrite_named_param(kwargs, "groups", 64) + _ovewrite_named_param(kwargs, "width_per_group", 4) + return _resnet(Bottleneck, [3, 4, 23, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Wide_ResNet50_2_Weights.IMAGENET1K_V1)) +def wide_resnet50_2( + *, weights: Optional[Wide_ResNet50_2_Weights] = None, progress: bool = True, **kwargs: Any +) -> ResNet: + """Wide ResNet-50-2 model from + `Wide Residual Networks `_. + + The model is the same as ResNet except for the bottleneck number of channels + which is twice larger in every block. The number of channels in outer 1x1 + convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 + channels, and in Wide ResNet-50-2 has 2048-1024-2048. + + Args: + weights (:class:`~torchvision.models.Wide_ResNet50_2_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Wide_ResNet50_2_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.Wide_ResNet50_2_Weights + :members: + """ + weights = Wide_ResNet50_2_Weights.verify(weights) + + _ovewrite_named_param(kwargs, "width_per_group", 64 * 2) + return _resnet(Bottleneck, [3, 4, 6, 3], weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Wide_ResNet101_2_Weights.IMAGENET1K_V1)) +def wide_resnet101_2( + *, weights: Optional[Wide_ResNet101_2_Weights] = None, progress: bool = True, **kwargs: Any +) -> ResNet: + """Wide ResNet-101-2 model from + `Wide Residual Networks `_. + + The model is the same as ResNet except for the bottleneck number of channels + which is twice larger in every block. The number of channels in outer 1x1 + convolutions is the same, e.g. last block in ResNet-101 has 2048-512-2048 + channels, and in Wide ResNet-101-2 has 2048-1024-2048. + + Args: + weights (:class:`~torchvision.models.Wide_ResNet101_2_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Wide_ResNet101_2_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.resnet.ResNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + .. autoclass:: torchvision.models.Wide_ResNet101_2_Weights + :members: + """ + weights = Wide_ResNet101_2_Weights.verify(weights) + + _ovewrite_named_param(kwargs, "width_per_group", 64 * 2) + return _resnet(Bottleneck, [3, 4, 23, 3], weights, progress, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d6f37f958a131b76ce80306718b77d78bc3f045 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__init__.py @@ -0,0 +1,3 @@ +from .deeplabv3 import * +from .fcn import * +from .lraspp import * diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edd365113c570fa608e285ca646e0056b6fe4194 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7ab936c5a85c1447ffd68dcc987f397cd810ecf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/deeplabv3.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/deeplabv3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7a5856dbbf2892a28f5b00c88df279319500b9c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/deeplabv3.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/fcn.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/fcn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c258062752ca376617b54e0e84dd61be0d603bc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/fcn.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/lraspp.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/lraspp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dd84fbe9e72b5854b65f7ed03fbf1cc72e72ad9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/__pycache__/lraspp.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/_utils.py b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..45bc2e7c43563ad5603f4c53cfee3064cce5e4c7 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/_utils.py @@ -0,0 +1,37 @@ +from collections import OrderedDict +from typing import Optional + +from torch import nn, Tensor +from torch.nn import functional as F + +from ...utils import _log_api_usage_once + + +class _SimpleSegmentationModel(nn.Module): + __constants__ = ["aux_classifier"] + + def __init__(self, backbone: nn.Module, classifier: nn.Module, aux_classifier: Optional[nn.Module] = None) -> None: + super().__init__() + _log_api_usage_once(self) + self.backbone = backbone + self.classifier = classifier + self.aux_classifier = aux_classifier + + def forward(self, x: Tensor) -> dict[str, Tensor]: + input_shape = x.shape[-2:] + # contract: features is a dict of tensors + features = self.backbone(x) + + result = OrderedDict() + x = features["out"] + x = self.classifier(x) + x = F.interpolate(x, size=input_shape, mode="bilinear", align_corners=False) + result["out"] = x + + if self.aux_classifier is not None: + x = features["aux"] + x = self.aux_classifier(x) + x = F.interpolate(x, size=input_shape, mode="bilinear", align_corners=False) + result["aux"] = x + + return result diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/deeplabv3.py b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/deeplabv3.py new file mode 100644 index 0000000000000000000000000000000000000000..62790ecb4ddcb05753cf4e7d2004154ad1159e94 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/deeplabv3.py @@ -0,0 +1,391 @@ +from collections.abc import Sequence +from functools import partial +from typing import Any, Optional + +import torch +from torch import nn +from torch.nn import functional as F + +from ...transforms._presets import SemanticSegmentation +from .._api import register_model, Weights, WeightsEnum +from .._meta import _VOC_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface, IntermediateLayerGetter +from ..mobilenetv3 import mobilenet_v3_large, MobileNet_V3_Large_Weights, MobileNetV3 +from ..resnet import ResNet, resnet101, ResNet101_Weights, resnet50, ResNet50_Weights +from ._utils import _SimpleSegmentationModel +from .fcn import FCNHead + + +__all__ = [ + "DeepLabV3", + "DeepLabV3_ResNet50_Weights", + "DeepLabV3_ResNet101_Weights", + "DeepLabV3_MobileNet_V3_Large_Weights", + "deeplabv3_mobilenet_v3_large", + "deeplabv3_resnet50", + "deeplabv3_resnet101", +] + + +class DeepLabV3(_SimpleSegmentationModel): + """ + Implements DeepLabV3 model from + `"Rethinking Atrous Convolution for Semantic Image Segmentation" + `_. + + Args: + backbone (nn.Module): the network used to compute the features for the model. + The backbone should return an OrderedDict[Tensor], with the key being + "out" for the last feature map used, and "aux" if an auxiliary classifier + is used. + classifier (nn.Module): module that takes the "out" element returned from + the backbone and returns a dense prediction. + aux_classifier (nn.Module, optional): auxiliary classifier used during training + """ + + pass + + +class DeepLabHead(nn.Sequential): + def __init__(self, in_channels: int, num_classes: int, atrous_rates: Sequence[int] = (12, 24, 36)) -> None: + super().__init__( + ASPP(in_channels, atrous_rates), + nn.Conv2d(256, 256, 3, padding=1, bias=False), + nn.BatchNorm2d(256), + nn.ReLU(), + nn.Conv2d(256, num_classes, 1), + ) + + +class ASPPConv(nn.Sequential): + def __init__(self, in_channels: int, out_channels: int, dilation: int) -> None: + modules = [ + nn.Conv2d(in_channels, out_channels, 3, padding=dilation, dilation=dilation, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(), + ] + super().__init__(*modules) + + +class ASPPPooling(nn.Sequential): + def __init__(self, in_channels: int, out_channels: int) -> None: + super().__init__( + nn.AdaptiveAvgPool2d(1), + nn.Conv2d(in_channels, out_channels, 1, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + size = x.shape[-2:] + for mod in self: + x = mod(x) + return F.interpolate(x, size=size, mode="bilinear", align_corners=False) + + +class ASPP(nn.Module): + def __init__(self, in_channels: int, atrous_rates: Sequence[int], out_channels: int = 256) -> None: + super().__init__() + modules = [] + modules.append( + nn.Sequential(nn.Conv2d(in_channels, out_channels, 1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU()) + ) + + rates = tuple(atrous_rates) + for rate in rates: + modules.append(ASPPConv(in_channels, out_channels, rate)) + + modules.append(ASPPPooling(in_channels, out_channels)) + + self.convs = nn.ModuleList(modules) + + self.project = nn.Sequential( + nn.Conv2d(len(self.convs) * out_channels, out_channels, 1, bias=False), + nn.BatchNorm2d(out_channels), + nn.ReLU(), + nn.Dropout(0.5), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + _res = [] + for conv in self.convs: + _res.append(conv(x)) + res = torch.cat(_res, dim=1) + return self.project(res) + + +def _deeplabv3_resnet( + backbone: ResNet, + num_classes: int, + aux: Optional[bool], +) -> DeepLabV3: + return_layers = {"layer4": "out"} + if aux: + return_layers["layer3"] = "aux" + backbone = IntermediateLayerGetter(backbone, return_layers=return_layers) + + aux_classifier = FCNHead(1024, num_classes) if aux else None + classifier = DeepLabHead(2048, num_classes) + return DeepLabV3(backbone, classifier, aux_classifier) + + +_COMMON_META = { + "categories": _VOC_CATEGORIES, + "min_size": (1, 1), + "_docs": """ + These weights were trained on a subset of COCO, using only the 20 categories that are present in the Pascal VOC + dataset. + """, +} + + +class DeepLabV3_ResNet50_Weights(WeightsEnum): + COCO_WITH_VOC_LABELS_V1 = Weights( + url="https://download.pytorch.org/models/deeplabv3_resnet50_coco-cd0a2569.pth", + transforms=partial(SemanticSegmentation, resize_size=520), + meta={ + **_COMMON_META, + "num_params": 42004074, + "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#deeplabv3_resnet50", + "_metrics": { + "COCO-val2017-VOC-labels": { + "miou": 66.4, + "pixel_acc": 92.4, + } + }, + "_ops": 178.722, + "_file_size": 160.515, + }, + ) + DEFAULT = COCO_WITH_VOC_LABELS_V1 + + +class DeepLabV3_ResNet101_Weights(WeightsEnum): + COCO_WITH_VOC_LABELS_V1 = Weights( + url="https://download.pytorch.org/models/deeplabv3_resnet101_coco-586e9e4e.pth", + transforms=partial(SemanticSegmentation, resize_size=520), + meta={ + **_COMMON_META, + "num_params": 60996202, + "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#fcn_resnet101", + "_metrics": { + "COCO-val2017-VOC-labels": { + "miou": 67.4, + "pixel_acc": 92.4, + } + }, + "_ops": 258.743, + "_file_size": 233.217, + }, + ) + DEFAULT = COCO_WITH_VOC_LABELS_V1 + + +class DeepLabV3_MobileNet_V3_Large_Weights(WeightsEnum): + COCO_WITH_VOC_LABELS_V1 = Weights( + url="https://download.pytorch.org/models/deeplabv3_mobilenet_v3_large-fc3c493d.pth", + transforms=partial(SemanticSegmentation, resize_size=520), + meta={ + **_COMMON_META, + "num_params": 11029328, + "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#deeplabv3_mobilenet_v3_large", + "_metrics": { + "COCO-val2017-VOC-labels": { + "miou": 60.3, + "pixel_acc": 91.2, + } + }, + "_ops": 10.452, + "_file_size": 42.301, + }, + ) + DEFAULT = COCO_WITH_VOC_LABELS_V1 + + +def _deeplabv3_mobilenetv3( + backbone: MobileNetV3, + num_classes: int, + aux: Optional[bool], +) -> DeepLabV3: + backbone = backbone.features + # Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks. + # The first and last blocks are always included because they are the C0 (conv1) and Cn. + stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1] + out_pos = stage_indices[-1] # use C5 which has output_stride = 16 + out_inplanes = backbone[out_pos].out_channels + aux_pos = stage_indices[-4] # use C2 here which has output_stride = 8 + aux_inplanes = backbone[aux_pos].out_channels + return_layers = {str(out_pos): "out"} + if aux: + return_layers[str(aux_pos)] = "aux" + backbone = IntermediateLayerGetter(backbone, return_layers=return_layers) + + aux_classifier = FCNHead(aux_inplanes, num_classes) if aux else None + classifier = DeepLabHead(out_inplanes, num_classes) + return DeepLabV3(backbone, classifier, aux_classifier) + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", DeepLabV3_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def deeplabv3_resnet50( + *, + weights: Optional[DeepLabV3_ResNet50_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + aux_loss: Optional[bool] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + **kwargs: Any, +) -> DeepLabV3: + """Constructs a DeepLabV3 model with a ResNet-50 backbone. + + .. betastatus:: segmentation module + + Reference: `Rethinking Atrous Convolution for Semantic Image Segmentation `__. + + Args: + weights (:class:`~torchvision.models.segmentation.DeepLabV3_ResNet50_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.segmentation.DeepLabV3_ResNet50_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + aux_loss (bool, optional): If True, it uses an auxiliary loss + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained weights for the + backbone + **kwargs: unused + + .. autoclass:: torchvision.models.segmentation.DeepLabV3_ResNet50_Weights + :members: + """ + weights = DeepLabV3_ResNet50_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + aux_loss = _ovewrite_value_param("aux_loss", aux_loss, True) + elif num_classes is None: + num_classes = 21 + + backbone = resnet50(weights=weights_backbone, replace_stride_with_dilation=[False, True, True]) + model = _deeplabv3_resnet(backbone, num_classes, aux_loss) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", DeepLabV3_ResNet101_Weights.COCO_WITH_VOC_LABELS_V1), + weights_backbone=("pretrained_backbone", ResNet101_Weights.IMAGENET1K_V1), +) +def deeplabv3_resnet101( + *, + weights: Optional[DeepLabV3_ResNet101_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + aux_loss: Optional[bool] = None, + weights_backbone: Optional[ResNet101_Weights] = ResNet101_Weights.IMAGENET1K_V1, + **kwargs: Any, +) -> DeepLabV3: + """Constructs a DeepLabV3 model with a ResNet-101 backbone. + + .. betastatus:: segmentation module + + Reference: `Rethinking Atrous Convolution for Semantic Image Segmentation `__. + + Args: + weights (:class:`~torchvision.models.segmentation.DeepLabV3_ResNet101_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.segmentation.DeepLabV3_ResNet101_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + aux_loss (bool, optional): If True, it uses an auxiliary loss + weights_backbone (:class:`~torchvision.models.ResNet101_Weights`, optional): The pretrained weights for the + backbone + **kwargs: unused + + .. autoclass:: torchvision.models.segmentation.DeepLabV3_ResNet101_Weights + :members: + """ + weights = DeepLabV3_ResNet101_Weights.verify(weights) + weights_backbone = ResNet101_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + aux_loss = _ovewrite_value_param("aux_loss", aux_loss, True) + elif num_classes is None: + num_classes = 21 + + backbone = resnet101(weights=weights_backbone, replace_stride_with_dilation=[False, True, True]) + model = _deeplabv3_resnet(backbone, num_classes, aux_loss) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", DeepLabV3_MobileNet_V3_Large_Weights.COCO_WITH_VOC_LABELS_V1), + weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1), +) +def deeplabv3_mobilenet_v3_large( + *, + weights: Optional[DeepLabV3_MobileNet_V3_Large_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + aux_loss: Optional[bool] = None, + weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1, + **kwargs: Any, +) -> DeepLabV3: + """Constructs a DeepLabV3 model with a MobileNetV3-Large backbone. + + Reference: `Rethinking Atrous Convolution for Semantic Image Segmentation `__. + + Args: + weights (:class:`~torchvision.models.segmentation.DeepLabV3_MobileNet_V3_Large_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.segmentation.DeepLabV3_MobileNet_V3_Large_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background) + aux_loss (bool, optional): If True, it uses an auxiliary loss + weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The pretrained weights + for the backbone + **kwargs: unused + + .. autoclass:: torchvision.models.segmentation.DeepLabV3_MobileNet_V3_Large_Weights + :members: + """ + weights = DeepLabV3_MobileNet_V3_Large_Weights.verify(weights) + weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + aux_loss = _ovewrite_value_param("aux_loss", aux_loss, True) + elif num_classes is None: + num_classes = 21 + + backbone = mobilenet_v3_large(weights=weights_backbone, dilated=True) + model = _deeplabv3_mobilenetv3(backbone, num_classes, aux_loss) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/fcn.py b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/fcn.py new file mode 100644 index 0000000000000000000000000000000000000000..fb2e242adac0e7430bab6155ae0347770e29fee9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/fcn.py @@ -0,0 +1,232 @@ +from functools import partial +from typing import Any, Optional + +from torch import nn + +from ...transforms._presets import SemanticSegmentation +from .._api import register_model, Weights, WeightsEnum +from .._meta import _VOC_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface, IntermediateLayerGetter +from ..resnet import ResNet, resnet101, ResNet101_Weights, resnet50, ResNet50_Weights +from ._utils import _SimpleSegmentationModel + + +__all__ = ["FCN", "FCN_ResNet50_Weights", "FCN_ResNet101_Weights", "fcn_resnet50", "fcn_resnet101"] + + +class FCN(_SimpleSegmentationModel): + """ + Implements FCN model from + `"Fully Convolutional Networks for Semantic Segmentation" + `_. + + Args: + backbone (nn.Module): the network used to compute the features for the model. + The backbone should return an OrderedDict[Tensor], with the key being + "out" for the last feature map used, and "aux" if an auxiliary classifier + is used. + classifier (nn.Module): module that takes the "out" element returned from + the backbone and returns a dense prediction. + aux_classifier (nn.Module, optional): auxiliary classifier used during training + """ + + pass + + +class FCNHead(nn.Sequential): + def __init__(self, in_channels: int, channels: int) -> None: + inter_channels = in_channels // 4 + layers = [ + nn.Conv2d(in_channels, inter_channels, 3, padding=1, bias=False), + nn.BatchNorm2d(inter_channels), + nn.ReLU(), + nn.Dropout(0.1), + nn.Conv2d(inter_channels, channels, 1), + ] + + super().__init__(*layers) + + +_COMMON_META = { + "categories": _VOC_CATEGORIES, + "min_size": (1, 1), + "_docs": """ + These weights were trained on a subset of COCO, using only the 20 categories that are present in the Pascal VOC + dataset. + """, +} + + +class FCN_ResNet50_Weights(WeightsEnum): + COCO_WITH_VOC_LABELS_V1 = Weights( + url="https://download.pytorch.org/models/fcn_resnet50_coco-1167a1af.pth", + transforms=partial(SemanticSegmentation, resize_size=520), + meta={ + **_COMMON_META, + "num_params": 35322218, + "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#fcn_resnet50", + "_metrics": { + "COCO-val2017-VOC-labels": { + "miou": 60.5, + "pixel_acc": 91.4, + } + }, + "_ops": 152.717, + "_file_size": 135.009, + }, + ) + DEFAULT = COCO_WITH_VOC_LABELS_V1 + + +class FCN_ResNet101_Weights(WeightsEnum): + COCO_WITH_VOC_LABELS_V1 = Weights( + url="https://download.pytorch.org/models/fcn_resnet101_coco-7ecb50ca.pth", + transforms=partial(SemanticSegmentation, resize_size=520), + meta={ + **_COMMON_META, + "num_params": 54314346, + "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#deeplabv3_resnet101", + "_metrics": { + "COCO-val2017-VOC-labels": { + "miou": 63.7, + "pixel_acc": 91.9, + } + }, + "_ops": 232.738, + "_file_size": 207.711, + }, + ) + DEFAULT = COCO_WITH_VOC_LABELS_V1 + + +def _fcn_resnet( + backbone: ResNet, + num_classes: int, + aux: Optional[bool], +) -> FCN: + return_layers = {"layer4": "out"} + if aux: + return_layers["layer3"] = "aux" + backbone = IntermediateLayerGetter(backbone, return_layers=return_layers) + + aux_classifier = FCNHead(1024, num_classes) if aux else None + classifier = FCNHead(2048, num_classes) + return FCN(backbone, classifier, aux_classifier) + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", FCN_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1), + weights_backbone=("pretrained_backbone", ResNet50_Weights.IMAGENET1K_V1), +) +def fcn_resnet50( + *, + weights: Optional[FCN_ResNet50_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + aux_loss: Optional[bool] = None, + weights_backbone: Optional[ResNet50_Weights] = ResNet50_Weights.IMAGENET1K_V1, + **kwargs: Any, +) -> FCN: + """Fully-Convolutional Network model with a ResNet-50 backbone from the `Fully Convolutional + Networks for Semantic Segmentation `_ paper. + + .. betastatus:: segmentation module + + Args: + weights (:class:`~torchvision.models.segmentation.FCN_ResNet50_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.segmentation.FCN_ResNet50_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background). + aux_loss (bool, optional): If True, it uses an auxiliary loss. + weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained + weights for the backbone. + **kwargs: parameters passed to the ``torchvision.models.segmentation.fcn.FCN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.segmentation.FCN_ResNet50_Weights + :members: + """ + + weights = FCN_ResNet50_Weights.verify(weights) + weights_backbone = ResNet50_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + aux_loss = _ovewrite_value_param("aux_loss", aux_loss, True) + elif num_classes is None: + num_classes = 21 + + backbone = resnet50(weights=weights_backbone, replace_stride_with_dilation=[False, True, True]) + model = _fcn_resnet(backbone, num_classes, aux_loss) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", FCN_ResNet101_Weights.COCO_WITH_VOC_LABELS_V1), + weights_backbone=("pretrained_backbone", ResNet101_Weights.IMAGENET1K_V1), +) +def fcn_resnet101( + *, + weights: Optional[FCN_ResNet101_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + aux_loss: Optional[bool] = None, + weights_backbone: Optional[ResNet101_Weights] = ResNet101_Weights.IMAGENET1K_V1, + **kwargs: Any, +) -> FCN: + """Fully-Convolutional Network model with a ResNet-101 backbone from the `Fully Convolutional + Networks for Semantic Segmentation `_ paper. + + .. betastatus:: segmentation module + + Args: + weights (:class:`~torchvision.models.segmentation.FCN_ResNet101_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.segmentation.FCN_ResNet101_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background). + aux_loss (bool, optional): If True, it uses an auxiliary loss. + weights_backbone (:class:`~torchvision.models.ResNet101_Weights`, optional): The pretrained + weights for the backbone. + **kwargs: parameters passed to the ``torchvision.models.segmentation.fcn.FCN`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.segmentation.FCN_ResNet101_Weights + :members: + """ + + weights = FCN_ResNet101_Weights.verify(weights) + weights_backbone = ResNet101_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + aux_loss = _ovewrite_value_param("aux_loss", aux_loss, True) + elif num_classes is None: + num_classes = 21 + + backbone = resnet101(weights=weights_backbone, replace_stride_with_dilation=[False, True, True]) + model = _fcn_resnet(backbone, num_classes, aux_loss) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/lraspp.py b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/lraspp.py new file mode 100644 index 0000000000000000000000000000000000000000..e49b06d5b9facef807acc8fc9516a53d56ef01c4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/segmentation/lraspp.py @@ -0,0 +1,178 @@ +from collections import OrderedDict +from functools import partial +from typing import Any, Optional + +from torch import nn, Tensor +from torch.nn import functional as F + +from ...transforms._presets import SemanticSegmentation +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _VOC_CATEGORIES +from .._utils import _ovewrite_value_param, handle_legacy_interface, IntermediateLayerGetter +from ..mobilenetv3 import mobilenet_v3_large, MobileNet_V3_Large_Weights, MobileNetV3 + + +__all__ = ["LRASPP", "LRASPP_MobileNet_V3_Large_Weights", "lraspp_mobilenet_v3_large"] + + +class LRASPP(nn.Module): + """ + Implements a Lite R-ASPP Network for semantic segmentation from + `"Searching for MobileNetV3" + `_. + + Args: + backbone (nn.Module): the network used to compute the features for the model. + The backbone should return an OrderedDict[Tensor], with the key being + "high" for the high level feature map and "low" for the low level feature map. + low_channels (int): the number of channels of the low level features. + high_channels (int): the number of channels of the high level features. + num_classes (int, optional): number of output classes of the model (including the background). + inter_channels (int, optional): the number of channels for intermediate computations. + """ + + def __init__( + self, backbone: nn.Module, low_channels: int, high_channels: int, num_classes: int, inter_channels: int = 128 + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.backbone = backbone + self.classifier = LRASPPHead(low_channels, high_channels, num_classes, inter_channels) + + def forward(self, input: Tensor) -> dict[str, Tensor]: + features = self.backbone(input) + out = self.classifier(features) + out = F.interpolate(out, size=input.shape[-2:], mode="bilinear", align_corners=False) + + result = OrderedDict() + result["out"] = out + + return result + + +class LRASPPHead(nn.Module): + def __init__(self, low_channels: int, high_channels: int, num_classes: int, inter_channels: int) -> None: + super().__init__() + self.cbr = nn.Sequential( + nn.Conv2d(high_channels, inter_channels, 1, bias=False), + nn.BatchNorm2d(inter_channels), + nn.ReLU(inplace=True), + ) + self.scale = nn.Sequential( + nn.AdaptiveAvgPool2d(1), + nn.Conv2d(high_channels, inter_channels, 1, bias=False), + nn.Sigmoid(), + ) + self.low_classifier = nn.Conv2d(low_channels, num_classes, 1) + self.high_classifier = nn.Conv2d(inter_channels, num_classes, 1) + + def forward(self, input: dict[str, Tensor]) -> Tensor: + low = input["low"] + high = input["high"] + + x = self.cbr(high) + s = self.scale(high) + x = x * s + x = F.interpolate(x, size=low.shape[-2:], mode="bilinear", align_corners=False) + + return self.low_classifier(low) + self.high_classifier(x) + + +def _lraspp_mobilenetv3(backbone: MobileNetV3, num_classes: int) -> LRASPP: + backbone = backbone.features + # Gather the indices of blocks which are strided. These are the locations of C1, ..., Cn-1 blocks. + # The first and last blocks are always included because they are the C0 (conv1) and Cn. + stage_indices = [0] + [i for i, b in enumerate(backbone) if getattr(b, "_is_cn", False)] + [len(backbone) - 1] + low_pos = stage_indices[-4] # use C2 here which has output_stride = 8 + high_pos = stage_indices[-1] # use C5 which has output_stride = 16 + low_channels = backbone[low_pos].out_channels + high_channels = backbone[high_pos].out_channels + backbone = IntermediateLayerGetter(backbone, return_layers={str(low_pos): "low", str(high_pos): "high"}) + + return LRASPP(backbone, low_channels, high_channels, num_classes) + + +class LRASPP_MobileNet_V3_Large_Weights(WeightsEnum): + COCO_WITH_VOC_LABELS_V1 = Weights( + url="https://download.pytorch.org/models/lraspp_mobilenet_v3_large-d234d4ea.pth", + transforms=partial(SemanticSegmentation, resize_size=520), + meta={ + "num_params": 3221538, + "categories": _VOC_CATEGORIES, + "min_size": (1, 1), + "recipe": "https://github.com/pytorch/vision/tree/main/references/segmentation#lraspp_mobilenet_v3_large", + "_metrics": { + "COCO-val2017-VOC-labels": { + "miou": 57.9, + "pixel_acc": 91.2, + } + }, + "_ops": 2.086, + "_file_size": 12.49, + "_docs": """ + These weights were trained on a subset of COCO, using only the 20 categories that are present in the + Pascal VOC dataset. + """, + }, + ) + DEFAULT = COCO_WITH_VOC_LABELS_V1 + + +@register_model() +@handle_legacy_interface( + weights=("pretrained", LRASPP_MobileNet_V3_Large_Weights.COCO_WITH_VOC_LABELS_V1), + weights_backbone=("pretrained_backbone", MobileNet_V3_Large_Weights.IMAGENET1K_V1), +) +def lraspp_mobilenet_v3_large( + *, + weights: Optional[LRASPP_MobileNet_V3_Large_Weights] = None, + progress: bool = True, + num_classes: Optional[int] = None, + weights_backbone: Optional[MobileNet_V3_Large_Weights] = MobileNet_V3_Large_Weights.IMAGENET1K_V1, + **kwargs: Any, +) -> LRASPP: + """Constructs a Lite R-ASPP Network model with a MobileNetV3-Large backbone from + `Searching for MobileNetV3 `_ paper. + + .. betastatus:: segmentation module + + Args: + weights (:class:`~torchvision.models.segmentation.LRASPP_MobileNet_V3_Large_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.segmentation.LRASPP_MobileNet_V3_Large_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + num_classes (int, optional): number of output classes of the model (including the background). + aux_loss (bool, optional): If True, it uses an auxiliary loss. + weights_backbone (:class:`~torchvision.models.MobileNet_V3_Large_Weights`, optional): The pretrained + weights for the backbone. + **kwargs: parameters passed to the ``torchvision.models.segmentation.LRASPP`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.segmentation.LRASPP_MobileNet_V3_Large_Weights + :members: + """ + if kwargs.pop("aux_loss", False): + raise NotImplementedError("This model does not use auxiliary loss") + + weights = LRASPP_MobileNet_V3_Large_Weights.verify(weights) + weights_backbone = MobileNet_V3_Large_Weights.verify(weights_backbone) + + if weights is not None: + weights_backbone = None + num_classes = _ovewrite_value_param("num_classes", num_classes, len(weights.meta["categories"])) + elif num_classes is None: + num_classes = 21 + + backbone = mobilenet_v3_large(weights=weights_backbone, dilated=True) + model = _lraspp_mobilenetv3(backbone, num_classes) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/shufflenetv2.py b/.venv/lib/python3.12/site-packages/torchvision/models/shufflenetv2.py new file mode 100644 index 0000000000000000000000000000000000000000..96736f6a7ac289102ef7a57cb4cbb960c02c625e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/shufflenetv2.py @@ -0,0 +1,408 @@ +from functools import partial +from typing import Any, Callable, Optional + +import torch +import torch.nn as nn +from torch import Tensor + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "ShuffleNetV2", + "ShuffleNet_V2_X0_5_Weights", + "ShuffleNet_V2_X1_0_Weights", + "ShuffleNet_V2_X1_5_Weights", + "ShuffleNet_V2_X2_0_Weights", + "shufflenet_v2_x0_5", + "shufflenet_v2_x1_0", + "shufflenet_v2_x1_5", + "shufflenet_v2_x2_0", +] + + +def channel_shuffle(x: Tensor, groups: int) -> Tensor: + batchsize, num_channels, height, width = x.size() + channels_per_group = num_channels // groups + + # reshape + x = x.view(batchsize, groups, channels_per_group, height, width) + + x = torch.transpose(x, 1, 2).contiguous() + + # flatten + x = x.view(batchsize, num_channels, height, width) + + return x + + +class InvertedResidual(nn.Module): + def __init__(self, inp: int, oup: int, stride: int) -> None: + super().__init__() + + if not (1 <= stride <= 3): + raise ValueError("illegal stride value") + self.stride = stride + + branch_features = oup // 2 + if (self.stride == 1) and (inp != branch_features << 1): + raise ValueError( + f"Invalid combination of stride {stride}, inp {inp} and oup {oup} values. If stride == 1 then inp should be equal to oup // 2 << 1." + ) + + if self.stride > 1: + self.branch1 = nn.Sequential( + self.depthwise_conv(inp, inp, kernel_size=3, stride=self.stride, padding=1), + nn.BatchNorm2d(inp), + nn.Conv2d(inp, branch_features, kernel_size=1, stride=1, padding=0, bias=False), + nn.BatchNorm2d(branch_features), + nn.ReLU(inplace=True), + ) + else: + self.branch1 = nn.Sequential() + + self.branch2 = nn.Sequential( + nn.Conv2d( + inp if (self.stride > 1) else branch_features, + branch_features, + kernel_size=1, + stride=1, + padding=0, + bias=False, + ), + nn.BatchNorm2d(branch_features), + nn.ReLU(inplace=True), + self.depthwise_conv(branch_features, branch_features, kernel_size=3, stride=self.stride, padding=1), + nn.BatchNorm2d(branch_features), + nn.Conv2d(branch_features, branch_features, kernel_size=1, stride=1, padding=0, bias=False), + nn.BatchNorm2d(branch_features), + nn.ReLU(inplace=True), + ) + + @staticmethod + def depthwise_conv( + i: int, o: int, kernel_size: int, stride: int = 1, padding: int = 0, bias: bool = False + ) -> nn.Conv2d: + return nn.Conv2d(i, o, kernel_size, stride, padding, bias=bias, groups=i) + + def forward(self, x: Tensor) -> Tensor: + if self.stride == 1: + x1, x2 = x.chunk(2, dim=1) + out = torch.cat((x1, self.branch2(x2)), dim=1) + else: + out = torch.cat((self.branch1(x), self.branch2(x)), dim=1) + + out = channel_shuffle(out, 2) + + return out + + +class ShuffleNetV2(nn.Module): + def __init__( + self, + stages_repeats: list[int], + stages_out_channels: list[int], + num_classes: int = 1000, + inverted_residual: Callable[..., nn.Module] = InvertedResidual, + ) -> None: + super().__init__() + _log_api_usage_once(self) + + if len(stages_repeats) != 3: + raise ValueError("expected stages_repeats as list of 3 positive ints") + if len(stages_out_channels) != 5: + raise ValueError("expected stages_out_channels as list of 5 positive ints") + self._stage_out_channels = stages_out_channels + + input_channels = 3 + output_channels = self._stage_out_channels[0] + self.conv1 = nn.Sequential( + nn.Conv2d(input_channels, output_channels, 3, 2, 1, bias=False), + nn.BatchNorm2d(output_channels), + nn.ReLU(inplace=True), + ) + input_channels = output_channels + + self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) + + # Static annotations for mypy + self.stage2: nn.Sequential + self.stage3: nn.Sequential + self.stage4: nn.Sequential + stage_names = [f"stage{i}" for i in [2, 3, 4]] + for name, repeats, output_channels in zip(stage_names, stages_repeats, self._stage_out_channels[1:]): + seq = [inverted_residual(input_channels, output_channels, 2)] + for i in range(repeats - 1): + seq.append(inverted_residual(output_channels, output_channels, 1)) + setattr(self, name, nn.Sequential(*seq)) + input_channels = output_channels + + output_channels = self._stage_out_channels[-1] + self.conv5 = nn.Sequential( + nn.Conv2d(input_channels, output_channels, 1, 1, 0, bias=False), + nn.BatchNorm2d(output_channels), + nn.ReLU(inplace=True), + ) + + self.fc = nn.Linear(output_channels, num_classes) + + def _forward_impl(self, x: Tensor) -> Tensor: + # See note [TorchScript super()] + x = self.conv1(x) + x = self.maxpool(x) + x = self.stage2(x) + x = self.stage3(x) + x = self.stage4(x) + x = self.conv5(x) + x = x.mean([2, 3]) # globalpool + x = self.fc(x) + return x + + def forward(self, x: Tensor) -> Tensor: + return self._forward_impl(x) + + +def _shufflenetv2( + weights: Optional[WeightsEnum], + progress: bool, + *args: Any, + **kwargs: Any, +) -> ShuffleNetV2: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = ShuffleNetV2(*args, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/ericsun99/Shufflenet-v2-Pytorch", +} + + +class ShuffleNet_V2_X0_5_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/ericsun99/Shufflenet-v2-Pytorch + url="https://download.pytorch.org/models/shufflenetv2_x0.5-f707e7126e.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 1366792, + "_metrics": { + "ImageNet-1K": { + "acc@1": 60.552, + "acc@5": 81.746, + } + }, + "_ops": 0.04, + "_file_size": 5.282, + "_docs": """These weights were trained from scratch to reproduce closely the results of the paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ShuffleNet_V2_X1_0_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + # Weights ported from https://github.com/ericsun99/Shufflenet-v2-Pytorch + url="https://download.pytorch.org/models/shufflenetv2_x1-5666bf0f80.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 2278604, + "_metrics": { + "ImageNet-1K": { + "acc@1": 69.362, + "acc@5": 88.316, + } + }, + "_ops": 0.145, + "_file_size": 8.791, + "_docs": """These weights were trained from scratch to reproduce closely the results of the paper.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ShuffleNet_V2_X1_5_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/shufflenetv2_x1_5-3c479a10.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/pull/5906", + "num_params": 3503624, + "_metrics": { + "ImageNet-1K": { + "acc@1": 72.996, + "acc@5": 91.086, + } + }, + "_ops": 0.296, + "_file_size": 13.557, + "_docs": """ + These weights were trained from scratch by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ShuffleNet_V2_X2_0_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/shufflenetv2_x2_0-8be3c8ee.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=232), + meta={ + **_COMMON_META, + "recipe": "https://github.com/pytorch/vision/pull/5906", + "num_params": 7393996, + "_metrics": { + "ImageNet-1K": { + "acc@1": 76.230, + "acc@5": 93.006, + } + }, + "_ops": 0.583, + "_file_size": 28.433, + "_docs": """ + These weights were trained from scratch by using TorchVision's `new training recipe + `_. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X0_5_Weights.IMAGENET1K_V1)) +def shufflenet_v2_x0_5( + *, weights: Optional[ShuffleNet_V2_X0_5_Weights] = None, progress: bool = True, **kwargs: Any +) -> ShuffleNetV2: + """ + Constructs a ShuffleNetV2 architecture with 0.5x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + Args: + weights (:class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ShuffleNet_V2_X0_5_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ShuffleNet_V2_X0_5_Weights + :members: + """ + weights = ShuffleNet_V2_X0_5_Weights.verify(weights) + + return _shufflenetv2(weights, progress, [4, 8, 4], [24, 48, 96, 192, 1024], **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X1_0_Weights.IMAGENET1K_V1)) +def shufflenet_v2_x1_0( + *, weights: Optional[ShuffleNet_V2_X1_0_Weights] = None, progress: bool = True, **kwargs: Any +) -> ShuffleNetV2: + """ + Constructs a ShuffleNetV2 architecture with 1.0x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + Args: + weights (:class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ShuffleNet_V2_X1_0_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ShuffleNet_V2_X1_0_Weights + :members: + """ + weights = ShuffleNet_V2_X1_0_Weights.verify(weights) + + return _shufflenetv2(weights, progress, [4, 8, 4], [24, 116, 232, 464, 1024], **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X1_5_Weights.IMAGENET1K_V1)) +def shufflenet_v2_x1_5( + *, weights: Optional[ShuffleNet_V2_X1_5_Weights] = None, progress: bool = True, **kwargs: Any +) -> ShuffleNetV2: + """ + Constructs a ShuffleNetV2 architecture with 1.5x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + Args: + weights (:class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ShuffleNet_V2_X1_5_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ShuffleNet_V2_X1_5_Weights + :members: + """ + weights = ShuffleNet_V2_X1_5_Weights.verify(weights) + + return _shufflenetv2(weights, progress, [4, 8, 4], [24, 176, 352, 704, 1024], **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ShuffleNet_V2_X2_0_Weights.IMAGENET1K_V1)) +def shufflenet_v2_x2_0( + *, weights: Optional[ShuffleNet_V2_X2_0_Weights] = None, progress: bool = True, **kwargs: Any +) -> ShuffleNetV2: + """ + Constructs a ShuffleNetV2 architecture with 2.0x output channels, as described in + `ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design + `__. + + Args: + weights (:class:`~torchvision.models.ShuffleNet_V2_X2_0_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.ShuffleNet_V2_X2_0_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.shufflenetv2.ShuffleNetV2`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ShuffleNet_V2_X2_0_Weights + :members: + """ + weights = ShuffleNet_V2_X2_0_Weights.verify(weights) + + return _shufflenetv2(weights, progress, [4, 8, 4], [24, 244, 488, 976, 2048], **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/squeezenet.py b/.venv/lib/python3.12/site-packages/torchvision/models/squeezenet.py new file mode 100644 index 0000000000000000000000000000000000000000..982b32107b09c280b4c7caa61e6b80be0cbf041e --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/squeezenet.py @@ -0,0 +1,223 @@ +from functools import partial +from typing import Any, Optional + +import torch +import torch.nn as nn +import torch.nn.init as init + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = ["SqueezeNet", "SqueezeNet1_0_Weights", "SqueezeNet1_1_Weights", "squeezenet1_0", "squeezenet1_1"] + + +class Fire(nn.Module): + def __init__(self, inplanes: int, squeeze_planes: int, expand1x1_planes: int, expand3x3_planes: int) -> None: + super().__init__() + self.inplanes = inplanes + self.squeeze = nn.Conv2d(inplanes, squeeze_planes, kernel_size=1) + self.squeeze_activation = nn.ReLU(inplace=True) + self.expand1x1 = nn.Conv2d(squeeze_planes, expand1x1_planes, kernel_size=1) + self.expand1x1_activation = nn.ReLU(inplace=True) + self.expand3x3 = nn.Conv2d(squeeze_planes, expand3x3_planes, kernel_size=3, padding=1) + self.expand3x3_activation = nn.ReLU(inplace=True) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.squeeze_activation(self.squeeze(x)) + return torch.cat( + [self.expand1x1_activation(self.expand1x1(x)), self.expand3x3_activation(self.expand3x3(x))], 1 + ) + + +class SqueezeNet(nn.Module): + def __init__(self, version: str = "1_0", num_classes: int = 1000, dropout: float = 0.5) -> None: + super().__init__() + _log_api_usage_once(self) + self.num_classes = num_classes + if version == "1_0": + self.features = nn.Sequential( + nn.Conv2d(3, 96, kernel_size=7, stride=2), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(96, 16, 64, 64), + Fire(128, 16, 64, 64), + Fire(128, 32, 128, 128), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(256, 32, 128, 128), + Fire(256, 48, 192, 192), + Fire(384, 48, 192, 192), + Fire(384, 64, 256, 256), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(512, 64, 256, 256), + ) + elif version == "1_1": + self.features = nn.Sequential( + nn.Conv2d(3, 64, kernel_size=3, stride=2), + nn.ReLU(inplace=True), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(64, 16, 64, 64), + Fire(128, 16, 64, 64), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(128, 32, 128, 128), + Fire(256, 32, 128, 128), + nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), + Fire(256, 48, 192, 192), + Fire(384, 48, 192, 192), + Fire(384, 64, 256, 256), + Fire(512, 64, 256, 256), + ) + else: + # FIXME: Is this needed? SqueezeNet should only be called from the + # FIXME: squeezenet1_x() functions + # FIXME: This checking is not done for the other models + raise ValueError(f"Unsupported SqueezeNet version {version}: 1_0 or 1_1 expected") + + # Final convolution is initialized differently from the rest + final_conv = nn.Conv2d(512, self.num_classes, kernel_size=1) + self.classifier = nn.Sequential( + nn.Dropout(p=dropout), final_conv, nn.ReLU(inplace=True), nn.AdaptiveAvgPool2d((1, 1)) + ) + + for m in self.modules(): + if isinstance(m, nn.Conv2d): + if m is final_conv: + init.normal_(m.weight, mean=0.0, std=0.01) + else: + init.kaiming_uniform_(m.weight) + if m.bias is not None: + init.constant_(m.bias, 0) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.features(x) + x = self.classifier(x) + return torch.flatten(x, 1) + + +def _squeezenet( + version: str, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> SqueezeNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = SqueezeNet(version, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/pull/49#issuecomment-277560717", + "_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""", +} + + +class SqueezeNet1_0_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/squeezenet1_0-b66bff10.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "min_size": (21, 21), + "num_params": 1248424, + "_metrics": { + "ImageNet-1K": { + "acc@1": 58.092, + "acc@5": 80.420, + } + }, + "_ops": 0.819, + "_file_size": 4.778, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class SqueezeNet1_1_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/squeezenet1_1-b8a52dc0.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "min_size": (17, 17), + "num_params": 1235496, + "_metrics": { + "ImageNet-1K": { + "acc@1": 58.178, + "acc@5": 80.624, + } + }, + "_ops": 0.349, + "_file_size": 4.729, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", SqueezeNet1_0_Weights.IMAGENET1K_V1)) +def squeezenet1_0( + *, weights: Optional[SqueezeNet1_0_Weights] = None, progress: bool = True, **kwargs: Any +) -> SqueezeNet: + """SqueezeNet model architecture from the `SqueezeNet: AlexNet-level + accuracy with 50x fewer parameters and <0.5MB model size + `_ paper. + + Args: + weights (:class:`~torchvision.models.SqueezeNet1_0_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.SqueezeNet1_0_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.squeezenet.SqueezeNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.SqueezeNet1_0_Weights + :members: + """ + weights = SqueezeNet1_0_Weights.verify(weights) + return _squeezenet("1_0", weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", SqueezeNet1_1_Weights.IMAGENET1K_V1)) +def squeezenet1_1( + *, weights: Optional[SqueezeNet1_1_Weights] = None, progress: bool = True, **kwargs: Any +) -> SqueezeNet: + """SqueezeNet 1.1 model from the `official SqueezeNet repo + `_. + + SqueezeNet 1.1 has 2.4x less computation and slightly fewer parameters + than SqueezeNet 1.0, without sacrificing accuracy. + + Args: + weights (:class:`~torchvision.models.SqueezeNet1_1_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.SqueezeNet1_1_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.squeezenet.SqueezeNet`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.SqueezeNet1_1_Weights + :members: + """ + weights = SqueezeNet1_1_Weights.verify(weights) + return _squeezenet("1_1", weights, progress, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/swin_transformer.py b/.venv/lib/python3.12/site-packages/torchvision/models/swin_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..80850b4a389e6488a2d5ae76a4159b5ad26a6faa --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/swin_transformer.py @@ -0,0 +1,1033 @@ +import math +from functools import partial +from typing import Any, Callable, Optional + +import torch +import torch.nn.functional as F +from torch import nn, Tensor + +from ..ops.misc import MLP, Permute +from ..ops.stochastic_depth import StochasticDepth +from ..transforms._presets import ImageClassification, InterpolationMode +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "SwinTransformer", + "Swin_T_Weights", + "Swin_S_Weights", + "Swin_B_Weights", + "Swin_V2_T_Weights", + "Swin_V2_S_Weights", + "Swin_V2_B_Weights", + "swin_t", + "swin_s", + "swin_b", + "swin_v2_t", + "swin_v2_s", + "swin_v2_b", +] + + +def _patch_merging_pad(x: torch.Tensor) -> torch.Tensor: + H, W, _ = x.shape[-3:] + x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2)) + x0 = x[..., 0::2, 0::2, :] # ... H/2 W/2 C + x1 = x[..., 1::2, 0::2, :] # ... H/2 W/2 C + x2 = x[..., 0::2, 1::2, :] # ... H/2 W/2 C + x3 = x[..., 1::2, 1::2, :] # ... H/2 W/2 C + x = torch.cat([x0, x1, x2, x3], -1) # ... H/2 W/2 4*C + return x + + +torch.fx.wrap("_patch_merging_pad") + + +def _get_relative_position_bias( + relative_position_bias_table: torch.Tensor, relative_position_index: torch.Tensor, window_size: list[int] +) -> torch.Tensor: + N = window_size[0] * window_size[1] + relative_position_bias = relative_position_bias_table[relative_position_index] # type: ignore[index] + relative_position_bias = relative_position_bias.view(N, N, -1) + relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous().unsqueeze(0) + return relative_position_bias + + +torch.fx.wrap("_get_relative_position_bias") + + +class PatchMerging(nn.Module): + """Patch Merging Layer. + Args: + dim (int): Number of input channels. + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + """ + + def __init__(self, dim: int, norm_layer: Callable[..., nn.Module] = nn.LayerNorm): + super().__init__() + _log_api_usage_once(self) + self.dim = dim + self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) + self.norm = norm_layer(4 * dim) + + def forward(self, x: Tensor): + """ + Args: + x (Tensor): input tensor with expected layout of [..., H, W, C] + Returns: + Tensor with layout of [..., H/2, W/2, 2*C] + """ + x = _patch_merging_pad(x) + x = self.norm(x) + x = self.reduction(x) # ... H/2 W/2 2*C + return x + + +class PatchMergingV2(nn.Module): + """Patch Merging Layer for Swin Transformer V2. + Args: + dim (int): Number of input channels. + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + """ + + def __init__(self, dim: int, norm_layer: Callable[..., nn.Module] = nn.LayerNorm): + super().__init__() + _log_api_usage_once(self) + self.dim = dim + self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) + self.norm = norm_layer(2 * dim) # difference + + def forward(self, x: Tensor): + """ + Args: + x (Tensor): input tensor with expected layout of [..., H, W, C] + Returns: + Tensor with layout of [..., H/2, W/2, 2*C] + """ + x = _patch_merging_pad(x) + x = self.reduction(x) # ... H/2 W/2 2*C + x = self.norm(x) + return x + + +def shifted_window_attention( + input: Tensor, + qkv_weight: Tensor, + proj_weight: Tensor, + relative_position_bias: Tensor, + window_size: list[int], + num_heads: int, + shift_size: list[int], + attention_dropout: float = 0.0, + dropout: float = 0.0, + qkv_bias: Optional[Tensor] = None, + proj_bias: Optional[Tensor] = None, + logit_scale: Optional[torch.Tensor] = None, + training: bool = True, +) -> Tensor: + """ + Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + Args: + input (Tensor[N, H, W, C]): The input tensor or 4-dimensions. + qkv_weight (Tensor[in_dim, out_dim]): The weight tensor of query, key, value. + proj_weight (Tensor[out_dim, out_dim]): The weight tensor of projection. + relative_position_bias (Tensor): The learned relative position bias added to attention. + window_size (List[int]): Window size. + num_heads (int): Number of attention heads. + shift_size (List[int]): Shift size for shifted window attention. + attention_dropout (float): Dropout ratio of attention weight. Default: 0.0. + dropout (float): Dropout ratio of output. Default: 0.0. + qkv_bias (Tensor[out_dim], optional): The bias tensor of query, key, value. Default: None. + proj_bias (Tensor[out_dim], optional): The bias tensor of projection. Default: None. + logit_scale (Tensor[out_dim], optional): Logit scale of cosine attention for Swin Transformer V2. Default: None. + training (bool, optional): Training flag used by the dropout parameters. Default: True. + Returns: + Tensor[N, H, W, C]: The output tensor after shifted window attention. + """ + B, H, W, C = input.shape + # pad feature maps to multiples of window size + pad_r = (window_size[1] - W % window_size[1]) % window_size[1] + pad_b = (window_size[0] - H % window_size[0]) % window_size[0] + x = F.pad(input, (0, 0, 0, pad_r, 0, pad_b)) + _, pad_H, pad_W, _ = x.shape + + shift_size = shift_size.copy() + # If window size is larger than feature size, there is no need to shift window + if window_size[0] >= pad_H: + shift_size[0] = 0 + if window_size[1] >= pad_W: + shift_size[1] = 0 + + # cyclic shift + if sum(shift_size) > 0: + x = torch.roll(x, shifts=(-shift_size[0], -shift_size[1]), dims=(1, 2)) + + # partition windows + num_windows = (pad_H // window_size[0]) * (pad_W // window_size[1]) + x = x.view(B, pad_H // window_size[0], window_size[0], pad_W // window_size[1], window_size[1], C) + x = x.permute(0, 1, 3, 2, 4, 5).reshape(B * num_windows, window_size[0] * window_size[1], C) # B*nW, Ws*Ws, C + + # multi-head attention + if logit_scale is not None and qkv_bias is not None: + qkv_bias = qkv_bias.clone() + length = qkv_bias.numel() // 3 + qkv_bias[length : 2 * length].zero_() + qkv = F.linear(x, qkv_weight, qkv_bias) + qkv = qkv.reshape(x.size(0), x.size(1), 3, num_heads, C // num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] + if logit_scale is not None: + # cosine attention + attn = F.normalize(q, dim=-1) @ F.normalize(k, dim=-1).transpose(-2, -1) + logit_scale = torch.clamp(logit_scale, max=math.log(100.0)).exp() + attn = attn * logit_scale + else: + q = q * (C // num_heads) ** -0.5 + attn = q.matmul(k.transpose(-2, -1)) + # add relative position bias + attn = attn + relative_position_bias + + if sum(shift_size) > 0: + # generate attention mask + attn_mask = x.new_zeros((pad_H, pad_W)) + h_slices = ((0, -window_size[0]), (-window_size[0], -shift_size[0]), (-shift_size[0], None)) + w_slices = ((0, -window_size[1]), (-window_size[1], -shift_size[1]), (-shift_size[1], None)) + count = 0 + for h in h_slices: + for w in w_slices: + attn_mask[h[0] : h[1], w[0] : w[1]] = count + count += 1 + attn_mask = attn_mask.view(pad_H // window_size[0], window_size[0], pad_W // window_size[1], window_size[1]) + attn_mask = attn_mask.permute(0, 2, 1, 3).reshape(num_windows, window_size[0] * window_size[1]) + attn_mask = attn_mask.unsqueeze(1) - attn_mask.unsqueeze(2) + attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) + attn = attn.view(x.size(0) // num_windows, num_windows, num_heads, x.size(1), x.size(1)) + attn = attn + attn_mask.unsqueeze(1).unsqueeze(0) + attn = attn.view(-1, num_heads, x.size(1), x.size(1)) + + attn = F.softmax(attn, dim=-1) + attn = F.dropout(attn, p=attention_dropout, training=training) + + x = attn.matmul(v).transpose(1, 2).reshape(x.size(0), x.size(1), C) + x = F.linear(x, proj_weight, proj_bias) + x = F.dropout(x, p=dropout, training=training) + + # reverse windows + x = x.view(B, pad_H // window_size[0], pad_W // window_size[1], window_size[0], window_size[1], C) + x = x.permute(0, 1, 3, 2, 4, 5).reshape(B, pad_H, pad_W, C) + + # reverse cyclic shift + if sum(shift_size) > 0: + x = torch.roll(x, shifts=(shift_size[0], shift_size[1]), dims=(1, 2)) + + # unpad features + x = x[:, :H, :W, :].contiguous() + return x + + +torch.fx.wrap("shifted_window_attention") + + +class ShiftedWindowAttention(nn.Module): + """ + See :func:`shifted_window_attention`. + """ + + def __init__( + self, + dim: int, + window_size: list[int], + shift_size: list[int], + num_heads: int, + qkv_bias: bool = True, + proj_bias: bool = True, + attention_dropout: float = 0.0, + dropout: float = 0.0, + ): + super().__init__() + if len(window_size) != 2 or len(shift_size) != 2: + raise ValueError("window_size and shift_size must be of length 2") + self.window_size = window_size + self.shift_size = shift_size + self.num_heads = num_heads + self.attention_dropout = attention_dropout + self.dropout = dropout + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim, bias=proj_bias) + + self.define_relative_position_bias_table() + self.define_relative_position_index() + + def define_relative_position_bias_table(self): + # define a parameter table of relative position bias + self.relative_position_bias_table = nn.Parameter( + torch.zeros((2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1), self.num_heads) + ) # 2*Wh-1 * 2*Ww-1, nH + nn.init.trunc_normal_(self.relative_position_bias_table, std=0.02) + + def define_relative_position_index(self): + # get pair-wise relative position index for each token inside the window + coords_h = torch.arange(self.window_size[0]) + coords_w = torch.arange(self.window_size[1]) + coords = torch.stack(torch.meshgrid(coords_h, coords_w, indexing="ij")) # 2, Wh, Ww + coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww + relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2 + relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 + relative_coords[:, :, 1] += self.window_size[1] - 1 + relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 + relative_position_index = relative_coords.sum(-1).flatten() # Wh*Ww*Wh*Ww + self.register_buffer("relative_position_index", relative_position_index) + + def get_relative_position_bias(self) -> torch.Tensor: + return _get_relative_position_bias( + self.relative_position_bias_table, self.relative_position_index, self.window_size # type: ignore[arg-type] + ) + + def forward(self, x: Tensor) -> Tensor: + """ + Args: + x (Tensor): Tensor with layout of [B, H, W, C] + Returns: + Tensor with same layout as input, i.e. [B, H, W, C] + """ + relative_position_bias = self.get_relative_position_bias() + return shifted_window_attention( + x, + self.qkv.weight, + self.proj.weight, + relative_position_bias, + self.window_size, + self.num_heads, + shift_size=self.shift_size, + attention_dropout=self.attention_dropout, + dropout=self.dropout, + qkv_bias=self.qkv.bias, + proj_bias=self.proj.bias, + training=self.training, + ) + + +class ShiftedWindowAttentionV2(ShiftedWindowAttention): + """ + See :func:`shifted_window_attention_v2`. + """ + + def __init__( + self, + dim: int, + window_size: list[int], + shift_size: list[int], + num_heads: int, + qkv_bias: bool = True, + proj_bias: bool = True, + attention_dropout: float = 0.0, + dropout: float = 0.0, + ): + super().__init__( + dim, + window_size, + shift_size, + num_heads, + qkv_bias=qkv_bias, + proj_bias=proj_bias, + attention_dropout=attention_dropout, + dropout=dropout, + ) + + self.logit_scale = nn.Parameter(torch.log(10 * torch.ones((num_heads, 1, 1)))) + # mlp to generate continuous relative position bias + self.cpb_mlp = nn.Sequential( + nn.Linear(2, 512, bias=True), nn.ReLU(inplace=True), nn.Linear(512, num_heads, bias=False) + ) + if qkv_bias: + length = self.qkv.bias.numel() // 3 + self.qkv.bias[length : 2 * length].data.zero_() + + def define_relative_position_bias_table(self): + # get relative_coords_table + relative_coords_h = torch.arange(-(self.window_size[0] - 1), self.window_size[0], dtype=torch.float32) + relative_coords_w = torch.arange(-(self.window_size[1] - 1), self.window_size[1], dtype=torch.float32) + relative_coords_table = torch.stack(torch.meshgrid([relative_coords_h, relative_coords_w], indexing="ij")) + relative_coords_table = relative_coords_table.permute(1, 2, 0).contiguous().unsqueeze(0) # 1, 2*Wh-1, 2*Ww-1, 2 + + relative_coords_table[:, :, :, 0] /= self.window_size[0] - 1 + relative_coords_table[:, :, :, 1] /= self.window_size[1] - 1 + + relative_coords_table *= 8 # normalize to -8, 8 + relative_coords_table = ( + torch.sign(relative_coords_table) * torch.log2(torch.abs(relative_coords_table) + 1.0) / 3.0 + ) + self.register_buffer("relative_coords_table", relative_coords_table) + + def get_relative_position_bias(self) -> torch.Tensor: + relative_position_bias = _get_relative_position_bias( + self.cpb_mlp(self.relative_coords_table).view(-1, self.num_heads), + self.relative_position_index, # type: ignore[arg-type] + self.window_size, + ) + relative_position_bias = 16 * torch.sigmoid(relative_position_bias) + return relative_position_bias + + def forward(self, x: Tensor): + """ + Args: + x (Tensor): Tensor with layout of [B, H, W, C] + Returns: + Tensor with same layout as input, i.e. [B, H, W, C] + """ + relative_position_bias = self.get_relative_position_bias() + return shifted_window_attention( + x, + self.qkv.weight, + self.proj.weight, + relative_position_bias, + self.window_size, + self.num_heads, + shift_size=self.shift_size, + attention_dropout=self.attention_dropout, + dropout=self.dropout, + qkv_bias=self.qkv.bias, + proj_bias=self.proj.bias, + logit_scale=self.logit_scale, + training=self.training, + ) + + +class SwinTransformerBlock(nn.Module): + """ + Swin Transformer Block. + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + window_size (List[int]): Window size. + shift_size (List[int]): Shift size for shifted window attention. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.0. + dropout (float): Dropout rate. Default: 0.0. + attention_dropout (float): Attention dropout rate. Default: 0.0. + stochastic_depth_prob: (float): Stochastic depth rate. Default: 0.0. + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + attn_layer (nn.Module): Attention layer. Default: ShiftedWindowAttention + """ + + def __init__( + self, + dim: int, + num_heads: int, + window_size: list[int], + shift_size: list[int], + mlp_ratio: float = 4.0, + dropout: float = 0.0, + attention_dropout: float = 0.0, + stochastic_depth_prob: float = 0.0, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + attn_layer: Callable[..., nn.Module] = ShiftedWindowAttention, + ): + super().__init__() + _log_api_usage_once(self) + + self.norm1 = norm_layer(dim) + self.attn = attn_layer( + dim, + window_size, + shift_size, + num_heads, + attention_dropout=attention_dropout, + dropout=dropout, + ) + self.stochastic_depth = StochasticDepth(stochastic_depth_prob, "row") + self.norm2 = norm_layer(dim) + self.mlp = MLP(dim, [int(dim * mlp_ratio), dim], activation_layer=nn.GELU, inplace=None, dropout=dropout) + + for m in self.mlp.modules(): + if isinstance(m, nn.Linear): + nn.init.xavier_uniform_(m.weight) + if m.bias is not None: + nn.init.normal_(m.bias, std=1e-6) + + def forward(self, x: Tensor): + x = x + self.stochastic_depth(self.attn(self.norm1(x))) + x = x + self.stochastic_depth(self.mlp(self.norm2(x))) + return x + + +class SwinTransformerBlockV2(SwinTransformerBlock): + """ + Swin Transformer V2 Block. + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + window_size (List[int]): Window size. + shift_size (List[int]): Shift size for shifted window attention. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.0. + dropout (float): Dropout rate. Default: 0.0. + attention_dropout (float): Attention dropout rate. Default: 0.0. + stochastic_depth_prob: (float): Stochastic depth rate. Default: 0.0. + norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. + attn_layer (nn.Module): Attention layer. Default: ShiftedWindowAttentionV2. + """ + + def __init__( + self, + dim: int, + num_heads: int, + window_size: list[int], + shift_size: list[int], + mlp_ratio: float = 4.0, + dropout: float = 0.0, + attention_dropout: float = 0.0, + stochastic_depth_prob: float = 0.0, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + attn_layer: Callable[..., nn.Module] = ShiftedWindowAttentionV2, + ): + super().__init__( + dim, + num_heads, + window_size, + shift_size, + mlp_ratio=mlp_ratio, + dropout=dropout, + attention_dropout=attention_dropout, + stochastic_depth_prob=stochastic_depth_prob, + norm_layer=norm_layer, + attn_layer=attn_layer, + ) + + def forward(self, x: Tensor): + # Here is the difference, we apply norm after the attention in V2. + # In V1 we applied norm before the attention. + x = x + self.stochastic_depth(self.norm1(self.attn(x))) + x = x + self.stochastic_depth(self.norm2(self.mlp(x))) + return x + + +class SwinTransformer(nn.Module): + """ + Implements Swin Transformer from the `"Swin Transformer: Hierarchical Vision Transformer using + Shifted Windows" `_ paper. + Args: + patch_size (List[int]): Patch size. + embed_dim (int): Patch embedding dimension. + depths (List(int)): Depth of each Swin Transformer layer. + num_heads (List(int)): Number of attention heads in different layers. + window_size (List[int]): Window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.0. + dropout (float): Dropout rate. Default: 0.0. + attention_dropout (float): Attention dropout rate. Default: 0.0. + stochastic_depth_prob (float): Stochastic depth rate. Default: 0.1. + num_classes (int): Number of classes for classification head. Default: 1000. + block (nn.Module, optional): SwinTransformer Block. Default: None. + norm_layer (nn.Module, optional): Normalization layer. Default: None. + downsample_layer (nn.Module): Downsample layer (patch merging). Default: PatchMerging. + """ + + def __init__( + self, + patch_size: list[int], + embed_dim: int, + depths: list[int], + num_heads: list[int], + window_size: list[int], + mlp_ratio: float = 4.0, + dropout: float = 0.0, + attention_dropout: float = 0.0, + stochastic_depth_prob: float = 0.1, + num_classes: int = 1000, + norm_layer: Optional[Callable[..., nn.Module]] = None, + block: Optional[Callable[..., nn.Module]] = None, + downsample_layer: Callable[..., nn.Module] = PatchMerging, + ): + super().__init__() + _log_api_usage_once(self) + self.num_classes = num_classes + + if block is None: + block = SwinTransformerBlock + if norm_layer is None: + norm_layer = partial(nn.LayerNorm, eps=1e-5) + + layers: list[nn.Module] = [] + # split image into non-overlapping patches + layers.append( + nn.Sequential( + nn.Conv2d( + 3, embed_dim, kernel_size=(patch_size[0], patch_size[1]), stride=(patch_size[0], patch_size[1]) + ), + Permute([0, 2, 3, 1]), + norm_layer(embed_dim), + ) + ) + + total_stage_blocks = sum(depths) + stage_block_id = 0 + # build SwinTransformer blocks + for i_stage in range(len(depths)): + stage: list[nn.Module] = [] + dim = embed_dim * 2**i_stage + for i_layer in range(depths[i_stage]): + # adjust stochastic depth probability based on the depth of the stage block + sd_prob = stochastic_depth_prob * float(stage_block_id) / (total_stage_blocks - 1) + stage.append( + block( + dim, + num_heads[i_stage], + window_size=window_size, + shift_size=[0 if i_layer % 2 == 0 else w // 2 for w in window_size], + mlp_ratio=mlp_ratio, + dropout=dropout, + attention_dropout=attention_dropout, + stochastic_depth_prob=sd_prob, + norm_layer=norm_layer, + ) + ) + stage_block_id += 1 + layers.append(nn.Sequential(*stage)) + # add patch merging layer + if i_stage < (len(depths) - 1): + layers.append(downsample_layer(dim, norm_layer)) + self.features = nn.Sequential(*layers) + + num_features = embed_dim * 2 ** (len(depths) - 1) + self.norm = norm_layer(num_features) + self.permute = Permute([0, 3, 1, 2]) # B H W C -> B C H W + self.avgpool = nn.AdaptiveAvgPool2d(1) + self.flatten = nn.Flatten(1) + self.head = nn.Linear(num_features, num_classes) + + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.zeros_(m.bias) + + def forward(self, x): + x = self.features(x) + x = self.norm(x) + x = self.permute(x) + x = self.avgpool(x) + x = self.flatten(x) + x = self.head(x) + return x + + +def _swin_transformer( + patch_size: list[int], + embed_dim: int, + depths: list[int], + num_heads: list[int], + window_size: list[int], + stochastic_depth_prob: float, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> SwinTransformer: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = SwinTransformer( + patch_size=patch_size, + embed_dim=embed_dim, + depths=depths, + num_heads=num_heads, + window_size=window_size, + stochastic_depth_prob=stochastic_depth_prob, + **kwargs, + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "categories": _IMAGENET_CATEGORIES, +} + + +class Swin_T_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/swin_t-704ceda3.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=232, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META, + "num_params": 28288354, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#swintransformer", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.474, + "acc@5": 95.776, + } + }, + "_ops": 4.491, + "_file_size": 108.19, + "_docs": """These weights reproduce closely the results of the paper using a similar training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class Swin_S_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/swin_s-5e29d889.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=246, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META, + "num_params": 49606258, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#swintransformer", + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.196, + "acc@5": 96.360, + } + }, + "_ops": 8.741, + "_file_size": 189.786, + "_docs": """These weights reproduce closely the results of the paper using a similar training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class Swin_B_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/swin_b-68c6b09e.pth", + transforms=partial( + ImageClassification, crop_size=224, resize_size=238, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META, + "num_params": 87768224, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#swintransformer", + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.582, + "acc@5": 96.640, + } + }, + "_ops": 15.431, + "_file_size": 335.364, + "_docs": """These weights reproduce closely the results of the paper using a similar training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class Swin_V2_T_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/swin_v2_t-b137f0e2.pth", + transforms=partial( + ImageClassification, crop_size=256, resize_size=260, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META, + "num_params": 28351570, + "min_size": (256, 256), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#swintransformer-v2", + "_metrics": { + "ImageNet-1K": { + "acc@1": 82.072, + "acc@5": 96.132, + } + }, + "_ops": 5.94, + "_file_size": 108.626, + "_docs": """These weights reproduce closely the results of the paper using a similar training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class Swin_V2_S_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/swin_v2_s-637d8ceb.pth", + transforms=partial( + ImageClassification, crop_size=256, resize_size=260, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META, + "num_params": 49737442, + "min_size": (256, 256), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#swintransformer-v2", + "_metrics": { + "ImageNet-1K": { + "acc@1": 83.712, + "acc@5": 96.816, + } + }, + "_ops": 11.546, + "_file_size": 190.675, + "_docs": """These weights reproduce closely the results of the paper using a similar training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class Swin_V2_B_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/swin_v2_b-781e5279.pth", + transforms=partial( + ImageClassification, crop_size=256, resize_size=272, interpolation=InterpolationMode.BICUBIC + ), + meta={ + **_COMMON_META, + "num_params": 87930848, + "min_size": (256, 256), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#swintransformer-v2", + "_metrics": { + "ImageNet-1K": { + "acc@1": 84.112, + "acc@5": 96.864, + } + }, + "_ops": 20.325, + "_file_size": 336.372, + "_docs": """These weights reproduce closely the results of the paper using a similar training recipe.""", + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin_T_Weights.IMAGENET1K_V1)) +def swin_t(*, weights: Optional[Swin_T_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer: + """ + Constructs a swin_tiny architecture from + `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows `_. + + Args: + weights (:class:`~torchvision.models.Swin_T_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Swin_T_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.Swin_T_Weights + :members: + """ + weights = Swin_T_Weights.verify(weights) + + return _swin_transformer( + patch_size=[4, 4], + embed_dim=96, + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_size=[7, 7], + stochastic_depth_prob=0.2, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin_S_Weights.IMAGENET1K_V1)) +def swin_s(*, weights: Optional[Swin_S_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer: + """ + Constructs a swin_small architecture from + `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows `_. + + Args: + weights (:class:`~torchvision.models.Swin_S_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Swin_S_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.Swin_S_Weights + :members: + """ + weights = Swin_S_Weights.verify(weights) + + return _swin_transformer( + patch_size=[4, 4], + embed_dim=96, + depths=[2, 2, 18, 2], + num_heads=[3, 6, 12, 24], + window_size=[7, 7], + stochastic_depth_prob=0.3, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin_B_Weights.IMAGENET1K_V1)) +def swin_b(*, weights: Optional[Swin_B_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer: + """ + Constructs a swin_base architecture from + `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows `_. + + Args: + weights (:class:`~torchvision.models.Swin_B_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Swin_B_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.Swin_B_Weights + :members: + """ + weights = Swin_B_Weights.verify(weights) + + return _swin_transformer( + patch_size=[4, 4], + embed_dim=128, + depths=[2, 2, 18, 2], + num_heads=[4, 8, 16, 32], + window_size=[7, 7], + stochastic_depth_prob=0.5, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin_V2_T_Weights.IMAGENET1K_V1)) +def swin_v2_t(*, weights: Optional[Swin_V2_T_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer: + """ + Constructs a swin_v2_tiny architecture from + `Swin Transformer V2: Scaling Up Capacity and Resolution `_. + + Args: + weights (:class:`~torchvision.models.Swin_V2_T_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Swin_V2_T_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.Swin_V2_T_Weights + :members: + """ + weights = Swin_V2_T_Weights.verify(weights) + + return _swin_transformer( + patch_size=[4, 4], + embed_dim=96, + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_size=[8, 8], + stochastic_depth_prob=0.2, + weights=weights, + progress=progress, + block=SwinTransformerBlockV2, + downsample_layer=PatchMergingV2, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin_V2_S_Weights.IMAGENET1K_V1)) +def swin_v2_s(*, weights: Optional[Swin_V2_S_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer: + """ + Constructs a swin_v2_small architecture from + `Swin Transformer V2: Scaling Up Capacity and Resolution `_. + + Args: + weights (:class:`~torchvision.models.Swin_V2_S_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Swin_V2_S_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.Swin_V2_S_Weights + :members: + """ + weights = Swin_V2_S_Weights.verify(weights) + + return _swin_transformer( + patch_size=[4, 4], + embed_dim=96, + depths=[2, 2, 18, 2], + num_heads=[3, 6, 12, 24], + window_size=[8, 8], + stochastic_depth_prob=0.3, + weights=weights, + progress=progress, + block=SwinTransformerBlockV2, + downsample_layer=PatchMergingV2, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin_V2_B_Weights.IMAGENET1K_V1)) +def swin_v2_b(*, weights: Optional[Swin_V2_B_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer: + """ + Constructs a swin_v2_base architecture from + `Swin Transformer V2: Scaling Up Capacity and Resolution `_. + + Args: + weights (:class:`~torchvision.models.Swin_V2_B_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.Swin_V2_B_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.Swin_V2_B_Weights + :members: + """ + weights = Swin_V2_B_Weights.verify(weights) + + return _swin_transformer( + patch_size=[4, 4], + embed_dim=128, + depths=[2, 2, 18, 2], + num_heads=[4, 8, 16, 32], + window_size=[8, 8], + stochastic_depth_prob=0.5, + weights=weights, + progress=progress, + block=SwinTransformerBlockV2, + downsample_layer=PatchMergingV2, + **kwargs, + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/vgg.py b/.venv/lib/python3.12/site-packages/torchvision/models/vgg.py new file mode 100644 index 0000000000000000000000000000000000000000..feed0ce8d77ed53cfdca222b11d5c694dae4b104 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/vgg.py @@ -0,0 +1,511 @@ +from functools import partial +from typing import Any, cast, Optional, Union + +import torch +import torch.nn as nn + +from ..transforms._presets import ImageClassification +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "VGG", + "VGG11_Weights", + "VGG11_BN_Weights", + "VGG13_Weights", + "VGG13_BN_Weights", + "VGG16_Weights", + "VGG16_BN_Weights", + "VGG19_Weights", + "VGG19_BN_Weights", + "vgg11", + "vgg11_bn", + "vgg13", + "vgg13_bn", + "vgg16", + "vgg16_bn", + "vgg19", + "vgg19_bn", +] + + +class VGG(nn.Module): + def __init__( + self, features: nn.Module, num_classes: int = 1000, init_weights: bool = True, dropout: float = 0.5 + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.features = features + self.avgpool = nn.AdaptiveAvgPool2d((7, 7)) + self.classifier = nn.Sequential( + nn.Linear(512 * 7 * 7, 4096), + nn.ReLU(True), + nn.Dropout(p=dropout), + nn.Linear(4096, 4096), + nn.ReLU(True), + nn.Dropout(p=dropout), + nn.Linear(4096, num_classes), + ) + if init_weights: + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + nn.init.constant_(m.bias, 0) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.features(x) + x = self.avgpool(x) + x = torch.flatten(x, 1) + x = self.classifier(x) + return x + + +def make_layers(cfg: list[Union[str, int]], batch_norm: bool = False) -> nn.Sequential: + layers: list[nn.Module] = [] + in_channels = 3 + for v in cfg: + if v == "M": + layers += [nn.MaxPool2d(kernel_size=2, stride=2)] + else: + v = cast(int, v) + conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1) + if batch_norm: + layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)] + else: + layers += [conv2d, nn.ReLU(inplace=True)] + in_channels = v + return nn.Sequential(*layers) + + +cfgs: dict[str, list[Union[str, int]]] = { + "A": [64, "M", 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"], + "B": [64, 64, "M", 128, 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"], + "D": [64, 64, "M", 128, 128, "M", 256, 256, 256, "M", 512, 512, 512, "M", 512, 512, 512, "M"], + "E": [64, 64, "M", 128, 128, "M", 256, 256, 256, 256, "M", 512, 512, 512, 512, "M", 512, 512, 512, 512, "M"], +} + + +def _vgg(cfg: str, batch_norm: bool, weights: Optional[WeightsEnum], progress: bool, **kwargs: Any) -> VGG: + if weights is not None: + kwargs["init_weights"] = False + if weights.meta["categories"] is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs) + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + return model + + +_COMMON_META = { + "min_size": (32, 32), + "categories": _IMAGENET_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#alexnet-and-vgg", + "_docs": """These weights were trained from scratch by using a simplified training recipe.""", +} + + +class VGG11_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg11-8a719046.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 132863336, + "_metrics": { + "ImageNet-1K": { + "acc@1": 69.020, + "acc@5": 88.628, + } + }, + "_ops": 7.609, + "_file_size": 506.84, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class VGG11_BN_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg11_bn-6002323d.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 132868840, + "_metrics": { + "ImageNet-1K": { + "acc@1": 70.370, + "acc@5": 89.810, + } + }, + "_ops": 7.609, + "_file_size": 506.881, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class VGG13_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg13-19584684.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 133047848, + "_metrics": { + "ImageNet-1K": { + "acc@1": 69.928, + "acc@5": 89.246, + } + }, + "_ops": 11.308, + "_file_size": 507.545, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class VGG13_BN_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg13_bn-abd245e5.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 133053736, + "_metrics": { + "ImageNet-1K": { + "acc@1": 71.586, + "acc@5": 90.374, + } + }, + "_ops": 11.308, + "_file_size": 507.59, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class VGG16_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg16-397923af.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 138357544, + "_metrics": { + "ImageNet-1K": { + "acc@1": 71.592, + "acc@5": 90.382, + } + }, + "_ops": 15.47, + "_file_size": 527.796, + }, + ) + IMAGENET1K_FEATURES = Weights( + # Weights ported from https://github.com/amdegroot/ssd.pytorch/ + url="https://download.pytorch.org/models/vgg16_features-amdegroot-88682ab5.pth", + transforms=partial( + ImageClassification, + crop_size=224, + mean=(0.48235, 0.45882, 0.40784), + std=(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0), + ), + meta={ + **_COMMON_META, + "num_params": 138357544, + "categories": None, + "recipe": "https://github.com/amdegroot/ssd.pytorch#training-ssd", + "_metrics": { + "ImageNet-1K": { + "acc@1": float("nan"), + "acc@5": float("nan"), + } + }, + "_ops": 15.47, + "_file_size": 527.802, + "_docs": """ + These weights can't be used for classification because they are missing values in the `classifier` + module. Only the `features` module has valid values and can be used for feature extraction. The weights + were trained using the original input standardization method as described in the paper. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class VGG16_BN_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg16_bn-6c64b313.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 138365992, + "_metrics": { + "ImageNet-1K": { + "acc@1": 73.360, + "acc@5": 91.516, + } + }, + "_ops": 15.47, + "_file_size": 527.866, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class VGG19_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg19-dcbb9e9d.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 143667240, + "_metrics": { + "ImageNet-1K": { + "acc@1": 72.376, + "acc@5": 90.876, + } + }, + "_ops": 19.632, + "_file_size": 548.051, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class VGG19_BN_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vgg19_bn-c79401a0.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 143678248, + "_metrics": { + "ImageNet-1K": { + "acc@1": 74.218, + "acc@5": 91.842, + } + }, + "_ops": 19.632, + "_file_size": 548.143, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG11_Weights.IMAGENET1K_V1)) +def vgg11(*, weights: Optional[VGG11_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-11 from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG11_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG11_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG11_Weights + :members: + """ + weights = VGG11_Weights.verify(weights) + + return _vgg("A", False, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG11_BN_Weights.IMAGENET1K_V1)) +def vgg11_bn(*, weights: Optional[VGG11_BN_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-11-BN from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG11_BN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG11_BN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG11_BN_Weights + :members: + """ + weights = VGG11_BN_Weights.verify(weights) + + return _vgg("A", True, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG13_Weights.IMAGENET1K_V1)) +def vgg13(*, weights: Optional[VGG13_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-13 from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG13_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG13_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG13_Weights + :members: + """ + weights = VGG13_Weights.verify(weights) + + return _vgg("B", False, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG13_BN_Weights.IMAGENET1K_V1)) +def vgg13_bn(*, weights: Optional[VGG13_BN_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-13-BN from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG13_BN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG13_BN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG13_BN_Weights + :members: + """ + weights = VGG13_BN_Weights.verify(weights) + + return _vgg("B", True, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG16_Weights.IMAGENET1K_V1)) +def vgg16(*, weights: Optional[VGG16_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-16 from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG16_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG16_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG16_Weights + :members: + """ + weights = VGG16_Weights.verify(weights) + + return _vgg("D", False, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG16_BN_Weights.IMAGENET1K_V1)) +def vgg16_bn(*, weights: Optional[VGG16_BN_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-16-BN from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG16_BN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG16_BN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG16_BN_Weights + :members: + """ + weights = VGG16_BN_Weights.verify(weights) + + return _vgg("D", True, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG19_Weights.IMAGENET1K_V1)) +def vgg19(*, weights: Optional[VGG19_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-19 from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG19_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG19_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG19_Weights + :members: + """ + weights = VGG19_Weights.verify(weights) + + return _vgg("E", False, weights, progress, **kwargs) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", VGG19_BN_Weights.IMAGENET1K_V1)) +def vgg19_bn(*, weights: Optional[VGG19_BN_Weights] = None, progress: bool = True, **kwargs: Any) -> VGG: + """VGG-19_BN from `Very Deep Convolutional Networks for Large-Scale Image Recognition `__. + + Args: + weights (:class:`~torchvision.models.VGG19_BN_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.VGG19_BN_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vgg.VGG`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.VGG19_BN_Weights + :members: + """ + weights = VGG19_BN_Weights.verify(weights) + + return _vgg("E", True, weights, progress, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/video/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/models/video/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f1eedd3116001af22ec202d2ccec6eefad8090ae --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/video/__init__.py @@ -0,0 +1,4 @@ +from .mvit import * +from .resnet import * +from .s3d import * +from .swin_transformer import * diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d80cd815a9378b517e91ae78b6756f42b358b2c9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/mvit.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/mvit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6178cece136bfc14702465c1bfcae95b26c095ed Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/mvit.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/resnet.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/resnet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..725a985fa2273b63701c5bd16d194d2902ab1f51 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/resnet.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/s3d.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/s3d.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c8fa6cb41fb716b7dc527a9f26060e472c2aa53 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/s3d.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/swin_transformer.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/swin_transformer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..390c7ab8407ec8094b1da05749c4b673c0e80b9c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/models/video/__pycache__/swin_transformer.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/video/mvit.py b/.venv/lib/python3.12/site-packages/torchvision/models/video/mvit.py new file mode 100644 index 0000000000000000000000000000000000000000..64d6d171b75d4f6a316e0ff4b80aa94efeb49294 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/video/mvit.py @@ -0,0 +1,898 @@ +import math +from collections.abc import Sequence +from dataclasses import dataclass +from functools import partial +from typing import Any, Callable, Optional + +import torch +import torch.fx +import torch.nn as nn + +from ...ops import MLP, StochasticDepth +from ...transforms._presets import VideoClassification +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _KINETICS400_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "MViT", + "MViT_V1_B_Weights", + "mvit_v1_b", + "MViT_V2_S_Weights", + "mvit_v2_s", +] + + +@dataclass +class MSBlockConfig: + num_heads: int + input_channels: int + output_channels: int + kernel_q: list[int] + kernel_kv: list[int] + stride_q: list[int] + stride_kv: list[int] + + +def _prod(s: Sequence[int]) -> int: + product = 1 + for v in s: + product *= v + return product + + +def _unsqueeze(x: torch.Tensor, target_dim: int, expand_dim: int) -> tuple[torch.Tensor, int]: + tensor_dim = x.dim() + if tensor_dim == target_dim - 1: + x = x.unsqueeze(expand_dim) + elif tensor_dim != target_dim: + raise ValueError(f"Unsupported input dimension {x.shape}") + return x, tensor_dim + + +def _squeeze(x: torch.Tensor, target_dim: int, expand_dim: int, tensor_dim: int) -> torch.Tensor: + if tensor_dim == target_dim - 1: + x = x.squeeze(expand_dim) + return x + + +torch.fx.wrap("_unsqueeze") +torch.fx.wrap("_squeeze") + + +class Pool(nn.Module): + def __init__( + self, + pool: nn.Module, + norm: Optional[nn.Module], + activation: Optional[nn.Module] = None, + norm_before_pool: bool = False, + ) -> None: + super().__init__() + self.pool = pool + layers = [] + if norm is not None: + layers.append(norm) + if activation is not None: + layers.append(activation) + self.norm_act = nn.Sequential(*layers) if layers else None + self.norm_before_pool = norm_before_pool + + def forward(self, x: torch.Tensor, thw: tuple[int, int, int]) -> tuple[torch.Tensor, tuple[int, int, int]]: + x, tensor_dim = _unsqueeze(x, 4, 1) + + # Separate the class token and reshape the input + class_token, x = torch.tensor_split(x, indices=(1,), dim=2) + x = x.transpose(2, 3) + B, N, C = x.shape[:3] + x = x.reshape((B * N, C) + thw).contiguous() + + # normalizing prior pooling is useful when we use BN which can be absorbed to speed up inference + if self.norm_before_pool and self.norm_act is not None: + x = self.norm_act(x) + + # apply the pool on the input and add back the token + x = self.pool(x) + T, H, W = x.shape[2:] + x = x.reshape(B, N, C, -1).transpose(2, 3) + x = torch.cat((class_token, x), dim=2) + + if not self.norm_before_pool and self.norm_act is not None: + x = self.norm_act(x) + + x = _squeeze(x, 4, 1, tensor_dim) + return x, (T, H, W) + + +def _interpolate(embedding: torch.Tensor, d: int) -> torch.Tensor: + if embedding.shape[0] == d: + return embedding + + return ( + nn.functional.interpolate( + embedding.permute(1, 0).unsqueeze(0), + size=d, + mode="linear", + ) + .squeeze(0) + .permute(1, 0) + ) + + +def _add_rel_pos( + attn: torch.Tensor, + q: torch.Tensor, + q_thw: tuple[int, int, int], + k_thw: tuple[int, int, int], + rel_pos_h: torch.Tensor, + rel_pos_w: torch.Tensor, + rel_pos_t: torch.Tensor, +) -> torch.Tensor: + # Modified code from: https://github.com/facebookresearch/SlowFast/commit/1aebd71a2efad823d52b827a3deaf15a56cf4932 + q_t, q_h, q_w = q_thw + k_t, k_h, k_w = k_thw + dh = int(2 * max(q_h, k_h) - 1) + dw = int(2 * max(q_w, k_w) - 1) + dt = int(2 * max(q_t, k_t) - 1) + + # Scale up rel pos if shapes for q and k are different. + q_h_ratio = max(k_h / q_h, 1.0) + k_h_ratio = max(q_h / k_h, 1.0) + dist_h = torch.arange(q_h)[:, None] * q_h_ratio - (torch.arange(k_h)[None, :] + (1.0 - k_h)) * k_h_ratio + q_w_ratio = max(k_w / q_w, 1.0) + k_w_ratio = max(q_w / k_w, 1.0) + dist_w = torch.arange(q_w)[:, None] * q_w_ratio - (torch.arange(k_w)[None, :] + (1.0 - k_w)) * k_w_ratio + q_t_ratio = max(k_t / q_t, 1.0) + k_t_ratio = max(q_t / k_t, 1.0) + dist_t = torch.arange(q_t)[:, None] * q_t_ratio - (torch.arange(k_t)[None, :] + (1.0 - k_t)) * k_t_ratio + + # Interpolate rel pos if needed. + rel_pos_h = _interpolate(rel_pos_h, dh) + rel_pos_w = _interpolate(rel_pos_w, dw) + rel_pos_t = _interpolate(rel_pos_t, dt) + Rh = rel_pos_h[dist_h.long()] + Rw = rel_pos_w[dist_w.long()] + Rt = rel_pos_t[dist_t.long()] + + B, n_head, _, dim = q.shape + + r_q = q[:, :, 1:].reshape(B, n_head, q_t, q_h, q_w, dim) + rel_h_q = torch.einsum("bythwc,hkc->bythwk", r_q, Rh) # [B, H, q_t, qh, qw, k_h] + rel_w_q = torch.einsum("bythwc,wkc->bythwk", r_q, Rw) # [B, H, q_t, qh, qw, k_w] + # [B, H, q_t, q_h, q_w, dim] -> [q_t, B, H, q_h, q_w, dim] -> [q_t, B*H*q_h*q_w, dim] + r_q = r_q.permute(2, 0, 1, 3, 4, 5).reshape(q_t, B * n_head * q_h * q_w, dim) + # [q_t, B*H*q_h*q_w, dim] * [q_t, dim, k_t] = [q_t, B*H*q_h*q_w, k_t] -> [B*H*q_h*q_w, q_t, k_t] + rel_q_t = torch.matmul(r_q, Rt.transpose(1, 2)).transpose(0, 1) + # [B*H*q_h*q_w, q_t, k_t] -> [B, H, q_t, q_h, q_w, k_t] + rel_q_t = rel_q_t.view(B, n_head, q_h, q_w, q_t, k_t).permute(0, 1, 4, 2, 3, 5) + + # Combine rel pos. + rel_pos = ( + rel_h_q[:, :, :, :, :, None, :, None] + + rel_w_q[:, :, :, :, :, None, None, :] + + rel_q_t[:, :, :, :, :, :, None, None] + ).reshape(B, n_head, q_t * q_h * q_w, k_t * k_h * k_w) + + # Add it to attention + attn[:, :, 1:, 1:] += rel_pos + + return attn + + +def _add_shortcut(x: torch.Tensor, shortcut: torch.Tensor, residual_with_cls_embed: bool): + if residual_with_cls_embed: + x.add_(shortcut) + else: + x[:, :, 1:, :] += shortcut[:, :, 1:, :] + return x + + +torch.fx.wrap("_add_rel_pos") +torch.fx.wrap("_add_shortcut") + + +class MultiscaleAttention(nn.Module): + def __init__( + self, + input_size: list[int], + embed_dim: int, + output_dim: int, + num_heads: int, + kernel_q: list[int], + kernel_kv: list[int], + stride_q: list[int], + stride_kv: list[int], + residual_pool: bool, + residual_with_cls_embed: bool, + rel_pos_embed: bool, + dropout: float = 0.0, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + ) -> None: + super().__init__() + self.embed_dim = embed_dim + self.output_dim = output_dim + self.num_heads = num_heads + self.head_dim = output_dim // num_heads + self.scaler = 1.0 / math.sqrt(self.head_dim) + self.residual_pool = residual_pool + self.residual_with_cls_embed = residual_with_cls_embed + + self.qkv = nn.Linear(embed_dim, 3 * output_dim) + layers: list[nn.Module] = [nn.Linear(output_dim, output_dim)] + if dropout > 0.0: + layers.append(nn.Dropout(dropout, inplace=True)) + self.project = nn.Sequential(*layers) + + self.pool_q: Optional[nn.Module] = None + if _prod(kernel_q) > 1 or _prod(stride_q) > 1: + padding_q = [int(q // 2) for q in kernel_q] + self.pool_q = Pool( + nn.Conv3d( + self.head_dim, + self.head_dim, + kernel_q, # type: ignore[arg-type] + stride=stride_q, # type: ignore[arg-type] + padding=padding_q, # type: ignore[arg-type] + groups=self.head_dim, + bias=False, + ), + norm_layer(self.head_dim), + ) + + self.pool_k: Optional[nn.Module] = None + self.pool_v: Optional[nn.Module] = None + if _prod(kernel_kv) > 1 or _prod(stride_kv) > 1: + padding_kv = [int(kv // 2) for kv in kernel_kv] + self.pool_k = Pool( + nn.Conv3d( + self.head_dim, + self.head_dim, + kernel_kv, # type: ignore[arg-type] + stride=stride_kv, # type: ignore[arg-type] + padding=padding_kv, # type: ignore[arg-type] + groups=self.head_dim, + bias=False, + ), + norm_layer(self.head_dim), + ) + self.pool_v = Pool( + nn.Conv3d( + self.head_dim, + self.head_dim, + kernel_kv, # type: ignore[arg-type] + stride=stride_kv, # type: ignore[arg-type] + padding=padding_kv, # type: ignore[arg-type] + groups=self.head_dim, + bias=False, + ), + norm_layer(self.head_dim), + ) + + self.rel_pos_h: Optional[nn.Parameter] = None + self.rel_pos_w: Optional[nn.Parameter] = None + self.rel_pos_t: Optional[nn.Parameter] = None + if rel_pos_embed: + size = max(input_size[1:]) + q_size = size // stride_q[1] if len(stride_q) > 0 else size + kv_size = size // stride_kv[1] if len(stride_kv) > 0 else size + spatial_dim = 2 * max(q_size, kv_size) - 1 + temporal_dim = 2 * input_size[0] - 1 + self.rel_pos_h = nn.Parameter(torch.zeros(spatial_dim, self.head_dim)) + self.rel_pos_w = nn.Parameter(torch.zeros(spatial_dim, self.head_dim)) + self.rel_pos_t = nn.Parameter(torch.zeros(temporal_dim, self.head_dim)) + nn.init.trunc_normal_(self.rel_pos_h, std=0.02) + nn.init.trunc_normal_(self.rel_pos_w, std=0.02) + nn.init.trunc_normal_(self.rel_pos_t, std=0.02) + + def forward(self, x: torch.Tensor, thw: tuple[int, int, int]) -> tuple[torch.Tensor, tuple[int, int, int]]: + B, N, C = x.shape + q, k, v = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).transpose(1, 3).unbind(dim=2) + + if self.pool_k is not None: + k, k_thw = self.pool_k(k, thw) + else: + k_thw = thw + if self.pool_v is not None: + v = self.pool_v(v, thw)[0] + if self.pool_q is not None: + q, thw = self.pool_q(q, thw) + + attn = torch.matmul(self.scaler * q, k.transpose(2, 3)) + if self.rel_pos_h is not None and self.rel_pos_w is not None and self.rel_pos_t is not None: + attn = _add_rel_pos( + attn, + q, + thw, + k_thw, + self.rel_pos_h, + self.rel_pos_w, + self.rel_pos_t, + ) + attn = attn.softmax(dim=-1) + + x = torch.matmul(attn, v) + if self.residual_pool: + _add_shortcut(x, q, self.residual_with_cls_embed) + x = x.transpose(1, 2).reshape(B, -1, self.output_dim) + x = self.project(x) + + return x, thw + + +class MultiscaleBlock(nn.Module): + def __init__( + self, + input_size: list[int], + cnf: MSBlockConfig, + residual_pool: bool, + residual_with_cls_embed: bool, + rel_pos_embed: bool, + proj_after_attn: bool, + dropout: float = 0.0, + stochastic_depth_prob: float = 0.0, + norm_layer: Callable[..., nn.Module] = nn.LayerNorm, + ) -> None: + super().__init__() + self.proj_after_attn = proj_after_attn + + self.pool_skip: Optional[nn.Module] = None + if _prod(cnf.stride_q) > 1: + kernel_skip = [s + 1 if s > 1 else s for s in cnf.stride_q] + padding_skip = [int(k // 2) for k in kernel_skip] + self.pool_skip = Pool( + nn.MaxPool3d(kernel_skip, stride=cnf.stride_q, padding=padding_skip), None # type: ignore[arg-type] + ) + + attn_dim = cnf.output_channels if proj_after_attn else cnf.input_channels + + self.norm1 = norm_layer(cnf.input_channels) + self.norm2 = norm_layer(attn_dim) + self.needs_transposal = isinstance(self.norm1, nn.BatchNorm1d) + + self.attn = MultiscaleAttention( + input_size, + cnf.input_channels, + attn_dim, + cnf.num_heads, + kernel_q=cnf.kernel_q, + kernel_kv=cnf.kernel_kv, + stride_q=cnf.stride_q, + stride_kv=cnf.stride_kv, + rel_pos_embed=rel_pos_embed, + residual_pool=residual_pool, + residual_with_cls_embed=residual_with_cls_embed, + dropout=dropout, + norm_layer=norm_layer, + ) + self.mlp = MLP( + attn_dim, + [4 * attn_dim, cnf.output_channels], + activation_layer=nn.GELU, + dropout=dropout, + inplace=None, + ) + + self.stochastic_depth = StochasticDepth(stochastic_depth_prob, "row") + + self.project: Optional[nn.Module] = None + if cnf.input_channels != cnf.output_channels: + self.project = nn.Linear(cnf.input_channels, cnf.output_channels) + + def forward(self, x: torch.Tensor, thw: tuple[int, int, int]) -> tuple[torch.Tensor, tuple[int, int, int]]: + x_norm1 = self.norm1(x.transpose(1, 2)).transpose(1, 2) if self.needs_transposal else self.norm1(x) + x_attn, thw_new = self.attn(x_norm1, thw) + x = x if self.project is None or not self.proj_after_attn else self.project(x_norm1) + x_skip = x if self.pool_skip is None else self.pool_skip(x, thw)[0] + x = x_skip + self.stochastic_depth(x_attn) + + x_norm2 = self.norm2(x.transpose(1, 2)).transpose(1, 2) if self.needs_transposal else self.norm2(x) + x_proj = x if self.project is None or self.proj_after_attn else self.project(x_norm2) + + return x_proj + self.stochastic_depth(self.mlp(x_norm2)), thw_new + + +class PositionalEncoding(nn.Module): + def __init__(self, embed_size: int, spatial_size: tuple[int, int], temporal_size: int, rel_pos_embed: bool) -> None: + super().__init__() + self.spatial_size = spatial_size + self.temporal_size = temporal_size + + self.class_token = nn.Parameter(torch.zeros(embed_size)) + self.spatial_pos: Optional[nn.Parameter] = None + self.temporal_pos: Optional[nn.Parameter] = None + self.class_pos: Optional[nn.Parameter] = None + if not rel_pos_embed: + self.spatial_pos = nn.Parameter(torch.zeros(self.spatial_size[0] * self.spatial_size[1], embed_size)) + self.temporal_pos = nn.Parameter(torch.zeros(self.temporal_size, embed_size)) + self.class_pos = nn.Parameter(torch.zeros(embed_size)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + class_token = self.class_token.expand(x.size(0), -1).unsqueeze(1) + x = torch.cat((class_token, x), dim=1) + + if self.spatial_pos is not None and self.temporal_pos is not None and self.class_pos is not None: + hw_size, embed_size = self.spatial_pos.shape + pos_embedding = torch.repeat_interleave(self.temporal_pos, hw_size, dim=0) + pos_embedding.add_(self.spatial_pos.unsqueeze(0).expand(self.temporal_size, -1, -1).reshape(-1, embed_size)) + pos_embedding = torch.cat((self.class_pos.unsqueeze(0), pos_embedding), dim=0).unsqueeze(0) + x.add_(pos_embedding) + + return x + + +class MViT(nn.Module): + def __init__( + self, + spatial_size: tuple[int, int], + temporal_size: int, + block_setting: Sequence[MSBlockConfig], + residual_pool: bool, + residual_with_cls_embed: bool, + rel_pos_embed: bool, + proj_after_attn: bool, + dropout: float = 0.5, + attention_dropout: float = 0.0, + stochastic_depth_prob: float = 0.0, + num_classes: int = 400, + block: Optional[Callable[..., nn.Module]] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + patch_embed_kernel: tuple[int, int, int] = (3, 7, 7), + patch_embed_stride: tuple[int, int, int] = (2, 4, 4), + patch_embed_padding: tuple[int, int, int] = (1, 3, 3), + ) -> None: + """ + MViT main class. + + Args: + spatial_size (tuple of ints): The spacial size of the input as ``(H, W)``. + temporal_size (int): The temporal size ``T`` of the input. + block_setting (sequence of MSBlockConfig): The Network structure. + residual_pool (bool): If True, use MViTv2 pooling residual connection. + residual_with_cls_embed (bool): If True, the addition on the residual connection will include + the class embedding. + rel_pos_embed (bool): If True, use MViTv2's relative positional embeddings. + proj_after_attn (bool): If True, apply the projection after the attention. + dropout (float): Dropout rate. Default: 0.0. + attention_dropout (float): Attention dropout rate. Default: 0.0. + stochastic_depth_prob: (float): Stochastic depth rate. Default: 0.0. + num_classes (int): The number of classes. + block (callable, optional): Module specifying the layer which consists of the attention and mlp. + norm_layer (callable, optional): Module specifying the normalization layer to use. + patch_embed_kernel (tuple of ints): The kernel of the convolution that patchifies the input. + patch_embed_stride (tuple of ints): The stride of the convolution that patchifies the input. + patch_embed_padding (tuple of ints): The padding of the convolution that patchifies the input. + """ + super().__init__() + # This implementation employs a different parameterization scheme than the one used at PyTorch Video: + # https://github.com/facebookresearch/pytorchvideo/blob/718d0a4/pytorchvideo/models/vision_transformers.py + # We remove any experimental configuration that didn't make it to the final variants of the models. To represent + # the configuration of the architecture we use the simplified form suggested at Table 1 of the paper. + _log_api_usage_once(self) + total_stage_blocks = len(block_setting) + if total_stage_blocks == 0: + raise ValueError("The configuration parameter can't be empty.") + + if block is None: + block = MultiscaleBlock + + if norm_layer is None: + norm_layer = partial(nn.LayerNorm, eps=1e-6) + + # Patch Embedding module + self.conv_proj = nn.Conv3d( + in_channels=3, + out_channels=block_setting[0].input_channels, + kernel_size=patch_embed_kernel, + stride=patch_embed_stride, + padding=patch_embed_padding, + ) + + input_size = [size // stride for size, stride in zip((temporal_size,) + spatial_size, self.conv_proj.stride)] + + # Spatio-Temporal Class Positional Encoding + self.pos_encoding = PositionalEncoding( + embed_size=block_setting[0].input_channels, + spatial_size=(input_size[1], input_size[2]), + temporal_size=input_size[0], + rel_pos_embed=rel_pos_embed, + ) + + # Encoder module + self.blocks = nn.ModuleList() + for stage_block_id, cnf in enumerate(block_setting): + # adjust stochastic depth probability based on the depth of the stage block + sd_prob = stochastic_depth_prob * stage_block_id / (total_stage_blocks - 1.0) + + self.blocks.append( + block( + input_size=input_size, + cnf=cnf, + residual_pool=residual_pool, + residual_with_cls_embed=residual_with_cls_embed, + rel_pos_embed=rel_pos_embed, + proj_after_attn=proj_after_attn, + dropout=attention_dropout, + stochastic_depth_prob=sd_prob, + norm_layer=norm_layer, + ) + ) + + if len(cnf.stride_q) > 0: + input_size = [size // stride for size, stride in zip(input_size, cnf.stride_q)] + self.norm = norm_layer(block_setting[-1].output_channels) + + # Classifier module + self.head = nn.Sequential( + nn.Dropout(dropout, inplace=True), + nn.Linear(block_setting[-1].output_channels, num_classes), + ) + + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.trunc_normal_(m.weight, std=0.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0.0) + elif isinstance(m, nn.LayerNorm): + if m.weight is not None: + nn.init.constant_(m.weight, 1.0) + if m.bias is not None: + nn.init.constant_(m.bias, 0.0) + elif isinstance(m, PositionalEncoding): + for weights in m.parameters(): + nn.init.trunc_normal_(weights, std=0.02) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + # Convert if necessary (B, C, H, W) -> (B, C, 1, H, W) + x = _unsqueeze(x, 5, 2)[0] + # patchify and reshape: (B, C, T, H, W) -> (B, embed_channels[0], T', H', W') -> (B, THW', embed_channels[0]) + x = self.conv_proj(x) + x = x.flatten(2).transpose(1, 2) + + # add positional encoding + x = self.pos_encoding(x) + + # pass patches through the encoder + thw = (self.pos_encoding.temporal_size,) + self.pos_encoding.spatial_size + for block in self.blocks: + x, thw = block(x, thw) + x = self.norm(x) + + # classifier "token" as used by standard language architectures + x = x[:, 0] + x = self.head(x) + + return x + + +def _mvit( + block_setting: list[MSBlockConfig], + stochastic_depth_prob: float, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> MViT: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + assert weights.meta["min_size"][0] == weights.meta["min_size"][1] + _ovewrite_named_param(kwargs, "spatial_size", weights.meta["min_size"]) + _ovewrite_named_param(kwargs, "temporal_size", weights.meta["min_temporal_size"]) + spatial_size = kwargs.pop("spatial_size", (224, 224)) + temporal_size = kwargs.pop("temporal_size", 16) + + model = MViT( + spatial_size=spatial_size, + temporal_size=temporal_size, + block_setting=block_setting, + residual_pool=kwargs.pop("residual_pool", False), + residual_with_cls_embed=kwargs.pop("residual_with_cls_embed", True), + rel_pos_embed=kwargs.pop("rel_pos_embed", False), + proj_after_attn=kwargs.pop("proj_after_attn", False), + stochastic_depth_prob=stochastic_depth_prob, + **kwargs, + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +class MViT_V1_B_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/mvit_v1_b-dbeb1030.pth", + transforms=partial( + VideoClassification, + crop_size=(224, 224), + resize_size=(256,), + mean=(0.45, 0.45, 0.45), + std=(0.225, 0.225, 0.225), + ), + meta={ + "min_size": (224, 224), + "min_temporal_size": 16, + "categories": _KINETICS400_CATEGORIES, + "recipe": "https://github.com/facebookresearch/pytorchvideo/blob/main/docs/source/model_zoo.md", + "_docs": ( + "The weights were ported from the paper. The accuracies are estimated on video-level " + "with parameters `frame_rate=7.5`, `clips_per_video=5`, and `clip_len=16`" + ), + "num_params": 36610672, + "_metrics": { + "Kinetics-400": { + "acc@1": 78.477, + "acc@5": 93.582, + } + }, + "_ops": 70.599, + "_file_size": 139.764, + }, + ) + DEFAULT = KINETICS400_V1 + + +class MViT_V2_S_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/mvit_v2_s-ae3be167.pth", + transforms=partial( + VideoClassification, + crop_size=(224, 224), + resize_size=(256,), + mean=(0.45, 0.45, 0.45), + std=(0.225, 0.225, 0.225), + ), + meta={ + "min_size": (224, 224), + "min_temporal_size": 16, + "categories": _KINETICS400_CATEGORIES, + "recipe": "https://github.com/facebookresearch/SlowFast/blob/main/MODEL_ZOO.md", + "_docs": ( + "The weights were ported from the paper. The accuracies are estimated on video-level " + "with parameters `frame_rate=7.5`, `clips_per_video=5`, and `clip_len=16`" + ), + "num_params": 34537744, + "_metrics": { + "Kinetics-400": { + "acc@1": 80.757, + "acc@5": 94.665, + } + }, + "_ops": 64.224, + "_file_size": 131.884, + }, + ) + DEFAULT = KINETICS400_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MViT_V1_B_Weights.KINETICS400_V1)) +def mvit_v1_b(*, weights: Optional[MViT_V1_B_Weights] = None, progress: bool = True, **kwargs: Any) -> MViT: + """ + Constructs a base MViTV1 architecture from + `Multiscale Vision Transformers `__. + + .. betastatus:: video module + + Args: + weights (:class:`~torchvision.models.video.MViT_V1_B_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.MViT_V1_B_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.MViT`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.MViT_V1_B_Weights + :members: + """ + weights = MViT_V1_B_Weights.verify(weights) + + config: dict[str, list] = { + "num_heads": [1, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8], + "input_channels": [96, 192, 192, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 768, 768], + "output_channels": [192, 192, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 768, 768, 768], + "kernel_q": [[], [3, 3, 3], [], [3, 3, 3], [], [], [], [], [], [], [], [], [], [], [3, 3, 3], []], + "kernel_kv": [ + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + ], + "stride_q": [[], [1, 2, 2], [], [1, 2, 2], [], [], [], [], [], [], [], [], [], [], [1, 2, 2], []], + "stride_kv": [ + [1, 8, 8], + [1, 4, 4], + [1, 4, 4], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 1, 1], + [1, 1, 1], + ], + } + + block_setting = [] + for i in range(len(config["num_heads"])): + block_setting.append( + MSBlockConfig( + num_heads=config["num_heads"][i], + input_channels=config["input_channels"][i], + output_channels=config["output_channels"][i], + kernel_q=config["kernel_q"][i], + kernel_kv=config["kernel_kv"][i], + stride_q=config["stride_q"][i], + stride_kv=config["stride_kv"][i], + ) + ) + + return _mvit( + spatial_size=(224, 224), + temporal_size=16, + block_setting=block_setting, + residual_pool=False, + residual_with_cls_embed=False, + stochastic_depth_prob=kwargs.pop("stochastic_depth_prob", 0.2), + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MViT_V2_S_Weights.KINETICS400_V1)) +def mvit_v2_s(*, weights: Optional[MViT_V2_S_Weights] = None, progress: bool = True, **kwargs: Any) -> MViT: + """Constructs a small MViTV2 architecture from + `Multiscale Vision Transformers `__ and + `MViTv2: Improved Multiscale Vision Transformers for Classification + and Detection `__. + + .. betastatus:: video module + + Args: + weights (:class:`~torchvision.models.video.MViT_V2_S_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.MViT_V2_S_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.MViT`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.MViT_V2_S_Weights + :members: + """ + weights = MViT_V2_S_Weights.verify(weights) + + config: dict[str, list] = { + "num_heads": [1, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8], + "input_channels": [96, 96, 192, 192, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 768], + "output_channels": [96, 192, 192, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 384, 768, 768], + "kernel_q": [ + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + ], + "kernel_kv": [ + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + [3, 3, 3], + ], + "stride_q": [ + [1, 1, 1], + [1, 2, 2], + [1, 1, 1], + [1, 2, 2], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 1, 1], + [1, 2, 2], + [1, 1, 1], + ], + "stride_kv": [ + [1, 8, 8], + [1, 4, 4], + [1, 4, 4], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 2, 2], + [1, 1, 1], + [1, 1, 1], + ], + } + + block_setting = [] + for i in range(len(config["num_heads"])): + block_setting.append( + MSBlockConfig( + num_heads=config["num_heads"][i], + input_channels=config["input_channels"][i], + output_channels=config["output_channels"][i], + kernel_q=config["kernel_q"][i], + kernel_kv=config["kernel_kv"][i], + stride_q=config["stride_q"][i], + stride_kv=config["stride_kv"][i], + ) + ) + + return _mvit( + spatial_size=(224, 224), + temporal_size=16, + block_setting=block_setting, + residual_pool=True, + residual_with_cls_embed=False, + rel_pos_embed=True, + proj_after_attn=True, + stochastic_depth_prob=kwargs.pop("stochastic_depth_prob", 0.2), + weights=weights, + progress=progress, + **kwargs, + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/video/resnet.py b/.venv/lib/python3.12/site-packages/torchvision/models/video/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..43b0df48ffe35c055e63362031088d18c24a2dbe --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/video/resnet.py @@ -0,0 +1,504 @@ +from collections.abc import Sequence +from functools import partial +from typing import Any, Callable, Optional, Union + +import torch.nn as nn +from torch import Tensor + +from ...transforms._presets import VideoClassification +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _KINETICS400_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "VideoResNet", + "R3D_18_Weights", + "MC3_18_Weights", + "R2Plus1D_18_Weights", + "r3d_18", + "mc3_18", + "r2plus1d_18", +] + + +class Conv3DSimple(nn.Conv3d): + def __init__( + self, in_planes: int, out_planes: int, midplanes: Optional[int] = None, stride: int = 1, padding: int = 1 + ) -> None: + + super().__init__( + in_channels=in_planes, + out_channels=out_planes, + kernel_size=(3, 3, 3), + stride=stride, + padding=padding, + bias=False, + ) + + @staticmethod + def get_downsample_stride(stride: int) -> tuple[int, int, int]: + return stride, stride, stride + + +class Conv2Plus1D(nn.Sequential): + def __init__(self, in_planes: int, out_planes: int, midplanes: int, stride: int = 1, padding: int = 1) -> None: + super().__init__( + nn.Conv3d( + in_planes, + midplanes, + kernel_size=(1, 3, 3), + stride=(1, stride, stride), + padding=(0, padding, padding), + bias=False, + ), + nn.BatchNorm3d(midplanes), + nn.ReLU(inplace=True), + nn.Conv3d( + midplanes, out_planes, kernel_size=(3, 1, 1), stride=(stride, 1, 1), padding=(padding, 0, 0), bias=False + ), + ) + + @staticmethod + def get_downsample_stride(stride: int) -> tuple[int, int, int]: + return stride, stride, stride + + +class Conv3DNoTemporal(nn.Conv3d): + def __init__( + self, in_planes: int, out_planes: int, midplanes: Optional[int] = None, stride: int = 1, padding: int = 1 + ) -> None: + + super().__init__( + in_channels=in_planes, + out_channels=out_planes, + kernel_size=(1, 3, 3), + stride=(1, stride, stride), + padding=(0, padding, padding), + bias=False, + ) + + @staticmethod + def get_downsample_stride(stride: int) -> tuple[int, int, int]: + return 1, stride, stride + + +class BasicBlock(nn.Module): + + expansion = 1 + + def __init__( + self, + inplanes: int, + planes: int, + conv_builder: Callable[..., nn.Module], + stride: int = 1, + downsample: Optional[nn.Module] = None, + ) -> None: + midplanes = (inplanes * planes * 3 * 3 * 3) // (inplanes * 3 * 3 + 3 * planes) + + super().__init__() + self.conv1 = nn.Sequential( + conv_builder(inplanes, planes, midplanes, stride), nn.BatchNorm3d(planes), nn.ReLU(inplace=True) + ) + self.conv2 = nn.Sequential(conv_builder(planes, planes, midplanes), nn.BatchNorm3d(planes)) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x: Tensor) -> Tensor: + residual = x + + out = self.conv1(x) + out = self.conv2(out) + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__( + self, + inplanes: int, + planes: int, + conv_builder: Callable[..., nn.Module], + stride: int = 1, + downsample: Optional[nn.Module] = None, + ) -> None: + + super().__init__() + midplanes = (inplanes * planes * 3 * 3 * 3) // (inplanes * 3 * 3 + 3 * planes) + + # 1x1x1 + self.conv1 = nn.Sequential( + nn.Conv3d(inplanes, planes, kernel_size=1, bias=False), nn.BatchNorm3d(planes), nn.ReLU(inplace=True) + ) + # Second kernel + self.conv2 = nn.Sequential( + conv_builder(planes, planes, midplanes, stride), nn.BatchNorm3d(planes), nn.ReLU(inplace=True) + ) + + # 1x1x1 + self.conv3 = nn.Sequential( + nn.Conv3d(planes, planes * self.expansion, kernel_size=1, bias=False), + nn.BatchNorm3d(planes * self.expansion), + ) + self.relu = nn.ReLU(inplace=True) + self.downsample = downsample + self.stride = stride + + def forward(self, x: Tensor) -> Tensor: + residual = x + + out = self.conv1(x) + out = self.conv2(out) + out = self.conv3(out) + + if self.downsample is not None: + residual = self.downsample(x) + + out += residual + out = self.relu(out) + + return out + + +class BasicStem(nn.Sequential): + """The default conv-batchnorm-relu stem""" + + def __init__(self) -> None: + super().__init__( + nn.Conv3d(3, 64, kernel_size=(3, 7, 7), stride=(1, 2, 2), padding=(1, 3, 3), bias=False), + nn.BatchNorm3d(64), + nn.ReLU(inplace=True), + ) + + +class R2Plus1dStem(nn.Sequential): + """R(2+1)D stem is different than the default one as it uses separated 3D convolution""" + + def __init__(self) -> None: + super().__init__( + nn.Conv3d(3, 45, kernel_size=(1, 7, 7), stride=(1, 2, 2), padding=(0, 3, 3), bias=False), + nn.BatchNorm3d(45), + nn.ReLU(inplace=True), + nn.Conv3d(45, 64, kernel_size=(3, 1, 1), stride=(1, 1, 1), padding=(1, 0, 0), bias=False), + nn.BatchNorm3d(64), + nn.ReLU(inplace=True), + ) + + +class VideoResNet(nn.Module): + def __init__( + self, + block: type[Union[BasicBlock, Bottleneck]], + conv_makers: Sequence[type[Union[Conv3DSimple, Conv3DNoTemporal, Conv2Plus1D]]], + layers: list[int], + stem: Callable[..., nn.Module], + num_classes: int = 400, + zero_init_residual: bool = False, + ) -> None: + """Generic resnet video generator. + + Args: + block (Type[Union[BasicBlock, Bottleneck]]): resnet building block + conv_makers (List[Type[Union[Conv3DSimple, Conv3DNoTemporal, Conv2Plus1D]]]): generator + function for each layer + layers (List[int]): number of blocks per layer + stem (Callable[..., nn.Module]): module specifying the ResNet stem. + num_classes (int, optional): Dimension of the final FC layer. Defaults to 400. + zero_init_residual (bool, optional): Zero init bottleneck residual BN. Defaults to False. + """ + super().__init__() + _log_api_usage_once(self) + self.inplanes = 64 + + self.stem = stem() + + self.layer1 = self._make_layer(block, conv_makers[0], 64, layers[0], stride=1) + self.layer2 = self._make_layer(block, conv_makers[1], 128, layers[1], stride=2) + self.layer3 = self._make_layer(block, conv_makers[2], 256, layers[2], stride=2) + self.layer4 = self._make_layer(block, conv_makers[3], 512, layers[3], stride=2) + + self.avgpool = nn.AdaptiveAvgPool3d((1, 1, 1)) + self.fc = nn.Linear(512 * block.expansion, num_classes) + + # init weights + for m in self.modules(): + if isinstance(m, nn.Conv3d): + nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") + if m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.BatchNorm3d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + nn.init.constant_(m.bias, 0) + + if zero_init_residual: + for m in self.modules(): + if isinstance(m, Bottleneck): + nn.init.constant_(m.bn3.weight, 0) # type: ignore[union-attr, arg-type] + + def forward(self, x: Tensor) -> Tensor: + x = self.stem(x) + + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + + x = self.avgpool(x) + # Flatten the layer to fc + x = x.flatten(1) + x = self.fc(x) + + return x + + def _make_layer( + self, + block: type[Union[BasicBlock, Bottleneck]], + conv_builder: type[Union[Conv3DSimple, Conv3DNoTemporal, Conv2Plus1D]], + planes: int, + blocks: int, + stride: int = 1, + ) -> nn.Sequential: + downsample = None + + if stride != 1 or self.inplanes != planes * block.expansion: + ds_stride = conv_builder.get_downsample_stride(stride) + downsample = nn.Sequential( + nn.Conv3d(self.inplanes, planes * block.expansion, kernel_size=1, stride=ds_stride, bias=False), + nn.BatchNorm3d(planes * block.expansion), + ) + layers = [] + layers.append(block(self.inplanes, planes, conv_builder, stride, downsample)) + + self.inplanes = planes * block.expansion + for i in range(1, blocks): + layers.append(block(self.inplanes, planes, conv_builder)) + + return nn.Sequential(*layers) + + +def _video_resnet( + block: type[Union[BasicBlock, Bottleneck]], + conv_makers: Sequence[type[Union[Conv3DSimple, Conv3DNoTemporal, Conv2Plus1D]]], + layers: list[int], + stem: Callable[..., nn.Module], + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> VideoResNet: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = VideoResNet(block, conv_makers, layers, stem, **kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "min_size": (1, 1), + "categories": _KINETICS400_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/video_classification", + "_docs": ( + "The weights reproduce closely the accuracy of the paper. The accuracies are estimated on video-level " + "with parameters `frame_rate=15`, `clips_per_video=5`, and `clip_len=16`." + ), +} + + +class R3D_18_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/r3d_18-b3b3357e.pth", + transforms=partial(VideoClassification, crop_size=(112, 112), resize_size=(128, 171)), + meta={ + **_COMMON_META, + "num_params": 33371472, + "_metrics": { + "Kinetics-400": { + "acc@1": 63.200, + "acc@5": 83.479, + } + }, + "_ops": 40.697, + "_file_size": 127.359, + }, + ) + DEFAULT = KINETICS400_V1 + + +class MC3_18_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/mc3_18-a90a0ba3.pth", + transforms=partial(VideoClassification, crop_size=(112, 112), resize_size=(128, 171)), + meta={ + **_COMMON_META, + "num_params": 11695440, + "_metrics": { + "Kinetics-400": { + "acc@1": 63.960, + "acc@5": 84.130, + } + }, + "_ops": 43.343, + "_file_size": 44.672, + }, + ) + DEFAULT = KINETICS400_V1 + + +class R2Plus1D_18_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/r2plus1d_18-91a641e6.pth", + transforms=partial(VideoClassification, crop_size=(112, 112), resize_size=(128, 171)), + meta={ + **_COMMON_META, + "num_params": 31505325, + "_metrics": { + "Kinetics-400": { + "acc@1": 67.463, + "acc@5": 86.175, + } + }, + "_ops": 40.519, + "_file_size": 120.318, + }, + ) + DEFAULT = KINETICS400_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", R3D_18_Weights.KINETICS400_V1)) +def r3d_18(*, weights: Optional[R3D_18_Weights] = None, progress: bool = True, **kwargs: Any) -> VideoResNet: + """Construct 18 layer Resnet3D model. + + .. betastatus:: video module + + Reference: `A Closer Look at Spatiotemporal Convolutions for Action Recognition `__. + + Args: + weights (:class:`~torchvision.models.video.R3D_18_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.R3D_18_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.resnet.VideoResNet`` base class. + Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.R3D_18_Weights + :members: + """ + weights = R3D_18_Weights.verify(weights) + + return _video_resnet( + BasicBlock, + [Conv3DSimple] * 4, + [2, 2, 2, 2], + BasicStem, + weights, + progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", MC3_18_Weights.KINETICS400_V1)) +def mc3_18(*, weights: Optional[MC3_18_Weights] = None, progress: bool = True, **kwargs: Any) -> VideoResNet: + """Construct 18 layer Mixed Convolution network as in + + .. betastatus:: video module + + Reference: `A Closer Look at Spatiotemporal Convolutions for Action Recognition `__. + + Args: + weights (:class:`~torchvision.models.video.MC3_18_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.MC3_18_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.resnet.VideoResNet`` base class. + Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.MC3_18_Weights + :members: + """ + weights = MC3_18_Weights.verify(weights) + + return _video_resnet( + BasicBlock, + [Conv3DSimple] + [Conv3DNoTemporal] * 3, # type: ignore[list-item] + [2, 2, 2, 2], + BasicStem, + weights, + progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", R2Plus1D_18_Weights.KINETICS400_V1)) +def r2plus1d_18(*, weights: Optional[R2Plus1D_18_Weights] = None, progress: bool = True, **kwargs: Any) -> VideoResNet: + """Construct 18 layer deep R(2+1)D network as in + + .. betastatus:: video module + + Reference: `A Closer Look at Spatiotemporal Convolutions for Action Recognition `__. + + Args: + weights (:class:`~torchvision.models.video.R2Plus1D_18_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.R2Plus1D_18_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.resnet.VideoResNet`` base class. + Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.R2Plus1D_18_Weights + :members: + """ + weights = R2Plus1D_18_Weights.verify(weights) + + return _video_resnet( + BasicBlock, + [Conv2Plus1D] * 4, + [2, 2, 2, 2], + R2Plus1dStem, + weights, + progress, + **kwargs, + ) + + +# The dictionary below is internal implementation detail and will be removed in v0.15 +from .._utils import _ModelURLs + + +model_urls = _ModelURLs( + { + "r3d_18": R3D_18_Weights.KINETICS400_V1.url, + "mc3_18": MC3_18_Weights.KINETICS400_V1.url, + "r2plus1d_18": R2Plus1D_18_Weights.KINETICS400_V1.url, + } +) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/video/s3d.py b/.venv/lib/python3.12/site-packages/torchvision/models/video/s3d.py new file mode 100644 index 0000000000000000000000000000000000000000..4b202829b24fb1dc314452d38a521dfe6c8e446f --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/video/s3d.py @@ -0,0 +1,219 @@ +from functools import partial +from typing import Any, Callable, Optional + +import torch +from torch import nn +from torchvision.ops.misc import Conv3dNormActivation + +from ...transforms._presets import VideoClassification +from ...utils import _log_api_usage_once +from .._api import register_model, Weights, WeightsEnum +from .._meta import _KINETICS400_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "S3D", + "S3D_Weights", + "s3d", +] + + +class TemporalSeparableConv(nn.Sequential): + def __init__( + self, + in_planes: int, + out_planes: int, + kernel_size: int, + stride: int, + padding: int, + norm_layer: Callable[..., nn.Module], + ): + super().__init__( + Conv3dNormActivation( + in_planes, + out_planes, + kernel_size=(1, kernel_size, kernel_size), + stride=(1, stride, stride), + padding=(0, padding, padding), + bias=False, + norm_layer=norm_layer, + ), + Conv3dNormActivation( + out_planes, + out_planes, + kernel_size=(kernel_size, 1, 1), + stride=(stride, 1, 1), + padding=(padding, 0, 0), + bias=False, + norm_layer=norm_layer, + ), + ) + + +class SepInceptionBlock3D(nn.Module): + def __init__( + self, + in_planes: int, + b0_out: int, + b1_mid: int, + b1_out: int, + b2_mid: int, + b2_out: int, + b3_out: int, + norm_layer: Callable[..., nn.Module], + ): + super().__init__() + + self.branch0 = Conv3dNormActivation(in_planes, b0_out, kernel_size=1, stride=1, norm_layer=norm_layer) + self.branch1 = nn.Sequential( + Conv3dNormActivation(in_planes, b1_mid, kernel_size=1, stride=1, norm_layer=norm_layer), + TemporalSeparableConv(b1_mid, b1_out, kernel_size=3, stride=1, padding=1, norm_layer=norm_layer), + ) + self.branch2 = nn.Sequential( + Conv3dNormActivation(in_planes, b2_mid, kernel_size=1, stride=1, norm_layer=norm_layer), + TemporalSeparableConv(b2_mid, b2_out, kernel_size=3, stride=1, padding=1, norm_layer=norm_layer), + ) + self.branch3 = nn.Sequential( + nn.MaxPool3d(kernel_size=(3, 3, 3), stride=1, padding=1), + Conv3dNormActivation(in_planes, b3_out, kernel_size=1, stride=1, norm_layer=norm_layer), + ) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + x2 = self.branch2(x) + x3 = self.branch3(x) + out = torch.cat((x0, x1, x2, x3), 1) + + return out + + +class S3D(nn.Module): + """S3D main class. + + Args: + num_class (int): number of classes for the classification task. + dropout (float): dropout probability. + norm_layer (Optional[Callable]): Module specifying the normalization layer to use. + + Inputs: + x (Tensor): batch of videos with dimensions (batch, channel, time, height, width) + """ + + def __init__( + self, + num_classes: int = 400, + dropout: float = 0.2, + norm_layer: Optional[Callable[..., torch.nn.Module]] = None, + ) -> None: + super().__init__() + _log_api_usage_once(self) + + if norm_layer is None: + norm_layer = partial(nn.BatchNorm3d, eps=0.001, momentum=0.001) + + self.features = nn.Sequential( + TemporalSeparableConv(3, 64, 7, 2, 3, norm_layer), + nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1)), + Conv3dNormActivation( + 64, + 64, + kernel_size=1, + stride=1, + norm_layer=norm_layer, + ), + TemporalSeparableConv(64, 192, 3, 1, 1, norm_layer), + nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1)), + SepInceptionBlock3D(192, 64, 96, 128, 16, 32, 32, norm_layer), + SepInceptionBlock3D(256, 128, 128, 192, 32, 96, 64, norm_layer), + nn.MaxPool3d(kernel_size=(3, 3, 3), stride=(2, 2, 2), padding=(1, 1, 1)), + SepInceptionBlock3D(480, 192, 96, 208, 16, 48, 64, norm_layer), + SepInceptionBlock3D(512, 160, 112, 224, 24, 64, 64, norm_layer), + SepInceptionBlock3D(512, 128, 128, 256, 24, 64, 64, norm_layer), + SepInceptionBlock3D(512, 112, 144, 288, 32, 64, 64, norm_layer), + SepInceptionBlock3D(528, 256, 160, 320, 32, 128, 128, norm_layer), + nn.MaxPool3d(kernel_size=(2, 2, 2), stride=(2, 2, 2), padding=(0, 0, 0)), + SepInceptionBlock3D(832, 256, 160, 320, 32, 128, 128, norm_layer), + SepInceptionBlock3D(832, 384, 192, 384, 48, 128, 128, norm_layer), + ) + self.avgpool = nn.AvgPool3d(kernel_size=(2, 7, 7), stride=1) + self.classifier = nn.Sequential( + nn.Dropout(p=dropout), + nn.Conv3d(1024, num_classes, kernel_size=1, stride=1, bias=True), + ) + + def forward(self, x): + x = self.features(x) + x = self.avgpool(x) + x = self.classifier(x) + x = torch.mean(x, dim=(2, 3, 4)) + return x + + +class S3D_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/s3d-d76dad2f.pth", + transforms=partial( + VideoClassification, + crop_size=(224, 224), + resize_size=(256, 256), + ), + meta={ + "min_size": (224, 224), + "min_temporal_size": 14, + "categories": _KINETICS400_CATEGORIES, + "recipe": "https://github.com/pytorch/vision/tree/main/references/video_classification#s3d", + "_docs": ( + "The weights aim to approximate the accuracy of the paper. The accuracies are estimated on clip-level " + "with parameters `frame_rate=15`, `clips_per_video=1`, and `clip_len=128`." + ), + "num_params": 8320048, + "_metrics": { + "Kinetics-400": { + "acc@1": 68.368, + "acc@5": 88.050, + } + }, + "_ops": 17.979, + "_file_size": 31.972, + }, + ) + DEFAULT = KINETICS400_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", S3D_Weights.KINETICS400_V1)) +def s3d(*, weights: Optional[S3D_Weights] = None, progress: bool = True, **kwargs: Any) -> S3D: + """Construct Separable 3D CNN model. + + Reference: `Rethinking Spatiotemporal Feature Learning `__. + + .. betastatus:: video module + + Args: + weights (:class:`~torchvision.models.video.S3D_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.S3D_Weights` + below for more details, and possible values. By default, no + pre-trained weights are used. + progress (bool): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.S3D`` base class. + Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.S3D_Weights + :members: + """ + weights = S3D_Weights.verify(weights) + + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = S3D(**kwargs) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/video/swin_transformer.py b/.venv/lib/python3.12/site-packages/torchvision/models/video/swin_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..1a198142874224a6766f321d9e0dfc97a01ecb43 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/video/swin_transformer.py @@ -0,0 +1,743 @@ +# Modified from 2d Swin Transformers in torchvision: +# https://github.com/pytorch/vision/blob/main/torchvision/models/swin_transformer.py + +from functools import partial +from typing import Any, Callable, Optional + +import torch +import torch.nn.functional as F +from torch import nn, Tensor + +from ...transforms._presets import VideoClassification + +from ...utils import _log_api_usage_once + +from .._api import register_model, Weights, WeightsEnum + +from .._meta import _KINETICS400_CATEGORIES +from .._utils import _ovewrite_named_param, handle_legacy_interface +from ..swin_transformer import PatchMerging, SwinTransformerBlock + +__all__ = [ + "SwinTransformer3d", + "Swin3D_T_Weights", + "Swin3D_S_Weights", + "Swin3D_B_Weights", + "swin3d_t", + "swin3d_s", + "swin3d_b", +] + + +def _get_window_and_shift_size( + shift_size: list[int], size_dhw: list[int], window_size: list[int] +) -> tuple[list[int], list[int]]: + for i in range(3): + if size_dhw[i] <= window_size[i]: + # In this case, window_size will adapt to the input size, and no need to shift + window_size[i] = size_dhw[i] + shift_size[i] = 0 + + return window_size, shift_size + + +torch.fx.wrap("_get_window_and_shift_size") + + +def _get_relative_position_bias( + relative_position_bias_table: torch.Tensor, relative_position_index: torch.Tensor, window_size: list[int] +) -> Tensor: + window_vol = window_size[0] * window_size[1] * window_size[2] + # In 3d case we flatten the relative_position_bias + relative_position_bias = relative_position_bias_table[ + relative_position_index[:window_vol, :window_vol].flatten() # type: ignore[index] + ] + relative_position_bias = relative_position_bias.view(window_vol, window_vol, -1) + relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous().unsqueeze(0) + return relative_position_bias + + +torch.fx.wrap("_get_relative_position_bias") + + +def _compute_pad_size_3d(size_dhw: tuple[int, int, int], patch_size: tuple[int, int, int]) -> tuple[int, int, int]: + pad_size = [(patch_size[i] - size_dhw[i] % patch_size[i]) % patch_size[i] for i in range(3)] + return pad_size[0], pad_size[1], pad_size[2] + + +torch.fx.wrap("_compute_pad_size_3d") + + +def _compute_attention_mask_3d( + x: Tensor, + size_dhw: tuple[int, int, int], + window_size: tuple[int, int, int], + shift_size: tuple[int, int, int], +) -> Tensor: + # generate attention mask + attn_mask = x.new_zeros(*size_dhw) + num_windows = (size_dhw[0] // window_size[0]) * (size_dhw[1] // window_size[1]) * (size_dhw[2] // window_size[2]) + slices = [ + ( + (0, -window_size[i]), + (-window_size[i], -shift_size[i]), + (-shift_size[i], None), + ) + for i in range(3) + ] + count = 0 + for d in slices[0]: + for h in slices[1]: + for w in slices[2]: + attn_mask[d[0] : d[1], h[0] : h[1], w[0] : w[1]] = count + count += 1 + + # Partition window on attn_mask + attn_mask = attn_mask.view( + size_dhw[0] // window_size[0], + window_size[0], + size_dhw[1] // window_size[1], + window_size[1], + size_dhw[2] // window_size[2], + window_size[2], + ) + attn_mask = attn_mask.permute(0, 2, 4, 1, 3, 5).reshape( + num_windows, window_size[0] * window_size[1] * window_size[2] + ) + attn_mask = attn_mask.unsqueeze(1) - attn_mask.unsqueeze(2) + attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) + return attn_mask + + +torch.fx.wrap("_compute_attention_mask_3d") + + +def shifted_window_attention_3d( + input: Tensor, + qkv_weight: Tensor, + proj_weight: Tensor, + relative_position_bias: Tensor, + window_size: list[int], + num_heads: int, + shift_size: list[int], + attention_dropout: float = 0.0, + dropout: float = 0.0, + qkv_bias: Optional[Tensor] = None, + proj_bias: Optional[Tensor] = None, + training: bool = True, +) -> Tensor: + """ + Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + Args: + input (Tensor[B, T, H, W, C]): The input tensor, 5-dimensions. + qkv_weight (Tensor[in_dim, out_dim]): The weight tensor of query, key, value. + proj_weight (Tensor[out_dim, out_dim]): The weight tensor of projection. + relative_position_bias (Tensor): The learned relative position bias added to attention. + window_size (List[int]): 3-dimensions window size, T, H, W . + num_heads (int): Number of attention heads. + shift_size (List[int]): Shift size for shifted window attention (T, H, W). + attention_dropout (float): Dropout ratio of attention weight. Default: 0.0. + dropout (float): Dropout ratio of output. Default: 0.0. + qkv_bias (Tensor[out_dim], optional): The bias tensor of query, key, value. Default: None. + proj_bias (Tensor[out_dim], optional): The bias tensor of projection. Default: None. + training (bool, optional): Training flag used by the dropout parameters. Default: True. + Returns: + Tensor[B, T, H, W, C]: The output tensor after shifted window attention. + """ + b, t, h, w, c = input.shape + # pad feature maps to multiples of window size + pad_size = _compute_pad_size_3d((t, h, w), (window_size[0], window_size[1], window_size[2])) + x = F.pad(input, (0, 0, 0, pad_size[2], 0, pad_size[1], 0, pad_size[0])) + _, tp, hp, wp, _ = x.shape + padded_size = (tp, hp, wp) + + # cyclic shift + if sum(shift_size) > 0: + x = torch.roll(x, shifts=(-shift_size[0], -shift_size[1], -shift_size[2]), dims=(1, 2, 3)) + + # partition windows + num_windows = ( + (padded_size[0] // window_size[0]) * (padded_size[1] // window_size[1]) * (padded_size[2] // window_size[2]) + ) + x = x.view( + b, + padded_size[0] // window_size[0], + window_size[0], + padded_size[1] // window_size[1], + window_size[1], + padded_size[2] // window_size[2], + window_size[2], + c, + ) + x = x.permute(0, 1, 3, 5, 2, 4, 6, 7).reshape( + b * num_windows, window_size[0] * window_size[1] * window_size[2], c + ) # B*nW, Wd*Wh*Ww, C + + # multi-head attention + qkv = F.linear(x, qkv_weight, qkv_bias) + qkv = qkv.reshape(x.size(0), x.size(1), 3, num_heads, c // num_heads).permute(2, 0, 3, 1, 4) + q, k, v = qkv[0], qkv[1], qkv[2] + q = q * (c // num_heads) ** -0.5 + attn = q.matmul(k.transpose(-2, -1)) + # add relative position bias + attn = attn + relative_position_bias + + if sum(shift_size) > 0: + # generate attention mask to handle shifted windows with varying size + attn_mask = _compute_attention_mask_3d( + x, + (padded_size[0], padded_size[1], padded_size[2]), + (window_size[0], window_size[1], window_size[2]), + (shift_size[0], shift_size[1], shift_size[2]), + ) + attn = attn.view(x.size(0) // num_windows, num_windows, num_heads, x.size(1), x.size(1)) + attn = attn + attn_mask.unsqueeze(1).unsqueeze(0) + attn = attn.view(-1, num_heads, x.size(1), x.size(1)) + + attn = F.softmax(attn, dim=-1) + attn = F.dropout(attn, p=attention_dropout, training=training) + + x = attn.matmul(v).transpose(1, 2).reshape(x.size(0), x.size(1), c) + x = F.linear(x, proj_weight, proj_bias) + x = F.dropout(x, p=dropout, training=training) + + # reverse windows + x = x.view( + b, + padded_size[0] // window_size[0], + padded_size[1] // window_size[1], + padded_size[2] // window_size[2], + window_size[0], + window_size[1], + window_size[2], + c, + ) + x = x.permute(0, 1, 4, 2, 5, 3, 6, 7).reshape(b, tp, hp, wp, c) + + # reverse cyclic shift + if sum(shift_size) > 0: + x = torch.roll(x, shifts=(shift_size[0], shift_size[1], shift_size[2]), dims=(1, 2, 3)) + + # unpad features + x = x[:, :t, :h, :w, :].contiguous() + return x + + +torch.fx.wrap("shifted_window_attention_3d") + + +class ShiftedWindowAttention3d(nn.Module): + """ + See :func:`shifted_window_attention_3d`. + """ + + def __init__( + self, + dim: int, + window_size: list[int], + shift_size: list[int], + num_heads: int, + qkv_bias: bool = True, + proj_bias: bool = True, + attention_dropout: float = 0.0, + dropout: float = 0.0, + ) -> None: + super().__init__() + if len(window_size) != 3 or len(shift_size) != 3: + raise ValueError("window_size and shift_size must be of length 2") + + self.window_size = window_size # Wd, Wh, Ww + self.shift_size = shift_size + self.num_heads = num_heads + self.attention_dropout = attention_dropout + self.dropout = dropout + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim, bias=proj_bias) + + self.define_relative_position_bias_table() + self.define_relative_position_index() + + def define_relative_position_bias_table(self) -> None: + # define a parameter table of relative position bias + self.relative_position_bias_table = nn.Parameter( + torch.zeros( + (2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1) * (2 * self.window_size[2] - 1), + self.num_heads, + ) + ) # 2*Wd-1 * 2*Wh-1 * 2*Ww-1, nH + nn.init.trunc_normal_(self.relative_position_bias_table, std=0.02) + + def define_relative_position_index(self) -> None: + # get pair-wise relative position index for each token inside the window + coords_dhw = [torch.arange(self.window_size[i]) for i in range(3)] + coords = torch.stack( + torch.meshgrid(coords_dhw[0], coords_dhw[1], coords_dhw[2], indexing="ij") + ) # 3, Wd, Wh, Ww + coords_flatten = torch.flatten(coords, 1) # 3, Wd*Wh*Ww + relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 3, Wd*Wh*Ww, Wd*Wh*Ww + relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wd*Wh*Ww, Wd*Wh*Ww, 3 + relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0 + relative_coords[:, :, 1] += self.window_size[1] - 1 + relative_coords[:, :, 2] += self.window_size[2] - 1 + + relative_coords[:, :, 0] *= (2 * self.window_size[1] - 1) * (2 * self.window_size[2] - 1) + relative_coords[:, :, 1] *= 2 * self.window_size[2] - 1 + # We don't flatten the relative_position_index here in 3d case. + relative_position_index = relative_coords.sum(-1) # Wd*Wh*Ww, Wd*Wh*Ww + self.register_buffer("relative_position_index", relative_position_index) + + def get_relative_position_bias(self, window_size: list[int]) -> torch.Tensor: + return _get_relative_position_bias(self.relative_position_bias_table, self.relative_position_index, window_size) # type: ignore + + def forward(self, x: Tensor) -> Tensor: + _, t, h, w, _ = x.shape + size_dhw = [t, h, w] + window_size, shift_size = self.window_size.copy(), self.shift_size.copy() + # Handle case where window_size is larger than the input tensor + window_size, shift_size = _get_window_and_shift_size(shift_size, size_dhw, window_size) + + relative_position_bias = self.get_relative_position_bias(window_size) + + return shifted_window_attention_3d( + x, + self.qkv.weight, + self.proj.weight, + relative_position_bias, + window_size, + self.num_heads, + shift_size=shift_size, + attention_dropout=self.attention_dropout, + dropout=self.dropout, + qkv_bias=self.qkv.bias, + proj_bias=self.proj.bias, + training=self.training, + ) + + +# Modified from: +# https://github.com/SwinTransformer/Video-Swin-Transformer/blob/master/mmaction/models/backbones/swin_transformer.py +class PatchEmbed3d(nn.Module): + """Video to Patch Embedding. + + Args: + patch_size (List[int]): Patch token size. + in_channels (int): Number of input channels. Default: 3 + embed_dim (int): Number of linear projection output channels. Default: 96. + norm_layer (nn.Module, optional): Normalization layer. Default: None + """ + + def __init__( + self, + patch_size: list[int], + in_channels: int = 3, + embed_dim: int = 96, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.tuple_patch_size = (patch_size[0], patch_size[1], patch_size[2]) + + self.proj = nn.Conv3d( + in_channels, + embed_dim, + kernel_size=self.tuple_patch_size, + stride=self.tuple_patch_size, + ) + if norm_layer is not None: + self.norm = norm_layer(embed_dim) + else: + self.norm = nn.Identity() + + def forward(self, x: Tensor) -> Tensor: + """Forward function.""" + # padding + _, _, t, h, w = x.size() + pad_size = _compute_pad_size_3d((t, h, w), self.tuple_patch_size) + x = F.pad(x, (0, pad_size[2], 0, pad_size[1], 0, pad_size[0])) + x = self.proj(x) # B C T Wh Ww + x = x.permute(0, 2, 3, 4, 1) # B T Wh Ww C + if self.norm is not None: + x = self.norm(x) + return x + + +class SwinTransformer3d(nn.Module): + """ + Implements 3D Swin Transformer from the `"Video Swin Transformer" `_ paper. + Args: + patch_size (List[int]): Patch size. + embed_dim (int): Patch embedding dimension. + depths (List(int)): Depth of each Swin Transformer layer. + num_heads (List(int)): Number of attention heads in different layers. + window_size (List[int]): Window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.0. + dropout (float): Dropout rate. Default: 0.0. + attention_dropout (float): Attention dropout rate. Default: 0.0. + stochastic_depth_prob (float): Stochastic depth rate. Default: 0.1. + num_classes (int): Number of classes for classification head. Default: 400. + norm_layer (nn.Module, optional): Normalization layer. Default: None. + block (nn.Module, optional): SwinTransformer Block. Default: None. + downsample_layer (nn.Module): Downsample layer (patch merging). Default: PatchMerging. + patch_embed (nn.Module, optional): Patch Embedding layer. Default: None. + """ + + def __init__( + self, + patch_size: list[int], + embed_dim: int, + depths: list[int], + num_heads: list[int], + window_size: list[int], + mlp_ratio: float = 4.0, + dropout: float = 0.0, + attention_dropout: float = 0.0, + stochastic_depth_prob: float = 0.1, + num_classes: int = 400, + norm_layer: Optional[Callable[..., nn.Module]] = None, + block: Optional[Callable[..., nn.Module]] = None, + downsample_layer: Callable[..., nn.Module] = PatchMerging, + patch_embed: Optional[Callable[..., nn.Module]] = None, + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.num_classes = num_classes + + if block is None: + block = partial(SwinTransformerBlock, attn_layer=ShiftedWindowAttention3d) + + if norm_layer is None: + norm_layer = partial(nn.LayerNorm, eps=1e-5) + + if patch_embed is None: + patch_embed = PatchEmbed3d + + # split image into non-overlapping patches + self.patch_embed = patch_embed(patch_size=patch_size, embed_dim=embed_dim, norm_layer=norm_layer) + self.pos_drop = nn.Dropout(p=dropout) + + layers: list[nn.Module] = [] + total_stage_blocks = sum(depths) + stage_block_id = 0 + # build SwinTransformer blocks + for i_stage in range(len(depths)): + stage: list[nn.Module] = [] + dim = embed_dim * 2**i_stage + for i_layer in range(depths[i_stage]): + # adjust stochastic depth probability based on the depth of the stage block + sd_prob = stochastic_depth_prob * float(stage_block_id) / (total_stage_blocks - 1) + stage.append( + block( + dim, + num_heads[i_stage], + window_size=window_size, + shift_size=[0 if i_layer % 2 == 0 else w // 2 for w in window_size], + mlp_ratio=mlp_ratio, + dropout=dropout, + attention_dropout=attention_dropout, + stochastic_depth_prob=sd_prob, + norm_layer=norm_layer, + attn_layer=ShiftedWindowAttention3d, + ) + ) + stage_block_id += 1 + layers.append(nn.Sequential(*stage)) + # add patch merging layer + if i_stage < (len(depths) - 1): + layers.append(downsample_layer(dim, norm_layer)) + self.features = nn.Sequential(*layers) + + self.num_features = embed_dim * 2 ** (len(depths) - 1) + self.norm = norm_layer(self.num_features) + self.avgpool = nn.AdaptiveAvgPool3d(1) + self.head = nn.Linear(self.num_features, num_classes) + + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.trunc_normal_(m.weight, std=0.02) + if m.bias is not None: + nn.init.zeros_(m.bias) + + def forward(self, x: Tensor) -> Tensor: + # x: B C T H W + x = self.patch_embed(x) # B _T _H _W C + x = self.pos_drop(x) + x = self.features(x) # B _T _H _W C + x = self.norm(x) + x = x.permute(0, 4, 1, 2, 3) # B, C, _T, _H, _W + x = self.avgpool(x) + x = torch.flatten(x, 1) + x = self.head(x) + return x + + +def _swin_transformer3d( + patch_size: list[int], + embed_dim: int, + depths: list[int], + num_heads: list[int], + window_size: list[int], + stochastic_depth_prob: float, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> SwinTransformer3d: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + + model = SwinTransformer3d( + patch_size=patch_size, + embed_dim=embed_dim, + depths=depths, + num_heads=num_heads, + window_size=window_size, + stochastic_depth_prob=stochastic_depth_prob, + **kwargs, + ) + + if weights is not None: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META = { + "categories": _KINETICS400_CATEGORIES, + "min_size": (1, 1), + "min_temporal_size": 1, +} + + +class Swin3D_T_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/swin3d_t-7615ae03.pth", + transforms=partial( + VideoClassification, + crop_size=(224, 224), + resize_size=(256,), + mean=(0.4850, 0.4560, 0.4060), + std=(0.2290, 0.2240, 0.2250), + ), + meta={ + **_COMMON_META, + "recipe": "https://github.com/SwinTransformer/Video-Swin-Transformer#kinetics-400", + "_docs": ( + "The weights were ported from the paper. The accuracies are estimated on video-level " + "with parameters `frame_rate=15`, `clips_per_video=12`, and `clip_len=32`" + ), + "num_params": 28158070, + "_metrics": { + "Kinetics-400": { + "acc@1": 77.715, + "acc@5": 93.519, + } + }, + "_ops": 43.882, + "_file_size": 121.543, + }, + ) + DEFAULT = KINETICS400_V1 + + +class Swin3D_S_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/swin3d_s-da41c237.pth", + transforms=partial( + VideoClassification, + crop_size=(224, 224), + resize_size=(256,), + mean=(0.4850, 0.4560, 0.4060), + std=(0.2290, 0.2240, 0.2250), + ), + meta={ + **_COMMON_META, + "recipe": "https://github.com/SwinTransformer/Video-Swin-Transformer#kinetics-400", + "_docs": ( + "The weights were ported from the paper. The accuracies are estimated on video-level " + "with parameters `frame_rate=15`, `clips_per_video=12`, and `clip_len=32`" + ), + "num_params": 49816678, + "_metrics": { + "Kinetics-400": { + "acc@1": 79.521, + "acc@5": 94.158, + } + }, + "_ops": 82.841, + "_file_size": 218.288, + }, + ) + DEFAULT = KINETICS400_V1 + + +class Swin3D_B_Weights(WeightsEnum): + KINETICS400_V1 = Weights( + url="https://download.pytorch.org/models/swin3d_b_1k-24f7c7c6.pth", + transforms=partial( + VideoClassification, + crop_size=(224, 224), + resize_size=(256,), + mean=(0.4850, 0.4560, 0.4060), + std=(0.2290, 0.2240, 0.2250), + ), + meta={ + **_COMMON_META, + "recipe": "https://github.com/SwinTransformer/Video-Swin-Transformer#kinetics-400", + "_docs": ( + "The weights were ported from the paper. The accuracies are estimated on video-level " + "with parameters `frame_rate=15`, `clips_per_video=12`, and `clip_len=32`" + ), + "num_params": 88048984, + "_metrics": { + "Kinetics-400": { + "acc@1": 79.427, + "acc@5": 94.386, + } + }, + "_ops": 140.667, + "_file_size": 364.134, + }, + ) + KINETICS400_IMAGENET22K_V1 = Weights( + url="https://download.pytorch.org/models/swin3d_b_22k-7c6ae6fa.pth", + transforms=partial( + VideoClassification, + crop_size=(224, 224), + resize_size=(256,), + mean=(0.4850, 0.4560, 0.4060), + std=(0.2290, 0.2240, 0.2250), + ), + meta={ + **_COMMON_META, + "recipe": "https://github.com/SwinTransformer/Video-Swin-Transformer#kinetics-400", + "_docs": ( + "The weights were ported from the paper. The accuracies are estimated on video-level " + "with parameters `frame_rate=15`, `clips_per_video=12`, and `clip_len=32`" + ), + "num_params": 88048984, + "_metrics": { + "Kinetics-400": { + "acc@1": 81.643, + "acc@5": 95.574, + } + }, + "_ops": 140.667, + "_file_size": 364.134, + }, + ) + DEFAULT = KINETICS400_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin3D_T_Weights.KINETICS400_V1)) +def swin3d_t(*, weights: Optional[Swin3D_T_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer3d: + """ + Constructs a swin_tiny architecture from + `Video Swin Transformer `_. + + Args: + weights (:class:`~torchvision.models.video.Swin3D_T_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.Swin3D_T_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.Swin3D_T_Weights + :members: + """ + weights = Swin3D_T_Weights.verify(weights) + + return _swin_transformer3d( + patch_size=[2, 4, 4], + embed_dim=96, + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_size=[8, 7, 7], + stochastic_depth_prob=0.1, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin3D_S_Weights.KINETICS400_V1)) +def swin3d_s(*, weights: Optional[Swin3D_S_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer3d: + """ + Constructs a swin_small architecture from + `Video Swin Transformer `_. + + Args: + weights (:class:`~torchvision.models.video.Swin3D_S_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.Swin3D_S_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.Swin3D_S_Weights + :members: + """ + weights = Swin3D_S_Weights.verify(weights) + + return _swin_transformer3d( + patch_size=[2, 4, 4], + embed_dim=96, + depths=[2, 2, 18, 2], + num_heads=[3, 6, 12, 24], + window_size=[8, 7, 7], + stochastic_depth_prob=0.1, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", Swin3D_B_Weights.KINETICS400_V1)) +def swin3d_b(*, weights: Optional[Swin3D_B_Weights] = None, progress: bool = True, **kwargs: Any) -> SwinTransformer3d: + """ + Constructs a swin_base architecture from + `Video Swin Transformer `_. + + Args: + weights (:class:`~torchvision.models.video.Swin3D_B_Weights`, optional): The + pretrained weights to use. See + :class:`~torchvision.models.video.Swin3D_B_Weights` below for + more details, and possible values. By default, no pre-trained + weights are used. + progress (bool, optional): If True, displays a progress bar of the + download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.video.swin_transformer.SwinTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.video.Swin3D_B_Weights + :members: + """ + weights = Swin3D_B_Weights.verify(weights) + + return _swin_transformer3d( + patch_size=[2, 4, 4], + embed_dim=128, + depths=[2, 2, 18, 2], + num_heads=[4, 8, 16, 32], + window_size=[8, 7, 7], + stochastic_depth_prob=0.1, + weights=weights, + progress=progress, + **kwargs, + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/models/vision_transformer.py b/.venv/lib/python3.12/site-packages/torchvision/models/vision_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..4ec3a5c59f0a4112f1eec0ec7d5c0ccba5289946 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/models/vision_transformer.py @@ -0,0 +1,864 @@ +import math +from collections import OrderedDict +from functools import partial +from typing import Any, Callable, NamedTuple, Optional + +import torch +import torch.nn as nn + +from ..ops.misc import Conv2dNormActivation, MLP +from ..transforms._presets import ImageClassification, InterpolationMode +from ..utils import _log_api_usage_once +from ._api import register_model, Weights, WeightsEnum +from ._meta import _IMAGENET_CATEGORIES +from ._utils import _ovewrite_named_param, handle_legacy_interface + + +__all__ = [ + "VisionTransformer", + "ViT_B_16_Weights", + "ViT_B_32_Weights", + "ViT_L_16_Weights", + "ViT_L_32_Weights", + "ViT_H_14_Weights", + "vit_b_16", + "vit_b_32", + "vit_l_16", + "vit_l_32", + "vit_h_14", +] + + +class ConvStemConfig(NamedTuple): + out_channels: int + kernel_size: int + stride: int + norm_layer: Callable[..., nn.Module] = nn.BatchNorm2d + activation_layer: Callable[..., nn.Module] = nn.ReLU + + +class MLPBlock(MLP): + """Transformer MLP block.""" + + _version = 2 + + def __init__(self, in_dim: int, mlp_dim: int, dropout: float): + super().__init__(in_dim, [mlp_dim, in_dim], activation_layer=nn.GELU, inplace=None, dropout=dropout) + + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.xavier_uniform_(m.weight) + if m.bias is not None: + nn.init.normal_(m.bias, std=1e-6) + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if version is None or version < 2: + # Replacing legacy MLPBlock with MLP. See https://github.com/pytorch/vision/pull/6053 + for i in range(2): + for type in ["weight", "bias"]: + old_key = f"{prefix}linear_{i+1}.{type}" + new_key = f"{prefix}{3*i}.{type}" + if old_key in state_dict: + state_dict[new_key] = state_dict.pop(old_key) + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + +class EncoderBlock(nn.Module): + """Transformer encoder block.""" + + def __init__( + self, + num_heads: int, + hidden_dim: int, + mlp_dim: int, + dropout: float, + attention_dropout: float, + norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6), + ): + super().__init__() + self.num_heads = num_heads + + # Attention block + self.ln_1 = norm_layer(hidden_dim) + self.self_attention = nn.MultiheadAttention(hidden_dim, num_heads, dropout=attention_dropout, batch_first=True) + self.dropout = nn.Dropout(dropout) + + # MLP block + self.ln_2 = norm_layer(hidden_dim) + self.mlp = MLPBlock(hidden_dim, mlp_dim, dropout) + + def forward(self, input: torch.Tensor): + torch._assert(input.dim() == 3, f"Expected (batch_size, seq_length, hidden_dim) got {input.shape}") + x = self.ln_1(input) + x, _ = self.self_attention(x, x, x, need_weights=False) + x = self.dropout(x) + x = x + input + + y = self.ln_2(x) + y = self.mlp(y) + return x + y + + +class Encoder(nn.Module): + """Transformer Model Encoder for sequence to sequence translation.""" + + def __init__( + self, + seq_length: int, + num_layers: int, + num_heads: int, + hidden_dim: int, + mlp_dim: int, + dropout: float, + attention_dropout: float, + norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6), + ): + super().__init__() + # Note that batch_size is on the first dim because + # we have batch_first=True in nn.MultiAttention() by default + self.pos_embedding = nn.Parameter(torch.empty(1, seq_length, hidden_dim).normal_(std=0.02)) # from BERT + self.dropout = nn.Dropout(dropout) + layers: OrderedDict[str, nn.Module] = OrderedDict() + for i in range(num_layers): + layers[f"encoder_layer_{i}"] = EncoderBlock( + num_heads, + hidden_dim, + mlp_dim, + dropout, + attention_dropout, + norm_layer, + ) + self.layers = nn.Sequential(layers) + self.ln = norm_layer(hidden_dim) + + def forward(self, input: torch.Tensor): + torch._assert(input.dim() == 3, f"Expected (batch_size, seq_length, hidden_dim) got {input.shape}") + input = input + self.pos_embedding + return self.ln(self.layers(self.dropout(input))) + + +class VisionTransformer(nn.Module): + """Vision Transformer as per https://arxiv.org/abs/2010.11929.""" + + def __init__( + self, + image_size: int, + patch_size: int, + num_layers: int, + num_heads: int, + hidden_dim: int, + mlp_dim: int, + dropout: float = 0.0, + attention_dropout: float = 0.0, + num_classes: int = 1000, + representation_size: Optional[int] = None, + norm_layer: Callable[..., torch.nn.Module] = partial(nn.LayerNorm, eps=1e-6), + conv_stem_configs: Optional[list[ConvStemConfig]] = None, + ): + super().__init__() + _log_api_usage_once(self) + torch._assert(image_size % patch_size == 0, "Input shape indivisible by patch size!") + self.image_size = image_size + self.patch_size = patch_size + self.hidden_dim = hidden_dim + self.mlp_dim = mlp_dim + self.attention_dropout = attention_dropout + self.dropout = dropout + self.num_classes = num_classes + self.representation_size = representation_size + self.norm_layer = norm_layer + + if conv_stem_configs is not None: + # As per https://arxiv.org/abs/2106.14881 + seq_proj = nn.Sequential() + prev_channels = 3 + for i, conv_stem_layer_config in enumerate(conv_stem_configs): + seq_proj.add_module( + f"conv_bn_relu_{i}", + Conv2dNormActivation( + in_channels=prev_channels, + out_channels=conv_stem_layer_config.out_channels, + kernel_size=conv_stem_layer_config.kernel_size, + stride=conv_stem_layer_config.stride, + norm_layer=conv_stem_layer_config.norm_layer, + activation_layer=conv_stem_layer_config.activation_layer, + ), + ) + prev_channels = conv_stem_layer_config.out_channels + seq_proj.add_module( + "conv_last", nn.Conv2d(in_channels=prev_channels, out_channels=hidden_dim, kernel_size=1) + ) + self.conv_proj: nn.Module = seq_proj + else: + self.conv_proj = nn.Conv2d( + in_channels=3, out_channels=hidden_dim, kernel_size=patch_size, stride=patch_size + ) + + seq_length = (image_size // patch_size) ** 2 + + # Add a class token + self.class_token = nn.Parameter(torch.zeros(1, 1, hidden_dim)) + seq_length += 1 + + self.encoder = Encoder( + seq_length, + num_layers, + num_heads, + hidden_dim, + mlp_dim, + dropout, + attention_dropout, + norm_layer, + ) + self.seq_length = seq_length + + heads_layers: OrderedDict[str, nn.Module] = OrderedDict() + if representation_size is None: + heads_layers["head"] = nn.Linear(hidden_dim, num_classes) + else: + heads_layers["pre_logits"] = nn.Linear(hidden_dim, representation_size) + heads_layers["act"] = nn.Tanh() + heads_layers["head"] = nn.Linear(representation_size, num_classes) + + self.heads = nn.Sequential(heads_layers) + + if isinstance(self.conv_proj, nn.Conv2d): + # Init the patchify stem + fan_in = self.conv_proj.in_channels * self.conv_proj.kernel_size[0] * self.conv_proj.kernel_size[1] + nn.init.trunc_normal_(self.conv_proj.weight, std=math.sqrt(1 / fan_in)) + if self.conv_proj.bias is not None: + nn.init.zeros_(self.conv_proj.bias) + elif self.conv_proj.conv_last is not None and isinstance(self.conv_proj.conv_last, nn.Conv2d): + # Init the last 1x1 conv of the conv stem + nn.init.normal_( + self.conv_proj.conv_last.weight, mean=0.0, std=math.sqrt(2.0 / self.conv_proj.conv_last.out_channels) + ) + if self.conv_proj.conv_last.bias is not None: + nn.init.zeros_(self.conv_proj.conv_last.bias) + + if hasattr(self.heads, "pre_logits") and isinstance(self.heads.pre_logits, nn.Linear): + fan_in = self.heads.pre_logits.in_features + nn.init.trunc_normal_(self.heads.pre_logits.weight, std=math.sqrt(1 / fan_in)) + nn.init.zeros_(self.heads.pre_logits.bias) + + if isinstance(self.heads.head, nn.Linear): + nn.init.zeros_(self.heads.head.weight) + nn.init.zeros_(self.heads.head.bias) + + def _process_input(self, x: torch.Tensor) -> torch.Tensor: + n, c, h, w = x.shape + p = self.patch_size + torch._assert(h == self.image_size, f"Wrong image height! Expected {self.image_size} but got {h}!") + torch._assert(w == self.image_size, f"Wrong image width! Expected {self.image_size} but got {w}!") + n_h = h // p + n_w = w // p + + # (n, c, h, w) -> (n, hidden_dim, n_h, n_w) + x = self.conv_proj(x) + # (n, hidden_dim, n_h, n_w) -> (n, hidden_dim, (n_h * n_w)) + x = x.reshape(n, self.hidden_dim, n_h * n_w) + + # (n, hidden_dim, (n_h * n_w)) -> (n, (n_h * n_w), hidden_dim) + # The self attention layer expects inputs in the format (N, S, E) + # where S is the source sequence length, N is the batch size, E is the + # embedding dimension + x = x.permute(0, 2, 1) + + return x + + def forward(self, x: torch.Tensor): + # Reshape and permute the input tensor + x = self._process_input(x) + n = x.shape[0] + + # Expand the class token to the full batch + batch_class_token = self.class_token.expand(n, -1, -1) + x = torch.cat([batch_class_token, x], dim=1) + + x = self.encoder(x) + + # Classifier "token" as used by standard language architectures + x = x[:, 0] + + x = self.heads(x) + + return x + + +def _vision_transformer( + patch_size: int, + num_layers: int, + num_heads: int, + hidden_dim: int, + mlp_dim: int, + weights: Optional[WeightsEnum], + progress: bool, + **kwargs: Any, +) -> VisionTransformer: + if weights is not None: + _ovewrite_named_param(kwargs, "num_classes", len(weights.meta["categories"])) + assert weights.meta["min_size"][0] == weights.meta["min_size"][1] + _ovewrite_named_param(kwargs, "image_size", weights.meta["min_size"][0]) + image_size = kwargs.pop("image_size", 224) + + model = VisionTransformer( + image_size=image_size, + patch_size=patch_size, + num_layers=num_layers, + num_heads=num_heads, + hidden_dim=hidden_dim, + mlp_dim=mlp_dim, + **kwargs, + ) + + if weights: + model.load_state_dict(weights.get_state_dict(progress=progress, check_hash=True)) + + return model + + +_COMMON_META: dict[str, Any] = { + "categories": _IMAGENET_CATEGORIES, +} + +_COMMON_SWAG_META = { + **_COMMON_META, + "recipe": "https://github.com/facebookresearch/SWAG", + "license": "https://github.com/facebookresearch/SWAG/blob/main/LICENSE", +} + + +class ViT_B_16_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vit_b_16-c867db91.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 86567656, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#vit_b_16", + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.072, + "acc@5": 95.318, + } + }, + "_ops": 17.564, + "_file_size": 330.285, + "_docs": """ + These weights were trained from scratch by using a modified version of `DeIT + `_'s training recipe. + """, + }, + ) + IMAGENET1K_SWAG_E2E_V1 = Weights( + url="https://download.pytorch.org/models/vit_b_16_swag-9ac1b537.pth", + transforms=partial( + ImageClassification, + crop_size=384, + resize_size=384, + interpolation=InterpolationMode.BICUBIC, + ), + meta={ + **_COMMON_SWAG_META, + "num_params": 86859496, + "min_size": (384, 384), + "_metrics": { + "ImageNet-1K": { + "acc@1": 85.304, + "acc@5": 97.650, + } + }, + "_ops": 55.484, + "_file_size": 331.398, + "_docs": """ + These weights are learnt via transfer learning by end-to-end fine-tuning the original + `SWAG `_ weights on ImageNet-1K data. + """, + }, + ) + IMAGENET1K_SWAG_LINEAR_V1 = Weights( + url="https://download.pytorch.org/models/vit_b_16_lc_swag-4e70ced5.pth", + transforms=partial( + ImageClassification, + crop_size=224, + resize_size=224, + interpolation=InterpolationMode.BICUBIC, + ), + meta={ + **_COMMON_SWAG_META, + "recipe": "https://github.com/pytorch/vision/pull/5793", + "num_params": 86567656, + "min_size": (224, 224), + "_metrics": { + "ImageNet-1K": { + "acc@1": 81.886, + "acc@5": 96.180, + } + }, + "_ops": 17.564, + "_file_size": 330.285, + "_docs": """ + These weights are composed of the original frozen `SWAG `_ trunk + weights and a linear classifier learnt on top of them trained on ImageNet-1K data. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ViT_B_32_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vit_b_32-d86f8d99.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 88224232, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#vit_b_32", + "_metrics": { + "ImageNet-1K": { + "acc@1": 75.912, + "acc@5": 92.466, + } + }, + "_ops": 4.409, + "_file_size": 336.604, + "_docs": """ + These weights were trained from scratch by using a modified version of `DeIT + `_'s training recipe. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ViT_L_16_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vit_l_16-852ce7e3.pth", + transforms=partial(ImageClassification, crop_size=224, resize_size=242), + meta={ + **_COMMON_META, + "num_params": 304326632, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#vit_l_16", + "_metrics": { + "ImageNet-1K": { + "acc@1": 79.662, + "acc@5": 94.638, + } + }, + "_ops": 61.555, + "_file_size": 1161.023, + "_docs": """ + These weights were trained from scratch by using a modified version of TorchVision's + `new training recipe + `_. + """, + }, + ) + IMAGENET1K_SWAG_E2E_V1 = Weights( + url="https://download.pytorch.org/models/vit_l_16_swag-4f3808c9.pth", + transforms=partial( + ImageClassification, + crop_size=512, + resize_size=512, + interpolation=InterpolationMode.BICUBIC, + ), + meta={ + **_COMMON_SWAG_META, + "num_params": 305174504, + "min_size": (512, 512), + "_metrics": { + "ImageNet-1K": { + "acc@1": 88.064, + "acc@5": 98.512, + } + }, + "_ops": 361.986, + "_file_size": 1164.258, + "_docs": """ + These weights are learnt via transfer learning by end-to-end fine-tuning the original + `SWAG `_ weights on ImageNet-1K data. + """, + }, + ) + IMAGENET1K_SWAG_LINEAR_V1 = Weights( + url="https://download.pytorch.org/models/vit_l_16_lc_swag-4d563306.pth", + transforms=partial( + ImageClassification, + crop_size=224, + resize_size=224, + interpolation=InterpolationMode.BICUBIC, + ), + meta={ + **_COMMON_SWAG_META, + "recipe": "https://github.com/pytorch/vision/pull/5793", + "num_params": 304326632, + "min_size": (224, 224), + "_metrics": { + "ImageNet-1K": { + "acc@1": 85.146, + "acc@5": 97.422, + } + }, + "_ops": 61.555, + "_file_size": 1161.023, + "_docs": """ + These weights are composed of the original frozen `SWAG `_ trunk + weights and a linear classifier learnt on top of them trained on ImageNet-1K data. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ViT_L_32_Weights(WeightsEnum): + IMAGENET1K_V1 = Weights( + url="https://download.pytorch.org/models/vit_l_32-c7638314.pth", + transforms=partial(ImageClassification, crop_size=224), + meta={ + **_COMMON_META, + "num_params": 306535400, + "min_size": (224, 224), + "recipe": "https://github.com/pytorch/vision/tree/main/references/classification#vit_l_32", + "_metrics": { + "ImageNet-1K": { + "acc@1": 76.972, + "acc@5": 93.07, + } + }, + "_ops": 15.378, + "_file_size": 1169.449, + "_docs": """ + These weights were trained from scratch by using a modified version of `DeIT + `_'s training recipe. + """, + }, + ) + DEFAULT = IMAGENET1K_V1 + + +class ViT_H_14_Weights(WeightsEnum): + IMAGENET1K_SWAG_E2E_V1 = Weights( + url="https://download.pytorch.org/models/vit_h_14_swag-80465313.pth", + transforms=partial( + ImageClassification, + crop_size=518, + resize_size=518, + interpolation=InterpolationMode.BICUBIC, + ), + meta={ + **_COMMON_SWAG_META, + "num_params": 633470440, + "min_size": (518, 518), + "_metrics": { + "ImageNet-1K": { + "acc@1": 88.552, + "acc@5": 98.694, + } + }, + "_ops": 1016.717, + "_file_size": 2416.643, + "_docs": """ + These weights are learnt via transfer learning by end-to-end fine-tuning the original + `SWAG `_ weights on ImageNet-1K data. + """, + }, + ) + IMAGENET1K_SWAG_LINEAR_V1 = Weights( + url="https://download.pytorch.org/models/vit_h_14_lc_swag-c1eb923e.pth", + transforms=partial( + ImageClassification, + crop_size=224, + resize_size=224, + interpolation=InterpolationMode.BICUBIC, + ), + meta={ + **_COMMON_SWAG_META, + "recipe": "https://github.com/pytorch/vision/pull/5793", + "num_params": 632045800, + "min_size": (224, 224), + "_metrics": { + "ImageNet-1K": { + "acc@1": 85.708, + "acc@5": 97.730, + } + }, + "_ops": 167.295, + "_file_size": 2411.209, + "_docs": """ + These weights are composed of the original frozen `SWAG `_ trunk + weights and a linear classifier learnt on top of them trained on ImageNet-1K data. + """, + }, + ) + DEFAULT = IMAGENET1K_SWAG_E2E_V1 + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ViT_B_16_Weights.IMAGENET1K_V1)) +def vit_b_16(*, weights: Optional[ViT_B_16_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer: + """ + Constructs a vit_b_16 architecture from + `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale `_. + + Args: + weights (:class:`~torchvision.models.ViT_B_16_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.ViT_B_16_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ViT_B_16_Weights + :members: + """ + weights = ViT_B_16_Weights.verify(weights) + + return _vision_transformer( + patch_size=16, + num_layers=12, + num_heads=12, + hidden_dim=768, + mlp_dim=3072, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ViT_B_32_Weights.IMAGENET1K_V1)) +def vit_b_32(*, weights: Optional[ViT_B_32_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer: + """ + Constructs a vit_b_32 architecture from + `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale `_. + + Args: + weights (:class:`~torchvision.models.ViT_B_32_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.ViT_B_32_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ViT_B_32_Weights + :members: + """ + weights = ViT_B_32_Weights.verify(weights) + + return _vision_transformer( + patch_size=32, + num_layers=12, + num_heads=12, + hidden_dim=768, + mlp_dim=3072, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ViT_L_16_Weights.IMAGENET1K_V1)) +def vit_l_16(*, weights: Optional[ViT_L_16_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer: + """ + Constructs a vit_l_16 architecture from + `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale `_. + + Args: + weights (:class:`~torchvision.models.ViT_L_16_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.ViT_L_16_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ViT_L_16_Weights + :members: + """ + weights = ViT_L_16_Weights.verify(weights) + + return _vision_transformer( + patch_size=16, + num_layers=24, + num_heads=16, + hidden_dim=1024, + mlp_dim=4096, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", ViT_L_32_Weights.IMAGENET1K_V1)) +def vit_l_32(*, weights: Optional[ViT_L_32_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer: + """ + Constructs a vit_l_32 architecture from + `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale `_. + + Args: + weights (:class:`~torchvision.models.ViT_L_32_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.ViT_L_32_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ViT_L_32_Weights + :members: + """ + weights = ViT_L_32_Weights.verify(weights) + + return _vision_transformer( + patch_size=32, + num_layers=24, + num_heads=16, + hidden_dim=1024, + mlp_dim=4096, + weights=weights, + progress=progress, + **kwargs, + ) + + +@register_model() +@handle_legacy_interface(weights=("pretrained", None)) +def vit_h_14(*, weights: Optional[ViT_H_14_Weights] = None, progress: bool = True, **kwargs: Any) -> VisionTransformer: + """ + Constructs a vit_h_14 architecture from + `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale `_. + + Args: + weights (:class:`~torchvision.models.ViT_H_14_Weights`, optional): The pretrained + weights to use. See :class:`~torchvision.models.ViT_H_14_Weights` + below for more details and possible values. By default, no pre-trained weights are used. + progress (bool, optional): If True, displays a progress bar of the download to stderr. Default is True. + **kwargs: parameters passed to the ``torchvision.models.vision_transformer.VisionTransformer`` + base class. Please refer to the `source code + `_ + for more details about this class. + + .. autoclass:: torchvision.models.ViT_H_14_Weights + :members: + """ + weights = ViT_H_14_Weights.verify(weights) + + return _vision_transformer( + patch_size=14, + num_layers=32, + num_heads=16, + hidden_dim=1280, + mlp_dim=5120, + weights=weights, + progress=progress, + **kwargs, + ) + + +def interpolate_embeddings( + image_size: int, + patch_size: int, + model_state: "OrderedDict[str, torch.Tensor]", + interpolation_mode: str = "bicubic", + reset_heads: bool = False, +) -> "OrderedDict[str, torch.Tensor]": + """This function helps interpolate positional embeddings during checkpoint loading, + especially when you want to apply a pre-trained model on images with different resolution. + + Args: + image_size (int): Image size of the new model. + patch_size (int): Patch size of the new model. + model_state (OrderedDict[str, torch.Tensor]): State dict of the pre-trained model. + interpolation_mode (str): The algorithm used for upsampling. Default: bicubic. + reset_heads (bool): If true, not copying the state of heads. Default: False. + + Returns: + OrderedDict[str, torch.Tensor]: A state dict which can be loaded into the new model. + """ + # Shape of pos_embedding is (1, seq_length, hidden_dim) + pos_embedding = model_state["encoder.pos_embedding"] + n, seq_length, hidden_dim = pos_embedding.shape + if n != 1: + raise ValueError(f"Unexpected position embedding shape: {pos_embedding.shape}") + + new_seq_length = (image_size // patch_size) ** 2 + 1 + + # Need to interpolate the weights for the position embedding. + # We do this by reshaping the positions embeddings to a 2d grid, performing + # an interpolation in the (h, w) space and then reshaping back to a 1d grid. + if new_seq_length != seq_length: + # The class token embedding shouldn't be interpolated, so we split it up. + seq_length -= 1 + new_seq_length -= 1 + pos_embedding_token = pos_embedding[:, :1, :] + pos_embedding_img = pos_embedding[:, 1:, :] + + # (1, seq_length, hidden_dim) -> (1, hidden_dim, seq_length) + pos_embedding_img = pos_embedding_img.permute(0, 2, 1) + seq_length_1d = int(math.sqrt(seq_length)) + if seq_length_1d * seq_length_1d != seq_length: + raise ValueError( + f"seq_length is not a perfect square! Instead got seq_length_1d * seq_length_1d = {seq_length_1d * seq_length_1d } and seq_length = {seq_length}" + ) + + # (1, hidden_dim, seq_length) -> (1, hidden_dim, seq_l_1d, seq_l_1d) + pos_embedding_img = pos_embedding_img.reshape(1, hidden_dim, seq_length_1d, seq_length_1d) + new_seq_length_1d = image_size // patch_size + + # Perform interpolation. + # (1, hidden_dim, seq_l_1d, seq_l_1d) -> (1, hidden_dim, new_seq_l_1d, new_seq_l_1d) + new_pos_embedding_img = nn.functional.interpolate( + pos_embedding_img, + size=new_seq_length_1d, + mode=interpolation_mode, + align_corners=True, + ) + + # (1, hidden_dim, new_seq_l_1d, new_seq_l_1d) -> (1, hidden_dim, new_seq_length) + new_pos_embedding_img = new_pos_embedding_img.reshape(1, hidden_dim, new_seq_length) + + # (1, hidden_dim, new_seq_length) -> (1, new_seq_length, hidden_dim) + new_pos_embedding_img = new_pos_embedding_img.permute(0, 2, 1) + new_pos_embedding = torch.cat([pos_embedding_token, new_pos_embedding_img], dim=1) + + model_state["encoder.pos_embedding"] = new_pos_embedding + + if reset_heads: + model_state_copy: "OrderedDict[str, torch.Tensor]" = OrderedDict() + for k, v in model_state.items(): + if not k.startswith("heads"): + model_state_copy[k] = v + model_state = model_state_copy + + return model_state diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..827505b842d4f1ad0e16dfe54ef28658364cc9ac --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/__init__.py @@ -0,0 +1,73 @@ +from ._register_onnx_ops import _register_custom_op +from .boxes import ( + batched_nms, + box_area, + box_convert, + box_iou, + clip_boxes_to_image, + complete_box_iou, + distance_box_iou, + generalized_box_iou, + masks_to_boxes, + nms, + remove_small_boxes, +) +from .ciou_loss import complete_box_iou_loss +from .deform_conv import deform_conv2d, DeformConv2d +from .diou_loss import distance_box_iou_loss +from .drop_block import drop_block2d, drop_block3d, DropBlock2d, DropBlock3d +from .feature_pyramid_network import FeaturePyramidNetwork +from .focal_loss import sigmoid_focal_loss +from .giou_loss import generalized_box_iou_loss +from .misc import Conv2dNormActivation, Conv3dNormActivation, FrozenBatchNorm2d, MLP, Permute, SqueezeExcitation +from .poolers import MultiScaleRoIAlign +from .ps_roi_align import ps_roi_align, PSRoIAlign +from .ps_roi_pool import ps_roi_pool, PSRoIPool +from .roi_align import roi_align, RoIAlign +from .roi_pool import roi_pool, RoIPool +from .stochastic_depth import stochastic_depth, StochasticDepth + +_register_custom_op() + + +__all__ = [ + "masks_to_boxes", + "deform_conv2d", + "DeformConv2d", + "nms", + "batched_nms", + "remove_small_boxes", + "clip_boxes_to_image", + "box_convert", + "box_area", + "box_iou", + "generalized_box_iou", + "distance_box_iou", + "complete_box_iou", + "roi_align", + "RoIAlign", + "roi_pool", + "RoIPool", + "ps_roi_align", + "PSRoIAlign", + "ps_roi_pool", + "PSRoIPool", + "MultiScaleRoIAlign", + "FeaturePyramidNetwork", + "sigmoid_focal_loss", + "stochastic_depth", + "StochasticDepth", + "FrozenBatchNorm2d", + "Conv2dNormActivation", + "Conv3dNormActivation", + "SqueezeExcitation", + "MLP", + "Permute", + "generalized_box_iou_loss", + "distance_box_iou_loss", + "complete_box_iou_loss", + "drop_block2d", + "DropBlock2d", + "drop_block3d", + "DropBlock3d", +] diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89dce2f2391de356decd08e6eb6f16f4f85ed2bf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/_box_convert.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/_box_convert.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e98d1051a55f6e9530c2ab8371ae7e3716e4553 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/_box_convert.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/_register_onnx_ops.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/_register_onnx_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3267cc493ac71812d6f7a275a93b7a2c25bf4b8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/_register_onnx_ops.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9a5cc05ca0148c2b7e4a652296fa9cfdb6c27de Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/boxes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/boxes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa1d8d22fef5e5dcd00ff17a86f3855179c1abc5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/boxes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/ciou_loss.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/ciou_loss.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d14fb65b84a5949e21e1822893cfa19a9a465baf Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/ciou_loss.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/deform_conv.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/deform_conv.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecdaf2b1acc52fa8d1f3ce114263f2fbf6e1563b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/deform_conv.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/diou_loss.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/diou_loss.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7de3eddc3c59a80f3150b59445bfce5355beaac3 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/diou_loss.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/drop_block.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/drop_block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d42a3fb691ec2faa1a2eacb67af8dad5ed61bea Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/drop_block.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/feature_pyramid_network.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/feature_pyramid_network.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc7671cc86d8816dbdcca2341acfd05c763fde7d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/feature_pyramid_network.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/focal_loss.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/focal_loss.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c2f59fb77ae9e5b7bbcbd60cc5911f6e02c1358 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/focal_loss.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/giou_loss.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/giou_loss.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6277d4a93e4bd684751978358ae4384680db6980 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/giou_loss.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/misc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/misc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7b7dc3e0e2806aa94aaac1672f795db00edb41a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/misc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/poolers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/poolers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24165c33f698187f85004fd8805964a729dc4512 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/poolers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/ps_roi_align.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/ps_roi_align.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a06dfa872a20b6c31305174c631f22d83c6d078c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/ps_roi_align.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/ps_roi_pool.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/ps_roi_pool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3fc355a9f56e72146ba0f5fa6f009cad053542b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/ps_roi_pool.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/roi_align.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/roi_align.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05dc87bb0a5461fa3b3612f2efbf1c4539aed0c9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/roi_align.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/roi_pool.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/roi_pool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cb7fdda21791bad700677c3897da5f3f7368075 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/roi_pool.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/stochastic_depth.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/stochastic_depth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1570e6f962d7c7311d8df487f38f7602c8ec3719 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/ops/__pycache__/stochastic_depth.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/_box_convert.py b/.venv/lib/python3.12/site-packages/torchvision/ops/_box_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..81406248020b5e284b8d4a6ae8bd6528bb12c58a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/_box_convert.py @@ -0,0 +1,207 @@ +import torch +from torch import Tensor + + +def _box_cxcywh_to_xyxy(boxes: Tensor) -> Tensor: + """ + Converts bounding boxes from (cx, cy, w, h) format to (x1, y1, x2, y2) format. + (cx, cy) refers to center of bounding box + (w, h) are width and height of bounding box + Args: + boxes (Tensor[N, 4]): boxes in (cx, cy, w, h) format which will be converted. + + Returns: + boxes (Tensor(N, 4)): boxes in (x1, y1, x2, y2) format. + """ + # We need to change all 4 of them so some temporary variable is needed. + cx, cy, w, h = boxes.unbind(-1) + x1 = cx - 0.5 * w + y1 = cy - 0.5 * h + x2 = cx + 0.5 * w + y2 = cy + 0.5 * h + + boxes = torch.stack((x1, y1, x2, y2), dim=-1) + + return boxes + + +def _box_xyxy_to_cxcywh(boxes: Tensor) -> Tensor: + """ + Converts bounding boxes from (x1, y1, x2, y2) format to (cx, cy, w, h) format. + (x1, y1) refer to top left of bounding box + (x2, y2) refer to bottom right of bounding box + Args: + boxes (Tensor[N, 4]): boxes in (x1, y1, x2, y2) format which will be converted. + + Returns: + boxes (Tensor(N, 4)): boxes in (cx, cy, w, h) format. + """ + x1, y1, x2, y2 = boxes.unbind(-1) + cx = (x1 + x2) / 2 + cy = (y1 + y2) / 2 + w = x2 - x1 + h = y2 - y1 + + boxes = torch.stack((cx, cy, w, h), dim=-1) + + return boxes + + +def _box_xywh_to_xyxy(boxes: Tensor) -> Tensor: + """ + Converts bounding boxes from (x, y, w, h) format to (x1, y1, x2, y2) format. + (x, y) refers to top left of bounding box. + (w, h) refers to width and height of box. + Args: + boxes (Tensor[N, 4]): boxes in (x, y, w, h) which will be converted. + + Returns: + boxes (Tensor[N, 4]): boxes in (x1, y1, x2, y2) format. + """ + x, y, w, h = boxes.unbind(-1) + boxes = torch.stack([x, y, x + w, y + h], dim=-1) + return boxes + + +def _box_xyxy_to_xywh(boxes: Tensor) -> Tensor: + """ + Converts bounding boxes from (x1, y1, x2, y2) format to (x, y, w, h) format. + (x1, y1) refer to top left of bounding box + (x2, y2) refer to bottom right of bounding box + Args: + boxes (Tensor[N, 4]): boxes in (x1, y1, x2, y2) which will be converted. + + Returns: + boxes (Tensor[N, 4]): boxes in (x, y, w, h) format. + """ + x1, y1, x2, y2 = boxes.unbind(-1) + w = x2 - x1 # x2 - x1 + h = y2 - y1 # y2 - y1 + boxes = torch.stack((x1, y1, w, h), dim=-1) + return boxes + + +def _box_cxcywhr_to_xywhr(boxes: Tensor) -> Tensor: + """ + Converts rotated bounding boxes from (cx, cy, w, h, r) format to (x1, y1, w, h, r) format. + (cx, cy) refers to center of bounding box + (w, h) refers to width and height of rotated bounding box + (x1, y1) refers to top left of rotated bounding box + r is rotation angle w.r.t to the box center by :math:`|r|` degrees counter clock wise in the image plan + Args: + boxes (Tensor[N, 5]): boxes in (cx, cy, w, h, r) format which will be converted. + + Returns: + boxes (Tensor(N, 5)): rotated boxes in (x1, y1, w, h, r) format. + """ + dtype = boxes.dtype + need_cast = not boxes.is_floating_point() + cx, cy, w, h, r = boxes.unbind(-1) + r_rad = r * torch.pi / 180.0 + cos, sin = torch.cos(r_rad), torch.sin(r_rad) + + x1 = cx - w / 2 * cos - h / 2 * sin + y1 = cy - h / 2 * cos + w / 2 * sin + boxes = torch.stack((x1, y1, w, h, r), dim=-1) + + if need_cast: + boxes.round_() + boxes = boxes.to(dtype) + return boxes + + +def _box_xywhr_to_cxcywhr(boxes: Tensor) -> Tensor: + """ + Converts rotated bounding boxes from (x1, y1, w, h, r) format to (cx, cy, w, h, r) format. + (x1, y1) refers to top left of rotated bounding box + (w, h) refers to width and height of rotated bounding box + r is rotation angle w.r.t to the box center by :math:`|r|` degrees counter clock wise in the image plan + Args: + boxes (Tensor[N, 5]): rotated boxes in (x1, y1, w, h, r) format which will be converted. + + Returns: + boxes (Tensor[N, 5]): rotated boxes in (cx, cy, w, h, r) format. + """ + dtype = boxes.dtype + need_cast = not boxes.is_floating_point() + x1, y1, w, h, r = boxes.unbind(-1) + r_rad = r * torch.pi / 180.0 + cos, sin = torch.cos(r_rad), torch.sin(r_rad) + + cx = x1 + w / 2 * cos + h / 2 * sin + cy = y1 - w / 2 * sin + h / 2 * cos + + boxes = torch.stack([cx, cy, w, h, r], dim=-1) + if need_cast: + boxes.round_() + boxes = boxes.to(dtype) + return boxes + + +def _box_xywhr_to_xyxyxyxy(boxes: Tensor) -> Tensor: + """ + Converts rotated bounding boxes from (x1, y1, w, h, r) format to (x1, y1, x2, y2, x3, y3, x4, y4) format. + (x1, y1) refer to top left of bounding box + (w, h) are width and height of the rotated bounding box + r is rotation angle w.r.t to the box center by :math:`|r|` degrees counter clock wise in the image plan + + (x1, y1) refer to top left of rotated bounding box + (x2, y2) refer to top right of rotated bounding box + (x3, y3) refer to bottom right of rotated bounding box + (x4, y4) refer to bottom left ofrotated bounding box + Args: + boxes (Tensor[N, 5]): rotated boxes in (cx, cy, w, h, r) format which will be converted. + + Returns: + boxes (Tensor(N, 8)): rotated boxes in (x1, y1, x2, y2, x3, y3, x4, y4) format. + """ + dtype = boxes.dtype + need_cast = not boxes.is_floating_point() + x1, y1, w, h, r = boxes.unbind(-1) + r_rad = r * torch.pi / 180.0 + cos, sin = torch.cos(r_rad), torch.sin(r_rad) + + x2 = x1 + w * cos + y2 = y1 - w * sin + x3 = x2 + h * sin + y3 = y2 + h * cos + x4 = x1 + h * sin + y4 = y1 + h * cos + + boxes = torch.stack((x1, y1, x2, y2, x3, y3, x4, y4), dim=-1) + if need_cast: + boxes.round_() + boxes = boxes.to(dtype) + return boxes + + +def _box_xyxyxyxy_to_xywhr(boxes: Tensor) -> Tensor: + """ + Converts rotated bounding boxes from (x1, y1, x2, y2, x3, y3, x4, y4) format to (x1, y1, w, h, r) format. + (x1, y1) refer to top left of the rotated bounding box + (x2, y2) refer to bottom left of the rotated bounding box + (x3, y3) refer to bottom right of the rotated bounding box + (x4, y4) refer to top right of the rotated bounding box + (w, h) refers to width and height of rotated bounding box + r is rotation angle w.r.t to the box center by :math:`|r|` degrees counter clock wise in the image plan + + Args: + boxes (Tensor(N, 8)): rotated boxes in (x1, y1, x2, y2, x3, y3, x4, y4) format. + + Returns: + boxes (Tensor[N, 5]): rotated boxes in (x1, y1, w, h, r) format. + """ + dtype = boxes.dtype + need_cast = not boxes.is_floating_point() + x1, y1, x2, y2, x3, y3, x4, y4 = boxes.unbind(-1) + r_rad = torch.atan2(y1 - y2, x2 - x1) + r = r_rad * 180 / torch.pi + + w = ((x2 - x1) ** 2 + (y1 - y2) ** 2).sqrt() + h = ((x3 - x2) ** 2 + (y3 - y2) ** 2).sqrt() + + boxes = torch.stack((x1, y1, w, h, r), dim=-1) + if need_cast: + boxes.round_() + boxes = boxes.to(dtype) + return boxes diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/_register_onnx_ops.py b/.venv/lib/python3.12/site-packages/torchvision/ops/_register_onnx_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd263a5d8ef497becc4aa39252a93c913b84880 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/_register_onnx_ops.py @@ -0,0 +1,107 @@ +import sys +import warnings + +import torch +from torch.onnx import symbolic_opset11 as opset11 +from torch.onnx.symbolic_helper import parse_args + +_ONNX_OPSET_VERSION_11 = 11 +_ONNX_OPSET_VERSION_16 = 16 +BASE_ONNX_OPSET_VERSION = _ONNX_OPSET_VERSION_11 + + +@parse_args("v", "v", "f") +def symbolic_multi_label_nms(g, boxes, scores, iou_threshold): + boxes = opset11.unsqueeze(g, boxes, 0) + scores = opset11.unsqueeze(g, opset11.unsqueeze(g, scores, 0), 0) + max_output_per_class = g.op("Constant", value_t=torch.tensor([sys.maxsize], dtype=torch.long)) + iou_threshold = g.op("Constant", value_t=torch.tensor([iou_threshold], dtype=torch.float)) + + # Cast boxes and scores to float32 in case they are float64 inputs + nms_out = g.op( + "NonMaxSuppression", + g.op("Cast", boxes, to_i=torch.onnx.TensorProtoDataType.FLOAT), + g.op("Cast", scores, to_i=torch.onnx.TensorProtoDataType.FLOAT), + max_output_per_class, + iou_threshold, + ) + return opset11.squeeze( + g, opset11.select(g, nms_out, 1, g.op("Constant", value_t=torch.tensor([2], dtype=torch.long))), 1 + ) + + +def _process_batch_indices_for_roi_align(g, rois): + indices = opset11.squeeze( + g, opset11.select(g, rois, 1, g.op("Constant", value_t=torch.tensor([0], dtype=torch.long))), 1 + ) + return g.op("Cast", indices, to_i=torch.onnx.TensorProtoDataType.INT64) + + +def _process_rois_for_roi_align(g, rois): + return opset11.select(g, rois, 1, g.op("Constant", value_t=torch.tensor([1, 2, 3, 4], dtype=torch.long))) + + +def _process_sampling_ratio_for_roi_align(g, sampling_ratio: int): + if sampling_ratio < 0: + warnings.warn( + "ONNX export for RoIAlign with a non-zero sampling_ratio is not supported. " + "The model will be exported with a sampling_ratio of 0." + ) + sampling_ratio = 0 + return sampling_ratio + + +@parse_args("v", "v", "f", "i", "i", "i", "i") +def roi_align_opset11(g, input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio, aligned): + batch_indices = _process_batch_indices_for_roi_align(g, rois) + rois = _process_rois_for_roi_align(g, rois) + if aligned: + warnings.warn( + "ROIAlign with aligned=True is only supported in opset >= 16. " + "Please export with opset 16 or higher, or use aligned=False." + ) + sampling_ratio = _process_sampling_ratio_for_roi_align(g, sampling_ratio) + return g.op( + "RoiAlign", + input, + rois, + batch_indices, + spatial_scale_f=spatial_scale, + output_height_i=pooled_height, + output_width_i=pooled_width, + sampling_ratio_i=sampling_ratio, + ) + + +@parse_args("v", "v", "f", "i", "i", "i", "i") +def roi_align_opset16(g, input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio, aligned): + batch_indices = _process_batch_indices_for_roi_align(g, rois) + rois = _process_rois_for_roi_align(g, rois) + coordinate_transformation_mode = "half_pixel" if aligned else "output_half_pixel" + sampling_ratio = _process_sampling_ratio_for_roi_align(g, sampling_ratio) + return g.op( + "RoiAlign", + input, + rois, + batch_indices, + coordinate_transformation_mode_s=coordinate_transformation_mode, + spatial_scale_f=spatial_scale, + output_height_i=pooled_height, + output_width_i=pooled_width, + sampling_ratio_i=sampling_ratio, + ) + + +@parse_args("v", "v", "f", "i", "i") +def roi_pool(g, input, rois, spatial_scale, pooled_height, pooled_width): + roi_pool = g.op( + "MaxRoiPool", input, rois, pooled_shape_i=(pooled_height, pooled_width), spatial_scale_f=spatial_scale + ) + return roi_pool, None + + +def _register_custom_op(): + torch.onnx.register_custom_op_symbolic("torchvision::nms", symbolic_multi_label_nms, _ONNX_OPSET_VERSION_11) + torch.onnx.register_custom_op_symbolic("torchvision::roi_align", roi_align_opset11, _ONNX_OPSET_VERSION_11) + torch.onnx.register_custom_op_symbolic("torchvision::roi_align", roi_align_opset16, _ONNX_OPSET_VERSION_16) + torch.onnx.register_custom_op_symbolic("torchvision::roi_pool", roi_pool, _ONNX_OPSET_VERSION_11) diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/_utils.py b/.venv/lib/python3.12/site-packages/torchvision/ops/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..40bae605d028d3f522531711a1e28298b63ffbfc --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/_utils.py @@ -0,0 +1,106 @@ +from typing import Optional, Union + +import torch +from torch import nn, Tensor + + +def _cat(tensors: list[Tensor], dim: int = 0) -> Tensor: + """ + Efficient version of torch.cat that avoids a copy if there is only a single element in a list + """ + # TODO add back the assert + # assert isinstance(tensors, (list, tuple)) + if len(tensors) == 1: + return tensors[0] + return torch.cat(tensors, dim) + + +def convert_boxes_to_roi_format(boxes: list[Tensor]) -> Tensor: + concat_boxes = _cat([b for b in boxes], dim=0) + temp = [] + for i, b in enumerate(boxes): + temp.append(torch.full_like(b[:, :1], i)) + ids = _cat(temp, dim=0) + rois = torch.cat([ids, concat_boxes], dim=1) + return rois + + +def check_roi_boxes_shape(boxes: Union[Tensor, list[Tensor]]): + if isinstance(boxes, (list, tuple)): + for _tensor in boxes: + torch._assert( + _tensor.size(1) == 4, "The shape of the tensor in the boxes list is not correct as List[Tensor[L, 4]]" + ) + elif isinstance(boxes, torch.Tensor): + torch._assert(boxes.size(1) == 5, "The boxes tensor shape is not correct as Tensor[K, 5]") + else: + torch._assert(False, "boxes is expected to be a Tensor[L, 5] or a List[Tensor[K, 4]]") + return + + +def split_normalization_params( + model: nn.Module, norm_classes: Optional[list[type]] = None +) -> tuple[list[Tensor], list[Tensor]]: + # Adapted from https://github.com/facebookresearch/ClassyVision/blob/659d7f78/classy_vision/generic/util.py#L501 + if not norm_classes: + norm_classes = [ + nn.modules.batchnorm._BatchNorm, + nn.LayerNorm, + nn.GroupNorm, + nn.modules.instancenorm._InstanceNorm, + nn.LocalResponseNorm, + ] + + for t in norm_classes: + if not issubclass(t, nn.Module): + raise ValueError(f"Class {t} is not a subclass of nn.Module.") + + classes = tuple(norm_classes) + + norm_params = [] + other_params = [] + for module in model.modules(): + if next(module.children(), None): + other_params.extend(p for p in module.parameters(recurse=False) if p.requires_grad) + elif isinstance(module, classes): + norm_params.extend(p for p in module.parameters() if p.requires_grad) + else: + other_params.extend(p for p in module.parameters() if p.requires_grad) + return norm_params, other_params + + +def _upcast(t: Tensor) -> Tensor: + # Protects from numerical overflows in multiplications by upcasting to the equivalent higher type + if t.is_floating_point(): + return t if t.dtype in (torch.float32, torch.float64) else t.float() + else: + return t if t.dtype in (torch.int32, torch.int64) else t.int() + + +def _upcast_non_float(t: Tensor) -> Tensor: + # Protects from numerical overflows in multiplications by upcasting to the equivalent higher type + if t.dtype not in (torch.float32, torch.float64): + return t.float() + return t + + +def _loss_inter_union( + boxes1: torch.Tensor, + boxes2: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + + x1, y1, x2, y2 = boxes1.unbind(dim=-1) + x1g, y1g, x2g, y2g = boxes2.unbind(dim=-1) + + # Intersection keypoints + xkis1 = torch.max(x1, x1g) + ykis1 = torch.max(y1, y1g) + xkis2 = torch.min(x2, x2g) + ykis2 = torch.min(y2, y2g) + + intsctk = torch.zeros_like(x1) + mask = (ykis2 > ykis1) & (xkis2 > xkis1) + intsctk[mask] = (xkis2[mask] - xkis1[mask]) * (ykis2[mask] - ykis1[mask]) + unionk = (x2 - x1) * (y2 - y1) + (x2g - x1g) * (y2g - y1g) - intsctk + + return intsctk, unionk diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/boxes.py b/.venv/lib/python3.12/site-packages/torchvision/ops/boxes.py new file mode 100644 index 0000000000000000000000000000000000000000..73fbebde9d7599dd5c384eadb94866f617c99d3a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/boxes.py @@ -0,0 +1,568 @@ +import torch +import torchvision +from torch import Tensor +from torchvision.extension import _assert_has_ops + +from ..utils import _log_api_usage_once +from ._box_convert import ( + _box_cxcywh_to_xyxy, + _box_cxcywhr_to_xywhr, + _box_xywh_to_xyxy, + _box_xywhr_to_cxcywhr, + _box_xywhr_to_xyxyxyxy, + _box_xyxy_to_cxcywh, + _box_xyxy_to_xywh, + _box_xyxyxyxy_to_xywhr, +) +from ._utils import _upcast + + +def nms(boxes: Tensor, scores: Tensor, iou_threshold: float) -> Tensor: + """ + Performs non-maximum suppression (NMS) on the boxes according + to their intersection-over-union (IoU). + + NMS iteratively removes lower scoring boxes which have an + IoU greater than ``iou_threshold`` with another (higher scoring) + box. + + If multiple boxes have the exact same score and satisfy the IoU + criterion with respect to a reference box, the selected box is + not guaranteed to be the same between CPU and GPU. This is similar + to the behavior of argsort in PyTorch when repeated values are present. + + Args: + boxes (Tensor[N, 4])): boxes to perform NMS on. They + are expected to be in ``(x1, y1, x2, y2)`` format with ``0 <= x1 < x2`` and + ``0 <= y1 < y2``. + scores (Tensor[N]): scores for each one of the boxes + iou_threshold (float): discards all overlapping boxes with IoU > iou_threshold + + Returns: + Tensor: int64 tensor with the indices of the elements that have been kept + by NMS, sorted in decreasing order of scores + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(nms) + _assert_has_ops() + if not torch.jit.is_scripting() and boxes.is_quantized: + return torch.ops.torchvision.qnms( + boxes.int_repr(), + scores.int_repr(), + iou_threshold, + ) + return torch.ops.torchvision.nms(boxes, scores, iou_threshold) + + +def batched_nms( + boxes: Tensor, + scores: Tensor, + idxs: Tensor, + iou_threshold: float, +) -> Tensor: + """ + Performs non-maximum suppression in a batched fashion. + + Each index value correspond to a category, and NMS + will not be applied between elements of different categories. + + Args: + boxes (Tensor[N, 4]): boxes where NMS will be performed. They + are expected to be in ``(x1, y1, x2, y2)`` format with ``0 <= x1 < x2`` and + ``0 <= y1 < y2``. + scores (Tensor[N]): scores for each one of the boxes + idxs (Tensor[N]): indices of the categories for each one of the boxes. + iou_threshold (float): discards all overlapping boxes with IoU > iou_threshold + + Returns: + Tensor: int64 tensor with the indices of the elements that have been kept by NMS, sorted + in decreasing order of scores + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(batched_nms) + # Benchmarks that drove the following thresholds are at + # https://github.com/pytorch/vision/issues/1311#issuecomment-781329339 + # and https://github.com/pytorch/vision/pull/8925 + if boxes.numel() > (4000 if boxes.device.type == "cpu" else 100_000) and not torchvision._is_tracing(): + return _batched_nms_vanilla(boxes, scores, idxs, iou_threshold) + else: + return _batched_nms_coordinate_trick(boxes, scores, idxs, iou_threshold) + + +@torch.jit._script_if_tracing +def _batched_nms_coordinate_trick( + boxes: Tensor, + scores: Tensor, + idxs: Tensor, + iou_threshold: float, +) -> Tensor: + # strategy: in order to perform NMS independently per class, + # we add an offset to all the boxes. The offset is dependent + # only on the class idx, and is large enough so that boxes + # from different classes do not overlap + if boxes.numel() == 0: + return torch.empty((0,), dtype=torch.int64, device=boxes.device) + max_coordinate = boxes.max() + offsets = idxs.to(boxes) * (max_coordinate + torch.tensor(1).to(boxes)) + boxes_for_nms = boxes + offsets[:, None] + keep = nms(boxes_for_nms, scores, iou_threshold) + return keep + + +@torch.jit._script_if_tracing +def _batched_nms_vanilla( + boxes: Tensor, + scores: Tensor, + idxs: Tensor, + iou_threshold: float, +) -> Tensor: + # Based on Detectron2 implementation, just manually call nms() on each class independently + keep_mask = torch.zeros_like(scores, dtype=torch.bool) + for class_id in torch.unique(idxs): + curr_indices = torch.where(idxs == class_id)[0] + curr_keep_indices = nms(boxes[curr_indices], scores[curr_indices], iou_threshold) + keep_mask[curr_indices[curr_keep_indices]] = True + keep_indices = torch.where(keep_mask)[0] + return keep_indices[scores[keep_indices].sort(descending=True)[1]] + + +def remove_small_boxes(boxes: Tensor, min_size: float) -> Tensor: + """ + Remove every box from ``boxes`` which contains at least one side length + that is smaller than ``min_size``. + + .. note:: + For sanitizing a :class:`~torchvision.tv_tensors.BoundingBoxes` object, consider using + the transform :func:`~torchvision.transforms.v2.SanitizeBoundingBoxes` instead. + + Args: + boxes (Tensor[..., 4]): boxes in ``(x1, y1, x2, y2)`` format + with ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + min_size (float): minimum size + + Returns: + Tensor[K]: indices of the boxes that have both sides + larger than ``min_size`` + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(remove_small_boxes) + ws, hs = boxes[..., 2] - boxes[..., 0], boxes[..., 3] - boxes[..., 1] + keep = (ws >= min_size) & (hs >= min_size) + keep = torch.where(keep)[0] + return keep + + +def clip_boxes_to_image(boxes: Tensor, size: tuple[int, int]) -> Tensor: + """ + Clip boxes so that they lie inside an image of size ``size``. + + .. note:: + For clipping a :class:`~torchvision.tv_tensors.BoundingBoxes` object, consider using + the transform :func:`~torchvision.transforms.v2.ClampBoundingBoxes` instead. + + Args: + boxes (Tensor[..., 4]): boxes in ``(x1, y1, x2, y2)`` format + with ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + size (Tuple[height, width]): size of the image + + Returns: + Tensor[..., 4]: clipped boxes + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(clip_boxes_to_image) + dim = boxes.dim() + boxes_x = boxes[..., 0::2] + boxes_y = boxes[..., 1::2] + height, width = size + + if torchvision._is_tracing(): + boxes_x = torch.max(boxes_x, torch.tensor(0, dtype=boxes.dtype, device=boxes.device)) + boxes_x = torch.min(boxes_x, torch.tensor(width, dtype=boxes.dtype, device=boxes.device)) + boxes_y = torch.max(boxes_y, torch.tensor(0, dtype=boxes.dtype, device=boxes.device)) + boxes_y = torch.min(boxes_y, torch.tensor(height, dtype=boxes.dtype, device=boxes.device)) + else: + boxes_x = boxes_x.clamp(min=0, max=width) + boxes_y = boxes_y.clamp(min=0, max=height) + + clipped_boxes = torch.stack((boxes_x, boxes_y), dim=dim) + return clipped_boxes.reshape(boxes.shape) + + +def box_convert(boxes: Tensor, in_fmt: str, out_fmt: str) -> Tensor: + """ + Converts :class:`torch.Tensor` boxes from a given ``in_fmt`` to ``out_fmt``. + + .. note:: + For converting a :class:`torch.Tensor` or a :class:`~torchvision.tv_tensors.BoundingBoxes` object + between different formats, + consider using :func:`~torchvision.transforms.v2.functional.convert_bounding_box_format` instead. + Or see the corresponding transform :func:`~torchvision.transforms.v2.ConvertBoundingBoxFormat`. + + Supported ``in_fmt`` and ``out_fmt`` strings are: + + ``'xyxy'``: boxes are represented via corners, x1, y1 being top left and x2, y2 being bottom right. + This is the format that torchvision utilities expect. + + ``'xywh'``: boxes are represented via corner, width and height, x1, y2 being top left, w, h being width and height. + + ``'cxcywh'``: boxes are represented via centre, width and height, cx, cy being center of box, w, h + being width and height. + + ``'xywhr'``: boxes are represented via corner, width and height, x1, y2 being top left, w, h being width and height. + r is rotation angle w.r.t to the box center by :math:`|r|` degrees counter clock wise in the image plan + + ``'cxcywhr'``: boxes are represented via centre, width and height, cx, cy being center of box, w, h + being width and height. + r is rotation angle w.r.t to the box center by :math:`|r|` degrees counter clock wise in the image plan + + ``'xyxyxyxy'``: boxes are represented via corners, x1, y1 being top left, x2, y2 top right, + x3, y3 bottom right, and x4, y4 bottom left. + + Args: + boxes (Tensor[..., K]): boxes which will be converted. K is the number of coordinates (4 for unrotated bounding boxes, 5 or 8 for rotated bounding boxes). Supports any number of leading batch dimensions. + in_fmt (str): Input format of given boxes. Supported formats are ['xyxy', 'xywh', 'cxcywh', 'xywhr', 'cxcywhr', 'xyxyxyxy']. + out_fmt (str): Output format of given boxes. Supported formats are ['xyxy', 'xywh', 'cxcywh', 'xywhr', 'cxcywhr', 'xyxyxyxy'] + + Returns: + Tensor[..., K]: Boxes into converted format. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(box_convert) + allowed_fmts = ( + "xyxy", + "xywh", + "cxcywh", + "xywhr", + "cxcywhr", + "xyxyxyxy", + ) + if in_fmt not in allowed_fmts or out_fmt not in allowed_fmts: + raise ValueError(f"Unsupported Bounding Box Conversions for given in_fmt {in_fmt} and out_fmt {out_fmt}") + + if in_fmt == out_fmt: + return boxes.clone() + e = (in_fmt, out_fmt) + if e == ("xywh", "xyxy"): + boxes = _box_xywh_to_xyxy(boxes) + elif e == ("cxcywh", "xyxy"): + boxes = _box_cxcywh_to_xyxy(boxes) + elif e == ("xyxy", "xywh"): + boxes = _box_xyxy_to_xywh(boxes) + elif e == ("xyxy", "cxcywh"): + boxes = _box_xyxy_to_cxcywh(boxes) + elif e == ("xywh", "cxcywh"): + boxes = _box_xywh_to_xyxy(boxes) + boxes = _box_xyxy_to_cxcywh(boxes) + elif e == ("cxcywh", "xywh"): + boxes = _box_cxcywh_to_xyxy(boxes) + boxes = _box_xyxy_to_xywh(boxes) + elif e == ("cxcywhr", "xywhr"): + boxes = _box_cxcywhr_to_xywhr(boxes) + elif e == ("xywhr", "cxcywhr"): + boxes = _box_xywhr_to_cxcywhr(boxes) + elif e == ("cxcywhr", "xyxyxyxy"): + boxes = _box_cxcywhr_to_xywhr(boxes).to(boxes.dtype) + boxes = _box_xywhr_to_xyxyxyxy(boxes) + elif e == ("xyxyxyxy", "cxcywhr"): + boxes = _box_xyxyxyxy_to_xywhr(boxes).to(boxes.dtype) + boxes = _box_xywhr_to_cxcywhr(boxes) + elif e == ("xywhr", "xyxyxyxy"): + boxes = _box_xywhr_to_xyxyxyxy(boxes) + elif e == ("xyxyxyxy", "xywhr"): + boxes = _box_xyxyxyxy_to_xywhr(boxes) + else: + raise NotImplementedError(f"Unsupported Bounding Box Conversions for given in_fmt {e[0]} and out_fmt {e[1]}") + + return boxes + + +def box_area(boxes: Tensor, fmt: str = "xyxy") -> Tensor: + """ + Computes the area of a set of bounding boxes from a given format. + + Args: + boxes (Tensor[..., 4]): boxes for which the area will be computed. + fmt (str): Format of the input boxes. + Default is "xyxy" to preserve backward compatibility. + Supported formats are "xyxy", "xywh", and "cxcywh". + + Returns: + Tensor[N]: Tensor containing the area for each box. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(box_area) + allowed_fmts = ( + "xyxy", + "xywh", + "cxcywh", + ) + if fmt not in allowed_fmts: + raise ValueError(f"Unsupported Bounding Box area for given format {fmt}") + boxes = _upcast(boxes) + if fmt == "xyxy": + area = (boxes[..., 2] - boxes[..., 0]) * (boxes[..., 3] - boxes[..., 1]) + else: + # For formats with width and height, area = width * height + # Supported: cxcywh, xywh + area = boxes[..., 2] * boxes[..., 3] + + return area + + +# implementation from https://github.com/kuangliu/torchcv/blob/master/torchcv/utils/box.py +# with slight modifications +def _box_inter_union(boxes1: Tensor, boxes2: Tensor, fmt: str = "xyxy") -> tuple[Tensor, Tensor]: + area1 = box_area(boxes1, fmt=fmt) + area2 = box_area(boxes2, fmt=fmt) + + allowed_fmts = ( + "xyxy", + "xywh", + "cxcywh", + ) + if fmt not in allowed_fmts: + raise ValueError(f"Unsupported Box IoU Calculation for given fmt {fmt}.") + + if fmt == "xyxy": + lt = torch.max(boxes1[..., None, :2], boxes2[..., None, :, :2]) # [...,N,M,2] + rb = torch.min(boxes1[..., None, 2:], boxes2[..., None, :, 2:]) # [...,N,M,2] + elif fmt == "xywh": + lt = torch.max(boxes1[..., None, :2], boxes2[..., None, :, :2]) # [...,N,M,2] + rb = torch.min( + boxes1[..., None, :2] + boxes1[..., None, 2:], boxes2[..., None, :, :2] + boxes2[..., None, :, 2:] + ) # [...,N,M,2] + else: # fmt == "cxcywh": + lt = torch.max( + boxes1[..., None, :2] - boxes1[..., None, 2:] / 2, boxes2[..., None, :, :2] - boxes2[..., None, :, 2:] / 2 + ) # [N,M,2] + rb = torch.min( + boxes1[..., None, :2] + boxes1[..., None, 2:] / 2, boxes2[..., None, :, :2] + boxes2[..., None, :, 2:] / 2 + ) # [N,M,2] + + wh = _upcast(rb - lt).clamp(min=0) # [N,M,2] + inter = wh[..., 0] * wh[..., 1] # [N,M] + + union = area1[..., None] + area2[..., None, :] - inter + + return inter, union + + +def box_iou(boxes1: Tensor, boxes2: Tensor, fmt: str = "xyxy") -> Tensor: + """ + Return intersection-over-union (Jaccard index) between two sets of boxes from a given format. + + Args: + boxes1 (Tensor[..., N, K]): first set of boxes + boxes2 (Tensor[..., M, K]): second set of boxes + fmt (str): Format of the input boxes. + Default is "xyxy" to preserve backward compatibility. + + Supported axis-aligned formats (K=4): + + - ``'xyxy'``: boxes are represented via (x1, y1, x2, y2) corner coordinates. + - ``'xywh'``: boxes are represented via (x1, y1, width, height). + - ``'cxcywh'``: boxes are represented via (cx, cy, width, height) center coordinates. + + Supported rotated formats: + + - ``'cxcywhr'`` (K=5): boxes are represented via center, width, height, and rotation angle. + (cx, cy) is the center, (w, h) is width and height, r is rotation angle in degrees + (counter-clockwise positive). + - ``'xywhr'`` (K=5): boxes are represented via corner, width, height, and rotation angle. + (x1, y1) is the top-left corner, (w, h) is width and height, r is rotation angle in degrees. + - ``'xyxyxyxy'`` (K=8): boxes are represented via 4 corner coordinates. + (x1, y1) is top-left, (x2, y2) is top-right, (x3, y3) is bottom-right, (x4, y4) is bottom-left. + + Returns: + Tensor[..., N, M]: the NxM matrix containing the pairwise IoU values for every element + in boxes1 and boxes2 + + + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(box_iou) + + axis_aligned_fmts = ("xyxy", "xywh", "cxcywh") + rotated_fmts = ("cxcywhr", "xywhr", "xyxyxyxy") + + if fmt in axis_aligned_fmts: + inter, union = _box_inter_union(boxes1, boxes2, fmt=fmt) + iou = inter / union + return iou + elif fmt in rotated_fmts: + # Convert to cxcywhr format for internal computation + if fmt != "cxcywhr": + boxes1 = box_convert(boxes1, in_fmt=fmt, out_fmt="cxcywhr") + boxes2 = box_convert(boxes2, in_fmt=fmt, out_fmt="cxcywhr") + + _assert_has_ops() + return torch.ops.torchvision.box_iou_rotated(boxes1, boxes2) + else: + raise ValueError( + f"Unsupported format '{fmt}'. " + f"Supported axis-aligned formats: {axis_aligned_fmts}. " + f"Supported rotated formats: {rotated_fmts}." + ) + + +# Implementation adapted from https://github.com/facebookresearch/detr/blob/master/util/box_ops.py +def generalized_box_iou(boxes1: Tensor, boxes2: Tensor) -> Tensor: + """ + Return generalized intersection-over-union (Jaccard index) between two sets of boxes. + + Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + + Args: + boxes1 (Tensor[..., N, 4]): first set of boxes + boxes2 (Tensor[..., M, 4]): second set of boxes + + Returns: + Tensor[..., N, M]: the NxM matrix containing the pairwise generalized IoU values + for every element in boxes1 and boxes2 + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(generalized_box_iou) + + inter, union = _box_inter_union(boxes1, boxes2) + iou = inter / union + + lti = torch.min(boxes1[..., None, :2], boxes2[..., None, :, :2]) + rbi = torch.max(boxes1[..., None, 2:], boxes2[..., None, :, 2:]) + + whi = _upcast(rbi - lti).clamp(min=0) # [N,M,2] + areai = whi[..., 0] * whi[..., 1] + + return iou - (areai - union) / areai + + +def complete_box_iou(boxes1: Tensor, boxes2: Tensor, eps: float = 1e-7) -> Tensor: + """ + Return complete intersection-over-union (Jaccard index) between two sets of boxes. + Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + Args: + boxes1 (Tensor[..., N, 4]): first set of boxes + boxes2 (Tensor[..., M, 4]): second set of boxes + eps (float, optional): small number to prevent division by zero. Default: 1e-7 + Returns: + Tensor[..., N, M]: the NxM matrix containing the pairwise complete IoU values + for every element in boxes1 and boxes2 + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(complete_box_iou) + + boxes1 = _upcast(boxes1) + boxes2 = _upcast(boxes2) + + diou, iou = _box_diou_iou(boxes1, boxes2, eps) + + w_pred = boxes1[..., None, 2] - boxes1[..., None, 0] + h_pred = boxes1[..., None, 3] - boxes1[..., None, 1] + + w_gt = boxes2[..., None, :, 2] - boxes2[..., None, :, 0] + h_gt = boxes2[..., None, :, 3] - boxes2[..., None, :, 1] + + v = (4 / (torch.pi**2)) * torch.pow(torch.atan(w_pred / h_pred) - torch.atan(w_gt / h_gt), 2) + with torch.no_grad(): + alpha = v / (1 - iou + v + eps) + return diou - alpha * v + + +def distance_box_iou(boxes1: Tensor, boxes2: Tensor, eps: float = 1e-7) -> Tensor: + """ + Return distance intersection-over-union (Jaccard index) between two sets of boxes. + + Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + + Args: + boxes1 (Tensor[..., N, 4]): first set of boxes + boxes2 (Tensor[..., M, 4]): second set of boxes + eps (float, optional): small number to prevent division by zero. Default: 1e-7 + + Returns: + Tensor[..., N, M]: the NxM matrix containing the pairwise distance IoU values + for every element in boxes1 and boxes2 + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(distance_box_iou) + + boxes1 = _upcast(boxes1) + boxes2 = _upcast(boxes2) + diou, _ = _box_diou_iou(boxes1, boxes2, eps=eps) + return diou + + +def _box_diou_iou(boxes1: Tensor, boxes2: Tensor, eps: float = 1e-7) -> tuple[Tensor, Tensor]: + + iou = box_iou(boxes1, boxes2) + lti = torch.min(boxes1[..., None, :2], boxes2[..., None, :, :2]) + rbi = torch.max(boxes1[..., None, 2:], boxes2[..., None, :, 2:]) + whi = _upcast(rbi - lti).clamp(min=0) # [N,M,2] + diagonal_distance_squared = (whi[..., 0] ** 2) + (whi[..., 1] ** 2) + eps + # centers of boxes + x_p = (boxes1[..., 0] + boxes1[..., 2]) / 2 + y_p = (boxes1[..., 1] + boxes1[..., 3]) / 2 + x_g = (boxes2[..., 0] + boxes2[..., 2]) / 2 + y_g = (boxes2[..., 1] + boxes2[..., 3]) / 2 + # The distance between boxes' centers squared. + centers_distance_squared = (_upcast(x_p[..., None] - x_g[..., None, :]) ** 2) + ( + _upcast(y_p[..., None] - y_g[..., None, :]) ** 2 + ) + # The distance IoU is the IoU penalized by a normalized + # distance between boxes' centers squared. + return iou - (centers_distance_squared / diagonal_distance_squared), iou + + +def masks_to_boxes(masks: torch.Tensor) -> torch.Tensor: + """ + Compute the bounding boxes around the provided masks. + + Returns a [N, 4] tensor containing bounding boxes. The boxes are in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 <= x2`` and ``0 <= y1 <= y2``. + + .. note:: + + Empty masks (all zeros) will return bounding boxes ``[0, 0, 0, 0]``. + + .. warning:: + + In most cases the output will guarantee ``x1 < x2`` and ``y1 < y2``. But + if the input is degenerate, e.g. if a mask is a single row or a single + column, then the output may have x1 = x2 or y1 = y2. + + Args: + masks (Tensor[N, H, W]): masks to transform where N is the number of masks + and (H, W) are the spatial dimensions. + + Returns: + Tensor[N, 4]: bounding boxes + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(masks_to_boxes) + if masks.numel() == 0: + return torch.zeros((0, 4), device=masks.device, dtype=torch.float) + + n, h, w = masks.shape + + masks_bool = masks.bool() + + non_zero_rows = torch.any(masks_bool, dim=2) + non_zero_cols = torch.any(masks_bool, dim=1) + + empty_masks = ~torch.any(non_zero_rows, dim=1) + + non_zero_rows_f = non_zero_rows.float() + non_zero_cols_f = non_zero_cols.float() + + y1 = non_zero_rows_f.argmax(dim=1) + x1 = non_zero_cols_f.argmax(dim=1) + y2 = (h - 1) - non_zero_rows_f.flip(dims=[1]).argmax(dim=1) + x2 = (w - 1) - non_zero_cols_f.flip(dims=[1]).argmax(dim=1) + + bounding_boxes = torch.stack([x1, y1, x2, y2], dim=1).float() + + bounding_boxes[empty_masks] = 0 + + return bounding_boxes diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/ciou_loss.py b/.venv/lib/python3.12/site-packages/torchvision/ops/ciou_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..d825e79dff0953389897195785b34cbf905f01e5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/ciou_loss.py @@ -0,0 +1,77 @@ +import torch + +from ..utils import _log_api_usage_once +from ._utils import _upcast_non_float +from .diou_loss import _diou_iou_loss + + +def complete_box_iou_loss( + boxes1: torch.Tensor, + boxes2: torch.Tensor, + reduction: str = "none", + eps: float = 1e-7, +) -> torch.Tensor: + """ + Gradient-friendly IoU loss with an additional penalty that is non-zero when the + boxes do not overlap. This loss function considers important geometrical + factors such as overlap area, normalized central point distance and aspect ratio. + This loss is symmetric, so the boxes1 and boxes2 arguments are interchangeable. + + Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 < x2`` and ``0 <= y1 < y2``, and The two boxes should have the + same dimensions. + + Args: + boxes1 : (Tensor[N, 4] or Tensor[4]) first set of boxes + boxes2 : (Tensor[N, 4] or Tensor[4]) second set of boxes + reduction : (string, optional) Specifies the reduction to apply to the output: + ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: No reduction will be + applied to the output. ``'mean'``: The output will be averaged. + ``'sum'``: The output will be summed. Default: ``'none'`` + eps : (float): small number to prevent division by zero. Default: 1e-7 + + Returns: + Tensor: Loss tensor with the reduction option applied. + + Reference: + Zhaohui Zheng et al.: Complete Intersection over Union Loss: + https://arxiv.org/abs/1911.08287 + + """ + + # Original Implementation from https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/losses.py + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(complete_box_iou_loss) + + boxes1 = _upcast_non_float(boxes1) + boxes2 = _upcast_non_float(boxes2) + + diou_loss, iou = _diou_iou_loss(boxes1, boxes2) + + x1, y1, x2, y2 = boxes1.unbind(dim=-1) + x1g, y1g, x2g, y2g = boxes2.unbind(dim=-1) + + # width and height of boxes + w_pred = x2 - x1 + h_pred = y2 - y1 + w_gt = x2g - x1g + h_gt = y2g - y1g + v = (4 / (torch.pi**2)) * torch.pow((torch.atan(w_gt / h_gt) - torch.atan(w_pred / h_pred)), 2) + with torch.no_grad(): + alpha = v / (1 - iou + v + eps) + + loss = diou_loss + alpha * v + + # Check reduction option and return loss accordingly + if reduction == "none": + pass + elif reduction == "mean": + loss = loss.mean() if loss.numel() > 0 else 0.0 * loss.sum() + elif reduction == "sum": + loss = loss.sum() + else: + raise ValueError( + f"Invalid Value for arg 'reduction': '{reduction} \n Supported reduction modes: 'none', 'mean', 'sum'" + ) + return loss diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/deform_conv.py b/.venv/lib/python3.12/site-packages/torchvision/ops/deform_conv.py new file mode 100644 index 0000000000000000000000000000000000000000..da13ee6da9a69770ca321f1dc74a19382e4b7c20 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/deform_conv.py @@ -0,0 +1,195 @@ +import math +from typing import Optional + +import torch +from torch import nn, Tensor +from torch.nn import init +from torch.nn.modules.utils import _pair +from torch.nn.parameter import Parameter +from torchvision.extension import _assert_has_ops + +from ..utils import _log_api_usage_once + + +def deform_conv2d( + input: Tensor, + offset: Tensor, + weight: Tensor, + bias: Optional[Tensor] = None, + stride: tuple[int, int] = (1, 1), + padding: tuple[int, int] = (0, 0), + dilation: tuple[int, int] = (1, 1), + mask: Optional[Tensor] = None, +) -> Tensor: + r""" + Performs Deformable Convolution v2, described in + `Deformable ConvNets v2: More Deformable, Better Results + `__ if :attr:`mask` is not ``None`` and + Performs Deformable Convolution, described in + `Deformable Convolutional Networks + `__ if :attr:`mask` is ``None``. + + Args: + input (Tensor[batch_size, in_channels, in_height, in_width]): input tensor + offset (Tensor[batch_size, 2 * offset_groups * kernel_height * kernel_width, out_height, out_width]): + offsets to be applied for each position in the convolution kernel. + weight (Tensor[out_channels, in_channels // groups, kernel_height, kernel_width]): convolution weights, + split into groups of size (in_channels // groups) + bias (Tensor[out_channels]): optional bias of shape (out_channels,). Default: None + stride (int or Tuple[int, int]): distance between convolution centers. Default: 1 + padding (int or Tuple[int, int]): height/width of padding of zeroes around + each image. Default: 0 + dilation (int or Tuple[int, int]): the spacing between kernel elements. Default: 1 + mask (Tensor[batch_size, offset_groups * kernel_height * kernel_width, out_height, out_width]): + masks to be applied for each position in the convolution kernel. Default: None + + Returns: + Tensor[batch_sz, out_channels, out_h, out_w]: result of convolution + + Examples:: + >>> input = torch.rand(4, 3, 10, 10) + >>> kh, kw = 3, 3 + >>> weight = torch.rand(5, 3, kh, kw) + >>> # offset and mask should have the same spatial size as the output + >>> # of the convolution. In this case, for an input of 10, stride of 1 + >>> # and kernel size of 3, without padding, the output size is 8 + >>> offset = torch.rand(4, 2 * kh * kw, 8, 8) + >>> mask = torch.rand(4, kh * kw, 8, 8) + >>> out = deform_conv2d(input, offset, weight, mask=mask) + >>> print(out.shape) + >>> # returns + >>> torch.Size([4, 5, 8, 8]) + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(deform_conv2d) + _assert_has_ops() + out_channels = weight.shape[0] + + use_mask = mask is not None + + if mask is None: + mask = torch.zeros((input.shape[0], 1), device=input.device, dtype=input.dtype) + + if bias is None: + bias = torch.zeros(out_channels, device=input.device, dtype=input.dtype) + + stride_h, stride_w = _pair(stride) + pad_h, pad_w = _pair(padding) + dil_h, dil_w = _pair(dilation) + weights_h, weights_w = weight.shape[-2:] + _, n_in_channels, _, _ = input.shape + + n_offset_grps = offset.shape[1] // (2 * weights_h * weights_w) + n_weight_grps = n_in_channels // weight.shape[1] + + if n_offset_grps == 0: + raise RuntimeError( + "the shape of the offset tensor at dimension 1 is not valid. It should " + "be a multiple of 2 * weight.size[2] * weight.size[3].\n" + f"Got offset.shape[1]={offset.shape[1]}, while 2 * weight.size[2] * weight.size[3]={2 * weights_h * weights_w}" + ) + + return torch.ops.torchvision.deform_conv2d( + input, + weight, + offset, + mask, + bias, + stride_h, + stride_w, + pad_h, + pad_w, + dil_h, + dil_w, + n_weight_grps, + n_offset_grps, + use_mask, + ) + + +class DeformConv2d(nn.Module): + """ + See :func:`deform_conv2d`. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: int, + stride: int = 1, + padding: int = 0, + dilation: int = 1, + groups: int = 1, + bias: bool = True, + ): + super().__init__() + _log_api_usage_once(self) + + if in_channels % groups != 0: + raise ValueError("in_channels must be divisible by groups") + if out_channels % groups != 0: + raise ValueError("out_channels must be divisible by groups") + + self.in_channels = in_channels + self.out_channels = out_channels + self.kernel_size = _pair(kernel_size) + self.stride = _pair(stride) + self.padding = _pair(padding) + self.dilation = _pair(dilation) + self.groups = groups + + self.weight = Parameter( + torch.empty(out_channels, in_channels // groups, self.kernel_size[0], self.kernel_size[1]) + ) + + if bias: + self.bias = Parameter(torch.empty(out_channels)) + else: + self.register_parameter("bias", None) + + self.reset_parameters() + + def reset_parameters(self) -> None: + init.kaiming_uniform_(self.weight, a=math.sqrt(5)) + + if self.bias is not None: + fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight) + bound = 1 / math.sqrt(fan_in) + init.uniform_(self.bias, -bound, bound) + + def forward(self, input: Tensor, offset: Tensor, mask: Optional[Tensor] = None) -> Tensor: + """ + Args: + input (Tensor[batch_size, in_channels, in_height, in_width]): input tensor + offset (Tensor[batch_size, 2 * offset_groups * kernel_height * kernel_width, out_height, out_width]): + offsets to be applied for each position in the convolution kernel. + mask (Tensor[batch_size, offset_groups * kernel_height * kernel_width, out_height, out_width]): + masks to be applied for each position in the convolution kernel. + """ + return deform_conv2d( + input, + offset, + self.weight, + self.bias, + stride=self.stride, + padding=self.padding, + dilation=self.dilation, + mask=mask, + ) + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"{self.in_channels}" + f", {self.out_channels}" + f", kernel_size={self.kernel_size}" + f", stride={self.stride}" + ) + s += f", padding={self.padding}" if self.padding != (0, 0) else "" + s += f", dilation={self.dilation}" if self.dilation != (1, 1) else "" + s += f", groups={self.groups}" if self.groups != 1 else "" + s += ", bias=False" if self.bias is None else "" + s += ")" + + return s diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/diou_loss.py b/.venv/lib/python3.12/site-packages/torchvision/ops/diou_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..9381878ce1d81e853b370d8cc92681cfd3a5b5c6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/diou_loss.py @@ -0,0 +1,91 @@ +import torch + +from ..utils import _log_api_usage_once +from ._utils import _loss_inter_union, _upcast_non_float + + +def distance_box_iou_loss( + boxes1: torch.Tensor, + boxes2: torch.Tensor, + reduction: str = "none", + eps: float = 1e-7, +) -> torch.Tensor: + """ + Gradient-friendly IoU loss with an additional penalty that is non-zero when the + distance between boxes' centers isn't zero. Indeed, for two exactly overlapping + boxes, the distance IoU is the same as the IoU loss. + This loss is symmetric, so the boxes1 and boxes2 arguments are interchangeable. + + Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 < x2`` and ``0 <= y1 < y2``, and The two boxes should have the + same dimensions. + + Args: + boxes1 (Tensor[N, 4]): first set of boxes + boxes2 (Tensor[N, 4]): second set of boxes + reduction (string, optional): Specifies the reduction to apply to the output: + ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: No reduction will be + applied to the output. ``'mean'``: The output will be averaged. + ``'sum'``: The output will be summed. Default: ``'none'`` + eps (float, optional): small number to prevent division by zero. Default: 1e-7 + + Returns: + Tensor: Loss tensor with the reduction option applied. + + Reference: + Zhaohui Zheng et al.: Distance Intersection over Union Loss: + https://arxiv.org/abs/1911.08287 + """ + + # Original Implementation from https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/losses.py + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(distance_box_iou_loss) + + boxes1 = _upcast_non_float(boxes1) + boxes2 = _upcast_non_float(boxes2) + + loss, _ = _diou_iou_loss(boxes1, boxes2, eps) + + # Check reduction option and return loss accordingly + if reduction == "none": + pass + elif reduction == "mean": + loss = loss.mean() if loss.numel() > 0 else 0.0 * loss.sum() + elif reduction == "sum": + loss = loss.sum() + else: + raise ValueError( + f"Invalid Value for arg 'reduction': '{reduction} \n Supported reduction modes: 'none', 'mean', 'sum'" + ) + return loss + + +def _diou_iou_loss( + boxes1: torch.Tensor, + boxes2: torch.Tensor, + eps: float = 1e-7, +) -> tuple[torch.Tensor, torch.Tensor]: + + intsct, union = _loss_inter_union(boxes1, boxes2) + iou = intsct / (union + eps) + # smallest enclosing box + x1, y1, x2, y2 = boxes1.unbind(dim=-1) + x1g, y1g, x2g, y2g = boxes2.unbind(dim=-1) + xc1 = torch.min(x1, x1g) + yc1 = torch.min(y1, y1g) + xc2 = torch.max(x2, x2g) + yc2 = torch.max(y2, y2g) + # The diagonal distance of the smallest enclosing box squared + diagonal_distance_squared = ((xc2 - xc1) ** 2) + ((yc2 - yc1) ** 2) + eps + # centers of boxes + x_p = (x2 + x1) / 2 + y_p = (y2 + y1) / 2 + x_g = (x1g + x2g) / 2 + y_g = (y1g + y2g) / 2 + # The distance between boxes' centers squared. + centers_distance_squared = ((x_p - x_g) ** 2) + ((y_p - y_g) ** 2) + # The distance IoU is the IoU penalized by a normalized + # distance between boxes' centers squared. + loss = 1 - iou + (centers_distance_squared / diagonal_distance_squared) + return loss, iou diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/drop_block.py b/.venv/lib/python3.12/site-packages/torchvision/ops/drop_block.py new file mode 100644 index 0000000000000000000000000000000000000000..eb80921e3afaf9d4163e4cbfe857e1218dd02337 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/drop_block.py @@ -0,0 +1,161 @@ +import torch +import torch.fx +import torch.nn.functional as F +from torch import nn, Tensor + +from ..utils import _log_api_usage_once + + +def drop_block2d( + input: Tensor, p: float, block_size: int, inplace: bool = False, eps: float = 1e-06, training: bool = True +) -> Tensor: + """ + Implements DropBlock2d from `"DropBlock: A regularization method for convolutional networks" + `. + + Args: + input (Tensor[N, C, H, W]): The input tensor or 4-dimensions with the first one + being its batch i.e. a batch with ``N`` rows. + p (float): Probability of an element to be dropped. + block_size (int): Size of the block to drop. + inplace (bool): If set to ``True``, will do this operation in-place. Default: ``False``. + eps (float): A value added to the denominator for numerical stability. Default: 1e-6. + training (bool): apply dropblock if is ``True``. Default: ``True``. + + Returns: + Tensor[N, C, H, W]: The randomly zeroed tensor after dropblock. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(drop_block2d) + if p < 0.0 or p > 1.0: + raise ValueError(f"drop probability has to be between 0 and 1, but got {p}.") + if input.ndim != 4: + raise ValueError(f"input should be 4 dimensional. Got {input.ndim} dimensions.") + if not training or p == 0.0: + return input + + N, C, H, W = input.size() + block_size = min(block_size, W, H) + if block_size % 2 == 0: + raise ValueError(f"block size should be odd. Got {block_size} which is even.") + + # compute the gamma of Bernoulli distribution + gamma = (p * H * W) / ((block_size**2) * ((H - block_size + 1) * (W - block_size + 1))) + noise = torch.empty((N, C, H - block_size + 1, W - block_size + 1), dtype=input.dtype, device=input.device) + noise.bernoulli_(gamma) + + noise = F.pad(noise, [block_size // 2] * 4, value=0) + noise = F.max_pool2d(noise, stride=(1, 1), kernel_size=(block_size, block_size), padding=block_size // 2) + noise = 1 - noise + normalize_scale = noise.numel() / (eps + noise.sum()) + if inplace: + input.mul_(noise).mul_(normalize_scale) + else: + input = input * noise * normalize_scale + return input + + +def drop_block3d( + input: Tensor, p: float, block_size: int, inplace: bool = False, eps: float = 1e-06, training: bool = True +) -> Tensor: + """ + Implements DropBlock3d from `"DropBlock: A regularization method for convolutional networks" + `. + + Args: + input (Tensor[N, C, D, H, W]): The input tensor or 5-dimensions with the first one + being its batch i.e. a batch with ``N`` rows. + p (float): Probability of an element to be dropped. + block_size (int): Size of the block to drop. + inplace (bool): If set to ``True``, will do this operation in-place. Default: ``False``. + eps (float): A value added to the denominator for numerical stability. Default: 1e-6. + training (bool): apply dropblock if is ``True``. Default: ``True``. + + Returns: + Tensor[N, C, D, H, W]: The randomly zeroed tensor after dropblock. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(drop_block3d) + if p < 0.0 or p > 1.0: + raise ValueError(f"drop probability has to be between 0 and 1, but got {p}.") + if input.ndim != 5: + raise ValueError(f"input should be 5 dimensional. Got {input.ndim} dimensions.") + if not training or p == 0.0: + return input + + N, C, D, H, W = input.size() + block_size = min(block_size, D, H, W) + if block_size % 2 == 0: + raise ValueError(f"block size should be odd. Got {block_size} which is even.") + + # compute the gamma of Bernoulli distribution + gamma = (p * D * H * W) / ((block_size**3) * ((D - block_size + 1) * (H - block_size + 1) * (W - block_size + 1))) + noise = torch.empty( + (N, C, D - block_size + 1, H - block_size + 1, W - block_size + 1), dtype=input.dtype, device=input.device + ) + noise.bernoulli_(gamma) + + noise = F.pad(noise, [block_size // 2] * 6, value=0) + noise = F.max_pool3d( + noise, stride=(1, 1, 1), kernel_size=(block_size, block_size, block_size), padding=block_size // 2 + ) + noise = 1 - noise + normalize_scale = noise.numel() / (eps + noise.sum()) + if inplace: + input.mul_(noise).mul_(normalize_scale) + else: + input = input * noise * normalize_scale + return input + + +torch.fx.wrap("drop_block2d") + + +class DropBlock2d(nn.Module): + """ + See :func:`drop_block2d`. + """ + + def __init__(self, p: float, block_size: int, inplace: bool = False, eps: float = 1e-06) -> None: + super().__init__() + + self.p = p + self.block_size = block_size + self.inplace = inplace + self.eps = eps + + def forward(self, input: Tensor) -> Tensor: + """ + Args: + input (Tensor): Input feature map on which some areas will be randomly + dropped. + Returns: + Tensor: The tensor after DropBlock layer. + """ + return drop_block2d(input, self.p, self.block_size, self.inplace, self.eps, self.training) + + def __repr__(self) -> str: + s = f"{self.__class__.__name__}(p={self.p}, block_size={self.block_size}, inplace={self.inplace})" + return s + + +torch.fx.wrap("drop_block3d") + + +class DropBlock3d(DropBlock2d): + """ + See :func:`drop_block3d`. + """ + + def __init__(self, p: float, block_size: int, inplace: bool = False, eps: float = 1e-06) -> None: + super().__init__(p, block_size, inplace, eps) + + def forward(self, input: Tensor) -> Tensor: + """ + Args: + input (Tensor): Input feature map on which some areas will be randomly + dropped. + Returns: + Tensor: The tensor after DropBlock layer. + """ + return drop_block3d(input, self.p, self.block_size, self.inplace, self.eps, self.training) diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/feature_pyramid_network.py b/.venv/lib/python3.12/site-packages/torchvision/ops/feature_pyramid_network.py new file mode 100644 index 0000000000000000000000000000000000000000..5c85e19a6996e38b5b1a5a5690708d2c9ff99dff --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/feature_pyramid_network.py @@ -0,0 +1,250 @@ +from collections import OrderedDict +from typing import Callable, Optional + +import torch.nn.functional as F +from torch import nn, Tensor + +from ..ops.misc import Conv2dNormActivation +from ..utils import _log_api_usage_once + + +class ExtraFPNBlock(nn.Module): + """ + Base class for the extra block in the FPN. + + Args: + results (List[Tensor]): the result of the FPN + x (List[Tensor]): the original feature maps + names (List[str]): the names for each one of the + original feature maps + + Returns: + results (List[Tensor]): the extended set of results + of the FPN + names (List[str]): the extended set of names for the results + """ + + def forward( + self, + results: list[Tensor], + x: list[Tensor], + names: list[str], + ) -> tuple[list[Tensor], list[str]]: + pass + + +class FeaturePyramidNetwork(nn.Module): + """ + Module that adds a FPN from on top of a set of feature maps. This is based on + `"Feature Pyramid Network for Object Detection" `_. + + The feature maps are currently supposed to be in increasing depth + order. + + The input to the model is expected to be an OrderedDict[Tensor], containing + the feature maps on top of which the FPN will be added. + + Args: + in_channels_list (list[int]): number of channels for each feature map that + is passed to the module + out_channels (int): number of channels of the FPN representation + extra_blocks (ExtraFPNBlock or None): if provided, extra operations will + be performed. It is expected to take the fpn features, the original + features and the names of the original features as input, and returns + a new list of feature maps and their corresponding names + norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None + + Examples:: + + >>> m = torchvision.ops.FeaturePyramidNetwork([10, 20, 30], 5) + >>> # get some dummy data + >>> x = OrderedDict() + >>> x['feat0'] = torch.rand(1, 10, 64, 64) + >>> x['feat2'] = torch.rand(1, 20, 16, 16) + >>> x['feat3'] = torch.rand(1, 30, 8, 8) + >>> # compute the FPN on top of x + >>> output = m(x) + >>> print([(k, v.shape) for k, v in output.items()]) + >>> # returns + >>> [('feat0', torch.Size([1, 5, 64, 64])), + >>> ('feat2', torch.Size([1, 5, 16, 16])), + >>> ('feat3', torch.Size([1, 5, 8, 8]))] + + """ + + _version = 2 + + def __init__( + self, + in_channels_list: list[int], + out_channels: int, + extra_blocks: Optional[ExtraFPNBlock] = None, + norm_layer: Optional[Callable[..., nn.Module]] = None, + ): + super().__init__() + _log_api_usage_once(self) + self.inner_blocks = nn.ModuleList() + self.layer_blocks = nn.ModuleList() + for in_channels in in_channels_list: + if in_channels == 0: + raise ValueError("in_channels=0 is currently not supported") + inner_block_module = Conv2dNormActivation( + in_channels, out_channels, kernel_size=1, padding=0, norm_layer=norm_layer, activation_layer=None + ) + layer_block_module = Conv2dNormActivation( + out_channels, out_channels, kernel_size=3, norm_layer=norm_layer, activation_layer=None + ) + self.inner_blocks.append(inner_block_module) + self.layer_blocks.append(layer_block_module) + + # initialize parameters now to avoid modifying the initialization of top_blocks + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_uniform_(m.weight, a=1) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + if extra_blocks is not None: + if not isinstance(extra_blocks, ExtraFPNBlock): + raise TypeError(f"extra_blocks should be of type ExtraFPNBlock not {type(extra_blocks)}") + self.extra_blocks = extra_blocks + + def _load_from_state_dict( + self, + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ): + version = local_metadata.get("version", None) + + if version is None or version < 2: + num_blocks = len(self.inner_blocks) + for block in ["inner_blocks", "layer_blocks"]: + for i in range(num_blocks): + for type in ["weight", "bias"]: + old_key = f"{prefix}{block}.{i}.{type}" + new_key = f"{prefix}{block}.{i}.0.{type}" + if old_key in state_dict: + state_dict[new_key] = state_dict.pop(old_key) + + super()._load_from_state_dict( + state_dict, + prefix, + local_metadata, + strict, + missing_keys, + unexpected_keys, + error_msgs, + ) + + def get_result_from_inner_blocks(self, x: Tensor, idx: int) -> Tensor: + """ + This is equivalent to self.inner_blocks[idx](x), + but torchscript doesn't support this yet + """ + num_blocks = len(self.inner_blocks) + if idx < 0: + idx += num_blocks + out = x + for i, module in enumerate(self.inner_blocks): + if i == idx: + out = module(x) + return out + + def get_result_from_layer_blocks(self, x: Tensor, idx: int) -> Tensor: + """ + This is equivalent to self.layer_blocks[idx](x), + but torchscript doesn't support this yet + """ + num_blocks = len(self.layer_blocks) + if idx < 0: + idx += num_blocks + out = x + for i, module in enumerate(self.layer_blocks): + if i == idx: + out = module(x) + return out + + def forward(self, x: dict[str, Tensor]) -> dict[str, Tensor]: + """ + Computes the FPN for a set of feature maps. + + Args: + x (OrderedDict[Tensor]): feature maps for each feature level. + + Returns: + results (OrderedDict[Tensor]): feature maps after FPN layers. + They are ordered from the highest resolution first. + """ + # unpack OrderedDict into two lists for easier handling + names = list(x.keys()) + x = list(x.values()) + + last_inner = self.get_result_from_inner_blocks(x[-1], -1) + results = [] + results.append(self.get_result_from_layer_blocks(last_inner, -1)) + + for idx in range(len(x) - 2, -1, -1): + inner_lateral = self.get_result_from_inner_blocks(x[idx], idx) + feat_shape = inner_lateral.shape[-2:] + inner_top_down = F.interpolate(last_inner, size=feat_shape, mode="nearest") + last_inner = inner_lateral + inner_top_down + results.insert(0, self.get_result_from_layer_blocks(last_inner, idx)) + + if self.extra_blocks is not None: + results, names = self.extra_blocks(results, x, names) + + # make it back an OrderedDict + out = OrderedDict([(k, v) for k, v in zip(names, results)]) + + return out + + +class LastLevelMaxPool(ExtraFPNBlock): + """ + Applies a max_pool2d (not actual max_pool2d, we just subsample) on top of the last feature map + """ + + def forward( + self, + x: list[Tensor], + y: list[Tensor], + names: list[str], + ) -> tuple[list[Tensor], list[str]]: + names.append("pool") + # Use max pooling to simulate stride 2 subsampling + x.append(F.max_pool2d(x[-1], kernel_size=1, stride=2, padding=0)) + return x, names + + +class LastLevelP6P7(ExtraFPNBlock): + """ + This module is used in RetinaNet to generate extra layers, P6 and P7. + """ + + def __init__(self, in_channels: int, out_channels: int): + super().__init__() + self.p6 = nn.Conv2d(in_channels, out_channels, 3, 2, 1) + self.p7 = nn.Conv2d(out_channels, out_channels, 3, 2, 1) + for module in [self.p6, self.p7]: + nn.init.kaiming_uniform_(module.weight, a=1) + nn.init.constant_(module.bias, 0) + self.use_P5 = in_channels == out_channels + + def forward( + self, + p: list[Tensor], + c: list[Tensor], + names: list[str], + ) -> tuple[list[Tensor], list[str]]: + p5, c5 = p[-1], c[-1] + x = p5 if self.use_P5 else c5 + p6 = self.p6(x) + p7 = self.p7(F.relu(p6)) + p.extend([p6, p7]) + names.extend(["p6", "p7"]) + return p, names diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/focal_loss.py b/.venv/lib/python3.12/site-packages/torchvision/ops/focal_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..5cd781eaab54b3eec755c341f2678a58068e84eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/focal_loss.py @@ -0,0 +1,61 @@ +import torch +import torch.nn.functional as F + +from ..utils import _log_api_usage_once + + +def sigmoid_focal_loss( + inputs: torch.Tensor, + targets: torch.Tensor, + alpha: float = 0.25, + gamma: float = 2, + reduction: str = "none", +) -> torch.Tensor: + """ + Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. + + Args: + inputs (Tensor): A float tensor of arbitrary shape. + The predictions for each example. + targets (Tensor): A float tensor with the same shape as inputs. Stores the binary + classification label for each element in inputs + (0 for the negative class and 1 for the positive class). + alpha (float): Weighting factor in range [0, 1] to balance + positive vs negative examples or -1 for ignore. Default: ``0.25``. + gamma (float): Exponent of the modulating factor (1 - p_t) to + balance easy vs hard examples. Default: ``2``. + reduction (string): ``'none'`` | ``'mean'`` | ``'sum'`` + ``'none'``: No reduction will be applied to the output. + ``'mean'``: The output will be averaged. + ``'sum'``: The output will be summed. Default: ``'none'``. + Returns: + Loss tensor with the reduction option applied. + """ + # Original implementation from https://github.com/facebookresearch/fvcore/blob/master/fvcore/nn/focal_loss.py + + if not (0 <= alpha <= 1) and alpha != -1: + raise ValueError(f"Invalid alpha value: {alpha}. alpha must be in the range [0,1] or -1 for ignore.") + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(sigmoid_focal_loss) + p = torch.sigmoid(inputs) + ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") + p_t = p * targets + (1 - p) * (1 - targets) + loss = ce_loss * ((1 - p_t) ** gamma) + + if alpha >= 0: + alpha_t = alpha * targets + (1 - alpha) * (1 - targets) + loss = alpha_t * loss + + # Check reduction option and return loss accordingly + if reduction == "none": + pass + elif reduction == "mean": + loss = loss.mean() + elif reduction == "sum": + loss = loss.sum() + else: + raise ValueError( + f"Invalid Value for arg 'reduction': '{reduction} \n Supported reduction modes: 'none', 'mean', 'sum'" + ) + return loss diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/giou_loss.py b/.venv/lib/python3.12/site-packages/torchvision/ops/giou_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..e56dcc16c7d84fe6ba0f59c0b60e30a84110fbb0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/giou_loss.py @@ -0,0 +1,75 @@ +import torch + +from ..utils import _log_api_usage_once +from ._utils import _loss_inter_union, _upcast_non_float + + +def generalized_box_iou_loss( + boxes1: torch.Tensor, + boxes2: torch.Tensor, + reduction: str = "none", + eps: float = 1e-7, +) -> torch.Tensor: + """ + Gradient-friendly IoU loss with an additional penalty that is non-zero when the + boxes do not overlap and scales with the size of their smallest enclosing box. + This loss is symmetric, so the boxes1 and boxes2 arguments are interchangeable. + + Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with + ``0 <= x1 < x2`` and ``0 <= y1 < y2``, and The two boxes should have the + same dimensions. + + Args: + boxes1 (Tensor[N, 4] or Tensor[4]): first set of boxes + boxes2 (Tensor[N, 4] or Tensor[4]): second set of boxes + reduction (string, optional): Specifies the reduction to apply to the output: + ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: No reduction will be + applied to the output. ``'mean'``: The output will be averaged. + ``'sum'``: The output will be summed. Default: ``'none'`` + eps (float): small number to prevent division by zero. Default: 1e-7 + + Returns: + Tensor: Loss tensor with the reduction option applied. + + Reference: + Hamid Rezatofighi et al.: Generalized Intersection over Union: + A Metric and A Loss for Bounding Box Regression: + https://arxiv.org/abs/1902.09630 + """ + + # Original implementation from https://github.com/facebookresearch/fvcore/blob/bfff2ef/fvcore/nn/giou_loss.py + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(generalized_box_iou_loss) + + boxes1 = _upcast_non_float(boxes1) + boxes2 = _upcast_non_float(boxes2) + intsctk, unionk = _loss_inter_union(boxes1, boxes2) + iouk = intsctk / (unionk + eps) + + x1, y1, x2, y2 = boxes1.unbind(dim=-1) + x1g, y1g, x2g, y2g = boxes2.unbind(dim=-1) + + # smallest enclosing box + xc1 = torch.min(x1, x1g) + yc1 = torch.min(y1, y1g) + xc2 = torch.max(x2, x2g) + yc2 = torch.max(y2, y2g) + + area_c = (xc2 - xc1) * (yc2 - yc1) + miouk = iouk - ((area_c - unionk) / (area_c + eps)) + + loss = 1 - miouk + + # Check reduction option and return loss accordingly + if reduction == "none": + pass + elif reduction == "mean": + loss = loss.mean() if loss.numel() > 0 else 0.0 * loss.sum() + elif reduction == "sum": + loss = loss.sum() + else: + raise ValueError( + f"Invalid Value for arg 'reduction': '{reduction} \n Supported reduction modes: 'none', 'mean', 'sum'" + ) + return loss diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/misc.py b/.venv/lib/python3.12/site-packages/torchvision/ops/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..cfa1e23a5ee62a81784949157fb485b7529a37e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/misc.py @@ -0,0 +1,321 @@ +import warnings +from collections.abc import Sequence +from typing import Callable, Optional, Union + +import torch +from torch import Tensor + +from ..utils import _log_api_usage_once, _make_ntuple + + +interpolate = torch.nn.functional.interpolate + + +class FrozenBatchNorm2d(torch.nn.Module): + """ + BatchNorm2d where the batch statistics and the affine parameters are fixed + + Args: + num_features (int): Number of features ``C`` from an expected input of size ``(N, C, H, W)`` + eps (float): a value added to the denominator for numerical stability. Default: 1e-5 + """ + + def __init__( + self, + num_features: int, + eps: float = 1e-5, + ): + super().__init__() + _log_api_usage_once(self) + self.eps = eps + self.register_buffer("weight", torch.ones(num_features)) + self.register_buffer("bias", torch.zeros(num_features)) + self.register_buffer("running_mean", torch.zeros(num_features)) + self.register_buffer("running_var", torch.ones(num_features)) + + def _load_from_state_dict( + self, + state_dict: dict, + prefix: str, + local_metadata: dict, + strict: bool, + missing_keys: list[str], + unexpected_keys: list[str], + error_msgs: list[str], + ): + num_batches_tracked_key = prefix + "num_batches_tracked" + if num_batches_tracked_key in state_dict: + del state_dict[num_batches_tracked_key] + + super()._load_from_state_dict( + state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ) + + def forward(self, x: Tensor) -> Tensor: + # move reshapes to the beginning + # to make it fuser-friendly + w = self.weight.reshape(1, -1, 1, 1) + b = self.bias.reshape(1, -1, 1, 1) + rv = self.running_var.reshape(1, -1, 1, 1) + rm = self.running_mean.reshape(1, -1, 1, 1) + scale = w * (rv + self.eps).rsqrt() + bias = b - rm * scale + return x * scale + bias + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.weight.shape[0]}, eps={self.eps})" + + +class ConvNormActivation(torch.nn.Sequential): + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: Union[int, tuple[int, ...]] = 3, + stride: Union[int, tuple[int, ...]] = 1, + padding: Optional[Union[int, tuple[int, ...], str]] = None, + groups: int = 1, + norm_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.BatchNorm2d, + activation_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.ReLU, + dilation: Union[int, tuple[int, ...]] = 1, + inplace: Optional[bool] = True, + bias: Optional[bool] = None, + conv_layer: Callable[..., torch.nn.Module] = torch.nn.Conv2d, + ) -> None: + + if padding is None: + if isinstance(kernel_size, int) and isinstance(dilation, int): + padding = (kernel_size - 1) // 2 * dilation + else: + _conv_dim = len(kernel_size) if isinstance(kernel_size, Sequence) else len(dilation) + kernel_size = _make_ntuple(kernel_size, _conv_dim) + dilation = _make_ntuple(dilation, _conv_dim) + padding = tuple((kernel_size[i] - 1) // 2 * dilation[i] for i in range(_conv_dim)) + if bias is None: + bias = norm_layer is None + + layers = [ + conv_layer( + in_channels, + out_channels, + kernel_size, + stride, + padding, + dilation=dilation, + groups=groups, + bias=bias, + ) + ] + + if norm_layer is not None: + layers.append(norm_layer(out_channels)) + + if activation_layer is not None: + params = {} if inplace is None else {"inplace": inplace} + layers.append(activation_layer(**params)) + super().__init__(*layers) + _log_api_usage_once(self) + self.out_channels = out_channels + + if self.__class__ == ConvNormActivation: + warnings.warn( + "Don't use ConvNormActivation directly, please use Conv2dNormActivation and Conv3dNormActivation instead." + ) + + +class Conv2dNormActivation(ConvNormActivation): + """ + Configurable block used for Convolution2d-Normalization-Activation blocks. + + Args: + in_channels (int): Number of channels in the input image + out_channels (int): Number of channels produced by the Convolution-Normalization-Activation block + kernel_size: (int, optional): Size of the convolving kernel. Default: 3 + stride (int, optional): Stride of the convolution. Default: 1 + padding (int, tuple or str, optional): Padding added to all four sides of the input. Default: None, in which case it will be calculated as ``padding = (kernel_size - 1) // 2 * dilation`` + groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1 + norm_layer (Callable[..., torch.nn.Module], optional): Norm layer that will be stacked on top of the convolution layer. If ``None`` this layer won't be used. Default: ``torch.nn.BatchNorm2d`` + activation_layer (Callable[..., torch.nn.Module], optional): Activation function which will be stacked on top of the normalization layer (if not None), otherwise on top of the conv layer. If ``None`` this layer won't be used. Default: ``torch.nn.ReLU`` + dilation (int): Spacing between kernel elements. Default: 1 + inplace (bool): Parameter for the activation layer, which can optionally do the operation in-place. Default ``True`` + bias (bool, optional): Whether to use bias in the convolution layer. By default, biases are included if ``norm_layer is None``. + + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: Union[int, tuple[int, int]] = 3, + stride: Union[int, tuple[int, int]] = 1, + padding: Optional[Union[int, tuple[int, int], str]] = None, + groups: int = 1, + norm_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.BatchNorm2d, + activation_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.ReLU, + dilation: Union[int, tuple[int, int]] = 1, + inplace: Optional[bool] = True, + bias: Optional[bool] = None, + ) -> None: + + super().__init__( + in_channels, + out_channels, + kernel_size, + stride, + padding, + groups, + norm_layer, + activation_layer, + dilation, + inplace, + bias, + torch.nn.Conv2d, + ) + + +class Conv3dNormActivation(ConvNormActivation): + """ + Configurable block used for Convolution3d-Normalization-Activation blocks. + + Args: + in_channels (int): Number of channels in the input video. + out_channels (int): Number of channels produced by the Convolution-Normalization-Activation block + kernel_size: (int, optional): Size of the convolving kernel. Default: 3 + stride (int, optional): Stride of the convolution. Default: 1 + padding (int, tuple or str, optional): Padding added to all four sides of the input. Default: None, in which case it will be calculated as ``padding = (kernel_size - 1) // 2 * dilation`` + groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1 + norm_layer (Callable[..., torch.nn.Module], optional): Norm layer that will be stacked on top of the convolution layer. If ``None`` this layer won't be used. Default: ``torch.nn.BatchNorm3d`` + activation_layer (Callable[..., torch.nn.Module], optional): Activation function which will be stacked on top of the normalization layer (if not None), otherwise on top of the conv layer. If ``None`` this layer won't be used. Default: ``torch.nn.ReLU`` + dilation (int): Spacing between kernel elements. Default: 1 + inplace (bool): Parameter for the activation layer, which can optionally do the operation in-place. Default ``True`` + bias (bool, optional): Whether to use bias in the convolution layer. By default, biases are included if ``norm_layer is None``. + """ + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: Union[int, tuple[int, int, int]] = 3, + stride: Union[int, tuple[int, int, int]] = 1, + padding: Optional[Union[int, tuple[int, int, int], str]] = None, + groups: int = 1, + norm_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.BatchNorm3d, + activation_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.ReLU, + dilation: Union[int, tuple[int, int, int]] = 1, + inplace: Optional[bool] = True, + bias: Optional[bool] = None, + ) -> None: + + super().__init__( + in_channels, + out_channels, + kernel_size, + stride, + padding, + groups, + norm_layer, + activation_layer, + dilation, + inplace, + bias, + torch.nn.Conv3d, + ) + + +class SqueezeExcitation(torch.nn.Module): + """ + This block implements the Squeeze-and-Excitation block from https://arxiv.org/abs/1709.01507 (see Fig. 1). + Parameters ``activation``, and ``scale_activation`` correspond to ``delta`` and ``sigma`` in eq. 3. + + Args: + input_channels (int): Number of channels in the input image + squeeze_channels (int): Number of squeeze channels + activation (Callable[..., torch.nn.Module], optional): ``delta`` activation. Default: ``torch.nn.ReLU`` + scale_activation (Callable[..., torch.nn.Module]): ``sigma`` activation. Default: ``torch.nn.Sigmoid`` + """ + + def __init__( + self, + input_channels: int, + squeeze_channels: int, + activation: Callable[..., torch.nn.Module] = torch.nn.ReLU, + scale_activation: Callable[..., torch.nn.Module] = torch.nn.Sigmoid, + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.avgpool = torch.nn.AdaptiveAvgPool2d(1) + self.fc1 = torch.nn.Conv2d(input_channels, squeeze_channels, 1) + self.fc2 = torch.nn.Conv2d(squeeze_channels, input_channels, 1) + self.activation = activation() + self.scale_activation = scale_activation() + + def _scale(self, input: Tensor) -> Tensor: + scale = self.avgpool(input) + scale = self.fc1(scale) + scale = self.activation(scale) + scale = self.fc2(scale) + return self.scale_activation(scale) + + def forward(self, input: Tensor) -> Tensor: + scale = self._scale(input) + return scale * input + + +class MLP(torch.nn.Sequential): + """This block implements the multi-layer perceptron (MLP) module. + + Args: + in_channels (int): Number of channels of the input + hidden_channels (List[int]): List of the hidden channel dimensions + norm_layer (Callable[..., torch.nn.Module], optional): Norm layer that will be stacked on top of the linear layer. If ``None`` this layer won't be used. Default: ``None`` + activation_layer (Callable[..., torch.nn.Module], optional): Activation function which will be stacked on top of the normalization layer (if not None), otherwise on top of the linear layer. If ``None`` this layer won't be used. Default: ``torch.nn.ReLU`` + inplace (bool, optional): Parameter for the activation layer, which can optionally do the operation in-place. + Default is ``None``, which uses the respective default values of the ``activation_layer`` and Dropout layer. + bias (bool): Whether to use bias in the linear layer. Default ``True`` + dropout (float): The probability for the dropout layer. Default: 0.0 + """ + + def __init__( + self, + in_channels: int, + hidden_channels: list[int], + norm_layer: Optional[Callable[..., torch.nn.Module]] = None, + activation_layer: Optional[Callable[..., torch.nn.Module]] = torch.nn.ReLU, + inplace: Optional[bool] = None, + bias: bool = True, + dropout: float = 0.0, + ): + # The addition of `norm_layer` is inspired from the implementation of TorchMultimodal: + # https://github.com/facebookresearch/multimodal/blob/5dec8a/torchmultimodal/modules/layers/mlp.py + params = {} if inplace is None else {"inplace": inplace} + + layers = [] + in_dim = in_channels + for hidden_dim in hidden_channels[:-1]: + layers.append(torch.nn.Linear(in_dim, hidden_dim, bias=bias)) + if norm_layer is not None: + layers.append(norm_layer(hidden_dim)) + layers.append(activation_layer(**params)) + layers.append(torch.nn.Dropout(dropout, **params)) + in_dim = hidden_dim + + layers.append(torch.nn.Linear(in_dim, hidden_channels[-1], bias=bias)) + layers.append(torch.nn.Dropout(dropout, **params)) + + super().__init__(*layers) + _log_api_usage_once(self) + + +class Permute(torch.nn.Module): + """This module returns a view of the tensor input with its dimensions permuted. + + Args: + dims (List[int]): The desired ordering of dimensions + """ + + def __init__(self, dims: list[int]): + super().__init__() + self.dims = dims + + def forward(self, x: Tensor) -> Tensor: + return torch.permute(x, self.dims) diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/poolers.py b/.venv/lib/python3.12/site-packages/torchvision/ops/poolers.py new file mode 100644 index 0000000000000000000000000000000000000000..f887f6aee332e8785f2a6596fe0c11f66264cb88 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/poolers.py @@ -0,0 +1,327 @@ +from typing import Optional, Union + +import torch +import torch.fx +import torchvision +from torch import nn, Tensor +from torchvision.ops.boxes import box_area + +from ..utils import _log_api_usage_once +from .roi_align import roi_align + + +# copying result_idx_in_level to a specific index in result[] +# is not supported by ONNX tracing yet. +# _onnx_merge_levels() is an implementation supported by ONNX +# that merges the levels to the right indices +@torch.jit.unused +def _onnx_merge_levels(levels: Tensor, unmerged_results: list[Tensor]) -> Tensor: + first_result = unmerged_results[0] + dtype, device = first_result.dtype, first_result.device + res = torch.zeros( + (levels.size(0), first_result.size(1), first_result.size(2), first_result.size(3)), dtype=dtype, device=device + ) + for level in range(len(unmerged_results)): + index = torch.where(levels == level)[0].view(-1, 1, 1, 1) + index = index.expand( + index.size(0), + unmerged_results[level].size(1), + unmerged_results[level].size(2), + unmerged_results[level].size(3), + ) + res = res.scatter(0, index, unmerged_results[level]) + return res + + +# TODO: (eellison) T54974082 https://github.com/pytorch/pytorch/issues/26744/pytorch/issues/26744 +def initLevelMapper( + k_min: int, + k_max: int, + canonical_scale: int = 224, + canonical_level: int = 4, + eps: float = 1e-6, +): + return LevelMapper(k_min, k_max, canonical_scale, canonical_level, eps) + + +class LevelMapper: + """Determine which FPN level each RoI in a set of RoIs should map to based + on the heuristic in the FPN paper. + + Args: + k_min (int) + k_max (int) + canonical_scale (int) + canonical_level (int) + eps (float) + """ + + def __init__( + self, + k_min: int, + k_max: int, + canonical_scale: int = 224, + canonical_level: int = 4, + eps: float = 1e-6, + ): + self.k_min = k_min + self.k_max = k_max + self.s0 = canonical_scale + self.lvl0 = canonical_level + self.eps = eps + + def __call__(self, boxlists: list[Tensor]) -> Tensor: + """ + Args: + boxlists (list[BoxList]) + """ + # Compute level ids + s = torch.sqrt(torch.cat([box_area(boxlist) for boxlist in boxlists])) + + # Eqn.(1) in FPN paper + target_lvls = torch.floor(self.lvl0 + torch.log2(s / self.s0) + torch.tensor(self.eps, dtype=s.dtype)) + target_lvls = torch.clamp(target_lvls, min=self.k_min, max=self.k_max) + return (target_lvls.to(torch.int64) - self.k_min).to(torch.int64) + + +def _convert_to_roi_format(boxes: list[Tensor]) -> Tensor: + concat_boxes = torch.cat(boxes, dim=0) + device, dtype = concat_boxes.device, concat_boxes.dtype + ids = torch.cat( + [torch.full_like(b[:, :1], i, dtype=dtype, layout=torch.strided, device=device) for i, b in enumerate(boxes)], + dim=0, + ) + rois = torch.cat([ids, concat_boxes], dim=1) + return rois + + +def _infer_scale(feature: Tensor, original_size: list[int]) -> float: + # assumption: the scale is of the form 2 ** (-k), with k integer + size = feature.shape[-2:] + possible_scales: list[float] = [] + for s1, s2 in zip(size, original_size): + approx_scale = float(s1) / float(s2) + scale = 2 ** float(torch.tensor(approx_scale).log2().round()) + possible_scales.append(scale) + return possible_scales[0] + + +@torch.fx.wrap +def _setup_scales( + features: list[Tensor], image_shapes: list[tuple[int, int]], canonical_scale: int, canonical_level: int +) -> tuple[list[float], LevelMapper]: + if not image_shapes: + raise ValueError("images list should not be empty") + max_x = 0 + max_y = 0 + for shape in image_shapes: + max_x = max(shape[0], max_x) + max_y = max(shape[1], max_y) + original_input_shape = (max_x, max_y) + + scales = [_infer_scale(feat, original_input_shape) for feat in features] + # get the levels in the feature map by leveraging the fact that the network always + # downsamples by a factor of 2 at each level. + lvl_min = -torch.log2(torch.tensor(scales[0], dtype=torch.float32)).item() + lvl_max = -torch.log2(torch.tensor(scales[-1], dtype=torch.float32)).item() + + map_levels = initLevelMapper( + int(lvl_min), + int(lvl_max), + canonical_scale=canonical_scale, + canonical_level=canonical_level, + ) + return scales, map_levels + + +@torch.fx.wrap +def _filter_input(x: dict[str, Tensor], featmap_names: list[str]) -> list[Tensor]: + x_filtered = [] + for k, v in x.items(): + if k in featmap_names: + x_filtered.append(v) + return x_filtered + + +@torch.fx.wrap +def _multiscale_roi_align( + x_filtered: list[Tensor], + boxes: list[Tensor], + output_size: list[int], + sampling_ratio: int, + scales: Optional[list[float]], + mapper: Optional[LevelMapper], +) -> Tensor: + """ + Args: + x_filtered (List[Tensor]): List of input tensors. + boxes (List[Tensor[N, 4]]): boxes to be used to perform the pooling operation, in + (x1, y1, x2, y2) format and in the image reference size, not the feature map + reference. The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + output_size (Union[List[Tuple[int, int]], List[int]]): size of the output + sampling_ratio (int): sampling ratio for ROIAlign + scales (Optional[List[float]]): If None, scales will be automatically inferred. Default value is None. + mapper (Optional[LevelMapper]): If none, mapper will be automatically inferred. Default value is None. + Returns: + result (Tensor) + """ + if scales is None or mapper is None: + raise ValueError("scales and mapper should not be None") + + num_levels = len(x_filtered) + rois = _convert_to_roi_format(boxes) + + if num_levels == 1: + return roi_align( + x_filtered[0], + rois, + output_size=output_size, + spatial_scale=scales[0], + sampling_ratio=sampling_ratio, + ) + + levels = mapper(boxes) + + num_rois = len(rois) + num_channels = x_filtered[0].shape[1] + + dtype, device = x_filtered[0].dtype, x_filtered[0].device + result = torch.zeros( + ( + num_rois, + num_channels, + ) + + output_size, + dtype=dtype, + device=device, + ) + + tracing_results = [] + for level, (per_level_feature, scale) in enumerate(zip(x_filtered, scales)): + idx_in_level = torch.where(levels == level)[0] + rois_per_level = rois[idx_in_level] + + result_idx_in_level = roi_align( + per_level_feature, + rois_per_level, + output_size=output_size, + spatial_scale=scale, + sampling_ratio=sampling_ratio, + ) + + if torchvision._is_tracing(): + tracing_results.append(result_idx_in_level.to(dtype)) + else: + # result and result_idx_in_level's dtypes are based on dtypes of different + # elements in x_filtered. x_filtered contains tensors output by different + # layers. When autocast is active, it may choose different dtypes for + # different layers' outputs. Therefore, we defensively match result's dtype + # before copying elements from result_idx_in_level in the following op. + # We need to cast manually (can't rely on autocast to cast for us) because + # the op acts on result in-place, and autocast only affects out-of-place ops. + result[idx_in_level] = result_idx_in_level.to(result.dtype) + + if torchvision._is_tracing(): + result = _onnx_merge_levels(levels, tracing_results) + + return result + + +class MultiScaleRoIAlign(nn.Module): + """ + Multi-scale RoIAlign pooling, which is useful for detection with or without FPN. + + It infers the scale of the pooling via the heuristics specified in eq. 1 + of the `Feature Pyramid Network paper `_. + They keyword-only parameters ``canonical_scale`` and ``canonical_level`` + correspond respectively to ``224`` and ``k0=4`` in eq. 1, and + have the following meaning: ``canonical_level`` is the target level of the pyramid from + which to pool a region of interest with ``w x h = canonical_scale x canonical_scale``. + + Args: + featmap_names (List[str]): the names of the feature maps that will be used + for the pooling. + output_size (List[Tuple[int, int]] or List[int]): output size for the pooled region + sampling_ratio (int): sampling ratio for ROIAlign + canonical_scale (int, optional): canonical_scale for LevelMapper + canonical_level (int, optional): canonical_level for LevelMapper + + Examples:: + + >>> m = torchvision.ops.MultiScaleRoIAlign(['feat1', 'feat3'], 3, 2) + >>> i = OrderedDict() + >>> i['feat1'] = torch.rand(1, 5, 64, 64) + >>> i['feat2'] = torch.rand(1, 5, 32, 32) # this feature won't be used in the pooling + >>> i['feat3'] = torch.rand(1, 5, 16, 16) + >>> # create some random bounding boxes + >>> boxes = torch.rand(6, 4) * 256; boxes[:, 2:] += boxes[:, :2] + >>> # original image size, before computing the feature maps + >>> image_sizes = [(512, 512)] + >>> output = m(i, [boxes], image_sizes) + >>> print(output.shape) + >>> torch.Size([6, 5, 3, 3]) + + """ + + __annotations__ = {"scales": Optional[list[float]], "map_levels": Optional[LevelMapper]} + + def __init__( + self, + featmap_names: list[str], + output_size: Union[int, tuple[int], list[int]], + sampling_ratio: int, + *, + canonical_scale: int = 224, + canonical_level: int = 4, + ): + super().__init__() + _log_api_usage_once(self) + if isinstance(output_size, int): + output_size = (output_size, output_size) + self.featmap_names = featmap_names + self.sampling_ratio = sampling_ratio + self.output_size = tuple(output_size) + self.scales = None + self.map_levels = None + self.canonical_scale = canonical_scale + self.canonical_level = canonical_level + + def forward( + self, + x: dict[str, Tensor], + boxes: list[Tensor], + image_shapes: list[tuple[int, int]], + ) -> Tensor: + """ + Args: + x (OrderedDict[Tensor]): feature maps for each level. They are assumed to have + all the same number of channels, but they can have different sizes. + boxes (List[Tensor[N, 4]]): boxes to be used to perform the pooling operation, in + (x1, y1, x2, y2) format and in the image reference size, not the feature map + reference. The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + image_shapes (List[Tuple[height, width]]): the sizes of each image before they + have been fed to a CNN to obtain feature maps. This allows us to infer the + scale factor for each one of the levels to be pooled. + Returns: + result (Tensor) + """ + x_filtered = _filter_input(x, self.featmap_names) + if self.scales is None or self.map_levels is None: + self.scales, self.map_levels = _setup_scales( + x_filtered, image_shapes, self.canonical_scale, self.canonical_level + ) + + return _multiscale_roi_align( + x_filtered, + boxes, + self.output_size, + self.sampling_ratio, + self.scales, + self.map_levels, + ) + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(featmap_names={self.featmap_names}, " + f"output_size={self.output_size}, sampling_ratio={self.sampling_ratio})" + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/ps_roi_align.py b/.venv/lib/python3.12/site-packages/torchvision/ops/ps_roi_align.py new file mode 100644 index 0000000000000000000000000000000000000000..82809b8f8885667b28eccd22aca60d1dca02f3bf --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/ps_roi_align.py @@ -0,0 +1,90 @@ +import torch +import torch.fx +from torch import nn, Tensor +from torch.nn.modules.utils import _pair +from torchvision.extension import _assert_has_ops + +from ..utils import _log_api_usage_once +from ._utils import check_roi_boxes_shape, convert_boxes_to_roi_format + + +@torch.fx.wrap +def ps_roi_align( + input: Tensor, + boxes: Tensor, + output_size: int, + spatial_scale: float = 1.0, + sampling_ratio: int = -1, +) -> Tensor: + """ + Performs Position-Sensitive Region of Interest (RoI) Align operator + mentioned in Light-Head R-CNN. + + Args: + input (Tensor[N, C, H, W]): The input tensor, i.e. a batch with ``N`` elements. Each element + contains ``C`` feature maps of dimensions ``H x W``. + boxes (Tensor[K, 5] or List[Tensor[L, 4]]): the box coordinates in (x1, y1, x2, y2) + format where the regions will be taken from. + The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + If a single Tensor is passed, then the first column should + contain the index of the corresponding element in the batch, i.e. a number in ``[0, N - 1]``. + If a list of Tensors is passed, then each Tensor will correspond to the boxes for an element i + in the batch. + output_size (int or Tuple[int, int]): the size of the output (in bins or pixels) after the pooling + is performed, as (height, width). + spatial_scale (float): a scaling factor that maps the box coordinates to + the input coordinates. For example, if your boxes are defined on the scale + of a 224x224 image and your input is a 112x112 feature map (resulting from a 0.5x scaling of + the original image), you'll want to set this to 0.5. Default: 1.0 + sampling_ratio (int): number of sampling points in the interpolation grid + used to compute the output value of each pooled output bin. If > 0, + then exactly ``sampling_ratio x sampling_ratio`` sampling points per bin are used. If + <= 0, then an adaptive number of grid points are used (computed as + ``ceil(roi_width / output_width)``, and likewise for height). Default: -1 + + Returns: + Tensor[K, C / (output_size[0] * output_size[1]), output_size[0], output_size[1]]: The pooled RoIs + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(ps_roi_align) + _assert_has_ops() + check_roi_boxes_shape(boxes) + rois = boxes + output_size = _pair(output_size) + if not isinstance(rois, torch.Tensor): + rois = convert_boxes_to_roi_format(rois) + output, _ = torch.ops.torchvision.ps_roi_align( + input, rois, spatial_scale, output_size[0], output_size[1], sampling_ratio + ) + return output + + +class PSRoIAlign(nn.Module): + """ + See :func:`ps_roi_align`. + """ + + def __init__( + self, + output_size: int, + spatial_scale: float, + sampling_ratio: int, + ): + super().__init__() + _log_api_usage_once(self) + self.output_size = output_size + self.spatial_scale = spatial_scale + self.sampling_ratio = sampling_ratio + + def forward(self, input: Tensor, rois: Tensor) -> Tensor: + return ps_roi_align(input, rois, self.output_size, self.spatial_scale, self.sampling_ratio) + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"output_size={self.output_size}" + f", spatial_scale={self.spatial_scale}" + f", sampling_ratio={self.sampling_ratio}" + f")" + ) + return s diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/ps_roi_pool.py b/.venv/lib/python3.12/site-packages/torchvision/ops/ps_roi_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..15292dcad97490aaa740cdec2d0aedb31e5662eb --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/ps_roi_pool.py @@ -0,0 +1,70 @@ +import torch +import torch.fx +from torch import nn, Tensor +from torch.nn.modules.utils import _pair +from torchvision.extension import _assert_has_ops + +from ..utils import _log_api_usage_once +from ._utils import check_roi_boxes_shape, convert_boxes_to_roi_format + + +@torch.fx.wrap +def ps_roi_pool( + input: Tensor, + boxes: Tensor, + output_size: int, + spatial_scale: float = 1.0, +) -> Tensor: + """ + Performs Position-Sensitive Region of Interest (RoI) Pool operator + described in R-FCN + + Args: + input (Tensor[N, C, H, W]): The input tensor, i.e. a batch with ``N`` elements. Each element + contains ``C`` feature maps of dimensions ``H x W``. + boxes (Tensor[K, 5] or List[Tensor[L, 4]]): the box coordinates in (x1, y1, x2, y2) + format where the regions will be taken from. + The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + If a single Tensor is passed, then the first column should + contain the index of the corresponding element in the batch, i.e. a number in ``[0, N - 1]``. + If a list of Tensors is passed, then each Tensor will correspond to the boxes for an element i + in the batch. + output_size (int or Tuple[int, int]): the size of the output (in bins or pixels) after the pooling + is performed, as (height, width). + spatial_scale (float): a scaling factor that maps the box coordinates to + the input coordinates. For example, if your boxes are defined on the scale + of a 224x224 image and your input is a 112x112 feature map (resulting from a 0.5x scaling of + the original image), you'll want to set this to 0.5. Default: 1.0 + + Returns: + Tensor[K, C / (output_size[0] * output_size[1]), output_size[0], output_size[1]]: The pooled RoIs. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(ps_roi_pool) + _assert_has_ops() + check_roi_boxes_shape(boxes) + rois = boxes + output_size = _pair(output_size) + if not isinstance(rois, torch.Tensor): + rois = convert_boxes_to_roi_format(rois) + output, _ = torch.ops.torchvision.ps_roi_pool(input, rois, spatial_scale, output_size[0], output_size[1]) + return output + + +class PSRoIPool(nn.Module): + """ + See :func:`ps_roi_pool`. + """ + + def __init__(self, output_size: int, spatial_scale: float): + super().__init__() + _log_api_usage_once(self) + self.output_size = output_size + self.spatial_scale = spatial_scale + + def forward(self, input: Tensor, rois: Tensor) -> Tensor: + return ps_roi_pool(input, rois, self.output_size, self.spatial_scale) + + def __repr__(self) -> str: + s = f"{self.__class__.__name__}(output_size={self.output_size}, spatial_scale={self.spatial_scale})" + return s diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/roi_align.py b/.venv/lib/python3.12/site-packages/torchvision/ops/roi_align.py new file mode 100644 index 0000000000000000000000000000000000000000..facd5fb219c25d9c57278a6d2c2c5b9f7dfe1a02 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/roi_align.py @@ -0,0 +1,319 @@ +import functools +from typing import Union + +import torch +import torch.fx +from torch import nn, Tensor +from torch._dynamo.utils import is_compile_supported +from torch.jit.annotations import BroadcastingList2 +from torch.nn.modules.utils import _pair +from torchvision.extension import _assert_has_ops, _has_ops + +from ..utils import _log_api_usage_once +from ._utils import check_roi_boxes_shape, convert_boxes_to_roi_format + + +def lazy_compile(**compile_kwargs): + """Lazily wrap a function with torch.compile on the first call + + This avoids eagerly importing dynamo. + """ + + def decorate_fn(fn): + @functools.wraps(fn) + def compile_hook(*args, **kwargs): + compiled_fn = torch.compile(fn, **compile_kwargs) + globals()[fn.__name__] = functools.wraps(fn)(compiled_fn) + return compiled_fn(*args, **kwargs) + + return compile_hook + + return decorate_fn + + +# NB: all inputs are tensors +def _bilinear_interpolate( + input, # [N, C, H, W] + roi_batch_ind, # [K] + y, # [K, PH, IY] + x, # [K, PW, IX] + ymask, # [K, IY] + xmask, # [K, IX] +): + _, channels, height, width = input.size() + + # deal with inverse element out of feature map boundary + y = y.clamp(min=0) + x = x.clamp(min=0) + y_low = y.int() + x_low = x.int() + y_high = torch.where(y_low >= height - 1, height - 1, y_low + 1) + y_low = torch.where(y_low >= height - 1, height - 1, y_low) + y = torch.where(y_low >= height - 1, y.to(input.dtype), y) + + x_high = torch.where(x_low >= width - 1, width - 1, x_low + 1) + x_low = torch.where(x_low >= width - 1, width - 1, x_low) + x = torch.where(x_low >= width - 1, x.to(input.dtype), x) + + ly = y - y_low + lx = x - x_low + hy = 1.0 - ly + hx = 1.0 - lx + + # do bilinear interpolation, but respect the masking! + # TODO: It's possible the masking here is unnecessary if y and + # x were clamped appropriately; hard to tell + def masked_index( + y, # [K, PH, IY] + x, # [K, PW, IX] + ): + if ymask is not None: + assert xmask is not None + y = torch.where(ymask[:, None, :], y, 0) + x = torch.where(xmask[:, None, :], x, 0) + return input[ + roi_batch_ind[:, None, None, None, None, None], + torch.arange(channels, device=input.device)[None, :, None, None, None, None], + y[:, None, :, None, :, None], # prev [K, PH, IY] + x[:, None, None, :, None, :], # prev [K, PW, IX] + ] # [K, C, PH, PW, IY, IX] + + v1 = masked_index(y_low, x_low) + v2 = masked_index(y_low, x_high) + v3 = masked_index(y_high, x_low) + v4 = masked_index(y_high, x_high) + + # all ws preemptively [K, C, PH, PW, IY, IX] + def outer_prod(y, x): + return y[:, None, :, None, :, None] * x[:, None, None, :, None, :] + + w1 = outer_prod(hy, hx) + w2 = outer_prod(hy, lx) + w3 = outer_prod(ly, hx) + w4 = outer_prod(ly, lx) + + val = w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4 + return val + + +# TODO: this doesn't actually cache +# TODO: main library should make this easier to do +def maybe_cast(tensor): + if torch.is_autocast_enabled() and tensor.is_cuda and tensor.dtype != torch.double: + return tensor.float() + else: + return tensor + + +# This is a pure Python and differentiable implementation of roi_align. When +# run in eager mode, it uses a lot of memory, but when compiled it has +# acceptable memory usage. The main point of this implementation is that +# its backwards is deterministic. +# It is transcribed directly off of the roi_align CUDA kernel, see +# https://dev-discuss.pytorch.org/t/a-pure-python-implementation-of-roi-align-that-looks-just-like-its-cuda-kernel/1266 +@lazy_compile(dynamic=True) +def _roi_align(input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio, aligned): + orig_dtype = input.dtype + + input = maybe_cast(input) + rois = maybe_cast(rois) + + _, _, height, width = input.size() + + ph = torch.arange(pooled_height, device=input.device) # [PH] + pw = torch.arange(pooled_width, device=input.device) # [PW] + + # input: [N, C, H, W] + # rois: [K, 5] + + roi_batch_ind = rois[:, 0].int() # [K] + offset = 0.5 if aligned else 0.0 + roi_start_w = rois[:, 1] * spatial_scale - offset # [K] + roi_start_h = rois[:, 2] * spatial_scale - offset # [K] + roi_end_w = rois[:, 3] * spatial_scale - offset # [K] + roi_end_h = rois[:, 4] * spatial_scale - offset # [K] + + roi_width = roi_end_w - roi_start_w # [K] + roi_height = roi_end_h - roi_start_h # [K] + if not aligned: + roi_width = torch.clamp(roi_width, min=1.0) # [K] + roi_height = torch.clamp(roi_height, min=1.0) # [K] + + bin_size_h = roi_height / pooled_height # [K] + bin_size_w = roi_width / pooled_width # [K] + + exact_sampling = sampling_ratio > 0 + + roi_bin_grid_h = sampling_ratio if exact_sampling else torch.ceil(roi_height / pooled_height) # scalar or [K] + roi_bin_grid_w = sampling_ratio if exact_sampling else torch.ceil(roi_width / pooled_width) # scalar or [K] + + """ + iy, ix = dims(2) + """ + + if exact_sampling: + count = max(roi_bin_grid_h * roi_bin_grid_w, 1) # scalar + iy = torch.arange(roi_bin_grid_h, device=input.device) # [IY] + ix = torch.arange(roi_bin_grid_w, device=input.device) # [IX] + ymask = None + xmask = None + else: + count = torch.clamp(roi_bin_grid_h * roi_bin_grid_w, min=1) # [K] + # When doing adaptive sampling, the number of samples we need to do + # is data-dependent based on how big the ROIs are. This is a bit + # awkward because first-class dims can't actually handle this. + # So instead, we inefficiently suppose that we needed to sample ALL + # the points and mask out things that turned out to be unnecessary + iy = torch.arange(height, device=input.device) # [IY] + ix = torch.arange(width, device=input.device) # [IX] + ymask = iy[None, :] < roi_bin_grid_h[:, None] # [K, IY] + xmask = ix[None, :] < roi_bin_grid_w[:, None] # [K, IX] + + def from_K(t): + return t[:, None, None] + + y = ( + from_K(roi_start_h) + + ph[None, :, None] * from_K(bin_size_h) + + (iy[None, None, :] + 0.5).to(input.dtype) * from_K(bin_size_h / roi_bin_grid_h) + ) # [K, PH, IY] + x = ( + from_K(roi_start_w) + + pw[None, :, None] * from_K(bin_size_w) + + (ix[None, None, :] + 0.5).to(input.dtype) * from_K(bin_size_w / roi_bin_grid_w) + ) # [K, PW, IX] + val = _bilinear_interpolate(input, roi_batch_ind, y, x, ymask, xmask) # [K, C, PH, PW, IY, IX] + + # Mask out samples that weren't actually adaptively needed + if not exact_sampling: + val = torch.where(ymask[:, None, None, None, :, None], val, 0) + val = torch.where(xmask[:, None, None, None, None, :], val, 0) + + output = val.sum((-1, -2)) # remove IY, IX ~> [K, C, PH, PW] + if isinstance(count, torch.Tensor): + output /= count[:, None, None, None] + else: + output /= count + + output = output.to(orig_dtype) + + return output + + +@torch.fx.wrap +def roi_align( + input: Tensor, + boxes: Union[Tensor, list[Tensor]], + output_size: BroadcastingList2[int], + spatial_scale: float = 1.0, + sampling_ratio: int = -1, + aligned: bool = False, +) -> Tensor: + """ + Performs Region of Interest (RoI) Align operator with average pooling, as described in Mask R-CNN. + + Args: + input (Tensor[N, C, H, W]): The input tensor, i.e. a batch with ``N`` elements. Each element + contains ``C`` feature maps of dimensions ``H x W``. + If the tensor is quantized, we expect a batch size of ``N == 1``. + boxes (Tensor[K, 5] or List[Tensor[L, 4]]): the box coordinates in (x1, y1, x2, y2) + format where the regions will be taken from. + The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + If a single Tensor is passed, then the first column should + contain the index of the corresponding element in the batch, i.e. a number in ``[0, N - 1]``. + If a list of Tensors is passed, then each Tensor will correspond to the boxes for an element i + in the batch. + output_size (int or Tuple[int, int]): the size of the output (in bins or pixels) after the pooling + is performed, as (height, width). + spatial_scale (float): a scaling factor that maps the box coordinates to + the input coordinates. For example, if your boxes are defined on the scale + of a 224x224 image and your input is a 112x112 feature map (resulting from a 0.5x scaling of + the original image), you'll want to set this to 0.5. Default: 1.0 + sampling_ratio (int): number of sampling points in the interpolation grid + used to compute the output value of each pooled output bin. If > 0, + then exactly ``sampling_ratio x sampling_ratio`` sampling points per bin are used. If + <= 0, then an adaptive number of grid points are used (computed as + ``ceil(roi_width / output_width)``, and likewise for height). Default: -1 + aligned (bool): If False, use the legacy implementation. + If True, pixel shift the box coordinates it by -0.5 for a better alignment with the two + neighboring pixel indices. This version is used in Detectron2 + + Returns: + Tensor[K, C, output_size[0], output_size[1]]: The pooled RoIs. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(roi_align) + check_roi_boxes_shape(boxes) + rois = boxes + output_size = _pair(output_size) + if not isinstance(rois, torch.Tensor): + rois = convert_boxes_to_roi_format(rois) + if not torch.jit.is_scripting() and input.is_quantized: + _assert_has_ops() + input_scale = input.q_scale() + input_zero_point = input.q_zero_point() + int_data = input.int_repr() + if not rois.is_quantized: + raise ValueError("If input is quantized, rois must also be quantized.") + rois_scale = rois.q_scale() + rois_zero_point = rois.q_zero_point() + rois_int = rois.int_repr() + out_int = torch.ops.torchvision.qroi_align( + int_data, + rois_int, + input_scale, + input_zero_point, + rois_scale, + rois_zero_point, + spatial_scale, + output_size[0], + output_size[1], + sampling_ratio, + aligned, + ) + return torch._make_per_tensor_quantized_tensor(out_int, scale=input_scale, zero_point=input_zero_point) + + if not torch.jit.is_scripting(): + if ( + not _has_ops() + or (torch.are_deterministic_algorithms_enabled() and (input.is_cuda or input.is_mps or input.is_xpu)) + ) and is_compile_supported(input.device.type): + return _roi_align(input, rois, spatial_scale, output_size[0], output_size[1], sampling_ratio, aligned) + _assert_has_ops() + return torch.ops.torchvision.roi_align( + input, rois, spatial_scale, output_size[0], output_size[1], sampling_ratio, aligned + ) + + +class RoIAlign(nn.Module): + """ + See :func:`roi_align`. + """ + + def __init__( + self, + output_size: BroadcastingList2[int], + spatial_scale: float, + sampling_ratio: int, + aligned: bool = False, + ): + super().__init__() + _log_api_usage_once(self) + self.output_size = output_size + self.spatial_scale = spatial_scale + self.sampling_ratio = sampling_ratio + self.aligned = aligned + + def forward(self, input: Tensor, rois: Union[Tensor, list[Tensor]]) -> Tensor: + return roi_align(input, rois, self.output_size, self.spatial_scale, self.sampling_ratio, self.aligned) + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"output_size={self.output_size}" + f", spatial_scale={self.spatial_scale}" + f", sampling_ratio={self.sampling_ratio}" + f", aligned={self.aligned}" + f")" + ) + return s diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/roi_pool.py b/.venv/lib/python3.12/site-packages/torchvision/ops/roi_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..5f4bb95c0f3e49da94ef46d9f85f9f449531b632 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/roi_pool.py @@ -0,0 +1,72 @@ +from typing import Union + +import torch +import torch.fx +from torch import nn, Tensor +from torch.jit.annotations import BroadcastingList2 +from torch.nn.modules.utils import _pair +from torchvision.extension import _assert_has_ops + +from ..utils import _log_api_usage_once +from ._utils import check_roi_boxes_shape, convert_boxes_to_roi_format + + +@torch.fx.wrap +def roi_pool( + input: Tensor, + boxes: Union[Tensor, list[Tensor]], + output_size: BroadcastingList2[int], + spatial_scale: float = 1.0, +) -> Tensor: + """ + Performs Region of Interest (RoI) Pool operator described in Fast R-CNN + + Args: + input (Tensor[N, C, H, W]): The input tensor, i.e. a batch with ``N`` elements. Each element + contains ``C`` feature maps of dimensions ``H x W``. + boxes (Tensor[K, 5] or List[Tensor[L, 4]]): the box coordinates in (x1, y1, x2, y2) + format where the regions will be taken from. + The coordinate must satisfy ``0 <= x1 < x2`` and ``0 <= y1 < y2``. + If a single Tensor is passed, then the first column should + contain the index of the corresponding element in the batch, i.e. a number in ``[0, N - 1]``. + If a list of Tensors is passed, then each Tensor will correspond to the boxes for an element i + in the batch. + output_size (int or Tuple[int, int]): the size of the output after the cropping + is performed, as (height, width) + spatial_scale (float): a scaling factor that maps the box coordinates to + the input coordinates. For example, if your boxes are defined on the scale + of a 224x224 image and your input is a 112x112 feature map (resulting from a 0.5x scaling of + the original image), you'll want to set this to 0.5. Default: 1.0 + + Returns: + Tensor[K, C, output_size[0], output_size[1]]: The pooled RoIs. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(roi_pool) + _assert_has_ops() + check_roi_boxes_shape(boxes) + rois = boxes + output_size = _pair(output_size) + if not isinstance(rois, torch.Tensor): + rois = convert_boxes_to_roi_format(rois) + output, _ = torch.ops.torchvision.roi_pool(input, rois, spatial_scale, output_size[0], output_size[1]) + return output + + +class RoIPool(nn.Module): + """ + See :func:`roi_pool`. + """ + + def __init__(self, output_size: BroadcastingList2[int], spatial_scale: float): + super().__init__() + _log_api_usage_once(self) + self.output_size = output_size + self.spatial_scale = spatial_scale + + def forward(self, input: Tensor, rois: Union[Tensor, list[Tensor]]) -> Tensor: + return roi_pool(input, rois, self.output_size, self.spatial_scale) + + def __repr__(self) -> str: + s = f"{self.__class__.__name__}(output_size={self.output_size}, spatial_scale={self.spatial_scale})" + return s diff --git a/.venv/lib/python3.12/site-packages/torchvision/ops/stochastic_depth.py b/.venv/lib/python3.12/site-packages/torchvision/ops/stochastic_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..ff8167b2315e941f7e31a0626eeec270d350a710 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/ops/stochastic_depth.py @@ -0,0 +1,66 @@ +import torch +import torch.fx +from torch import nn, Tensor + +from ..utils import _log_api_usage_once + + +def stochastic_depth(input: Tensor, p: float, mode: str, training: bool = True) -> Tensor: + """ + Implements the Stochastic Depth from `"Deep Networks with Stochastic Depth" + `_ used for randomly dropping residual + branches of residual architectures. + + Args: + input (Tensor[N, ...]): The input tensor or arbitrary dimensions with the first one + being its batch i.e. a batch with ``N`` rows. + p (float): probability of the input to be zeroed. + mode (str): ``"batch"`` or ``"row"``. + ``"batch"`` randomly zeroes the entire input, ``"row"`` zeroes + randomly selected rows from the batch. + training: apply stochastic depth if is ``True``. Default: ``True`` + + Returns: + Tensor[N, ...]: The randomly zeroed tensor. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(stochastic_depth) + if p < 0.0 or p > 1.0: + raise ValueError(f"drop probability has to be between 0 and 1, but got {p}") + if mode not in ["batch", "row"]: + raise ValueError(f"mode has to be either 'batch' or 'row', but got {mode}") + if not training or p == 0.0: + return input + + survival_rate = 1.0 - p + if mode == "row": + size = [input.shape[0]] + [1] * (input.ndim - 1) + else: + size = [1] * input.ndim + noise = torch.empty(size, dtype=input.dtype, device=input.device) + noise = noise.bernoulli_(survival_rate) + if survival_rate > 0.0: + noise.div_(survival_rate) + return input * noise + + +torch.fx.wrap("stochastic_depth") + + +class StochasticDepth(nn.Module): + """ + See :func:`stochastic_depth`. + """ + + def __init__(self, p: float, mode: str) -> None: + super().__init__() + _log_api_usage_once(self) + self.p = p + self.mode = mode + + def forward(self, input: Tensor) -> Tensor: + return stochastic_depth(input, self.p, self.mode, self.training) + + def __repr__(self) -> str: + s = f"{self.__class__.__name__}(p={self.p}, mode={self.mode})" + return s diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..77680a14f0d0599f4004a2ce5c299c0f5e13a0d5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/__init__.py @@ -0,0 +1,2 @@ +from .transforms import * +from .autoaugment import * diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e998a847ce5461d8992141959a29bde816d5500 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_functional_pil.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_functional_pil.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..911eb33ba5bd53faba1d8d4a30696debf5f4e4fc Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_functional_pil.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_functional_tensor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_functional_tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d035a343cef9c4464409d37ad87b7b28c950f76a Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_functional_tensor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_functional_video.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_functional_video.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0aff857db2385eb8cdd7fc55d5374fe9dc1a44e1 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_functional_video.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_presets.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_presets.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03af4fa492b686eaeaffd61e790d012d690c1db7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_presets.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_transforms_video.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_transforms_video.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae5077d1ce9b539e6fb1773535a1eb83233fd2c4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/_transforms_video.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/autoaugment.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/autoaugment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bcde345f6ffe6a870abc8a08a58b2e25d9c45b4 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/autoaugment.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/functional.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/functional.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c6857db83c5c6c13030ae8d44f7896959df1825 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/functional.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/transforms.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/transforms.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dc9f19c051354f912fe95b1387c0fb825a5a732 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/__pycache__/transforms.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb3eee69657549193d38ca397128b15af2660ee8a2d202099fad5e8b05629feb +size 115705 diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/_functional_pil.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/_functional_pil.py new file mode 100644 index 0000000000000000000000000000000000000000..56b806cf6edfe7657cce7a67562b53cf494ba814 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/_functional_pil.py @@ -0,0 +1,396 @@ +import numbers +from collections.abc import Sequence +from typing import Any, Literal, Optional, Union + +import numpy as np +import torch +from PIL import Image, ImageEnhance, ImageOps + +from ..utils import _Image_fromarray + +try: + import accimage +except ImportError: + accimage = None + + +@torch.jit.unused +def _is_pil_image(img: Any) -> bool: + if accimage is not None: + return isinstance(img, (Image.Image, accimage.Image)) + else: + return isinstance(img, Image.Image) + + +@torch.jit.unused +def get_dimensions(img: Any) -> list[int]: + if _is_pil_image(img): + if hasattr(img, "getbands"): + channels = len(img.getbands()) + else: + channels = img.channels + width, height = img.size + return [channels, height, width] + raise TypeError(f"Unexpected type {type(img)}") + + +@torch.jit.unused +def get_image_size(img: Any) -> list[int]: + if _is_pil_image(img): + return list(img.size) + raise TypeError(f"Unexpected type {type(img)}") + + +@torch.jit.unused +def get_image_num_channels(img: Any) -> int: + if _is_pil_image(img): + if hasattr(img, "getbands"): + return len(img.getbands()) + else: + return img.channels + raise TypeError(f"Unexpected type {type(img)}") + + +@torch.jit.unused +def hflip(img: Image.Image) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + return img.transpose(Image.FLIP_LEFT_RIGHT) + + +@torch.jit.unused +def vflip(img: Image.Image) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + return img.transpose(Image.FLIP_TOP_BOTTOM) + + +@torch.jit.unused +def adjust_brightness(img: Image.Image, brightness_factor: float) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + enhancer = ImageEnhance.Brightness(img) + img = enhancer.enhance(brightness_factor) + return img + + +@torch.jit.unused +def adjust_contrast(img: Image.Image, contrast_factor: float) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + enhancer = ImageEnhance.Contrast(img) + img = enhancer.enhance(contrast_factor) + return img + + +@torch.jit.unused +def adjust_saturation(img: Image.Image, saturation_factor: float) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + enhancer = ImageEnhance.Color(img) + img = enhancer.enhance(saturation_factor) + return img + + +@torch.jit.unused +def adjust_hue(img: Image.Image, hue_factor: float) -> Image.Image: + if not (-0.5 <= hue_factor <= 0.5): + raise ValueError(f"hue_factor ({hue_factor}) is not in [-0.5, 0.5].") + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + input_mode = img.mode + if input_mode in {"L", "1", "I", "F"}: + return img + + h, s, v = img.convert("HSV").split() + + np_h = np.array(h, dtype=np.uint8) + # This will over/underflow, as desired + np_h += np.int32(hue_factor * 255).astype(np.uint8) + + h = _Image_fromarray(np_h, "L") + + img = Image.merge("HSV", (h, s, v)).convert(input_mode) + return img + + +@torch.jit.unused +def adjust_gamma( + img: Image.Image, + gamma: float, + gain: float = 1.0, +) -> Image.Image: + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + if gamma < 0: + raise ValueError("Gamma should be a non-negative real number") + + input_mode = img.mode + img = img.convert("RGB") + gamma_map = [int((255 + 1 - 1e-3) * gain * pow(ele / 255.0, gamma)) for ele in range(256)] * 3 + img = img.point(gamma_map) # use PIL's point-function to accelerate this part + + img = img.convert(input_mode) + return img + + +@torch.jit.unused +def pad( + img: Image.Image, + padding: Union[int, list[int], tuple[int, ...]], + fill: Optional[Union[float, list[float], tuple[float, ...]]] = 0, + padding_mode: Literal["constant", "edge", "reflect", "symmetric"] = "constant", +) -> Image.Image: + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + if not isinstance(padding, (numbers.Number, tuple, list)): + raise TypeError("Got inappropriate padding arg") + if fill is not None and not isinstance(fill, (numbers.Number, tuple, list)): + raise TypeError("Got inappropriate fill arg") + if not isinstance(padding_mode, str): + raise TypeError("Got inappropriate padding_mode arg") + + if isinstance(padding, list): + padding = tuple(padding) + + if isinstance(padding, tuple) and len(padding) not in [1, 2, 4]: + raise ValueError(f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple") + + if isinstance(padding, tuple) and len(padding) == 1: + # Compatibility with `functional_tensor.pad` + padding = padding[0] + + if padding_mode not in ["constant", "edge", "reflect", "symmetric"]: + raise ValueError("Padding mode should be either constant, edge, reflect or symmetric") + + if padding_mode == "constant": + opts = _parse_fill(fill, img, name="fill") + if img.mode == "P": + palette = img.getpalette() + image = ImageOps.expand(img, border=padding, **opts) + image.putpalette(palette) + return image + + return ImageOps.expand(img, border=padding, **opts) + else: + if isinstance(padding, int): + pad_left = pad_right = pad_top = pad_bottom = padding + if isinstance(padding, tuple) and len(padding) == 2: + pad_left = pad_right = padding[0] + pad_top = pad_bottom = padding[1] + if isinstance(padding, tuple) and len(padding) == 4: + pad_left = padding[0] + pad_top = padding[1] + pad_right = padding[2] + pad_bottom = padding[3] + + p = [pad_left, pad_top, pad_right, pad_bottom] + cropping = -np.minimum(p, 0) + + if cropping.any(): + crop_left, crop_top, crop_right, crop_bottom = cropping + img = img.crop((crop_left, crop_top, img.width - crop_right, img.height - crop_bottom)) + + pad_left, pad_top, pad_right, pad_bottom = np.maximum(p, 0) + + if img.mode == "P": + palette = img.getpalette() + img = np.asarray(img) + img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), mode=padding_mode) + img = Image.fromarray(img) + img.putpalette(palette) + return img + + img = np.asarray(img) + # RGB image + if len(img.shape) == 3: + img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right), (0, 0)), padding_mode) + # Grayscale image + if len(img.shape) == 2: + img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode) + + return Image.fromarray(img) + + +@torch.jit.unused +def crop( + img: Image.Image, + top: int, + left: int, + height: int, + width: int, +) -> Image.Image: + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + return img.crop((left, top, left + width, top + height)) + + +@torch.jit.unused +def resize( + img: Image.Image, + size: Union[list[int], int], + interpolation: int = Image.BILINEAR, +) -> Image.Image: + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + if not (isinstance(size, list) and len(size) == 2): + raise TypeError(f"Got inappropriate size arg: {size}") + + return img.resize(tuple(size[::-1]), interpolation) + + +@torch.jit.unused +def _parse_fill( + fill: Optional[Union[float, list[float], tuple[float, ...]]], + img: Image.Image, + name: str = "fillcolor", +) -> dict[str, Optional[Union[float, list[float], tuple[float, ...]]]]: + + # Process fill color for affine transforms + num_channels = get_image_num_channels(img) + if fill is None: + fill = 0 + if isinstance(fill, (int, float)) and num_channels > 1: + fill = tuple([fill] * num_channels) + if isinstance(fill, (list, tuple)): + if len(fill) == 1: + fill = fill * num_channels + elif len(fill) != num_channels: + msg = "The number of elements in 'fill' does not match the number of channels of the image ({} != {})" + raise ValueError(msg.format(len(fill), num_channels)) + + fill = tuple(fill) # type: ignore[arg-type] + + if img.mode != "F": + if isinstance(fill, (list, tuple)): + fill = tuple(int(x) for x in fill) + else: + fill = int(fill) + + return {name: fill} + + +@torch.jit.unused +def affine( + img: Image.Image, + matrix: list[float], + interpolation: int = Image.NEAREST, + fill: Optional[Union[int, float, Sequence[int], Sequence[float]]] = None, +) -> Image.Image: + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + output_size = img.size + opts = _parse_fill(fill, img) + return img.transform(output_size, Image.AFFINE, matrix, interpolation, **opts) + + +@torch.jit.unused +def rotate( + img: Image.Image, + angle: float, + interpolation: int = Image.NEAREST, + expand: bool = False, + center: Optional[tuple[int, int]] = None, + fill: Optional[Union[int, float, Sequence[int], Sequence[float]]] = None, +) -> Image.Image: + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + opts = _parse_fill(fill, img) + return img.rotate(angle, interpolation, expand, center, **opts) + + +@torch.jit.unused +def perspective( + img: Image.Image, + perspective_coeffs: list[float], + interpolation: int = Image.BICUBIC, + fill: Optional[Union[int, float, Sequence[int], Sequence[float]]] = None, +) -> Image.Image: + + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + opts = _parse_fill(fill, img) + + return img.transform(img.size, Image.PERSPECTIVE, perspective_coeffs, interpolation, **opts) + + +@torch.jit.unused +def to_grayscale(img: Image.Image, num_output_channels: int) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + if num_output_channels == 1: + img = img.convert("L") + elif num_output_channels == 3: + img = img.convert("L") + np_img = np.array(img, dtype=np.uint8) + np_img = np.dstack([np_img, np_img, np_img]) + img = _Image_fromarray(np_img, "RGB") + else: + raise ValueError("num_output_channels should be either 1 or 3") + + return img + + +@torch.jit.unused +def invert(img: Image.Image) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + return ImageOps.invert(img) + + +@torch.jit.unused +def posterize(img: Image.Image, bits: int) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + return ImageOps.posterize(img, bits) + + +@torch.jit.unused +def solarize(img: Image.Image, threshold: int) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + return ImageOps.solarize(img, threshold) + + +@torch.jit.unused +def adjust_sharpness(img: Image.Image, sharpness_factor: float) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + + enhancer = ImageEnhance.Sharpness(img) + img = enhancer.enhance(sharpness_factor) + return img + + +@torch.jit.unused +def autocontrast(img: Image.Image) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + return ImageOps.autocontrast(img) + + +@torch.jit.unused +def equalize(img: Image.Image) -> Image.Image: + if not _is_pil_image(img): + raise TypeError(f"img should be PIL Image. Got {type(img)}") + return ImageOps.equalize(img) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/_functional_tensor.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/_functional_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..1a9830450d575db2e06a9b6aacb156dd5b56041a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/_functional_tensor.py @@ -0,0 +1,962 @@ +import warnings +from typing import Optional, Union + +import torch +from torch import Tensor +from torch.nn.functional import conv2d, grid_sample, interpolate, pad as torch_pad + + +def _is_tensor_a_torch_image(x: Tensor) -> bool: + return x.ndim >= 2 + + +def _assert_image_tensor(img: Tensor) -> None: + if not _is_tensor_a_torch_image(img): + raise TypeError("Tensor is not a torch image.") + + +def get_dimensions(img: Tensor) -> list[int]: + _assert_image_tensor(img) + channels = 1 if img.ndim == 2 else img.shape[-3] + height, width = img.shape[-2:] + return [channels, height, width] + + +def get_image_size(img: Tensor) -> list[int]: + # Returns (w, h) of tensor image + _assert_image_tensor(img) + return [img.shape[-1], img.shape[-2]] + + +def get_image_num_channels(img: Tensor) -> int: + _assert_image_tensor(img) + if img.ndim == 2: + return 1 + elif img.ndim > 2: + return img.shape[-3] + + raise TypeError(f"Input ndim should be 2 or more. Got {img.ndim}") + + +def _max_value(dtype: torch.dtype) -> int: + if dtype == torch.uint8: + return 255 + elif dtype == torch.int8: + return 127 + elif dtype == torch.int16: + return 32767 + elif dtype == torch.uint16: + return 65535 + elif dtype == torch.int32: + return 2147483647 + elif dtype == torch.int64: + return 9223372036854775807 + else: + # This is only here for completeness. This value is implicitly assumed in a lot of places so changing it is not + # easy. + return 1 + + +def _assert_channels(img: Tensor, permitted: list[int]) -> None: + c = get_dimensions(img)[0] + if c not in permitted: + raise TypeError(f"Input image tensor permitted channel values are {permitted}, but found {c}") + + +def convert_image_dtype(image: torch.Tensor, dtype: torch.dtype = torch.float) -> torch.Tensor: + if image.dtype == dtype: + return image + + if image.is_floating_point(): + + # TODO: replace with dtype.is_floating_point when torchscript supports it + if torch.tensor(0, dtype=dtype).is_floating_point(): + return image.to(dtype) + + # float to int + if (image.dtype == torch.float32 and dtype in (torch.int32, torch.int64)) or ( + image.dtype == torch.float64 and dtype == torch.int64 + ): + msg = f"The cast from {image.dtype} to {dtype} cannot be performed safely." + raise RuntimeError(msg) + + # https://github.com/pytorch/vision/pull/2078#issuecomment-612045321 + # For data in the range 0-1, (float * 255).to(uint) is only 255 + # when float is exactly 1.0. + # `max + 1 - epsilon` provides more evenly distributed mapping of + # ranges of floats to ints. + eps = 1e-3 + max_val = float(_max_value(dtype)) + result = image.mul(max_val + 1.0 - eps) + return result.to(dtype) + else: + input_max = float(_max_value(image.dtype)) + + # int to float + # TODO: replace with dtype.is_floating_point when torchscript supports it + if torch.tensor(0, dtype=dtype).is_floating_point(): + image = image.to(dtype) + return image / input_max + + output_max = float(_max_value(dtype)) + + # int to int + if input_max > output_max: + # factor should be forced to int for torch jit script + # otherwise factor is a float and image // factor can produce different results + factor = int((input_max + 1) // (output_max + 1)) + image = torch.div(image, factor, rounding_mode="floor") + return image.to(dtype) + else: + # factor should be forced to int for torch jit script + # otherwise factor is a float and image * factor can produce different results + factor = int((output_max + 1) // (input_max + 1)) + image = image.to(dtype) + return image * factor + + +def vflip(img: Tensor) -> Tensor: + _assert_image_tensor(img) + + return img.flip(-2) + + +def hflip(img: Tensor) -> Tensor: + _assert_image_tensor(img) + + return img.flip(-1) + + +def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor: + _assert_image_tensor(img) + + _, h, w = get_dimensions(img) + right = left + width + bottom = top + height + + if left < 0 or top < 0 or right > w or bottom > h: + padding_ltrb = [ + max(-left + min(0, right), 0), + max(-top + min(0, bottom), 0), + max(right - max(w, left), 0), + max(bottom - max(h, top), 0), + ] + return pad(img[..., max(top, 0) : bottom, max(left, 0) : right], padding_ltrb, fill=0) + return img[..., top:bottom, left:right] + + +def rgb_to_grayscale(img: Tensor, num_output_channels: int = 1) -> Tensor: + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + _assert_channels(img, [1, 3]) + + if num_output_channels not in (1, 3): + raise ValueError("num_output_channels should be either 1 or 3") + + if img.shape[-3] == 3: + r, g, b = img.unbind(dim=-3) + # This implementation closely follows the TF one: + # https://github.com/tensorflow/tensorflow/blob/v2.3.0/tensorflow/python/ops/image_ops_impl.py#L2105-L2138 + l_img = (0.2989 * r + 0.587 * g + 0.114 * b).to(img.dtype) + l_img = l_img.unsqueeze(dim=-3) + else: + l_img = img.clone() + + if num_output_channels == 3: + return l_img.expand(img.shape) + + return l_img + + +def adjust_brightness(img: Tensor, brightness_factor: float) -> Tensor: + if brightness_factor < 0: + raise ValueError(f"brightness_factor ({brightness_factor}) is not non-negative.") + + _assert_image_tensor(img) + + _assert_channels(img, [1, 3]) + + return _blend(img, torch.zeros_like(img), brightness_factor) + + +def adjust_contrast(img: Tensor, contrast_factor: float) -> Tensor: + if contrast_factor < 0: + raise ValueError(f"contrast_factor ({contrast_factor}) is not non-negative.") + + _assert_image_tensor(img) + + _assert_channels(img, [3, 1]) + c = get_dimensions(img)[0] + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + if c == 3: + mean = torch.mean(rgb_to_grayscale(img).to(dtype), dim=(-3, -2, -1), keepdim=True) + else: + mean = torch.mean(img.to(dtype), dim=(-3, -2, -1), keepdim=True) + + return _blend(img, mean, contrast_factor) + + +def adjust_hue(img: Tensor, hue_factor: float) -> Tensor: + if not (-0.5 <= hue_factor <= 0.5): + raise ValueError(f"hue_factor ({hue_factor}) is not in [-0.5, 0.5].") + + if not (isinstance(img, torch.Tensor)): + raise TypeError("Input img should be Tensor image") + + _assert_image_tensor(img) + + _assert_channels(img, [1, 3]) + if get_dimensions(img)[0] == 1: # Match PIL behaviour + return img + + orig_dtype = img.dtype + img = convert_image_dtype(img, torch.float32) + + img = _rgb2hsv(img) + h, s, v = img.unbind(dim=-3) + h = (h + hue_factor) % 1.0 + img = torch.stack((h, s, v), dim=-3) + img_hue_adj = _hsv2rgb(img) + + return convert_image_dtype(img_hue_adj, orig_dtype) + + +def adjust_saturation(img: Tensor, saturation_factor: float) -> Tensor: + if saturation_factor < 0: + raise ValueError(f"saturation_factor ({saturation_factor}) is not non-negative.") + + _assert_image_tensor(img) + + _assert_channels(img, [1, 3]) + + if get_dimensions(img)[0] == 1: # Match PIL behaviour + return img + + return _blend(img, rgb_to_grayscale(img), saturation_factor) + + +def adjust_gamma(img: Tensor, gamma: float, gain: float = 1) -> Tensor: + if not isinstance(img, torch.Tensor): + raise TypeError("Input img should be a Tensor.") + + _assert_channels(img, [1, 3]) + + if gamma < 0: + raise ValueError("Gamma should be a non-negative real number") + + result = img + dtype = img.dtype + if not torch.is_floating_point(img): + result = convert_image_dtype(result, torch.float32) + + result = (gain * result.pow(gamma)).clamp(0, 1) + + result = convert_image_dtype(result, dtype) + return result + + +def _blend(img1: Tensor, img2: Tensor, ratio: float) -> Tensor: + ratio = float(ratio) + bound = _max_value(img1.dtype) + return (ratio * img1 + (1.0 - ratio) * img2).clamp(0, bound).to(img1.dtype) + + +def _rgb2hsv(img: Tensor) -> Tensor: + r, g, b = img.unbind(dim=-3) + + # Implementation is based on https://github.com/python-pillow/Pillow/blob/4174d4267616897df3746d315d5a2d0f82c656ee/ + # src/libImaging/Convert.c#L330 + maxc = torch.max(img, dim=-3).values + minc = torch.min(img, dim=-3).values + + # The algorithm erases S and H channel where `maxc = minc`. This avoids NaN + # from happening in the results, because + # + S channel has division by `maxc`, which is zero only if `maxc = minc` + # + H channel has division by `(maxc - minc)`. + # + # Instead of overwriting NaN afterwards, we just prevent it from occurring, so + # we don't need to deal with it in case we save the NaN in a buffer in + # backprop, if it is ever supported, but it doesn't hurt to do so. + eqc = maxc == minc + + cr = maxc - minc + # Since `eqc => cr = 0`, replacing denominator with 1 when `eqc` is fine. + ones = torch.ones_like(maxc) + s = cr / torch.where(eqc, ones, maxc) + # Note that `eqc => maxc = minc = r = g = b`. So the following calculation + # of `h` would reduce to `bc - gc + 2 + rc - bc + 4 + rc - bc = 6` so it + # would not matter what values `rc`, `gc`, and `bc` have here, and thus + # replacing denominator with 1 when `eqc` is fine. + cr_divisor = torch.where(eqc, ones, cr) + rc = (maxc - r) / cr_divisor + gc = (maxc - g) / cr_divisor + bc = (maxc - b) / cr_divisor + + hr = (maxc == r) * (bc - gc) + hg = ((maxc == g) & (maxc != r)) * (2.0 + rc - bc) + hb = ((maxc != g) & (maxc != r)) * (4.0 + gc - rc) + h = hr + hg + hb + h = torch.fmod((h / 6.0 + 1.0), 1.0) + return torch.stack((h, s, maxc), dim=-3) + + +def _hsv2rgb(img: Tensor) -> Tensor: + h, s, v = img.unbind(dim=-3) + i = torch.floor(h * 6.0) + f = (h * 6.0) - i + i = i.to(dtype=torch.int32) + + p = torch.clamp((v * (1.0 - s)), 0.0, 1.0) + q = torch.clamp((v * (1.0 - s * f)), 0.0, 1.0) + t = torch.clamp((v * (1.0 - s * (1.0 - f))), 0.0, 1.0) + i = i % 6 + + mask = i.unsqueeze(dim=-3) == torch.arange(6, device=i.device).view(-1, 1, 1) + + a1 = torch.stack((v, q, p, p, t, v), dim=-3) + a2 = torch.stack((t, v, v, q, p, p), dim=-3) + a3 = torch.stack((p, p, t, v, v, q), dim=-3) + a4 = torch.stack((a1, a2, a3), dim=-4) + + return torch.einsum("...ijk, ...xijk -> ...xjk", mask.to(dtype=img.dtype), a4) + + +def _pad_symmetric(img: Tensor, padding: list[int]) -> Tensor: + # padding is left, right, top, bottom + + # crop if needed + if padding[0] < 0 or padding[1] < 0 or padding[2] < 0 or padding[3] < 0: + neg_min_padding = [-min(x, 0) for x in padding] + crop_left, crop_right, crop_top, crop_bottom = neg_min_padding + img = img[..., crop_top : img.shape[-2] - crop_bottom, crop_left : img.shape[-1] - crop_right] + padding = [max(x, 0) for x in padding] + + in_sizes = img.size() + + _x_indices = [i for i in range(in_sizes[-1])] # [0, 1, 2, 3, ...] + left_indices = [i for i in range(padding[0] - 1, -1, -1)] # e.g. [3, 2, 1, 0] + right_indices = [-(i + 1) for i in range(padding[1])] # e.g. [-1, -2, -3] + x_indices = torch.tensor(left_indices + _x_indices + right_indices, device=img.device) + + _y_indices = [i for i in range(in_sizes[-2])] + top_indices = [i for i in range(padding[2] - 1, -1, -1)] + bottom_indices = [-(i + 1) for i in range(padding[3])] + y_indices = torch.tensor(top_indices + _y_indices + bottom_indices, device=img.device) + + ndim = img.ndim + if ndim == 3: + return img[:, y_indices[:, None], x_indices[None, :]] + elif ndim == 4: + return img[:, :, y_indices[:, None], x_indices[None, :]] + else: + raise RuntimeError("Symmetric padding of N-D tensors are not supported yet") + + +def _parse_pad_padding(padding: Union[int, list[int]]) -> list[int]: + if isinstance(padding, int): + if torch.jit.is_scripting(): + # This maybe unreachable + raise ValueError("padding can't be an int while torchscripting, set it as a list [value, ]") + pad_left = pad_right = pad_top = pad_bottom = padding + elif len(padding) == 1: + pad_left = pad_right = pad_top = pad_bottom = padding[0] + elif len(padding) == 2: + pad_left = pad_right = padding[0] + pad_top = pad_bottom = padding[1] + else: + pad_left = padding[0] + pad_top = padding[1] + pad_right = padding[2] + pad_bottom = padding[3] + + return [pad_left, pad_right, pad_top, pad_bottom] + + +def pad( + img: Tensor, padding: Union[int, list[int]], fill: Optional[Union[int, float]] = 0, padding_mode: str = "constant" +) -> Tensor: + _assert_image_tensor(img) + + if fill is None: + fill = 0 + + if not isinstance(padding, (int, tuple, list)): + raise TypeError("Got inappropriate padding arg") + if not isinstance(fill, (int, float)): + raise TypeError("Got inappropriate fill arg") + if not isinstance(padding_mode, str): + raise TypeError("Got inappropriate padding_mode arg") + + if isinstance(padding, tuple): + padding = list(padding) + + if isinstance(padding, list): + # TODO: Jit is failing on loading this op when scripted and saved + # https://github.com/pytorch/pytorch/issues/81100 + if len(padding) not in [1, 2, 4]: + raise ValueError( + f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple" + ) + + if padding_mode not in ["constant", "edge", "reflect", "symmetric"]: + raise ValueError("Padding mode should be either constant, edge, reflect or symmetric") + + p = _parse_pad_padding(padding) + + if padding_mode == "edge": + # remap padding_mode str + padding_mode = "replicate" + elif padding_mode == "symmetric": + # route to another implementation + return _pad_symmetric(img, p) + + need_squeeze = False + if img.ndim < 4: + img = img.unsqueeze(dim=0) + need_squeeze = True + + out_dtype = img.dtype + need_cast = False + if (padding_mode != "constant") and img.dtype not in (torch.float32, torch.float64): + # Here we temporarily cast input tensor to float + # until pytorch issue is resolved : + # https://github.com/pytorch/pytorch/issues/40763 + need_cast = True + img = img.to(torch.float32) + + if padding_mode in ("reflect", "replicate"): + img = torch_pad(img, p, mode=padding_mode) + else: + img = torch_pad(img, p, mode=padding_mode, value=float(fill)) + + if need_squeeze: + img = img.squeeze(dim=0) + + if need_cast: + img = img.to(out_dtype) + + return img + + +def resize( + img: Tensor, + size: list[int], + interpolation: str = "bilinear", + antialias: Optional[bool] = True, +) -> Tensor: + _assert_image_tensor(img) + + if isinstance(size, tuple): + size = list(size) + + if antialias is None: + antialias = False + + if antialias and interpolation not in ["bilinear", "bicubic"]: + # We manually set it to False to avoid an error downstream in interpolate() + # This behaviour is documented: the parameter is irrelevant for modes + # that are not bilinear or bicubic. We used to raise an error here, but + # now we don't as True is the default. + antialias = False + + img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [torch.float32, torch.float64]) + + # Define align_corners to avoid warnings + align_corners = False if interpolation in ["bilinear", "bicubic"] else None + + img = interpolate(img, size=size, mode=interpolation, align_corners=align_corners, antialias=antialias) + + if interpolation == "bicubic" and out_dtype == torch.uint8: + img = img.clamp(min=0, max=255) + + img = _cast_squeeze_out(img, need_cast=need_cast, need_squeeze=need_squeeze, out_dtype=out_dtype) + + return img + + +def _assert_grid_transform_inputs( + img: Tensor, + matrix: Optional[list[float]], + interpolation: str, + fill: Optional[Union[int, float, list[float]]], + supported_interpolation_modes: list[str], + coeffs: Optional[list[float]] = None, +) -> None: + + if not (isinstance(img, torch.Tensor)): + raise TypeError("Input img should be Tensor") + + _assert_image_tensor(img) + + if matrix is not None and not isinstance(matrix, list): + raise TypeError("Argument matrix should be a list") + + if matrix is not None and len(matrix) != 6: + raise ValueError("Argument matrix should have 6 float values") + + if coeffs is not None and len(coeffs) != 8: + raise ValueError("Argument coeffs should have 8 float values") + + if fill is not None and not isinstance(fill, (int, float, tuple, list)): + warnings.warn("Argument fill should be either int, float, tuple or list") + + # Check fill + num_channels = get_dimensions(img)[0] + if fill is not None and isinstance(fill, (tuple, list)) and len(fill) > 1 and len(fill) != num_channels: + msg = ( + "The number of elements in 'fill' cannot broadcast to match the number of " + "channels of the image ({} != {})" + ) + raise ValueError(msg.format(len(fill), num_channels)) + + if interpolation not in supported_interpolation_modes: + raise ValueError(f"Interpolation mode '{interpolation}' is unsupported with Tensor input") + + +def _cast_squeeze_in(img: Tensor, req_dtypes: list[torch.dtype]) -> tuple[Tensor, bool, bool, torch.dtype]: + need_squeeze = False + # make image NCHW + if img.ndim < 4: + img = img.unsqueeze(dim=0) + need_squeeze = True + + out_dtype = img.dtype + need_cast = False + if out_dtype not in req_dtypes: + need_cast = True + req_dtype = req_dtypes[0] + img = img.to(req_dtype) + return img, need_cast, need_squeeze, out_dtype + + +def _cast_squeeze_out(img: Tensor, need_cast: bool, need_squeeze: bool, out_dtype: torch.dtype) -> Tensor: + if need_squeeze: + img = img.squeeze(dim=0) + + if need_cast: + if out_dtype in (torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64): + # it is better to round before cast + img = torch.round(img) + img = img.to(out_dtype) + + return img + + +def _apply_grid_transform( + img: Tensor, grid: Tensor, mode: str, fill: Optional[Union[int, float, list[float]]] +) -> Tensor: + + img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [grid.dtype]) + + if img.shape[0] > 1: + # Apply same grid to a batch of images + grid = grid.expand(img.shape[0], grid.shape[1], grid.shape[2], grid.shape[3]) + + # Append a dummy mask for customized fill colors, should be faster than grid_sample() twice + if fill is not None: + mask = torch.ones((img.shape[0], 1, img.shape[2], img.shape[3]), dtype=img.dtype, device=img.device) + img = torch.cat((img, mask), dim=1) + + img = grid_sample(img, grid, mode=mode, padding_mode="zeros", align_corners=False) + + # Fill with required color + if fill is not None: + mask = img[:, -1:, :, :] # N * 1 * H * W + img = img[:, :-1, :, :] # N * C * H * W + mask = mask.expand_as(img) + fill_list, len_fill = (fill, len(fill)) if isinstance(fill, (tuple, list)) else ([float(fill)], 1) + fill_img = torch.tensor(fill_list, dtype=img.dtype, device=img.device).view(1, len_fill, 1, 1).expand_as(img) + if mode == "nearest": + mask = mask < 0.5 + img[mask] = fill_img[mask] + else: # 'bilinear' + img = img * mask + (1.0 - mask) * fill_img + + img = _cast_squeeze_out(img, need_cast, need_squeeze, out_dtype) + return img + + +def _gen_affine_grid( + theta: Tensor, + w: int, + h: int, + ow: int, + oh: int, +) -> Tensor: + # https://github.com/pytorch/pytorch/blob/74b65c32be68b15dc7c9e8bb62459efbfbde33d8/aten/src/ATen/native/ + # AffineGridGenerator.cpp#L18 + # Difference with AffineGridGenerator is that: + # 1) we normalize grid values after applying theta + # 2) we can normalize by other image size, such that it covers "extend" option like in PIL.Image.rotate + + d = 0.5 + base_grid = torch.empty(1, oh, ow, 3, dtype=theta.dtype, device=theta.device) + x_grid = torch.linspace(-ow * 0.5 + d, ow * 0.5 + d - 1, steps=ow, device=theta.device) + base_grid[..., 0].copy_(x_grid) + y_grid = torch.linspace(-oh * 0.5 + d, oh * 0.5 + d - 1, steps=oh, device=theta.device).unsqueeze_(-1) + base_grid[..., 1].copy_(y_grid) + base_grid[..., 2].fill_(1) + + rescaled_theta = theta.transpose(1, 2) / torch.tensor([0.5 * w, 0.5 * h], dtype=theta.dtype, device=theta.device) + output_grid = base_grid.view(1, oh * ow, 3).bmm(rescaled_theta) + return output_grid.view(1, oh, ow, 2) + + +def affine( + img: Tensor, + matrix: list[float], + interpolation: str = "nearest", + fill: Optional[Union[int, float, list[float]]] = None, +) -> Tensor: + _assert_grid_transform_inputs(img, matrix, interpolation, fill, ["nearest", "bilinear"]) + + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + theta = torch.tensor(matrix, dtype=dtype, device=img.device).reshape(1, 2, 3) + shape = img.shape + # grid will be generated on the same device as theta and img + grid = _gen_affine_grid(theta, w=shape[-1], h=shape[-2], ow=shape[-1], oh=shape[-2]) + return _apply_grid_transform(img, grid, interpolation, fill=fill) + + +def _compute_affine_output_size(matrix: list[float], w: int, h: int) -> tuple[int, int]: + + # Inspired of PIL implementation: + # https://github.com/python-pillow/Pillow/blob/11de3318867e4398057373ee9f12dcb33db7335c/src/PIL/Image.py#L2054 + + # pts are Top-Left, Top-Right, Bottom-Left, Bottom-Right points. + # Points are shifted due to affine matrix torch convention about + # the center point. Center is (0, 0) for image center pivot point (w * 0.5, h * 0.5) + pts = torch.tensor( + [ + [-0.5 * w, -0.5 * h, 1.0], + [-0.5 * w, 0.5 * h, 1.0], + [0.5 * w, 0.5 * h, 1.0], + [0.5 * w, -0.5 * h, 1.0], + ] + ) + theta = torch.tensor(matrix, dtype=torch.float).view(2, 3) + new_pts = torch.matmul(pts, theta.T) + min_vals, _ = new_pts.min(dim=0) + max_vals, _ = new_pts.max(dim=0) + + # shift points to [0, w] and [0, h] interval to match PIL results + min_vals += torch.tensor((w * 0.5, h * 0.5)) + max_vals += torch.tensor((w * 0.5, h * 0.5)) + + # Truncate precision to 1e-4 to avoid ceil of Xe-15 to 1.0 + tol = 1e-4 + cmax = torch.ceil((max_vals / tol).trunc_() * tol) + cmin = torch.floor((min_vals / tol).trunc_() * tol) + size = cmax - cmin + return int(size[0]), int(size[1]) # w, h + + +def rotate( + img: Tensor, + matrix: list[float], + interpolation: str = "nearest", + expand: bool = False, + fill: Optional[Union[int, float, list[float]]] = None, +) -> Tensor: + _assert_grid_transform_inputs(img, matrix, interpolation, fill, ["nearest", "bilinear"]) + w, h = img.shape[-1], img.shape[-2] + ow, oh = _compute_affine_output_size(matrix, w, h) if expand else (w, h) + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + theta = torch.tensor(matrix, dtype=dtype, device=img.device).reshape(1, 2, 3) + # grid will be generated on the same device as theta and img + grid = _gen_affine_grid(theta, w=w, h=h, ow=ow, oh=oh) + + return _apply_grid_transform(img, grid, interpolation, fill=fill) + + +def _perspective_grid(coeffs: list[float], ow: int, oh: int, dtype: torch.dtype, device: torch.device) -> Tensor: + # https://github.com/python-pillow/Pillow/blob/4634eafe3c695a014267eefdce830b4a825beed7/ + # src/libImaging/Geometry.c#L394 + + # + # x_out = (coeffs[0] * x + coeffs[1] * y + coeffs[2]) / (coeffs[6] * x + coeffs[7] * y + 1) + # y_out = (coeffs[3] * x + coeffs[4] * y + coeffs[5]) / (coeffs[6] * x + coeffs[7] * y + 1) + # + theta1 = torch.tensor( + [[[coeffs[0], coeffs[1], coeffs[2]], [coeffs[3], coeffs[4], coeffs[5]]]], dtype=dtype, device=device + ) + theta2 = torch.tensor([[[coeffs[6], coeffs[7], 1.0], [coeffs[6], coeffs[7], 1.0]]], dtype=dtype, device=device) + + d = 0.5 + base_grid = torch.empty(1, oh, ow, 3, dtype=dtype, device=device) + x_grid = torch.linspace(d, ow * 1.0 + d - 1.0, steps=ow, device=device) + base_grid[..., 0].copy_(x_grid) + y_grid = torch.linspace(d, oh * 1.0 + d - 1.0, steps=oh, device=device).unsqueeze_(-1) + base_grid[..., 1].copy_(y_grid) + base_grid[..., 2].fill_(1) + + rescaled_theta1 = theta1.transpose(1, 2) / torch.tensor([0.5 * ow, 0.5 * oh], dtype=dtype, device=device) + output_grid1 = base_grid.view(1, oh * ow, 3).bmm(rescaled_theta1) + output_grid2 = base_grid.view(1, oh * ow, 3).bmm(theta2.transpose(1, 2)) + + output_grid = output_grid1 / output_grid2 - 1.0 + return output_grid.view(1, oh, ow, 2) + + +def perspective( + img: Tensor, + perspective_coeffs: list[float], + interpolation: str = "bilinear", + fill: Optional[Union[int, float, list[float]]] = None, +) -> Tensor: + if not (isinstance(img, torch.Tensor)): + raise TypeError("Input img should be Tensor.") + + _assert_image_tensor(img) + + _assert_grid_transform_inputs( + img, + matrix=None, + interpolation=interpolation, + fill=fill, + supported_interpolation_modes=["nearest", "bilinear"], + coeffs=perspective_coeffs, + ) + + ow, oh = img.shape[-1], img.shape[-2] + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + grid = _perspective_grid(perspective_coeffs, ow=ow, oh=oh, dtype=dtype, device=img.device) + return _apply_grid_transform(img, grid, interpolation, fill=fill) + + +def _get_gaussian_kernel1d(kernel_size: int, sigma: float, dtype: torch.dtype, device: torch.device) -> Tensor: + ksize_half = (kernel_size - 1) * 0.5 + + x = torch.linspace(-ksize_half, ksize_half, steps=kernel_size, dtype=dtype, device=device) + pdf = torch.exp(-0.5 * (x / sigma).pow(2)) + kernel1d = pdf / pdf.sum() + + return kernel1d + + +def _get_gaussian_kernel2d( + kernel_size: list[int], sigma: list[float], dtype: torch.dtype, device: torch.device +) -> Tensor: + kernel1d_x = _get_gaussian_kernel1d(kernel_size[0], sigma[0], dtype, device) + kernel1d_y = _get_gaussian_kernel1d(kernel_size[1], sigma[1], dtype, device) + kernel2d = torch.mm(kernel1d_y[:, None], kernel1d_x[None, :]) + return kernel2d + + +def gaussian_blur(img: Tensor, kernel_size: list[int], sigma: list[float]) -> Tensor: + if not (isinstance(img, torch.Tensor)): + raise TypeError(f"img should be Tensor. Got {type(img)}") + + _assert_image_tensor(img) + + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + kernel = _get_gaussian_kernel2d(kernel_size, sigma, dtype=dtype, device=img.device) + kernel = kernel.expand(img.shape[-3], 1, kernel.shape[0], kernel.shape[1]) + + img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [kernel.dtype]) + + # padding = (left, right, top, bottom) + padding = [kernel_size[0] // 2, kernel_size[0] // 2, kernel_size[1] // 2, kernel_size[1] // 2] + img = torch_pad(img, padding, mode="reflect") + img = conv2d(img, kernel, groups=img.shape[-3]) + + img = _cast_squeeze_out(img, need_cast, need_squeeze, out_dtype) + return img + + +def invert(img: Tensor) -> Tensor: + + _assert_image_tensor(img) + + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + + _assert_channels(img, [1, 3]) + + return _max_value(img.dtype) - img + + +def posterize(img: Tensor, bits: int) -> Tensor: + + _assert_image_tensor(img) + + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + if img.dtype != torch.uint8: + raise TypeError(f"Only torch.uint8 image tensors are supported, but found {img.dtype}") + + _assert_channels(img, [1, 3]) + mask = -int(2 ** (8 - bits)) # JIT-friendly for: ~(2 ** (8 - bits) - 1) + return img & mask + + +def solarize(img: Tensor, threshold: float) -> Tensor: + + _assert_image_tensor(img) + + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + + _assert_channels(img, [1, 3]) + + if threshold > _max_value(img.dtype): + raise TypeError("Threshold should be less than bound of img.") + + inverted_img = invert(img) + return torch.where(img >= threshold, inverted_img, img) + + +def _blurred_degenerate_image(img: Tensor) -> Tensor: + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + + kernel = torch.ones((3, 3), dtype=dtype, device=img.device) + kernel[1, 1] = 5.0 + kernel /= kernel.sum() + kernel = kernel.expand(img.shape[-3], 1, kernel.shape[0], kernel.shape[1]) + + result_tmp, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [kernel.dtype]) + result_tmp = conv2d(result_tmp, kernel, groups=result_tmp.shape[-3]) + result_tmp = _cast_squeeze_out(result_tmp, need_cast, need_squeeze, out_dtype) + + result = img.clone() + result[..., 1:-1, 1:-1] = result_tmp + + return result + + +def adjust_sharpness(img: Tensor, sharpness_factor: float) -> Tensor: + if sharpness_factor < 0: + raise ValueError(f"sharpness_factor ({sharpness_factor}) is not non-negative.") + + _assert_image_tensor(img) + + _assert_channels(img, [1, 3]) + + if img.size(-1) <= 2 or img.size(-2) <= 2: + return img + + return _blend(img, _blurred_degenerate_image(img), sharpness_factor) + + +def autocontrast(img: Tensor) -> Tensor: + + _assert_image_tensor(img) + + if img.ndim < 3: + raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}") + + _assert_channels(img, [1, 3]) + + bound = _max_value(img.dtype) + dtype = img.dtype if torch.is_floating_point(img) else torch.float32 + + minimum = img.amin(dim=(-2, -1), keepdim=True).to(dtype) + maximum = img.amax(dim=(-2, -1), keepdim=True).to(dtype) + scale = bound / (maximum - minimum) + eq_idxs = torch.isfinite(scale).logical_not() + minimum[eq_idxs] = 0 + scale[eq_idxs] = 1 + + return ((img - minimum) * scale).clamp(0, bound).to(img.dtype) + + +def _scale_channel(img_chan: Tensor) -> Tensor: + # TODO: we should expect bincount to always be faster than histc, but this + # isn't always the case. Once + # https://github.com/pytorch/pytorch/issues/53194 is fixed, remove the if + # block and only use bincount. + if img_chan.is_cuda: + hist = torch.histc(img_chan.to(torch.float32), bins=256, min=0, max=255) + else: + hist = torch.bincount(img_chan.reshape(-1), minlength=256) + + nonzero_hist = hist[hist != 0] + step = torch.div(nonzero_hist[:-1].sum(), 255, rounding_mode="floor") + if step == 0: + return img_chan + + lut = torch.div(torch.cumsum(hist, 0) + torch.div(step, 2, rounding_mode="floor"), step, rounding_mode="floor") + lut = torch.nn.functional.pad(lut, [1, 0])[:-1].clamp(0, 255) + + return lut[img_chan.to(torch.int64)].to(torch.uint8) + + +def _equalize_single_image(img: Tensor) -> Tensor: + return torch.stack([_scale_channel(img[c]) for c in range(img.size(0))]) + + +def equalize(img: Tensor) -> Tensor: + + _assert_image_tensor(img) + + if not (3 <= img.ndim <= 4): + raise TypeError(f"Input image tensor should have 3 or 4 dimensions, but found {img.ndim}") + if img.dtype != torch.uint8: + raise TypeError(f"Only torch.uint8 image tensors are supported, but found {img.dtype}") + + _assert_channels(img, [1, 3]) + + if img.ndim == 3: + return _equalize_single_image(img) + + return torch.stack([_equalize_single_image(x) for x in img]) + + +def normalize(tensor: Tensor, mean: list[float], std: list[float], inplace: bool = False) -> Tensor: + _assert_image_tensor(tensor) + + if not tensor.is_floating_point(): + raise TypeError(f"Input tensor should be a float tensor. Got {tensor.dtype}.") + + if tensor.ndim < 3: + raise ValueError( + f"Expected tensor to be a tensor image of size (..., C, H, W). Got tensor.size() = {tensor.size()}" + ) + + if not inplace: + tensor = tensor.clone() + + dtype = tensor.dtype + mean = torch.as_tensor(mean, dtype=dtype, device=tensor.device) + std = torch.as_tensor(std, dtype=dtype, device=tensor.device) + if (std == 0).any(): + raise ValueError(f"std evaluated to zero after conversion to {dtype}, leading to division by zero.") + if mean.ndim == 1: + mean = mean.view(-1, 1, 1) + if std.ndim == 1: + std = std.view(-1, 1, 1) + return tensor.sub_(mean).div_(std) + + +def erase(img: Tensor, i: int, j: int, h: int, w: int, v: Tensor, inplace: bool = False) -> Tensor: + _assert_image_tensor(img) + + if not inplace: + img = img.clone() + + img[..., i : i + h, j : j + w] = v + return img + + +def _create_identity_grid(size: list[int]) -> Tensor: + hw_space = [torch.linspace((-s + 1) / s, (s - 1) / s, s) for s in size] + grid_y, grid_x = torch.meshgrid(hw_space, indexing="ij") + return torch.stack([grid_x, grid_y], -1).unsqueeze(0) # 1 x H x W x 2 + + +def elastic_transform( + img: Tensor, + displacement: Tensor, + interpolation: str = "bilinear", + fill: Optional[Union[int, float, list[float]]] = None, +) -> Tensor: + + if not (isinstance(img, torch.Tensor)): + raise TypeError(f"img should be Tensor. Got {type(img)}") + + size = list(img.shape[-2:]) + displacement = displacement.to(img.device) + + identity_grid = _create_identity_grid(size) + grid = identity_grid.to(img.device) + displacement + return _apply_grid_transform(img, grid, interpolation, fill) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/_functional_video.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/_functional_video.py new file mode 100644 index 0000000000000000000000000000000000000000..91df7d42cd71fc554aba51fcf5e90db30e3c3851 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/_functional_video.py @@ -0,0 +1,114 @@ +import warnings + +import torch + + +warnings.warn( + "The 'torchvision.transforms._functional_video' module is deprecated since 0.12 and will be removed in the future. " + "Please use the 'torchvision.transforms.functional' module instead." +) + + +def _is_tensor_video_clip(clip): + if not torch.is_tensor(clip): + raise TypeError("clip should be Tensor. Got %s" % type(clip)) + + if not clip.ndimension() == 4: + raise ValueError("clip should be 4D. Got %dD" % clip.dim()) + + return True + + +def crop(clip, i, j, h, w): + """ + Args: + clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) + """ + if len(clip.size()) != 4: + raise ValueError("clip should be a 4D tensor") + return clip[..., i : i + h, j : j + w] + + +def resize(clip, target_size, interpolation_mode): + if len(target_size) != 2: + raise ValueError(f"target size should be tuple (height, width), instead got {target_size}") + return torch.nn.functional.interpolate(clip, size=target_size, mode=interpolation_mode, align_corners=False) + + +def resized_crop(clip, i, j, h, w, size, interpolation_mode="bilinear"): + """ + Do spatial cropping and resizing to the video clip + Args: + clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) + i (int): i in (i,j) i.e coordinates of the upper left corner. + j (int): j in (i,j) i.e coordinates of the upper left corner. + h (int): Height of the cropped region. + w (int): Width of the cropped region. + size (tuple(int, int)): height and width of resized clip + Returns: + clip (torch.tensor): Resized and cropped clip. Size is (C, T, H, W) + """ + if not _is_tensor_video_clip(clip): + raise ValueError("clip should be a 4D torch.tensor") + clip = crop(clip, i, j, h, w) + clip = resize(clip, size, interpolation_mode) + return clip + + +def center_crop(clip, crop_size): + if not _is_tensor_video_clip(clip): + raise ValueError("clip should be a 4D torch.tensor") + h, w = clip.size(-2), clip.size(-1) + th, tw = crop_size + if h < th or w < tw: + raise ValueError("height and width must be no smaller than crop_size") + + i = int(round((h - th) / 2.0)) + j = int(round((w - tw) / 2.0)) + return crop(clip, i, j, th, tw) + + +def to_tensor(clip): + """ + Convert tensor data type from uint8 to float, divide value by 255.0 and + permute the dimensions of clip tensor + Args: + clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C) + Return: + clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W) + """ + _is_tensor_video_clip(clip) + if not clip.dtype == torch.uint8: + raise TypeError("clip tensor should have data type uint8. Got %s" % str(clip.dtype)) + return clip.float().permute(3, 0, 1, 2) / 255.0 + + +def normalize(clip, mean, std, inplace=False): + """ + Args: + clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W) + mean (tuple): pixel RGB mean. Size is (3) + std (tuple): pixel standard deviation. Size is (3) + Returns: + normalized clip (torch.tensor): Size is (C, T, H, W) + """ + if not _is_tensor_video_clip(clip): + raise ValueError("clip should be a 4D torch.tensor") + if not inplace: + clip = clip.clone() + mean = torch.as_tensor(mean, dtype=clip.dtype, device=clip.device) + std = torch.as_tensor(std, dtype=clip.dtype, device=clip.device) + clip.sub_(mean[:, None, None, None]).div_(std[:, None, None, None]) + return clip + + +def hflip(clip): + """ + Args: + clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W) + Returns: + flipped clip (torch.tensor): Size is (C, T, H, W) + """ + if not _is_tensor_video_clip(clip): + raise ValueError("clip should be a 4D torch.tensor") + return clip.flip(-1) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/_presets.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/_presets.py new file mode 100644 index 0000000000000000000000000000000000000000..a7eba6721c789625da9b5a4e8ed7372c6efbcd4d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/_presets.py @@ -0,0 +1,217 @@ +""" +This file is part of the private API. Please do not use directly these classes as they will be modified on +future versions without warning. The classes should be accessed only via the transforms argument of Weights. +""" + +from typing import Optional, Union + +import torch +from torch import nn, Tensor + +from . import functional as F, InterpolationMode + + +__all__ = [ + "ObjectDetection", + "ImageClassification", + "VideoClassification", + "SemanticSegmentation", + "OpticalFlow", +] + + +class ObjectDetection(nn.Module): + def forward(self, img: Tensor) -> Tensor: + if not isinstance(img, Tensor): + img = F.pil_to_tensor(img) + return F.convert_image_dtype(img, torch.float) + + def __repr__(self) -> str: + return self.__class__.__name__ + "()" + + def describe(self) -> str: + return ( + "Accepts ``PIL.Image``, batched ``(B, C, H, W)`` and single ``(C, H, W)`` image ``torch.Tensor`` objects. " + "The images are rescaled to ``[0.0, 1.0]``." + ) + + +class ImageClassification(nn.Module): + def __init__( + self, + *, + crop_size: int, + resize_size: int = 256, + mean: tuple[float, ...] = (0.485, 0.456, 0.406), + std: tuple[float, ...] = (0.229, 0.224, 0.225), + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, + ) -> None: + super().__init__() + self.crop_size = [crop_size] + self.resize_size = [resize_size] + self.mean = list(mean) + self.std = list(std) + self.interpolation = interpolation + self.antialias = antialias + + def forward(self, img: Tensor) -> Tensor: + img = F.resize(img, self.resize_size, interpolation=self.interpolation, antialias=self.antialias) + img = F.center_crop(img, self.crop_size) + if not isinstance(img, Tensor): + img = F.pil_to_tensor(img) + img = F.convert_image_dtype(img, torch.float) + img = F.normalize(img, mean=self.mean, std=self.std) + return img + + def __repr__(self) -> str: + format_string = self.__class__.__name__ + "(" + format_string += f"\n crop_size={self.crop_size}" + format_string += f"\n resize_size={self.resize_size}" + format_string += f"\n mean={self.mean}" + format_string += f"\n std={self.std}" + format_string += f"\n interpolation={self.interpolation}" + format_string += "\n)" + return format_string + + def describe(self) -> str: + return ( + "Accepts ``PIL.Image``, batched ``(B, C, H, W)`` and single ``(C, H, W)`` image ``torch.Tensor`` objects. " + f"The images are resized to ``resize_size={self.resize_size}`` using ``interpolation={self.interpolation}``, " + f"followed by a central crop of ``crop_size={self.crop_size}``. Finally the values are first rescaled to " + f"``[0.0, 1.0]`` and then normalized using ``mean={self.mean}`` and ``std={self.std}``." + ) + + +class VideoClassification(nn.Module): + def __init__( + self, + *, + crop_size: tuple[int, int], + resize_size: Union[tuple[int], tuple[int, int]], + mean: tuple[float, ...] = (0.43216, 0.394666, 0.37645), + std: tuple[float, ...] = (0.22803, 0.22145, 0.216989), + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + ) -> None: + super().__init__() + self.crop_size = list(crop_size) + self.resize_size = list(resize_size) + self.mean = list(mean) + self.std = list(std) + self.interpolation = interpolation + + def forward(self, vid: Tensor) -> Tensor: + need_squeeze = False + if vid.ndim < 5: + vid = vid.unsqueeze(dim=0) + need_squeeze = True + + N, T, C, H, W = vid.shape + vid = vid.view(-1, C, H, W) + # We hard-code antialias=False to preserve results after we changed + # its default from None to True (see + # https://github.com/pytorch/vision/pull/7160) + # TODO: we could re-train the video models with antialias=True? + vid = F.resize(vid, self.resize_size, interpolation=self.interpolation, antialias=False) + vid = F.center_crop(vid, self.crop_size) + vid = F.convert_image_dtype(vid, torch.float) + vid = F.normalize(vid, mean=self.mean, std=self.std) + H, W = self.crop_size + vid = vid.view(N, T, C, H, W) + vid = vid.permute(0, 2, 1, 3, 4) # (N, T, C, H, W) => (N, C, T, H, W) + + if need_squeeze: + vid = vid.squeeze(dim=0) + return vid + + def __repr__(self) -> str: + format_string = self.__class__.__name__ + "(" + format_string += f"\n crop_size={self.crop_size}" + format_string += f"\n resize_size={self.resize_size}" + format_string += f"\n mean={self.mean}" + format_string += f"\n std={self.std}" + format_string += f"\n interpolation={self.interpolation}" + format_string += "\n)" + return format_string + + def describe(self) -> str: + return ( + "Accepts batched ``(B, T, C, H, W)`` and single ``(T, C, H, W)`` video frame ``torch.Tensor`` objects. " + f"The frames are resized to ``resize_size={self.resize_size}`` using ``interpolation={self.interpolation}``, " + f"followed by a central crop of ``crop_size={self.crop_size}``. Finally the values are first rescaled to " + f"``[0.0, 1.0]`` and then normalized using ``mean={self.mean}`` and ``std={self.std}``. Finally the output " + "dimensions are permuted to ``(..., C, T, H, W)`` tensors." + ) + + +class SemanticSegmentation(nn.Module): + def __init__( + self, + *, + resize_size: Optional[int], + mean: tuple[float, ...] = (0.485, 0.456, 0.406), + std: tuple[float, ...] = (0.229, 0.224, 0.225), + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, + ) -> None: + super().__init__() + self.resize_size = [resize_size] if resize_size is not None else None + self.mean = list(mean) + self.std = list(std) + self.interpolation = interpolation + self.antialias = antialias + + def forward(self, img: Tensor) -> Tensor: + if isinstance(self.resize_size, list): + img = F.resize(img, self.resize_size, interpolation=self.interpolation, antialias=self.antialias) + if not isinstance(img, Tensor): + img = F.pil_to_tensor(img) + img = F.convert_image_dtype(img, torch.float) + img = F.normalize(img, mean=self.mean, std=self.std) + return img + + def __repr__(self) -> str: + format_string = self.__class__.__name__ + "(" + format_string += f"\n resize_size={self.resize_size}" + format_string += f"\n mean={self.mean}" + format_string += f"\n std={self.std}" + format_string += f"\n interpolation={self.interpolation}" + format_string += "\n)" + return format_string + + def describe(self) -> str: + return ( + "Accepts ``PIL.Image``, batched ``(B, C, H, W)`` and single ``(C, H, W)`` image ``torch.Tensor`` objects. " + f"The images are resized to ``resize_size={self.resize_size}`` using ``interpolation={self.interpolation}``. " + f"Finally the values are first rescaled to ``[0.0, 1.0]`` and then normalized using ``mean={self.mean}`` and " + f"``std={self.std}``." + ) + + +class OpticalFlow(nn.Module): + def forward(self, img1: Tensor, img2: Tensor) -> tuple[Tensor, Tensor]: + if not isinstance(img1, Tensor): + img1 = F.pil_to_tensor(img1) + if not isinstance(img2, Tensor): + img2 = F.pil_to_tensor(img2) + + img1 = F.convert_image_dtype(img1, torch.float) + img2 = F.convert_image_dtype(img2, torch.float) + + # map [0, 1] into [-1, 1] + img1 = F.normalize(img1, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + img2 = F.normalize(img2, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) + + img1 = img1.contiguous() + img2 = img2.contiguous() + + return img1, img2 + + def __repr__(self) -> str: + return self.__class__.__name__ + "()" + + def describe(self) -> str: + return ( + "Accepts ``PIL.Image``, batched ``(B, C, H, W)`` and single ``(C, H, W)`` image ``torch.Tensor`` objects. " + "The images are rescaled to ``[-1.0, 1.0]``." + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/_transforms_video.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/_transforms_video.py new file mode 100644 index 0000000000000000000000000000000000000000..a04da4f74849805641e4c470f6b6b8d5f7000e3a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/_transforms_video.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 + +import numbers +import random +import warnings + +from torchvision.transforms import RandomCrop, RandomResizedCrop + +from . import _functional_video as F + + +__all__ = [ + "RandomCropVideo", + "RandomResizedCropVideo", + "CenterCropVideo", + "NormalizeVideo", + "ToTensorVideo", + "RandomHorizontalFlipVideo", +] + + +warnings.warn( + "The 'torchvision.transforms._transforms_video' module is deprecated since 0.12 and will be removed in the future. " + "Please use the 'torchvision.transforms' module instead." +) + + +class RandomCropVideo(RandomCrop): + def __init__(self, size): + if isinstance(size, numbers.Number): + self.size = (int(size), int(size)) + else: + self.size = size + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) + Returns: + torch.tensor: randomly cropped/resized video clip. + size is (C, T, OH, OW) + """ + i, j, h, w = self.get_params(clip, self.size) + return F.crop(clip, i, j, h, w) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(size={self.size})" + + +class RandomResizedCropVideo(RandomResizedCrop): + def __init__( + self, + size, + scale=(0.08, 1.0), + ratio=(3.0 / 4.0, 4.0 / 3.0), + interpolation_mode="bilinear", + ): + if isinstance(size, tuple): + if len(size) != 2: + raise ValueError(f"size should be tuple (height, width), instead got {size}") + self.size = size + else: + self.size = (size, size) + + self.interpolation_mode = interpolation_mode + self.scale = scale + self.ratio = ratio + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) + Returns: + torch.tensor: randomly cropped/resized video clip. + size is (C, T, H, W) + """ + i, j, h, w = self.get_params(clip, self.scale, self.ratio) + return F.resized_crop(clip, i, j, h, w, self.size, self.interpolation_mode) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(size={self.size}, interpolation_mode={self.interpolation_mode}, scale={self.scale}, ratio={self.ratio})" + + +class CenterCropVideo: + def __init__(self, crop_size): + if isinstance(crop_size, numbers.Number): + self.crop_size = (int(crop_size), int(crop_size)) + else: + self.crop_size = crop_size + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) + Returns: + torch.tensor: central cropping of video clip. Size is + (C, T, crop_size, crop_size) + """ + return F.center_crop(clip, self.crop_size) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(crop_size={self.crop_size})" + + +class NormalizeVideo: + """ + Normalize the video clip by mean subtraction and division by standard deviation + Args: + mean (3-tuple): pixel RGB mean + std (3-tuple): pixel RGB standard deviation + inplace (boolean): whether do in-place normalization + """ + + def __init__(self, mean, std, inplace=False): + self.mean = mean + self.std = std + self.inplace = inplace + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): video clip to be normalized. Size is (C, T, H, W) + """ + return F.normalize(clip, self.mean, self.std, self.inplace) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(mean={self.mean}, std={self.std}, inplace={self.inplace})" + + +class ToTensorVideo: + """ + Convert tensor data type from uint8 to float, divide value by 255.0 and + permute the dimensions of clip tensor + """ + + def __init__(self): + pass + + def __call__(self, clip): + """ + Args: + clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C) + Return: + clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W) + """ + return F.to_tensor(clip) + + def __repr__(self) -> str: + return self.__class__.__name__ + + +class RandomHorizontalFlipVideo: + """ + Flip the video clip along the horizontal direction with a given probability + Args: + p (float): probability of the clip being flipped. Default value is 0.5 + """ + + def __init__(self, p=0.5): + self.p = p + + def __call__(self, clip): + """ + Args: + clip (torch.tensor): Size is (C, T, H, W) + Return: + clip (torch.tensor): Size is (C, T, H, W) + """ + if random.random() < self.p: + clip = F.hflip(clip) + return clip + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/autoaugment.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/autoaugment.py new file mode 100644 index 0000000000000000000000000000000000000000..4157a62d20ff426728434fa9f33a217a3b6f6ba1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/autoaugment.py @@ -0,0 +1,614 @@ +import math +from enum import Enum +from typing import Optional + +import torch +from torch import Tensor + +from . import functional as F, InterpolationMode + +__all__ = ["AutoAugmentPolicy", "AutoAugment", "RandAugment", "TrivialAugmentWide", "AugMix"] + + +def _apply_op( + img: Tensor, op_name: str, magnitude: float, interpolation: InterpolationMode, fill: Optional[list[float]] +): + if op_name == "ShearX": + # magnitude should be arctan(magnitude) + # official autoaug: (1, level, 0, 0, 1, 0) + # https://github.com/tensorflow/models/blob/dd02069717128186b88afa8d857ce57d17957f03/research/autoaugment/augmentation_transforms.py#L290 + # compared to + # torchvision: (1, tan(level), 0, 0, 1, 0) + # https://github.com/pytorch/vision/blob/0c2373d0bba3499e95776e7936e207d8a1676e65/torchvision/transforms/functional.py#L976 + img = F.affine( + img, + angle=0.0, + translate=[0, 0], + scale=1.0, + shear=[math.degrees(math.atan(magnitude)), 0.0], + interpolation=interpolation, + fill=fill, + center=[0, 0], + ) + elif op_name == "ShearY": + # magnitude should be arctan(magnitude) + # See above + img = F.affine( + img, + angle=0.0, + translate=[0, 0], + scale=1.0, + shear=[0.0, math.degrees(math.atan(magnitude))], + interpolation=interpolation, + fill=fill, + center=[0, 0], + ) + elif op_name == "TranslateX": + img = F.affine( + img, + angle=0.0, + translate=[int(magnitude), 0], + scale=1.0, + interpolation=interpolation, + shear=[0.0, 0.0], + fill=fill, + ) + elif op_name == "TranslateY": + img = F.affine( + img, + angle=0.0, + translate=[0, int(magnitude)], + scale=1.0, + interpolation=interpolation, + shear=[0.0, 0.0], + fill=fill, + ) + elif op_name == "Rotate": + img = F.rotate(img, magnitude, interpolation=interpolation, fill=fill) + elif op_name == "Brightness": + img = F.adjust_brightness(img, 1.0 + magnitude) + elif op_name == "Color": + img = F.adjust_saturation(img, 1.0 + magnitude) + elif op_name == "Contrast": + img = F.adjust_contrast(img, 1.0 + magnitude) + elif op_name == "Sharpness": + img = F.adjust_sharpness(img, 1.0 + magnitude) + elif op_name == "Posterize": + img = F.posterize(img, int(magnitude)) + elif op_name == "Solarize": + img = F.solarize(img, magnitude) + elif op_name == "AutoContrast": + img = F.autocontrast(img) + elif op_name == "Equalize": + img = F.equalize(img) + elif op_name == "Invert": + img = F.invert(img) + elif op_name == "Identity": + pass + else: + raise ValueError(f"The provided operator {op_name} is not recognized.") + return img + + +class AutoAugmentPolicy(Enum): + """AutoAugment policies learned on different datasets. + Available policies are IMAGENET, CIFAR10 and SVHN. + """ + + IMAGENET = "imagenet" + CIFAR10 = "cifar10" + SVHN = "svhn" + + +class AutoAugment(torch.nn.Module): + r"""AutoAugment data augmentation method based on + `"AutoAugment: Learning Augmentation Strategies from Data" `_. + If the image is torch Tensor, it should be of type torch.uint8, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + policy (AutoAugmentPolicy): Desired policy enum defined by + :class:`torchvision.transforms.autoaugment.AutoAugmentPolicy`. Default is ``AutoAugmentPolicy.IMAGENET``. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + def __init__( + self, + policy: AutoAugmentPolicy = AutoAugmentPolicy.IMAGENET, + interpolation: InterpolationMode = InterpolationMode.NEAREST, + fill: Optional[list[float]] = None, + ) -> None: + super().__init__() + self.policy = policy + self.interpolation = interpolation + self.fill = fill + self.policies = self._get_policies(policy) + + def _get_policies( + self, policy: AutoAugmentPolicy + ) -> list[tuple[tuple[str, float, Optional[int]], tuple[str, float, Optional[int]]]]: + if policy == AutoAugmentPolicy.IMAGENET: + return [ + (("Posterize", 0.4, 8), ("Rotate", 0.6, 9)), + (("Solarize", 0.6, 5), ("AutoContrast", 0.6, None)), + (("Equalize", 0.8, None), ("Equalize", 0.6, None)), + (("Posterize", 0.6, 7), ("Posterize", 0.6, 6)), + (("Equalize", 0.4, None), ("Solarize", 0.2, 4)), + (("Equalize", 0.4, None), ("Rotate", 0.8, 8)), + (("Solarize", 0.6, 3), ("Equalize", 0.6, None)), + (("Posterize", 0.8, 5), ("Equalize", 1.0, None)), + (("Rotate", 0.2, 3), ("Solarize", 0.6, 8)), + (("Equalize", 0.6, None), ("Posterize", 0.4, 6)), + (("Rotate", 0.8, 8), ("Color", 0.4, 0)), + (("Rotate", 0.4, 9), ("Equalize", 0.6, None)), + (("Equalize", 0.0, None), ("Equalize", 0.8, None)), + (("Invert", 0.6, None), ("Equalize", 1.0, None)), + (("Color", 0.6, 4), ("Contrast", 1.0, 8)), + (("Rotate", 0.8, 8), ("Color", 1.0, 2)), + (("Color", 0.8, 8), ("Solarize", 0.8, 7)), + (("Sharpness", 0.4, 7), ("Invert", 0.6, None)), + (("ShearX", 0.6, 5), ("Equalize", 1.0, None)), + (("Color", 0.4, 0), ("Equalize", 0.6, None)), + (("Equalize", 0.4, None), ("Solarize", 0.2, 4)), + (("Solarize", 0.6, 5), ("AutoContrast", 0.6, None)), + (("Invert", 0.6, None), ("Equalize", 1.0, None)), + (("Color", 0.6, 4), ("Contrast", 1.0, 8)), + (("Equalize", 0.8, None), ("Equalize", 0.6, None)), + ] + elif policy == AutoAugmentPolicy.CIFAR10: + return [ + (("Invert", 0.1, None), ("Contrast", 0.2, 6)), + (("Rotate", 0.7, 2), ("TranslateX", 0.3, 9)), + (("Sharpness", 0.8, 1), ("Sharpness", 0.9, 3)), + (("ShearY", 0.5, 8), ("TranslateY", 0.7, 9)), + (("AutoContrast", 0.5, None), ("Equalize", 0.9, None)), + (("ShearY", 0.2, 7), ("Posterize", 0.3, 7)), + (("Color", 0.4, 3), ("Brightness", 0.6, 7)), + (("Sharpness", 0.3, 9), ("Brightness", 0.7, 9)), + (("Equalize", 0.6, None), ("Equalize", 0.5, None)), + (("Contrast", 0.6, 7), ("Sharpness", 0.6, 5)), + (("Color", 0.7, 7), ("TranslateX", 0.5, 8)), + (("Equalize", 0.3, None), ("AutoContrast", 0.4, None)), + (("TranslateY", 0.4, 3), ("Sharpness", 0.2, 6)), + (("Brightness", 0.9, 6), ("Color", 0.2, 8)), + (("Solarize", 0.5, 2), ("Invert", 0.0, None)), + (("Equalize", 0.2, None), ("AutoContrast", 0.6, None)), + (("Equalize", 0.2, None), ("Equalize", 0.6, None)), + (("Color", 0.9, 9), ("Equalize", 0.6, None)), + (("AutoContrast", 0.8, None), ("Solarize", 0.2, 8)), + (("Brightness", 0.1, 3), ("Color", 0.7, 0)), + (("Solarize", 0.4, 5), ("AutoContrast", 0.9, None)), + (("TranslateY", 0.9, 9), ("TranslateY", 0.7, 9)), + (("AutoContrast", 0.9, None), ("Solarize", 0.8, 3)), + (("Equalize", 0.8, None), ("Invert", 0.1, None)), + (("TranslateY", 0.7, 9), ("AutoContrast", 0.9, None)), + ] + elif policy == AutoAugmentPolicy.SVHN: + return [ + (("ShearX", 0.9, 4), ("Invert", 0.2, None)), + (("ShearY", 0.9, 8), ("Invert", 0.7, None)), + (("Equalize", 0.6, None), ("Solarize", 0.6, 6)), + (("Invert", 0.9, None), ("Equalize", 0.6, None)), + (("Equalize", 0.6, None), ("Rotate", 0.9, 3)), + (("ShearX", 0.9, 4), ("AutoContrast", 0.8, None)), + (("ShearY", 0.9, 8), ("Invert", 0.4, None)), + (("ShearY", 0.9, 5), ("Solarize", 0.2, 6)), + (("Invert", 0.9, None), ("AutoContrast", 0.8, None)), + (("Equalize", 0.6, None), ("Rotate", 0.9, 3)), + (("ShearX", 0.9, 4), ("Solarize", 0.3, 3)), + (("ShearY", 0.8, 8), ("Invert", 0.7, None)), + (("Equalize", 0.9, None), ("TranslateY", 0.6, 6)), + (("Invert", 0.9, None), ("Equalize", 0.6, None)), + (("Contrast", 0.3, 3), ("Rotate", 0.8, 4)), + (("Invert", 0.8, None), ("TranslateY", 0.0, 2)), + (("ShearY", 0.7, 6), ("Solarize", 0.4, 8)), + (("Invert", 0.6, None), ("Rotate", 0.8, 4)), + (("ShearY", 0.3, 7), ("TranslateX", 0.9, 3)), + (("ShearX", 0.1, 6), ("Invert", 0.6, None)), + (("Solarize", 0.7, 2), ("TranslateY", 0.6, 7)), + (("ShearY", 0.8, 4), ("Invert", 0.8, None)), + (("ShearX", 0.7, 9), ("TranslateY", 0.8, 3)), + (("ShearY", 0.8, 5), ("AutoContrast", 0.7, None)), + (("ShearX", 0.7, 2), ("Invert", 0.1, None)), + ] + else: + raise ValueError(f"The provided policy {policy} is not recognized.") + + def _augmentation_space(self, num_bins: int, image_size: tuple[int, int]) -> dict[str, tuple[Tensor, bool]]: + return { + # op_name: (magnitudes, signed) + "ShearX": (torch.linspace(0.0, 0.3, num_bins), True), + "ShearY": (torch.linspace(0.0, 0.3, num_bins), True), + "TranslateX": (torch.linspace(0.0, 150.0 / 331.0 * image_size[1], num_bins), True), + "TranslateY": (torch.linspace(0.0, 150.0 / 331.0 * image_size[0], num_bins), True), + "Rotate": (torch.linspace(0.0, 30.0, num_bins), True), + "Brightness": (torch.linspace(0.0, 0.9, num_bins), True), + "Color": (torch.linspace(0.0, 0.9, num_bins), True), + "Contrast": (torch.linspace(0.0, 0.9, num_bins), True), + "Sharpness": (torch.linspace(0.0, 0.9, num_bins), True), + "Posterize": (8 - (torch.arange(num_bins) / ((num_bins - 1) / 4)).round().int(), False), + "Solarize": (torch.linspace(255.0, 0.0, num_bins), False), + "AutoContrast": (torch.tensor(0.0), False), + "Equalize": (torch.tensor(0.0), False), + "Invert": (torch.tensor(0.0), False), + } + + @staticmethod + def get_params(transform_num: int) -> tuple[int, Tensor, Tensor]: + """Get parameters for autoaugment transformation + + Returns: + params required by the autoaugment transformation + """ + policy_id = int(torch.randint(transform_num, (1,)).item()) + probs = torch.rand((2,)) + signs = torch.randint(2, (2,)) + + return policy_id, probs, signs + + def forward(self, img: Tensor) -> Tensor: + """ + img (PIL Image or Tensor): Image to be transformed. + + Returns: + PIL Image or Tensor: AutoAugmented image. + """ + fill = self.fill + channels, height, width = F.get_dimensions(img) + if isinstance(img, Tensor): + if isinstance(fill, (int, float)): + fill = [float(fill)] * channels + elif fill is not None: + fill = [float(f) for f in fill] + + transform_id, probs, signs = self.get_params(len(self.policies)) + + op_meta = self._augmentation_space(10, (height, width)) + for i, (op_name, p, magnitude_id) in enumerate(self.policies[transform_id]): + if probs[i] <= p: + magnitudes, signed = op_meta[op_name] + magnitude = float(magnitudes[magnitude_id].item()) if magnitude_id is not None else 0.0 + if signed and signs[i] == 0: + magnitude *= -1.0 + img = _apply_op(img, op_name, magnitude, interpolation=self.interpolation, fill=fill) + + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(policy={self.policy}, fill={self.fill})" + + +class RandAugment(torch.nn.Module): + r"""RandAugment data augmentation method based on + `"RandAugment: Practical automated data augmentation with a reduced search space" + `_. + If the image is torch Tensor, it should be of type torch.uint8, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + num_ops (int): Number of augmentation transformations to apply sequentially. + magnitude (int): Magnitude for all the transformations. + num_magnitude_bins (int): The number of different magnitude values. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + def __init__( + self, + num_ops: int = 2, + magnitude: int = 9, + num_magnitude_bins: int = 31, + interpolation: InterpolationMode = InterpolationMode.NEAREST, + fill: Optional[list[float]] = None, + ) -> None: + super().__init__() + self.num_ops = num_ops + self.magnitude = magnitude + self.num_magnitude_bins = num_magnitude_bins + self.interpolation = interpolation + self.fill = fill + + def _augmentation_space(self, num_bins: int, image_size: tuple[int, int]) -> dict[str, tuple[Tensor, bool]]: + return { + # op_name: (magnitudes, signed) + "Identity": (torch.tensor(0.0), False), + "ShearX": (torch.linspace(0.0, 0.3, num_bins), True), + "ShearY": (torch.linspace(0.0, 0.3, num_bins), True), + "TranslateX": (torch.linspace(0.0, 150.0 / 331.0 * image_size[1], num_bins), True), + "TranslateY": (torch.linspace(0.0, 150.0 / 331.0 * image_size[0], num_bins), True), + "Rotate": (torch.linspace(0.0, 30.0, num_bins), True), + "Brightness": (torch.linspace(0.0, 0.9, num_bins), True), + "Color": (torch.linspace(0.0, 0.9, num_bins), True), + "Contrast": (torch.linspace(0.0, 0.9, num_bins), True), + "Sharpness": (torch.linspace(0.0, 0.9, num_bins), True), + "Posterize": (8 - (torch.arange(num_bins) / ((num_bins - 1) / 4)).round().int(), False), + "Solarize": (torch.linspace(255.0, 0.0, num_bins), False), + "AutoContrast": (torch.tensor(0.0), False), + "Equalize": (torch.tensor(0.0), False), + } + + def forward(self, img: Tensor) -> Tensor: + """ + img (PIL Image or Tensor): Image to be transformed. + + Returns: + PIL Image or Tensor: Transformed image. + """ + fill = self.fill + channels, height, width = F.get_dimensions(img) + if isinstance(img, Tensor): + if isinstance(fill, (int, float)): + fill = [float(fill)] * channels + elif fill is not None: + fill = [float(f) for f in fill] + + op_meta = self._augmentation_space(self.num_magnitude_bins, (height, width)) + for _ in range(self.num_ops): + op_index = int(torch.randint(len(op_meta), (1,)).item()) + op_name = list(op_meta.keys())[op_index] + magnitudes, signed = op_meta[op_name] + magnitude = float(magnitudes[self.magnitude].item()) if magnitudes.ndim > 0 else 0.0 + if signed and torch.randint(2, (1,)): + magnitude *= -1.0 + img = _apply_op(img, op_name, magnitude, interpolation=self.interpolation, fill=fill) + + return img + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"num_ops={self.num_ops}" + f", magnitude={self.magnitude}" + f", num_magnitude_bins={self.num_magnitude_bins}" + f", interpolation={self.interpolation}" + f", fill={self.fill}" + f")" + ) + return s + + +class TrivialAugmentWide(torch.nn.Module): + r"""Dataset-independent data-augmentation with TrivialAugment Wide, as described in + `"TrivialAugment: Tuning-free Yet State-of-the-Art Data Augmentation" `_. + If the image is torch Tensor, it should be of type torch.uint8, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + num_magnitude_bins (int): The number of different magnitude values. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + def __init__( + self, + num_magnitude_bins: int = 31, + interpolation: InterpolationMode = InterpolationMode.NEAREST, + fill: Optional[list[float]] = None, + ) -> None: + super().__init__() + self.num_magnitude_bins = num_magnitude_bins + self.interpolation = interpolation + self.fill = fill + + def _augmentation_space(self, num_bins: int) -> dict[str, tuple[Tensor, bool]]: + return { + # op_name: (magnitudes, signed) + "Identity": (torch.tensor(0.0), False), + "ShearX": (torch.linspace(0.0, 0.99, num_bins), True), + "ShearY": (torch.linspace(0.0, 0.99, num_bins), True), + "TranslateX": (torch.linspace(0.0, 32.0, num_bins), True), + "TranslateY": (torch.linspace(0.0, 32.0, num_bins), True), + "Rotate": (torch.linspace(0.0, 135.0, num_bins), True), + "Brightness": (torch.linspace(0.0, 0.99, num_bins), True), + "Color": (torch.linspace(0.0, 0.99, num_bins), True), + "Contrast": (torch.linspace(0.0, 0.99, num_bins), True), + "Sharpness": (torch.linspace(0.0, 0.99, num_bins), True), + "Posterize": (8 - (torch.arange(num_bins) / ((num_bins - 1) / 6)).round().int(), False), + "Solarize": (torch.linspace(255.0, 0.0, num_bins), False), + "AutoContrast": (torch.tensor(0.0), False), + "Equalize": (torch.tensor(0.0), False), + } + + def forward(self, img: Tensor) -> Tensor: + """ + img (PIL Image or Tensor): Image to be transformed. + + Returns: + PIL Image or Tensor: Transformed image. + """ + fill = self.fill + channels, height, width = F.get_dimensions(img) + if isinstance(img, Tensor): + if isinstance(fill, (int, float)): + fill = [float(fill)] * channels + elif fill is not None: + fill = [float(f) for f in fill] + + op_meta = self._augmentation_space(self.num_magnitude_bins) + op_index = int(torch.randint(len(op_meta), (1,)).item()) + op_name = list(op_meta.keys())[op_index] + magnitudes, signed = op_meta[op_name] + magnitude = ( + float(magnitudes[torch.randint(len(magnitudes), (1,), dtype=torch.long)].item()) + if magnitudes.ndim > 0 + else 0.0 + ) + if signed and torch.randint(2, (1,)): + magnitude *= -1.0 + + return _apply_op(img, op_name, magnitude, interpolation=self.interpolation, fill=fill) + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"num_magnitude_bins={self.num_magnitude_bins}" + f", interpolation={self.interpolation}" + f", fill={self.fill}" + f")" + ) + return s + + +class AugMix(torch.nn.Module): + r"""AugMix data augmentation method based on + `"AugMix: A Simple Data Processing Method to Improve Robustness and Uncertainty" `_. + If the image is torch Tensor, it should be of type torch.uint8, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + severity (int): The severity of base augmentation operators. Default is ``3``. + mixture_width (int): The number of augmentation chains. Default is ``3``. + chain_depth (int): The depth of augmentation chains. A negative value denotes stochastic depth sampled from the interval [1, 3]. + Default is ``-1``. + alpha (float): The hyperparameter for the probability distributions. Default is ``1.0``. + all_ops (bool): Use all operations (including brightness, contrast, color and sharpness). Default is ``True``. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + def __init__( + self, + severity: int = 3, + mixture_width: int = 3, + chain_depth: int = -1, + alpha: float = 1.0, + all_ops: bool = True, + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + fill: Optional[list[float]] = None, + ) -> None: + super().__init__() + self._PARAMETER_MAX = 10 + if not (1 <= severity <= self._PARAMETER_MAX): + raise ValueError(f"The severity must be between [1, {self._PARAMETER_MAX}]. Got {severity} instead.") + self.severity = severity + self.mixture_width = mixture_width + self.chain_depth = chain_depth + self.alpha = alpha + self.all_ops = all_ops + self.interpolation = interpolation + self.fill = fill + + def _augmentation_space(self, num_bins: int, image_size: tuple[int, int]) -> dict[str, tuple[Tensor, bool]]: + s = { + # op_name: (magnitudes, signed) + "ShearX": (torch.linspace(0.0, 0.3, num_bins), True), + "ShearY": (torch.linspace(0.0, 0.3, num_bins), True), + "TranslateX": (torch.linspace(0.0, image_size[1] / 3.0, num_bins), True), + "TranslateY": (torch.linspace(0.0, image_size[0] / 3.0, num_bins), True), + "Rotate": (torch.linspace(0.0, 30.0, num_bins), True), + "Posterize": (4 - (torch.arange(num_bins) / ((num_bins - 1) / 4)).round().int(), False), + "Solarize": (torch.linspace(255.0, 0.0, num_bins), False), + "AutoContrast": (torch.tensor(0.0), False), + "Equalize": (torch.tensor(0.0), False), + } + if self.all_ops: + s.update( + { + "Brightness": (torch.linspace(0.0, 0.9, num_bins), True), + "Color": (torch.linspace(0.0, 0.9, num_bins), True), + "Contrast": (torch.linspace(0.0, 0.9, num_bins), True), + "Sharpness": (torch.linspace(0.0, 0.9, num_bins), True), + } + ) + return s + + @torch.jit.unused + def _pil_to_tensor(self, img) -> Tensor: + return F.pil_to_tensor(img) + + @torch.jit.unused + def _tensor_to_pil(self, img: Tensor): + return F.to_pil_image(img) + + def _sample_dirichlet(self, params: Tensor) -> Tensor: + # Must be on a separate method so that we can overwrite it in tests. + return torch._sample_dirichlet(params) + + def forward(self, orig_img: Tensor) -> Tensor: + """ + img (PIL Image or Tensor): Image to be transformed. + + Returns: + PIL Image or Tensor: Transformed image. + """ + fill = self.fill + channels, height, width = F.get_dimensions(orig_img) + if isinstance(orig_img, Tensor): + img = orig_img + if isinstance(fill, (int, float)): + fill = [float(fill)] * channels + elif fill is not None: + fill = [float(f) for f in fill] + else: + img = self._pil_to_tensor(orig_img) + + op_meta = self._augmentation_space(self._PARAMETER_MAX, (height, width)) + + orig_dims = list(img.shape) + batch = img.view([1] * max(4 - img.ndim, 0) + orig_dims) + batch_dims = [batch.size(0)] + [1] * (batch.ndim - 1) + + # Sample the beta weights for combining the original and augmented image. To get Beta, we use a Dirichlet + # with 2 parameters. The 1st column stores the weights of the original and the 2nd the ones of augmented image. + m = self._sample_dirichlet( + torch.tensor([self.alpha, self.alpha], device=batch.device).expand(batch_dims[0], -1) + ) + + # Sample the mixing weights and combine them with the ones sampled from Beta for the augmented images. + combined_weights = self._sample_dirichlet( + torch.tensor([self.alpha] * self.mixture_width, device=batch.device).expand(batch_dims[0], -1) + ) * m[:, 1].view([batch_dims[0], -1]) + + mix = m[:, 0].view(batch_dims) * batch + for i in range(self.mixture_width): + aug = batch + depth = self.chain_depth if self.chain_depth > 0 else int(torch.randint(low=1, high=4, size=(1,)).item()) + for _ in range(depth): + op_index = int(torch.randint(len(op_meta), (1,)).item()) + op_name = list(op_meta.keys())[op_index] + magnitudes, signed = op_meta[op_name] + magnitude = ( + float(magnitudes[torch.randint(self.severity, (1,), dtype=torch.long)].item()) + if magnitudes.ndim > 0 + else 0.0 + ) + if signed and torch.randint(2, (1,)): + magnitude *= -1.0 + aug = _apply_op(aug, op_name, magnitude, interpolation=self.interpolation, fill=fill) + mix.add_(combined_weights[:, i].view(batch_dims) * aug) + mix = mix.view(orig_dims).to(dtype=img.dtype) + + if not isinstance(orig_img, Tensor): + return self._tensor_to_pil(mix) + return mix + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"severity={self.severity}" + f", mixture_width={self.mixture_width}" + f", chain_depth={self.chain_depth}" + f", alpha={self.alpha}" + f", all_ops={self.all_ops}" + f", interpolation={self.interpolation}" + f", fill={self.fill}" + f")" + ) + return s diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/functional.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..7b950b0c45b53f82949d3fe14850a3d1c17f24d1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/functional.py @@ -0,0 +1,1586 @@ +import math +import numbers +import sys +import warnings +from enum import Enum +from typing import Any, Optional, Union + +import numpy as np +import torch +from PIL import Image +from PIL.Image import Image as PILImage +from torch import Tensor + +try: + import accimage +except ImportError: + accimage = None + +from ..utils import _Image_fromarray, _log_api_usage_once +from . import _functional_pil as F_pil, _functional_tensor as F_t + + +class InterpolationMode(Enum): + """Interpolation modes + Available interpolation methods are ``nearest``, ``nearest-exact``, ``bilinear``, ``bicubic``, ``box``, ``hamming``, + and ``lanczos``. + """ + + NEAREST = "nearest" + NEAREST_EXACT = "nearest-exact" + BILINEAR = "bilinear" + BICUBIC = "bicubic" + # For PIL compatibility + BOX = "box" + HAMMING = "hamming" + LANCZOS = "lanczos" + + +# TODO: Once torchscript supports Enums with staticmethod +# this can be put into InterpolationMode as staticmethod +def _interpolation_modes_from_int(i: int) -> InterpolationMode: + inverse_modes_mapping = { + 0: InterpolationMode.NEAREST, + 2: InterpolationMode.BILINEAR, + 3: InterpolationMode.BICUBIC, + 4: InterpolationMode.BOX, + 5: InterpolationMode.HAMMING, + 1: InterpolationMode.LANCZOS, + } + return inverse_modes_mapping[i] + + +pil_modes_mapping = { + InterpolationMode.NEAREST: 0, + InterpolationMode.BILINEAR: 2, + InterpolationMode.BICUBIC: 3, + InterpolationMode.NEAREST_EXACT: 0, + InterpolationMode.BOX: 4, + InterpolationMode.HAMMING: 5, + InterpolationMode.LANCZOS: 1, +} + +_is_pil_image = F_pil._is_pil_image + + +def get_dimensions(img: Tensor) -> list[int]: + """Returns the dimensions of an image as [channels, height, width]. + + Args: + img (PIL Image or Tensor): The image to be checked. + + Returns: + List[int]: The image dimensions. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(get_dimensions) + if isinstance(img, torch.Tensor): + return F_t.get_dimensions(img) + + return F_pil.get_dimensions(img) + + +def get_image_size(img: Tensor) -> list[int]: + """Returns the size of an image as [width, height]. + + Args: + img (PIL Image or Tensor): The image to be checked. + + Returns: + List[int]: The image size. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(get_image_size) + if isinstance(img, torch.Tensor): + return F_t.get_image_size(img) + + return F_pil.get_image_size(img) + + +def get_image_num_channels(img: Tensor) -> int: + """Returns the number of channels of an image. + + Args: + img (PIL Image or Tensor): The image to be checked. + + Returns: + int: The number of channels. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(get_image_num_channels) + if isinstance(img, torch.Tensor): + return F_t.get_image_num_channels(img) + + return F_pil.get_image_num_channels(img) + + +@torch.jit.unused +def _is_numpy(img: Any) -> bool: + return isinstance(img, np.ndarray) + + +@torch.jit.unused +def _is_numpy_image(img: Any) -> bool: + return img.ndim in {2, 3} + + +def to_tensor(pic: Union[PILImage, np.ndarray]) -> Tensor: + """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. + This function does not support torchscript. + + See :class:`~torchvision.transforms.ToTensor` for more details. + + Args: + pic (PIL Image or numpy.ndarray): Image to be converted to tensor. + + Returns: + Tensor: Converted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(to_tensor) + if not (F_pil._is_pil_image(pic) or _is_numpy(pic)): + raise TypeError(f"pic should be PIL Image or ndarray. Got {type(pic)}") + + if _is_numpy(pic) and not _is_numpy_image(pic): + raise ValueError(f"pic should be 2/3 dimensional. Got {pic.ndim} dimensions.") + + default_float_dtype = torch.get_default_dtype() + + if isinstance(pic, np.ndarray): + # handle numpy array + if pic.ndim == 2: + pic = pic[:, :, None] + + img = torch.from_numpy(pic.transpose((2, 0, 1))).contiguous() + # backward compatibility + if isinstance(img, torch.ByteTensor): + return img.to(dtype=default_float_dtype).div(255) + else: + return img + + if accimage is not None and isinstance(pic, accimage.Image): + nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32) + pic.copyto(nppic) + return torch.from_numpy(nppic).to(dtype=default_float_dtype) + + # handle PIL Image + mode_to_nptype = {"I": np.int32, "I;16" if sys.byteorder == "little" else "I;16B": np.int16, "F": np.float32} + img = torch.from_numpy(np.array(pic, mode_to_nptype.get(pic.mode, np.uint8), copy=True)) + + if pic.mode == "1": + img = 255 * img + img = img.view(pic.size[1], pic.size[0], F_pil.get_image_num_channels(pic)) + # put it from HWC to CHW format + img = img.permute((2, 0, 1)).contiguous() + if isinstance(img, torch.ByteTensor): + return img.to(dtype=default_float_dtype).div(255) + else: + return img + + +def pil_to_tensor(pic: Any) -> Tensor: + """Convert a ``PIL Image`` to a tensor of the same type. + This function does not support torchscript. + + See :class:`~torchvision.transforms.PILToTensor` for more details. + + .. note:: + + A deep copy of the underlying array is performed. + + Args: + pic (PIL Image): Image to be converted to tensor. + + Returns: + Tensor: Converted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(pil_to_tensor) + if not F_pil._is_pil_image(pic): + raise TypeError(f"pic should be PIL Image. Got {type(pic)}") + + if accimage is not None and isinstance(pic, accimage.Image): + # accimage format is always uint8 internally, so always return uint8 here + nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.uint8) + pic.copyto(nppic) + return torch.as_tensor(nppic) + + # handle PIL Image + img = torch.as_tensor(np.array(pic, copy=True)) + img = img.view(pic.size[1], pic.size[0], F_pil.get_image_num_channels(pic)) + # put it from HWC to CHW format + img = img.permute((2, 0, 1)) + return img + + +def convert_image_dtype(image: torch.Tensor, dtype: torch.dtype = torch.float) -> torch.Tensor: + """Convert a tensor image to the given ``dtype`` and scale the values accordingly + This function does not support PIL Image. + + Args: + image (torch.Tensor): Image to be converted + dtype (torch.dtype): Desired data type of the output + + Returns: + Tensor: Converted image + + .. note:: + + When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly. + If converted back and forth, this mismatch has no effect. + + Raises: + RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as + well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to + overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range + of the integer ``dtype``. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(convert_image_dtype) + if not isinstance(image, torch.Tensor): + raise TypeError("Input img should be Tensor Image") + + return F_t.convert_image_dtype(image, dtype) + + +def to_pil_image(pic, mode=None): + """Convert a tensor or an ndarray to PIL Image. This function does not support torchscript. + + See :class:`~torchvision.transforms.ToPILImage` for more details. + + Args: + pic (Tensor or numpy.ndarray): Image to be converted to PIL Image. + mode (`PIL.Image mode`_): color space and pixel depth of input data (optional). + + .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes + + Returns: + PIL Image: Image converted to PIL Image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(to_pil_image) + + if isinstance(pic, torch.Tensor): + if pic.ndim == 3: + pic = pic.permute((1, 2, 0)) + pic = pic.numpy(force=True) + elif not isinstance(pic, np.ndarray): + raise TypeError(f"pic should be Tensor or ndarray. Got {type(pic)}.") + + if pic.ndim == 2: + # if 2D image, add channel dimension (HWC) + pic = np.expand_dims(pic, 2) + if pic.ndim != 3: + raise ValueError(f"pic should be 2/3 dimensional. Got {pic.ndim} dimensions.") + + if pic.shape[-1] > 4: + raise ValueError(f"pic should not have > 4 channels. Got {pic.shape[-1]} channels.") + + npimg = pic + + if np.issubdtype(npimg.dtype, np.floating) and mode != "F": + npimg = (npimg * 255).astype(np.uint8) + + if npimg.shape[2] == 1: + expected_mode = None + npimg = npimg[:, :, 0] + if npimg.dtype == np.uint8: + expected_mode = "L" + elif npimg.dtype == np.int16: + expected_mode = "I;16" if sys.byteorder == "little" else "I;16B" + elif npimg.dtype == np.int32: + expected_mode = "I" + elif npimg.dtype == np.float32: + expected_mode = "F" + if mode is not None and mode != expected_mode: + raise ValueError(f"Incorrect mode ({mode}) supplied for input type {np.dtype}. Should be {expected_mode}") + mode = expected_mode + + elif npimg.shape[2] == 2: + permitted_2_channel_modes = ["LA"] + if mode is not None and mode not in permitted_2_channel_modes: + raise ValueError(f"Only modes {permitted_2_channel_modes} are supported for 2D inputs") + + if mode is None and npimg.dtype == np.uint8: + mode = "LA" + + elif npimg.shape[2] == 4: + permitted_4_channel_modes = ["RGBA", "CMYK", "RGBX"] + if mode is not None and mode not in permitted_4_channel_modes: + raise ValueError(f"Only modes {permitted_4_channel_modes} are supported for 4D inputs") + + if mode is None and npimg.dtype == np.uint8: + mode = "RGBA" + else: + permitted_3_channel_modes = ["RGB", "YCbCr", "HSV"] + if mode is not None and mode not in permitted_3_channel_modes: + raise ValueError(f"Only modes {permitted_3_channel_modes} are supported for 3D inputs") + if mode is None and npimg.dtype == np.uint8: + mode = "RGB" + + if mode is None: + raise TypeError(f"Input type {npimg.dtype} is not supported") + + return _Image_fromarray(npimg, mode=mode) + + +def normalize(tensor: Tensor, mean: list[float], std: list[float], inplace: bool = False) -> Tensor: + """Normalize a float tensor image with mean and standard deviation. + This transform does not support PIL Image. + + .. note:: + This transform acts out of place by default, i.e., it does not mutates the input tensor. + + See :class:`~torchvision.transforms.Normalize` for more details. + + Args: + tensor (Tensor): Float tensor image of size (C, H, W) or (B, C, H, W) to be normalized. + mean (sequence): Sequence of means for each channel. + std (sequence): Sequence of standard deviations for each channel. + inplace(bool,optional): Bool to make this operation inplace. + + Returns: + Tensor: Normalized Tensor image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(normalize) + if not isinstance(tensor, torch.Tensor): + raise TypeError(f"img should be Tensor Image. Got {type(tensor)}") + + return F_t.normalize(tensor, mean=mean, std=std, inplace=inplace) + + +def _compute_resized_output_size( + image_size: tuple[int, int], + size: Optional[list[int]], + max_size: Optional[int] = None, + allow_size_none: bool = False, # only True in v2 +) -> list[int]: + h, w = image_size + short, long = (w, h) if w <= h else (h, w) + if size is None: + if not allow_size_none: + raise ValueError("This should never happen!!") + if not isinstance(max_size, int): + raise ValueError(f"max_size must be an integer when size is None, but got {max_size} instead.") + new_short, new_long = int(max_size * short / long), max_size + new_w, new_h = (new_short, new_long) if w <= h else (new_long, new_short) + elif len(size) == 1: # specified size only for the smallest edge + requested_new_short = size if isinstance(size, int) else size[0] + new_short, new_long = requested_new_short, int(requested_new_short * long / short) + + if max_size is not None: + if max_size <= requested_new_short: + raise ValueError( + f"max_size = {max_size} must be strictly greater than the requested " + f"size for the smaller edge size = {size}" + ) + if new_long > max_size: + new_short, new_long = int(max_size * new_short / new_long), max_size + + new_w, new_h = (new_short, new_long) if w <= h else (new_long, new_short) + else: # specified both h and w + new_w, new_h = size[1], size[0] + return [new_h, new_w] + + +def resize( + img: Tensor, + size: list[int], + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, + antialias: Optional[bool] = True, +) -> Tensor: + r"""Resize the input image to the given size. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions + + Args: + img (PIL Image or Tensor): Image to be resized. + size (sequence or int): Desired output size. If size is a sequence like + (h, w), the output size will be matched to this. If size is an int, + the smaller edge of the image will be matched to this number maintaining + the aspect ratio. i.e, if height > width, then image will be rescaled to + :math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)`. + + .. note:: + In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. + Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``, + ``InterpolationMode.NEAREST_EXACT``, ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are + supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + max_size (int, optional): The maximum allowed for the longer edge of + the resized image. If the longer edge of the image is greater + than ``max_size`` after being resized according to ``size``, + ``size`` will be overruled so that the longer edge is equal to + ``max_size``. + As a result, the smaller edge may be shorter than ``size``. This + is only supported if ``size`` is an int (or a sequence of length + 1 in torchscript mode). + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear or bicubic modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear or bicubic modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + + Returns: + PIL Image or Tensor: Resized image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(resize) + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + elif not isinstance(interpolation, InterpolationMode): + raise TypeError( + "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant" + ) + + if isinstance(size, (list, tuple)): + if len(size) not in [1, 2]: + raise ValueError( + f"Size must be an int or a 1 or 2 element tuple/list, not a {len(size)} element tuple/list" + ) + if max_size is not None and len(size) != 1: + raise ValueError( + "max_size should only be passed if size specifies the length of the smaller edge, " + "i.e. size should be an int or a sequence of length 1 in torchscript mode." + ) + + _, image_height, image_width = get_dimensions(img) + if isinstance(size, int): + size = [size] + output_size = _compute_resized_output_size((image_height, image_width), size, max_size) + + if [image_height, image_width] == output_size: + return img + + if not isinstance(img, torch.Tensor): + if antialias is False: + warnings.warn("Anti-alias option is always applied for PIL Image input. Argument antialias is ignored.") + pil_interpolation = pil_modes_mapping[interpolation] + return F_pil.resize(img, size=output_size, interpolation=pil_interpolation) + + return F_t.resize(img, size=output_size, interpolation=interpolation.value, antialias=antialias) + + +def pad(img: Tensor, padding: list[int], fill: Union[int, float] = 0, padding_mode: str = "constant") -> Tensor: + r"""Pad the given image on all sides with the given "pad" value. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric, + at most 3 leading dimensions for mode edge, + and an arbitrary number of leading dimensions for mode constant + + Args: + img (PIL Image or Tensor): Image to be padded. + padding (int or sequence): Padding on each border. If a single int is provided this + is used to pad all borders. If sequence of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a sequence of length 4 is provided + this is the padding for the left, top, right and bottom borders respectively. + + .. note:: + In torchscript mode padding as single int is not supported, use a sequence of + length 1: ``[padding, ]``. + fill (number or tuple): Pixel fill value for constant fill. Default is 0. + If a tuple of length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. + Only number is supported for torch Tensor. + Only int or tuple value is supported for PIL Image. + padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric. + Default is constant. + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value at the edge of the image. + If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2 + + - reflect: pads with reflection of image without repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + + Returns: + PIL Image or Tensor: Padded image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(pad) + if not isinstance(img, torch.Tensor): + return F_pil.pad(img, padding=padding, fill=fill, padding_mode=padding_mode) + + return F_t.pad(img, padding=padding, fill=fill, padding_mode=padding_mode) + + +def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor: + """Crop the given image at specified location and output size. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + If image size is smaller than output size along any edge, image is padded with 0 and then cropped. + + Args: + img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image. + top (int): Vertical component of the top left corner of the crop box. + left (int): Horizontal component of the top left corner of the crop box. + height (int): Height of the crop box. + width (int): Width of the crop box. + + Returns: + PIL Image or Tensor: Cropped image. + """ + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(crop) + if not isinstance(img, torch.Tensor): + return F_pil.crop(img, top, left, height, width) + + return F_t.crop(img, top, left, height, width) + + +def center_crop(img: Tensor, output_size: list[int]) -> Tensor: + """Crops the given image at the center. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + If image size is smaller than output size along any edge, image is padded with 0 and then center cropped. + + Args: + img (PIL Image or Tensor): Image to be cropped. + output_size (sequence or int): (height, width) of the crop box. If int or sequence with single int, + it is used for both directions. + + Returns: + PIL Image or Tensor: Cropped image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(center_crop) + if isinstance(output_size, numbers.Number): + output_size = (int(output_size), int(output_size)) + elif isinstance(output_size, (tuple, list)) and len(output_size) == 1: + output_size = (output_size[0], output_size[0]) + + _, image_height, image_width = get_dimensions(img) + crop_height, crop_width = output_size + + if crop_width > image_width or crop_height > image_height: + padding_ltrb = [ + (crop_width - image_width) // 2 if crop_width > image_width else 0, + (crop_height - image_height) // 2 if crop_height > image_height else 0, + (crop_width - image_width + 1) // 2 if crop_width > image_width else 0, + (crop_height - image_height + 1) // 2 if crop_height > image_height else 0, + ] + img = pad(img, padding_ltrb, fill=0) # PIL uses fill value 0 + _, image_height, image_width = get_dimensions(img) + if crop_width == image_width and crop_height == image_height: + return img + + crop_top = int(round((image_height - crop_height) / 2.0)) + crop_left = int(round((image_width - crop_width) / 2.0)) + return crop(img, crop_top, crop_left, crop_height, crop_width) + + +def resized_crop( + img: Tensor, + top: int, + left: int, + height: int, + width: int, + size: list[int], + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, +) -> Tensor: + """Crop the given image and resize it to desired size. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions + + Notably used in :class:`~torchvision.transforms.RandomResizedCrop`. + + Args: + img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image. + top (int): Vertical component of the top left corner of the crop box. + left (int): Horizontal component of the top left corner of the crop box. + height (int): Height of the crop box. + width (int): Width of the crop box. + size (sequence or int): Desired output size. Same semantics as ``resize``. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. + Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``, + ``InterpolationMode.NEAREST_EXACT``, ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are + supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear or bicubic modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear or bicubic modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + Returns: + PIL Image or Tensor: Cropped image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(resized_crop) + img = crop(img, top, left, height, width) + img = resize(img, size, interpolation, antialias=antialias) + return img + + +def hflip(img: Tensor) -> Tensor: + """Horizontally flip the given image. + + Args: + img (PIL Image or Tensor): Image to be flipped. If img + is a Tensor, it is expected to be in [..., H, W] format, + where ... means it can have an arbitrary number of leading + dimensions. + + Returns: + PIL Image or Tensor: Horizontally flipped image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(hflip) + if not isinstance(img, torch.Tensor): + return F_pil.hflip(img) + + return F_t.hflip(img) + + +def _get_perspective_coeffs(startpoints: list[list[int]], endpoints: list[list[int]]) -> list[float]: + """Helper function to get the coefficients (a, b, c, d, e, f, g, h) for the perspective transforms. + + In Perspective Transform each pixel (x, y) in the original image gets transformed as, + (x, y) -> ( (ax + by + c) / (gx + hy + 1), (dx + ey + f) / (gx + hy + 1) ) + + Args: + startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners + ``[top-left, top-right, bottom-right, bottom-left]`` of the original image. + endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners + ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image. + + Returns: + octuple (a, b, c, d, e, f, g, h) for transforming each pixel. + """ + if len(startpoints) != 4 or len(endpoints) != 4: + raise ValueError( + f"Please provide exactly four corners, got {len(startpoints)} startpoints and {len(endpoints)} endpoints." + ) + a_matrix = torch.zeros(2 * len(startpoints), 8, dtype=torch.float64) + + for i, (p1, p2) in enumerate(zip(endpoints, startpoints)): + a_matrix[2 * i, :] = torch.tensor([p1[0], p1[1], 1, 0, 0, 0, -p2[0] * p1[0], -p2[0] * p1[1]]) + a_matrix[2 * i + 1, :] = torch.tensor([0, 0, 0, p1[0], p1[1], 1, -p2[1] * p1[0], -p2[1] * p1[1]]) + + b_matrix = torch.tensor(startpoints, dtype=torch.float64).view(8) + # do least squares in double precision to prevent numerical issues + res = torch.linalg.lstsq(a_matrix, b_matrix, driver="gels").solution.to(torch.float32) + + output: list[float] = res.tolist() + return output + + +def perspective( + img: Tensor, + startpoints: list[list[int]], + endpoints: list[list[int]], + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + fill: Optional[list[float]] = None, +) -> Tensor: + """Perform perspective transform of the given image. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + img (PIL Image or Tensor): Image to be transformed. + startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners + ``[top-left, top-right, bottom-right, bottom-left]`` of the original image. + endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners + ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + + .. note:: + In torchscript mode single int/float value is not supported, please use a sequence + of length 1: ``[value, ]``. + + Returns: + PIL Image or Tensor: transformed Image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(perspective) + + coeffs = _get_perspective_coeffs(startpoints, endpoints) + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + elif not isinstance(interpolation, InterpolationMode): + raise TypeError( + "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant" + ) + + if not isinstance(img, torch.Tensor): + pil_interpolation = pil_modes_mapping[interpolation] + return F_pil.perspective(img, coeffs, interpolation=pil_interpolation, fill=fill) + + return F_t.perspective(img, coeffs, interpolation=interpolation.value, fill=fill) + + +def vflip(img: Tensor) -> Tensor: + """Vertically flip the given image. + + Args: + img (PIL Image or Tensor): Image to be flipped. If img + is a Tensor, it is expected to be in [..., H, W] format, + where ... means it can have an arbitrary number of leading + dimensions. + + Returns: + PIL Image or Tensor: Vertically flipped image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(vflip) + if not isinstance(img, torch.Tensor): + return F_pil.vflip(img) + + return F_t.vflip(img) + + +def five_crop(img: Tensor, size: list[int]) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: + """Crop the given image into four corners and the central crop. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions + + .. Note:: + This transform returns a tuple of images and there may be a + mismatch in the number of inputs and targets your ``Dataset`` returns. + + Args: + img (PIL Image or Tensor): Image to be cropped. + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + + Returns: + tuple: tuple (tl, tr, bl, br, center) + Corresponding top left, top right, bottom left, bottom right and center crop. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(five_crop) + if isinstance(size, numbers.Number): + size = (int(size), int(size)) + elif isinstance(size, (tuple, list)) and len(size) == 1: + size = (size[0], size[0]) + + if len(size) != 2: + raise ValueError("Please provide only two dimensions (h, w) for size.") + + _, image_height, image_width = get_dimensions(img) + crop_height, crop_width = size + if crop_width > image_width or crop_height > image_height: + msg = "Requested crop size {} is bigger than input size {}" + raise ValueError(msg.format(size, (image_height, image_width))) + + tl = crop(img, 0, 0, crop_height, crop_width) + tr = crop(img, 0, image_width - crop_width, crop_height, crop_width) + bl = crop(img, image_height - crop_height, 0, crop_height, crop_width) + br = crop(img, image_height - crop_height, image_width - crop_width, crop_height, crop_width) + + center = center_crop(img, [crop_height, crop_width]) + + return tl, tr, bl, br, center + + +def ten_crop( + img: Tensor, size: list[int], vertical_flip: bool = False +) -> tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]: + """Generate ten cropped images from the given image. + Crop the given image into four corners and the central crop plus the + flipped version of these (horizontal flipping is used by default). + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions + + .. Note:: + This transform returns a tuple of images and there may be a + mismatch in the number of inputs and targets your ``Dataset`` returns. + + Args: + img (PIL Image or Tensor): Image to be cropped. + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + vertical_flip (bool): Use vertical flipping instead of horizontal + + Returns: + tuple: tuple (tl, tr, bl, br, center, tl_flip, tr_flip, bl_flip, br_flip, center_flip) + Corresponding top left, top right, bottom left, bottom right and + center crop and same for the flipped image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(ten_crop) + if isinstance(size, numbers.Number): + size = (int(size), int(size)) + elif isinstance(size, (tuple, list)) and len(size) == 1: + size = (size[0], size[0]) + + if len(size) != 2: + raise ValueError("Please provide only two dimensions (h, w) for size.") + + first_five = five_crop(img, size) + + if vertical_flip: + img = vflip(img) + else: + img = hflip(img) + + second_five = five_crop(img, size) + return first_five + second_five + + +def adjust_brightness(img: Tensor, brightness_factor: float) -> Tensor: + """Adjust brightness of an image. + + Args: + img (PIL Image or Tensor): Image to be adjusted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + brightness_factor (float): How much to adjust the brightness. Can be + any non-negative number. 0 gives a black image, 1 gives the + original image while 2 increases the brightness by a factor of 2. + + Returns: + PIL Image or Tensor: Brightness adjusted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(adjust_brightness) + if not isinstance(img, torch.Tensor): + return F_pil.adjust_brightness(img, brightness_factor) + + return F_t.adjust_brightness(img, brightness_factor) + + +def adjust_contrast(img: Tensor, contrast_factor: float) -> Tensor: + """Adjust contrast of an image. + + Args: + img (PIL Image or Tensor): Image to be adjusted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + contrast_factor (float): How much to adjust the contrast. Can be any + non-negative number. 0 gives a solid gray image, 1 gives the + original image while 2 increases the contrast by a factor of 2. + + Returns: + PIL Image or Tensor: Contrast adjusted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(adjust_contrast) + if not isinstance(img, torch.Tensor): + return F_pil.adjust_contrast(img, contrast_factor) + + return F_t.adjust_contrast(img, contrast_factor) + + +def adjust_saturation(img: Tensor, saturation_factor: float) -> Tensor: + """Adjust color saturation of an image. + + Args: + img (PIL Image or Tensor): Image to be adjusted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + saturation_factor (float): How much to adjust the saturation. 0 will + give a black and white image, 1 will give the original image while + 2 will enhance the saturation by a factor of 2. + + Returns: + PIL Image or Tensor: Saturation adjusted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(adjust_saturation) + if not isinstance(img, torch.Tensor): + return F_pil.adjust_saturation(img, saturation_factor) + + return F_t.adjust_saturation(img, saturation_factor) + + +def adjust_hue(img: Tensor, hue_factor: float) -> Tensor: + """Adjust hue of an image. + + The image hue is adjusted by converting the image to HSV and + cyclically shifting the intensities in the hue channel (H). + The image is then converted back to original image mode. + + `hue_factor` is the amount of shift in H channel and must be in the + interval `[-0.5, 0.5]`. + + See `Hue`_ for more details. + + .. _Hue: https://en.wikipedia.org/wiki/Hue + + Args: + img (PIL Image or Tensor): Image to be adjusted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image mode "1", "I", "F" and modes with transparency (alpha channel) are not supported. + Note: the pixel values of the input image has to be non-negative for conversion to HSV space; + thus it does not work if you normalize your image to an interval with negative values, + or use an interpolation that generates negative values before using this function. + hue_factor (float): How much to shift the hue channel. Should be in + [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in + HSV space in positive and negative direction respectively. + 0 means no shift. Therefore, both -0.5 and 0.5 will give an image + with complementary colors while 0 gives the original image. + + Returns: + PIL Image or Tensor: Hue adjusted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(adjust_hue) + if not isinstance(img, torch.Tensor): + return F_pil.adjust_hue(img, hue_factor) + + return F_t.adjust_hue(img, hue_factor) + + +def adjust_gamma(img: Tensor, gamma: float, gain: float = 1) -> Tensor: + r"""Perform gamma correction on an image. + + Also known as Power Law Transform. Intensities in RGB mode are adjusted + based on the following equation: + + .. math:: + I_{\text{out}} = 255 \times \text{gain} \times \left(\frac{I_{\text{in}}}{255}\right)^{\gamma} + + See `Gamma Correction`_ for more details. + + .. _Gamma Correction: https://en.wikipedia.org/wiki/Gamma_correction + + Args: + img (PIL Image or Tensor): PIL Image to be adjusted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, modes with transparency (alpha channel) are not supported. + gamma (float): Non negative real number, same as :math:`\gamma` in the equation. + gamma larger than 1 make the shadows darker, + while gamma smaller than 1 make dark regions lighter. + gain (float): The constant multiplier. + Returns: + PIL Image or Tensor: Gamma correction adjusted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(adjust_gamma) + if not isinstance(img, torch.Tensor): + return F_pil.adjust_gamma(img, gamma, gain) + + return F_t.adjust_gamma(img, gamma, gain) + + +def _get_inverse_affine_matrix( + center: list[float], angle: float, translate: list[float], scale: float, shear: list[float], inverted: bool = True +) -> list[float]: + # Helper method to compute inverse matrix for affine transformation + + # Pillow requires inverse affine transformation matrix: + # Affine matrix is : M = T * C * RotateScaleShear * C^-1 + # + # where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1] + # C is translation matrix to keep center: [1, 0, cx | 0, 1, cy | 0, 0, 1] + # RotateScaleShear is rotation with scale and shear matrix + # + # RotateScaleShear(a, s, (sx, sy)) = + # = R(a) * S(s) * SHy(sy) * SHx(sx) + # = [ s*cos(a - sy)/cos(sy), s*(-cos(a - sy)*tan(sx)/cos(sy) - sin(a)), 0 ] + # [ s*sin(a - sy)/cos(sy), s*(-sin(a - sy)*tan(sx)/cos(sy) + cos(a)), 0 ] + # [ 0 , 0 , 1 ] + # where R is a rotation matrix, S is a scaling matrix, and SHx and SHy are the shears: + # SHx(s) = [1, -tan(s)] and SHy(s) = [1 , 0] + # [0, 1 ] [-tan(s), 1] + # + # Thus, the inverse is M^-1 = C * RotateScaleShear^-1 * C^-1 * T^-1 + + rot = math.radians(angle) + sx = math.radians(shear[0]) + sy = math.radians(shear[1]) + + cx, cy = center + tx, ty = translate + + # RSS without scaling + a = math.cos(rot - sy) / math.cos(sy) + b = -math.cos(rot - sy) * math.tan(sx) / math.cos(sy) - math.sin(rot) + c = math.sin(rot - sy) / math.cos(sy) + d = -math.sin(rot - sy) * math.tan(sx) / math.cos(sy) + math.cos(rot) + + if inverted: + # Inverted rotation matrix with scale and shear + # det([[a, b], [c, d]]) == 1, since det(rotation) = 1 and det(shear) = 1 + matrix = [d, -b, 0.0, -c, a, 0.0] + matrix = [x / scale for x in matrix] + # Apply inverse of translation and of center translation: RSS^-1 * C^-1 * T^-1 + matrix[2] += matrix[0] * (-cx - tx) + matrix[1] * (-cy - ty) + matrix[5] += matrix[3] * (-cx - tx) + matrix[4] * (-cy - ty) + # Apply center translation: C * RSS^-1 * C^-1 * T^-1 + matrix[2] += cx + matrix[5] += cy + else: + matrix = [a, b, 0.0, c, d, 0.0] + matrix = [x * scale for x in matrix] + # Apply inverse of center translation: RSS * C^-1 + matrix[2] += matrix[0] * (-cx) + matrix[1] * (-cy) + matrix[5] += matrix[3] * (-cx) + matrix[4] * (-cy) + # Apply translation and center : T * C * RSS * C^-1 + matrix[2] += cx + tx + matrix[5] += cy + ty + + return matrix + + +def rotate( + img: Tensor, + angle: float, + interpolation: InterpolationMode = InterpolationMode.NEAREST, + expand: bool = False, + center: Optional[list[int]] = None, + fill: Optional[list[float]] = None, +) -> Tensor: + """Rotate the image by angle. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + img (PIL Image or Tensor): image to be rotated. + angle (number): rotation angle value in degrees, counter-clockwise. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + expand (bool, optional): Optional expansion flag. + If true, expands the output image to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the input image. + Note that the expand flag assumes rotation around the center and no translation. + center (sequence, optional): Optional center of rotation. Origin is the upper left corner. + Default is the center of the image. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + + .. note:: + In torchscript mode single int/float value is not supported, please use a sequence + of length 1: ``[value, ]``. + Returns: + PIL Image or Tensor: Rotated image. + + .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters + + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(rotate) + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + elif not isinstance(interpolation, InterpolationMode): + raise TypeError( + "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant" + ) + + if not isinstance(angle, (int, float)): + raise TypeError("Argument angle should be int or float") + + if center is not None and not isinstance(center, (list, tuple)): + raise TypeError("Argument center should be a sequence") + + if not isinstance(img, torch.Tensor): + pil_interpolation = pil_modes_mapping[interpolation] + return F_pil.rotate(img, angle=angle, interpolation=pil_interpolation, expand=expand, center=center, fill=fill) + + center_f = [0.0, 0.0] + if center is not None: + _, height, width = get_dimensions(img) + # Center values should be in pixel coordinates but translated such that (0, 0) corresponds to image center. + center_f = [1.0 * (c - s * 0.5) for c, s in zip(center, [width, height])] + + # due to current incoherence of rotation angle direction between affine and rotate implementations + # we need to set -angle. + matrix = _get_inverse_affine_matrix(center_f, -angle, [0.0, 0.0], 1.0, [0.0, 0.0]) + return F_t.rotate(img, matrix=matrix, interpolation=interpolation.value, expand=expand, fill=fill) + + +def affine( + img: Tensor, + angle: float, + translate: list[int], + scale: float, + shear: list[float], + interpolation: InterpolationMode = InterpolationMode.NEAREST, + fill: Optional[list[float]] = None, + center: Optional[list[int]] = None, +) -> Tensor: + """Apply affine transformation on the image keeping image center invariant. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + img (PIL Image or Tensor): image to transform. + angle (number): rotation angle in degrees between -180 and 180, clockwise direction. + translate (sequence of integers): horizontal and vertical translations (post-rotation translation) + scale (float): overall scale + shear (float or sequence): shear angle value in degrees between -180 to 180, clockwise direction. + If a sequence is specified, the first value corresponds to a shear parallel to the x-axis, while + the second value corresponds to a shear parallel to the y-axis. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + + .. note:: + In torchscript mode single int/float value is not supported, please use a sequence + of length 1: ``[value, ]``. + center (sequence, optional): Optional center of rotation. Origin is the upper left corner. + Default is the center of the image. + + Returns: + PIL Image or Tensor: Transformed image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(affine) + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + elif not isinstance(interpolation, InterpolationMode): + raise TypeError( + "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant" + ) + + if not isinstance(angle, (int, float)): + raise TypeError("Argument angle should be int or float") + + if not isinstance(translate, (list, tuple)): + raise TypeError("Argument translate should be a sequence") + + if len(translate) != 2: + raise ValueError("Argument translate should be a sequence of length 2") + + if scale <= 0.0: + raise ValueError("Argument scale should be positive") + + if not isinstance(shear, (numbers.Number, (list, tuple))): + raise TypeError("Shear should be either a single value or a sequence of two values") + + if isinstance(angle, int): + angle = float(angle) + + if isinstance(translate, tuple): + translate = list(translate) + + if isinstance(shear, numbers.Number): + shear = [shear, 0.0] + + if isinstance(shear, tuple): + shear = list(shear) + + if len(shear) == 1: + shear = [shear[0], shear[0]] + + if len(shear) != 2: + raise ValueError(f"Shear should be a sequence containing two values. Got {shear}") + + if center is not None and not isinstance(center, (list, tuple)): + raise TypeError("Argument center should be a sequence") + + _, height, width = get_dimensions(img) + if not isinstance(img, torch.Tensor): + # center = (width * 0.5 + 0.5, height * 0.5 + 0.5) + # it is visually better to estimate the center without 0.5 offset + # otherwise image rotated by 90 degrees is shifted vs output image of torch.rot90 or F_t.affine + if center is None: + center = [width * 0.5, height * 0.5] + matrix = _get_inverse_affine_matrix(center, angle, translate, scale, shear) + pil_interpolation = pil_modes_mapping[interpolation] + return F_pil.affine(img, matrix=matrix, interpolation=pil_interpolation, fill=fill) + + center_f = [0.0, 0.0] + if center is not None: + _, height, width = get_dimensions(img) + # Center values should be in pixel coordinates but translated such that (0, 0) corresponds to image center. + center_f = [1.0 * (c - s * 0.5) for c, s in zip(center, [width, height])] + + translate_f = [1.0 * t for t in translate] + matrix = _get_inverse_affine_matrix(center_f, angle, translate_f, scale, shear) + return F_t.affine(img, matrix=matrix, interpolation=interpolation.value, fill=fill) + + +# Looks like to_grayscale() is a stand-alone functional that is never called +# from the transform classes. Perhaps it's still here for BC? I can't be +# bothered to dig. +@torch.jit.unused +def to_grayscale(img, num_output_channels=1): + """Convert PIL image of any mode (RGB, HSV, LAB, etc) to grayscale version of image. + This transform does not support torch Tensor. + + Args: + img (PIL Image): PIL Image to be converted to grayscale. + num_output_channels (int): number of channels of the output image. Value can be 1 or 3. Default is 1. + + Returns: + PIL Image: Grayscale version of the image. + + - if num_output_channels = 1 : returned image is single channel + - if num_output_channels = 3 : returned image is 3 channel with r = g = b + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(to_grayscale) + if isinstance(img, Image.Image): + return F_pil.to_grayscale(img, num_output_channels) + + raise TypeError("Input should be PIL Image") + + +def rgb_to_grayscale(img: Tensor, num_output_channels: int = 1) -> Tensor: + """Convert RGB image to grayscale version of image. + If the image is torch Tensor, it is expected + to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions + + Note: + Please, note that this method supports only RGB images as input. For inputs in other color spaces, + please, consider using :meth:`~torchvision.transforms.functional.to_grayscale` with PIL Image. + + Args: + img (PIL Image or Tensor): RGB Image to be converted to grayscale. + num_output_channels (int): number of channels of the output image. Value can be 1 or 3. Default, 1. + + Returns: + PIL Image or Tensor: Grayscale version of the image. + + - if num_output_channels = 1 : returned image is single channel + - if num_output_channels = 3 : returned image is 3 channel with r = g = b + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(rgb_to_grayscale) + if not isinstance(img, torch.Tensor): + return F_pil.to_grayscale(img, num_output_channels) + + return F_t.rgb_to_grayscale(img, num_output_channels) + + +def erase(img: Tensor, i: int, j: int, h: int, w: int, v: Tensor, inplace: bool = False) -> Tensor: + """Erase the input Tensor Image with given value. + This transform does not support PIL Image. + + Args: + img (Tensor Image): Tensor image of size (C, H, W) to be erased + i (int): i in (i,j) i.e coordinates of the upper left corner. + j (int): j in (i,j) i.e coordinates of the upper left corner. + h (int): Height of the erased region. + w (int): Width of the erased region. + v: Erasing value. + inplace(bool, optional): For in-place operations. By default, is set False. + + Returns: + Tensor Image: Erased image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(erase) + if not isinstance(img, torch.Tensor): + raise TypeError(f"img should be Tensor Image. Got {type(img)}") + + return F_t.erase(img, i, j, h, w, v, inplace=inplace) + + +def gaussian_blur(img: Tensor, kernel_size: list[int], sigma: Optional[list[float]] = None) -> Tensor: + """Performs Gaussian blurring on the image by given kernel + + The convolution will be using reflection padding corresponding to the kernel size, to maintain the input shape. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means at most one leading dimension. + + Args: + img (PIL Image or Tensor): Image to be blurred + kernel_size (sequence of ints or int): Gaussian kernel size. Can be a sequence of integers + like ``(kx, ky)`` or a single integer for square kernels. + + .. note:: + In torchscript mode kernel_size as single int is not supported, use a sequence of + length 1: ``[ksize, ]``. + sigma (sequence of floats or float, optional): Gaussian kernel standard deviation. Can be a + sequence of floats like ``(sigma_x, sigma_y)`` or a single float to define the + same sigma in both X/Y directions. If None, then it is computed using + ``kernel_size`` as ``sigma = 0.3 * ((kernel_size - 1) * 0.5 - 1) + 0.8``. + Default, None. + + .. note:: + In torchscript mode sigma as single float is + not supported, use a sequence of length 1: ``[sigma, ]``. + + Returns: + PIL Image or Tensor: Gaussian Blurred version of the image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(gaussian_blur) + if not isinstance(kernel_size, (int, list, tuple)): + raise TypeError(f"kernel_size should be int or a sequence of integers. Got {type(kernel_size)}") + if isinstance(kernel_size, int): + kernel_size = [kernel_size, kernel_size] + if len(kernel_size) != 2: + raise ValueError(f"If kernel_size is a sequence its length should be 2. Got {len(kernel_size)}") + for ksize in kernel_size: + if ksize % 2 == 0 or ksize < 0: + raise ValueError(f"kernel_size should have odd and positive integers. Got {kernel_size}") + + if sigma is None: + sigma = [ksize * 0.15 + 0.35 for ksize in kernel_size] + + if sigma is not None and not isinstance(sigma, (int, float, list, tuple)): + raise TypeError(f"sigma should be either float or sequence of floats. Got {type(sigma)}") + if isinstance(sigma, (int, float)): + sigma = [float(sigma), float(sigma)] + if isinstance(sigma, (list, tuple)) and len(sigma) == 1: + sigma = [sigma[0], sigma[0]] + if len(sigma) != 2: + raise ValueError(f"If sigma is a sequence, its length should be 2. Got {len(sigma)}") + for s in sigma: + if s <= 0.0: + raise ValueError(f"sigma should have positive values. Got {sigma}") + + t_img = img + if not isinstance(img, torch.Tensor): + if not F_pil._is_pil_image(img): + raise TypeError(f"img should be PIL Image or Tensor. Got {type(img)}") + + t_img = pil_to_tensor(img) + + output = F_t.gaussian_blur(t_img, kernel_size, sigma) + + if not isinstance(img, torch.Tensor): + output = to_pil_image(output, mode=img.mode) + return output + + +def invert(img: Tensor) -> Tensor: + """Invert the colors of an RGB/grayscale image. + + Args: + img (PIL Image or Tensor): Image to have its colors inverted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Returns: + PIL Image or Tensor: Color inverted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(invert) + if not isinstance(img, torch.Tensor): + return F_pil.invert(img) + + return F_t.invert(img) + + +def posterize(img: Tensor, bits: int) -> Tensor: + """Posterize an image by reducing the number of bits for each color channel. + + Args: + img (PIL Image or Tensor): Image to have its colors posterized. + If img is torch Tensor, it should be of type torch.uint8, and + it is expected to be in [..., 1 or 3, H, W] format, where ... means + it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + bits (int): The number of bits to keep for each channel (0-8). + Returns: + PIL Image or Tensor: Posterized image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(posterize) + if not (0 <= bits <= 8): + raise ValueError(f"The number if bits should be between 0 and 8. Got {bits}") + + if not isinstance(img, torch.Tensor): + return F_pil.posterize(img, bits) + + return F_t.posterize(img, bits) + + +def solarize(img: Tensor, threshold: float) -> Tensor: + """Solarize an RGB/grayscale image by inverting all pixel values above a threshold. + + Args: + img (PIL Image or Tensor): Image to have its colors inverted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + threshold (float): All pixels equal or above this value are inverted. + Returns: + PIL Image or Tensor: Solarized image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(solarize) + if not isinstance(img, torch.Tensor): + return F_pil.solarize(img, threshold) + + return F_t.solarize(img, threshold) + + +def adjust_sharpness(img: Tensor, sharpness_factor: float) -> Tensor: + """Adjust the sharpness of an image. + + Args: + img (PIL Image or Tensor): Image to be adjusted. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + sharpness_factor (float): How much to adjust the sharpness. Can be + any non-negative number. 0 gives a blurred image, 1 gives the + original image while 2 increases the sharpness by a factor of 2. + + Returns: + PIL Image or Tensor: Sharpness adjusted image. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(adjust_sharpness) + if not isinstance(img, torch.Tensor): + return F_pil.adjust_sharpness(img, sharpness_factor) + + return F_t.adjust_sharpness(img, sharpness_factor) + + +def autocontrast(img: Tensor) -> Tensor: + """Maximize contrast of an image by remapping its + pixels per channel so that the lowest becomes black and the lightest + becomes white. + + Args: + img (PIL Image or Tensor): Image on which autocontrast is applied. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Returns: + PIL Image or Tensor: An image that was autocontrasted. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(autocontrast) + if not isinstance(img, torch.Tensor): + return F_pil.autocontrast(img) + + return F_t.autocontrast(img) + + +def equalize(img: Tensor) -> Tensor: + """Equalize the histogram of an image by applying + a non-linear mapping to the input in order to create a uniform + distribution of grayscale values in the output. + + Args: + img (PIL Image or Tensor): Image on which equalize is applied. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + The tensor dtype must be ``torch.uint8`` and values are expected to be in ``[0, 255]``. + If img is PIL Image, it is expected to be in mode "P", "L" or "RGB". + + Returns: + PIL Image or Tensor: An image that was equalized. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(equalize) + if not isinstance(img, torch.Tensor): + return F_pil.equalize(img) + + return F_t.equalize(img) + + +def elastic_transform( + img: Tensor, + displacement: Tensor, + interpolation: InterpolationMode = InterpolationMode.BILINEAR, + fill: Optional[list[float]] = None, +) -> Tensor: + """Transform a tensor image with elastic transformations. + Given alpha and sigma, it will generate displacement + vectors for all pixels based on random offsets. Alpha controls the strength + and sigma controls the smoothness of the displacements. + The displacements are added to an identity grid and the resulting grid is + used to grid_sample from the image. + + Applications: + Randomly transforms the morphology of objects in images and produces a + see-through-water-like effect. + + Args: + img (PIL Image or Tensor): Image on which elastic_transform is applied. + If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "P", "L" or "RGB". + displacement (Tensor): The displacement field. Expected shape is [1, H, W, 2]. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. + Default is ``InterpolationMode.BILINEAR``. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (number or str or tuple): Pixel fill value for constant fill. Default is 0. + If a tuple of length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(elastic_transform) + # Backward compatibility with integer value + if isinstance(interpolation, int): + warnings.warn( + "Argument interpolation should be of type InterpolationMode instead of int. " + "Please, use InterpolationMode enum." + ) + interpolation = _interpolation_modes_from_int(interpolation) + + if not isinstance(displacement, torch.Tensor): + raise TypeError("Argument displacement should be a Tensor") + + t_img = img + if not isinstance(img, torch.Tensor): + if not F_pil._is_pil_image(img): + raise TypeError(f"img should be PIL Image or Tensor. Got {type(img)}") + t_img = pil_to_tensor(img) + + shape = t_img.shape + shape = (1,) + shape[-2:] + (2,) + if shape != displacement.shape: + raise ValueError(f"Argument displacement shape should be {shape}, but given {displacement.shape}") + + # TODO: if image shape is [N1, N2, ..., C, H, W] and + # displacement is [1, H, W, 2] we need to reshape input image + # such grid_sampler takes internal code for 4D input + + output = F_t.elastic_transform( + t_img, + displacement, + interpolation=interpolation.value, + fill=fill, + ) + + if not isinstance(img, torch.Tensor): + output = to_pil_image(output, mode=img.mode) + return output diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/transforms.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..e33b3e28194e78a6fb56da0a8abc85e2d94668f0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/transforms.py @@ -0,0 +1,2163 @@ +import math +import numbers +import random +import warnings +from collections.abc import Sequence +from typing import Optional, Union + +import torch +from torch import Tensor + +try: + import accimage +except ImportError: + accimage = None + +from ..utils import _log_api_usage_once +from . import functional as F +from .functional import _interpolation_modes_from_int, InterpolationMode + +__all__ = [ + "Compose", + "ToTensor", + "PILToTensor", + "ConvertImageDtype", + "ToPILImage", + "Normalize", + "Resize", + "CenterCrop", + "Pad", + "Lambda", + "RandomApply", + "RandomChoice", + "RandomOrder", + "RandomCrop", + "RandomHorizontalFlip", + "RandomVerticalFlip", + "RandomResizedCrop", + "FiveCrop", + "TenCrop", + "LinearTransformation", + "ColorJitter", + "RandomRotation", + "RandomAffine", + "Grayscale", + "RandomGrayscale", + "RandomPerspective", + "RandomErasing", + "GaussianBlur", + "InterpolationMode", + "RandomInvert", + "RandomPosterize", + "RandomSolarize", + "RandomAdjustSharpness", + "RandomAutocontrast", + "RandomEqualize", + "ElasticTransform", +] + + +class Compose: + """Composes several transforms together. This transform does not support torchscript. + Please, see the note below. + + Args: + transforms (list of ``Transform`` objects): list of transforms to compose. + + Example: + >>> transforms.Compose([ + >>> transforms.CenterCrop(10), + >>> transforms.PILToTensor(), + >>> transforms.ConvertImageDtype(torch.float), + >>> ]) + + .. note:: + In order to script the transformations, please use ``torch.nn.Sequential`` as below. + + >>> transforms = torch.nn.Sequential( + >>> transforms.CenterCrop(10), + >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + >>> ) + >>> scripted_transforms = torch.jit.script(transforms) + + Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require + `lambda` functions or ``PIL.Image``. + + """ + + def __init__(self, transforms): + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(self) + self.transforms = transforms + + def __call__(self, img): + for t in self.transforms: + img = t(img) + return img + + def __repr__(self) -> str: + format_string = self.__class__.__name__ + "(" + for t in self.transforms: + format_string += "\n" + format_string += f" {t}" + format_string += "\n)" + return format_string + + +class ToTensor: + """Convert a PIL Image or ndarray to tensor and scale the values accordingly. + + This transform does not support torchscript. + + Converts a PIL Image or numpy.ndarray (H x W x C) in the range + [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] + if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1) + or if the numpy.ndarray has dtype = np.uint8 + + In the other cases, tensors are returned without scaling. + + .. note:: + Because the input image is scaled to [0.0, 1.0], this transformation should not be used when + transforming target image masks. See the `references`_ for implementing the transforms for image masks. + + .. _references: https://github.com/pytorch/vision/tree/main/references/segmentation + """ + + def __init__(self) -> None: + _log_api_usage_once(self) + + def __call__(self, pic): + """ + Args: + pic (PIL Image or numpy.ndarray): Image to be converted to tensor. + + Returns: + Tensor: Converted image. + """ + return F.to_tensor(pic) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}()" + + +class PILToTensor: + """Convert a PIL Image to a tensor of the same type - this does not scale values. + + This transform does not support torchscript. + + Convert a PIL Image with H height, W width, and C channels to a Tensor of shape (C x H x W). + + Example: + >>> from PIL import Image + >>> import torchvision.transforms as T + >>> img = Image.new("RGB", (320, 240)) # size (W=320, H=240) + >>> tensor = T.PILToTensor()(img) + >>> print(tensor.shape) + torch.Size([3, 240, 320]) + """ + + def __init__(self) -> None: + _log_api_usage_once(self) + + def __call__(self, pic): + """ + .. note:: + + A deep copy of the underlying array is performed. + + Args: + pic (PIL Image): Image to be converted to tensor. + + Returns: + Tensor: Converted image. + """ + return F.pil_to_tensor(pic) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}()" + + +class ConvertImageDtype(torch.nn.Module): + """Convert a tensor image to the given ``dtype`` and scale the values accordingly. + + This function does not support PIL Image. + + Args: + dtype (torch.dtype): Desired data type of the output + + .. note:: + + When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly. + If converted back and forth, this mismatch has no effect. + + Raises: + RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as + well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to + overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range + of the integer ``dtype``. + """ + + def __init__(self, dtype: torch.dtype) -> None: + super().__init__() + _log_api_usage_once(self) + self.dtype = dtype + + def forward(self, image): + return F.convert_image_dtype(image, self.dtype) + + +class ToPILImage: + """Convert a tensor or an ndarray to PIL Image + + This transform does not support torchscript. + + Converts a torch.*Tensor of shape C x H x W or a numpy ndarray of shape + H x W x C to a PIL Image while adjusting the value range depending on the ``mode``. + + Args: + mode (`PIL.Image mode`_): color space and pixel depth of input data (optional). + If ``mode`` is ``None`` (default) there are some assumptions made about the input data: + + - If the input has 4 channels, the ``mode`` is assumed to be ``RGBA``. + - If the input has 3 channels, the ``mode`` is assumed to be ``RGB``. + - If the input has 2 channels, the ``mode`` is assumed to be ``LA``. + - If the input has 1 channel, the ``mode`` is determined by the data type (i.e ``int``, ``float``, ``short``). + + .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes + """ + + def __init__(self, mode=None): + _log_api_usage_once(self) + self.mode = mode + + def __call__(self, pic): + """ + Args: + pic (Tensor or numpy.ndarray): Image to be converted to PIL Image. + + Returns: + PIL Image: Image converted to PIL Image. + + """ + return F.to_pil_image(pic, self.mode) + + def __repr__(self) -> str: + format_string = self.__class__.__name__ + "(" + if self.mode is not None: + format_string += f"mode={self.mode}" + format_string += ")" + return format_string + + +class Normalize(torch.nn.Module): + """Normalize a tensor image with mean and standard deviation. + This transform does not support PIL Image. + Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])`` for ``n`` + channels, this transform will normalize each channel of the input + ``torch.*Tensor`` i.e., + ``output[channel] = (input[channel] - mean[channel]) / std[channel]`` + + .. note:: + This transform acts out of place, i.e., it does not mutate the input tensor. + + Args: + mean (sequence): Sequence of means for each channel. + std (sequence): Sequence of standard deviations for each channel. + inplace(bool,optional): Bool to make this operation in-place. + + """ + + def __init__(self, mean, std, inplace=False): + super().__init__() + _log_api_usage_once(self) + self.mean = mean + self.std = std + self.inplace = inplace + + def forward(self, tensor: Tensor) -> Tensor: + """ + Args: + tensor (Tensor): Tensor image to be normalized. + + Returns: + Tensor: Normalized Tensor image. + """ + return F.normalize(tensor, self.mean, self.std, self.inplace) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(mean={self.mean}, std={self.std})" + + +class Resize(torch.nn.Module): + """Resize the input image to the given size. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means a maximum of two leading dimensions + + Args: + size (sequence or int): Desired output size. If size is a sequence like + (h, w), output size will be matched to this. If size is an int, + smaller edge of the image will be matched to this number. + i.e, if height > width, then image will be rescaled to + (size * height / width, size). + + .. note:: + In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``, + ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + max_size (int, optional): The maximum allowed for the longer edge of + the resized image. If the longer edge of the image is greater + than ``max_size`` after being resized according to ``size``, + ``size`` will be overruled so that the longer edge is equal to + ``max_size``. + As a result, the smaller edge may be shorter than ``size``. This + is only supported if ``size`` is an int (or a sequence of length + 1 in torchscript mode). + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear or bicubic modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear or bicubic modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + """ + + def __init__(self, size, interpolation=InterpolationMode.BILINEAR, max_size=None, antialias=True): + super().__init__() + _log_api_usage_once(self) + if not isinstance(size, (int, Sequence)): + raise TypeError(f"Size should be int or sequence. Got {type(size)}") + if isinstance(size, Sequence) and len(size) not in (1, 2): + raise ValueError("If size is a sequence, it should have 1 or 2 values") + self.size = size + self.max_size = max_size + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + + self.interpolation = interpolation + self.antialias = antialias + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be scaled. + + Returns: + PIL Image or Tensor: Rescaled image. + """ + return F.resize(img, self.size, self.interpolation, self.max_size, self.antialias) + + def __repr__(self) -> str: + detail = f"(size={self.size}, interpolation={self.interpolation.value}, max_size={self.max_size}, antialias={self.antialias})" + return f"{self.__class__.__name__}{detail}" + + +class CenterCrop(torch.nn.Module): + """Crops the given image at the center. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + If image size is smaller than output size along any edge, image is padded with 0 and then center cropped. + + Args: + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + """ + + def __init__(self, size): + super().__init__() + _log_api_usage_once(self) + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be cropped. + + Returns: + PIL Image or Tensor: Cropped image. + """ + return F.center_crop(img, self.size) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(size={self.size})" + + +class Pad(torch.nn.Module): + """Pad the given image on all sides with the given "pad" value. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric, + at most 3 leading dimensions for mode edge, + and an arbitrary number of leading dimensions for mode constant + + Args: + padding (int or sequence): Padding on each border. If a single int is provided this + is used to pad all borders. If sequence of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a sequence of length 4 is provided + this is the padding for the left, top, right and bottom borders respectively. + + .. note:: + In torchscript mode padding as single int is not supported, use a sequence of + length 1: ``[padding, ]``. + fill (number or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of + length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. + Only number is supported for torch Tensor. + Only int or tuple value is supported for PIL Image. + padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric. + Default is constant. + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value at the edge of the image. + If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2 + + - reflect: pads with reflection of image without repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + """ + + def __init__(self, padding, fill=0, padding_mode="constant"): + super().__init__() + _log_api_usage_once(self) + if not isinstance(padding, (numbers.Number, tuple, list)): + raise TypeError("Got inappropriate padding arg") + + if not isinstance(fill, (numbers.Number, tuple, list)): + raise TypeError("Got inappropriate fill arg") + + if padding_mode not in ["constant", "edge", "reflect", "symmetric"]: + raise ValueError("Padding mode should be either constant, edge, reflect or symmetric") + + if isinstance(padding, Sequence) and len(padding) not in [1, 2, 4]: + raise ValueError( + f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple" + ) + + self.padding = padding + self.fill = fill + self.padding_mode = padding_mode + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be padded. + + Returns: + PIL Image or Tensor: Padded image. + """ + return F.pad(img, self.padding, self.fill, self.padding_mode) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(padding={self.padding}, fill={self.fill}, padding_mode={self.padding_mode})" + + +class Lambda: + """Apply a user-defined lambda as a transform. This transform does not support torchscript. + + Args: + lambd (function): Lambda/function to be used for transform. + """ + + def __init__(self, lambd): + _log_api_usage_once(self) + if not callable(lambd): + raise TypeError(f"Argument lambd should be callable, got {repr(type(lambd).__name__)}") + self.lambd = lambd + + def __call__(self, img): + return self.lambd(img) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}()" + + +class RandomTransforms: + """Base class for a list of transformations with randomness + + Args: + transforms (sequence): list of transformations + """ + + def __init__(self, transforms): + _log_api_usage_once(self) + if not isinstance(transforms, Sequence): + raise TypeError("Argument transforms should be a sequence") + self.transforms = transforms + + def __call__(self, *args, **kwargs): + raise NotImplementedError() + + def __repr__(self) -> str: + format_string = self.__class__.__name__ + "(" + for t in self.transforms: + format_string += "\n" + format_string += f" {t}" + format_string += "\n)" + return format_string + + +class RandomApply(torch.nn.Module): + """Apply randomly a list of transformations with a given probability. + + .. note:: + In order to script the transformation, please use ``torch.nn.ModuleList`` as input instead of list/tuple of + transforms as shown below: + + >>> transforms = transforms.RandomApply(torch.nn.ModuleList([ + >>> transforms.ColorJitter(), + >>> ]), p=0.3) + >>> scripted_transforms = torch.jit.script(transforms) + + Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require + `lambda` functions or ``PIL.Image``. + + Args: + transforms (sequence or torch.nn.Module): list of transformations + p (float): probability + """ + + def __init__(self, transforms, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.transforms = transforms + self.p = p + + def forward(self, img): + if self.p < torch.rand(1): + return img + for t in self.transforms: + img = t(img) + return img + + def __repr__(self) -> str: + format_string = self.__class__.__name__ + "(" + format_string += f"\n p={self.p}" + for t in self.transforms: + format_string += "\n" + format_string += f" {t}" + format_string += "\n)" + return format_string + + +class RandomOrder(RandomTransforms): + """Apply a list of transformations in a random order. This transform does not support torchscript.""" + + def __call__(self, img): + order = list(range(len(self.transforms))) + random.shuffle(order) + for i in order: + img = self.transforms[i](img) + return img + + +class RandomChoice(RandomTransforms): + """Apply single transformation randomly picked from a list. This transform does not support torchscript.""" + + def __init__(self, transforms, p=None): + super().__init__(transforms) + if p is not None and not isinstance(p, Sequence): + raise TypeError("Argument p should be a sequence") + self.p = p + + def __call__(self, *args): + t = random.choices(self.transforms, weights=self.p)[0] + return t(*args) + + def __repr__(self) -> str: + return f"{super().__repr__()}(p={self.p})" + + +class RandomCrop(torch.nn.Module): + """Crop the given image at a random location. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions, + but if non-constant padding is used, the input is expected to have at most 2 leading dimensions + + Args: + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + padding (int or sequence, optional): Optional padding on each border + of the image, applied before cropping. Default is None. If a single int is provided this + is used to pad all borders. If sequence of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a sequence of length 4 is provided + this is the padding for the left, top, right and bottom borders respectively. + + .. note:: + In torchscript mode padding as single int is not supported, use a sequence of + length 1: ``[padding, ]``. + pad_if_needed (boolean): It will pad the image if smaller than the + desired size to avoid raising an exception. Since cropping is done + after padding, the padding seems to be done at a random offset. + fill (number or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of + length 3, it is used to fill R, G, B channels respectively. + This value is only used when the padding_mode is constant. + Only number is supported for torch Tensor. + Only int or tuple value is supported for PIL Image. + padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric. + Default is constant. + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value at the edge of the image. + If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2 + + - reflect: pads with reflection of image without repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + """ + + @staticmethod + def get_params(img: Tensor, output_size: tuple[int, int]) -> tuple[int, int, int, int]: + """Get parameters for ``crop`` for a random crop. + + Args: + img (PIL Image or Tensor): Image to be cropped. + output_size (tuple): Expected output size of the crop. + + Returns: + tuple: params (i, j, h, w) to be passed to ``crop`` for random crop. + """ + _, h, w = F.get_dimensions(img) + th, tw = output_size + + if h < th or w < tw: + raise ValueError(f"Required crop size {(th, tw)} is larger than input image size {(h, w)}") + + if w == tw and h == th: + return 0, 0, h, w + + i = torch.randint(0, h - th + 1, size=(1,)).item() + j = torch.randint(0, w - tw + 1, size=(1,)).item() + return i, j, th, tw + + def __init__(self, size, padding=None, pad_if_needed=False, fill=0, padding_mode="constant"): + super().__init__() + _log_api_usage_once(self) + + self.size = tuple(_setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")) + + self.padding = padding + self.pad_if_needed = pad_if_needed + self.fill = fill + self.padding_mode = padding_mode + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be cropped. + + Returns: + PIL Image or Tensor: Cropped image. + """ + if self.padding is not None: + img = F.pad(img, self.padding, self.fill, self.padding_mode) + + _, height, width = F.get_dimensions(img) + # pad the width if needed + if self.pad_if_needed and width < self.size[1]: + padding = [self.size[1] - width, 0] + img = F.pad(img, padding, self.fill, self.padding_mode) + # pad the height if needed + if self.pad_if_needed and height < self.size[0]: + padding = [0, self.size[0] - height] + img = F.pad(img, padding, self.fill, self.padding_mode) + + i, j, h, w = self.get_params(img, self.size) + + return F.crop(img, i, j, h, w) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(size={self.size}, padding={self.padding})" + + +class RandomHorizontalFlip(torch.nn.Module): + """Horizontally flip the given image randomly with a given probability. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading + dimensions + + Args: + p (float): probability of the image being flipped. Default value is 0.5 + """ + + def __init__(self, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be flipped. + + Returns: + PIL Image or Tensor: Randomly flipped image. + """ + if torch.rand(1) < self.p: + return F.hflip(img) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" + + +class RandomVerticalFlip(torch.nn.Module): + """Vertically flip the given image randomly with a given probability. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading + dimensions + + Args: + p (float): probability of the image being flipped. Default value is 0.5 + """ + + def __init__(self, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be flipped. + + Returns: + PIL Image or Tensor: Randomly flipped image. + """ + if torch.rand(1) < self.p: + return F.vflip(img) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" + + +class RandomPerspective(torch.nn.Module): + """Performs a random perspective transformation of the given image with a given probability. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + distortion_scale (float): argument to control the degree of distortion and ranges from 0 to 1. + Default is 0.5. + p (float): probability of the image being transformed. Default is 0.5. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (sequence or number): Pixel fill value for the area outside the transformed + image. Default is ``0``. If given a number, the value is used for all bands respectively. + """ + + def __init__(self, distortion_scale=0.5, p=0.5, interpolation=InterpolationMode.BILINEAR, fill=0): + super().__init__() + _log_api_usage_once(self) + self.p = p + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + + self.interpolation = interpolation + self.distortion_scale = distortion_scale + + if fill is None: + fill = 0 + elif not isinstance(fill, (Sequence, numbers.Number)): + raise TypeError("Fill should be either a sequence or a number.") + + self.fill = fill + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be Perspectively transformed. + + Returns: + PIL Image or Tensor: Randomly transformed image. + """ + + fill = self.fill + channels, height, width = F.get_dimensions(img) + if isinstance(img, Tensor): + if isinstance(fill, (int, float)): + fill = [float(fill)] * channels + else: + fill = [float(f) for f in fill] + + if torch.rand(1) < self.p: + startpoints, endpoints = self.get_params(width, height, self.distortion_scale) + return F.perspective(img, startpoints, endpoints, self.interpolation, fill) + return img + + @staticmethod + def get_params(width: int, height: int, distortion_scale: float) -> tuple[list[list[int]], list[list[int]]]: + """Get parameters for ``perspective`` for a random perspective transform. + + Args: + width (int): width of the image. + height (int): height of the image. + distortion_scale (float): argument to control the degree of distortion and ranges from 0 to 1. + + Returns: + List containing [top-left, top-right, bottom-right, bottom-left] of the original image, + List containing [top-left, top-right, bottom-right, bottom-left] of the transformed image. + """ + half_height = height // 2 + half_width = width // 2 + topleft = [ + int(torch.randint(0, int(distortion_scale * half_width) + 1, size=(1,)).item()), + int(torch.randint(0, int(distortion_scale * half_height) + 1, size=(1,)).item()), + ] + topright = [ + int(torch.randint(width - int(distortion_scale * half_width) - 1, width, size=(1,)).item()), + int(torch.randint(0, int(distortion_scale * half_height) + 1, size=(1,)).item()), + ] + botright = [ + int(torch.randint(width - int(distortion_scale * half_width) - 1, width, size=(1,)).item()), + int(torch.randint(height - int(distortion_scale * half_height) - 1, height, size=(1,)).item()), + ] + botleft = [ + int(torch.randint(0, int(distortion_scale * half_width) + 1, size=(1,)).item()), + int(torch.randint(height - int(distortion_scale * half_height) - 1, height, size=(1,)).item()), + ] + startpoints = [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]] + endpoints = [topleft, topright, botright, botleft] + return startpoints, endpoints + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" + + +class RandomResizedCrop(torch.nn.Module): + """Crop a random portion of image and resize it to a given size. + + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions + + A crop of the original image is made: the crop has a random area (H * W) + and a random aspect ratio. This crop is finally resized to the given + size. This is popularly used to train the Inception networks. + + Args: + size (int or sequence): expected output size of the crop, for each edge. If size is an + int instead of sequence like (h, w), a square output size ``(size, size)`` is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + + .. note:: + In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``. + scale (tuple of float): Specifies the lower and upper bounds for the random area of the crop, + before resizing. The scale is defined with respect to the area of the original image. + ratio (tuple of float): lower and upper bounds for the random aspect ratio of the crop, before + resizing. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``, + ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear or bicubic modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear or bicubic modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + """ + + def __init__( + self, + size, + scale=(0.08, 1.0), + ratio=(3.0 / 4.0, 4.0 / 3.0), + interpolation=InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, + ): + super().__init__() + _log_api_usage_once(self) + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + + if not isinstance(scale, Sequence): + raise TypeError("Scale should be a sequence") + if not isinstance(ratio, Sequence): + raise TypeError("Ratio should be a sequence") + if (scale[0] > scale[1]) or (ratio[0] > ratio[1]): + warnings.warn("Scale and ratio should be of kind (min, max)") + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + + self.interpolation = interpolation + self.antialias = antialias + self.scale = scale + self.ratio = ratio + + @staticmethod + def get_params(img: Tensor, scale: list[float], ratio: list[float]) -> tuple[int, int, int, int]: + """Get parameters for ``crop`` for a random sized crop. + + Args: + img (PIL Image or Tensor): Input image. + scale (list): range of scale of the origin size cropped + ratio (list): range of aspect ratio of the origin aspect ratio cropped + + Returns: + tuple: params (i, j, h, w) to be passed to ``crop`` for a random + sized crop. + """ + _, height, width = F.get_dimensions(img) + area = height * width + + log_ratio = torch.log(torch.tensor(ratio)) + for _ in range(10): + target_area = area * torch.empty(1).uniform_(scale[0], scale[1]).item() + aspect_ratio = torch.exp(torch.empty(1).uniform_(log_ratio[0], log_ratio[1])).item() + + w = int(round(math.sqrt(target_area * aspect_ratio))) + h = int(round(math.sqrt(target_area / aspect_ratio))) + + if 0 < w <= width and 0 < h <= height: + i = torch.randint(0, height - h + 1, size=(1,)).item() + j = torch.randint(0, width - w + 1, size=(1,)).item() + return i, j, h, w + + # Fallback to central crop + in_ratio = float(width) / float(height) + if in_ratio < min(ratio): + w = width + h = int(round(w / min(ratio))) + elif in_ratio > max(ratio): + h = height + w = int(round(h * max(ratio))) + else: # whole image + w = width + h = height + i = (height - h) // 2 + j = (width - w) // 2 + return i, j, h, w + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be cropped and resized. + + Returns: + PIL Image or Tensor: Randomly cropped and resized image. + """ + i, j, h, w = self.get_params(img, self.scale, self.ratio) + return F.resized_crop(img, i, j, h, w, self.size, self.interpolation, antialias=self.antialias) + + def __repr__(self) -> str: + interpolate_str = self.interpolation.value + format_string = self.__class__.__name__ + f"(size={self.size}" + format_string += f", scale={tuple(round(s, 4) for s in self.scale)}" + format_string += f", ratio={tuple(round(r, 4) for r in self.ratio)}" + format_string += f", interpolation={interpolate_str}" + format_string += f", antialias={self.antialias})" + return format_string + + +class FiveCrop(torch.nn.Module): + """Crop the given image into four corners and the central crop. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading + dimensions + + .. Note:: + This transform returns a tuple of images and there may be a mismatch in the number of + inputs and targets your Dataset returns. See below for an example of how to deal with + this. + + Args: + size (sequence or int): Desired output size of the crop. If size is an ``int`` + instead of sequence like (h, w), a square crop of size (size, size) is made. + If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + + Example: + >>> transform = Compose([ + >>> FiveCrop(size), # this is a list of PIL Images + >>> Lambda(lambda crops: torch.stack([PILToTensor()(crop) for crop in crops])) # returns a 4D tensor + >>> ]) + >>> #In your test loop you can do the following: + >>> input, target = batch # input is a 5d tensor, target is 2d + >>> bs, ncrops, c, h, w = input.size() + >>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops + >>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops + """ + + def __init__(self, size): + super().__init__() + _log_api_usage_once(self) + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be cropped. + + Returns: + tuple of 5 images. Image can be PIL Image or Tensor + """ + return F.five_crop(img, self.size) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(size={self.size})" + + +class TenCrop(torch.nn.Module): + """Crop the given image into four corners and the central crop plus the flipped version of + these (horizontal flipping is used by default). + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading + dimensions + + .. Note:: + This transform returns a tuple of images and there may be a mismatch in the number of + inputs and targets your Dataset returns. See below for an example of how to deal with + this. + + Args: + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + vertical_flip (bool): Use vertical flipping instead of horizontal + + Example: + >>> transform = Compose([ + >>> TenCrop(size), # this is a tuple of PIL Images + >>> Lambda(lambda crops: torch.stack([PILToTensor()(crop) for crop in crops])) # returns a 4D tensor + >>> ]) + >>> #In your test loop you can do the following: + >>> input, target = batch # input is a 5d tensor, target is 2d + >>> bs, ncrops, c, h, w = input.size() + >>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops + >>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops + """ + + def __init__(self, size, vertical_flip=False): + super().__init__() + _log_api_usage_once(self) + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + self.vertical_flip = vertical_flip + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be cropped. + + Returns: + tuple of 10 images. Image can be PIL Image or Tensor + """ + return F.ten_crop(img, self.size, self.vertical_flip) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(size={self.size}, vertical_flip={self.vertical_flip})" + + +class LinearTransformation(torch.nn.Module): + """Transform a tensor image with a square transformation matrix and a mean_vector computed + offline. + This transform does not support PIL Image. + Given transformation_matrix and mean_vector, will flatten the torch.*Tensor and + subtract mean_vector from it which is then followed by computing the dot + product with the transformation matrix and then reshaping the tensor to its + original shape. + + Applications: + whitening transformation: Suppose X is a column vector zero-centered data. + Then compute the data covariance matrix [D x D] with torch.mm(X.t(), X), + perform SVD on this matrix and pass it as transformation_matrix. + + Args: + transformation_matrix (Tensor): tensor [D x D], D = C x H x W + mean_vector (Tensor): tensor [D], D = C x H x W + """ + + def __init__(self, transformation_matrix, mean_vector): + super().__init__() + _log_api_usage_once(self) + if transformation_matrix.size(0) != transformation_matrix.size(1): + raise ValueError( + "transformation_matrix should be square. Got " + f"{tuple(transformation_matrix.size())} rectangular matrix." + ) + + if mean_vector.size(0) != transformation_matrix.size(0): + raise ValueError( + f"mean_vector should have the same length {mean_vector.size(0)}" + f" as any one of the dimensions of the transformation_matrix [{tuple(transformation_matrix.size())}]" + ) + + if transformation_matrix.device != mean_vector.device: + raise ValueError( + f"Input tensors should be on the same device. Got {transformation_matrix.device} and {mean_vector.device}" + ) + + if transformation_matrix.dtype != mean_vector.dtype: + raise ValueError( + f"Input tensors should have the same dtype. Got {transformation_matrix.dtype} and {mean_vector.dtype}" + ) + + self.transformation_matrix = transformation_matrix + self.mean_vector = mean_vector + + def forward(self, tensor: Tensor) -> Tensor: + """ + Args: + tensor (Tensor): Tensor image to be whitened. + + Returns: + Tensor: Transformed image. + """ + shape = tensor.shape + n = shape[-3] * shape[-2] * shape[-1] + if n != self.transformation_matrix.shape[0]: + raise ValueError( + "Input tensor and transformation matrix have incompatible shape." + + f"[{shape[-3]} x {shape[-2]} x {shape[-1]}] != " + + f"{self.transformation_matrix.shape[0]}" + ) + + if tensor.device.type != self.mean_vector.device.type: + raise ValueError( + "Input tensor should be on the same device as transformation matrix and mean vector. " + f"Got {tensor.device} vs {self.mean_vector.device}" + ) + + flat_tensor = tensor.view(-1, n) - self.mean_vector + transformation_matrix = self.transformation_matrix.to(flat_tensor.dtype) + transformed_tensor = torch.mm(flat_tensor, transformation_matrix) + tensor = transformed_tensor.view(shape) + return tensor + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(transformation_matrix=" + f"{self.transformation_matrix.tolist()}" + f", mean_vector={self.mean_vector.tolist()})" + ) + return s + + +class ColorJitter(torch.nn.Module): + """Randomly change the brightness, contrast, saturation and hue of an image. + If the image is torch Tensor, it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, mode "1", "I", "F" and modes with transparency (alpha channel) are not supported. + + Args: + brightness (float or tuple of float (min, max)): How much to jitter brightness. + brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness] + or the given [min, max]. Should be non negative numbers. + contrast (float or tuple of float (min, max)): How much to jitter contrast. + contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast] + or the given [min, max]. Should be non-negative numbers. + saturation (float or tuple of float (min, max)): How much to jitter saturation. + saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation] + or the given [min, max]. Should be non negative numbers. + hue (float or tuple of float (min, max)): How much to jitter hue. + hue_factor is chosen uniformly from [-hue, hue] or the given [min, max]. + Should have 0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5. + To jitter hue, the pixel values of the input image has to be non-negative for conversion to HSV space; + thus it does not work if you normalize your image to an interval with negative values, + or use an interpolation that generates negative values before using this function. + """ + + def __init__( + self, + brightness: Union[float, tuple[float, float]] = 0, + contrast: Union[float, tuple[float, float]] = 0, + saturation: Union[float, tuple[float, float]] = 0, + hue: Union[float, tuple[float, float]] = 0, + ) -> None: + super().__init__() + _log_api_usage_once(self) + self.brightness = self._check_input(brightness, "brightness") + self.contrast = self._check_input(contrast, "contrast") + self.saturation = self._check_input(saturation, "saturation") + self.hue = self._check_input(hue, "hue", center=0, bound=(-0.5, 0.5), clip_first_on_zero=False) + + @torch.jit.unused + def _check_input(self, value, name, center=1, bound=(0, float("inf")), clip_first_on_zero=True): + if isinstance(value, numbers.Number): + if value < 0: + raise ValueError(f"If {name} is a single number, it must be non negative.") + value = [center - float(value), center + float(value)] + if clip_first_on_zero: + value[0] = max(value[0], 0.0) + elif isinstance(value, (tuple, list)) and len(value) == 2: + value = [float(value[0]), float(value[1])] + else: + raise TypeError(f"{name} should be a single number or a list/tuple with length 2.") + + if not bound[0] <= value[0] <= value[1] <= bound[1]: + raise ValueError(f"{name} values should be between {bound}, but got {value}.") + + # if value is 0 or (1., 1.) for brightness/contrast/saturation + # or (0., 0.) for hue, do nothing + if value[0] == value[1] == center: + return None + else: + return tuple(value) + + @staticmethod + def get_params( + brightness: Optional[list[float]], + contrast: Optional[list[float]], + saturation: Optional[list[float]], + hue: Optional[list[float]], + ) -> tuple[Tensor, Optional[float], Optional[float], Optional[float], Optional[float]]: + """Get the parameters for the randomized transform to be applied on image. + + Args: + brightness (tuple of float (min, max), optional): The range from which the brightness_factor is chosen + uniformly. Pass None to turn off the transformation. + contrast (tuple of float (min, max), optional): The range from which the contrast_factor is chosen + uniformly. Pass None to turn off the transformation. + saturation (tuple of float (min, max), optional): The range from which the saturation_factor is chosen + uniformly. Pass None to turn off the transformation. + hue (tuple of float (min, max), optional): The range from which the hue_factor is chosen uniformly. + Pass None to turn off the transformation. + + Returns: + tuple: The parameters used to apply the randomized transform + along with their random order. + """ + fn_idx = torch.randperm(4) + + b = None if brightness is None else float(torch.empty(1).uniform_(brightness[0], brightness[1])) + c = None if contrast is None else float(torch.empty(1).uniform_(contrast[0], contrast[1])) + s = None if saturation is None else float(torch.empty(1).uniform_(saturation[0], saturation[1])) + h = None if hue is None else float(torch.empty(1).uniform_(hue[0], hue[1])) + + return fn_idx, b, c, s, h + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Input image. + + Returns: + PIL Image or Tensor: Color jittered image. + """ + fn_idx, brightness_factor, contrast_factor, saturation_factor, hue_factor = self.get_params( + self.brightness, self.contrast, self.saturation, self.hue + ) + + for fn_id in fn_idx: + if fn_id == 0 and brightness_factor is not None: + img = F.adjust_brightness(img, brightness_factor) + elif fn_id == 1 and contrast_factor is not None: + img = F.adjust_contrast(img, contrast_factor) + elif fn_id == 2 and saturation_factor is not None: + img = F.adjust_saturation(img, saturation_factor) + elif fn_id == 3 and hue_factor is not None: + img = F.adjust_hue(img, hue_factor) + + return img + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}(" + f"brightness={self.brightness}" + f", contrast={self.contrast}" + f", saturation={self.saturation}" + f", hue={self.hue})" + ) + return s + + +class RandomRotation(torch.nn.Module): + """Rotate the image by angle. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + degrees (sequence or number): Range of degrees to select from. + If degrees is a number instead of sequence like (min, max), the range of degrees + will be (-degrees, +degrees). + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + expand (bool, optional): Optional expansion flag. + If true, expands the output to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the input image. + Note that the expand flag assumes rotation around the center and no translation. + center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner. + Default is the center of the image. + fill (sequence or number): Pixel fill value for the area outside the rotated + image. Default is ``0``. If given a number, the value is used for all bands respectively. + + .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters + + """ + + def __init__(self, degrees, interpolation=InterpolationMode.NEAREST, expand=False, center=None, fill=0): + super().__init__() + _log_api_usage_once(self) + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + + self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,)) + + if center is not None: + _check_sequence_input(center, "center", req_sizes=(2,)) + + self.center = center + + self.interpolation = interpolation + self.expand = expand + + if fill is None: + fill = 0 + elif not isinstance(fill, (Sequence, numbers.Number)): + raise TypeError("Fill should be either a sequence or a number.") + + self.fill = fill + + @staticmethod + def get_params(degrees: list[float]) -> float: + """Get parameters for ``rotate`` for a random rotation. + + Returns: + float: angle parameter to be passed to ``rotate`` for random rotation. + """ + angle = float(torch.empty(1).uniform_(float(degrees[0]), float(degrees[1])).item()) + return angle + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be rotated. + + Returns: + PIL Image or Tensor: Rotated image. + """ + fill = self.fill + channels, _, _ = F.get_dimensions(img) + if isinstance(img, Tensor): + if isinstance(fill, (int, float)): + fill = [float(fill)] * channels + else: + fill = [float(f) for f in fill] + angle = self.get_params(self.degrees) + + return F.rotate(img, angle, self.interpolation, self.expand, self.center, fill) + + def __repr__(self) -> str: + interpolate_str = self.interpolation.value + format_string = self.__class__.__name__ + f"(degrees={self.degrees}" + format_string += f", interpolation={interpolate_str}" + format_string += f", expand={self.expand}" + if self.center is not None: + format_string += f", center={self.center}" + if self.fill is not None: + format_string += f", fill={self.fill}" + format_string += ")" + return format_string + + +class RandomAffine(torch.nn.Module): + """Random affine transformation of the image keeping center invariant. + If the image is torch Tensor, it is expected + to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + degrees (sequence or number): Range of degrees to select from. + If degrees is a number instead of sequence like (min, max), the range of degrees + will be (-degrees, +degrees). Set to 0 to deactivate rotations. + translate (tuple, optional): tuple of maximum absolute fraction for horizontal + and vertical translations. For example translate=(a, b), then horizontal shift + is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is + randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default. + scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is + randomly sampled from the range a <= scale <= b. Will keep original scale by default. + shear (sequence or number, optional): Range of degrees to select from. + If shear is a number, a shear parallel to the x-axis in the range (-shear, +shear) + will be applied. Else if shear is a sequence of 2 values a shear parallel to the x-axis in the + range (shear[0], shear[1]) will be applied. Else if shear is a sequence of 4 values, + an x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied. + Will not apply shear by default. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (sequence or number): Pixel fill value for the area outside the transformed + image. Default is ``0``. If given a number, the value is used for all bands respectively. + center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner. + Default is the center of the image. + + .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters + + """ + + def __init__( + self, + degrees, + translate=None, + scale=None, + shear=None, + interpolation=InterpolationMode.NEAREST, + fill=0, + center=None, + ): + super().__init__() + _log_api_usage_once(self) + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + + self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,)) + + if translate is not None: + _check_sequence_input(translate, "translate", req_sizes=(2,)) + for t in translate: + if not (0.0 <= t <= 1.0): + raise ValueError("translation values should be between 0 and 1") + self.translate = translate + + if scale is not None: + _check_sequence_input(scale, "scale", req_sizes=(2,)) + for s in scale: + if s <= 0: + raise ValueError("scale values should be positive") + self.scale = scale + + if shear is not None: + self.shear = _setup_angle(shear, name="shear", req_sizes=(2, 4)) + else: + self.shear = shear + + self.interpolation = interpolation + + if fill is None: + fill = 0 + elif not isinstance(fill, (Sequence, numbers.Number)): + raise TypeError("Fill should be either a sequence or a number.") + + self.fill = fill + + if center is not None: + _check_sequence_input(center, "center", req_sizes=(2,)) + + self.center = center + + @staticmethod + def get_params( + degrees: list[float], + translate: Optional[list[float]], + scale_ranges: Optional[list[float]], + shears: Optional[list[float]], + img_size: list[int], + ) -> tuple[float, tuple[int, int], float, tuple[float, float]]: + """Get parameters for affine transformation + + Returns: + params to be passed to the affine transformation + """ + angle = float(torch.empty(1).uniform_(float(degrees[0]), float(degrees[1])).item()) + if translate is not None: + max_dx = float(translate[0] * img_size[0]) + max_dy = float(translate[1] * img_size[1]) + tx = int(round(torch.empty(1).uniform_(-max_dx, max_dx).item())) + ty = int(round(torch.empty(1).uniform_(-max_dy, max_dy).item())) + translations = (tx, ty) + else: + translations = (0, 0) + + if scale_ranges is not None: + scale = float(torch.empty(1).uniform_(scale_ranges[0], scale_ranges[1]).item()) + else: + scale = 1.0 + + shear_x = shear_y = 0.0 + if shears is not None: + shear_x = float(torch.empty(1).uniform_(shears[0], shears[1]).item()) + if len(shears) == 4: + shear_y = float(torch.empty(1).uniform_(shears[2], shears[3]).item()) + + shear = (shear_x, shear_y) + + return angle, translations, scale, shear + + def forward(self, img): + """ + img (PIL Image or Tensor): Image to be transformed. + + Returns: + PIL Image or Tensor: Affine transformed image. + """ + fill = self.fill + channels, height, width = F.get_dimensions(img) + if isinstance(img, Tensor): + if isinstance(fill, (int, float)): + fill = [float(fill)] * channels + else: + fill = [float(f) for f in fill] + + img_size = [width, height] # flip for keeping BC on get_params call + + ret = self.get_params(self.degrees, self.translate, self.scale, self.shear, img_size) + + return F.affine(img, *ret, interpolation=self.interpolation, fill=fill, center=self.center) + + def __repr__(self) -> str: + s = f"{self.__class__.__name__}(degrees={self.degrees}" + s += f", translate={self.translate}" if self.translate is not None else "" + s += f", scale={self.scale}" if self.scale is not None else "" + s += f", shear={self.shear}" if self.shear is not None else "" + s += f", interpolation={self.interpolation.value}" if self.interpolation != InterpolationMode.NEAREST else "" + s += f", fill={self.fill}" if self.fill != 0 else "" + s += f", center={self.center}" if self.center is not None else "" + s += ")" + + return s + + +class Grayscale(torch.nn.Module): + """Convert image to grayscale. + If the image is torch Tensor, it is expected + to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions + + Args: + num_output_channels (int): (1 or 3) number of channels desired for output image + + Returns: + PIL Image: Grayscale version of the input. + + - If ``num_output_channels == 1`` : returned image is single channel + - If ``num_output_channels == 3`` : returned image is 3 channel with r == g == b + + """ + + def __init__(self, num_output_channels=1): + super().__init__() + _log_api_usage_once(self) + self.num_output_channels = num_output_channels + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be converted to grayscale. + + Returns: + PIL Image or Tensor: Grayscaled image. + """ + return F.rgb_to_grayscale(img, num_output_channels=self.num_output_channels) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(num_output_channels={self.num_output_channels})" + + +class RandomGrayscale(torch.nn.Module): + """Randomly convert image to grayscale with a probability of p (default 0.1). + If the image is torch Tensor, it is expected + to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions + + Args: + p (float): probability that image should be converted to grayscale. + + Returns: + PIL Image or Tensor: Grayscale version of the input image with probability p and unchanged + with probability (1-p). + - If input image is 1 channel: grayscale version is 1 channel + - If input image is 3 channel: grayscale version is 3 channel with r == g == b + + """ + + def __init__(self, p=0.1): + super().__init__() + _log_api_usage_once(self) + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be converted to grayscale. + + Returns: + PIL Image or Tensor: Randomly grayscaled image. + """ + num_output_channels, _, _ = F.get_dimensions(img) + if torch.rand(1) < self.p: + return F.rgb_to_grayscale(img, num_output_channels=num_output_channels) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" + + +class RandomErasing(torch.nn.Module): + """Randomly selects a rectangle region in a torch.Tensor image and erases its pixels. + This transform does not support PIL Image. + 'Random Erasing Data Augmentation' by Zhong et al. See https://arxiv.org/abs/1708.04896 + + Args: + p: probability that the random erasing operation will be performed. + scale: range of proportion of erased area against input image. + ratio: range of aspect ratio of erased area. + value: erasing value. Default is 0. If a single int, it is used to + erase all pixels. If a tuple of length 3, it is used to erase + R, G, B channels respectively. + If a str of 'random', erasing each pixel with random values. + inplace: boolean to make this transform inplace. Default set to False. + + Returns: + Erased Image. + + Example: + >>> transform = transforms.Compose([ + >>> transforms.RandomHorizontalFlip(), + >>> transforms.PILToTensor(), + >>> transforms.ConvertImageDtype(torch.float), + >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + >>> transforms.RandomErasing(), + >>> ]) + """ + + def __init__(self, p=0.5, scale=(0.02, 0.33), ratio=(0.3, 3.3), value=0, inplace=False): + super().__init__() + _log_api_usage_once(self) + if not isinstance(value, (numbers.Number, str, tuple, list)): + raise TypeError("Argument value should be either a number or str or a sequence") + if isinstance(value, str) and value != "random": + raise ValueError("If value is str, it should be 'random'") + if not isinstance(scale, Sequence): + raise TypeError("Scale should be a sequence") + if not isinstance(ratio, Sequence): + raise TypeError("Ratio should be a sequence") + if (scale[0] > scale[1]) or (ratio[0] > ratio[1]): + warnings.warn("Scale and ratio should be of kind (min, max)") + if scale[0] < 0 or scale[1] > 1: + raise ValueError("Scale should be between 0 and 1") + if p < 0 or p > 1: + raise ValueError("Random erasing probability should be between 0 and 1") + + self.p = p + self.scale = scale + self.ratio = ratio + self.value = value + self.inplace = inplace + + @staticmethod + def get_params( + img: Tensor, scale: tuple[float, float], ratio: tuple[float, float], value: Optional[list[float]] = None + ) -> tuple[int, int, int, int, Tensor]: + """Get parameters for ``erase`` for a random erasing. + + Args: + img (Tensor): Tensor image to be erased. + scale (sequence): range of proportion of erased area against input image. + ratio (sequence): range of aspect ratio of erased area. + value (list, optional): erasing value. If None, it is interpreted as "random" + (erasing each pixel with random values). If ``len(value)`` is 1, it is interpreted as a number, + i.e. ``value[0]``. + + Returns: + tuple: params (i, j, h, w, v) to be passed to ``erase`` for random erasing. + """ + img_c, img_h, img_w = img.shape[-3], img.shape[-2], img.shape[-1] + area = img_h * img_w + + log_ratio = torch.log(torch.tensor(ratio)) + for _ in range(10): + erase_area = area * torch.empty(1).uniform_(scale[0], scale[1]).item() + aspect_ratio = torch.exp(torch.empty(1).uniform_(log_ratio[0], log_ratio[1])).item() + + h = int(round(math.sqrt(erase_area * aspect_ratio))) + w = int(round(math.sqrt(erase_area / aspect_ratio))) + if not (h < img_h and w < img_w): + continue + + if value is None: + v = torch.empty([img_c, h, w], dtype=torch.float32).normal_() + else: + v = torch.tensor(value)[:, None, None] + + i = torch.randint(0, img_h - h + 1, size=(1,)).item() + j = torch.randint(0, img_w - w + 1, size=(1,)).item() + return i, j, h, w, v + + # Return original image + return 0, 0, img_h, img_w, img + + def forward(self, img): + """ + Args: + img (Tensor): Tensor image to be erased. + + Returns: + img (Tensor): Erased Tensor image. + """ + if torch.rand(1) < self.p: + + # cast self.value to script acceptable type + if isinstance(self.value, (int, float)): + value = [float(self.value)] + elif isinstance(self.value, str): + value = None + elif isinstance(self.value, (list, tuple)): + value = [float(v) for v in self.value] + else: + value = self.value + + if value is not None and len(value) not in (1, img.shape[-3]): + raise ValueError( + "If value is a sequence, it should have either a single value or " + f"{img.shape[-3]} (number of input channels)" + ) + + x, y, h, w, v = self.get_params(img, scale=self.scale, ratio=self.ratio, value=value) + return F.erase(img, x, y, h, w, v, self.inplace) + return img + + def __repr__(self) -> str: + s = ( + f"{self.__class__.__name__}" + f"(p={self.p}, " + f"scale={self.scale}, " + f"ratio={self.ratio}, " + f"value={self.value}, " + f"inplace={self.inplace})" + ) + return s + + +class GaussianBlur(torch.nn.Module): + """Blurs image with randomly chosen Gaussian blur. + If the image is torch Tensor, it is expected + to have [..., C, H, W] shape, where ... means at most one leading dimension. + + Args: + kernel_size (int or sequence): Size of the Gaussian kernel. + sigma (float or tuple of float (min, max)): Standard deviation to be used for + creating kernel to perform blurring. If float, sigma is fixed. If it is tuple + of float (min, max), sigma is chosen uniformly at random to lie in the + given range. + + Returns: + PIL Image or Tensor: Gaussian blurred version of the input image. + + """ + + def __init__(self, kernel_size, sigma=(0.1, 2.0)): + super().__init__() + _log_api_usage_once(self) + self.kernel_size = _setup_size(kernel_size, "Kernel size should be a tuple/list of two integers") + for ks in self.kernel_size: + if ks <= 0 or ks % 2 == 0: + raise ValueError("Kernel size value should be an odd and positive number.") + + if isinstance(sigma, numbers.Number): + if sigma <= 0: + raise ValueError("If sigma is a single number, it must be positive.") + sigma = (sigma, sigma) + elif isinstance(sigma, Sequence) and len(sigma) == 2: + if not 0.0 < sigma[0] <= sigma[1]: + raise ValueError("sigma values should be positive and of the form (min, max).") + else: + raise ValueError("sigma should be a single number or a list/tuple with length 2.") + + self.sigma = sigma + + @staticmethod + def get_params(sigma_min: float, sigma_max: float) -> float: + """Choose sigma for random gaussian blurring. + + Args: + sigma_min (float): Minimum standard deviation that can be chosen for blurring kernel. + sigma_max (float): Maximum standard deviation that can be chosen for blurring kernel. + + Returns: + float: Standard deviation to be passed to calculate kernel for gaussian blurring. + """ + return torch.empty(1).uniform_(sigma_min, sigma_max).item() + + def forward(self, img: Tensor) -> Tensor: + """ + Args: + img (PIL Image or Tensor): image to be blurred. + + Returns: + PIL Image or Tensor: Gaussian blurred image + """ + sigma = self.get_params(self.sigma[0], self.sigma[1]) + return F.gaussian_blur(img, self.kernel_size, [sigma, sigma]) + + def __repr__(self) -> str: + s = f"{self.__class__.__name__}(kernel_size={self.kernel_size}, sigma={self.sigma})" + return s + + +def _setup_size(size, error_msg): + if isinstance(size, numbers.Number): + return int(size), int(size) + + if isinstance(size, Sequence) and len(size) == 1: + return size[0], size[0] + + if len(size) != 2: + raise ValueError(error_msg) + + return size + + +def _check_sequence_input(x, name, req_sizes): + msg = req_sizes[0] if len(req_sizes) < 2 else " or ".join([str(s) for s in req_sizes]) + if not isinstance(x, Sequence): + raise TypeError(f"{name} should be a sequence of length {msg}.") + if len(x) not in req_sizes: + raise ValueError(f"{name} should be a sequence of length {msg}.") + + +def _setup_angle(x, name, req_sizes=(2,)): + if isinstance(x, numbers.Number): + if x < 0: + raise ValueError(f"If {name} is a single number, it must be positive.") + x = [-x, x] + else: + _check_sequence_input(x, name, req_sizes) + + return [float(d) for d in x] + + +class RandomInvert(torch.nn.Module): + """Inverts the colors of the given image randomly with a given probability. + If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + p (float): probability of the image being color inverted. Default value is 0.5 + """ + + def __init__(self, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be inverted. + + Returns: + PIL Image or Tensor: Randomly color inverted image. + """ + if torch.rand(1).item() < self.p: + return F.invert(img) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" + + +class RandomPosterize(torch.nn.Module): + """Posterize the image randomly with a given probability by reducing the + number of bits for each color channel. If the image is torch Tensor, it should be of type torch.uint8, + and it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + bits (int): number of bits to keep for each channel (0-8) + p (float): probability of the image being posterized. Default value is 0.5 + """ + + def __init__(self, bits, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.bits = bits + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be posterized. + + Returns: + PIL Image or Tensor: Randomly posterized image. + """ + if torch.rand(1).item() < self.p: + return F.posterize(img, self.bits) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(bits={self.bits},p={self.p})" + + +class RandomSolarize(torch.nn.Module): + """Solarize the image randomly with a given probability by inverting all pixel + values above a threshold. If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + threshold (float): all pixels equal or above this value are inverted. + p (float): probability of the image being solarized. Default value is 0.5 + """ + + def __init__(self, threshold, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.threshold = threshold + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be solarized. + + Returns: + PIL Image or Tensor: Randomly solarized image. + """ + if torch.rand(1).item() < self.p: + return F.solarize(img, self.threshold) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(threshold={self.threshold},p={self.p})" + + +class RandomAdjustSharpness(torch.nn.Module): + """Adjust the sharpness of the image randomly with a given probability. If the image is torch Tensor, + it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + sharpness_factor (float): How much to adjust the sharpness. Can be + any non-negative number. 0 gives a blurred image, 1 gives the + original image while 2 increases the sharpness by a factor of 2. + p (float): probability of the image being sharpened. Default value is 0.5 + """ + + def __init__(self, sharpness_factor, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.sharpness_factor = sharpness_factor + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be sharpened. + + Returns: + PIL Image or Tensor: Randomly sharpened image. + """ + if torch.rand(1).item() < self.p: + return F.adjust_sharpness(img, self.sharpness_factor) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(sharpness_factor={self.sharpness_factor},p={self.p})" + + +class RandomAutocontrast(torch.nn.Module): + """Autocontrast the pixels of the given image randomly with a given probability. + If the image is torch Tensor, it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + p (float): probability of the image being autocontrasted. Default value is 0.5 + """ + + def __init__(self, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be autocontrasted. + + Returns: + PIL Image or Tensor: Randomly autocontrasted image. + """ + if torch.rand(1).item() < self.p: + return F.autocontrast(img) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" + + +class RandomEqualize(torch.nn.Module): + """Equalize the histogram of the given image randomly with a given probability. + If the image is torch Tensor, it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "P", "L" or "RGB". + + Args: + p (float): probability of the image being equalized. Default value is 0.5 + """ + + def __init__(self, p=0.5): + super().__init__() + _log_api_usage_once(self) + self.p = p + + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be equalized. + + Returns: + PIL Image or Tensor: Randomly equalized image. + """ + if torch.rand(1).item() < self.p: + return F.equalize(img) + return img + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(p={self.p})" + + +class ElasticTransform(torch.nn.Module): + """Transform a tensor image with elastic transformations. + Given alpha and sigma, it will generate displacement + vectors for all pixels based on random offsets. Alpha controls the strength + and sigma controls the smoothness of the displacements. + The displacements are added to an identity grid and the resulting grid is + used to grid_sample from the image. + + Applications: + Randomly transforms the morphology of objects in images and produces a + see-through-water-like effect. + + Args: + alpha (float or sequence of floats): Magnitude of displacements. Default is 50.0. + sigma (float or sequence of floats): Smoothness of displacements. Default is 5.0. + interpolation (InterpolationMode): Desired interpolation enum defined by + :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. + If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. + The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (sequence or number): Pixel fill value for the area outside the transformed + image. Default is ``0``. If given a number, the value is used for all bands respectively. + + """ + + def __init__(self, alpha=50.0, sigma=5.0, interpolation=InterpolationMode.BILINEAR, fill=0): + super().__init__() + _log_api_usage_once(self) + if not isinstance(alpha, (float, Sequence)): + raise TypeError(f"alpha should be float or a sequence of floats. Got {type(alpha)}") + if isinstance(alpha, Sequence) and len(alpha) != 2: + raise ValueError(f"If alpha is a sequence its length should be 2. Got {len(alpha)}") + if isinstance(alpha, Sequence): + for element in alpha: + if not isinstance(element, float): + raise TypeError(f"alpha should be a sequence of floats. Got {type(element)}") + + if isinstance(alpha, float): + alpha = [float(alpha), float(alpha)] + if isinstance(alpha, (list, tuple)) and len(alpha) == 1: + alpha = [alpha[0], alpha[0]] + + self.alpha = alpha + + if not isinstance(sigma, (float, Sequence)): + raise TypeError(f"sigma should be float or a sequence of floats. Got {type(sigma)}") + if isinstance(sigma, Sequence) and len(sigma) != 2: + raise ValueError(f"If sigma is a sequence its length should be 2. Got {len(sigma)}") + if isinstance(sigma, Sequence): + for element in sigma: + if not isinstance(element, float): + raise TypeError(f"sigma should be a sequence of floats. Got {type(element)}") + + if isinstance(sigma, float): + sigma = [float(sigma), float(sigma)] + if isinstance(sigma, (list, tuple)) and len(sigma) == 1: + sigma = [sigma[0], sigma[0]] + + self.sigma = sigma + + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + self.interpolation = interpolation + + if isinstance(fill, (int, float)): + fill = [float(fill)] + elif isinstance(fill, (list, tuple)): + fill = [float(f) for f in fill] + else: + raise TypeError(f"fill should be int or float or a list or tuple of them. Got {type(fill)}") + self.fill = fill + + @staticmethod + def get_params(alpha: list[float], sigma: list[float], size: list[int]) -> Tensor: + dx = torch.rand([1, 1] + size) * 2 - 1 + if sigma[0] > 0.0: + kx = int(8 * sigma[0] + 1) + # if kernel size is even we have to make it odd + if kx % 2 == 0: + kx += 1 + dx = F.gaussian_blur(dx, [kx, kx], sigma) + # normalize horizontal displacement by width (size[1]) + dx = dx * alpha[0] / size[1] + + dy = torch.rand([1, 1] + size) * 2 - 1 + if sigma[1] > 0.0: + ky = int(8 * sigma[1] + 1) + # if kernel size is even we have to make it odd + if ky % 2 == 0: + ky += 1 + dy = F.gaussian_blur(dy, [ky, ky], sigma) + # normalize vertical displacement by height (size[0]) + dy = dy * alpha[1] / size[0] + return torch.concat([dx, dy], 1).permute([0, 2, 3, 1]) # 1 x H x W x 2 + + def forward(self, tensor: Tensor) -> Tensor: + """ + Args: + tensor (PIL Image or Tensor): Image to be transformed. + + Returns: + PIL Image or Tensor: Transformed image. + """ + _, height, width = F.get_dimensions(tensor) + displacement = self.get_params(self.alpha, self.sigma, [height, width]) + return F.elastic_transform(tensor, displacement, self.interpolation, self.fill) + + def __repr__(self): + format_string = self.__class__.__name__ + format_string += f"(alpha={self.alpha}" + format_string += f", sigma={self.sigma}" + format_string += f", interpolation={self.interpolation}" + format_string += f", fill={self.fill})" + return format_string diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e182932a372bb38a0a5121cf082c1bfa09cceb04 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__init__.py @@ -0,0 +1,62 @@ +from torchvision.transforms import AutoAugmentPolicy # usort: skip +from torchvision.transforms.functional import InterpolationMode # usort: skip + +from . import functional # usort: skip + +from ._transform import Transform # usort: skip + +from ._augment import CutMix, JPEG, MixUp, RandomErasing +from ._auto_augment import AugMix, AutoAugment, RandAugment, TrivialAugmentWide +from ._color import ( + ColorJitter, + Grayscale, + RandomAdjustSharpness, + RandomAutocontrast, + RandomChannelPermutation, + RandomEqualize, + RandomGrayscale, + RandomInvert, + RandomPhotometricDistort, + RandomPosterize, + RandomSolarize, + RGB, +) +from ._container import Compose, RandomApply, RandomChoice, RandomOrder +from ._geometry import ( + CenterCrop, + ElasticTransform, + FiveCrop, + Pad, + RandomAffine, + RandomCrop, + RandomHorizontalFlip, + RandomIoUCrop, + RandomPerspective, + RandomResize, + RandomResizedCrop, + RandomRotation, + RandomShortestSize, + RandomVerticalFlip, + RandomZoomOut, + Resize, + ScaleJitter, + TenCrop, +) +from ._meta import ClampBoundingBoxes, ClampKeyPoints, ConvertBoundingBoxFormat, SetClampingMode +from ._misc import ( + ConvertImageDtype, + GaussianBlur, + GaussianNoise, + Identity, + Lambda, + LinearTransformation, + Normalize, + SanitizeBoundingBoxes, + SanitizeKeyPoints, + ToDtype, +) +from ._temporal import UniformTemporalSubsample +from ._type_conversion import PILToTensor, ToImage, ToPILImage, ToPureTensor +from ._utils import check_type, get_bounding_boxes, get_keypoints, has_all, has_any, query_chw, query_size + +from ._deprecated import ToTensor # usort: skip diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ddf8746eff9cae2a1ddd5101f0b3ca7d6b55efa Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_augment.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_augment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a4090cf62e2095cb372c4fef22edc86e21bdb00 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_augment.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_auto_augment.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_auto_augment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7f0679484f5847774eac98cfe9686142bc42cef Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_auto_augment.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_color.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_color.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8d390ac68a39b184cf85885b347fbf0870ed303 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_color.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_container.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_container.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d87fccb93e77780502aa29a847558949e12d596 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_container.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_deprecated.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_deprecated.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..590592a1de299f4b886ef236fff285928b39f5f7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_deprecated.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_geometry.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_geometry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0ff0fc03ef32ac1ca036823da56b33dd656edb5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_geometry.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_meta.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_meta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5705bfd7974b2d6272d55434050ed4d4f567a8ad Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_meta.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_misc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_misc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..404690ce587e54c153621db349d30f97dc8c92ae Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_misc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_temporal.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_temporal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e05947a8b2c6895d3c2792978c72fe31b8075402 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_temporal.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_transform.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_transform.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..366327ae74d2043ed0e545ace9b809186e4bfae9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_transform.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_type_conversion.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_type_conversion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7b174019a65f051f500a27449f776d450dc10c8 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_type_conversion.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e02c9fc44b687a1eb1d9e3d75f740628917612b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/__pycache__/_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_augment.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_augment.py new file mode 100644 index 0000000000000000000000000000000000000000..4b1d15a91e183a4d4e093df7d5bff84b732da847 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_augment.py @@ -0,0 +1,372 @@ +import math +import numbers +import warnings +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +import PIL.Image +import torch +from torch.nn.functional import one_hot +from torch.utils._pytree import tree_flatten, tree_unflatten +from torchvision import transforms as _transforms, tv_tensors +from torchvision.transforms.v2 import functional as F + +from ._transform import _RandomApplyTransform, Transform +from ._utils import _check_sequence_input, _parse_labels_getter, has_any, is_pure_tensor, query_chw, query_size + + +class RandomErasing(_RandomApplyTransform): + """Randomly select a rectangle region in the input image or video and erase its pixels. + 'Random Erasing Data Augmentation' by Zhong et al. See https://arxiv.org/abs/1708.04896 + + Args: + p (float, optional): probability that the random erasing operation will be performed. + scale (tuple of float, optional): range of proportion of erased area against input image. + ratio (tuple of float, optional): range of aspect ratio of erased area. + value (number or tuple of numbers): erasing value. Default is 0. If a single int, it is used to + erase all pixels. If a tuple of length 3, it is used to erase + R, G, B channels respectively. + If a str of 'random', erasing each pixel with random values. + inplace (bool, optional): boolean to make this transform inplace. Default set to False. + + Returns: + Erased input. + + Example: + >>> from torchvision.transforms import v2 as transforms + >>> + >>> transform = transforms.Compose([ + >>> transforms.RandomHorizontalFlip(), + >>> transforms.PILToTensor(), + >>> transforms.ConvertImageDtype(torch.float), + >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + >>> transforms.RandomErasing(), + >>> ]) + """ + + _v1_transform_cls = _transforms.RandomErasing + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + return dict( + super()._extract_params_for_v1_transform(), + value="random" if self.value is None else self.value, + ) + + def __init__( + self, + p: float = 0.5, + scale: Sequence[float] = (0.02, 0.33), + ratio: Sequence[float] = (0.3, 3.3), + value: float = 0.0, + inplace: bool = False, + ): + super().__init__(p=p) + if not isinstance(value, (numbers.Number, str, tuple, list)): + raise TypeError("Argument value should be either a number or str or a sequence") + if isinstance(value, str) and value != "random": + raise ValueError("If value is str, it should be 'random'") + if not isinstance(scale, Sequence): + raise TypeError("Scale should be a sequence") + if not isinstance(ratio, Sequence): + raise TypeError("Ratio should be a sequence") + if (scale[0] > scale[1]) or (ratio[0] > ratio[1]): + warnings.warn("Scale and ratio should be of kind (min, max)") + if scale[0] < 0 or scale[1] > 1: + raise ValueError("Scale should be between 0 and 1") + self.scale = scale + self.ratio = ratio + if isinstance(value, (int, float)): + self.value = [float(value)] + elif isinstance(value, str): + self.value = None + elif isinstance(value, (list, tuple)): + self.value = [float(v) for v in value] + else: + self.value = value + self.inplace = inplace + + self._log_ratio = torch.log(torch.tensor(self.ratio)) + + def _call_kernel(self, functional: Callable, inpt: Any, *args: Any, **kwargs: Any) -> Any: + if isinstance(inpt, (tv_tensors.BoundingBoxes, tv_tensors.KeyPoints, tv_tensors.Mask)): + warnings.warn( + f"{type(self).__name__}() is currently passing through inputs of type " + f"tv_tensors.{type(inpt).__name__}. This will likely change in the future." + ) + return super()._call_kernel(functional, inpt, *args, **kwargs) + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + img_c, img_h, img_w = query_chw(flat_inputs) + + if self.value is not None and len(self.value) not in (1, img_c): + raise ValueError( + f"If value is a sequence, it should have either a single value or {img_c} (number of inpt channels)" + ) + + area = img_h * img_w + + log_ratio = self._log_ratio + for _ in range(10): + erase_area = area * torch.empty(1).uniform_(self.scale[0], self.scale[1]).item() + aspect_ratio = torch.exp( + torch.empty(1).uniform_( + log_ratio[0], # type: ignore[arg-type] + log_ratio[1], # type: ignore[arg-type] + ) + ).item() + + h = int(round(math.sqrt(erase_area * aspect_ratio))) + w = int(round(math.sqrt(erase_area / aspect_ratio))) + if not (h < img_h and w < img_w): + continue + + if self.value is None: + v = torch.empty([img_c, h, w], dtype=torch.float32).normal_() + else: + v = torch.tensor(self.value)[:, None, None] + + i = torch.randint(0, img_h - h + 1, size=(1,)).item() + j = torch.randint(0, img_w - w + 1, size=(1,)).item() + break + else: + i, j, h, w, v = 0, 0, img_h, img_w, None + + return dict(i=i, j=j, h=h, w=w, v=v) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + if params["v"] is not None: + inpt = self._call_kernel(F.erase, inpt, **params, inplace=self.inplace) + + return inpt + + +class _BaseMixUpCutMix(Transform): + def __init__(self, *, alpha: float = 1.0, num_classes: Optional[int] = None, labels_getter="default") -> None: + super().__init__() + self.alpha = float(alpha) + self._dist = torch.distributions.Beta(torch.tensor([alpha]), torch.tensor([alpha])) + + self.num_classes = num_classes + + self._labels_getter = _parse_labels_getter(labels_getter) + + def forward(self, *inputs): + inputs = inputs if len(inputs) > 1 else inputs[0] + flat_inputs, spec = tree_flatten(inputs) + needs_transform_list = self._needs_transform_list(flat_inputs) + + if has_any(flat_inputs, PIL.Image.Image, tv_tensors.BoundingBoxes, tv_tensors.Mask, tv_tensors.KeyPoints): + raise ValueError( + f"{type(self).__name__}() does not support PIL images, bounding boxes, keypoints and masks." + ) + + labels = self._labels_getter(inputs) + if not isinstance(labels, torch.Tensor): + raise ValueError(f"The labels must be a tensor, but got {type(labels)} instead.") + if labels.ndim not in (1, 2): + raise ValueError( + f"labels should be index based with shape (batch_size,) " + f"or probability based with shape (batch_size, num_classes), " + f"but got a tensor of shape {labels.shape} instead." + ) + if labels.ndim == 2 and self.num_classes is not None and labels.shape[-1] != self.num_classes: + raise ValueError( + f"When passing 2D labels, " + f"the number of elements in last dimension must match num_classes: " + f"{labels.shape[-1]} != {self.num_classes}. " + f"You can Leave num_classes to None." + ) + if labels.ndim == 1 and self.num_classes is None: + raise ValueError("num_classes must be passed if the labels are index-based (1D)") + + params = { + "labels": labels, + "batch_size": labels.shape[0], + **self.make_params( + [inpt for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) if needs_transform] + ), + } + + # By default, the labels will be False inside needs_transform_list, since they are a torch.Tensor coming + # after an image or video. However, we need to handle them in _transform, so we make sure to set them to True + needs_transform_list[next(idx for idx, inpt in enumerate(flat_inputs) if inpt is labels)] = True + flat_outputs = [ + self.transform(inpt, params) if needs_transform else inpt + for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) + ] + + return tree_unflatten(flat_outputs, spec) + + def _check_image_or_video(self, inpt: torch.Tensor, *, batch_size: int): + expected_num_dims = 5 if isinstance(inpt, tv_tensors.Video) else 4 + if inpt.ndim != expected_num_dims: + raise ValueError( + f"Expected a batched input with {expected_num_dims} dims, but got {inpt.ndim} dimensions instead." + ) + if inpt.shape[0] != batch_size: + raise ValueError( + f"The batch size of the image or video does not match the batch size of the labels: " + f"{inpt.shape[0]} != {batch_size}." + ) + + def _mixup_label(self, label: torch.Tensor, *, lam: float) -> torch.Tensor: + if label.ndim == 1: + label = one_hot(label, num_classes=self.num_classes) # type: ignore[arg-type] + if not label.dtype.is_floating_point: + label = label.float() + return label.roll(1, 0).mul_(1.0 - lam).add_(label.mul(lam)) + + +class MixUp(_BaseMixUpCutMix): + """Apply MixUp to the provided batch of images and labels. + + Paper: `mixup: Beyond Empirical Risk Minimization `_. + + .. note:: + This transform is meant to be used on **batches** of samples, not + individual images. See + :ref:`sphx_glr_auto_examples_transforms_plot_cutmix_mixup.py` for detailed usage + examples. + The sample pairing is deterministic and done by matching consecutive + samples in the batch, so the batch needs to be shuffled (this is an + implementation detail, not a guaranteed convention.) + + In the input, the labels are expected to be a tensor of shape ``(batch_size,)``. They will be transformed + into a tensor of shape ``(batch_size, num_classes)``. + + Args: + alpha (float, optional): hyperparameter of the Beta distribution used for mixup. Default is 1. + num_classes (int, optional): number of classes in the batch. Used for one-hot-encoding. + Can be None only if the labels are already one-hot-encoded. + labels_getter (callable or "default", optional): indicates how to identify the labels in the input. + By default, this will pick the second parameter as the labels if it's a tensor. This covers the most + common scenario where this transform is called as ``MixUp()(imgs_batch, labels_batch)``. + It can also be a callable that takes the same input as the transform, and returns the labels. + """ + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + return dict(lam=float(self._dist.sample(()))) # type: ignore[arg-type] + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + lam = params["lam"] + + if inpt is params["labels"]: + return self._mixup_label(inpt, lam=lam) + elif isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)) or is_pure_tensor(inpt): + self._check_image_or_video(inpt, batch_size=params["batch_size"]) + + output = inpt.roll(1, 0).mul_(1.0 - lam).add_(inpt.mul(lam)) + + if isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)): + output = tv_tensors.wrap(output, like=inpt) + + return output + else: + return inpt + + +class CutMix(_BaseMixUpCutMix): + """Apply CutMix to the provided batch of images and labels. + + Paper: `CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features + `_. + + .. note:: + This transform is meant to be used on **batches** of samples, not + individual images. See + :ref:`sphx_glr_auto_examples_transforms_plot_cutmix_mixup.py` for detailed usage + examples. + The sample pairing is deterministic and done by matching consecutive + samples in the batch, so the batch needs to be shuffled (this is an + implementation detail, not a guaranteed convention.) + + In the input, the labels are expected to be a tensor of shape ``(batch_size,)``. They will be transformed + into a tensor of shape ``(batch_size, num_classes)``. + + Args: + alpha (float, optional): hyperparameter of the Beta distribution used for mixup. Default is 1. + num_classes (int, optional): number of classes in the batch. Used for one-hot-encoding. + Can be None only if the labels are already one-hot-encoded. + labels_getter (callable or "default", optional): indicates how to identify the labels in the input. + By default, this will pick the second parameter as the labels if it's a tensor. This covers the most + common scenario where this transform is called as ``CutMix()(imgs_batch, labels_batch)``. + It can also be a callable that takes the same input as the transform, and returns the labels. + """ + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + lam = float(self._dist.sample(())) # type: ignore[arg-type] + + H, W = query_size(flat_inputs) + + r_x = torch.randint(W, size=(1,)) + r_y = torch.randint(H, size=(1,)) + + r = 0.5 * math.sqrt(1.0 - lam) + r_w_half = int(r * W) + r_h_half = int(r * H) + + x1 = int(torch.clamp(r_x - r_w_half, min=0)) + y1 = int(torch.clamp(r_y - r_h_half, min=0)) + x2 = int(torch.clamp(r_x + r_w_half, max=W)) + y2 = int(torch.clamp(r_y + r_h_half, max=H)) + box = (x1, y1, x2, y2) + + lam_adjusted = float(1.0 - (x2 - x1) * (y2 - y1) / (W * H)) + + return dict(box=box, lam_adjusted=lam_adjusted) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + if inpt is params["labels"]: + return self._mixup_label(inpt, lam=params["lam_adjusted"]) + elif isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)) or is_pure_tensor(inpt): + self._check_image_or_video(inpt, batch_size=params["batch_size"]) + + x1, y1, x2, y2 = params["box"] + rolled = inpt.roll(1, 0) + output = inpt.clone() + output[..., y1:y2, x1:x2] = rolled[..., y1:y2, x1:x2] + + if isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)): + output = tv_tensors.wrap(output, like=inpt) + + return output + else: + return inpt + + +class JPEG(Transform): + """Apply JPEG compression and decompression to the given images. + + If the input is a :class:`torch.Tensor`, it is expected + to be of dtype uint8, on CPU, and have [..., 3 or 1, H, W] shape, + where ... means an arbitrary number of leading dimensions. + + Args: + quality (sequence or number): JPEG quality, from 1 to 100. Lower means more compression. + If quality is a sequence like (min, max), it specifies the range of JPEG quality to + randomly select from (inclusive of both ends). + + Returns: + image with JPEG compression. + """ + + def __init__(self, quality: Union[int, Sequence[int]]): + super().__init__() + if isinstance(quality, int): + if isinstance(quality, bool): + raise TypeError("quality can't be bool") + quality = [quality, quality] + else: + _check_sequence_input(quality, "quality", req_sizes=(2,)) + + if not (1 <= quality[0] <= quality[1] <= 100 and isinstance(quality[0], int) and isinstance(quality[1], int)): + raise ValueError(f"quality must be an integer from 1 to 100, got {quality =}") + + self.quality = quality + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + quality = torch.randint(self.quality[0], self.quality[1] + 1, ()).item() + return dict(quality=quality) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.jpeg, inpt, quality=params["quality"]) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_auto_augment.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_auto_augment.py new file mode 100644 index 0000000000000000000000000000000000000000..00e2b03325e3797835bfcf6670f5d5cb8b7b020d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_auto_augment.py @@ -0,0 +1,646 @@ +import math +from typing import Any, Callable, cast, Optional, Union + +import PIL.Image +import torch + +from torch.utils._pytree import tree_flatten, tree_unflatten, TreeSpec +from torchvision import transforms as _transforms, tv_tensors +from torchvision.transforms import _functional_tensor as _FT +from torchvision.transforms.v2 import AutoAugmentPolicy, functional as F, InterpolationMode, Transform +from torchvision.transforms.v2.functional._meta import get_size +from torchvision.transforms.v2.functional._utils import _FillType, _FillTypeJIT + +from ._utils import _get_fill, _setup_fill_arg, check_type, is_pure_tensor + + +ImageOrVideo = Union[torch.Tensor, PIL.Image.Image, tv_tensors.Image, tv_tensors.Video] + + +class _AutoAugmentBase(Transform): + def __init__( + self, + *, + interpolation: Union[str, InterpolationMode, int] = "nearest", + fill: Union[_FillType, dict[Union[type, str], _FillType]] = None, + ) -> None: + super().__init__() + self.interpolation = interpolation + self.fill = fill + self._fill = _setup_fill_arg(fill) + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + params = super()._extract_params_for_v1_transform() + + if isinstance(params["fill"], dict): + raise ValueError(f"{type(self).__name__}() can not be scripted for when `fill` is a dictionary.") + + return params + + def _get_random_item(self, dct: dict[str, tuple[Callable, bool]]) -> tuple[str, tuple[Callable, bool]]: + keys = tuple(dct.keys()) + key = keys[int(torch.randint(len(keys), ()))] + return key, dct[key] + + def _flatten_and_extract_image_or_video( + self, + inputs: Any, + unsupported_types: tuple[type, ...] = (tv_tensors.BoundingBoxes, tv_tensors.Mask, tv_tensors.KeyPoints), + ) -> tuple[tuple[list[Any], TreeSpec, int], ImageOrVideo]: + flat_inputs, spec = tree_flatten(inputs if len(inputs) > 1 else inputs[0]) + needs_transform_list = self._needs_transform_list(flat_inputs) + + image_or_videos = [] + for idx, (inpt, needs_transform) in enumerate(zip(flat_inputs, needs_transform_list)): + if needs_transform and check_type( + inpt, + ( + tv_tensors.Image, + PIL.Image.Image, + is_pure_tensor, + tv_tensors.Video, + ), + ): + image_or_videos.append((idx, inpt)) + elif isinstance(inpt, unsupported_types): + raise TypeError(f"Inputs of type {type(inpt).__name__} are not supported by {type(self).__name__}()") + + if not image_or_videos: + raise TypeError("Found no image in the sample.") + if len(image_or_videos) > 1: + raise TypeError( + f"Auto augment transformations are only properly defined for a single image or video, " + f"but found {len(image_or_videos)}." + ) + + idx, image_or_video = image_or_videos[0] + return (flat_inputs, spec, idx), image_or_video + + def _unflatten_and_insert_image_or_video( + self, + flat_inputs_with_spec: tuple[list[Any], TreeSpec, int], + image_or_video: ImageOrVideo, + ) -> Any: + flat_inputs, spec, idx = flat_inputs_with_spec + flat_inputs[idx] = image_or_video + return tree_unflatten(flat_inputs, spec) + + def _apply_image_or_video_transform( + self, + image: ImageOrVideo, + transform_id: str, + magnitude: float, + interpolation: Union[str, InterpolationMode, int], + fill: dict[Union[type, str], _FillTypeJIT], + ) -> ImageOrVideo: + # Note: this cast is wrong and is only here to make mypy happy (it disagrees with torchscript) + image = cast(torch.Tensor, image) + fill_ = _get_fill(fill, type(image)) + + if transform_id == "Identity": + return image + elif transform_id == "ShearX": + # magnitude should be arctan(magnitude) + # official autoaug: (1, level, 0, 0, 1, 0) + # https://github.com/tensorflow/models/blob/dd02069717128186b88afa8d857ce57d17957f03/research/autoaugment/augmentation_transforms.py#L290 + # compared to + # torchvision: (1, tan(level), 0, 0, 1, 0) + # https://github.com/pytorch/vision/blob/0c2373d0bba3499e95776e7936e207d8a1676e65/torchvision/transforms/functional.py#L976 + return F.affine( + image, + angle=0.0, + translate=[0, 0], + scale=1.0, + shear=[math.degrees(math.atan(magnitude)), 0.0], + interpolation=interpolation, + fill=fill_, + center=[0, 0], + ) + elif transform_id == "ShearY": + # magnitude should be arctan(magnitude) + # See above + return F.affine( + image, + angle=0.0, + translate=[0, 0], + scale=1.0, + shear=[0.0, math.degrees(math.atan(magnitude))], + interpolation=interpolation, + fill=fill_, + center=[0, 0], + ) + elif transform_id == "TranslateX": + return F.affine( + image, + angle=0.0, + translate=[int(magnitude), 0], + scale=1.0, + interpolation=interpolation, + shear=[0.0, 0.0], + fill=fill_, + ) + elif transform_id == "TranslateY": + return F.affine( + image, + angle=0.0, + translate=[0, int(magnitude)], + scale=1.0, + interpolation=interpolation, + shear=[0.0, 0.0], + fill=fill_, + ) + elif transform_id == "Rotate": + return F.rotate(image, angle=magnitude, interpolation=interpolation, fill=fill_) + elif transform_id == "Brightness": + return F.adjust_brightness(image, brightness_factor=1.0 + magnitude) + elif transform_id == "Color": + return F.adjust_saturation(image, saturation_factor=1.0 + magnitude) + elif transform_id == "Contrast": + return F.adjust_contrast(image, contrast_factor=1.0 + magnitude) + elif transform_id == "Sharpness": + return F.adjust_sharpness(image, sharpness_factor=1.0 + magnitude) + elif transform_id == "Posterize": + return F.posterize(image, bits=int(magnitude)) + elif transform_id == "Solarize": + bound = _FT._max_value(image.dtype) if isinstance(image, torch.Tensor) else 255.0 + return F.solarize(image, threshold=bound * magnitude) + elif transform_id == "AutoContrast": + return F.autocontrast(image) + elif transform_id == "Equalize": + return F.equalize(image) + elif transform_id == "Invert": + return F.invert(image) + else: + raise ValueError(f"No transform available for {transform_id}") + + +class AutoAugment(_AutoAugmentBase): + r"""AutoAugment data augmentation method based on + `"AutoAugment: Learning Augmentation Strategies from Data" `_. + + This transformation works on images and videos only. + + If the input is :class:`torch.Tensor`, it should be of type ``torch.uint8``, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + policy (AutoAugmentPolicy, optional): Desired policy enum defined by + :class:`torchvision.transforms.autoaugment.AutoAugmentPolicy`. Default is ``AutoAugmentPolicy.IMAGENET``. + interpolation (str or InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.v2.InterpolationMode`. + Accepted string values are ``"nearest"``, ``"nearest-exact"``, ``"bilinear"``, ``"bicubic"``, + ``"box"``, ``"hamming"``, and ``"lanczos"``. + ``"box"``, ``"hamming"``, and ``"lanczos"`` are only supported for PIL images. + The corresponding ``InterpolationMode`` enum values and Pillow integer + constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + _v1_transform_cls = _transforms.AutoAugment + + _AUGMENTATION_SPACE = { + "ShearX": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True), + "ShearY": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True), + "TranslateX": ( + lambda num_bins, height, width: torch.linspace(0.0, 150.0 / 331.0 * width, num_bins), + True, + ), + "TranslateY": ( + lambda num_bins, height, width: torch.linspace(0.0, 150.0 / 331.0 * height, num_bins), + True, + ), + "Rotate": (lambda num_bins, height, width: torch.linspace(0.0, 30.0, num_bins), True), + "Brightness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Color": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Contrast": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Sharpness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Posterize": ( + lambda num_bins, height, width: (8 - (torch.arange(num_bins) / ((num_bins - 1) / 4))).round().int(), + False, + ), + "Solarize": (lambda num_bins, height, width: torch.linspace(1.0, 0.0, num_bins), False), + "AutoContrast": (lambda num_bins, height, width: None, False), + "Equalize": (lambda num_bins, height, width: None, False), + "Invert": (lambda num_bins, height, width: None, False), + } + + def __init__( + self, + policy: AutoAugmentPolicy = AutoAugmentPolicy.IMAGENET, + interpolation: Union[str, InterpolationMode, int] = "nearest", + fill: Union[_FillType, dict[Union[type, str], _FillType]] = None, + ) -> None: + super().__init__(interpolation=interpolation, fill=fill) + self.policy = policy + self._policies = self._get_policies(policy) + + def _get_policies( + self, policy: AutoAugmentPolicy + ) -> list[tuple[tuple[str, float, Optional[int]], tuple[str, float, Optional[int]]]]: + if policy == AutoAugmentPolicy.IMAGENET: + return [ + (("Posterize", 0.4, 8), ("Rotate", 0.6, 9)), + (("Solarize", 0.6, 5), ("AutoContrast", 0.6, None)), + (("Equalize", 0.8, None), ("Equalize", 0.6, None)), + (("Posterize", 0.6, 7), ("Posterize", 0.6, 6)), + (("Equalize", 0.4, None), ("Solarize", 0.2, 4)), + (("Equalize", 0.4, None), ("Rotate", 0.8, 8)), + (("Solarize", 0.6, 3), ("Equalize", 0.6, None)), + (("Posterize", 0.8, 5), ("Equalize", 1.0, None)), + (("Rotate", 0.2, 3), ("Solarize", 0.6, 8)), + (("Equalize", 0.6, None), ("Posterize", 0.4, 6)), + (("Rotate", 0.8, 8), ("Color", 0.4, 0)), + (("Rotate", 0.4, 9), ("Equalize", 0.6, None)), + (("Equalize", 0.0, None), ("Equalize", 0.8, None)), + (("Invert", 0.6, None), ("Equalize", 1.0, None)), + (("Color", 0.6, 4), ("Contrast", 1.0, 8)), + (("Rotate", 0.8, 8), ("Color", 1.0, 2)), + (("Color", 0.8, 8), ("Solarize", 0.8, 7)), + (("Sharpness", 0.4, 7), ("Invert", 0.6, None)), + (("ShearX", 0.6, 5), ("Equalize", 1.0, None)), + (("Color", 0.4, 0), ("Equalize", 0.6, None)), + (("Equalize", 0.4, None), ("Solarize", 0.2, 4)), + (("Solarize", 0.6, 5), ("AutoContrast", 0.6, None)), + (("Invert", 0.6, None), ("Equalize", 1.0, None)), + (("Color", 0.6, 4), ("Contrast", 1.0, 8)), + (("Equalize", 0.8, None), ("Equalize", 0.6, None)), + ] + elif policy == AutoAugmentPolicy.CIFAR10: + return [ + (("Invert", 0.1, None), ("Contrast", 0.2, 6)), + (("Rotate", 0.7, 2), ("TranslateX", 0.3, 9)), + (("Sharpness", 0.8, 1), ("Sharpness", 0.9, 3)), + (("ShearY", 0.5, 8), ("TranslateY", 0.7, 9)), + (("AutoContrast", 0.5, None), ("Equalize", 0.9, None)), + (("ShearY", 0.2, 7), ("Posterize", 0.3, 7)), + (("Color", 0.4, 3), ("Brightness", 0.6, 7)), + (("Sharpness", 0.3, 9), ("Brightness", 0.7, 9)), + (("Equalize", 0.6, None), ("Equalize", 0.5, None)), + (("Contrast", 0.6, 7), ("Sharpness", 0.6, 5)), + (("Color", 0.7, 7), ("TranslateX", 0.5, 8)), + (("Equalize", 0.3, None), ("AutoContrast", 0.4, None)), + (("TranslateY", 0.4, 3), ("Sharpness", 0.2, 6)), + (("Brightness", 0.9, 6), ("Color", 0.2, 8)), + (("Solarize", 0.5, 2), ("Invert", 0.0, None)), + (("Equalize", 0.2, None), ("AutoContrast", 0.6, None)), + (("Equalize", 0.2, None), ("Equalize", 0.6, None)), + (("Color", 0.9, 9), ("Equalize", 0.6, None)), + (("AutoContrast", 0.8, None), ("Solarize", 0.2, 8)), + (("Brightness", 0.1, 3), ("Color", 0.7, 0)), + (("Solarize", 0.4, 5), ("AutoContrast", 0.9, None)), + (("TranslateY", 0.9, 9), ("TranslateY", 0.7, 9)), + (("AutoContrast", 0.9, None), ("Solarize", 0.8, 3)), + (("Equalize", 0.8, None), ("Invert", 0.1, None)), + (("TranslateY", 0.7, 9), ("AutoContrast", 0.9, None)), + ] + elif policy == AutoAugmentPolicy.SVHN: + return [ + (("ShearX", 0.9, 4), ("Invert", 0.2, None)), + (("ShearY", 0.9, 8), ("Invert", 0.7, None)), + (("Equalize", 0.6, None), ("Solarize", 0.6, 6)), + (("Invert", 0.9, None), ("Equalize", 0.6, None)), + (("Equalize", 0.6, None), ("Rotate", 0.9, 3)), + (("ShearX", 0.9, 4), ("AutoContrast", 0.8, None)), + (("ShearY", 0.9, 8), ("Invert", 0.4, None)), + (("ShearY", 0.9, 5), ("Solarize", 0.2, 6)), + (("Invert", 0.9, None), ("AutoContrast", 0.8, None)), + (("Equalize", 0.6, None), ("Rotate", 0.9, 3)), + (("ShearX", 0.9, 4), ("Solarize", 0.3, 3)), + (("ShearY", 0.8, 8), ("Invert", 0.7, None)), + (("Equalize", 0.9, None), ("TranslateY", 0.6, 6)), + (("Invert", 0.9, None), ("Equalize", 0.6, None)), + (("Contrast", 0.3, 3), ("Rotate", 0.8, 4)), + (("Invert", 0.8, None), ("TranslateY", 0.0, 2)), + (("ShearY", 0.7, 6), ("Solarize", 0.4, 8)), + (("Invert", 0.6, None), ("Rotate", 0.8, 4)), + (("ShearY", 0.3, 7), ("TranslateX", 0.9, 3)), + (("ShearX", 0.1, 6), ("Invert", 0.6, None)), + (("Solarize", 0.7, 2), ("TranslateY", 0.6, 7)), + (("ShearY", 0.8, 4), ("Invert", 0.8, None)), + (("ShearX", 0.7, 9), ("TranslateY", 0.8, 3)), + (("ShearY", 0.8, 5), ("AutoContrast", 0.7, None)), + (("ShearX", 0.7, 2), ("Invert", 0.1, None)), + ] + else: + raise ValueError(f"The provided policy {policy} is not recognized.") + + def forward(self, *inputs: Any) -> Any: + flat_inputs_with_spec, image_or_video = self._flatten_and_extract_image_or_video(inputs) + height, width = get_size(image_or_video) # type: ignore[arg-type] + + policy = self._policies[int(torch.randint(len(self._policies), ()))] + + for transform_id, probability, magnitude_idx in policy: + if not torch.rand(()) <= probability: + continue + + magnitudes_fn, signed = self._AUGMENTATION_SPACE[transform_id] + + magnitudes = magnitudes_fn(10, height, width) + if magnitudes is not None: + magnitude = float(magnitudes[magnitude_idx]) + if signed and torch.rand(()) <= 0.5: + magnitude *= -1 + else: + magnitude = 0.0 + + image_or_video = self._apply_image_or_video_transform( + image_or_video, transform_id, magnitude, interpolation=self.interpolation, fill=self._fill + ) + + return self._unflatten_and_insert_image_or_video(flat_inputs_with_spec, image_or_video) + + +class RandAugment(_AutoAugmentBase): + r"""RandAugment data augmentation method based on + `"RandAugment: Practical automated data augmentation with a reduced search space" + `_. + + This transformation works on images and videos only. + + If the input is :class:`torch.Tensor`, it should be of type ``torch.uint8``, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + num_ops (int, optional): Number of augmentation transformations to apply sequentially, + must be non-negative integer. Default: 2. + magnitude (int, optional): Magnitude for all the transformations. + num_magnitude_bins (int, optional): The number of different magnitude values. + interpolation (str or InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.v2.InterpolationMode`. + Accepted string values are ``"nearest"``, ``"nearest-exact"``, ``"bilinear"``, ``"bicubic"``, + ``"box"``, ``"hamming"``, and ``"lanczos"``. + ``"box"``, ``"hamming"``, and ``"lanczos"`` are only supported for PIL images. + The corresponding ``InterpolationMode`` enum values and Pillow integer + constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + _v1_transform_cls = _transforms.RandAugment + _AUGMENTATION_SPACE = { + "Identity": (lambda num_bins, height, width: None, False), + "ShearX": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True), + "ShearY": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True), + "TranslateX": ( + lambda num_bins, height, width: torch.linspace(0.0, 150.0 / 331.0 * width, num_bins), + True, + ), + "TranslateY": ( + lambda num_bins, height, width: torch.linspace(0.0, 150.0 / 331.0 * height, num_bins), + True, + ), + "Rotate": (lambda num_bins, height, width: torch.linspace(0.0, 30.0, num_bins), True), + "Brightness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Color": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Contrast": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Sharpness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Posterize": ( + lambda num_bins, height, width: (8 - (torch.arange(num_bins) / ((num_bins - 1) / 4))).round().int(), + False, + ), + "Solarize": (lambda num_bins, height, width: torch.linspace(1.0, 0.0, num_bins), False), + "AutoContrast": (lambda num_bins, height, width: None, False), + "Equalize": (lambda num_bins, height, width: None, False), + } + + def __init__( + self, + num_ops: int = 2, + magnitude: int = 9, + num_magnitude_bins: int = 31, + interpolation: Union[str, InterpolationMode, int] = "nearest", + fill: Union[_FillType, dict[Union[type, str], _FillType]] = None, + ) -> None: + super().__init__(interpolation=interpolation, fill=fill) + if not isinstance(num_ops, int) or (num_ops < 0): + raise ValueError(f"num_ops should be a non-negative integer, but got {num_ops} instead.") + self.num_ops = num_ops + self.magnitude = magnitude + self.num_magnitude_bins = num_magnitude_bins + + def forward(self, *inputs: Any) -> Any: + flat_inputs_with_spec, image_or_video = self._flatten_and_extract_image_or_video(inputs) + height, width = get_size(image_or_video) # type: ignore[arg-type] + + for _ in range(self.num_ops): + transform_id, (magnitudes_fn, signed) = self._get_random_item(self._AUGMENTATION_SPACE) + magnitudes = magnitudes_fn(self.num_magnitude_bins, height, width) + if magnitudes is not None: + magnitude = float(magnitudes[self.magnitude]) + if signed and torch.rand(()) <= 0.5: + magnitude *= -1 + else: + magnitude = 0.0 + image_or_video = self._apply_image_or_video_transform( + image_or_video, transform_id, magnitude, interpolation=self.interpolation, fill=self._fill + ) + + return self._unflatten_and_insert_image_or_video(flat_inputs_with_spec, image_or_video) + + +class TrivialAugmentWide(_AutoAugmentBase): + r"""Dataset-independent data-augmentation with TrivialAugment Wide, as described in + `"TrivialAugment: Tuning-free Yet State-of-the-Art Data Augmentation" `_. + + This transformation works on images and videos only. + + If the input is :class:`torch.Tensor`, it should be of type ``torch.uint8``, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + num_magnitude_bins (int, optional): The number of different magnitude values. + interpolation (str or InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.v2.InterpolationMode`. + Accepted string values are ``"nearest"``, ``"nearest-exact"``, ``"bilinear"``, ``"bicubic"``, + ``"box"``, ``"hamming"``, and ``"lanczos"``. + ``"box"``, ``"hamming"``, and ``"lanczos"`` are only supported for PIL images. + The corresponding ``InterpolationMode`` enum values and Pillow integer + constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + _v1_transform_cls = _transforms.TrivialAugmentWide + _AUGMENTATION_SPACE = { + "Identity": (lambda num_bins, height, width: None, False), + "ShearX": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True), + "ShearY": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True), + "TranslateX": (lambda num_bins, height, width: torch.linspace(0.0, 32.0, num_bins), True), + "TranslateY": (lambda num_bins, height, width: torch.linspace(0.0, 32.0, num_bins), True), + "Rotate": (lambda num_bins, height, width: torch.linspace(0.0, 135.0, num_bins), True), + "Brightness": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True), + "Color": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True), + "Contrast": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True), + "Sharpness": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True), + "Posterize": ( + lambda num_bins, height, width: (8 - (torch.arange(num_bins) / ((num_bins - 1) / 6))).round().int(), + False, + ), + "Solarize": (lambda num_bins, height, width: torch.linspace(1.0, 0.0, num_bins), False), + "AutoContrast": (lambda num_bins, height, width: None, False), + "Equalize": (lambda num_bins, height, width: None, False), + } + + def __init__( + self, + num_magnitude_bins: int = 31, + interpolation: Union[str, InterpolationMode, int] = "nearest", + fill: Union[_FillType, dict[Union[type, str], _FillType]] = None, + ): + super().__init__(interpolation=interpolation, fill=fill) + self.num_magnitude_bins = num_magnitude_bins + + def forward(self, *inputs: Any) -> Any: + flat_inputs_with_spec, image_or_video = self._flatten_and_extract_image_or_video(inputs) + height, width = get_size(image_or_video) # type: ignore[arg-type] + + transform_id, (magnitudes_fn, signed) = self._get_random_item(self._AUGMENTATION_SPACE) + + magnitudes = magnitudes_fn(self.num_magnitude_bins, height, width) + if magnitudes is not None: + magnitude = float(magnitudes[int(torch.randint(self.num_magnitude_bins, ()))]) + if signed and torch.rand(()) <= 0.5: + magnitude *= -1 + else: + magnitude = 0.0 + + image_or_video = self._apply_image_or_video_transform( + image_or_video, transform_id, magnitude, interpolation=self.interpolation, fill=self._fill + ) + return self._unflatten_and_insert_image_or_video(flat_inputs_with_spec, image_or_video) + + +class AugMix(_AutoAugmentBase): + r"""AugMix data augmentation method based on + `"AugMix: A Simple Data Processing Method to Improve Robustness and Uncertainty" `_. + + This transformation works on images and videos only. + + If the input is :class:`torch.Tensor`, it should be of type ``torch.uint8``, and it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + severity (int, optional): The severity of base augmentation operators. Default is ``3``. + mixture_width (int, optional): The number of augmentation chains. Default is ``3``. + chain_depth (int, optional): The depth of augmentation chains. A negative value denotes stochastic depth sampled from the interval [1, 3]. + Default is ``-1``. + alpha (float, optional): The hyperparameter for the probability distributions. Default is ``1.0``. + all_ops (bool, optional): Use all operations (including brightness, contrast, color and sharpness). Default is ``True``. + interpolation (str or InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.v2.InterpolationMode`. + Accepted string values are ``"nearest"``, ``"nearest-exact"``, ``"bilinear"``, ``"bicubic"``, + ``"box"``, ``"hamming"``, and ``"lanczos"``. + ``"box"``, ``"hamming"``, and ``"lanczos"`` are only supported for PIL images. + The corresponding ``InterpolationMode`` enum values and Pillow integer + constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (sequence or number, optional): Pixel fill value for the area outside the transformed + image. If given a number, the value is used for all bands respectively. + """ + + _v1_transform_cls = _transforms.AugMix + + _PARTIAL_AUGMENTATION_SPACE = { + "ShearX": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True), + "ShearY": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True), + "TranslateX": (lambda num_bins, height, width: torch.linspace(0.0, width / 3.0, num_bins), True), + "TranslateY": (lambda num_bins, height, width: torch.linspace(0.0, height / 3.0, num_bins), True), + "Rotate": (lambda num_bins, height, width: torch.linspace(0.0, 30.0, num_bins), True), + "Posterize": ( + lambda num_bins, height, width: (4 - (torch.arange(num_bins) / ((num_bins - 1) / 4))).round().int(), + False, + ), + "Solarize": (lambda num_bins, height, width: torch.linspace(1.0, 0.0, num_bins), False), + "AutoContrast": (lambda num_bins, height, width: None, False), + "Equalize": (lambda num_bins, height, width: None, False), + } + _AUGMENTATION_SPACE: dict[str, tuple[Callable[[int, int, int], Optional[torch.Tensor]], bool]] = { + **_PARTIAL_AUGMENTATION_SPACE, + "Brightness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Color": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Contrast": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + "Sharpness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True), + } + + def __init__( + self, + severity: int = 3, + mixture_width: int = 3, + chain_depth: int = -1, + alpha: float = 1.0, + all_ops: bool = True, + interpolation: Union[str, InterpolationMode, int] = "bilinear", + fill: Union[_FillType, dict[Union[type, str], _FillType]] = None, + ) -> None: + super().__init__(interpolation=interpolation, fill=fill) + self._PARAMETER_MAX = 10 + if not (1 <= severity <= self._PARAMETER_MAX): + raise ValueError(f"The severity must be between [1, {self._PARAMETER_MAX}]. Got {severity} instead.") + self.severity = severity + self.mixture_width = mixture_width + self.chain_depth = chain_depth + self.alpha = alpha + self.all_ops = all_ops + + def _sample_dirichlet(self, params: torch.Tensor) -> torch.Tensor: + # Must be on a separate method so that we can overwrite it in tests. + return torch._sample_dirichlet(params) + + def forward(self, *inputs: Any) -> Any: + flat_inputs_with_spec, orig_image_or_video = self._flatten_and_extract_image_or_video(inputs) + height, width = get_size(orig_image_or_video) # type: ignore[arg-type] + + if isinstance(orig_image_or_video, torch.Tensor): + image_or_video = orig_image_or_video + else: # isinstance(inpt, PIL.Image.Image): + image_or_video = F.pil_to_tensor(orig_image_or_video) + + augmentation_space = self._AUGMENTATION_SPACE if self.all_ops else self._PARTIAL_AUGMENTATION_SPACE + + orig_dims = list(image_or_video.shape) + expected_ndim = 5 if isinstance(orig_image_or_video, tv_tensors.Video) else 4 + batch = image_or_video.reshape([1] * max(expected_ndim - image_or_video.ndim, 0) + orig_dims) + batch_dims = [batch.size(0)] + [1] * (batch.ndim - 1) + + # Sample the beta weights for combining the original and augmented image or video. To get Beta, we use a + # Dirichlet with 2 parameters. The 1st column stores the weights of the original and the 2nd the ones of + # augmented image or video. + m = self._sample_dirichlet( + torch.tensor([self.alpha, self.alpha], device=batch.device).expand(batch_dims[0], -1) + ) + + # Sample the mixing weights and combine them with the ones sampled from Beta for the augmented images or videos. + combined_weights = self._sample_dirichlet( + torch.tensor([self.alpha] * self.mixture_width, device=batch.device).expand(batch_dims[0], -1) + ) * m[:, 1].reshape([batch_dims[0], -1]) + + mix = m[:, 0].reshape(batch_dims) * batch + for i in range(self.mixture_width): + aug = batch + depth = self.chain_depth if self.chain_depth > 0 else int(torch.randint(low=1, high=4, size=(1,)).item()) + for _ in range(depth): + transform_id, (magnitudes_fn, signed) = self._get_random_item(augmentation_space) + + magnitudes = magnitudes_fn(self._PARAMETER_MAX, height, width) + if magnitudes is not None: + magnitude = float(magnitudes[int(torch.randint(self.severity, ()))]) + if signed and torch.rand(()) <= 0.5: + magnitude *= -1 + else: + magnitude = 0.0 + + aug = self._apply_image_or_video_transform(aug, transform_id, magnitude, interpolation=self.interpolation, fill=self._fill) # type: ignore[assignment] + mix.add_(combined_weights[:, i].reshape(batch_dims) * aug) + mix = mix.reshape(orig_dims).to(dtype=image_or_video.dtype) + + if isinstance(orig_image_or_video, (tv_tensors.Image, tv_tensors.Video)): + mix = tv_tensors.wrap(mix, like=orig_image_or_video) + elif isinstance(orig_image_or_video, PIL.Image.Image): + mix = F.to_pil_image(mix) + + return self._unflatten_and_insert_image_or_video(flat_inputs_with_spec, mix) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_color.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_color.py new file mode 100644 index 0000000000000000000000000000000000000000..e249dbc0b1fbda68624ebbcec48dd6a769d9e4ed --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_color.py @@ -0,0 +1,377 @@ +import collections.abc +from collections.abc import Sequence +from typing import Any, Optional, Union + +import torch +from torchvision import transforms as _transforms +from torchvision.transforms.v2 import functional as F, Transform + +from ._transform import _RandomApplyTransform +from ._utils import query_chw + + +class Grayscale(Transform): + """Convert images or videos to grayscale. + + If the input is a :class:`torch.Tensor`, it is expected + to have [..., 3 or 1, H, W] shape, where ... means an arbitrary number of leading dimensions + + Args: + num_output_channels (int): (1 or 3) number of channels desired for output image + """ + + _v1_transform_cls = _transforms.Grayscale + + def __init__(self, num_output_channels: int = 1): + super().__init__() + self.num_output_channels = num_output_channels + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.rgb_to_grayscale, inpt, num_output_channels=self.num_output_channels) + + +class RandomGrayscale(_RandomApplyTransform): + """Randomly convert image or videos to grayscale with a probability of p (default 0.1). + + If the input is a :class:`torch.Tensor`, it is expected to have [..., 3 or 1, H, W] shape, + where ... means an arbitrary number of leading dimensions + + The output has the same number of channels as the input. + + Args: + p (float): probability that image should be converted to grayscale. + """ + + _v1_transform_cls = _transforms.RandomGrayscale + + def __init__(self, p: float = 0.1) -> None: + super().__init__(p=p) + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + num_input_channels, *_ = query_chw(flat_inputs) + return dict(num_input_channels=num_input_channels) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.rgb_to_grayscale, inpt, num_output_channels=params["num_input_channels"]) + + +class RGB(Transform): + """Convert images or videos to RGB (if they are already not RGB). + + If the input is a :class:`torch.Tensor`, it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions + """ + + def __init__(self): + super().__init__() + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.grayscale_to_rgb, inpt) + + +class ColorJitter(Transform): + """Randomly change the brightness, contrast, saturation and hue of an image or video. + + If the input is a :class:`torch.Tensor`, it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, mode "1", "I", "F" and modes with transparency (alpha channel) are not supported. + + Args: + brightness (float or tuple of float (min, max)): How much to jitter brightness. + brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness] + or the given [min, max]. Should be non negative numbers. + contrast (float or tuple of float (min, max)): How much to jitter contrast. + contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast] + or the given [min, max]. Should be non-negative numbers. + saturation (float or tuple of float (min, max)): How much to jitter saturation. + saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation] + or the given [min, max]. Should be non negative numbers. + hue (float or tuple of float (min, max)): How much to jitter hue. + hue_factor is chosen uniformly from [-hue, hue] or the given [min, max]. + Should have 0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5. + To jitter hue, the pixel values of the input image has to be non-negative for conversion to HSV space; + thus it does not work if you normalize your image to an interval with negative values, + or use an interpolation that generates negative values before using this function. + """ + + _v1_transform_cls = _transforms.ColorJitter + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + return {attr: value or 0 for attr, value in super()._extract_params_for_v1_transform().items()} + + def __init__( + self, + brightness: Optional[Union[float, Sequence[float]]] = None, + contrast: Optional[Union[float, Sequence[float]]] = None, + saturation: Optional[Union[float, Sequence[float]]] = None, + hue: Optional[Union[float, Sequence[float]]] = None, + ) -> None: + super().__init__() + self.brightness = self._check_input(brightness, "brightness") + self.contrast = self._check_input(contrast, "contrast") + self.saturation = self._check_input(saturation, "saturation") + self.hue = self._check_input(hue, "hue", center=0, bound=(-0.5, 0.5), clip_first_on_zero=False) + + def _check_input( + self, + value: Optional[Union[float, Sequence[float]]], + name: str, + center: float = 1.0, + bound: tuple[float, float] = (0, float("inf")), + clip_first_on_zero: bool = True, + ) -> Optional[tuple[float, float]]: + if value is None: + return None + + if isinstance(value, (int, float)): + if value < 0: + raise ValueError(f"If {name} is a single number, it must be non negative.") + value = [center - value, center + value] + if clip_first_on_zero: + value[0] = max(value[0], 0.0) + elif isinstance(value, collections.abc.Sequence) and len(value) == 2: + value = [float(v) for v in value] + else: + raise TypeError(f"{name}={value} should be a single number or a sequence with length 2.") + + if not bound[0] <= value[0] <= value[1] <= bound[1]: + raise ValueError(f"{name} values should be between {bound} and increasing, but got {value}.") + + return None if value[0] == value[1] == center else (float(value[0]), float(value[1])) + + @staticmethod + def _generate_value(left: float, right: float) -> float: + return float(torch.empty(1).uniform_(left, right).item()) + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + fn_idx = torch.randperm(4) + + b = None if self.brightness is None else self._generate_value(self.brightness[0], self.brightness[1]) + c = None if self.contrast is None else self._generate_value(self.contrast[0], self.contrast[1]) + s = None if self.saturation is None else self._generate_value(self.saturation[0], self.saturation[1]) + h = None if self.hue is None else self._generate_value(self.hue[0], self.hue[1]) + + return dict(fn_idx=fn_idx, brightness_factor=b, contrast_factor=c, saturation_factor=s, hue_factor=h) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + output = inpt + brightness_factor = params["brightness_factor"] + contrast_factor = params["contrast_factor"] + saturation_factor = params["saturation_factor"] + hue_factor = params["hue_factor"] + for fn_id in params["fn_idx"]: + if fn_id == 0 and brightness_factor is not None: + output = self._call_kernel(F.adjust_brightness, output, brightness_factor=brightness_factor) + elif fn_id == 1 and contrast_factor is not None: + output = self._call_kernel(F.adjust_contrast, output, contrast_factor=contrast_factor) + elif fn_id == 2 and saturation_factor is not None: + output = self._call_kernel(F.adjust_saturation, output, saturation_factor=saturation_factor) + elif fn_id == 3 and hue_factor is not None: + output = self._call_kernel(F.adjust_hue, output, hue_factor=hue_factor) + return output + + +class RandomChannelPermutation(Transform): + """Randomly permute the channels of an image or video""" + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + num_channels, *_ = query_chw(flat_inputs) + return dict(permutation=torch.randperm(num_channels)) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.permute_channels, inpt, params["permutation"]) + + +class RandomPhotometricDistort(Transform): + """Randomly distorts the image or video as used in `SSD: Single Shot + MultiBox Detector `_. + + This transform relies on :class:`~torchvision.transforms.v2.ColorJitter` + under the hood to adjust the contrast, saturation, hue, brightness, and also + randomly permutes channels. + + Args: + brightness (tuple of float (min, max), optional): How much to jitter brightness. + brightness_factor is chosen uniformly from [min, max]. Should be non negative numbers. + contrast (tuple of float (min, max), optional): How much to jitter contrast. + contrast_factor is chosen uniformly from [min, max]. Should be non-negative numbers. + saturation (tuple of float (min, max), optional): How much to jitter saturation. + saturation_factor is chosen uniformly from [min, max]. Should be non negative numbers. + hue (tuple of float (min, max), optional): How much to jitter hue. + hue_factor is chosen uniformly from [min, max]. Should have -0.5 <= min <= max <= 0.5. + To jitter hue, the pixel values of the input image has to be non-negative for conversion to HSV space; + thus it does not work if you normalize your image to an interval with negative values, + or use an interpolation that generates negative values before using this function. + p (float, optional) probability each distortion operation (contrast, saturation, ...) to be applied. + Default is 0.5. + """ + + def __init__( + self, + brightness: tuple[float, float] = (0.875, 1.125), + contrast: tuple[float, float] = (0.5, 1.5), + saturation: tuple[float, float] = (0.5, 1.5), + hue: tuple[float, float] = (-0.05, 0.05), + p: float = 0.5, + ): + super().__init__() + self.brightness = brightness + self.contrast = contrast + self.hue = hue + self.saturation = saturation + self.p = p + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + num_channels, *_ = query_chw(flat_inputs) + params: dict[str, Any] = { + key: ColorJitter._generate_value(range[0], range[1]) if torch.rand(1) < self.p else None + for key, range in [ + ("brightness_factor", self.brightness), + ("contrast_factor", self.contrast), + ("saturation_factor", self.saturation), + ("hue_factor", self.hue), + ] + } + params["contrast_before"] = bool(torch.rand(()) < 0.5) + params["channel_permutation"] = torch.randperm(num_channels) if torch.rand(1) < self.p else None + return params + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + if params["brightness_factor"] is not None: + inpt = self._call_kernel(F.adjust_brightness, inpt, brightness_factor=params["brightness_factor"]) + if params["contrast_factor"] is not None and params["contrast_before"]: + inpt = self._call_kernel(F.adjust_contrast, inpt, contrast_factor=params["contrast_factor"]) + if params["saturation_factor"] is not None: + inpt = self._call_kernel(F.adjust_saturation, inpt, saturation_factor=params["saturation_factor"]) + if params["hue_factor"] is not None: + inpt = self._call_kernel(F.adjust_hue, inpt, hue_factor=params["hue_factor"]) + if params["contrast_factor"] is not None and not params["contrast_before"]: + inpt = self._call_kernel(F.adjust_contrast, inpt, contrast_factor=params["contrast_factor"]) + if params["channel_permutation"] is not None: + inpt = self._call_kernel(F.permute_channels, inpt, permutation=params["channel_permutation"]) + return inpt + + +class RandomEqualize(_RandomApplyTransform): + """Equalize the histogram of the given image or video with a given probability. + + If the input is a :class:`torch.Tensor`, it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "P", "L" or "RGB". + + Args: + p (float): probability of the image being equalized. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomEqualize + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.equalize, inpt) + + +class RandomInvert(_RandomApplyTransform): + """Inverts the colors of the given image or video with a given probability. + + If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + p (float): probability of the image being color inverted. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomInvert + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.invert, inpt) + + +class RandomPosterize(_RandomApplyTransform): + """Posterize the image or video with a given probability by reducing the + number of bits for each color channel. + + If the input is a :class:`torch.Tensor`, it should be of type torch.uint8, + and it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + bits (int): number of bits to keep for each channel (0-8) + p (float): probability of the image being posterized. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomPosterize + + def __init__(self, bits: int, p: float = 0.5) -> None: + super().__init__(p=p) + self.bits = bits + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.posterize, inpt, bits=self.bits) + + +class RandomSolarize(_RandomApplyTransform): + """Solarize the image or video with a given probability by inverting all pixel + values above a threshold. + + If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + threshold (float): all pixels equal or above this value are inverted. + p (float): probability of the image being solarized. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomSolarize + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + params = super()._extract_params_for_v1_transform() + params["threshold"] = float(params["threshold"]) + return params + + def __init__(self, threshold: float, p: float = 0.5) -> None: + super().__init__(p=p) + self.threshold = threshold + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.solarize, inpt, threshold=self.threshold) + + +class RandomAutocontrast(_RandomApplyTransform): + """Autocontrast the pixels of the given image or video with a given probability. + + If the input is a :class:`torch.Tensor`, it is expected + to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + If img is PIL Image, it is expected to be in mode "L" or "RGB". + + Args: + p (float): probability of the image being autocontrasted. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomAutocontrast + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.autocontrast, inpt) + + +class RandomAdjustSharpness(_RandomApplyTransform): + """Adjust the sharpness of the image or video with a given probability. + + If the input is a :class:`torch.Tensor`, + it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + sharpness_factor (float): How much to adjust the sharpness. Can be + any non-negative number. 0 gives a blurred image, 1 gives the + original image while 2 increases the sharpness by a factor of 2. + p (float): probability of the image being sharpened. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomAdjustSharpness + + def __init__(self, sharpness_factor: float, p: float = 0.5) -> None: + super().__init__(p=p) + self.sharpness_factor = sharpness_factor + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.adjust_sharpness, inpt, sharpness_factor=self.sharpness_factor) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_container.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_container.py new file mode 100644 index 0000000000000000000000000000000000000000..95ec25a22f84501ac6ca7520f70db63b5a0f5084 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_container.py @@ -0,0 +1,180 @@ +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +import torch + +from torch import nn +from torchvision import transforms as _transforms +from torchvision.transforms.v2 import Transform + + +class Compose(Transform): + """Composes several transforms together. + + This transform does not support torchscript. + Please, see the note below. + + Args: + transforms (list of ``Transform`` objects): list of transforms to compose. + + Example: + >>> transforms.Compose([ + >>> transforms.CenterCrop(10), + >>> transforms.PILToTensor(), + >>> transforms.ConvertImageDtype(torch.float), + >>> ]) + + .. note:: + In order to script the transformations, please use ``torch.nn.Sequential`` as below. + + >>> transforms = torch.nn.Sequential( + >>> transforms.CenterCrop(10), + >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)), + >>> ) + >>> scripted_transforms = torch.jit.script(transforms) + + Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require + `lambda` functions or ``PIL.Image``. + + """ + + def __init__(self, transforms: Sequence[Callable]) -> None: + super().__init__() + if not isinstance(transforms, Sequence): + raise TypeError("Argument transforms should be a sequence of callables") + elif not transforms: + raise ValueError("Pass at least one transform") + self.transforms = transforms + + def forward(self, *inputs: Any) -> Any: + needs_unpacking = len(inputs) > 1 + for transform in self.transforms: + outputs = transform(*inputs) + inputs = outputs if needs_unpacking else (outputs,) + return outputs + + def extra_repr(self) -> str: + format_string = [] + for t in self.transforms: + format_string.append(f" {t}") + return "\n".join(format_string) + + +class RandomApply(Transform): + """Apply randomly a list of transformations with a given probability. + + .. note:: + In order to script the transformation, please use ``torch.nn.ModuleList`` as input instead of list/tuple of + transforms as shown below: + + >>> transforms = transforms.RandomApply(torch.nn.ModuleList([ + >>> transforms.ColorJitter(), + >>> ]), p=0.3) + >>> scripted_transforms = torch.jit.script(transforms) + + Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require + `lambda` functions or ``PIL.Image``. + + Args: + transforms (sequence or torch.nn.Module): list of transformations + p (float): probability of applying the list of transforms + """ + + _v1_transform_cls = _transforms.RandomApply + + def __init__(self, transforms: Union[Sequence[Callable], nn.ModuleList], p: float = 0.5) -> None: + super().__init__() + + if not isinstance(transforms, (Sequence, nn.ModuleList)): + raise TypeError("Argument transforms should be a sequence of callables or a `nn.ModuleList`") + elif not transforms: + raise ValueError("Pass at least one transform") + self.transforms = transforms + + if not (0.0 <= p <= 1.0): + raise ValueError("`p` should be a floating point value in the interval [0.0, 1.0].") + self.p = p + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + return {"transforms": self.transforms, "p": self.p} + + def forward(self, *inputs: Any) -> Any: + needs_unpacking = len(inputs) > 1 + + if torch.rand(1) >= self.p: + return inputs if needs_unpacking else inputs[0] + + for transform in self.transforms: + outputs = transform(*inputs) + inputs = outputs if needs_unpacking else (outputs,) + return outputs + + def extra_repr(self) -> str: + format_string = [] + for t in self.transforms: + format_string.append(f" {t}") + return "\n".join(format_string) + + +class RandomChoice(Transform): + """Apply single transformation randomly picked from a list. + + This transform does not support torchscript. + + Args: + transforms (sequence or torch.nn.Module): list of transformations + p (list of floats or None, optional): probability of each transform being picked. + If ``p`` doesn't sum to 1, it is automatically normalized. If ``None`` + (default), all transforms have the same probability. + """ + + def __init__( + self, + transforms: Sequence[Callable], + p: Optional[list[float]] = None, + ) -> None: + if not isinstance(transforms, Sequence): + raise TypeError("Argument transforms should be a sequence of callables") + elif not transforms: + raise ValueError("Pass at least one transform") + if p is None: + p = [1] * len(transforms) + elif len(p) != len(transforms): + raise ValueError(f"Length of p doesn't match the number of transforms: {len(p)} != {len(transforms)}") + + super().__init__() + + self.transforms = transforms + total = sum(p) + self.p = [prob / total for prob in p] + + def forward(self, *inputs: Any) -> Any: + idx = int(torch.multinomial(torch.tensor(self.p), 1)) + transform = self.transforms[idx] + return transform(*inputs) + + +class RandomOrder(Transform): + """Apply a list of transformations in a random order. + + This transform does not support torchscript. + + Args: + transforms (sequence or torch.nn.Module): list of transformations + """ + + def __init__(self, transforms: Sequence[Callable]) -> None: + if not isinstance(transforms, Sequence): + raise TypeError("Argument transforms should be a sequence of callables") + elif not transforms: + raise ValueError("Pass at least one transform") + super().__init__() + self.transforms = transforms + + def forward(self, *inputs: Any) -> Any: + needs_unpacking = len(inputs) > 1 + for idx in torch.randperm(len(self.transforms)): + transform = self.transforms[idx] + outputs = transform(*inputs) + inputs = outputs if needs_unpacking else (outputs,) + return outputs diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_deprecated.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..4e7d6170d4f4c48678027e75cbb246cf250b587a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_deprecated.py @@ -0,0 +1,50 @@ +import warnings +from typing import Any, Union + +import numpy as np +import PIL.Image +import torch +from torchvision.transforms import functional as _F + +from torchvision.transforms.v2 import Transform + + +class ToTensor(Transform): + """[DEPRECATED] Use ``v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])`` instead. + + Convert a PIL Image or ndarray to tensor and scale the values accordingly. + + .. warning:: + :class:`v2.ToTensor` is deprecated and will be removed in a future release. + Please use instead ``v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])``. + Output is equivalent up to float precision. + + This transform does not support torchscript. + + + Converts a PIL Image or numpy.ndarray (H x W x C) in the range + [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] + if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1) + or if the numpy.ndarray has dtype = np.uint8 + + In the other cases, tensors are returned without scaling. + + .. note:: + Because the input image is scaled to [0.0, 1.0], this transformation should not be used when + transforming target image masks. See the `references`_ for implementing the transforms for image masks. + + .. _references: https://github.com/pytorch/vision/tree/main/references/segmentation + """ + + _transformed_types = (PIL.Image.Image, np.ndarray) + + def __init__(self) -> None: + warnings.warn( + "The transform `ToTensor()` is deprecated and will be removed in a future release. " + "Instead, please use `v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])`." + "Output is equivalent up to float precision." + ) + super().__init__() + + def transform(self, inpt: Union[PIL.Image.Image, np.ndarray], params: dict[str, Any]) -> torch.Tensor: + return _F.to_tensor(inpt) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_geometry.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..278b58eae2f1466e4c3933f4fdd3b6f20af86126 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_geometry.py @@ -0,0 +1,1463 @@ +import math +import numbers +import warnings +from collections.abc import Sequence +from typing import Any, Callable, Literal, Optional, Union + +import PIL.Image +import torch + +from torchvision import transforms as _transforms, tv_tensors +from torchvision.ops.boxes import box_iou +from torchvision.transforms.functional import _get_perspective_coeffs +from torchvision.transforms.v2 import functional as F, InterpolationMode, Transform +from torchvision.transforms.v2.functional._utils import _FillType + +from ._transform import _RandomApplyTransform +from ._utils import ( + _check_padding_arg, + _check_padding_mode_arg, + _check_sequence_input, + _get_fill, + _setup_angle, + _setup_fill_arg, + _setup_number_or_seq, + _setup_size, + get_bounding_boxes, + has_all, + has_any, + is_pure_tensor, + query_size, +) + + +class RandomHorizontalFlip(_RandomApplyTransform): + """Horizontally flip the input with a given probability. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + p (float, optional): probability of the input being flipped. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomHorizontalFlip + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.horizontal_flip, inpt) + + +class RandomVerticalFlip(_RandomApplyTransform): + """Vertically flip the input with a given probability. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + p (float, optional): probability of the input being flipped. Default value is 0.5 + """ + + _v1_transform_cls = _transforms.RandomVerticalFlip + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.vertical_flip, inpt) + + +class Resize(Transform): + """Resize the input to the given size. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + size (sequence, int, or None): Desired + output size. + + - If size is a sequence like (h, w), output size will be matched to this. + - If size is an int, smaller edge of the image will be matched to this + number. i.e, if height > width, then image will be rescaled to + (size * height / width, size). + - If size is None, the output shape is determined by the ``max_size`` + parameter. + + .. note:: + In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``. + interpolation (str or InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.v2.InterpolationMode`. + Accepted string values are ``"nearest"``, ``"nearest-exact"``, ``"bilinear"``, ``"bicubic"``, + ``"box"``, ``"hamming"``, and ``"lanczos"``. + ``"box"`` and ``"hamming"`` are only supported for PIL images. + ``"lanczos"`` is only supported on CPU and requires ``antialias=True``. + Default is ``"bilinear"``. + The corresponding ``InterpolationMode`` enum values and Pillow integer + constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + max_size (int, optional): The maximum allowed for the longer edge of + the resized image. + + - If ``size`` is an int: if the longer edge of the image is greater + than ``max_size`` after being resized according to ``size``, + ``size`` will be overruled so that the longer edge is equal to + ``max_size``. As a result, the smaller edge may be shorter than + ``size``. This is only supported if ``size`` is an int (or a + sequence of length 1 in torchscript mode). + - If ``size`` is None: the longer edge of the image will be matched + to max_size. i.e, if height > width, then image will be rescaled + to (max_size, max_size * width / height). + + This should be left to ``None`` (default) when ``size`` is a + sequence. + + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear, bicubic, or lanczos modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear, bicubic, or lanczos modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + """ + + _v1_transform_cls = _transforms.Resize + + def __init__( + self, + size: Union[int, Sequence[int], None], + interpolation: Union[str, InterpolationMode, int] = "bilinear", + max_size: Optional[int] = None, + antialias: Optional[bool] = True, + ) -> None: + super().__init__() + + if isinstance(size, int): + size = [size] + elif isinstance(size, Sequence) and len(size) in {1, 2}: + size = list(size) + elif size is None: + if not isinstance(max_size, int): + raise ValueError(f"max_size must be an integer when size is None, but got {max_size} instead.") + else: + raise ValueError( + f"size can be an integer, a sequence of one or two integers, or None, but got {size} instead." + ) + self.size = size + + self.interpolation = interpolation + self.max_size = max_size + self.antialias = antialias + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel( + F.resize, + inpt, + self.size, + interpolation=self.interpolation, + max_size=self.max_size, + antialias=self.antialias, + ) + + +class CenterCrop(Transform): + """Crop the input at the center. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + If image size is smaller than output size along any edge, image is padded with 0 and then center cropped. + + Args: + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + """ + + _v1_transform_cls = _transforms.CenterCrop + + def __init__(self, size: Union[int, Sequence[int]]): + super().__init__() + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.center_crop, inpt, output_size=self.size) + + +class RandomResizedCrop(Transform): + """Crop a random portion of the input and resize it to a given size. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + A crop of the original input is made: the crop has a random area (H * W) + and a random aspect ratio. This crop is finally resized to the given + size. This is popularly used to train the Inception networks. + + Args: + size (int or sequence): expected output size of the crop, for each edge. If size is an + int instead of sequence like (h, w), a square output size ``(size, size)`` is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + + .. note:: + In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``. + scale (tuple of float, optional): Specifies the lower and upper bounds for the random area of the crop, + before resizing. The scale is defined with respect to the area of the original image. + ratio (tuple of float, optional): lower and upper bounds for the random aspect ratio of the crop, before + resizing. + interpolation (str or InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.v2.InterpolationMode`. + Accepted string values are ``"nearest"``, ``"nearest-exact"``, ``"bilinear"``, ``"bicubic"``, + ``"box"``, ``"hamming"``, and ``"lanczos"``. + ``"box"`` and ``"hamming"`` are only supported for PIL images. + ``"lanczos"`` is only supported on CPU and requires ``antialias=True``. + Default is ``"bilinear"``. + The corresponding ``InterpolationMode`` enum values and Pillow integer + constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear, bicubic, or lanczos modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear, bicubic, or lanczos modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + """ + + _v1_transform_cls = _transforms.RandomResizedCrop + + def __init__( + self, + size: Union[int, Sequence[int]], + scale: tuple[float, float] = (0.08, 1.0), + ratio: tuple[float, float] = (3.0 / 4.0, 4.0 / 3.0), + interpolation: Union[str, InterpolationMode, int] = "bilinear", + antialias: Optional[bool] = True, + ) -> None: + super().__init__() + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + + if not isinstance(scale, Sequence) or len(scale) != 2: + raise TypeError("Scale should be a sequence of two floats.") + if not isinstance(ratio, Sequence) or len(ratio) != 2: + raise TypeError("Ratio should be a sequence of two floats.") + if (scale[0] > scale[1]) or (ratio[0] > ratio[1]): + warnings.warn("Scale and ratio should be of kind (min, max)") + + self.scale = scale + self.ratio = ratio + self.interpolation = interpolation + self.antialias = antialias + + self._log_ratio = torch.log(torch.tensor(self.ratio)) + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + height, width = query_size(flat_inputs) + area = height * width + + log_ratio = self._log_ratio + for _ in range(10): + target_area = area * torch.empty(1).uniform_(self.scale[0], self.scale[1]).item() + aspect_ratio = torch.exp( + torch.empty(1).uniform_( + log_ratio[0], # type: ignore[arg-type] + log_ratio[1], # type: ignore[arg-type] + ) + ).item() + + w = int(round(math.sqrt(target_area * aspect_ratio))) + h = int(round(math.sqrt(target_area / aspect_ratio))) + + if 0 < w <= width and 0 < h <= height: + i = torch.randint(0, height - h + 1, size=(1,)).item() + j = torch.randint(0, width - w + 1, size=(1,)).item() + break + else: + # Fallback to central crop + in_ratio = float(width) / float(height) + if in_ratio < min(self.ratio): + w = width + h = int(round(w / min(self.ratio))) + elif in_ratio > max(self.ratio): + h = height + w = int(round(h * max(self.ratio))) + else: # whole image + w = width + h = height + i = (height - h) // 2 + j = (width - w) // 2 + + return dict(top=i, left=j, height=h, width=w) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel( + F.resized_crop, inpt, **params, size=self.size, interpolation=self.interpolation, antialias=self.antialias + ) + + +class FiveCrop(Transform): + """Crop the image or video into four corners and the central crop. + + If the input is a :class:`torch.Tensor` or a :class:`~torchvision.tv_tensors.Image` or a + :class:`~torchvision.tv_tensors.Video` it can have arbitrary number of leading batch dimensions. + For example, the image can have ``[..., C, H, W]`` shape. + + .. Note:: + This transform returns a tuple of images and there may be a mismatch in the number of + inputs and targets your Dataset returns. See below for an example of how to deal with + this. + + Args: + size (sequence or int): Desired output size of the crop. If size is an ``int`` + instead of sequence like (h, w), a square crop of size (size, size) is made. + If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + + Example: + >>> class BatchMultiCrop(transforms.Transform): + ... def forward(self, sample: Tuple[Tuple[Union[tv_tensors.Image, tv_tensors.Video], ...], int]): + ... images_or_videos, labels = sample + ... batch_size = len(images_or_videos) + ... image_or_video = images_or_videos[0] + ... images_or_videos = tv_tensors.wrap(torch.stack(images_or_videos), like=image_or_video) + ... labels = torch.full((batch_size,), label, device=images_or_videos.device) + ... return images_or_videos, labels + ... + >>> image = tv_tensors.Image(torch.rand(3, 256, 256)) + >>> label = 3 + >>> transform = transforms.Compose([transforms.FiveCrop(224), BatchMultiCrop()]) + >>> images, labels = transform(image, label) + >>> images.shape + torch.Size([5, 3, 224, 224]) + >>> labels + tensor([3, 3, 3, 3, 3]) + """ + + _v1_transform_cls = _transforms.FiveCrop + + def __init__(self, size: Union[int, Sequence[int]]) -> None: + super().__init__() + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + + def _call_kernel(self, functional: Callable, inpt: Any, *args: Any, **kwargs: Any) -> Any: + if isinstance(inpt, (tv_tensors.BoundingBoxes, tv_tensors.KeyPoints, tv_tensors.Mask)): + warnings.warn( + f"{type(self).__name__}() is currently passing through inputs of type " + f"tv_tensors.{type(inpt).__name__}. This will likely change in the future." + ) + return super()._call_kernel(functional, inpt, *args, **kwargs) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.five_crop, inpt, self.size) + + def check_inputs(self, flat_inputs: list[Any]) -> None: + if has_any(flat_inputs, tv_tensors.BoundingBoxes, tv_tensors.Mask): + raise TypeError(f"BoundingBoxes'es and Mask's are not supported by {type(self).__name__}()") + + +class TenCrop(Transform): + """Crop the image or video into four corners and the central crop plus the flipped version of + these (horizontal flipping is used by default). + + If the input is a :class:`torch.Tensor` or a :class:`~torchvision.tv_tensors.Image` or a + :class:`~torchvision.tv_tensors.Video` it can have arbitrary number of leading batch dimensions. + For example, the image can have ``[..., C, H, W]`` shape. + + See :class:`~torchvision.transforms.v2.FiveCrop` for an example. + + .. Note:: + This transform returns a tuple of images and there may be a mismatch in the number of + inputs and targets your Dataset returns. See below for an example of how to deal with + this. + + Args: + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + vertical_flip (bool, optional): Use vertical flipping instead of horizontal + """ + + _v1_transform_cls = _transforms.TenCrop + + def __init__(self, size: Union[int, Sequence[int]], vertical_flip: bool = False) -> None: + super().__init__() + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + self.vertical_flip = vertical_flip + + def _call_kernel(self, functional: Callable, inpt: Any, *args: Any, **kwargs: Any) -> Any: + if isinstance(inpt, (tv_tensors.BoundingBoxes, tv_tensors.KeyPoints, tv_tensors.Mask)): + warnings.warn( + f"{type(self).__name__}() is currently passing through inputs of type " + f"tv_tensors.{type(inpt).__name__}. This will likely change in the future." + ) + return super()._call_kernel(functional, inpt, *args, **kwargs) + + def check_inputs(self, flat_inputs: list[Any]) -> None: + if has_any(flat_inputs, tv_tensors.BoundingBoxes, tv_tensors.Mask): + raise TypeError(f"BoundingBoxes'es and Mask's are not supported by {type(self).__name__}()") + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.ten_crop, inpt, self.size, vertical_flip=self.vertical_flip) + + +class Pad(Transform): + """Pad the input on all sides with the given "pad" value. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + padding (int or sequence): Padding on each border. If a single int is provided this + is used to pad all borders. If sequence of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a sequence of length 4 is provided + this is the padding for the left, top, right and bottom borders respectively. + + .. note:: + In torchscript mode padding as single int is not supported, use a sequence of + length 1: ``[padding, ]``. + fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant. + Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. + Fill value can be also a dictionary mapping data type to the fill value, e.g. + ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and + ``Mask`` will be filled with 0. + padding_mode (str, optional): Type of padding. Should be: constant, edge, reflect or symmetric. + Default is "constant". + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value at the edge of the image. + + - reflect: pads with reflection of image without repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + """ + + _v1_transform_cls = _transforms.Pad + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + params = super()._extract_params_for_v1_transform() + + if not (params["fill"] is None or isinstance(params["fill"], (int, float))): + raise ValueError(f"{type(self).__name__}() can only be scripted for a scalar `fill`, but got {self.fill}.") + + return params + + def __init__( + self, + padding: Union[int, Sequence[int]], + fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, + padding_mode: Literal["constant", "edge", "reflect", "symmetric"] = "constant", + ) -> None: + super().__init__() + + _check_padding_arg(padding) + _check_padding_mode_arg(padding_mode) + + # This cast does Sequence[int] -> List[int] and is required to make mypy happy + if not isinstance(padding, int): + padding = list(padding) + self.padding = padding + self.fill = fill + self._fill = _setup_fill_arg(fill) + self.padding_mode = padding_mode + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + fill = _get_fill(self._fill, type(inpt)) + return self._call_kernel(F.pad, inpt, padding=self.padding, fill=fill, padding_mode=self.padding_mode) # type: ignore[arg-type] + + +class RandomZoomOut(_RandomApplyTransform): + """ "Zoom out" transformation from + `"SSD: Single Shot MultiBox Detector" `_. + + This transformation randomly pads images, videos, bounding boxes and masks creating a zoom out effect. + Output spatial size is randomly sampled from original size up to a maximum size configured + with ``side_range`` parameter: + + .. code-block:: python + + r = uniform_sample(side_range[0], side_range[1]) + output_width = input_width * r + output_height = input_height * r + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant. + Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. + Fill value can be also a dictionary mapping data type to the fill value, e.g. + ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and + ``Mask`` will be filled with 0. + side_range (sequence of floats, optional): tuple of two floats defines minimum and maximum factors to + scale the input size. + p (float, optional): probability that the zoom operation will be performed. + """ + + def __init__( + self, + fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, + side_range: Sequence[float] = (1.0, 4.0), + p: float = 0.5, + ) -> None: + super().__init__(p=p) + + self.fill = fill + self._fill = _setup_fill_arg(fill) + + _check_sequence_input(side_range, "side_range", req_sizes=(2,)) + + self.side_range = side_range + if side_range[0] < 1.0 or side_range[0] > side_range[1]: + raise ValueError(f"Invalid side range provided {side_range}.") + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + orig_h, orig_w = query_size(flat_inputs) + + r = self.side_range[0] + torch.rand(1) * (self.side_range[1] - self.side_range[0]) + canvas_width = int(orig_w * r) + canvas_height = int(orig_h * r) + + r = torch.rand(2) + left = int((canvas_width - orig_w) * r[0]) + top = int((canvas_height - orig_h) * r[1]) + right = canvas_width - (left + orig_w) + bottom = canvas_height - (top + orig_h) + padding = [left, top, right, bottom] + + return dict(padding=padding) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + fill = _get_fill(self._fill, type(inpt)) + return self._call_kernel(F.pad, inpt, **params, fill=fill) + + +class RandomRotation(Transform): + """Rotate the input by angle. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + .. note:: + + When ``center=None`` and the angle is a multiple of 90 degrees (0, 90, 180, 270), + the rotation is performed using :func:`torch.rot90` instead of an affine transform. + This is significantly faster, but the output tensor for 90 and 270 degree rotations + may not be contiguous. Users who need contiguous output should call :meth:`~torch.Tensor.contiguous` on the result. + + Args: + degrees (sequence or number): Range of degrees to select from. + If degrees is a number instead of sequence like (min, max), the range of degrees + will be [-degrees, +degrees]. ``[90, 90]`` will rotate the image by 90 degrees anticlockwise. + interpolation (str or InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.v2.InterpolationMode`. + Accepted string values are ``"nearest"``, ``"nearest-exact"``, ``"bilinear"``, ``"bicubic"``, + ``"box"``, ``"hamming"``, and ``"lanczos"``. + ``"box"``, ``"hamming"``, and ``"lanczos"`` are only supported for PIL images. + Default is ``"nearest"``. + The corresponding ``InterpolationMode`` enum values and Pillow integer + constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + expand (bool, optional): Optional expansion flag. + If true, expands the output to make it large enough to hold the entire rotated image. + If false or omitted, make the output image the same size as the input image. + Note that the expand flag assumes rotation around the center (see note below) and no translation. + center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner. + Default is the center of the image. + + .. note:: + + In theory, setting ``center`` has no effect if ``expand=True``, since the image center will become the + center of rotation. In practice however, due to numerical precision, this can lead to off-by-one + differences of the resulting image size compared to using the image center in the first place. Thus, when + setting ``expand=True``, it's best to leave ``center=None`` (default). + fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant. + Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. + Fill value can be also a dictionary mapping data type to the fill value, e.g. + ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and + ``Mask`` will be filled with 0. + + .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters + + """ + + _v1_transform_cls = _transforms.RandomRotation + + def __init__( + self, + degrees: Union[numbers.Number, Sequence], + interpolation: Union[str, InterpolationMode, int] = "nearest", + expand: bool = False, + center: Optional[list[float]] = None, + fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, + ) -> None: + super().__init__() + self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,)) + self.interpolation = interpolation + self.expand = expand + + self.fill = fill + self._fill = _setup_fill_arg(fill) + + if center is not None: + _check_sequence_input(center, "center", req_sizes=(2,)) + + self.center = center + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + angle = torch.empty(1).uniform_(self.degrees[0], self.degrees[1]).item() + return dict(angle=angle) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + fill = _get_fill(self._fill, type(inpt)) + return self._call_kernel( + F.rotate, + inpt, + **params, + interpolation=self.interpolation, + expand=self.expand, + center=self.center, + fill=fill, + ) + + +class RandomAffine(Transform): + """Random affine transformation the input keeping center invariant. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + degrees (sequence or number): Range of degrees to select from. + If degrees is a number instead of sequence like (min, max), the range of degrees + will be (-degrees, +degrees). Set to 0 to deactivate rotations. + translate (tuple, optional): tuple of maximum absolute fraction for horizontal + and vertical translations. For example translate=(a, b), then horizontal shift + is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is + randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default. + scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is + randomly sampled from the range a <= scale <= b. Will keep original scale by default. + shear (sequence or number, optional): Range of degrees to select from. + If shear is a number, a shear parallel to the x-axis in the range (-shear, +shear) + will be applied. Else if shear is a sequence of 2 values a shear parallel to the x-axis in the + range (shear[0], shear[1]) will be applied. Else if shear is a sequence of 4 values, + an x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied. + Will not apply shear by default. + interpolation (str or InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.v2.InterpolationMode`. + Accepted string values are ``"nearest"``, ``"nearest-exact"``, ``"bilinear"``, ``"bicubic"``, + ``"box"``, ``"hamming"``, and ``"lanczos"``. + ``"box"``, ``"hamming"``, and ``"lanczos"`` are only supported for PIL images. + Default is ``"nearest"``. + The corresponding ``InterpolationMode`` enum values and Pillow integer + constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant. + Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. + Fill value can be also a dictionary mapping data type to the fill value, e.g. + ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and + ``Mask`` will be filled with 0. + center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner. + Default is the center of the image. + + .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters + + """ + + _v1_transform_cls = _transforms.RandomAffine + + def __init__( + self, + degrees: Union[numbers.Number, Sequence], + translate: Optional[Sequence[float]] = None, + scale: Optional[Sequence[float]] = None, + shear: Optional[Union[int, float, Sequence[float]]] = None, + interpolation: Union[str, InterpolationMode, int] = "nearest", + fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, + center: Optional[list[float]] = None, + ) -> None: + super().__init__() + self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,)) + if translate is not None: + _check_sequence_input(translate, "translate", req_sizes=(2,)) + for t in translate: + if not (0.0 <= t <= 1.0): + raise ValueError("translation values should be between 0 and 1") + self.translate = translate + if scale is not None: + _check_sequence_input(scale, "scale", req_sizes=(2,)) + for s in scale: + if s <= 0: + raise ValueError("scale values should be positive") + self.scale = scale + + if shear is not None: + self.shear = _setup_angle(shear, name="shear", req_sizes=(2, 4)) + else: + self.shear = shear + + self.interpolation = interpolation + self.fill = fill + self._fill = _setup_fill_arg(fill) + + if center is not None: + _check_sequence_input(center, "center", req_sizes=(2,)) + + self.center = center + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + height, width = query_size(flat_inputs) + + angle = torch.empty(1).uniform_(self.degrees[0], self.degrees[1]).item() + if self.translate is not None: + max_dx = float(self.translate[0] * width) + max_dy = float(self.translate[1] * height) + tx = int(round(float(torch.empty(1).uniform_(-max_dx, max_dx).item()))) + ty = int(round(float(torch.empty(1).uniform_(-max_dy, max_dy).item()))) + + translate = (tx, ty) + else: + translate = (0, 0) + + if self.scale is not None: + scale = torch.empty(1).uniform_(self.scale[0], self.scale[1]).item() + else: + scale = 1.0 + + shear_x = shear_y = 0.0 + if self.shear is not None: + shear_x = float(torch.empty(1).uniform_(self.shear[0], self.shear[1]).item()) + if len(self.shear) == 4: + shear_y = float(torch.empty(1).uniform_(self.shear[2], self.shear[3]).item()) + + shear = (shear_x, shear_y) + return dict(angle=angle, translate=translate, scale=scale, shear=shear) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + fill = _get_fill(self._fill, type(inpt)) + return self._call_kernel( + F.affine, + inpt, + **params, + interpolation=self.interpolation, + fill=fill, + center=self.center, + ) + + +class RandomCrop(Transform): + """Crop the input at a random location. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + size (sequence or int): Desired output size of the crop. If size is an + int instead of sequence like (h, w), a square crop (size, size) is + made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). + padding (int or sequence, optional): Optional padding on each border + of the image, applied before cropping. Default is None. If a single int is provided this + is used to pad all borders. If sequence of length 2 is provided this is the padding + on left/right and top/bottom respectively. If a sequence of length 4 is provided + this is the padding for the left, top, right and bottom borders respectively. + + .. note:: + In torchscript mode padding as single int is not supported, use a sequence of + length 1: ``[padding, ]``. + pad_if_needed (boolean, optional): It will pad the image if smaller than the + desired size to avoid raising an exception. Since cropping is done + after padding, the padding seems to be done at a random offset. + fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant. + Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. + Fill value can be also a dictionary mapping data type to the fill value, e.g. + ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and + ``Mask`` will be filled with 0. + padding_mode (str, optional): Type of padding. Should be: constant, edge, reflect or symmetric. + Default is constant. + + - constant: pads with a constant value, this value is specified with fill + + - edge: pads with the last value at the edge of the image. + + - reflect: pads with reflection of image without repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode + will result in [3, 2, 1, 2, 3, 4, 3, 2] + + - symmetric: pads with reflection of image repeating the last value on the edge. + For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode + will result in [2, 1, 1, 2, 3, 4, 4, 3] + """ + + _v1_transform_cls = _transforms.RandomCrop + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + params = super()._extract_params_for_v1_transform() + + if not (params["fill"] is None or isinstance(params["fill"], (int, float))): + raise ValueError(f"{type(self).__name__}() can only be scripted for a scalar `fill`, but got {self.fill}.") + + padding = self.padding + if padding is not None: + pad_left, pad_right, pad_top, pad_bottom = padding + padding = [pad_left, pad_top, pad_right, pad_bottom] + params["padding"] = padding + + return params + + def __init__( + self, + size: Union[int, Sequence[int]], + padding: Optional[Union[int, Sequence[int]]] = None, + pad_if_needed: bool = False, + fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, + padding_mode: Literal["constant", "edge", "reflect", "symmetric"] = "constant", + ) -> None: + super().__init__() + + self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.") + + if pad_if_needed or padding is not None: + if padding is not None: + _check_padding_arg(padding) + _check_padding_mode_arg(padding_mode) + + self.padding = F._geometry._parse_pad_padding(padding) if padding else None # type: ignore[arg-type] + self.pad_if_needed = pad_if_needed + self.fill = fill + self._fill = _setup_fill_arg(fill) + self.padding_mode = padding_mode + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + padded_height, padded_width = query_size(flat_inputs) + + if self.padding is not None: + pad_left, pad_right, pad_top, pad_bottom = self.padding + padded_height += pad_top + pad_bottom + padded_width += pad_left + pad_right + else: + pad_left = pad_right = pad_top = pad_bottom = 0 + + cropped_height, cropped_width = self.size + + if self.pad_if_needed: + if padded_height < cropped_height: + diff = cropped_height - padded_height + + pad_top += diff + pad_bottom += diff + padded_height += 2 * diff + + if padded_width < cropped_width: + diff = cropped_width - padded_width + + pad_left += diff + pad_right += diff + padded_width += 2 * diff + + if padded_height < cropped_height or padded_width < cropped_width: + raise ValueError( + f"Required crop size {(cropped_height, cropped_width)} is larger than " + f"{'padded ' if self.padding is not None else ''}input image size {(padded_height, padded_width)}." + ) + + # We need a different order here than we have in self.padding since this padding will be parsed again in `F.pad` + padding = [pad_left, pad_top, pad_right, pad_bottom] + needs_pad = any(padding) + + needs_vert_crop, top = ( + (True, int(torch.randint(0, padded_height - cropped_height + 1, size=()))) + if padded_height > cropped_height + else (False, 0) + ) + needs_horz_crop, left = ( + (True, int(torch.randint(0, padded_width - cropped_width + 1, size=()))) + if padded_width > cropped_width + else (False, 0) + ) + + return dict( + needs_crop=needs_vert_crop or needs_horz_crop, + top=top, + left=left, + height=cropped_height, + width=cropped_width, + needs_pad=needs_pad, + padding=padding, + ) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + if params["needs_pad"]: + fill = _get_fill(self._fill, type(inpt)) + inpt = self._call_kernel(F.pad, inpt, padding=params["padding"], fill=fill, padding_mode=self.padding_mode) + + if params["needs_crop"]: + inpt = self._call_kernel( + F.crop, inpt, top=params["top"], left=params["left"], height=params["height"], width=params["width"] + ) + + return inpt + + +class RandomPerspective(_RandomApplyTransform): + """Perform a random perspective transformation of the input with a given probability. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + distortion_scale (float, optional): argument to control the degree of distortion and ranges from 0 to 1. + Default is 0.5. + p (float, optional): probability of the input being transformed. Default is 0.5. + interpolation (str or InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.v2.InterpolationMode`. + Accepted string values are ``"nearest"``, ``"nearest-exact"``, ``"bilinear"``, ``"bicubic"``, + ``"box"``, ``"hamming"``, and ``"lanczos"``. + ``"box"``, ``"hamming"``, and ``"lanczos"`` are only supported for PIL images. + Default is ``"bilinear"``. + The corresponding ``InterpolationMode`` enum values and Pillow integer + constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant. + Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. + Fill value can be also a dictionary mapping data type to the fill value, e.g. + ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and + ``Mask`` will be filled with 0. + """ + + _v1_transform_cls = _transforms.RandomPerspective + + def __init__( + self, + distortion_scale: float = 0.5, + p: float = 0.5, + interpolation: Union[str, InterpolationMode, int] = "bilinear", + fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, + ) -> None: + super().__init__(p=p) + + if not (0 <= distortion_scale <= 1): + raise ValueError("Argument distortion_scale value should be between 0 and 1") + + self.distortion_scale = distortion_scale + self.interpolation = interpolation + self.fill = fill + self._fill = _setup_fill_arg(fill) + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + height, width = query_size(flat_inputs) + + distortion_scale = self.distortion_scale + + half_height = height // 2 + half_width = width // 2 + bound_height = int(distortion_scale * half_height) + 1 + bound_width = int(distortion_scale * half_width) + 1 + topleft = [ + int(torch.randint(0, bound_width, size=(1,))), + int(torch.randint(0, bound_height, size=(1,))), + ] + topright = [ + int(torch.randint(width - bound_width, width, size=(1,))), + int(torch.randint(0, bound_height, size=(1,))), + ] + botright = [ + int(torch.randint(width - bound_width, width, size=(1,))), + int(torch.randint(height - bound_height, height, size=(1,))), + ] + botleft = [ + int(torch.randint(0, bound_width, size=(1,))), + int(torch.randint(height - bound_height, height, size=(1,))), + ] + startpoints = [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]] + endpoints = [topleft, topright, botright, botleft] + perspective_coeffs = _get_perspective_coeffs(startpoints, endpoints) + return dict(coefficients=perspective_coeffs) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + fill = _get_fill(self._fill, type(inpt)) + return self._call_kernel( + F.perspective, + inpt, + startpoints=None, + endpoints=None, + fill=fill, + interpolation=self.interpolation, + **params, + ) + + +class ElasticTransform(Transform): + """Transform the input with elastic transformations. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Given alpha and sigma, it will generate displacement + vectors for all pixels based on random offsets. Alpha controls the strength + and sigma controls the smoothness of the displacements. + The displacements are added to an identity grid and the resulting grid is + used to transform the input. + + .. note:: + Implementation to transform bounding boxes is approximative (not exact). + We construct an approximation of the inverse grid as ``inverse_grid = identity - displacement``. + This is not an exact inverse of the grid used to transform images, i.e. ``grid = identity + displacement``. + Our assumption is that ``displacement * displacement`` is small and can be ignored. + Large displacements would lead to large errors in the approximation. + + Applications: + Randomly transforms the morphology of objects in images and produces a + see-through-water-like effect. + + Args: + alpha (float or sequence of floats, optional): Magnitude of displacements. + Default is 50.0. A single value is ``[alpha, alpha]``. + sigma (float or sequence of floats, optional): Smoothness of displacements. + Default is 5.0. A single value is ``[sigma, sigma]``. + interpolation (str or InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.v2.InterpolationMode`. + Accepted string values are ``"nearest"``, ``"nearest-exact"``, ``"bilinear"``, ``"bicubic"``, + ``"box"``, ``"hamming"``, and ``"lanczos"``. + ``"box"``, ``"hamming"``, and ``"lanczos"`` are only supported for PIL images. + Default is ``"bilinear"``. + The corresponding ``InterpolationMode`` enum values and Pillow integer + constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant. + Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. + Fill value can be also a dictionary mapping data type to the fill value, e.g. + ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and + ``Mask`` will be filled with 0. + """ + + _v1_transform_cls = _transforms.ElasticTransform + + def __init__( + self, + alpha: Union[float, Sequence[float]] = 50.0, + sigma: Union[float, Sequence[float]] = 5.0, + interpolation: Union[str, InterpolationMode, int] = "bilinear", + fill: Union[_FillType, dict[Union[type, str], _FillType]] = 0, + ) -> None: + super().__init__() + self.alpha = _setup_number_or_seq(alpha, "alpha") + self.sigma = _setup_number_or_seq(sigma, "sigma") + + self.interpolation = interpolation + self.fill = fill + self._fill = _setup_fill_arg(fill) + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + height, width = query_size(flat_inputs) + + dx = torch.rand(1, 1, height, width) * 2 - 1 + if self.sigma[0] > 0.0: + kx = int(8 * self.sigma[0] + 1) + # if kernel size is even we have to make it odd + if kx % 2 == 0: + kx += 1 + dx = self._call_kernel(F.gaussian_blur, dx, [kx, kx], list(self.sigma)) + dx = dx * self.alpha[0] / width + + dy = torch.rand(1, 1, height, width) * 2 - 1 + if self.sigma[1] > 0.0: + ky = int(8 * self.sigma[1] + 1) + # if kernel size is even we have to make it odd + if ky % 2 == 0: + ky += 1 + dy = self._call_kernel(F.gaussian_blur, dy, [ky, ky], list(self.sigma)) + dy = dy * self.alpha[1] / height + displacement = torch.concat([dx, dy], 1).permute([0, 2, 3, 1]) # 1 x H x W x 2 + return dict(displacement=displacement) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + fill = _get_fill(self._fill, type(inpt)) + return self._call_kernel( + F.elastic, + inpt, + **params, + fill=fill, + interpolation=self.interpolation, + ) + + +class RandomIoUCrop(Transform): + """Random IoU crop transformation from + `"SSD: Single Shot MultiBox Detector" `_. + + This transformation requires an image or video data and ``tv_tensors.BoundingBoxes`` in the input. + + .. warning:: + In order to properly remove the bounding boxes below the IoU threshold, `RandomIoUCrop` + must be followed by :class:`~torchvision.transforms.v2.SanitizeBoundingBoxes`, either immediately + after or later in the transforms pipeline. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + min_scale (float, optional): Minimum factors to scale the input size. + max_scale (float, optional): Maximum factors to scale the input size. + min_aspect_ratio (float, optional): Minimum aspect ratio for the cropped image or video. + max_aspect_ratio (float, optional): Maximum aspect ratio for the cropped image or video. + sampler_options (list of float, optional): List of minimal IoU (Jaccard) overlap between all the boxes and + a cropped image or video. Default, ``None`` which corresponds to ``[0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0]`` + trials (int, optional): Number of trials to find a crop for a given value of minimal IoU (Jaccard) overlap. + Default, 40. + """ + + def __init__( + self, + min_scale: float = 0.3, + max_scale: float = 1.0, + min_aspect_ratio: float = 0.5, + max_aspect_ratio: float = 2.0, + sampler_options: Optional[list[float]] = None, + trials: int = 40, + ): + super().__init__() + # Configuration similar to https://github.com/weiliu89/caffe/blob/ssd/examples/ssd/ssd_coco.py#L89-L174 + self.min_scale = min_scale + self.max_scale = max_scale + self.min_aspect_ratio = min_aspect_ratio + self.max_aspect_ratio = max_aspect_ratio + if sampler_options is None: + sampler_options = [0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0] + self.options = sampler_options + self.trials = trials + + def check_inputs(self, flat_inputs: list[Any]) -> None: + if not ( + has_all(flat_inputs, tv_tensors.BoundingBoxes) + and has_any(flat_inputs, PIL.Image.Image, tv_tensors.Image, is_pure_tensor) + ): + raise TypeError( + f"{type(self).__name__}() requires input sample to contain tensor or PIL images " + "and bounding boxes. Sample can also contain masks." + ) + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + orig_h, orig_w = query_size(flat_inputs) + bboxes = get_bounding_boxes(flat_inputs) + + while True: + # sample an option + idx = int(torch.randint(low=0, high=len(self.options), size=(1,))) + min_jaccard_overlap = self.options[idx] + if min_jaccard_overlap >= 1.0: # a value larger than 1 encodes the leave as-is option + return dict() + + for _ in range(self.trials): + # check the aspect ratio limitations + r = self.min_scale + (self.max_scale - self.min_scale) * torch.rand(2) + new_w = int(orig_w * r[0]) + new_h = int(orig_h * r[1]) + aspect_ratio = new_w / new_h + if not (self.min_aspect_ratio <= aspect_ratio <= self.max_aspect_ratio): + continue + + # check for 0 area crops + r = torch.rand(2) + left = int((orig_w - new_w) * r[0]) + top = int((orig_h - new_h) * r[1]) + right = left + new_w + bottom = top + new_h + if left == right or top == bottom: + continue + + # check for any valid boxes with centers within the crop area + xyxy_bboxes = F.convert_bounding_box_format( + bboxes.as_subclass(torch.Tensor), + bboxes.format, + tv_tensors.BoundingBoxFormat.XYXY, + ) + cx = 0.5 * (xyxy_bboxes[..., 0] + xyxy_bboxes[..., 2]) + cy = 0.5 * (xyxy_bboxes[..., 1] + xyxy_bboxes[..., 3]) + is_within_crop_area = (left < cx) & (cx < right) & (top < cy) & (cy < bottom) + if not is_within_crop_area.any(): + continue + + # check at least 1 box with jaccard limitations + xyxy_bboxes = xyxy_bboxes[is_within_crop_area] + ious = box_iou( + xyxy_bboxes, + torch.tensor([[left, top, right, bottom]], dtype=xyxy_bboxes.dtype, device=xyxy_bboxes.device), + ) + if ious.max() < min_jaccard_overlap: + continue + + return dict(top=top, left=left, height=new_h, width=new_w, is_within_crop_area=is_within_crop_area) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + + if len(params) < 1: + return inpt + + output = self._call_kernel( + F.crop, inpt, top=params["top"], left=params["left"], height=params["height"], width=params["width"] + ) + + if isinstance(output, tv_tensors.BoundingBoxes): + # We "mark" the invalid boxes as degenreate, and they can be + # removed by a later call to SanitizeBoundingBoxes() + output[~params["is_within_crop_area"]] = 0 + + return output + + +class ScaleJitter(Transform): + """Perform Large Scale Jitter on the input according to + `"Simple Copy-Paste is a Strong Data Augmentation Method for Instance Segmentation" `_. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + target_size (tuple of int): Target size. This parameter defines base scale for jittering, + e.g. ``min(target_size[0] / width, target_size[1] / height)``. + scale_range (tuple of float, optional): Minimum and maximum of the scale range. Default, ``(0.1, 2.0)``. + interpolation (str or InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.v2.InterpolationMode`. + Accepted string values are ``"nearest"``, ``"nearest-exact"``, ``"bilinear"``, ``"bicubic"``, + ``"box"``, ``"hamming"``, and ``"lanczos"``. + ``"box"`` and ``"hamming"`` are only supported for PIL images. + ``"lanczos"`` is only supported on CPU and requires ``antialias=True``. + Default is ``"bilinear"``. + The corresponding ``InterpolationMode`` enum values and Pillow integer + constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear, bicubic, or lanczos modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear, bicubic, or lanczos modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + """ + + def __init__( + self, + target_size: tuple[int, int], + scale_range: tuple[float, float] = (0.1, 2.0), + interpolation: Union[str, InterpolationMode, int] = "bilinear", + antialias: Optional[bool] = True, + ): + super().__init__() + self.target_size = target_size + self.scale_range = scale_range + self.interpolation = interpolation + self.antialias = antialias + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + orig_height, orig_width = query_size(flat_inputs) + + scale = self.scale_range[0] + torch.rand(1) * (self.scale_range[1] - self.scale_range[0]) + r = min(self.target_size[1] / orig_height, self.target_size[0] / orig_width) * scale + new_width = int(orig_width * r) + new_height = int(orig_height * r) + + return dict(size=(new_height, new_width)) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel( + F.resize, inpt, size=params["size"], interpolation=self.interpolation, antialias=self.antialias + ) + + +class RandomShortestSize(Transform): + """Randomly resize the input. + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + min_size (int or sequence of int): Minimum spatial size. Single integer value or a sequence of integer values. + max_size (int, optional): Maximum spatial size. Default, None. + interpolation (str or InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.v2.InterpolationMode`. + Accepted string values are ``"nearest"``, ``"nearest-exact"``, ``"bilinear"``, ``"bicubic"``, + ``"box"``, ``"hamming"``, and ``"lanczos"``. + ``"box"`` and ``"hamming"`` are only supported for PIL images. + ``"lanczos"`` is only supported on CPU and requires ``antialias=True``. + Default is ``"bilinear"``. + The corresponding ``InterpolationMode`` enum values and Pillow integer + constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear, bicubic, or lanczos modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear, bicubic, or lanczos modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + """ + + def __init__( + self, + min_size: Union[list[int], tuple[int], int], + max_size: Optional[int] = None, + interpolation: Union[str, InterpolationMode, int] = "bilinear", + antialias: Optional[bool] = True, + ): + super().__init__() + self.min_size = [min_size] if isinstance(min_size, int) else list(min_size) + self.max_size = max_size + self.interpolation = interpolation + self.antialias = antialias + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + orig_height, orig_width = query_size(flat_inputs) + + min_size = self.min_size[int(torch.randint(len(self.min_size), ()))] + r = min_size / min(orig_height, orig_width) + if self.max_size is not None: + r = min(r, self.max_size / max(orig_height, orig_width)) + + new_width = int(orig_width * r) + new_height = int(orig_height * r) + + return dict(size=(new_height, new_width)) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel( + F.resize, inpt, size=params["size"], interpolation=self.interpolation, antialias=self.antialias + ) + + +class RandomResize(Transform): + """Randomly resize the input. + + This transformation can be used together with ``RandomCrop`` as data augmentations to train + models on image segmentation task. + + Output spatial size is randomly sampled from the interval ``[min_size, max_size]``: + + .. code-block:: python + + size = uniform_sample(min_size, max_size) + output_width = size + output_height = size + + If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`, + :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.) + it can have arbitrary number of leading batch dimensions. For example, + the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape. + + Args: + min_size (int): Minimum output size for random sampling + max_size (int): Maximum output size for random sampling + interpolation (str or InterpolationMode, optional): Desired interpolation enum defined by + :class:`torchvision.transforms.v2.InterpolationMode`. + Accepted string values are ``"nearest"``, ``"nearest-exact"``, ``"bilinear"``, ``"bicubic"``, + ``"box"``, ``"hamming"``, and ``"lanczos"``. + ``"box"`` and ``"hamming"`` are only supported for PIL images. + ``"lanczos"`` is only supported on CPU and requires ``antialias=True``. + Default is ``"bilinear"``. + The corresponding ``InterpolationMode`` enum values and Pillow integer + constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well. + antialias (bool, optional): Whether to apply antialiasing. + It only affects **tensors** with bilinear, bicubic, or lanczos modes and it is + ignored otherwise: on PIL images, antialiasing is always applied on + bilinear or bicubic modes; on other modes (for PIL images and + tensors), antialiasing makes no sense and this parameter is ignored. + Possible values are: + + - ``True`` (default): will apply antialiasing for bilinear, bicubic, or lanczos modes. + Other mode aren't affected. This is probably what you want to use. + - ``False``: will not apply antialiasing for tensors on any mode. PIL + images are still antialiased on bilinear or bicubic modes, because + PIL doesn't support no antialias. + - ``None``: equivalent to ``False`` for tensors and ``True`` for + PIL images. This value exists for legacy reasons and you probably + don't want to use it unless you really know what you are doing. + + The default value changed from ``None`` to ``True`` in + v0.17, for the PIL and Tensor backends to be consistent. + """ + + def __init__( + self, + min_size: int, + max_size: int, + interpolation: Union[str, InterpolationMode, int] = "bilinear", + antialias: Optional[bool] = True, + ) -> None: + super().__init__() + self.min_size = min_size + self.max_size = max_size + self.interpolation = interpolation + self.antialias = antialias + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + size = int(torch.randint(self.min_size, self.max_size, ())) + return dict(size=[size]) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel( + F.resize, inpt, params["size"], interpolation=self.interpolation, antialias=self.antialias + ) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_meta.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..39f223f0398c836b9d109faf817526376fece7d2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_meta.py @@ -0,0 +1,81 @@ +from typing import Any, Union + +from torchvision import tv_tensors +from torchvision.transforms.v2 import functional as F, Transform +from torchvision.tv_tensors._bounding_boxes import CLAMPING_MODE_TYPE + + +class ConvertBoundingBoxFormat(Transform): + """Convert bounding box coordinates to the given ``format``, eg from "CXCYWH" to "XYXY". + + Args: + format (str or tv_tensors.BoundingBoxFormat): output bounding box format. + Possible values are defined by :class:`~torchvision.tv_tensors.BoundingBoxFormat` and + string values match the enums, e.g. "XYXY" or "XYWH" etc. + """ + + _transformed_types = (tv_tensors.BoundingBoxes,) + + def __init__(self, format: Union[str, tv_tensors.BoundingBoxFormat]) -> None: + super().__init__() + self.format = format + + def transform(self, inpt: tv_tensors.BoundingBoxes, params: dict[str, Any]) -> tv_tensors.BoundingBoxes: + return F.convert_bounding_box_format(inpt, new_format=self.format) # type: ignore[return-value, arg-type] + + +class ClampBoundingBoxes(Transform): + """Clamp bounding boxes to their corresponding image dimensions. + + Args: + clamping_mode: Default is "auto" which relies on the input box' + ``clamping_mode`` attribute. Read more in :ref:`clamping_mode_tuto` + for more details on how to use this transform. + """ + + def __init__(self, clamping_mode: Union[CLAMPING_MODE_TYPE, str] = "auto") -> None: + super().__init__() + self.clamping_mode = clamping_mode + + _transformed_types = (tv_tensors.BoundingBoxes,) + + def transform(self, inpt: tv_tensors.BoundingBoxes, params: dict[str, Any]) -> tv_tensors.BoundingBoxes: + return F.clamp_bounding_boxes(inpt, clamping_mode=self.clamping_mode) # type: ignore[return-value] + + +class ClampKeyPoints(Transform): + """Clamp keypoints to their corresponding image dimensions. + + The clamping is done according to the keypoints' ``canvas_size`` meta-data. + """ + + _transformed_types = (tv_tensors.KeyPoints,) + + def transform(self, inpt: tv_tensors.KeyPoints, params: dict[str, Any]) -> tv_tensors.KeyPoints: + return F.clamp_keypoints(inpt) # type: ignore[return-value] + + +class SetClampingMode(Transform): + """Sets the ``clamping_mode`` attribute of the bounding boxes for future transforms. + + + + Args: + clamping_mode: The clamping mode to set. Possible values are: "soft", + "hard", or ``None``. Read more in :ref:`clamping_mode_tuto` for more + details on how to use this transform. + """ + + def __init__(self, clamping_mode: CLAMPING_MODE_TYPE) -> None: + super().__init__() + self.clamping_mode = clamping_mode + + if self.clamping_mode not in (None, "soft", "hard"): + raise ValueError(f"clamping_mode must be soft, hard or None, got {clamping_mode}") + + _transformed_types = (tv_tensors.BoundingBoxes,) + + def transform(self, inpt: tv_tensors.BoundingBoxes, params: dict[str, Any]) -> tv_tensors.BoundingBoxes: + out: tv_tensors.BoundingBoxes = inpt.clone() # type: ignore[assignment] + out.clamping_mode = self.clamping_mode + return out diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_misc.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..305149c87b115a7e6789979c224c71c53645d596 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_misc.py @@ -0,0 +1,570 @@ +import warnings +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +import PIL.Image + +import torch +from torch.utils._pytree import tree_flatten, tree_unflatten + +from torchvision import transforms as _transforms, tv_tensors +from torchvision.transforms.v2 import functional as F, Transform + +from ._utils import ( + _parse_labels_getter, + _setup_number_or_seq, + _setup_size, + get_bounding_boxes, + get_keypoints, + has_any, + is_pure_tensor, +) + + +# TODO: do we want/need to expose this? +class Identity(Transform): + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return inpt + + +class Lambda(Transform): + """Apply a user-defined function as a transform. + + This transform does not support torchscript. + + Args: + lambd (function): Lambda/function to be used for transform. + """ + + _transformed_types = (object,) + + def __init__(self, lambd: Callable[[Any], Any], *types: type): + super().__init__() + self.lambd = lambd + self.types = types or self._transformed_types + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + if isinstance(inpt, self.types): + return self.lambd(inpt) + else: + return inpt + + def extra_repr(self) -> str: + extras = [] + name = getattr(self.lambd, "__name__", None) + if name: + extras.append(name) + extras.append(f"types={[type.__name__ for type in self.types]}") + return ", ".join(extras) + + +class LinearTransformation(Transform): + """Transform a tensor image or video with a square transformation matrix and a mean_vector computed offline. + + This transform does not support PIL Image. + Given transformation_matrix and mean_vector, will flatten the torch.*Tensor and + subtract mean_vector from it which is then followed by computing the dot + product with the transformation matrix and then reshaping the tensor to its + original shape. + + Applications: + whitening transformation: Suppose X is a column vector zero-centered data. + Then compute the data covariance matrix [D x D] with torch.mm(X.t(), X), + perform SVD on this matrix and pass it as transformation_matrix. + + Args: + transformation_matrix (Tensor): tensor [D x D], D = C x H x W + mean_vector (Tensor): tensor [D], D = C x H x W + """ + + _v1_transform_cls = _transforms.LinearTransformation + + _transformed_types = (is_pure_tensor, tv_tensors.Image, tv_tensors.Video) + + def __init__(self, transformation_matrix: torch.Tensor, mean_vector: torch.Tensor): + super().__init__() + if transformation_matrix.size(0) != transformation_matrix.size(1): + raise ValueError( + "transformation_matrix should be square. Got " + f"{tuple(transformation_matrix.size())} rectangular matrix." + ) + + if mean_vector.size(0) != transformation_matrix.size(0): + raise ValueError( + f"mean_vector should have the same length {mean_vector.size(0)}" + f" as any one of the dimensions of the transformation_matrix [{tuple(transformation_matrix.size())}]" + ) + + if transformation_matrix.device != mean_vector.device: + raise ValueError( + f"Input tensors should be on the same device. Got {transformation_matrix.device} and {mean_vector.device}" + ) + + if transformation_matrix.dtype != mean_vector.dtype: + raise ValueError( + f"Input tensors should have the same dtype. Got {transformation_matrix.dtype} and {mean_vector.dtype}" + ) + + self.transformation_matrix = transformation_matrix + self.mean_vector = mean_vector + + def check_inputs(self, sample: Any) -> Any: + if has_any(sample, PIL.Image.Image): + raise TypeError(f"{type(self).__name__}() does not support PIL images.") + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + shape = inpt.shape + n = shape[-3] * shape[-2] * shape[-1] + if n != self.transformation_matrix.shape[0]: + raise ValueError( + "Input tensor and transformation matrix have incompatible shape." + + f"[{shape[-3]} x {shape[-2]} x {shape[-1]}] != " + + f"{self.transformation_matrix.shape[0]}" + ) + + if inpt.device.type != self.mean_vector.device.type: + raise ValueError( + "Input tensor should be on the same device as transformation matrix and mean vector. " + f"Got {inpt.device} vs {self.mean_vector.device}" + ) + + flat_inpt = inpt.reshape(-1, n) - self.mean_vector + + transformation_matrix = self.transformation_matrix.to(flat_inpt.dtype) + output = torch.mm(flat_inpt, transformation_matrix) + output = output.reshape(shape) + + if isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)): + output = tv_tensors.wrap(output, like=inpt) + return output + + +class Normalize(Transform): + """Normalize a tensor image or video with mean and standard deviation. + + This transform does not support PIL Image. + Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])`` for ``n`` + channels, this transform will normalize each channel of the input + ``torch.*Tensor`` i.e., + ``output[channel] = (input[channel] - mean[channel]) / std[channel]`` + + .. note:: + This transform acts out of place, i.e., it does not mutate the input tensor. + + Args: + mean (sequence): Sequence of means for each channel. + std (sequence): Sequence of standard deviations for each channel. + inplace(bool,optional): Bool to make this operation in-place. + + """ + + _v1_transform_cls = _transforms.Normalize + + def __init__(self, mean: Sequence[float], std: Sequence[float], inplace: bool = False): + super().__init__() + self.mean = list(mean) + self.std = list(std) + self.inplace = inplace + + def check_inputs(self, sample: Any) -> Any: + if has_any(sample, PIL.Image.Image): + raise TypeError(f"{type(self).__name__}() does not support PIL images.") + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.normalize, inpt, mean=self.mean, std=self.std, inplace=self.inplace) + + +class GaussianBlur(Transform): + """Blurs image with randomly chosen Gaussian blur kernel. + + The convolution will be using reflection padding corresponding to the kernel size, to maintain the input shape. + + If the input is a Tensor, it is expected + to have [..., C, H, W] shape, where ... means an arbitrary number of leading dimensions. + + Args: + kernel_size (int or sequence): Size of the Gaussian kernel. + sigma (float or tuple of float (min, max)): Standard deviation to be used for + creating kernel to perform blurring. If float, sigma is fixed. If it is tuple + of float (min, max), sigma is chosen uniformly at random to lie in the + given range. + """ + + _v1_transform_cls = _transforms.GaussianBlur + + def __init__( + self, kernel_size: Union[int, Sequence[int]], sigma: Union[int, float, Sequence[float]] = (0.1, 2.0) + ) -> None: + super().__init__() + self.kernel_size = _setup_size(kernel_size, "Kernel size should be a tuple/list of two integers") + for ks in self.kernel_size: + if ks <= 0 or ks % 2 == 0: + raise ValueError("Kernel size value should be an odd and positive number.") + + self.sigma = _setup_number_or_seq(sigma, "sigma") + + if not 0.0 < self.sigma[0] <= self.sigma[1]: + raise ValueError(f"sigma values should be positive and of the form (min, max). Got {self.sigma}") + + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + sigma = torch.empty(1).uniform_(self.sigma[0], self.sigma[1]).item() + return dict(sigma=[sigma, sigma]) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.gaussian_blur, inpt, self.kernel_size, **params) + + +class GaussianNoise(Transform): + """Add gaussian noise to images or videos. + + The input tensor is expected to be in [..., 1 or 3, H, W] format, + where ... means it can have an arbitrary number of leading dimensions. + Each image or frame in a batch will be transformed independently i.e. the + noise added to each image will be different. + + The input tensor is also expected to be of float dtype in ``[0, 1]``, + or of ``uint8`` dtype in ``[0, 255]``. This transform does not support PIL + images. + + Regardless of the dtype used, the parameters of the function use the same + scale, so a ``mean`` parameter of 0.5 will result in an average value + increase of 0.5 units for float images, and an average increase of 127.5 + units for ``uint8`` images. + + Args: + mean (float): Mean of the sampled normal distribution. Default is 0. + sigma (float): Standard deviation of the sampled normal distribution. Default is 0.1. + clip (bool, optional): Whether to clip the values after adding noise, be it to + ``[0, 1]`` for floats or to ``[0, 255]`` for ``uint8``. Setting this parameter to + ``False`` may cause unsigned integer overflows with uint8 inputs. + Default is True. + """ + + def __init__(self, mean: float = 0.0, sigma: float = 0.1, clip=True) -> None: + super().__init__() + self.mean = mean + self.sigma = sigma + self.clip = clip + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.gaussian_noise, inpt, mean=self.mean, sigma=self.sigma, clip=self.clip) + + +class ToDtype(Transform): + """Converts the input to a specific dtype, optionally scaling the values for images or videos. + + .. note:: + ``ToDtype(dtype, scale=True)`` is the recommended replacement for ``ConvertImageDtype(dtype)``. + + Args: + dtype (``torch.dtype`` or dict of ``TVTensor`` -> ``torch.dtype``): The dtype to convert to. + If a ``torch.dtype`` is passed, e.g. ``torch.float32``, only images and videos will be converted + to that dtype: this is for compatibility with :class:`~torchvision.transforms.v2.ConvertImageDtype`. + A dict can be passed to specify per-tv_tensor conversions, e.g. + ``dtype={tv_tensors.Image: torch.float32, tv_tensors.Mask: torch.int64, "others":None}``. The "others" + key can be used as a catch-all for any other tv_tensor type, and ``None`` means no conversion. + scale (bool, optional): Whether to scale the values for images or videos. See :ref:`range_and_dtype`. + Default: ``False``. + """ + + _transformed_types = (torch.Tensor,) + + def __init__( + self, dtype: Union[torch.dtype, dict[Union[type, str], Optional[torch.dtype]]], scale: bool = False + ) -> None: + super().__init__() + + if not isinstance(dtype, (dict, torch.dtype)): + raise ValueError(f"dtype must be a dict or a torch.dtype, got {type(dtype)} instead") + + if ( + isinstance(dtype, dict) + and torch.Tensor in dtype + and any(cls in dtype for cls in [tv_tensors.Image, tv_tensors.Video]) + ): + warnings.warn( + "Got `dtype` values for `torch.Tensor` and either `tv_tensors.Image` or `tv_tensors.Video`. " + "Note that a plain `torch.Tensor` will *not* be transformed by this (or any other transformation) " + "in case a `tv_tensors.Image` or `tv_tensors.Video` is present in the input." + ) + self.dtype = dtype + self.scale = scale + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + if isinstance(self.dtype, torch.dtype): + # For consistency / BC with ConvertImageDtype, we only care about images or videos when dtype + # is a simple torch.dtype + if not is_pure_tensor(inpt) and not isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)): + return inpt + + dtype: Optional[torch.dtype] = self.dtype + elif type(inpt) in self.dtype: + dtype = self.dtype[type(inpt)] + elif "others" in self.dtype: + dtype = self.dtype["others"] + else: + raise ValueError( + f"No dtype was specified for type {type(inpt)}. " + "If you only need to convert the dtype of images or videos, you can just pass e.g. dtype=torch.float32. " + "If you're passing a dict as dtype, " + 'you can use "others" as a catch-all key ' + 'e.g. dtype={tv_tensors.Mask: torch.int64, "others": None} to pass-through the rest of the inputs.' + ) + + supports_scaling = is_pure_tensor(inpt) or isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)) + if dtype is None: + if self.scale and supports_scaling: + warnings.warn( + "scale was set to True but no dtype was specified for images or videos: no scaling will be done." + ) + return inpt + + return self._call_kernel(F.to_dtype, inpt, dtype=dtype, scale=self.scale) + + +class ConvertImageDtype(Transform): + """[DEPRECATED] Use ``v2.ToDtype(dtype, scale=True)`` instead. + + Convert input image to the given ``dtype`` and scale the values accordingly. + + .. warning:: + Consider using ``ToDtype(dtype, scale=True)`` instead. See :class:`~torchvision.transforms.v2.ToDtype`. + + This function does not support PIL Image. + + Args: + dtype (torch.dtype): Desired data type of the output + + .. note:: + + When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly. + If converted back and forth, this mismatch has no effect. + + Raises: + RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as + well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to + overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range + of the integer ``dtype``. + """ + + _v1_transform_cls = _transforms.ConvertImageDtype + + def __init__(self, dtype: torch.dtype = torch.float32) -> None: + super().__init__() + self.dtype = dtype + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.to_dtype, inpt, dtype=self.dtype, scale=True) + + +class SanitizeBoundingBoxes(Transform): + """Remove degenerate/invalid bounding boxes and their corresponding labels and masks. + + This transform removes bounding boxes and their associated labels/masks that: + + - are below a given ``min_size`` or ``min_area``: by default this also removes degenerate boxes that have e.g. X2 <= X1. + - have any coordinate outside of their corresponding image. You may want to + call :class:`~torchvision.transforms.v2.ClampBoundingBoxes` first to avoid undesired removals. + + It can also sanitize other tensors like the "iscrowd" or "area" properties from COCO + (see ``labels_getter`` parameter). + + .. note:: + **Mask handling**: This transform automatically detects and sanitizes per-instance masks + (shape ``[N, H, W]`` where N matches the number of bounding boxes). Semantic segmentation masks + (shape ``[H, W]``) or masks with mismatched dimensions are passed through unchanged. + You do not need to add masks to ``labels_getter`` for them to be sanitized. + + It is recommended to call it at the end of a pipeline, before passing the + input to the models. It is critical to call this transform if + :class:`~torchvision.transforms.v2.RandomIoUCrop` was called. + If you want to be extra careful, you may call it after all transforms that + may modify bounding boxes but once at the end should be enough in most + cases. + + Args: + min_size (float, optional): The size below which bounding boxes are removed. Default is 1. + min_area (float, optional): The area below which bounding boxes are removed. Default is 1. + labels_getter (callable or str or None, optional): indicates how to identify the labels in the input + (or anything else that needs to be sanitized along with the bounding boxes). + By default, this will try to find a "labels" key in the input (case-insensitive), if + the input is a dict or it is a tuple whose second element is a dict. + This heuristic should work well with a lot of datasets, including the built-in torchvision datasets. + + It can also be a callable that takes the same input as the transform, and returns either: + + - A single tensor (the labels) + - A tuple/list of tensors, each of which will be subject to the same sanitization as the bounding boxes. + This is useful to sanitize multiple tensors like the labels, and the "iscrowd" or "area" properties + from COCO. + + If ``labels_getter`` is None then only bounding boxes are sanitized. + """ + + def __init__( + self, + min_size: float = 1.0, + min_area: float = 1.0, + labels_getter: Union[Callable[[Any], Any], str, None] = "default", + ) -> None: + super().__init__() + + if min_size < 1: + raise ValueError(f"min_size must be >= 1, got {min_size}.") + self.min_size = min_size + + if min_area < 1: + raise ValueError(f"min_area must be >= 1, got {min_area}.") + self.min_area = min_area + + self.labels_getter = labels_getter + self._labels_getter = _parse_labels_getter(labels_getter) + + def forward(self, *inputs: Any) -> Any: + inputs = inputs if len(inputs) > 1 else inputs[0] + + labels = self._labels_getter(inputs) + if labels is not None: + msg = "The labels in the input to forward() must be a tensor or None, got {type} instead." + if isinstance(labels, torch.Tensor): + labels = (labels,) + elif isinstance(labels, (tuple, list)): + for entry in labels: + if not isinstance(entry, torch.Tensor): + # TODO: we don't need to enforce tensors, just that entries are indexable as t[bool_mask] + raise ValueError(msg.format(type=type(entry))) + else: + raise ValueError(msg.format(type=type(labels))) + + flat_inputs, spec = tree_flatten(inputs) + boxes = get_bounding_boxes(flat_inputs) + + if labels is not None: + for label in labels: + if boxes.shape[0] != label.shape[0]: + raise ValueError( + f"Number of boxes (shape={boxes.shape}) and must match the number of labels." + f"Found labels with shape={label.shape})." + ) + + valid = F._misc._get_sanitize_bounding_boxes_mask( + boxes, + format=boxes.format, + canvas_size=boxes.canvas_size, + min_size=self.min_size, + min_area=self.min_area, + ) + + params = dict(valid=valid, labels=labels) + flat_outputs = [self.transform(inpt, params) for inpt in flat_inputs] + + return tree_unflatten(flat_outputs, spec) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + is_label = params["labels"] is not None and any(inpt is label for label in params["labels"]) + is_bounding_boxes = isinstance(inpt, tv_tensors.BoundingBoxes) + is_mask = isinstance(inpt, tv_tensors.Mask) + + if not (is_label or is_bounding_boxes or is_mask): + return inpt + + try: + output = inpt[params["valid"]] + except (IndexError): + # If indexing fails (e.g., shape mismatch), pass through unchanged + return inpt + + if is_label: + return output + else: + return tv_tensors.wrap(output, like=inpt) + + +class SanitizeKeyPoints(Transform): + """Remove keypoints outside of the image area and their corresponding labels (if any). + + This transform removes keypoints or groups of keypoints and their associated labels that + have coordinates outside of their corresponding image. + If you would instead like to clamp such keypoints to the image edges, use + :class:`~torchvision.transforms.v2.ClampKeyPoints`. + + It is recommended to call it at the end of a pipeline, before passing the + input to the models. + + Keypoints can be passed as a set of individual keypoints or as a set of objects + (e.g., polygons or polygonal chains) consisting of a fixed number of keypoints of shape ``[..., 2]``. + When groups of keypoints are passed (i.e., an at least 3-dimensional tensor), this transform + will only remove entire groups, not individual keypoints within a group. + + Args: + labels_getter (callable or str or None, optional): indicates how to identify the labels in the input + (or anything else that needs to be sanitized along with the keypoints). + If set to the string ``"default"``, this will try to find a "labels" key in the input (case-insensitive), if + the input is a dict or it is a tuple whose second element is a dict. + + It can also be a callable that takes the same input as the transform, and returns either: + + - A single tensor (the labels) + - A tuple/list of tensors, each of which will be subject to the same sanitization as the keypoints. + + If ``labels_getter`` is None (the default), then only keypoints are sanitized. + """ + + def __init__( + self, + labels_getter: Union[Callable[[Any], Any], str, None] = None, + ) -> None: + super().__init__() + self.labels_getter = labels_getter + self._labels_getter = _parse_labels_getter(labels_getter) + + def forward(self, *inputs: Any) -> Any: + inputs = inputs if len(inputs) > 1 else inputs[0] + + labels = self._labels_getter(inputs) + if labels is not None: + msg = "The labels in the input to forward() must be a tensor or None, got {type} instead." + if isinstance(labels, torch.Tensor): + labels = (labels,) + elif isinstance(labels, (tuple, list)): + for entry in labels: + if not isinstance(entry, torch.Tensor): + # TODO: we don't need to enforce tensors, just that entries are indexable as t[bool_mask] + raise ValueError(msg.format(type=type(entry))) + else: + raise ValueError(msg.format(type=type(labels))) + + flat_inputs, spec = tree_flatten(inputs) + points = get_keypoints(flat_inputs) + + if labels is not None: + for label in labels: + if points.shape[0] != label.shape[0]: + raise ValueError( + f"Number of kepyoints (shape={points.shape}) must match the number of labels." + f"Found labels with shape={label.shape})." + ) + + valid = F._misc._get_sanitize_keypoints_mask( + points, + canvas_size=points.canvas_size, + ) + + params = dict(valid=valid, labels=labels) + flat_outputs = [self.transform(inpt, params) for inpt in flat_inputs] + + return tree_unflatten(flat_outputs, spec) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + is_label = params["labels"] is not None and any(inpt is label for label in params["labels"]) + is_keypoints = isinstance(inpt, tv_tensors.KeyPoints) + + if not (is_label or is_keypoints): + return inpt + + output = inpt[params["valid"]] + + if is_label: + return output + else: + return tv_tensors.wrap(output, like=inpt) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_temporal.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_temporal.py new file mode 100644 index 0000000000000000000000000000000000000000..0642a741e35ae8bb2a3f2b825b7b921fd9548dad --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_temporal.py @@ -0,0 +1,26 @@ +from typing import Any + +import torch +from torchvision.transforms.v2 import functional as F, Transform + + +class UniformTemporalSubsample(Transform): + """Uniformly subsample ``num_samples`` indices from the temporal dimension of the video. + + Videos are expected to be of shape ``[..., T, C, H, W]`` where ``T`` denotes the temporal dimension. + + When ``num_samples`` is larger than the size of temporal dimension of the video, it + will sample frames based on nearest neighbor interpolation. + + Args: + num_samples (int): The number of equispaced samples to be selected + """ + + _transformed_types = (torch.Tensor,) + + def __init__(self, num_samples: int): + super().__init__() + self.num_samples = num_samples + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + return self._call_kernel(F.uniform_temporal_subsample, inpt, self.num_samples) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_transform.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..8fe01ffa2d3513bf3e97b2305de61a973c33f859 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_transform.py @@ -0,0 +1,200 @@ +from __future__ import annotations + +import enum +from typing import Any, Callable + +import PIL.Image +import torch +from torch import nn +from torch.utils._pytree import tree_flatten, tree_unflatten +from torchvision import tv_tensors +from torchvision.transforms.v2._utils import check_type, has_any, is_pure_tensor +from torchvision.utils import _log_api_usage_once + +from .functional._utils import _get_kernel + + +class Transform(nn.Module): + """Base class to implement your own v2 transforms. + + See :ref:`sphx_glr_auto_examples_transforms_plot_custom_transforms.py` for + more details. + """ + + # Class attribute defining transformed types. Other types are passed-through without any transformation + # We support both Types and callables that are able to do further checks on the type of the input. + _transformed_types: tuple[type | Callable[[Any], bool], ...] = (torch.Tensor, PIL.Image.Image) + + def __init__(self) -> None: + super().__init__() + _log_api_usage_once(self) + + def check_inputs(self, flat_inputs: list[Any]) -> None: + pass + + # When v2 was introduced, this method was private and called + # `_get_params()`. Now it's publicly exposed as `make_params()`. It cannot + # be exposed as `get_params()` because there is already a `get_params()` + # methods for v2 transforms: it's the v1's `get_params()` that we have to + # keep in order to guarantee 100% BC with v1. (It's defined in + # __init_subclass__ below). + def make_params(self, flat_inputs: list[Any]) -> dict[str, Any]: + """Method to override for custom transforms. + + See :ref:`sphx_glr_auto_examples_transforms_plot_custom_transforms.py`""" + return dict() + + def _call_kernel(self, functional: Callable, inpt: Any, *args: Any, **kwargs: Any) -> Any: + kernel = _get_kernel(functional, type(inpt), allow_passthrough=True) + return kernel(inpt, *args, **kwargs) + + def transform(self, inpt: Any, params: dict[str, Any]) -> Any: + """Method to override for custom transforms. + + See :ref:`sphx_glr_auto_examples_transforms_plot_custom_transforms.py`""" + raise NotImplementedError + + def forward(self, *inputs: Any) -> Any: + """Do not override this! Use ``transform()`` instead.""" + flat_inputs, spec = tree_flatten(inputs if len(inputs) > 1 else inputs[0]) + + self.check_inputs(flat_inputs) + + needs_transform_list = self._needs_transform_list(flat_inputs) + params = self.make_params( + [inpt for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) if needs_transform] + ) + + flat_outputs = [ + self.transform(inpt, params) if needs_transform else inpt + for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) + ] + + return tree_unflatten(flat_outputs, spec) + + def _needs_transform_list(self, flat_inputs: list[Any]) -> list[bool]: + # Below is a heuristic on how to deal with pure tensor inputs: + # 1. Pure tensors, i.e. tensors that are not a tv_tensor, are passed through if there is an explicit image + # (`tv_tensors.Image` or `PIL.Image.Image`) or video (`tv_tensors.Video`) in the sample. + # 2. If there is no explicit image or video in the sample, only the first encountered pure tensor is + # transformed as image, while the rest is passed through. The order is defined by the returned `flat_inputs` + # of `tree_flatten`, which recurses depth-first through the input. + # + # This heuristic stems from two requirements: + # 1. We need to keep BC for single input pure tensors and treat them as images. + # 2. We don't want to treat all pure tensors as images, because some datasets like `CelebA` or `Widerface` + # return supplemental numerical data as tensors that cannot be transformed as images. + # + # The heuristic should work well for most people in practice. The only case where it doesn't is if someone + # tries to transform multiple pure tensors at the same time, expecting them all to be treated as images. + # However, this case wasn't supported by transforms v1 either, so there is no BC concern. + + needs_transform_list = [] + transform_pure_tensor = not has_any(flat_inputs, tv_tensors.Image, tv_tensors.Video, PIL.Image.Image) + for inpt in flat_inputs: + needs_transform = True + + if not check_type(inpt, self._transformed_types): + needs_transform = False + elif is_pure_tensor(inpt): + if transform_pure_tensor: + transform_pure_tensor = False + else: + needs_transform = False + needs_transform_list.append(needs_transform) + return needs_transform_list + + def extra_repr(self) -> str: + extra = [] + for name, value in self.__dict__.items(): + if name.startswith("_") or name == "training": + continue + + if not isinstance(value, (bool, int, float, str, tuple, list, enum.Enum)): + continue + + extra.append(f"{name}={value}") + + return ", ".join(extra) + + # This attribute should be set on all transforms that have a v1 equivalent. Doing so enables two things: + # 1. In case the v1 transform has a static `get_params` method, it will also be available under the same name on + # the v2 transform. See `__init_subclass__` for details. + # 2. The v2 transform will be JIT scriptable. See `_extract_params_for_v1_transform` and `__prepare_scriptable__` + # for details. + _v1_transform_cls: type[nn.Module] | None = None + + def __init_subclass__(cls) -> None: + # Since `get_params` is a `@staticmethod`, we have to bind it to the class itself rather than to an instance. + # This method is called after subclassing has happened, i.e. `cls` is the subclass, e.g. `Resize`. + if cls._v1_transform_cls is not None and hasattr(cls._v1_transform_cls, "get_params"): + cls.get_params = staticmethod(cls._v1_transform_cls.get_params) # type: ignore[attr-defined] + + def _extract_params_for_v1_transform(self) -> dict[str, Any]: + # This method is called by `__prepare_scriptable__` to instantiate the equivalent v1 transform from the current + # v2 transform instance. It extracts all available public attributes that are specific to that transform and + # not `nn.Module` in general. + # Overwrite this method on the v2 transform class if the above is not sufficient. For example, this might happen + # if the v2 transform introduced new parameters that are not support by the v1 transform. + common_attrs = nn.Module().__dict__.keys() + params = { + attr: value + for attr, value in self.__dict__.items() + if not attr.startswith("_") and attr not in common_attrs + } + # v1 transforms don't support string interpolation modes, so convert them. + if "interpolation" in params and isinstance(params["interpolation"], str): + from torchvision.transforms import InterpolationMode + + params["interpolation"] = InterpolationMode(params["interpolation"]) + return params + + def __prepare_scriptable__(self) -> nn.Module: + # This method is called early on when `torch.jit.script`'ing an `nn.Module` instance. If it succeeds, the return + # value is used for scripting over the original object that should have been scripted. Since the v1 transforms + # are JIT scriptable, and we made sure that for single image inputs v1 and v2 are equivalent, we just return the + # equivalent v1 transform here. This of course only makes transforms v2 JIT scriptable as long as transforms v1 + # is around. + if self._v1_transform_cls is None: + raise RuntimeError( + f"Transform {type(self).__name__} cannot be JIT scripted. " + "torchscript is only supported for backward compatibility with transforms " + "which are already in torchvision.transforms. " + "For torchscript support (on tensors only), you can use the functional API instead." + ) + + return self._v1_transform_cls(**self._extract_params_for_v1_transform()) + + +class _RandomApplyTransform(Transform): + def __init__(self, p: float = 0.5) -> None: + if not (0.0 <= p <= 1.0): + raise ValueError("`p` should be a floating point value in the interval [0.0, 1.0].") + + super().__init__() + self.p = p + + def forward(self, *inputs: Any) -> Any: + # We need to almost duplicate `Transform.forward()` here since we always want to check the inputs, but return + # early afterwards in case the random check triggers. The same result could be achieved by calling + # `super().forward()` after the random check, but that would call `self.check_inputs` twice. + + inputs = inputs if len(inputs) > 1 else inputs[0] + flat_inputs, spec = tree_flatten(inputs) + + self.check_inputs(flat_inputs) + + if torch.rand(1) >= self.p: + return inputs + + needs_transform_list = self._needs_transform_list(flat_inputs) + params = self.make_params( + [inpt for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) if needs_transform] + ) + + flat_outputs = [ + self.transform(inpt, params) if needs_transform else inpt + for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) + ] + + return tree_unflatten(flat_outputs, spec) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_type_conversion.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_type_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..7cac62868b9b5331e4760e56dde284fa40929d14 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_type_conversion.py @@ -0,0 +1,92 @@ +from typing import Any, Optional, Union + +import numpy as np +import PIL.Image +import torch + +from torchvision import tv_tensors +from torchvision.transforms.v2 import functional as F, Transform + +from torchvision.transforms.v2._utils import is_pure_tensor + + +class PILToTensor(Transform): + """Convert a PIL Image to a tensor of the same type - this does not scale values. + + This transform does not support torchscript. + + Convert a PIL Image with H height, W width, and C channels to a Tensor of shape (C x H x W). + + Example: + >>> from PIL import Image + >>> from torchvision.transforms import v2 + >>> img = Image.new("RGB", (320, 240)) # size (W=320, H=240) + >>> tensor = v2.PILToTensor()(img) + >>> print(tensor.shape) + torch.Size([3, 240, 320]) + """ + + _transformed_types = (PIL.Image.Image,) + + def transform(self, inpt: PIL.Image.Image, params: dict[str, Any]) -> torch.Tensor: + return F.pil_to_tensor(inpt) + + +class ToImage(Transform): + """Convert a tensor, ndarray, or PIL Image to :class:`~torchvision.tv_tensors.Image` + ; this does not scale values. + + This transform does not support torchscript. + """ + + _transformed_types = (is_pure_tensor, PIL.Image.Image, np.ndarray) + + def transform( + self, inpt: Union[torch.Tensor, PIL.Image.Image, np.ndarray], params: dict[str, Any] + ) -> tv_tensors.Image: + return F.to_image(inpt) + + +class ToPILImage(Transform): + """Convert a tensor or an ndarray to PIL Image + + This transform does not support torchscript. + + Converts a torch.*Tensor of shape C x H x W or a numpy ndarray of shape + H x W x C to a PIL Image while adjusting the value range depending on the ``mode``. + + Args: + mode (`PIL.Image mode`_): color space and pixel depth of input data (optional). + If ``mode`` is ``None`` (default) there are some assumptions made about the input data: + + - If the input has 4 channels, the ``mode`` is assumed to be ``RGBA``. + - If the input has 3 channels, the ``mode`` is assumed to be ``RGB``. + - If the input has 2 channels, the ``mode`` is assumed to be ``LA``. + - If the input has 1 channel, the ``mode`` is determined by the data type (i.e ``int``, ``float``, + ``short``). + + .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes + """ + + _transformed_types = (is_pure_tensor, tv_tensors.Image, np.ndarray) + + def __init__(self, mode: Optional[str] = None) -> None: + super().__init__() + self.mode = mode + + def transform( + self, inpt: Union[torch.Tensor, PIL.Image.Image, np.ndarray], params: dict[str, Any] + ) -> PIL.Image.Image: + return F.to_pil_image(inpt, mode=self.mode) + + +class ToPureTensor(Transform): + """Convert all TVTensors to pure tensors, removing associated metadata (if any). + + This doesn't scale or change the values, only the type. + """ + + _transformed_types = (tv_tensors.TVTensor,) + + def transform(self, inpt: Any, params: dict[str, Any]) -> torch.Tensor: + return inpt.as_subclass(torch.Tensor) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_utils.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bb6051b4e61c02c004c01e6610f8a5f584046e87 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/_utils.py @@ -0,0 +1,242 @@ +from __future__ import annotations + +import collections.abc +import numbers +from collections.abc import Sequence +from contextlib import suppress + +from typing import Any, Callable, Literal + +import PIL.Image +import torch + +from torchvision import tv_tensors + +from torchvision._utils import sequence_to_str + +from torchvision.transforms.transforms import _check_sequence_input, _setup_angle, _setup_size # noqa: F401 +from torchvision.transforms.v2.functional import get_dimensions, get_size, is_pure_tensor +from torchvision.transforms.v2.functional._utils import _FillType, _FillTypeJIT + + +def _setup_number_or_seq(arg: int | float | Sequence[int | float], name: str) -> Sequence[float]: + if not isinstance(arg, (int, float, Sequence)): + raise TypeError(f"{name} should be a number or a sequence of numbers. Got {type(arg)}") + if isinstance(arg, Sequence) and len(arg) not in (1, 2): + raise ValueError(f"If {name} is a sequence its length should be 1 or 2. Got {len(arg)}") + if isinstance(arg, Sequence): + for element in arg: + if not isinstance(element, (int, float)): + raise ValueError(f"{name} should be a sequence of numbers. Got {type(element)}") + + if isinstance(arg, (int, float)): + arg = [float(arg), float(arg)] + elif isinstance(arg, Sequence): + if len(arg) == 1: + arg = [float(arg[0]), float(arg[0])] + else: + arg = [float(arg[0]), float(arg[1])] + return arg + + +def _check_fill_arg(fill: _FillType | dict[type | str, _FillType]) -> None: + if isinstance(fill, dict): + for value in fill.values(): + _check_fill_arg(value) + else: + if fill is not None and not isinstance(fill, (numbers.Number, tuple, list)): + raise TypeError("Got inappropriate fill arg, only Numbers, tuples, lists and dicts are allowed.") + + +def _convert_fill_arg(fill: _FillType) -> _FillTypeJIT: + # Fill = 0 is not equivalent to None, https://github.com/pytorch/vision/issues/6517 + # So, we can't reassign fill to 0 + # if fill is None: + # fill = 0 + if fill is None: + return fill + + if not isinstance(fill, (int, float)): + fill = [float(v) for v in list(fill)] + return fill # type: ignore[return-value] + + +def _setup_fill_arg(fill: _FillType | dict[type | str, _FillType]) -> dict[type | str, _FillTypeJIT]: + _check_fill_arg(fill) + + if isinstance(fill, dict): + for k, v in fill.items(): + fill[k] = _convert_fill_arg(v) + return fill # type: ignore[return-value] + else: + return {"others": _convert_fill_arg(fill)} + + +def _get_fill(fill_dict, inpt_type): + if inpt_type in fill_dict: + return fill_dict[inpt_type] + elif "others" in fill_dict: + return fill_dict["others"] + else: + RuntimeError("This should never happen, please open an issue on the torchvision repo if you hit this.") + + +def _check_padding_arg(padding: int | Sequence[int]) -> None: + + err_msg = f"Padding must be an int or a 1, 2, or 4 element of tuple or list, got {padding}." + if isinstance(padding, (tuple, list)): + if len(padding) not in [1, 2, 4] or not all(isinstance(p, int) for p in padding): + raise ValueError(err_msg) + elif not isinstance(padding, int): + raise ValueError(err_msg) + + +# TODO: let's use torchvision._utils.StrEnum to have the best of both worlds (strings and enums) +# https://github.com/pytorch/vision/issues/6250 +def _check_padding_mode_arg(padding_mode: Literal["constant", "edge", "reflect", "symmetric"]) -> None: + if padding_mode not in ["constant", "edge", "reflect", "symmetric"]: + raise ValueError("Padding mode should be either constant, edge, reflect or symmetric") + + +def _find_labels_default_heuristic(inputs: Any) -> torch.Tensor: + """ + This heuristic covers three cases: + + 1. The input is tuple or list whose second item is a labels tensor. This happens for already batched + classification inputs for MixUp and CutMix (typically after the Dataloder). + 2. The input is a tuple or list whose second item is a dictionary that contains the labels tensor + under a label-like (see below) key. This happens for the inputs of detection models. + 3. The input is a dictionary that is structured as the one from 2. + + What is "label-like" key? We first search for an case-insensitive match of 'labels' inside the keys of the + dictionary. This is the name our detection models expect. If we can't find that, we look for a case-insensitive + match of the term 'label' anywhere inside the key, i.e. 'FooLaBeLBar'. If we can't find that either, the dictionary + contains no "label-like" key. + """ + + if isinstance(inputs, (tuple, list)): + inputs = inputs[1] + + # MixUp, CutMix + if is_pure_tensor(inputs): + return inputs + + if not isinstance(inputs, collections.abc.Mapping): + raise ValueError( + f"When using the default labels_getter, the input passed to forward must be a dictionary or a two-tuple " + f"whose second item is a dictionary or a tensor, but got {inputs} instead." + ) + + candidate_key = None + with suppress(StopIteration): + candidate_key = next(key for key in inputs.keys() if key.lower() == "labels") + if candidate_key is None: + with suppress(StopIteration): + candidate_key = next(key for key in inputs.keys() if "label" in key.lower()) + if candidate_key is None: + raise ValueError( + "Could not infer where the labels are in the sample. Try passing a callable as the labels_getter parameter?" + "If there are no labels in the sample by design, pass labels_getter=None." + ) + + return inputs[candidate_key] + + +def _parse_labels_getter(labels_getter: str | Callable[[Any], Any] | None) -> Callable[[Any], Any]: + if labels_getter == "default": + return _find_labels_default_heuristic + elif callable(labels_getter): + return labels_getter + elif labels_getter is None: + return lambda _: None + else: + raise ValueError(f"labels_getter should either be 'default', a callable, or None, but got {labels_getter}.") + + +def get_bounding_boxes(flat_inputs: list[Any]) -> tv_tensors.BoundingBoxes: + """Return the Bounding Boxes in the input. + + Assumes only one ``BoundingBoxes`` object is present. + """ + # This assumes there is only one bbox per sample as per the general convention + try: + return next(inpt for inpt in flat_inputs if isinstance(inpt, tv_tensors.BoundingBoxes)) + except StopIteration: + raise ValueError("No bounding boxes were found in the sample") + + +def get_keypoints(flat_inputs: list[Any]) -> tv_tensors.KeyPoints: + """Return the keypoints in the input. + + Assumes only one ``KeyPoints`` object is present. + """ + # This assumes there is only one keypoint per sample as per the general convention + try: + return next(inpt for inpt in flat_inputs if isinstance(inpt, tv_tensors.KeyPoints)) + except StopIteration: + raise ValueError("No keypoints were found in the sample") + + +def query_chw(flat_inputs: list[Any]) -> tuple[int, int, int]: + """Return Channel, Height, and Width.""" + chws = { + tuple(get_dimensions(inpt)) + for inpt in flat_inputs + if check_type(inpt, (is_pure_tensor, tv_tensors.Image, PIL.Image.Image, tv_tensors.Video)) + } + if not chws: + raise TypeError("No image or video was found in the sample") + elif len(chws) > 1: + raise ValueError(f"Found multiple CxHxW dimensions in the sample: {sequence_to_str(sorted(chws))}") + c, h, w = chws.pop() + return c, h, w + + +def query_size(flat_inputs: list[Any]) -> tuple[int, int]: + """Return Height and Width.""" + sizes = { + tuple(get_size(inpt)) + for inpt in flat_inputs + if check_type( + inpt, + ( + is_pure_tensor, + tv_tensors.Image, + PIL.Image.Image, + tv_tensors.Video, + tv_tensors.Mask, + tv_tensors.BoundingBoxes, + tv_tensors.KeyPoints, + ), + ) + } + if not sizes: + raise TypeError("No image, video, mask, bounding box of keypoint was found in the sample") + elif len(sizes) > 1: + raise ValueError(f"Found multiple HxW dimensions in the sample: {sequence_to_str(sorted(sizes))}") + h, w = sizes.pop() + return h, w + + +def check_type(obj: Any, types_or_checks: tuple[type | Callable[[Any], bool], ...]) -> bool: + for type_or_check in types_or_checks: + if isinstance(obj, type_or_check) if isinstance(type_or_check, type) else type_or_check(obj): + return True + return False + + +def has_any(flat_inputs: list[Any], *types_or_checks: type | Callable[[Any], bool]) -> bool: + for inpt in flat_inputs: + if check_type(inpt, types_or_checks): + return True + return False + + +def has_all(flat_inputs: list[Any], *types_or_checks: type | Callable[[Any], bool]) -> bool: + for type_or_check in types_or_checks: + for inpt in flat_inputs: + if isinstance(inpt, type_or_check) if isinstance(type_or_check, type) else type_or_check(inpt): + break + else: + return False + return True diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..018affd75e2037bb5504ed6d554f5bbae228d376 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__init__.py @@ -0,0 +1,167 @@ +from torchvision.transforms.functional import InterpolationMode # usort: skip + +from ._utils import is_pure_tensor, register_kernel # usort: skip + +from ._meta import ( + clamp_bounding_boxes, + clamp_keypoints, + convert_bounding_box_format, + get_dimensions_image, + get_dimensions_video, + get_dimensions, + get_num_frames_video, + get_num_frames, + get_image_num_channels, + get_num_channels_image, + get_num_channels_video, + get_num_channels, + get_size_bounding_boxes, + get_size_keypoints, + get_size_image, + get_size_mask, + get_size_video, + get_size, +) # usort: skip + +from ._augment import erase, erase_image, erase_video, jpeg, jpeg_image, jpeg_video +from ._color import ( + adjust_brightness, + adjust_brightness_image, + adjust_brightness_video, + adjust_contrast, + adjust_contrast_image, + adjust_contrast_video, + adjust_gamma, + adjust_gamma_image, + adjust_gamma_video, + adjust_hue, + adjust_hue_image, + adjust_hue_video, + adjust_saturation, + adjust_saturation_image, + adjust_saturation_video, + adjust_sharpness, + adjust_sharpness_image, + adjust_sharpness_video, + autocontrast, + autocontrast_image, + autocontrast_video, + equalize, + equalize_image, + equalize_video, + grayscale_to_rgb, + grayscale_to_rgb_image, + invert, + invert_image, + invert_video, + permute_channels, + permute_channels_image, + permute_channels_video, + posterize, + posterize_image, + posterize_video, + rgb_to_grayscale, + rgb_to_grayscale_image, + solarize, + solarize_image, + solarize_video, + to_grayscale, +) +from ._geometry import ( + affine, + affine_bounding_boxes, + affine_image, + affine_keypoints, + affine_mask, + affine_video, + center_crop, + center_crop_bounding_boxes, + center_crop_image, + center_crop_keypoints, + center_crop_mask, + center_crop_video, + crop, + crop_bounding_boxes, + crop_image, + crop_keypoints, + crop_mask, + crop_video, + elastic, + elastic_bounding_boxes, + elastic_image, + elastic_keypoints, + elastic_mask, + elastic_transform, + elastic_video, + five_crop, + five_crop_image, + five_crop_video, + hflip, # TODO: Consider moving all pure alias definitions at the bottom of the file + horizontal_flip, + horizontal_flip_bounding_boxes, + horizontal_flip_image, + horizontal_flip_keypoints, + horizontal_flip_mask, + horizontal_flip_video, + pad, + pad_bounding_boxes, + pad_image, + pad_keypoints, + pad_mask, + pad_video, + perspective, + perspective_bounding_boxes, + perspective_image, + perspective_keypoints, + perspective_mask, + perspective_video, + resize, + resize_bounding_boxes, + resize_image, + resize_keypoints, + resize_mask, + resize_video, + resized_crop, + resized_crop_bounding_boxes, + resized_crop_image, + resized_crop_keypoints, + resized_crop_mask, + resized_crop_video, + rotate, + rotate_bounding_boxes, + rotate_image, + rotate_keypoints, + rotate_mask, + rotate_video, + ten_crop, + ten_crop_image, + ten_crop_video, + vertical_flip, + vertical_flip_bounding_boxes, + vertical_flip_image, + vertical_flip_keypoints, + vertical_flip_mask, + vertical_flip_video, + vflip, +) +from ._misc import ( + convert_image_dtype, + gaussian_blur, + gaussian_blur_image, + gaussian_blur_video, + gaussian_noise, + gaussian_noise_image, + gaussian_noise_video, + normalize, + normalize_image, + normalize_video, + sanitize_bounding_boxes, + sanitize_keypoints, + to_dtype, + to_dtype_image, + to_dtype_video, +) +from ._temporal import uniform_temporal_subsample, uniform_temporal_subsample_video +from ._type_conversion import pil_to_tensor, to_image, to_pil_image + +from ._deprecated import get_image_size, to_tensor # usort: skip diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..302a3bb85e496b4eeba09e2df8425de82cc3741c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_augment.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_augment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3ec752849f193f5e2cd4e10dbfcfe71f53942b7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_augment.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_color.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_color.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5754a6c9ed5be3fa5fbabea238c646006c511866 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_color.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_deprecated.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_deprecated.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8831d20924f8c70d87465356527471999ab50e6e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_deprecated.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_geometry.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_geometry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04af4d71d52235bd3a2740ff4603cc9d17ce7d8b --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_geometry.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51f897a265f5fe9a0fa5879d183289a2cfd80398f4ef1126d36723085c484560 +size 132885 diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_meta.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_meta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a78af7637ee3e48ff2de655b6be8ccec54da58cb Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_meta.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_misc.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_misc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e25ac7394d4be0b2c12f0d10fd768b6795003c18 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_misc.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_temporal.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_temporal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..323c065a8d70cf79f7654c5648080da2783aba14 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_temporal.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_type_conversion.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_type_conversion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31b609459424cdeb14ba17f4194ead3d745d70e7 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_type_conversion.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8de804800fa0ba86f9a7641b50f49a2a55ccb685 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/__pycache__/_utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_augment.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_augment.py new file mode 100644 index 0000000000000000000000000000000000000000..fc675f7b80cbbd486ba507ad22a18dd3bd2c476d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_augment.py @@ -0,0 +1,106 @@ +import io + +import PIL.Image + +import torch +from torchvision import tv_tensors +from torchvision.io import decode_jpeg, encode_jpeg +from torchvision.transforms.functional import pil_to_tensor, to_pil_image +from torchvision.utils import _log_api_usage_once + +from ._utils import _get_kernel, _register_kernel_internal + + +def erase( + inpt: torch.Tensor, + i: int, + j: int, + h: int, + w: int, + v: torch.Tensor, + inplace: bool = False, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomErase` for details.""" + if torch.jit.is_scripting(): + return erase_image(inpt, i=i, j=j, h=h, w=w, v=v, inplace=inplace) + + _log_api_usage_once(erase) + + kernel = _get_kernel(erase, type(inpt)) + return kernel(inpt, i=i, j=j, h=h, w=w, v=v, inplace=inplace) + + +@_register_kernel_internal(erase, torch.Tensor) +@_register_kernel_internal(erase, tv_tensors.Image) +def erase_image( + image: torch.Tensor, i: int, j: int, h: int, w: int, v: torch.Tensor, inplace: bool = False +) -> torch.Tensor: + if not inplace: + image = image.clone() + + image[..., i : i + h, j : j + w] = v + return image + + +@_register_kernel_internal(erase, PIL.Image.Image) +def _erase_image_pil( + image: PIL.Image.Image, i: int, j: int, h: int, w: int, v: torch.Tensor, inplace: bool = False +) -> PIL.Image.Image: + t_img = pil_to_tensor(image) + output = erase_image(t_img, i=i, j=j, h=h, w=w, v=v, inplace=inplace) + return to_pil_image(output, mode=image.mode) + + +@_register_kernel_internal(erase, tv_tensors.Video) +def erase_video( + video: torch.Tensor, i: int, j: int, h: int, w: int, v: torch.Tensor, inplace: bool = False +) -> torch.Tensor: + return erase_image(video, i=i, j=j, h=h, w=w, v=v, inplace=inplace) + + +def jpeg(image: torch.Tensor, quality: int) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.JPEG` for details.""" + if torch.jit.is_scripting(): + return jpeg_image(image, quality=quality) + + _log_api_usage_once(jpeg) + + kernel = _get_kernel(jpeg, type(image)) + return kernel(image, quality=quality) + + +@_register_kernel_internal(jpeg, torch.Tensor) +@_register_kernel_internal(jpeg, tv_tensors.Image) +def jpeg_image(image: torch.Tensor, quality: int) -> torch.Tensor: + original_shape = image.shape + image = image.reshape((-1,) + image.shape[-3:]) + + if image.shape[0] == 0: # degenerate + return image.reshape(original_shape).clone() + + images = [] + for i in range(image.shape[0]): + # isinstance checks are needed for torchscript. + encoded_image = encode_jpeg(image[i], quality=quality) + assert isinstance(encoded_image, torch.Tensor) + decoded_image = decode_jpeg(encoded_image) + assert isinstance(decoded_image, torch.Tensor) + images.append(decoded_image) + + images = torch.stack(images, dim=0).view(original_shape) + return images + + +@_register_kernel_internal(jpeg, tv_tensors.Video) +def jpeg_video(video: torch.Tensor, quality: int) -> torch.Tensor: + return jpeg_image(video, quality=quality) + + +@_register_kernel_internal(jpeg, PIL.Image.Image) +def _jpeg_image_pil(image: PIL.Image.Image, quality: int) -> PIL.Image.Image: + raw_jpeg = io.BytesIO() + image.save(raw_jpeg, format="JPEG", quality=quality) + + # we need to copy since PIL.Image.open() will return PIL.JpegImagePlugin.JpegImageFile + # which is a sub-class of PIL.Image.Image. this will fail check_transform() test. + return PIL.Image.open(raw_jpeg).copy() diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_color.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_color.py new file mode 100644 index 0000000000000000000000000000000000000000..be254c0d63a0dd6d67c3d3a042a24265a3bd2034 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_color.py @@ -0,0 +1,740 @@ +import PIL.Image +import torch +from torch.nn.functional import conv2d +from torchvision import tv_tensors +from torchvision.transforms import _functional_pil as _FP +from torchvision.transforms._functional_tensor import _max_value + +from torchvision.utils import _log_api_usage_once + +from ._misc import _num_value_bits, to_dtype_image +from ._type_conversion import pil_to_tensor, to_pil_image +from ._utils import _get_kernel, _register_kernel_internal + + +def rgb_to_grayscale(inpt: torch.Tensor, num_output_channels: int = 1) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.Grayscale` for details.""" + if torch.jit.is_scripting(): + return rgb_to_grayscale_image(inpt, num_output_channels=num_output_channels) + + _log_api_usage_once(rgb_to_grayscale) + + kernel = _get_kernel(rgb_to_grayscale, type(inpt)) + return kernel(inpt, num_output_channels=num_output_channels) + + +# `to_grayscale` actually predates `rgb_to_grayscale` in v1, but only handles PIL images. Since `rgb_to_grayscale` is a +# superset in terms of functionality and has the same signature, we alias here to avoid disruption. +to_grayscale = rgb_to_grayscale + + +def _rgb_to_grayscale_image( + image: torch.Tensor, num_output_channels: int = 1, preserve_dtype: bool = True +) -> torch.Tensor: + # TODO: Maybe move the validation that num_output_channels is 1 or 3 to this function instead of callers. + if image.shape[-3] == 1 and num_output_channels == 1: + return image.clone() + if image.shape[-3] == 1 and num_output_channels == 3: + s = [1] * len(image.shape) + s[-3] = 3 + return image.repeat(s) + r, g, b = image.unbind(dim=-3) + l_img = r.mul(0.2989).add_(g, alpha=0.587).add_(b, alpha=0.114) + l_img = l_img.unsqueeze(dim=-3) + if preserve_dtype: + l_img = l_img.to(image.dtype) + if num_output_channels == 3: + l_img = l_img.expand(image.shape) + return l_img + + +@_register_kernel_internal(rgb_to_grayscale, torch.Tensor) +@_register_kernel_internal(rgb_to_grayscale, tv_tensors.Image) +def rgb_to_grayscale_image(image: torch.Tensor, num_output_channels: int = 1) -> torch.Tensor: + if num_output_channels not in (1, 3): + raise ValueError(f"num_output_channels must be 1 or 3, got {num_output_channels}.") + return _rgb_to_grayscale_image(image, num_output_channels=num_output_channels, preserve_dtype=True) + + +@_register_kernel_internal(rgb_to_grayscale, PIL.Image.Image) +def _rgb_to_grayscale_image_pil(image: PIL.Image.Image, num_output_channels: int = 1) -> PIL.Image.Image: + if num_output_channels not in (1, 3): + raise ValueError(f"num_output_channels must be 1 or 3, got {num_output_channels}.") + return _FP.to_grayscale(image, num_output_channels=num_output_channels) + + +def grayscale_to_rgb(inpt: torch.Tensor) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RGB` for details.""" + if torch.jit.is_scripting(): + return grayscale_to_rgb_image(inpt) + + _log_api_usage_once(grayscale_to_rgb) + + kernel = _get_kernel(grayscale_to_rgb, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(grayscale_to_rgb, torch.Tensor) +@_register_kernel_internal(grayscale_to_rgb, tv_tensors.Image) +def grayscale_to_rgb_image(image: torch.Tensor) -> torch.Tensor: + if image.shape[-3] >= 3: + # Image already has RGB channels. We don't need to do anything. + return image + # rgb_to_grayscale can be used to add channels so we reuse that function. + return _rgb_to_grayscale_image(image, num_output_channels=3, preserve_dtype=True) + + +@_register_kernel_internal(grayscale_to_rgb, PIL.Image.Image) +def grayscale_to_rgb_image_pil(image: PIL.Image.Image) -> PIL.Image.Image: + return image.convert(mode="RGB") + + +def _blend(image1: torch.Tensor, image2: torch.Tensor, ratio: float) -> torch.Tensor: + ratio = float(ratio) + fp = image1.is_floating_point() + bound = _max_value(image1.dtype) + output = image1.mul(ratio).add_(image2, alpha=(1.0 - ratio)).clamp_(0, bound) + return output if fp else output.to(image1.dtype) + + +def adjust_brightness(inpt: torch.Tensor, brightness_factor: float) -> torch.Tensor: + """Adjust brightness.""" + + if torch.jit.is_scripting(): + return adjust_brightness_image(inpt, brightness_factor=brightness_factor) + + _log_api_usage_once(adjust_brightness) + + kernel = _get_kernel(adjust_brightness, type(inpt)) + return kernel(inpt, brightness_factor=brightness_factor) + + +@_register_kernel_internal(adjust_brightness, torch.Tensor) +@_register_kernel_internal(adjust_brightness, tv_tensors.Image) +def adjust_brightness_image(image: torch.Tensor, brightness_factor: float) -> torch.Tensor: + if brightness_factor < 0: + raise ValueError(f"brightness_factor ({brightness_factor}) is not non-negative.") + + c = image.shape[-3] + if c not in [1, 3]: + raise TypeError(f"Input image tensor permitted channel values are 1 or 3, but found {c}") + + fp = image.is_floating_point() + bound = _max_value(image.dtype) + output = image.mul(brightness_factor).clamp_(0, bound) + return output if fp else output.to(image.dtype) + + +@_register_kernel_internal(adjust_brightness, PIL.Image.Image) +def _adjust_brightness_image_pil(image: PIL.Image.Image, brightness_factor: float) -> PIL.Image.Image: + return _FP.adjust_brightness(image, brightness_factor=brightness_factor) + + +@_register_kernel_internal(adjust_brightness, tv_tensors.Video) +def adjust_brightness_video(video: torch.Tensor, brightness_factor: float) -> torch.Tensor: + return adjust_brightness_image(video, brightness_factor=brightness_factor) + + +def adjust_saturation(inpt: torch.Tensor, saturation_factor: float) -> torch.Tensor: + """Adjust saturation.""" + if torch.jit.is_scripting(): + return adjust_saturation_image(inpt, saturation_factor=saturation_factor) + + _log_api_usage_once(adjust_saturation) + + kernel = _get_kernel(adjust_saturation, type(inpt)) + return kernel(inpt, saturation_factor=saturation_factor) + + +@_register_kernel_internal(adjust_saturation, torch.Tensor) +@_register_kernel_internal(adjust_saturation, tv_tensors.Image) +def adjust_saturation_image(image: torch.Tensor, saturation_factor: float) -> torch.Tensor: + if saturation_factor < 0: + raise ValueError(f"saturation_factor ({saturation_factor}) is not non-negative.") + + c = image.shape[-3] + if c not in [1, 3]: + raise TypeError(f"Input image tensor permitted channel values are 1 or 3, but found {c}") + + if c == 1: # Match PIL behaviour + return image + + grayscale_image = _rgb_to_grayscale_image(image, num_output_channels=1, preserve_dtype=False) + if not image.is_floating_point(): + grayscale_image = grayscale_image.floor_() + + return _blend(image, grayscale_image, saturation_factor) + + +_adjust_saturation_image_pil = _register_kernel_internal(adjust_saturation, PIL.Image.Image)(_FP.adjust_saturation) + + +@_register_kernel_internal(adjust_saturation, tv_tensors.Video) +def adjust_saturation_video(video: torch.Tensor, saturation_factor: float) -> torch.Tensor: + return adjust_saturation_image(video, saturation_factor=saturation_factor) + + +def adjust_contrast(inpt: torch.Tensor, contrast_factor: float) -> torch.Tensor: + """See :class:`~torchvision.transforms.RandomAutocontrast`""" + if torch.jit.is_scripting(): + return adjust_contrast_image(inpt, contrast_factor=contrast_factor) + + _log_api_usage_once(adjust_contrast) + + kernel = _get_kernel(adjust_contrast, type(inpt)) + return kernel(inpt, contrast_factor=contrast_factor) + + +@_register_kernel_internal(adjust_contrast, torch.Tensor) +@_register_kernel_internal(adjust_contrast, tv_tensors.Image) +def adjust_contrast_image(image: torch.Tensor, contrast_factor: float) -> torch.Tensor: + if contrast_factor < 0: + raise ValueError(f"contrast_factor ({contrast_factor}) is not non-negative.") + + c = image.shape[-3] + if c not in [1, 3]: + raise TypeError(f"Input image tensor permitted channel values are 1 or 3, but found {c}") + fp = image.is_floating_point() + if c == 3: + grayscale_image = _rgb_to_grayscale_image(image, num_output_channels=1, preserve_dtype=False) + if not fp: + grayscale_image = grayscale_image.floor_() + else: + grayscale_image = image if fp else image.to(torch.float32) + mean = torch.mean(grayscale_image, dim=(-3, -2, -1), keepdim=True) + return _blend(image, mean, contrast_factor) + + +_adjust_contrast_image_pil = _register_kernel_internal(adjust_contrast, PIL.Image.Image)(_FP.adjust_contrast) + + +@_register_kernel_internal(adjust_contrast, tv_tensors.Video) +def adjust_contrast_video(video: torch.Tensor, contrast_factor: float) -> torch.Tensor: + return adjust_contrast_image(video, contrast_factor=contrast_factor) + + +def adjust_sharpness(inpt: torch.Tensor, sharpness_factor: float) -> torch.Tensor: + """See :class:`~torchvision.transforms.RandomAdjustSharpness`""" + if torch.jit.is_scripting(): + return adjust_sharpness_image(inpt, sharpness_factor=sharpness_factor) + + _log_api_usage_once(adjust_sharpness) + + kernel = _get_kernel(adjust_sharpness, type(inpt)) + return kernel(inpt, sharpness_factor=sharpness_factor) + + +@_register_kernel_internal(adjust_sharpness, torch.Tensor) +@_register_kernel_internal(adjust_sharpness, tv_tensors.Image) +def adjust_sharpness_image(image: torch.Tensor, sharpness_factor: float) -> torch.Tensor: + num_channels, height, width = image.shape[-3:] + if num_channels not in (1, 3): + raise TypeError(f"Input image tensor can have 1 or 3 channels, but found {num_channels}") + + if sharpness_factor < 0: + raise ValueError(f"sharpness_factor ({sharpness_factor}) is not non-negative.") + + if image.numel() == 0 or height <= 2 or width <= 2: + return image + + bound = _max_value(image.dtype) + fp = image.is_floating_point() + shape = image.shape + + if image.ndim > 4: + image = image.reshape(-1, num_channels, height, width) + needs_unsquash = True + else: + needs_unsquash = False + + # The following is a normalized 3x3 kernel with 1s in the edges and a 5 in the middle. + kernel_dtype = image.dtype if fp else torch.float32 + a, b = 1.0 / 13.0, 5.0 / 13.0 + kernel = torch.tensor([[a, a, a], [a, b, a], [a, a, a]], dtype=kernel_dtype, device=image.device) + kernel = kernel.expand(num_channels, 1, 3, 3) + + # We copy and cast at the same time to avoid modifications on the original data + output = image.to(dtype=kernel_dtype, copy=True) + blurred_degenerate = conv2d(output, kernel, groups=num_channels) + if not fp: + # it is better to round before cast + blurred_degenerate = blurred_degenerate.round_() + + # Create a view on the underlying output while pointing at the same data. We do this to avoid indexing twice. + view = output[..., 1:-1, 1:-1] + + # We speed up blending by minimizing flops and doing in-place. The 2 blend options are mathematically equivalent: + # x+(1-r)*(y-x) = x + (1-r)*y - (1-r)*x = x*r + y*(1-r) + view.add_(blurred_degenerate.sub_(view), alpha=(1.0 - sharpness_factor)) + + # The actual data of output have been modified by the above. We only need to clamp and cast now. + output = output.clamp_(0, bound) + if not fp: + output = output.to(image.dtype) + + if needs_unsquash: + output = output.reshape(shape) + + return output + + +_adjust_sharpness_image_pil = _register_kernel_internal(adjust_sharpness, PIL.Image.Image)(_FP.adjust_sharpness) + + +@_register_kernel_internal(adjust_sharpness, tv_tensors.Video) +def adjust_sharpness_video(video: torch.Tensor, sharpness_factor: float) -> torch.Tensor: + return adjust_sharpness_image(video, sharpness_factor=sharpness_factor) + + +def adjust_hue(inpt: torch.Tensor, hue_factor: float) -> torch.Tensor: + """Adjust hue""" + if torch.jit.is_scripting(): + return adjust_hue_image(inpt, hue_factor=hue_factor) + + _log_api_usage_once(adjust_hue) + + kernel = _get_kernel(adjust_hue, type(inpt)) + return kernel(inpt, hue_factor=hue_factor) + + +def _rgb_to_hsv(image: torch.Tensor) -> torch.Tensor: + r, g, _ = image.unbind(dim=-3) + + # Implementation is based on + # https://github.com/python-pillow/Pillow/blob/4174d4267616897df3746d315d5a2d0f82c656ee/src/libImaging/Convert.c#L330 + minc, maxc = torch.aminmax(image, dim=-3) + + # The algorithm erases S and H channel where `maxc = minc`. This avoids NaN + # from happening in the results, because + # + S channel has division by `maxc`, which is zero only if `maxc = minc` + # + H channel has division by `(maxc - minc)`. + # + # Instead of overwriting NaN afterwards, we just prevent it from occurring so + # we don't need to deal with it in case we save the NaN in a buffer in + # backprop, if it is ever supported, but it doesn't hurt to do so. + eqc = maxc == minc + + channels_range = maxc - minc + # Since `eqc => channels_range = 0`, replacing denominator with 1 when `eqc` is fine. + ones = torch.ones_like(maxc) + s = channels_range / torch.where(eqc, ones, maxc) + # Note that `eqc => maxc = minc = r = g = b`. So the following calculation + # of `h` would reduce to `bc - gc + 2 + rc - bc + 4 + rc - bc = 6` so it + # would not matter what values `rc`, `gc`, and `bc` have here, and thus + # replacing denominator with 1 when `eqc` is fine. + channels_range_divisor = torch.where(eqc, ones, channels_range).unsqueeze_(dim=-3) + rc, gc, bc = ((maxc.unsqueeze(dim=-3) - image) / channels_range_divisor).unbind(dim=-3) + + mask_maxc_neq_r = maxc != r + mask_maxc_eq_g = maxc == g + + hg = rc.add(2.0).sub_(bc).mul_(mask_maxc_eq_g & mask_maxc_neq_r) + hr = bc.sub_(gc).mul_(~mask_maxc_neq_r) + hb = gc.add_(4.0).sub_(rc).mul_(mask_maxc_neq_r.logical_and_(mask_maxc_eq_g.logical_not_())) + + h = hr.add_(hg).add_(hb) + h = h.mul_(1.0 / 6.0).add_(1.0).fmod_(1.0) + return torch.stack((h, s, maxc), dim=-3) + + +def _hsv_to_rgb(img: torch.Tensor) -> torch.Tensor: + h, s, v = img.unbind(dim=-3) + h6 = h.mul(6) + i = torch.floor(h6) + f = h6.sub_(i) + i = i.to(dtype=torch.int32) + + sxf = s * f + one_minus_s = 1.0 - s + q = (1.0 - sxf).mul_(v).clamp_(0.0, 1.0) + t = sxf.add_(one_minus_s).mul_(v).clamp_(0.0, 1.0) + p = one_minus_s.mul_(v).clamp_(0.0, 1.0) + i.remainder_(6) + + vpqt = torch.stack((v, p, q, t), dim=-3) + + # vpqt -> rgb mapping based on i + select = torch.tensor([[0, 2, 1, 1, 3, 0], [3, 0, 0, 2, 1, 1], [1, 1, 3, 0, 0, 2]], dtype=torch.long) + select = select.to(device=img.device, non_blocking=True) + + select = select[:, i] + if select.ndim > 3: + # if input.shape is (B, ..., C, H, W) then + # select.shape is (C, B, ..., H, W) + # thus we move C axis to get (B, ..., C, H, W) + select = select.moveaxis(0, -3) + + return vpqt.gather(-3, select) + + +@_register_kernel_internal(adjust_hue, torch.Tensor) +@_register_kernel_internal(adjust_hue, tv_tensors.Image) +def adjust_hue_image(image: torch.Tensor, hue_factor: float) -> torch.Tensor: + if not (-0.5 <= hue_factor <= 0.5): + raise ValueError(f"hue_factor ({hue_factor}) is not in [-0.5, 0.5].") + + c = image.shape[-3] + if c not in [1, 3]: + raise TypeError(f"Input image tensor permitted channel values are 1 or 3, but found {c}") + + if c == 1: # Match PIL behaviour + return image + + if image.numel() == 0: + # exit earlier on empty images + return image + + orig_dtype = image.dtype + image = to_dtype_image(image, torch.float32, scale=True) + + image = _rgb_to_hsv(image) + h, s, v = image.unbind(dim=-3) + h.add_(hue_factor).remainder_(1.0) + image = torch.stack((h, s, v), dim=-3) + image_hue_adj = _hsv_to_rgb(image) + + return to_dtype_image(image_hue_adj, orig_dtype, scale=True) + + +_adjust_hue_image_pil = _register_kernel_internal(adjust_hue, PIL.Image.Image)(_FP.adjust_hue) + + +@_register_kernel_internal(adjust_hue, tv_tensors.Video) +def adjust_hue_video(video: torch.Tensor, hue_factor: float) -> torch.Tensor: + return adjust_hue_image(video, hue_factor=hue_factor) + + +def adjust_gamma(inpt: torch.Tensor, gamma: float, gain: float = 1) -> torch.Tensor: + """Adjust gamma.""" + if torch.jit.is_scripting(): + return adjust_gamma_image(inpt, gamma=gamma, gain=gain) + + _log_api_usage_once(adjust_gamma) + + kernel = _get_kernel(adjust_gamma, type(inpt)) + return kernel(inpt, gamma=gamma, gain=gain) + + +@_register_kernel_internal(adjust_gamma, torch.Tensor) +@_register_kernel_internal(adjust_gamma, tv_tensors.Image) +def adjust_gamma_image(image: torch.Tensor, gamma: float, gain: float = 1.0) -> torch.Tensor: + if gamma < 0: + raise ValueError("Gamma should be a non-negative real number") + + # The input image is either assumed to be at [0, 1] scale (if float) or is converted to that scale (if integer). + # Since the gamma is non-negative, the output remains at [0, 1] scale. + if not torch.is_floating_point(image): + output = to_dtype_image(image, torch.float32, scale=True).pow_(gamma) + else: + output = image.pow(gamma) + + if gain != 1.0: + # The clamp operation is needed only if multiplication is performed. It's only when gain != 1, that the scale + # of the output can go beyond [0, 1]. + output = output.mul_(gain).clamp_(0.0, 1.0) + + return to_dtype_image(output, image.dtype, scale=True) + + +_adjust_gamma_image_pil = _register_kernel_internal(adjust_gamma, PIL.Image.Image)(_FP.adjust_gamma) + + +@_register_kernel_internal(adjust_gamma, tv_tensors.Video) +def adjust_gamma_video(video: torch.Tensor, gamma: float, gain: float = 1) -> torch.Tensor: + return adjust_gamma_image(video, gamma=gamma, gain=gain) + + +def posterize(inpt: torch.Tensor, bits: int) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomPosterize` for details.""" + if torch.jit.is_scripting(): + return posterize_image(inpt, bits=bits) + + _log_api_usage_once(posterize) + + kernel = _get_kernel(posterize, type(inpt)) + return kernel(inpt, bits=bits) + + +@_register_kernel_internal(posterize, torch.Tensor) +@_register_kernel_internal(posterize, tv_tensors.Image) +def posterize_image(image: torch.Tensor, bits: int) -> torch.Tensor: + if not isinstance(bits, int) or not 0 <= bits <= 8: + raise TypeError(f"bits must be a positive integer in the range [0, 8], got {bits} instead.") + + if image.is_floating_point(): + levels = 1 << bits + return image.mul(levels).floor_().clamp_(0, levels - 1).mul_(1.0 / levels) + else: + num_value_bits = _num_value_bits(image.dtype) + if bits >= num_value_bits: + return image + + mask = ((1 << bits) - 1) << (num_value_bits - bits) + return image & mask + + +_posterize_image_pil = _register_kernel_internal(posterize, PIL.Image.Image)(_FP.posterize) + + +@_register_kernel_internal(posterize, tv_tensors.Video) +def posterize_video(video: torch.Tensor, bits: int) -> torch.Tensor: + return posterize_image(video, bits=bits) + + +def solarize(inpt: torch.Tensor, threshold: float) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomSolarize` for details.""" + if torch.jit.is_scripting(): + return solarize_image(inpt, threshold=threshold) + + _log_api_usage_once(solarize) + + kernel = _get_kernel(solarize, type(inpt)) + return kernel(inpt, threshold=threshold) + + +@_register_kernel_internal(solarize, torch.Tensor) +@_register_kernel_internal(solarize, tv_tensors.Image) +def solarize_image(image: torch.Tensor, threshold: float) -> torch.Tensor: + if threshold > _max_value(image.dtype): + raise TypeError(f"Threshold should be less or equal the maximum value of the dtype, but got {threshold}") + + return torch.where(image >= threshold, invert_image(image), image) + + +_solarize_image_pil = _register_kernel_internal(solarize, PIL.Image.Image)(_FP.solarize) + + +@_register_kernel_internal(solarize, tv_tensors.Video) +def solarize_video(video: torch.Tensor, threshold: float) -> torch.Tensor: + return solarize_image(video, threshold=threshold) + + +def autocontrast(inpt: torch.Tensor) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomAutocontrast` for details.""" + if torch.jit.is_scripting(): + return autocontrast_image(inpt) + + _log_api_usage_once(autocontrast) + + kernel = _get_kernel(autocontrast, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(autocontrast, torch.Tensor) +@_register_kernel_internal(autocontrast, tv_tensors.Image) +def autocontrast_image(image: torch.Tensor) -> torch.Tensor: + c = image.shape[-3] + if c not in [1, 3]: + raise TypeError(f"Input image tensor permitted channel values are 1 or 3, but found {c}") + + if image.numel() == 0: + # exit earlier on empty images + return image + + bound = _max_value(image.dtype) + fp = image.is_floating_point() + float_image = image if fp else image.to(torch.float32) + + minimum = float_image.amin(dim=(-2, -1), keepdim=True) + maximum = float_image.amax(dim=(-2, -1), keepdim=True) + + eq_idxs = maximum == minimum + inv_scale = maximum.sub_(minimum).mul_(1.0 / bound) + minimum[eq_idxs] = 0.0 + inv_scale[eq_idxs] = 1.0 + + if fp: + diff = float_image.sub(minimum) + else: + diff = float_image.sub_(minimum) + + return diff.div_(inv_scale).clamp_(0, bound).to(image.dtype) + + +_autocontrast_image_pil = _register_kernel_internal(autocontrast, PIL.Image.Image)(_FP.autocontrast) + + +@_register_kernel_internal(autocontrast, tv_tensors.Video) +def autocontrast_video(video: torch.Tensor) -> torch.Tensor: + return autocontrast_image(video) + + +def equalize(inpt: torch.Tensor) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomEqualize` for details.""" + if torch.jit.is_scripting(): + return equalize_image(inpt) + + _log_api_usage_once(equalize) + + kernel = _get_kernel(equalize, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(equalize, torch.Tensor) +@_register_kernel_internal(equalize, tv_tensors.Image) +def equalize_image(image: torch.Tensor) -> torch.Tensor: + if image.numel() == 0: + return image + + # 1. The algorithm below can easily be extended to support arbitrary integer dtypes. However, the histogram that + # would be needed to computed will have at least `torch.iinfo(dtype).max + 1` values. That is perfectly fine for + # `torch.int8`, `torch.uint8`, and `torch.int16`, at least questionable for `torch.int32` and completely + # unfeasible for `torch.int64`. + # 2. Floating point inputs need to be binned for this algorithm. Apart from converting them to an integer dtype, we + # could also use PyTorch's builtin histogram functionality. However, that has its own set of issues: in addition + # to being slow in general, PyTorch's implementation also doesn't support batches. In total, that makes it slower + # and more complicated to implement than a simple conversion and a fast histogram implementation for integers. + # Since we need to convert in most cases anyway and out of the acceptable dtypes mentioned in 1. `torch.uint8` is + # by far the most common, we choose it as base. + output_dtype = image.dtype + image = to_dtype_image(image, torch.uint8, scale=True) + + # The histogram is computed by using the flattened image as index. For example, a pixel value of 127 in the image + # corresponds to adding 1 to index 127 in the histogram. + batch_shape = image.shape[:-2] + flat_image = image.flatten(start_dim=-2).to(torch.long) + hist = flat_image.new_zeros(batch_shape + (256,), dtype=torch.int32) + hist.scatter_add_(dim=-1, index=flat_image, src=hist.new_ones(1).expand_as(flat_image)) + cum_hist = hist.cumsum(dim=-1) + + # The simplest form of lookup-table (LUT) that also achieves histogram equalization is + # `lut = cum_hist / flat_image.shape[-1] * 255` + # However, PIL uses a more elaborate scheme: + # https://github.com/python-pillow/Pillow/blob/eb59cb61d5239ee69cbbf12709a0c6fd7314e6d7/src/PIL/ImageOps.py#L368-L385 + # `lut = ((cum_hist + num_non_max_pixels // (2 * 255)) // num_non_max_pixels) * 255` + + # The last non-zero element in the histogram is the first element in the cumulative histogram with the maximum + # value. Thus, the "max" in `num_non_max_pixels` does not refer to 255 as the maximum value of uint8 images, but + # rather the maximum value in the image, which might be or not be 255. + index = cum_hist.argmax(dim=-1) + num_non_max_pixels = flat_image.shape[-1] - hist.gather(dim=-1, index=index.unsqueeze_(-1)) + + # This is performance optimization that saves us one multiplication later. With this, the LUT computation simplifies + # to `lut = (cum_hist + step // 2) // step` and thus saving the final multiplication by 255 while keeping the + # division count the same. PIL uses the variable name `step` for this, so we keep that for easier comparison. + step = num_non_max_pixels.div_(255, rounding_mode="floor") + + # Although it looks like we could return early if we find `step == 0` like PIL does, that is unfortunately not as + # easy due to our support for batched images. We can only return early if `(step == 0).all()` holds. If it doesn't, + # we have to go through the computation below anyway. Since `step == 0` is an edge case anyway, it makes no sense to + # pay the runtime cost for checking it every time. + valid_equalization = step.ne(0).unsqueeze_(-1) + + # `lut[k]` is computed with `cum_hist[k-1]` with `lut[0] == (step // 2) // step == 0`. Thus, we perform the + # computation only for `lut[1:]` with `cum_hist[:-1]` and add `lut[0] == 0` afterwards. + cum_hist = cum_hist[..., :-1] + ( + cum_hist.add_(step // 2) + # We need the `clamp_`(min=1) call here to avoid zero division since they fail for integer dtypes. This has no + # effect on the returned result of this kernel since images inside the batch with `step == 0` are returned as is + # instead of equalized version. + .div_(step.clamp_(min=1), rounding_mode="floor") + # We need the `clamp_` call here since PILs LUT computation scheme can produce values outside the valid value + # range of uint8 images + .clamp_(0, 255) + ) + lut = cum_hist.to(torch.uint8) + lut = torch.cat([lut.new_zeros(1).expand(batch_shape + (1,)), lut], dim=-1) + equalized_image = lut.gather(dim=-1, index=flat_image).view_as(image) + + output = torch.where(valid_equalization, equalized_image, image) + return to_dtype_image(output, output_dtype, scale=True) + + +_equalize_image_pil = _register_kernel_internal(equalize, PIL.Image.Image)(_FP.equalize) + + +@_register_kernel_internal(equalize, tv_tensors.Video) +def equalize_video(video: torch.Tensor) -> torch.Tensor: + return equalize_image(video) + + +def invert(inpt: torch.Tensor) -> torch.Tensor: + """See :func:`~torchvision.transforms.v2.RandomInvert`.""" + if torch.jit.is_scripting(): + return invert_image(inpt) + + _log_api_usage_once(invert) + + kernel = _get_kernel(invert, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(invert, torch.Tensor) +@_register_kernel_internal(invert, tv_tensors.Image) +def invert_image(image: torch.Tensor) -> torch.Tensor: + if image.is_floating_point(): + return 1.0 - image + elif image.dtype == torch.uint8: + return image.bitwise_not() + else: # signed integer dtypes + # We can't use `Tensor.bitwise_not` here, since we want to retain the leading zero bit that encodes the sign + return image.bitwise_xor((1 << _num_value_bits(image.dtype)) - 1) + + +_invert_image_pil = _register_kernel_internal(invert, PIL.Image.Image)(_FP.invert) + + +@_register_kernel_internal(invert, tv_tensors.Video) +def invert_video(video: torch.Tensor) -> torch.Tensor: + return invert_image(video) + + +def permute_channels(inpt: torch.Tensor, permutation: list[int]) -> torch.Tensor: + """Permute the channels of the input according to the given permutation. + + This function supports plain :class:`~torch.Tensor`'s, :class:`PIL.Image.Image`'s, and + :class:`torchvision.tv_tensors.Image` and :class:`torchvision.tv_tensors.Video`. + + Example: + >>> rgb_image = torch.rand(3, 256, 256) + >>> bgr_image = F.permute_channels(rgb_image, permutation=[2, 1, 0]) + + Args: + permutation (List[int]): Valid permutation of the input channel indices. The index of the element determines the + channel index in the input and the value determines the channel index in the output. For example, + ``permutation=[2, 0 , 1]`` + + - takes ``ìnpt[..., 0, :, :]`` and puts it at ``output[..., 2, :, :]``, + - takes ``ìnpt[..., 1, :, :]`` and puts it at ``output[..., 0, :, :]``, and + - takes ``ìnpt[..., 2, :, :]`` and puts it at ``output[..., 1, :, :]``. + + Raises: + ValueError: If ``len(permutation)`` doesn't match the number of channels in the input. + """ + if torch.jit.is_scripting(): + return permute_channels_image(inpt, permutation=permutation) + + _log_api_usage_once(permute_channels) + + kernel = _get_kernel(permute_channels, type(inpt)) + return kernel(inpt, permutation=permutation) + + +@_register_kernel_internal(permute_channels, torch.Tensor) +@_register_kernel_internal(permute_channels, tv_tensors.Image) +def permute_channels_image(image: torch.Tensor, permutation: list[int]) -> torch.Tensor: + shape = image.shape + num_channels, height, width = shape[-3:] + + if len(permutation) != num_channels: + raise ValueError( + f"Length of permutation does not match number of channels: " f"{len(permutation)} != {num_channels}" + ) + + if image.numel() == 0: + return image + + image = image.reshape(-1, num_channels, height, width) + image = image[:, permutation, :, :] + return image.reshape(shape) + + +@_register_kernel_internal(permute_channels, PIL.Image.Image) +def _permute_channels_image_pil(image: PIL.Image.Image, permutation: list[int]) -> PIL.Image.Image: + return to_pil_image(permute_channels_image(pil_to_tensor(image), permutation=permutation)) + + +@_register_kernel_internal(permute_channels, tv_tensors.Video) +def permute_channels_video(video: torch.Tensor, permutation: list[int]) -> torch.Tensor: + return permute_channels_image(video, permutation=permutation) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_deprecated.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_deprecated.py new file mode 100644 index 0000000000000000000000000000000000000000..3131b5e8c495ec763ccc822a43e19133eb5fd3ba --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_deprecated.py @@ -0,0 +1,24 @@ +import warnings +from typing import Any + +import torch + +from torchvision.transforms import functional as _F + + +@torch.jit.unused +def to_tensor(inpt: Any) -> torch.Tensor: + """[DEPREACTED] Use to_image() and to_dtype() instead.""" + warnings.warn( + "The function `to_tensor(...)` is deprecated and will be removed in a future release. " + "Instead, please use `to_image(...)` followed by `to_dtype(..., dtype=torch.float32, scale=True)`." + ) + return _F.to_tensor(inpt) + + +def get_image_size(inpt: torch.Tensor) -> list[int]: + warnings.warn( + "The function `get_image_size(...)` is deprecated and will be removed in a future release. " + "Instead, please use `get_size(...)` which returns `[h, w]` instead of `[w, h]`." + ) + return _F.get_image_size(inpt) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_geometry.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..3ebf208b1a1a64fd4112b37221b815b7018f4dee --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_geometry.py @@ -0,0 +1,3041 @@ +import math +import numbers +import platform +import warnings +from collections.abc import Sequence +from typing import Any, Optional, Union + +import PIL.Image +import torch +from torch.nn.functional import grid_sample, interpolate, pad as torch_pad + +from torchvision import tv_tensors +from torchvision.transforms import _functional_pil as _FP +from torchvision.transforms._functional_tensor import _pad_symmetric +from torchvision.transforms.functional import ( + _compute_resized_output_size as __compute_resized_output_size, + _get_perspective_coeffs, + _interpolation_modes_from_int, + InterpolationMode, + pil_modes_mapping, + pil_to_tensor, + to_pil_image, +) +from torchvision.tv_tensors._bounding_boxes import CLAMPING_MODE_TYPE + +from torchvision.utils import _log_api_usage_once + +from ._meta import _get_size_image_pil, clamp_bounding_boxes, convert_bounding_box_format + +from ._utils import _FillTypeJIT, _get_kernel, _register_five_ten_crop_kernel_internal, _register_kernel_internal + + +_INTERPOLATION_STRING_TO_MODE: dict[str, InterpolationMode] = {m.value: m for m in InterpolationMode} + + +def _check_interpolation(interpolation: Union[str, InterpolationMode, int]) -> InterpolationMode: + if not torch.jit.is_scripting() and isinstance(interpolation, str): + if interpolation not in _INTERPOLATION_STRING_TO_MODE: + raise ValueError( + f"Invalid interpolation mode: '{interpolation}'. " + f"Supported string values are: {list(_INTERPOLATION_STRING_TO_MODE.keys())}." + ) + return _INTERPOLATION_STRING_TO_MODE[interpolation] + if isinstance(interpolation, int): + interpolation = _interpolation_modes_from_int(interpolation) + elif not isinstance(interpolation, InterpolationMode): + raise ValueError( + f"Argument interpolation should be an `InterpolationMode` or a corresponding Pillow integer constant, " + f"but got {interpolation}." + ) + return interpolation + + +def horizontal_flip(inpt: torch.Tensor) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomHorizontalFlip` for details.""" + if torch.jit.is_scripting(): + return horizontal_flip_image(inpt) + + _log_api_usage_once(horizontal_flip) + + kernel = _get_kernel(horizontal_flip, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(horizontal_flip, torch.Tensor) +@_register_kernel_internal(horizontal_flip, tv_tensors.Image) +def horizontal_flip_image(image: torch.Tensor) -> torch.Tensor: + return image.flip(-1) + + +@_register_kernel_internal(horizontal_flip, PIL.Image.Image) +def _horizontal_flip_image_pil(image: PIL.Image.Image) -> PIL.Image.Image: + return _FP.hflip(image) + + +@_register_kernel_internal(horizontal_flip, tv_tensors.Mask) +def horizontal_flip_mask(mask: torch.Tensor) -> torch.Tensor: + return horizontal_flip_image(mask) + + +def horizontal_flip_keypoints(keypoints: torch.Tensor, canvas_size: tuple[int, int]): + shape = keypoints.shape + keypoints = keypoints.clone().reshape(-1, 2) + keypoints[..., 0] = keypoints[..., 0].sub_(canvas_size[1] - 1).neg_() + return keypoints.reshape(shape) + + +@_register_kernel_internal(horizontal_flip, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _horizontal_flip_keypoints_dispatch(keypoints: tv_tensors.KeyPoints): + out = horizontal_flip_keypoints(keypoints.as_subclass(torch.Tensor), canvas_size=keypoints.canvas_size) + return tv_tensors.wrap(out, like=keypoints) + + +def horizontal_flip_bounding_boxes( + bounding_boxes: torch.Tensor, format: tv_tensors.BoundingBoxFormat, canvas_size: tuple[int, int] +) -> torch.Tensor: + shape = bounding_boxes.shape + + if tv_tensors.is_rotated_bounding_format(format): + bounding_boxes = ( + bounding_boxes.clone().reshape(-1, 5) + if format != tv_tensors.BoundingBoxFormat.XYXYXYXY + else bounding_boxes.clone().reshape(-1, 8) + ) + else: + bounding_boxes = bounding_boxes.clone().reshape(-1, 4) + + if format == tv_tensors.BoundingBoxFormat.XYXY: + bounding_boxes[:, [2, 0]] = bounding_boxes[:, [0, 2]].sub_(canvas_size[1]).neg_() + elif format == tv_tensors.BoundingBoxFormat.XYWH: + bounding_boxes[:, 0].add_(bounding_boxes[:, 2]).sub_(canvas_size[1]).neg_() + elif format == tv_tensors.BoundingBoxFormat.CXCYWH: + bounding_boxes[:, 0].sub_(canvas_size[1]).neg_() + elif format == tv_tensors.BoundingBoxFormat.XYXYXYXY: + bounding_boxes[:, 0::2].sub_(canvas_size[1]).neg_() + bounding_boxes = bounding_boxes[:, [2, 3, 0, 1, 6, 7, 4, 5]] + elif format == tv_tensors.BoundingBoxFormat.XYWHR: + angle_rad = bounding_boxes[:, 4].mul(torch.pi).div(180) + bounding_boxes[:, 0].add_(bounding_boxes[:, 2].mul(angle_rad.cos())).sub_(canvas_size[1]).neg_() + bounding_boxes[:, 1].sub_(bounding_boxes[:, 2].mul(angle_rad.sin())) + bounding_boxes[:, 4].neg_() + else: # format == tv_tensors.BoundingBoxFormat.CXCYWHR: + bounding_boxes[:, 0].sub_(canvas_size[1]).neg_() + bounding_boxes[:, 4].neg_() + + return bounding_boxes.reshape(shape) + + +@_register_kernel_internal(horizontal_flip, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _horizontal_flip_bounding_boxes_dispatch(inpt: tv_tensors.BoundingBoxes) -> tv_tensors.BoundingBoxes: + output = horizontal_flip_bounding_boxes( + inpt.as_subclass(torch.Tensor), format=inpt.format, canvas_size=inpt.canvas_size + ) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(horizontal_flip, tv_tensors.Video) +def horizontal_flip_video(video: torch.Tensor) -> torch.Tensor: + return horizontal_flip_image(video) + + +def vertical_flip(inpt: torch.Tensor) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomVerticalFlip` for details.""" + if torch.jit.is_scripting(): + return vertical_flip_image(inpt) + + _log_api_usage_once(vertical_flip) + + kernel = _get_kernel(vertical_flip, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(vertical_flip, torch.Tensor) +@_register_kernel_internal(vertical_flip, tv_tensors.Image) +def vertical_flip_image(image: torch.Tensor) -> torch.Tensor: + return image.flip(-2) + + +@_register_kernel_internal(vertical_flip, PIL.Image.Image) +def _vertical_flip_image_pil(image: PIL.Image.Image) -> PIL.Image.Image: + return _FP.vflip(image) + + +@_register_kernel_internal(vertical_flip, tv_tensors.Mask) +def vertical_flip_mask(mask: torch.Tensor) -> torch.Tensor: + return vertical_flip_image(mask) + + +def vertical_flip_keypoints(keypoints: torch.Tensor, canvas_size: tuple[int, int]) -> torch.Tensor: + shape = keypoints.shape + keypoints = keypoints.clone().reshape(-1, 2) + keypoints[..., 1] = keypoints[..., 1].sub_(canvas_size[0] - 1).neg_() + return keypoints.reshape(shape) + + +def vertical_flip_bounding_boxes( + bounding_boxes: torch.Tensor, format: tv_tensors.BoundingBoxFormat, canvas_size: tuple[int, int] +) -> torch.Tensor: + shape = bounding_boxes.shape + + if tv_tensors.is_rotated_bounding_format(format): + bounding_boxes = ( + bounding_boxes.clone().reshape(-1, 5) + if format != tv_tensors.BoundingBoxFormat.XYXYXYXY + else bounding_boxes.clone().reshape(-1, 8) + ) + else: + bounding_boxes = bounding_boxes.clone().reshape(-1, 4) + + if format == tv_tensors.BoundingBoxFormat.XYXY: + bounding_boxes[:, [1, 3]] = bounding_boxes[:, [3, 1]].sub_(canvas_size[0]).neg_() + elif format == tv_tensors.BoundingBoxFormat.XYWH: + bounding_boxes[:, 1].add_(bounding_boxes[:, 3]).sub_(canvas_size[0]).neg_() + elif format == tv_tensors.BoundingBoxFormat.CXCYWH: + bounding_boxes[:, 1].sub_(canvas_size[0]).neg_() + elif format == tv_tensors.BoundingBoxFormat.XYXYXYXY: + bounding_boxes[:, 1::2].sub_(canvas_size[0]).neg_() + bounding_boxes = bounding_boxes[:, [2, 3, 0, 1, 6, 7, 4, 5]] + elif format == tv_tensors.BoundingBoxFormat.XYWHR: + angle_rad = bounding_boxes[:, 4].mul(torch.pi).div(180) + bounding_boxes[:, 1].sub_(bounding_boxes[:, 2].mul(angle_rad.sin())).sub_(canvas_size[0]).neg_() + bounding_boxes[:, 0].add_(bounding_boxes[:, 2].mul(angle_rad.cos())) + bounding_boxes[:, 4].neg_().add_(180) + else: # format == tv_tensors.BoundingBoxFormat.CXCYWHR: + bounding_boxes[:, 1].sub_(canvas_size[0]).neg_() + bounding_boxes[:, 4].neg_().add_(180) + + return bounding_boxes.reshape(shape) + + +@_register_kernel_internal(vertical_flip, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _vertical_flip_keypoints_dispatch(inpt: tv_tensors.KeyPoints) -> tv_tensors.KeyPoints: + output = vertical_flip_keypoints(inpt.as_subclass(torch.Tensor), canvas_size=inpt.canvas_size) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(vertical_flip, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _vertical_flip_bounding_boxes_dispatch(inpt: tv_tensors.BoundingBoxes) -> tv_tensors.BoundingBoxes: + output = vertical_flip_bounding_boxes( + inpt.as_subclass(torch.Tensor), format=inpt.format, canvas_size=inpt.canvas_size + ) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(vertical_flip, tv_tensors.Video) +def vertical_flip_video(video: torch.Tensor) -> torch.Tensor: + return vertical_flip_image(video) + + +# We changed the names to align them with the transforms, i.e. `RandomHorizontalFlip`. Still, `hflip` and `vflip` are +# prevalent and well understood. Thus, we just alias them without deprecating the old names. +hflip = horizontal_flip +vflip = vertical_flip + + +def _compute_resized_output_size( + canvas_size: tuple[int, int], size: Optional[list[int]], max_size: Optional[int] = None +) -> list[int]: + if isinstance(size, int): + size = [size] + elif max_size is not None and size is not None and len(size) != 1: + raise ValueError( + "max_size should only be passed if size is None or specifies the length of the smaller edge, " + "i.e. size should be an int or a sequence of length 1 in torchscript mode." + ) + return __compute_resized_output_size(canvas_size, size=size, max_size=max_size, allow_size_none=True) + + +def resize( + inpt: torch.Tensor, + size: Optional[list[int]], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, + antialias: Optional[bool] = True, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.Resize` for details.""" + if torch.jit.is_scripting(): + return resize_image(inpt, size=size, interpolation=interpolation, max_size=max_size, antialias=antialias) + + _log_api_usage_once(resize) + + kernel = _get_kernel(resize, type(inpt)) + return kernel(inpt, size=size, interpolation=interpolation, max_size=max_size, antialias=antialias) + + +# This is an internal helper method for resize_image. We should put it here instead of keeping it +# inside resize_image due to torchscript. +# uint8 dtype support for bilinear and bicubic is limited to cpu and +# according to our benchmarks on eager, non-AVX x86 CPUs should still prefer u8->f32->interpolate->u8 path for bilinear +def _do_native_uint8_resize_on_cpu(interpolation: InterpolationMode) -> bool: + if interpolation == InterpolationMode.BILINEAR: + if torch.compiler.is_compiling() or torch.jit.is_scripting(): + return True + else: + return torch.backends.cpu.get_cpu_capability() in ("AVX2", "AVX512") or platform.machine() in ( + "aarch64", + "arm64", + ) + + return interpolation == InterpolationMode.BICUBIC or interpolation == InterpolationMode.LANCZOS + + +@_register_kernel_internal(resize, torch.Tensor) +@_register_kernel_internal(resize, tv_tensors.Image) +def resize_image( + image: torch.Tensor, + size: Optional[list[int]], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, + antialias: Optional[bool] = True, +) -> torch.Tensor: + interpolation = _check_interpolation(interpolation) + antialias = False if antialias is None else antialias + align_corners: Optional[bool] = None + if ( + interpolation == InterpolationMode.BILINEAR + or interpolation == InterpolationMode.BICUBIC + or interpolation == InterpolationMode.LANCZOS + ): + align_corners = False + if interpolation == InterpolationMode.LANCZOS and not antialias: + raise ValueError("InterpolationMode.LANCZOS requires antialias=True") + else: + # The default of antialias is True from 0.17, so we don't warn or + # error if other interpolation modes are used. This is documented. + antialias = False + + shape = image.shape + numel = image.numel() + num_channels, old_height, old_width = shape[-3:] + new_height, new_width = _compute_resized_output_size((old_height, old_width), size=size, max_size=max_size) + + if (new_height, new_width) == (old_height, old_width): + return image + elif numel > 0: + dtype = image.dtype + acceptable_dtypes = [torch.float32, torch.float64] + if interpolation == InterpolationMode.NEAREST or interpolation == InterpolationMode.NEAREST_EXACT: + # uint8 dtype can be included for cpu and cuda input if nearest mode + acceptable_dtypes.append(torch.uint8) + elif image.device.type == "cpu": + if _do_native_uint8_resize_on_cpu(interpolation): + acceptable_dtypes.append(torch.uint8) + + image = image.reshape(-1, num_channels, old_height, old_width) + strides = image.stride() + if image.is_contiguous(memory_format=torch.channels_last) and image.shape[0] == 1 and numel != strides[0]: + # There is a weird behaviour in torch core where the output tensor of `interpolate()` can be allocated as + # contiguous even though the input is un-ambiguously channels_last (https://github.com/pytorch/pytorch/issues/68430). + # In particular this happens for the typical torchvision use-case of single CHW images where we fake the batch dim + # to become 1CHW. Below, we restride those tensors to trick torch core into properly allocating the output as + # channels_last, thus preserving the memory format of the input. This is not just for format consistency: + # for uint8 bilinear images, this also avoids an extra copy (re-packing) of the output and saves time. + # TODO: when https://github.com/pytorch/pytorch/issues/68430 is fixed (possibly by https://github.com/pytorch/pytorch/pull/100373), + # we should be able to remove this hack. + new_strides = list(strides) + new_strides[0] = numel + image = image.as_strided((1, num_channels, old_height, old_width), new_strides) + + need_cast = dtype not in acceptable_dtypes + if need_cast: + image = image.to(dtype=torch.float32) + + image = interpolate( + image, + size=[new_height, new_width], + mode=interpolation.value, + align_corners=align_corners, + antialias=antialias, + ) + + if need_cast: + if ( + interpolation == InterpolationMode.BICUBIC or interpolation == InterpolationMode.LANCZOS + ) and dtype == torch.uint8: + # This path is hit on non-AVX archs, or on GPU. + image = image.clamp_(min=0, max=255) + if dtype in (torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64): + image = image.round_() + image = image.to(dtype=dtype) + + return image.reshape(shape[:-3] + (num_channels, new_height, new_width)) + + +def _resize_image_pil( + image: PIL.Image.Image, + size: Union[Sequence[int], int], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, +) -> PIL.Image.Image: + old_height, old_width = image.height, image.width + new_height, new_width = _compute_resized_output_size( + (old_height, old_width), + size=size, # type: ignore[arg-type] + max_size=max_size, + ) + + interpolation = _check_interpolation(interpolation) + + if (new_height, new_width) == (old_height, old_width): + return image + + return image.resize((new_width, new_height), resample=pil_modes_mapping[interpolation]) + + +@_register_kernel_internal(resize, PIL.Image.Image) +def __resize_image_pil_dispatch( + image: PIL.Image.Image, + size: Union[Sequence[int], int], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, + antialias: Optional[bool] = True, +) -> PIL.Image.Image: + if antialias is False: + warnings.warn("Anti-alias option is always applied for PIL Image input. Argument antialias is ignored.") + return _resize_image_pil(image, size=size, interpolation=interpolation, max_size=max_size) + + +def resize_mask( + mask: torch.Tensor, + size: Optional[list[int]], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, +) -> torch.Tensor: + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + interpolation = _check_interpolation(interpolation) + # Masks only support nearest-neighbor interpolations. Any other mode is + # silently coerced to NEAREST so the historical behavior of ignoring the + # signature-level default (BILINEAR) is preserved. + if interpolation != InterpolationMode.NEAREST and interpolation != InterpolationMode.NEAREST_EXACT: + interpolation = InterpolationMode.NEAREST + + output = resize_image(mask, size=size, interpolation=interpolation, max_size=max_size) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +@_register_kernel_internal(resize, tv_tensors.Mask, tv_tensor_wrapper=False) +def _resize_mask_dispatch( + inpt: tv_tensors.Mask, + size: list[int], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, + **kwargs: Any, +) -> tv_tensors.Mask: + output = resize_mask(inpt.as_subclass(torch.Tensor), size, interpolation=interpolation, max_size=max_size) + return tv_tensors.wrap(output, like=inpt) + + +def resize_keypoints( + keypoints: torch.Tensor, + size: Optional[list[int]], + canvas_size: tuple[int, int], + max_size: Optional[int] = None, +): + old_height, old_width = canvas_size + new_height, new_width = _compute_resized_output_size(canvas_size, size=size, max_size=max_size) + + if (new_height, new_width) == (old_height, old_width): + return keypoints, canvas_size + + w_ratio = new_width / old_width + h_ratio = new_height / old_height + ratios = torch.tensor([w_ratio, h_ratio], device=keypoints.device) + keypoints = keypoints.mul(ratios).to(keypoints.dtype) + + return keypoints, (new_height, new_width) + + +@_register_kernel_internal(resize, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _resize_keypoints_dispatch( + keypoints: tv_tensors.KeyPoints, + size: Optional[list[int]], + max_size: Optional[int] = None, + **kwargs: Any, +) -> tv_tensors.KeyPoints: + out, canvas_size = resize_keypoints( + keypoints.as_subclass(torch.Tensor), + size, + canvas_size=keypoints.canvas_size, + max_size=max_size, + ) + return tv_tensors.wrap(out, like=keypoints, canvas_size=canvas_size) + + +def _parallelogram_to_bounding_boxes(parallelogram: torch.Tensor) -> torch.Tensor: + """ + Convert a parallelogram to a rectangle while keeping two points unchanged. + This function transforms a parallelogram represented by 8 coordinates (4 points) into a rectangle. + The two diagonally opposed points of the parallelogram forming the longest diagonal remain fixed. + The other points are adjusted to form a proper rectangle. + + Note: + This function is not applied in-place and will return a copy of the input tensor. + + Args: + parallelogram (torch.Tensor): Tensor of shape (..., 8) containing coordinates of parallelograms. + Format is [x1, y1, x2, y2, x3, y3, x4, y4]. + + Returns: + torch.Tensor: Tensor of same shape as input containing the rectangle coordinates. + The output maintains the same dtype as the input. + """ + original_shape = parallelogram.shape + dtype = parallelogram.dtype + acceptable_dtypes = [torch.float32, torch.float64] + need_cast = dtype not in acceptable_dtypes + if need_cast: + # Up-case to avoid overflow for square operations + parallelogram = parallelogram.to(torch.float32) + + x1, y1, x2, y2, x3, y3, x4, y4 = parallelogram.unbind(-1) + cx = (x1 + x3) / 2 + cy = (y1 + y3) / 2 + + # Calculate width, height, and rotation angle of the parallelogram + wp = torch.sqrt((x2 - x1).pow(2) + (y2 - y1).pow(2)) + hp = torch.sqrt((x4 - x1).pow(2) + (y4 - y1).pow(2)) + r12 = torch.atan2(y1 - y2, x2 - x1) + r14 = torch.atan2(y1 - y4, x4 - x1) + r_rad = r12 - r14 + sign = torch.where(r_rad > torch.pi / 2, -1, 1) + cos, sin = r_rad.cos(), r_rad.sin() + + # Calculate width, height, and rotation angle of the rectangle + w = torch.where(wp < hp, wp * sin, wp + hp * cos * sign) + h = torch.where(wp > hp, hp * sin, hp + wp * cos * sign) + r_rad = torch.where(hp > wp, r14 + torch.pi / 2, r12) + cos, sin = r_rad.cos(), r_rad.sin() + + x1 = cx - w / 2 * cos - h / 2 * sin + y1 = cy - h / 2 * cos + w / 2 * sin + x2 = cx + w / 2 * cos - h / 2 * sin + y2 = cy - h / 2 * cos - w / 2 * sin + x3 = cx + w / 2 * cos + h / 2 * sin + y3 = cy + h / 2 * cos - w / 2 * sin + x4 = cx - w / 2 * cos + h / 2 * sin + y4 = cy + h / 2 * cos + w / 2 * sin + out_boxes = torch.stack((x1, y1, x2, y2, x3, y3, x4, y4), dim=-1).reshape(original_shape) + + if need_cast: + out_boxes = out_boxes.to(dtype) + return out_boxes + + +def resize_bounding_boxes( + bounding_boxes: torch.Tensor, + canvas_size: tuple[int, int], + size: Optional[list[int]], + max_size: Optional[int] = None, + format: tv_tensors.BoundingBoxFormat = tv_tensors.BoundingBoxFormat.XYXY, + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> tuple[torch.Tensor, tuple[int, int]]: + # We set the default format as `tv_tensors.BoundingBoxFormat.XYXY` + # to ensure backward compatibility. + # Indeed before the introduction of rotated bounding box format + # this function did not received `format` parameter as input. + old_height, old_width = canvas_size + new_height, new_width = _compute_resized_output_size(canvas_size, size=size, max_size=max_size) + + if (new_height, new_width) == (old_height, old_width): + return bounding_boxes, canvas_size + + w_ratio = new_width / old_width + h_ratio = new_height / old_height + if tv_tensors.is_rotated_bounding_format(format): + original_shape = bounding_boxes.shape + xyxyxyxy_boxes = convert_bounding_box_format( + bounding_boxes, old_format=format, new_format=tv_tensors.BoundingBoxFormat.XYXYXYXY, inplace=False + ).reshape(-1, 8) + + ratios = torch.tensor( + [w_ratio, h_ratio, w_ratio, h_ratio, w_ratio, h_ratio, w_ratio, h_ratio], device=bounding_boxes.device + ) + transformed_points = xyxyxyxy_boxes.mul(ratios) + out_bboxes = _parallelogram_to_bounding_boxes(transformed_points) + out_bboxes = clamp_bounding_boxes( + out_bboxes, + format=tv_tensors.BoundingBoxFormat.XYXYXYXY, + canvas_size=(new_height, new_width), + clamping_mode=clamping_mode, + ) + return ( + convert_bounding_box_format( + out_bboxes, + old_format=tv_tensors.BoundingBoxFormat.XYXYXYXY, + new_format=format, + inplace=False, + ) + .to(bounding_boxes.dtype) + .reshape(original_shape), + (new_height, new_width), + ) + else: + ratios = torch.tensor([w_ratio, h_ratio, w_ratio, h_ratio], device=bounding_boxes.device) + return ( + bounding_boxes.mul(ratios).to(bounding_boxes.dtype), + (new_height, new_width), + ) + + +@_register_kernel_internal(resize, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _resize_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, size: Optional[list[int]], max_size: Optional[int] = None, **kwargs: Any +) -> tv_tensors.BoundingBoxes: + output, canvas_size = resize_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + size=size, + max_size=max_size, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +@_register_kernel_internal(resize, tv_tensors.Video) +def resize_video( + video: torch.Tensor, + size: Optional[list[int]], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + max_size: Optional[int] = None, + antialias: Optional[bool] = True, +) -> torch.Tensor: + return resize_image(video, size=size, interpolation=interpolation, max_size=max_size, antialias=antialias) + + +def affine( + inpt: torch.Tensor, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.NEAREST, + fill: _FillTypeJIT = None, + center: Optional[list[float]] = None, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomAffine` for details.""" + if torch.jit.is_scripting(): + return affine_image( + inpt, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + interpolation=interpolation, + fill=fill, + center=center, + ) + + _log_api_usage_once(affine) + + kernel = _get_kernel(affine, type(inpt)) + return kernel( + inpt, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + interpolation=interpolation, + fill=fill, + center=center, + ) + + +def _affine_parse_args( + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + interpolation: InterpolationMode = InterpolationMode.NEAREST, + center: Optional[list[float]] = None, +) -> tuple[float, list[float], list[float], Optional[list[float]]]: + if not isinstance(angle, (int, float)): + raise TypeError("Argument angle should be int or float") + + if not isinstance(translate, (list, tuple)): + raise TypeError("Argument translate should be a sequence") + + if len(translate) != 2: + raise ValueError("Argument translate should be a sequence of length 2") + + if scale <= 0.0: + raise ValueError("Argument scale should be positive") + + if not isinstance(shear, (numbers.Number, (list, tuple))): + raise TypeError("Shear should be either a single value or a sequence of two values") + + if not isinstance(interpolation, InterpolationMode): + raise TypeError("Argument interpolation should be a InterpolationMode") + + if isinstance(angle, int): + angle = float(angle) + + if isinstance(translate, tuple): + translate = list(translate) + + if isinstance(shear, numbers.Number): + shear = [shear, 0.0] + + if isinstance(shear, tuple): + shear = list(shear) + + if len(shear) == 1: + shear = [shear[0], shear[0]] + + if len(shear) != 2: + raise ValueError(f"Shear should be a sequence containing two values. Got {shear}") + + if center is not None: + if not isinstance(center, (list, tuple)): + raise TypeError("Argument center should be a sequence") + else: + center = [float(c) for c in center] + + return angle, translate, shear, center + + +def _get_inverse_affine_matrix( + center: list[float], angle: float, translate: list[float], scale: float, shear: list[float], inverted: bool = True +) -> list[float]: + # Helper method to compute inverse matrix for affine transformation + + # Pillow requires inverse affine transformation matrix: + # Affine matrix is : M = T * C * RotateScaleShear * C^-1 + # + # where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1] + # C is translation matrix to keep center: [1, 0, cx | 0, 1, cy | 0, 0, 1] + # RotateScaleShear is rotation with scale and shear matrix + # + # RotateScaleShear(a, s, (sx, sy)) = + # = R(a) * S(s) * SHy(sy) * SHx(sx) + # = [ s*cos(a - sy)/cos(sy), s*(-cos(a - sy)*tan(sx)/cos(sy) - sin(a)), 0 ] + # [ s*sin(a - sy)/cos(sy), s*(-sin(a - sy)*tan(sx)/cos(sy) + cos(a)), 0 ] + # [ 0 , 0 , 1 ] + # where R is a rotation matrix, S is a scaling matrix, and SHx and SHy are the shears: + # SHx(s) = [1, -tan(s)] and SHy(s) = [1 , 0] + # [0, 1 ] [-tan(s), 1] + # + # Thus, the inverse is M^-1 = C * RotateScaleShear^-1 * C^-1 * T^-1 + + rot = math.radians(angle) + sx = math.radians(shear[0]) + sy = math.radians(shear[1]) + + cx, cy = center + tx, ty = translate + + # Cached results + cos_sy = math.cos(sy) + tan_sx = math.tan(sx) + rot_minus_sy = rot - sy + cx_plus_tx = cx + tx + cy_plus_ty = cy + ty + + # Rotate Scale Shear (RSS) without scaling + a = math.cos(rot_minus_sy) / cos_sy + b = -(a * tan_sx + math.sin(rot)) + c = math.sin(rot_minus_sy) / cos_sy + d = math.cos(rot) - c * tan_sx + + if inverted: + # Inverted rotation matrix with scale and shear + # det([[a, b], [c, d]]) == 1, since det(rotation) = 1 and det(shear) = 1 + matrix = [d / scale, -b / scale, 0.0, -c / scale, a / scale, 0.0] + # Apply inverse of translation and of center translation: RSS^-1 * C^-1 * T^-1 + # and then apply center translation: C * RSS^-1 * C^-1 * T^-1 + matrix[2] += cx - matrix[0] * cx_plus_tx - matrix[1] * cy_plus_ty + matrix[5] += cy - matrix[3] * cx_plus_tx - matrix[4] * cy_plus_ty + else: + matrix = [a * scale, b * scale, 0.0, c * scale, d * scale, 0.0] + # Apply inverse of center translation: RSS * C^-1 + # and then apply translation and center : T * C * RSS * C^-1 + matrix[2] += cx_plus_tx - matrix[0] * cx - matrix[1] * cy + matrix[5] += cy_plus_ty - matrix[3] * cx - matrix[4] * cy + + return matrix + + +def _compute_affine_output_size(matrix: list[float], w: int, h: int) -> tuple[int, int]: + if torch.compiler.is_compiling() and not torch.jit.is_scripting(): + return _compute_affine_output_size_python(matrix, w, h) + else: + return _compute_affine_output_size_tensor(matrix, w, h) + + +def _compute_affine_output_size_tensor(matrix: list[float], w: int, h: int) -> tuple[int, int]: + # Inspired of PIL implementation: + # https://github.com/python-pillow/Pillow/blob/11de3318867e4398057373ee9f12dcb33db7335c/src/PIL/Image.py#L2054 + + # pts are Top-Left, Top-Right, Bottom-Left, Bottom-Right points. + # Points are shifted due to affine matrix torch convention about + # the center point. Center is (0, 0) for image center pivot point (w * 0.5, h * 0.5) + half_w = 0.5 * w + half_h = 0.5 * h + pts = torch.tensor( + [ + [-half_w, -half_h, 1.0], + [-half_w, half_h, 1.0], + [half_w, half_h, 1.0], + [half_w, -half_h, 1.0], + ] + ) + theta = torch.tensor(matrix, dtype=torch.float).view(2, 3) + new_pts = torch.matmul(pts, theta.T) + min_vals, max_vals = new_pts.aminmax(dim=0) + + # shift points to [0, w] and [0, h] interval to match PIL results + halfs = torch.tensor((half_w, half_h)) + min_vals.add_(halfs) + max_vals.add_(halfs) + + # Truncate precision to 1e-4 to avoid ceil of Xe-15 to 1.0 + tol = 1e-4 + inv_tol = 1.0 / tol + cmax = max_vals.mul_(inv_tol).trunc_().mul_(tol).ceil_() + cmin = min_vals.mul_(inv_tol).trunc_().mul_(tol).floor_() + size = cmax.sub_(cmin) + return int(size[0]), int(size[1]) # w, h + + +def _compute_affine_output_size_python(matrix: list[float], w: int, h: int) -> tuple[int, int]: + # Mostly copied from PIL implementation: + # The only difference is with transformed points as input matrix has zero translation part here and + # PIL has a centered translation part. + # https://github.com/python-pillow/Pillow/blob/11de3318867e4398057373ee9f12dcb33db7335c/src/PIL/Image.py#L2054 + + a, b, c, d, e, f = matrix + xx = [] + yy = [] + + half_w = 0.5 * w + half_h = 0.5 * h + for x, y in ((-half_w, -half_h), (half_w, -half_h), (half_w, half_h), (-half_w, half_h)): + nx = a * x + b * y + c + ny = d * x + e * y + f + xx.append(nx + half_w) + yy.append(ny + half_h) + + nw = math.ceil(max(xx)) - math.floor(min(xx)) + nh = math.ceil(max(yy)) - math.floor(min(yy)) + return int(nw), int(nh) # w, h + + +def _apply_grid_transform(img: torch.Tensor, grid: torch.Tensor, mode: str, fill: _FillTypeJIT) -> torch.Tensor: + input_shape = img.shape + output_height, output_width = grid.shape[1], grid.shape[2] + num_channels, input_height, input_width = input_shape[-3:] + output_shape = input_shape[:-3] + (num_channels, output_height, output_width) + + if img.numel() == 0: + return img.reshape(output_shape) + + img = img.reshape(-1, num_channels, input_height, input_width) + squashed_batch_size = img.shape[0] + + # We are using context knowledge that grid should have float dtype + fp = img.dtype == grid.dtype + float_img = img if fp else img.to(grid.dtype) + + if squashed_batch_size > 1: + # Apply same grid to a batch of images + grid = grid.expand(squashed_batch_size, -1, -1, -1) + + # Append a dummy mask for customized fill colors, should be faster than grid_sample() twice + if fill is not None: + mask = torch.ones( + (squashed_batch_size, 1, input_height, input_width), dtype=float_img.dtype, device=float_img.device + ) + float_img = torch.cat((float_img, mask), dim=1) + + float_img = grid_sample(float_img, grid, mode=mode, padding_mode="zeros", align_corners=False) + + # Fill with required color + if fill is not None: + float_img, mask = torch.tensor_split(float_img, indices=(-1,), dim=-3) + mask = mask.expand_as(float_img) + fill_list = fill if isinstance(fill, (tuple, list)) else [float(fill)] # type: ignore[arg-type] + fill_img = torch.tensor(fill_list, dtype=float_img.dtype, device=float_img.device).view(1, -1, 1, 1) + if mode == "nearest": + float_img = torch.where(mask < 0.5, fill_img.expand_as(float_img), float_img) + else: # 'bilinear' + # The following is mathematically equivalent to: + # img * mask + (1.0 - mask) * fill = img * mask - fill * mask + fill = mask * (img - fill) + fill + float_img = float_img.sub_(fill_img).mul_(mask).add_(fill_img) + + img = float_img.round_().to(img.dtype) if not fp else float_img + + return img.reshape(output_shape) + + +def _assert_grid_transform_inputs( + image: torch.Tensor, + matrix: Optional[list[float]], + interpolation: str, + fill: _FillTypeJIT, + supported_interpolation_modes: list[str], + coeffs: Optional[list[float]] = None, +) -> None: + if matrix is not None: + if not isinstance(matrix, list): + raise TypeError("Argument matrix should be a list") + elif len(matrix) != 6: + raise ValueError("Argument matrix should have 6 float values") + + if coeffs is not None and len(coeffs) != 8: + raise ValueError("Argument coeffs should have 8 float values") + + if fill is not None: + if isinstance(fill, (tuple, list)): + length = len(fill) + num_channels = image.shape[-3] + if length > 1 and length != num_channels: + raise ValueError( + "The number of elements in 'fill' cannot broadcast to match the number of " + f"channels of the image ({length} != {num_channels})" + ) + elif not isinstance(fill, (int, float)): + raise ValueError("Argument fill should be either int, float, tuple or list") + + if interpolation not in supported_interpolation_modes: + raise ValueError(f"Interpolation mode '{interpolation}' is unsupported with Tensor input") + + +def _affine_grid( + theta: torch.Tensor, + w: int, + h: int, + ow: int, + oh: int, +) -> torch.Tensor: + # https://github.com/pytorch/pytorch/blob/74b65c32be68b15dc7c9e8bb62459efbfbde33d8/aten/src/ATen/native/ + # AffineGridGenerator.cpp#L18 + # Difference with AffineGridGenerator is that: + # 1) we normalize grid values after applying theta + # 2) we can normalize by other image size, such that it covers "extend" option like in PIL.Image.rotate + dtype = theta.dtype + device = theta.device + + base_grid = torch.empty(1, oh, ow, 3, dtype=dtype, device=device) + x_grid = torch.linspace((1.0 - ow) * 0.5, (ow - 1.0) * 0.5, steps=ow, device=device) + base_grid[..., 0].copy_(x_grid) + y_grid = torch.linspace((1.0 - oh) * 0.5, (oh - 1.0) * 0.5, steps=oh, device=device).unsqueeze_(-1) + base_grid[..., 1].copy_(y_grid) + base_grid[..., 2].fill_(1) + + rescaled_theta = theta.transpose(1, 2).div_(torch.tensor([0.5 * w, 0.5 * h], dtype=dtype, device=device)) + output_grid = base_grid.view(1, oh * ow, 3).bmm(rescaled_theta) + return output_grid.view(1, oh, ow, 2) + + +@_register_kernel_internal(affine, torch.Tensor) +@_register_kernel_internal(affine, tv_tensors.Image) +def affine_image( + image: torch.Tensor, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.NEAREST, + fill: _FillTypeJIT = None, + center: Optional[list[float]] = None, +) -> torch.Tensor: + interpolation = _check_interpolation(interpolation) + + angle, translate, shear, center = _affine_parse_args(angle, translate, scale, shear, interpolation, center) + + height, width = image.shape[-2:] + + center_f = [0.0, 0.0] + if center is not None: + # Center values should be in pixel coordinates but translated such that (0, 0) corresponds to image center. + center_f = [(c - s * 0.5) for c, s in zip(center, [width, height])] + + translate_f = [float(t) for t in translate] + matrix = _get_inverse_affine_matrix(center_f, angle, translate_f, scale, shear) + + _assert_grid_transform_inputs(image, matrix, interpolation.value, fill, ["nearest", "bilinear"]) + + dtype = image.dtype if torch.is_floating_point(image) else torch.float32 + theta = torch.tensor(matrix, dtype=dtype, device=image.device).reshape(1, 2, 3) + grid = _affine_grid(theta, w=width, h=height, ow=width, oh=height) + return _apply_grid_transform(image, grid, interpolation.value, fill=fill) + + +@_register_kernel_internal(affine, PIL.Image.Image) +def _affine_image_pil( + image: PIL.Image.Image, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.NEAREST, + fill: _FillTypeJIT = None, + center: Optional[list[float]] = None, +) -> PIL.Image.Image: + interpolation = _check_interpolation(interpolation) + angle, translate, shear, center = _affine_parse_args(angle, translate, scale, shear, interpolation, center) + + # center = (img_size[0] * 0.5 + 0.5, img_size[1] * 0.5 + 0.5) + # it is visually better to estimate the center without 0.5 offset + # otherwise image rotated by 90 degrees is shifted vs output image of torch.rot90 or F_t.affine + if center is None: + height, width = _get_size_image_pil(image) + center = [width * 0.5, height * 0.5] + matrix = _get_inverse_affine_matrix(center, angle, translate, scale, shear) + + return _FP.affine(image, matrix, interpolation=pil_modes_mapping[interpolation], fill=fill) + + +# TODO: Consider merging/unifying this with the bbox implementation +def _affine_keypoints_with_expand( + keypoints: torch.Tensor, + canvas_size: tuple[int, int], + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + center: Optional[list[float]] = None, + expand: bool = False, +) -> tuple[torch.Tensor, tuple[int, int]]: + if keypoints.numel() == 0: + return keypoints, canvas_size + + original_dtype = keypoints.dtype + original_shape = keypoints.shape + keypoints = keypoints.clone() if keypoints.is_floating_point() else keypoints.float() + dtype = keypoints.dtype + device = keypoints.device + + angle, translate, shear, center = _affine_parse_args( + angle, translate, scale, shear, InterpolationMode.NEAREST, center + ) + + if center is None: + height, width = canvas_size + center = [width * 0.5, height * 0.5] + + affine_vector = _get_inverse_affine_matrix(center, angle, translate, scale, shear, inverted=False) + transposed_affine_matrix = ( + torch.tensor( + affine_vector, + dtype=dtype, + device=device, + ) + .reshape(2, 3) + .T + ) + + # 1) We transform points into a tensor of points with shape (N, 3), where N is the number of points. + points = keypoints.reshape(-1, 2) + points = torch.cat([points, torch.ones(points.shape[0], 1, device=device, dtype=dtype)], dim=-1) + # 2) Now let's transform the points using affine matrix + transformed_points = torch.matmul(points, transposed_affine_matrix) + + if expand: + # Compute minimum point for transformed image frame: + # Points are Top-Left, Top-Right, Bottom-Left, Bottom-Right points. + height, width = canvas_size + points = torch.tensor( + [ + [0.0, 0.0, 1.0], + [0.0, float(height), 1.0], + [float(width), float(height), 1.0], + [float(width), 0.0, 1.0], + ], + dtype=dtype, + device=device, + ) + new_points = torch.matmul(points, transposed_affine_matrix) + tr = torch.amin(new_points, dim=0, keepdim=True) + # Translate keypoints + transformed_points.sub_(tr) + # Estimate meta-data for image with inverted=True + affine_vector = _get_inverse_affine_matrix(center, angle, translate, scale, shear) + new_width, new_height = _compute_affine_output_size(affine_vector, width, height) + canvas_size = (new_height, new_width) + + out_keypoints = transformed_points.reshape(original_shape) + out_keypoints = out_keypoints.to(original_dtype) + + return out_keypoints, canvas_size + + +def affine_keypoints( + keypoints: torch.Tensor, + canvas_size: tuple[int, int], + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + center: Optional[list[float]] = None, +): + return _affine_keypoints_with_expand( + keypoints=keypoints, + canvas_size=canvas_size, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + center=center, + expand=False, + ) + + +@_register_kernel_internal(affine, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _affine_keypoints_dispatch( + inpt: tv_tensors.KeyPoints, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + center: Optional[list[float]] = None, + **kwargs, +) -> tv_tensors.KeyPoints: + output, canvas_size = affine_keypoints( + inpt.as_subclass(torch.Tensor), + canvas_size=inpt.canvas_size, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + center=center, + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +def _affine_bounding_boxes_with_expand( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + center: Optional[list[float]] = None, + expand: bool = False, + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> tuple[torch.Tensor, tuple[int, int]]: + if bounding_boxes.numel() == 0: + return bounding_boxes, canvas_size + + original_shape = bounding_boxes.shape + dtype = bounding_boxes.dtype + need_cast = not bounding_boxes.is_floating_point() + bounding_boxes = bounding_boxes.float() if need_cast else bounding_boxes.clone() + device = bounding_boxes.device + is_rotated = tv_tensors.is_rotated_bounding_format(format) + intermediate_format = tv_tensors.BoundingBoxFormat.XYXYXYXY if is_rotated else tv_tensors.BoundingBoxFormat.XYXY + intermediate_shape = 8 if is_rotated else 4 + bounding_boxes = ( + convert_bounding_box_format(bounding_boxes, old_format=format, new_format=intermediate_format, inplace=True) + ).reshape(-1, intermediate_shape) + + angle, translate, shear, center = _affine_parse_args( + angle, translate, scale, shear, InterpolationMode.NEAREST, center + ) + + if center is None: + height, width = canvas_size + center = [width * 0.5, height * 0.5] + + affine_vector = _get_inverse_affine_matrix(center, angle, translate, scale, shear, inverted=False) + transposed_affine_matrix = ( + torch.tensor( + affine_vector, + dtype=bounding_boxes.dtype, + device=device, + ) + .reshape(2, 3) + .T + ) + # 1) Let's transform bboxes into a tensor of 4 points (top-left, top-right, bottom-left, bottom-right corners). + # Tensor of points has shape (N * 4, 3), where N is the number of bboxes + # Single point structure is similar to + # [(xmin, ymin, 1), (xmax, ymin, 1), (xmax, ymax, 1), (xmin, ymax, 1)] + if is_rotated: + points = bounding_boxes.reshape(-1, 2) + else: + points = bounding_boxes[:, [[0, 1], [2, 1], [2, 3], [0, 3]]].reshape(-1, 2) + points = torch.cat([points, torch.ones(points.shape[0], 1, device=device, dtype=bounding_boxes.dtype)], dim=-1) + # 2) Now let's transform the points using affine matrix + transformed_points = torch.matmul(points, transposed_affine_matrix) + # 3) Reshape transformed points to [N boxes, 4 points, x/y coords] + # and compute bounding box from 4 transformed points: + if is_rotated: + transformed_points = transformed_points.reshape(-1, 8) + out_bboxes = _parallelogram_to_bounding_boxes(transformed_points) + else: + transformed_points = transformed_points.reshape(-1, 4, 2) + out_bbox_mins, out_bbox_maxs = torch.aminmax(transformed_points, dim=1) + out_bboxes = torch.cat([out_bbox_mins, out_bbox_maxs], dim=1) + + if expand: + # Compute minimum point for transformed image frame: + # Points are Top-Left, Top-Right, Bottom-Left, Bottom-Right points. + height, width = canvas_size + points = torch.tensor( + [ + [0.0, 0.0, 1.0], + [0.0, float(height), 1.0], + [float(width), float(height), 1.0], + [float(width), 0.0, 1.0], + ], + dtype=bounding_boxes.dtype, + device=device, + ) + new_points = torch.matmul(points, transposed_affine_matrix) + tr = torch.amin(new_points, dim=0, keepdim=True) + # Translate bounding boxes + out_bboxes.sub_(tr.repeat((1, 4 if is_rotated else 2))) + # Estimate meta-data for image with inverted=True + affine_vector = _get_inverse_affine_matrix(center, angle, translate, scale, shear) + new_width, new_height = _compute_affine_output_size(affine_vector, width, height) + canvas_size = (new_height, new_width) + + out_bboxes = clamp_bounding_boxes( + out_bboxes, format=intermediate_format, canvas_size=canvas_size, clamping_mode=clamping_mode + ) + out_bboxes = convert_bounding_box_format( + out_bboxes, old_format=intermediate_format, new_format=format, inplace=True + ).reshape(original_shape) + + if need_cast: + out_bboxes = out_bboxes.to(dtype) + return out_bboxes, canvas_size + + +def affine_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + center: Optional[list[float]] = None, + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> torch.Tensor: + out_box, _ = _affine_bounding_boxes_with_expand( + bounding_boxes, + format=format, + canvas_size=canvas_size, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + center=center, + expand=False, + clamping_mode=clamping_mode, + ) + return out_box + + +@_register_kernel_internal(affine, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _affine_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + center: Optional[list[float]] = None, + **kwargs, +) -> tv_tensors.BoundingBoxes: + output = affine_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + center=center, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt) + + +def affine_mask( + mask: torch.Tensor, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + fill: _FillTypeJIT = None, + center: Optional[list[float]] = None, +) -> torch.Tensor: + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = affine_image( + mask, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + interpolation=InterpolationMode.NEAREST, + fill=fill, + center=center, + ) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +@_register_kernel_internal(affine, tv_tensors.Mask, tv_tensor_wrapper=False) +def _affine_mask_dispatch( + inpt: tv_tensors.Mask, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + fill: _FillTypeJIT = None, + center: Optional[list[float]] = None, + **kwargs, +) -> tv_tensors.Mask: + output = affine_mask( + inpt.as_subclass(torch.Tensor), + angle=angle, + translate=translate, + scale=scale, + shear=shear, + fill=fill, + center=center, + ) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(affine, tv_tensors.Video) +def affine_video( + video: torch.Tensor, + angle: Union[int, float], + translate: list[float], + scale: float, + shear: list[float], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.NEAREST, + fill: _FillTypeJIT = None, + center: Optional[list[float]] = None, +) -> torch.Tensor: + return affine_image( + video, + angle=angle, + translate=translate, + scale=scale, + shear=shear, + interpolation=interpolation, + fill=fill, + center=center, + ) + + +def rotate( + inpt: torch.Tensor, + angle: float, + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.NEAREST, + expand: bool = False, + center: Optional[list[float]] = None, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomRotation` for details.""" + if torch.jit.is_scripting(): + return rotate_image(inpt, angle=angle, interpolation=interpolation, expand=expand, fill=fill, center=center) + + _log_api_usage_once(rotate) + + kernel = _get_kernel(rotate, type(inpt)) + return kernel(inpt, angle=angle, interpolation=interpolation, expand=expand, fill=fill, center=center) + + +@_register_kernel_internal(rotate, torch.Tensor) +@_register_kernel_internal(rotate, tv_tensors.Image) +def rotate_image( + image: torch.Tensor, + angle: float, + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.NEAREST, + expand: bool = False, + center: Optional[list[float]] = None, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + angle = angle % 360 # shift angle to [0, 360) range + + # fast path: transpose without affine transform + if center is None: + if angle == 0: + return image.clone() + if angle == 180: + return torch.rot90(image, k=2, dims=(-2, -1)) + + if expand or image.shape[-1] == image.shape[-2]: + if angle == 90: + return torch.rot90(image, k=1, dims=(-2, -1)) + if angle == 270: + return torch.rot90(image, k=3, dims=(-2, -1)) + + interpolation = _check_interpolation(interpolation) + + input_height, input_width = image.shape[-2:] + + center_f = [0.0, 0.0] + if center is not None: + # Center values should be in pixel coordinates but translated such that (0, 0) corresponds to image center. + center_f = [(c - s * 0.5) for c, s in zip(center, [input_width, input_height])] + + # due to current incoherence of rotation angle direction between affine and rotate implementations + # we need to set -angle. + matrix = _get_inverse_affine_matrix(center_f, -angle, [0.0, 0.0], 1.0, [0.0, 0.0]) + + _assert_grid_transform_inputs(image, matrix, interpolation.value, fill, ["nearest", "bilinear"]) + + output_width, output_height = ( + _compute_affine_output_size(matrix, input_width, input_height) if expand else (input_width, input_height) + ) + dtype = image.dtype if torch.is_floating_point(image) else torch.float32 + theta = torch.tensor(matrix, dtype=dtype, device=image.device).reshape(1, 2, 3) + grid = _affine_grid(theta, w=input_width, h=input_height, ow=output_width, oh=output_height) + return _apply_grid_transform(image, grid, interpolation.value, fill=fill) + + +@_register_kernel_internal(rotate, PIL.Image.Image) +def _rotate_image_pil( + image: PIL.Image.Image, + angle: float, + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.NEAREST, + expand: bool = False, + center: Optional[list[float]] = None, + fill: _FillTypeJIT = None, +) -> PIL.Image.Image: + interpolation = _check_interpolation(interpolation) + + return _FP.rotate( + image, angle, interpolation=pil_modes_mapping[interpolation], expand=expand, fill=fill, center=center # type: ignore[arg-type] + ) + + +def rotate_keypoints( + keypoints: torch.Tensor, + canvas_size: tuple[int, int], + angle: float, + expand: bool = False, + center: Optional[list[float]] = None, +) -> tuple[torch.Tensor, tuple[int, int]]: + return _affine_keypoints_with_expand( + keypoints=keypoints, + canvas_size=canvas_size, + angle=-angle, + translate=[0.0, 0.0], + scale=1.0, + shear=[0.0, 0.0], + center=center, + expand=expand, + ) + + +@_register_kernel_internal(rotate, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _rotate_keypoints_dispatch( + inpt: tv_tensors.KeyPoints, angle: float, expand: bool = False, center: Optional[list[float]] = None, **kwargs +) -> tv_tensors.KeyPoints: + output, canvas_size = rotate_keypoints( + inpt, canvas_size=inpt.canvas_size, angle=angle, center=center, expand=expand + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +def rotate_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + angle: float, + expand: bool = False, + center: Optional[list[float]] = None, + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> tuple[torch.Tensor, tuple[int, int]]: + return _affine_bounding_boxes_with_expand( + bounding_boxes, + format=format, + canvas_size=canvas_size, + angle=-angle, + translate=[0.0, 0.0], + scale=1.0, + shear=[0.0, 0.0], + center=center, + expand=expand, + clamping_mode=clamping_mode, + ) + + +@_register_kernel_internal(rotate, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _rotate_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, angle: float, expand: bool = False, center: Optional[list[float]] = None, **kwargs +) -> tv_tensors.BoundingBoxes: + output, canvas_size = rotate_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + angle=angle, + expand=expand, + center=center, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +def rotate_mask( + mask: torch.Tensor, + angle: float, + expand: bool = False, + center: Optional[list[float]] = None, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = rotate_image( + mask, + angle=angle, + expand=expand, + interpolation=InterpolationMode.NEAREST, + fill=fill, + center=center, + ) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +@_register_kernel_internal(rotate, tv_tensors.Mask, tv_tensor_wrapper=False) +def _rotate_mask_dispatch( + inpt: tv_tensors.Mask, + angle: float, + expand: bool = False, + center: Optional[list[float]] = None, + fill: _FillTypeJIT = None, + **kwargs, +) -> tv_tensors.Mask: + output = rotate_mask(inpt.as_subclass(torch.Tensor), angle=angle, expand=expand, fill=fill, center=center) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(rotate, tv_tensors.Video) +def rotate_video( + video: torch.Tensor, + angle: float, + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.NEAREST, + expand: bool = False, + center: Optional[list[float]] = None, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + return rotate_image(video, angle, interpolation=interpolation, expand=expand, fill=fill, center=center) + + +def pad( + inpt: torch.Tensor, + padding: list[int], + fill: Optional[Union[int, float, list[float]]] = None, + padding_mode: str = "constant", +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.Pad` for details.""" + if torch.jit.is_scripting(): + return pad_image(inpt, padding=padding, fill=fill, padding_mode=padding_mode) + + _log_api_usage_once(pad) + + kernel = _get_kernel(pad, type(inpt)) + return kernel(inpt, padding=padding, fill=fill, padding_mode=padding_mode) + + +def _parse_pad_padding(padding: Union[int, list[int]]) -> list[int]: + if isinstance(padding, int): + pad_left = pad_right = pad_top = pad_bottom = padding + elif isinstance(padding, (tuple, list)): + if len(padding) == 1: + pad_left = pad_right = pad_top = pad_bottom = padding[0] + elif len(padding) == 2: + pad_left = pad_right = padding[0] + pad_top = pad_bottom = padding[1] + elif len(padding) == 4: + pad_left = padding[0] + pad_top = padding[1] + pad_right = padding[2] + pad_bottom = padding[3] + else: + raise ValueError(f"Padding must be an int or a 1, 2, or 4 element tuple or list. Found {len(padding)}") + else: + raise TypeError(f"`padding` should be an integer or tuple or list of integers, but got {padding}") + + return [pad_left, pad_right, pad_top, pad_bottom] + + +@_register_kernel_internal(pad, torch.Tensor) +@_register_kernel_internal(pad, tv_tensors.Image) +def pad_image( + image: torch.Tensor, + padding: list[int], + fill: Optional[Union[int, float, list[float]]] = None, + padding_mode: str = "constant", +) -> torch.Tensor: + # Be aware that while `padding` has order `[left, top, right, bottom]`, `torch_padding` uses + # `[left, right, top, bottom]`. This stems from the fact that we align our API with PIL, but need to use `torch_pad` + # internally. + torch_padding = _parse_pad_padding(padding) + + if padding_mode not in ("constant", "edge", "reflect", "symmetric"): + raise ValueError( + f"`padding_mode` should be either `'constant'`, `'edge'`, `'reflect'` or `'symmetric'`, " + f"but got `'{padding_mode}'`." + ) + + if fill is None: + fill = 0 + + if isinstance(fill, (int, float)): + return _pad_with_scalar_fill(image, torch_padding, fill=fill, padding_mode=padding_mode) + elif len(fill) == 1: + return _pad_with_scalar_fill(image, torch_padding, fill=fill[0], padding_mode=padding_mode) + else: + return _pad_with_vector_fill(image, torch_padding, fill=fill, padding_mode=padding_mode) + + +def _pad_with_scalar_fill( + image: torch.Tensor, + torch_padding: list[int], + fill: Union[int, float], + padding_mode: str, +) -> torch.Tensor: + shape = image.shape + num_channels, height, width = shape[-3:] + + batch_size = 1 + for s in shape[:-3]: + batch_size *= s + + image = image.reshape(batch_size, num_channels, height, width) + + if padding_mode == "edge": + # Similar to the padding order, `torch_pad`'s PIL's padding modes don't have the same names. Thus, we map + # the PIL name for the padding mode, which we are also using for our API, to the corresponding `torch_pad` + # name. + padding_mode = "replicate" + + if padding_mode == "constant": + image = torch_pad(image, torch_padding, mode=padding_mode, value=float(fill)) + elif padding_mode in ("reflect", "replicate"): + # `torch_pad` only supports `"reflect"` or `"replicate"` padding for floating point inputs. + # TODO: See https://github.com/pytorch/pytorch/issues/40763 + dtype = image.dtype + if not image.is_floating_point(): + needs_cast = True + image = image.to(torch.float32) + else: + needs_cast = False + + image = torch_pad(image, torch_padding, mode=padding_mode) + + if needs_cast: + image = image.to(dtype) + else: # padding_mode == "symmetric" + image = _pad_symmetric(image, torch_padding) + + new_height, new_width = image.shape[-2:] + + return image.reshape(shape[:-3] + (num_channels, new_height, new_width)) + + +# TODO: This should be removed once torch_pad supports non-scalar padding values +def _pad_with_vector_fill( + image: torch.Tensor, + torch_padding: list[int], + fill: list[float], + padding_mode: str, +) -> torch.Tensor: + if padding_mode != "constant": + raise ValueError(f"Padding mode '{padding_mode}' is not supported if fill is not scalar") + + output = _pad_with_scalar_fill(image, torch_padding, fill=0, padding_mode="constant") + left, right, top, bottom = torch_padding + + # We are creating the tensor in the autodetected dtype first and convert to the right one after to avoid an implicit + # float -> int conversion. That happens for example for the valid input of a uint8 image with floating point fill + # value. + fill = torch.tensor(fill, device=image.device).to(dtype=image.dtype).reshape(-1, 1, 1) + + if top > 0: + output[..., :top, :] = fill + if left > 0: + output[..., :, :left] = fill + if bottom > 0: + output[..., -bottom:, :] = fill + if right > 0: + output[..., :, -right:] = fill + return output + + +_pad_image_pil = _register_kernel_internal(pad, PIL.Image.Image)(_FP.pad) + + +@_register_kernel_internal(pad, tv_tensors.Mask) +def pad_mask( + mask: torch.Tensor, + padding: list[int], + fill: Optional[Union[int, float, list[float]]] = None, + padding_mode: str = "constant", +) -> torch.Tensor: + if fill is None: + fill = 0 + + if isinstance(fill, (tuple, list)): + raise ValueError("Non-scalar fill value is not supported") + + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = pad_image(mask, padding=padding, fill=fill, padding_mode=padding_mode) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +def pad_keypoints( + keypoints: torch.Tensor, canvas_size: tuple[int, int], padding: list[int], padding_mode: str = "constant" +): + SUPPORTED_MODES = ["constant"] + if padding_mode not in SUPPORTED_MODES: + # TODO: add support of other padding modes + raise ValueError( + f"Padding mode '{padding_mode}' is not supported with KeyPoints" + f" (supported modes are {', '.join(SUPPORTED_MODES)})" + ) + left, right, top, bottom = _parse_pad_padding(padding) + pad = torch.tensor([left, top], dtype=keypoints.dtype, device=keypoints.device) + canvas_size = (canvas_size[0] + top + bottom, canvas_size[1] + left + right) + return keypoints + pad, canvas_size + + +@_register_kernel_internal(pad, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _pad_keypoints_dispatch( + keypoints: tv_tensors.KeyPoints, padding: list[int], padding_mode: str = "constant", **kwargs +) -> tv_tensors.KeyPoints: + output, canvas_size = pad_keypoints( + keypoints.as_subclass(torch.Tensor), + canvas_size=keypoints.canvas_size, + padding=padding, + padding_mode=padding_mode, + ) + return tv_tensors.wrap(output, like=keypoints, canvas_size=canvas_size) + + +def pad_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + padding: list[int], + padding_mode: str = "constant", + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> tuple[torch.Tensor, tuple[int, int]]: + if padding_mode not in ["constant"]: + # TODO: add support of other padding modes + raise ValueError(f"Padding mode '{padding_mode}' is not supported with bounding boxes") + + left, right, top, bottom = _parse_pad_padding(padding) + + if format == tv_tensors.BoundingBoxFormat.XYXYXYXY: + pad = [left, top, left, top, left, top, left, top] + elif format == tv_tensors.BoundingBoxFormat.XYWHR or format == tv_tensors.BoundingBoxFormat.CXCYWHR: + pad = [left, top, 0, 0, 0] + elif format == tv_tensors.BoundingBoxFormat.XYXY: + pad = [left, top, left, top] + else: + pad = [left, top, 0, 0] + bounding_boxes = bounding_boxes + torch.tensor(pad, dtype=bounding_boxes.dtype, device=bounding_boxes.device) + + height, width = canvas_size + height += top + bottom + width += left + right + canvas_size = (height, width) + + return ( + clamp_bounding_boxes(bounding_boxes, format=format, canvas_size=canvas_size, clamping_mode=clamping_mode), + canvas_size, + ) + + +@_register_kernel_internal(pad, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _pad_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, padding: list[int], padding_mode: str = "constant", **kwargs +) -> tv_tensors.BoundingBoxes: + output, canvas_size = pad_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + padding=padding, + padding_mode=padding_mode, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +@_register_kernel_internal(pad, tv_tensors.Video) +def pad_video( + video: torch.Tensor, + padding: list[int], + fill: Optional[Union[int, float, list[float]]] = None, + padding_mode: str = "constant", +) -> torch.Tensor: + return pad_image(video, padding, fill=fill, padding_mode=padding_mode) + + +def crop(inpt: torch.Tensor, top: int, left: int, height: int, width: int) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomCrop` for details.""" + if torch.jit.is_scripting(): + return crop_image(inpt, top=top, left=left, height=height, width=width) + + _log_api_usage_once(crop) + + kernel = _get_kernel(crop, type(inpt)) + return kernel(inpt, top=top, left=left, height=height, width=width) + + +@_register_kernel_internal(crop, torch.Tensor) +@_register_kernel_internal(crop, tv_tensors.Image) +def crop_image(image: torch.Tensor, top: int, left: int, height: int, width: int) -> torch.Tensor: + h, w = image.shape[-2:] + + right = left + width + bottom = top + height + + if left < 0 or top < 0 or right > w or bottom > h: + image = image[..., max(top, 0) : bottom, max(left, 0) : right] + torch_padding = [ + max(min(right, 0) - left, 0), + max(right - max(w, left), 0), + max(min(bottom, 0) - top, 0), + max(bottom - max(h, top), 0), + ] + return _pad_with_scalar_fill(image, torch_padding, fill=0, padding_mode="constant") + return image[..., top:bottom, left:right] + + +_crop_image_pil = _FP.crop +_register_kernel_internal(crop, PIL.Image.Image)(_crop_image_pil) + + +def crop_keypoints( + keypoints: torch.Tensor, + top: int, + left: int, + height: int, + width: int, +) -> tuple[torch.Tensor, tuple[int, int]]: + + keypoints = keypoints - torch.tensor([left, top], dtype=keypoints.dtype, device=keypoints.device) + canvas_size = (height, width) + + return keypoints, canvas_size + + +@_register_kernel_internal(crop, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _crop_keypoints_dispatch( + inpt: tv_tensors.KeyPoints, top: int, left: int, height: int, width: int +) -> tv_tensors.KeyPoints: + output, canvas_size = crop_keypoints(inpt.as_subclass(torch.Tensor), top=top, left=left, height=height, width=width) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +def crop_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + top: int, + left: int, + height: int, + width: int, + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> tuple[torch.Tensor, tuple[int, int]]: + + # Crop or implicit pad if left and/or top have negative values: + if format == tv_tensors.BoundingBoxFormat.XYXYXYXY: + sub = [left, top, left, top, left, top, left, top] + elif format == tv_tensors.BoundingBoxFormat.XYWHR or format == tv_tensors.BoundingBoxFormat.CXCYWHR: + sub = [left, top, 0, 0, 0] + elif format == tv_tensors.BoundingBoxFormat.XYXY: + sub = [left, top, left, top] + else: + sub = [left, top, 0, 0] + + bounding_boxes = bounding_boxes - torch.tensor(sub, dtype=bounding_boxes.dtype, device=bounding_boxes.device) + canvas_size = (height, width) + + if format == tv_tensors.BoundingBoxFormat.XYXYXYXY: + bounding_boxes = _parallelogram_to_bounding_boxes(bounding_boxes) + + return ( + clamp_bounding_boxes(bounding_boxes, format=format, canvas_size=canvas_size, clamping_mode=clamping_mode), + canvas_size, + ) + + +@_register_kernel_internal(crop, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _crop_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, top: int, left: int, height: int, width: int +) -> tv_tensors.BoundingBoxes: + output, canvas_size = crop_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + top=top, + left=left, + height=height, + width=width, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +@_register_kernel_internal(crop, tv_tensors.Mask) +def crop_mask(mask: torch.Tensor, top: int, left: int, height: int, width: int) -> torch.Tensor: + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = crop_image(mask, top, left, height, width) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +@_register_kernel_internal(crop, tv_tensors.Video) +def crop_video(video: torch.Tensor, top: int, left: int, height: int, width: int) -> torch.Tensor: + return crop_image(video, top, left, height, width) + + +def perspective( + inpt: torch.Tensor, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, + coefficients: Optional[list[float]] = None, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomPerspective` for details.""" + if torch.jit.is_scripting(): + return perspective_image( + inpt, + startpoints=startpoints, + endpoints=endpoints, + interpolation=interpolation, + fill=fill, + coefficients=coefficients, + ) + + _log_api_usage_once(perspective) + + kernel = _get_kernel(perspective, type(inpt)) + return kernel( + inpt, + startpoints=startpoints, + endpoints=endpoints, + interpolation=interpolation, + fill=fill, + coefficients=coefficients, + ) + + +def _perspective_grid(coeffs: list[float], ow: int, oh: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor: + # https://github.com/python-pillow/Pillow/blob/4634eafe3c695a014267eefdce830b4a825beed7/ + # src/libImaging/Geometry.c#L394 + + # + # x_out = (coeffs[0] * x + coeffs[1] * y + coeffs[2]) / (coeffs[6] * x + coeffs[7] * y + 1) + # y_out = (coeffs[3] * x + coeffs[4] * y + coeffs[5]) / (coeffs[6] * x + coeffs[7] * y + 1) + # + theta1 = torch.tensor( + [[[coeffs[0], coeffs[1], coeffs[2]], [coeffs[3], coeffs[4], coeffs[5]]]], dtype=dtype, device=device + ) + theta2 = torch.tensor([[[coeffs[6], coeffs[7], 1.0], [coeffs[6], coeffs[7], 1.0]]], dtype=dtype, device=device) + + d = 0.5 + base_grid = torch.empty(1, oh, ow, 3, dtype=dtype, device=device) + x_grid = torch.linspace(d, ow + d - 1.0, steps=ow, device=device, dtype=dtype) + base_grid[..., 0].copy_(x_grid) + y_grid = torch.linspace(d, oh + d - 1.0, steps=oh, device=device, dtype=dtype).unsqueeze_(-1) + base_grid[..., 1].copy_(y_grid) + base_grid[..., 2].fill_(1) + + rescaled_theta1 = theta1.transpose(1, 2).div_(torch.tensor([0.5 * ow, 0.5 * oh], dtype=dtype, device=device)) + shape = (1, oh * ow, 3) + output_grid1 = base_grid.view(shape).bmm(rescaled_theta1) + output_grid2 = base_grid.view(shape).bmm(theta2.transpose(1, 2)) + + output_grid = output_grid1.div_(output_grid2).sub_(1.0) + return output_grid.view(1, oh, ow, 2) + + +def _perspective_coefficients( + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + coefficients: Optional[list[float]], +) -> list[float]: + if coefficients is not None: + if startpoints is not None and endpoints is not None: + raise ValueError("The startpoints/endpoints and the coefficients shouldn't be defined concurrently.") + elif len(coefficients) != 8: + raise ValueError("Argument coefficients should have 8 float values") + return coefficients + elif startpoints is not None and endpoints is not None: + return _get_perspective_coeffs(startpoints, endpoints) + else: + raise ValueError("Either the startpoints/endpoints or the coefficients must have non `None` values.") + + +@_register_kernel_internal(perspective, torch.Tensor) +@_register_kernel_internal(perspective, tv_tensors.Image) +def perspective_image( + image: torch.Tensor, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, + coefficients: Optional[list[float]] = None, +) -> torch.Tensor: + perspective_coeffs = _perspective_coefficients(startpoints, endpoints, coefficients) + interpolation = _check_interpolation(interpolation) + + _assert_grid_transform_inputs( + image, + matrix=None, + interpolation=interpolation.value, + fill=fill, + supported_interpolation_modes=["nearest", "bilinear"], + coeffs=perspective_coeffs, + ) + + oh, ow = image.shape[-2:] + dtype = image.dtype if torch.is_floating_point(image) else torch.float32 + grid = _perspective_grid(perspective_coeffs, ow=ow, oh=oh, dtype=dtype, device=image.device) + return _apply_grid_transform(image, grid, interpolation.value, fill=fill) + + +@_register_kernel_internal(perspective, PIL.Image.Image) +def _perspective_image_pil( + image: PIL.Image.Image, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, + coefficients: Optional[list[float]] = None, +) -> PIL.Image.Image: + perspective_coeffs = _perspective_coefficients(startpoints, endpoints, coefficients) + interpolation = _check_interpolation(interpolation) + return _FP.perspective(image, perspective_coeffs, interpolation=pil_modes_mapping[interpolation], fill=fill) + + +def perspective_keypoints( + keypoints: torch.Tensor, + canvas_size: tuple[int, int], + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + coefficients: Optional[list[float]] = None, +): + if keypoints.numel() == 0: + return keypoints + dtype = keypoints.dtype if torch.is_floating_point(keypoints) else torch.float32 + device = keypoints.device + original_shape = keypoints.shape + + keypoints = keypoints.clone().reshape(-1, 2) + perspective_coeffs = _perspective_coefficients(startpoints, endpoints, coefficients) + + denom = perspective_coeffs[0] * perspective_coeffs[4] - perspective_coeffs[1] * perspective_coeffs[3] + if denom == 0: + raise RuntimeError( + f"Provided perspective_coeffs {perspective_coeffs} can not be inverted to transform keypoints. " + f"Denominator is zero, denom={denom}" + ) + + theta1, theta2 = _compute_perspective_thetas(perspective_coeffs, dtype, device, denom) + points = torch.cat([keypoints, torch.ones(keypoints.shape[0], 1, device=keypoints.device)], dim=-1) + + numer_points = torch.matmul(points, theta1.T) + denom_points = torch.matmul(points, theta2.T) + transformed_points = numer_points.div_(denom_points) + return transformed_points.to(keypoints.dtype).reshape(original_shape) + + +@_register_kernel_internal(perspective, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _perspective_keypoints_dispatch( + inpt: tv_tensors.KeyPoints, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + coefficients: Optional[list[float]] = None, + **kwargs, +) -> tv_tensors.KeyPoints: + output = perspective_keypoints( + inpt.as_subclass(torch.Tensor), + canvas_size=inpt.canvas_size, + startpoints=startpoints, + endpoints=endpoints, + coefficients=coefficients, + ) + return tv_tensors.wrap(output, like=inpt) + + +def perspective_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + coefficients: Optional[list[float]] = None, + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> torch.Tensor: + if bounding_boxes.numel() == 0: + return bounding_boxes + + perspective_coeffs = _perspective_coefficients(startpoints, endpoints, coefficients) + + original_shape = bounding_boxes.shape + original_dtype = bounding_boxes.dtype + is_rotated = tv_tensors.is_rotated_bounding_format(format) + intermediate_format = tv_tensors.BoundingBoxFormat.XYXYXYXY if is_rotated else tv_tensors.BoundingBoxFormat.XYXY + # TODO: first cast to float if bbox is int64 before convert_bounding_box_format + bounding_boxes = ( + convert_bounding_box_format(bounding_boxes, old_format=format, new_format=intermediate_format) + ).reshape(-1, 8 if is_rotated else 4) + + dtype = bounding_boxes.dtype if torch.is_floating_point(bounding_boxes) else torch.float32 + device = bounding_boxes.device + + # perspective_coeffs are computed as endpoint -> start point + # We have to invert perspective_coeffs for bboxes: + # (x, y) - end point and (x_out, y_out) - start point + # x_out = (coeffs[0] * x + coeffs[1] * y + coeffs[2]) / (coeffs[6] * x + coeffs[7] * y + 1) + # y_out = (coeffs[3] * x + coeffs[4] * y + coeffs[5]) / (coeffs[6] * x + coeffs[7] * y + 1) + # and we would like to get: + # x = (inv_coeffs[0] * x_out + inv_coeffs[1] * y_out + inv_coeffs[2]) + # / (inv_coeffs[6] * x_out + inv_coeffs[7] * y_out + 1) + # y = (inv_coeffs[3] * x_out + inv_coeffs[4] * y_out + inv_coeffs[5]) + # / (inv_coeffs[6] * x_out + inv_coeffs[7] * y_out + 1) + # and compute inv_coeffs in terms of coeffs + + denom = perspective_coeffs[0] * perspective_coeffs[4] - perspective_coeffs[1] * perspective_coeffs[3] + if denom == 0: + raise RuntimeError( + f"Provided perspective_coeffs {perspective_coeffs} can not be inverted to transform bounding boxes. " + f"Denominator is zero, denom={denom}" + ) + + theta1, theta2 = _compute_perspective_thetas(perspective_coeffs, dtype, device, denom) + + # 1) Let's transform bboxes into a tensor of 4 points (top-left, top-right, bottom-left, bottom-right corners). + # Tensor of points has shape (N * 4, 3), where N is the number of bboxes + # Single point structure is similar to + # [(xmin, ymin, 1), (xmax, ymin, 1), (xmax, ymax, 1), (xmin, ymax, 1)] + points = bounding_boxes if is_rotated else bounding_boxes[:, [[0, 1], [2, 1], [2, 3], [0, 3]]] + points = points.reshape(-1, 2) + points = torch.cat([points, torch.ones(points.shape[0], 1, device=points.device)], dim=-1) + # 2) Now let's transform the points using perspective matrices + # x_out = (coeffs[0] * x + coeffs[1] * y + coeffs[2]) / (coeffs[6] * x + coeffs[7] * y + 1) + # y_out = (coeffs[3] * x + coeffs[4] * y + coeffs[5]) / (coeffs[6] * x + coeffs[7] * y + 1) + + numer_points = torch.matmul(points, theta1.T) + denom_points = torch.matmul(points, theta2.T) + transformed_points = numer_points.div_(denom_points) + + # 3) Reshape transformed points to [N boxes, 4 points, x/y coords] + # and compute bounding box from 4 transformed points: + if is_rotated: + transformed_points = transformed_points.reshape(-1, 8) + out_bboxes = _parallelogram_to_bounding_boxes(transformed_points) + else: + transformed_points = transformed_points.reshape(-1, 4, 2) + out_bbox_mins, out_bbox_maxs = torch.aminmax(transformed_points, dim=1) + out_bboxes = torch.cat([out_bbox_mins, out_bbox_maxs], dim=1) + + out_bboxes = clamp_bounding_boxes( + out_bboxes, format=intermediate_format, canvas_size=canvas_size, clamping_mode=clamping_mode + ) + + out_bboxes = convert_bounding_box_format( + out_bboxes, old_format=intermediate_format, new_format=format, inplace=True + ).reshape(original_shape) + + out_bboxes = out_bboxes.to(original_dtype) + return out_bboxes + + +def _compute_perspective_thetas( + perspective_coeffs: list[float], + dtype: torch.dtype, + device: torch.device, + denom: float, +) -> tuple[torch.Tensor, torch.Tensor]: + inv_coeffs = [ + (perspective_coeffs[4] - perspective_coeffs[5] * perspective_coeffs[7]) / denom, + (-perspective_coeffs[1] + perspective_coeffs[2] * perspective_coeffs[7]) / denom, + (perspective_coeffs[1] * perspective_coeffs[5] - perspective_coeffs[2] * perspective_coeffs[4]) / denom, + (-perspective_coeffs[3] + perspective_coeffs[5] * perspective_coeffs[6]) / denom, + (perspective_coeffs[0] - perspective_coeffs[2] * perspective_coeffs[6]) / denom, + (-perspective_coeffs[0] * perspective_coeffs[5] + perspective_coeffs[2] * perspective_coeffs[3]) / denom, + (-perspective_coeffs[4] * perspective_coeffs[6] + perspective_coeffs[3] * perspective_coeffs[7]) / denom, + (-perspective_coeffs[0] * perspective_coeffs[7] + perspective_coeffs[1] * perspective_coeffs[6]) / denom, + ] + + theta1 = torch.tensor( + [[inv_coeffs[0], inv_coeffs[1], inv_coeffs[2]], [inv_coeffs[3], inv_coeffs[4], inv_coeffs[5]]], + dtype=dtype, + device=device, + ) + + theta2 = torch.tensor( + [[inv_coeffs[6], inv_coeffs[7], 1.0], [inv_coeffs[6], inv_coeffs[7], 1.0]], dtype=dtype, device=device + ) + + return theta1, theta2 + + +@_register_kernel_internal(perspective, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _perspective_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + coefficients: Optional[list[float]] = None, + **kwargs, +) -> tv_tensors.BoundingBoxes: + output = perspective_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + startpoints=startpoints, + endpoints=endpoints, + coefficients=coefficients, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt) + + +def perspective_mask( + mask: torch.Tensor, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + fill: _FillTypeJIT = None, + coefficients: Optional[list[float]] = None, +) -> torch.Tensor: + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = perspective_image( + mask, startpoints, endpoints, interpolation=InterpolationMode.NEAREST, fill=fill, coefficients=coefficients + ) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +@_register_kernel_internal(perspective, tv_tensors.Mask, tv_tensor_wrapper=False) +def _perspective_mask_dispatch( + inpt: tv_tensors.Mask, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + fill: _FillTypeJIT = None, + coefficients: Optional[list[float]] = None, + **kwargs, +) -> tv_tensors.Mask: + output = perspective_mask( + inpt.as_subclass(torch.Tensor), + startpoints=startpoints, + endpoints=endpoints, + fill=fill, + coefficients=coefficients, + ) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(perspective, tv_tensors.Video) +def perspective_video( + video: torch.Tensor, + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, + coefficients: Optional[list[float]] = None, +) -> torch.Tensor: + return perspective_image( + video, startpoints, endpoints, interpolation=interpolation, fill=fill, coefficients=coefficients + ) + + +def elastic( + inpt: torch.Tensor, + displacement: torch.Tensor, + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.ElasticTransform` for details.""" + if torch.jit.is_scripting(): + return elastic_image(inpt, displacement=displacement, interpolation=interpolation, fill=fill) + + _log_api_usage_once(elastic) + + kernel = _get_kernel(elastic, type(inpt)) + return kernel(inpt, displacement=displacement, interpolation=interpolation, fill=fill) + + +elastic_transform = elastic + + +@_register_kernel_internal(elastic, torch.Tensor) +@_register_kernel_internal(elastic, tv_tensors.Image) +def elastic_image( + image: torch.Tensor, + displacement: torch.Tensor, + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + if not isinstance(displacement, torch.Tensor): + raise TypeError("Argument displacement should be a Tensor") + + interpolation = _check_interpolation(interpolation) + + height, width = image.shape[-2:] + device = image.device + dtype = image.dtype if torch.is_floating_point(image) else torch.float32 + + # Patch: elastic transform should support (cpu,f16) input + is_cpu_half = device.type == "cpu" and dtype == torch.float16 + if is_cpu_half: + image = image.to(torch.float32) + dtype = torch.float32 + + # We are aware that if input image dtype is uint8 and displacement is float64 then + # displacement will be cast to float32 and all computations will be done with float32 + # We can fix this later if needed + + expected_shape = (1, height, width, 2) + if expected_shape != displacement.shape: + raise ValueError(f"Argument displacement shape should be {expected_shape}, but given {displacement.shape}") + + grid = _create_identity_grid((height, width), device=device, dtype=dtype).add_( + displacement.to(dtype=dtype, device=device) + ) + output = _apply_grid_transform(image, grid, interpolation.value, fill=fill) + + if is_cpu_half: + output = output.to(torch.float16) + + return output + + +@_register_kernel_internal(elastic, PIL.Image.Image) +def _elastic_image_pil( + image: PIL.Image.Image, + displacement: torch.Tensor, + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, +) -> PIL.Image.Image: + t_img = pil_to_tensor(image) + output = elastic_image(t_img, displacement, interpolation=interpolation, fill=fill) + return to_pil_image(output, mode=image.mode) + + +def _create_identity_grid(size: tuple[int, int], device: torch.device, dtype: torch.dtype) -> torch.Tensor: + sy, sx = size + base_grid = torch.empty(1, sy, sx, 2, device=device, dtype=dtype) + x_grid = torch.linspace((-sx + 1) / sx, (sx - 1) / sx, sx, device=device, dtype=dtype) + base_grid[..., 0].copy_(x_grid) + + y_grid = torch.linspace((-sy + 1) / sy, (sy - 1) / sy, sy, device=device, dtype=dtype).unsqueeze_(-1) + base_grid[..., 1].copy_(y_grid) + + return base_grid + + +def elastic_keypoints( + keypoints: torch.Tensor, canvas_size: tuple[int, int], displacement: torch.Tensor +) -> torch.Tensor: + expected_shape = (1, canvas_size[0], canvas_size[1], 2) + if not isinstance(displacement, torch.Tensor): + raise TypeError("Argument displacement should be a Tensor") + elif displacement.shape != expected_shape: + raise ValueError(f"Argument displacement shape should be {expected_shape}, but given {displacement.shape}") + + if keypoints.numel() == 0: + return keypoints + + device = keypoints.device + dtype = keypoints.dtype if torch.is_floating_point(keypoints) else torch.float32 + + if displacement.dtype != dtype or displacement.device != device: + displacement = displacement.to(dtype=dtype, device=device) + + original_shape = keypoints.shape + keypoints = keypoints.clone().reshape(-1, 2) + + id_grid = _create_identity_grid(canvas_size, device=device, dtype=dtype) + inv_grid = id_grid.sub_(displacement) + + index_xy = keypoints.to(dtype=torch.long) + index_x, index_y = index_xy[:, 0], index_xy[:, 1] + # Unlike bounding boxes, this may not work well. + index_x.clamp_(0, inv_grid.shape[2] - 1) + index_y.clamp_(0, inv_grid.shape[1] - 1) + + t_size = torch.tensor(canvas_size[::-1], device=displacement.device, dtype=displacement.dtype) + transformed_points = inv_grid[0, index_y, index_x, :].add_(1).mul_(0.5 * t_size).sub_(0.5) + + return transformed_points.to(keypoints.dtype).reshape(original_shape) + + +@_register_kernel_internal(elastic, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _elastic_keypoints_dispatch(inpt: tv_tensors.KeyPoints, displacement: torch.Tensor, **kwargs): + output = elastic_keypoints(inpt.as_subclass(torch.Tensor), canvas_size=inpt.canvas_size, displacement=displacement) + return tv_tensors.wrap(output, like=inpt) + + +def elastic_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + displacement: torch.Tensor, + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> torch.Tensor: + expected_shape = (1, canvas_size[0], canvas_size[1], 2) + if not isinstance(displacement, torch.Tensor): + raise TypeError("Argument displacement should be a Tensor") + elif displacement.shape != expected_shape: + raise ValueError(f"Argument displacement shape should be {expected_shape}, but given {displacement.shape}") + + if bounding_boxes.numel() == 0: + return bounding_boxes + + # TODO: add in docstring about approximation we are doing for grid inversion + device = bounding_boxes.device + dtype = bounding_boxes.dtype if torch.is_floating_point(bounding_boxes) else torch.float32 + is_rotated = tv_tensors.is_rotated_bounding_format(format) + + if displacement.dtype != dtype or displacement.device != device: + displacement = displacement.to(dtype=dtype, device=device) + + original_shape = bounding_boxes.shape + # TODO: first cast to float if bbox is int64 before convert_bounding_box_format + intermediate_format = tv_tensors.BoundingBoxFormat.CXCYWHR if is_rotated else tv_tensors.BoundingBoxFormat.XYXY + + bounding_boxes = ( + convert_bounding_box_format(bounding_boxes.clone(), old_format=format, new_format=intermediate_format) + ).reshape(-1, 5 if is_rotated else 4) + + id_grid = _create_identity_grid(canvas_size, device=device, dtype=dtype) + # We construct an approximation of inverse grid as inv_grid = id_grid - displacement + # This is not an exact inverse of the grid + inv_grid = id_grid.sub_(displacement) + + # Get points from bboxes + points = bounding_boxes[:, :2] if is_rotated else bounding_boxes[:, [[0, 1], [2, 1], [2, 3], [0, 3]]] + points = points.reshape(-1, 2) + if points.is_floating_point(): + points = points.ceil_() + index_xy = points.to(dtype=torch.long) + index_x, index_y = index_xy[:, 0], index_xy[:, 1] + index_x = index_x.clamp(0, inv_grid.shape[2] - 1) + index_y = index_y.clamp(0, inv_grid.shape[1] - 1) + + # Transform points: + t_size = torch.tensor(canvas_size[::-1], device=displacement.device, dtype=displacement.dtype) + transformed_points = inv_grid[0, index_y, index_x, :].add_(1).mul_(0.5 * t_size).sub_(0.5) + + if is_rotated: + transformed_points = transformed_points.reshape(-1, 2) + out_bboxes = torch.cat([transformed_points, bounding_boxes[:, 2:]], dim=1).to(bounding_boxes.dtype) + else: + transformed_points = transformed_points.reshape(-1, 4, 2) + out_bbox_mins, out_bbox_maxs = torch.aminmax(transformed_points, dim=1) + out_bboxes = torch.cat([out_bbox_mins, out_bbox_maxs], dim=1).to(bounding_boxes.dtype) + + out_bboxes = clamp_bounding_boxes( + out_bboxes, format=intermediate_format, canvas_size=canvas_size, clamping_mode=clamping_mode + ) + + return convert_bounding_box_format( + out_bboxes, old_format=intermediate_format, new_format=format, inplace=False + ).reshape(original_shape) + + +@_register_kernel_internal(elastic, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _elastic_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, displacement: torch.Tensor, **kwargs +) -> tv_tensors.BoundingBoxes: + output = elastic_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + displacement=displacement, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt) + + +def elastic_mask( + mask: torch.Tensor, + displacement: torch.Tensor, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = elastic_image(mask, displacement=displacement, interpolation=InterpolationMode.NEAREST, fill=fill) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +@_register_kernel_internal(elastic, tv_tensors.Mask, tv_tensor_wrapper=False) +def _elastic_mask_dispatch( + inpt: tv_tensors.Mask, displacement: torch.Tensor, fill: _FillTypeJIT = None, **kwargs +) -> tv_tensors.Mask: + output = elastic_mask(inpt.as_subclass(torch.Tensor), displacement=displacement, fill=fill) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(elastic, tv_tensors.Video) +def elastic_video( + video: torch.Tensor, + displacement: torch.Tensor, + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, +) -> torch.Tensor: + return elastic_image(video, displacement, interpolation=interpolation, fill=fill) + + +def center_crop(inpt: torch.Tensor, output_size: list[int]) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.CenterCrop` for details.""" + if torch.jit.is_scripting(): + return center_crop_image(inpt, output_size=output_size) + + _log_api_usage_once(center_crop) + + kernel = _get_kernel(center_crop, type(inpt)) + return kernel(inpt, output_size=output_size) + + +def _center_crop_parse_output_size(output_size: list[int]) -> list[int]: + if isinstance(output_size, numbers.Number): + s = int(output_size) + return [s, s] + elif isinstance(output_size, (tuple, list)) and len(output_size) == 1: + return [output_size[0], output_size[0]] + else: + return list(output_size) + + +def _center_crop_compute_padding(crop_height: int, crop_width: int, image_height: int, image_width: int) -> list[int]: + return [ + (crop_width - image_width) // 2 if crop_width > image_width else 0, + (crop_height - image_height) // 2 if crop_height > image_height else 0, + (crop_width - image_width + 1) // 2 if crop_width > image_width else 0, + (crop_height - image_height + 1) // 2 if crop_height > image_height else 0, + ] + + +def _center_crop_compute_crop_anchor( + crop_height: int, crop_width: int, image_height: int, image_width: int +) -> tuple[int, int]: + crop_top = int(round((image_height - crop_height) / 2.0)) + crop_left = int(round((image_width - crop_width) / 2.0)) + return crop_top, crop_left + + +@_register_kernel_internal(center_crop, torch.Tensor) +@_register_kernel_internal(center_crop, tv_tensors.Image) +def center_crop_image(image: torch.Tensor, output_size: list[int]) -> torch.Tensor: + crop_height, crop_width = _center_crop_parse_output_size(output_size) + shape = image.shape + if image.numel() == 0: + return image.reshape(shape[:-2] + (crop_height, crop_width)) + image_height, image_width = shape[-2:] + + if crop_height > image_height or crop_width > image_width: + padding_ltrb = _center_crop_compute_padding(crop_height, crop_width, image_height, image_width) + image = torch_pad(image, _parse_pad_padding(padding_ltrb), value=0.0) + + image_height, image_width = image.shape[-2:] + if crop_width == image_width and crop_height == image_height: + return image + + crop_top, crop_left = _center_crop_compute_crop_anchor(crop_height, crop_width, image_height, image_width) + return image[..., crop_top : (crop_top + crop_height), crop_left : (crop_left + crop_width)] + + +@_register_kernel_internal(center_crop, PIL.Image.Image) +def _center_crop_image_pil(image: PIL.Image.Image, output_size: list[int]) -> PIL.Image.Image: + crop_height, crop_width = _center_crop_parse_output_size(output_size) + image_height, image_width = _get_size_image_pil(image) + + if crop_height > image_height or crop_width > image_width: + padding_ltrb = _center_crop_compute_padding(crop_height, crop_width, image_height, image_width) + image = _pad_image_pil(image, padding_ltrb, fill=0) + + image_height, image_width = _get_size_image_pil(image) + if crop_width == image_width and crop_height == image_height: + return image + + crop_top, crop_left = _center_crop_compute_crop_anchor(crop_height, crop_width, image_height, image_width) + return _crop_image_pil(image, crop_top, crop_left, crop_height, crop_width) + + +def center_crop_keypoints(inpt: torch.Tensor, canvas_size: tuple[int, int], output_size: list[int]): + crop_height, crop_width = _center_crop_parse_output_size(output_size) + crop_top, crop_left = _center_crop_compute_crop_anchor(crop_height, crop_width, *canvas_size) + return crop_keypoints(inpt, top=crop_top, left=crop_left, height=crop_height, width=crop_width) + + +@_register_kernel_internal(center_crop, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _center_crop_keypoints_dispatch(inpt: tv_tensors.KeyPoints, output_size: list[int]) -> tv_tensors.KeyPoints: + output, canvas_size = center_crop_keypoints( + inpt.as_subclass(torch.Tensor), canvas_size=inpt.canvas_size, output_size=output_size + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +def center_crop_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + output_size: list[int], + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> tuple[torch.Tensor, tuple[int, int]]: + crop_height, crop_width = _center_crop_parse_output_size(output_size) + crop_top, crop_left = _center_crop_compute_crop_anchor(crop_height, crop_width, *canvas_size) + return crop_bounding_boxes( + bounding_boxes, + format, + top=crop_top, + left=crop_left, + height=crop_height, + width=crop_width, + clamping_mode=clamping_mode, + ) + + +@_register_kernel_internal(center_crop, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _center_crop_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, output_size: list[int] +) -> tv_tensors.BoundingBoxes: + output, canvas_size = center_crop_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + output_size=output_size, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +@_register_kernel_internal(center_crop, tv_tensors.Mask) +def center_crop_mask(mask: torch.Tensor, output_size: list[int]) -> torch.Tensor: + if mask.ndim < 3: + mask = mask.unsqueeze(0) + needs_squeeze = True + else: + needs_squeeze = False + + output = center_crop_image(image=mask, output_size=output_size) + + if needs_squeeze: + output = output.squeeze(0) + + return output + + +@_register_kernel_internal(center_crop, tv_tensors.Video) +def center_crop_video(video: torch.Tensor, output_size: list[int]) -> torch.Tensor: + return center_crop_image(video, output_size) + + +def resized_crop( + inpt: torch.Tensor, + top: int, + left: int, + height: int, + width: int, + size: list[int], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.RandomResizedCrop` for details.""" + if torch.jit.is_scripting(): + return resized_crop_image( + inpt, + top=top, + left=left, + height=height, + width=width, + size=size, + interpolation=interpolation, + antialias=antialias, + ) + + _log_api_usage_once(resized_crop) + + kernel = _get_kernel(resized_crop, type(inpt)) + return kernel( + inpt, + top=top, + left=left, + height=height, + width=width, + size=size, + interpolation=interpolation, + antialias=antialias, + ) + + +@_register_kernel_internal(resized_crop, torch.Tensor) +@_register_kernel_internal(resized_crop, tv_tensors.Image) +def resized_crop_image( + image: torch.Tensor, + top: int, + left: int, + height: int, + width: int, + size: list[int], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, +) -> torch.Tensor: + image = crop_image(image, top, left, height, width) + return resize_image(image, size, interpolation=interpolation, antialias=antialias) + + +def _resized_crop_image_pil( + image: PIL.Image.Image, + top: int, + left: int, + height: int, + width: int, + size: list[int], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, +) -> PIL.Image.Image: + image = _crop_image_pil(image, top, left, height, width) + return _resize_image_pil(image, size, interpolation=interpolation) + + +@_register_kernel_internal(resized_crop, PIL.Image.Image) +def _resized_crop_image_pil_dispatch( + image: PIL.Image.Image, + top: int, + left: int, + height: int, + width: int, + size: list[int], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, +) -> PIL.Image.Image: + if antialias is False: + warnings.warn("Anti-alias option is always applied for PIL Image input. Argument antialias is ignored.") + return _resized_crop_image_pil( + image, + top=top, + left=left, + height=height, + width=width, + size=size, + interpolation=interpolation, + ) + + +def resized_crop_keypoints( + keypoints: torch.Tensor, + top: int, + left: int, + height: int, + width: int, + size: list[int], +) -> tuple[torch.Tensor, tuple[int, int]]: + keypoints, canvas_size = crop_keypoints(keypoints, top, left, height, width) + return resize_keypoints(keypoints, size=size, canvas_size=canvas_size) + + +@_register_kernel_internal(resized_crop, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def _resized_crop_keypoints_dispatch( + inpt: tv_tensors.BoundingBoxes, top: int, left: int, height: int, width: int, size: list[int], **kwargs +): + output, canvas_size = resized_crop_keypoints( + inpt.as_subclass(torch.Tensor), top=top, left=left, height=height, width=width, size=size + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +def resized_crop_bounding_boxes( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + top: int, + left: int, + height: int, + width: int, + size: list[int], + clamping_mode: CLAMPING_MODE_TYPE = "soft", +) -> tuple[torch.Tensor, tuple[int, int]]: + bounding_boxes, canvas_size = crop_bounding_boxes( + bounding_boxes, format, top, left, height, width, clamping_mode=clamping_mode + ) + return resize_bounding_boxes( + bounding_boxes, format=format, canvas_size=canvas_size, size=size, clamping_mode=clamping_mode + ) + + +@_register_kernel_internal(resized_crop, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def _resized_crop_bounding_boxes_dispatch( + inpt: tv_tensors.BoundingBoxes, top: int, left: int, height: int, width: int, size: list[int], **kwargs +) -> tv_tensors.BoundingBoxes: + output, canvas_size = resized_crop_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + top=top, + left=left, + height=height, + width=width, + size=size, + clamping_mode=inpt.clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt, canvas_size=canvas_size) + + +def resized_crop_mask( + mask: torch.Tensor, + top: int, + left: int, + height: int, + width: int, + size: list[int], +) -> torch.Tensor: + mask = crop_mask(mask, top, left, height, width) + return resize_mask(mask, size) + + +@_register_kernel_internal(resized_crop, tv_tensors.Mask, tv_tensor_wrapper=False) +def _resized_crop_mask_dispatch( + inpt: tv_tensors.Mask, top: int, left: int, height: int, width: int, size: list[int], **kwargs +) -> tv_tensors.Mask: + output = resized_crop_mask( + inpt.as_subclass(torch.Tensor), top=top, left=left, height=height, width=width, size=size + ) + return tv_tensors.wrap(output, like=inpt) + + +@_register_kernel_internal(resized_crop, tv_tensors.Video) +def resized_crop_video( + video: torch.Tensor, + top: int, + left: int, + height: int, + width: int, + size: list[int], + interpolation: Union[str, InterpolationMode, int] = InterpolationMode.BILINEAR, + antialias: Optional[bool] = True, +) -> torch.Tensor: + return resized_crop_image( + video, top, left, height, width, antialias=antialias, size=size, interpolation=interpolation + ) + + +def five_crop( + inpt: torch.Tensor, size: list[int] +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """See :class:`~torchvision.transforms.v2.FiveCrop` for details.""" + if torch.jit.is_scripting(): + return five_crop_image(inpt, size=size) + + _log_api_usage_once(five_crop) + + kernel = _get_kernel(five_crop, type(inpt)) + return kernel(inpt, size=size) + + +def _parse_five_crop_size(size: list[int]) -> list[int]: + if isinstance(size, numbers.Number): + s = int(size) + size = [s, s] + elif isinstance(size, (tuple, list)) and len(size) == 1: + s = size[0] + size = [s, s] + + if len(size) != 2: + raise ValueError("Please provide only two dimensions (h, w) for size.") + + return size + + +@_register_five_ten_crop_kernel_internal(five_crop, torch.Tensor) +@_register_five_ten_crop_kernel_internal(five_crop, tv_tensors.Image) +def five_crop_image( + image: torch.Tensor, size: list[int] +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + crop_height, crop_width = _parse_five_crop_size(size) + image_height, image_width = image.shape[-2:] + + if crop_width > image_width or crop_height > image_height: + raise ValueError(f"Requested crop size {size} is bigger than input size {(image_height, image_width)}") + + tl = crop_image(image, 0, 0, crop_height, crop_width) + tr = crop_image(image, 0, image_width - crop_width, crop_height, crop_width) + bl = crop_image(image, image_height - crop_height, 0, crop_height, crop_width) + br = crop_image(image, image_height - crop_height, image_width - crop_width, crop_height, crop_width) + center = center_crop_image(image, [crop_height, crop_width]) + + return tl, tr, bl, br, center + + +@_register_five_ten_crop_kernel_internal(five_crop, PIL.Image.Image) +def _five_crop_image_pil( + image: PIL.Image.Image, size: list[int] +) -> tuple[PIL.Image.Image, PIL.Image.Image, PIL.Image.Image, PIL.Image.Image, PIL.Image.Image]: + crop_height, crop_width = _parse_five_crop_size(size) + image_height, image_width = _get_size_image_pil(image) + + if crop_width > image_width or crop_height > image_height: + raise ValueError(f"Requested crop size {size} is bigger than input size {(image_height, image_width)}") + + tl = _crop_image_pil(image, 0, 0, crop_height, crop_width) + tr = _crop_image_pil(image, 0, image_width - crop_width, crop_height, crop_width) + bl = _crop_image_pil(image, image_height - crop_height, 0, crop_height, crop_width) + br = _crop_image_pil(image, image_height - crop_height, image_width - crop_width, crop_height, crop_width) + center = _center_crop_image_pil(image, [crop_height, crop_width]) + + return tl, tr, bl, br, center + + +@_register_five_ten_crop_kernel_internal(five_crop, tv_tensors.Video) +def five_crop_video( + video: torch.Tensor, size: list[int] +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + return five_crop_image(video, size) + + +def ten_crop( + inpt: torch.Tensor, size: list[int], vertical_flip: bool = False +) -> tuple[ + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, +]: + """See :class:`~torchvision.transforms.v2.TenCrop` for details.""" + if torch.jit.is_scripting(): + return ten_crop_image(inpt, size=size, vertical_flip=vertical_flip) + + _log_api_usage_once(ten_crop) + + kernel = _get_kernel(ten_crop, type(inpt)) + return kernel(inpt, size=size, vertical_flip=vertical_flip) + + +@_register_five_ten_crop_kernel_internal(ten_crop, torch.Tensor) +@_register_five_ten_crop_kernel_internal(ten_crop, tv_tensors.Image) +def ten_crop_image( + image: torch.Tensor, size: list[int], vertical_flip: bool = False +) -> tuple[ + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, +]: + non_flipped = five_crop_image(image, size) + + if vertical_flip: + image = vertical_flip_image(image) + else: + image = horizontal_flip_image(image) + + flipped = five_crop_image(image, size) + + return non_flipped + flipped + + +@_register_five_ten_crop_kernel_internal(ten_crop, PIL.Image.Image) +def _ten_crop_image_pil( + image: PIL.Image.Image, size: list[int], vertical_flip: bool = False +) -> tuple[ + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, + PIL.Image.Image, +]: + non_flipped = _five_crop_image_pil(image, size) + + if vertical_flip: + image = _vertical_flip_image_pil(image) + else: + image = _horizontal_flip_image_pil(image) + + flipped = _five_crop_image_pil(image, size) + + return non_flipped + flipped + + +@_register_five_ten_crop_kernel_internal(ten_crop, tv_tensors.Video) +def ten_crop_video( + video: torch.Tensor, size: list[int], vertical_flip: bool = False +) -> tuple[ + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, + torch.Tensor, +]: + return ten_crop_image(video, size, vertical_flip=vertical_flip) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_meta.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..80bd23a926dfba0609a747dcfba4f2fba00f90b9 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_meta.py @@ -0,0 +1,741 @@ +from typing import Optional, Union + +import PIL.Image +import torch +from torchvision import tv_tensors +from torchvision.transforms import _functional_pil as _FP +from torchvision.tv_tensors import BoundingBoxFormat +from torchvision.tv_tensors._bounding_boxes import CLAMPING_MODE_TYPE + +from torchvision.utils import _log_api_usage_once + +from ._utils import _get_kernel, _register_kernel_internal, is_pure_tensor + + +def get_dimensions(inpt: torch.Tensor) -> list[int]: + if torch.jit.is_scripting(): + return get_dimensions_image(inpt) + + _log_api_usage_once(get_dimensions) + + kernel = _get_kernel(get_dimensions, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(get_dimensions, torch.Tensor) +@_register_kernel_internal(get_dimensions, tv_tensors.Image, tv_tensor_wrapper=False) +def get_dimensions_image(image: torch.Tensor) -> list[int]: + chw = list(image.shape[-3:]) + ndims = len(chw) + if ndims == 3: + return chw + elif ndims == 2: + chw.insert(0, 1) + return chw + else: + raise TypeError(f"Input tensor should have at least two dimensions, but got {ndims}") + + +_get_dimensions_image_pil = _register_kernel_internal(get_dimensions, PIL.Image.Image)(_FP.get_dimensions) + + +@_register_kernel_internal(get_dimensions, tv_tensors.Video, tv_tensor_wrapper=False) +def get_dimensions_video(video: torch.Tensor) -> list[int]: + return get_dimensions_image(video) + + +def get_num_channels(inpt: torch.Tensor) -> int: + if torch.jit.is_scripting(): + return get_num_channels_image(inpt) + + _log_api_usage_once(get_num_channels) + + kernel = _get_kernel(get_num_channels, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(get_num_channels, torch.Tensor) +@_register_kernel_internal(get_num_channels, tv_tensors.Image, tv_tensor_wrapper=False) +def get_num_channels_image(image: torch.Tensor) -> int: + chw = image.shape[-3:] + ndims = len(chw) + if ndims == 3: + return chw[0] + elif ndims == 2: + return 1 + else: + raise TypeError(f"Input tensor should have at least two dimensions, but got {ndims}") + + +_get_num_channels_image_pil = _register_kernel_internal(get_num_channels, PIL.Image.Image)(_FP.get_image_num_channels) + + +@_register_kernel_internal(get_num_channels, tv_tensors.Video, tv_tensor_wrapper=False) +def get_num_channels_video(video: torch.Tensor) -> int: + return get_num_channels_image(video) + + +# We changed the names to ensure it can be used not only for images but also videos. Thus, we just alias it without +# deprecating the old names. +get_image_num_channels = get_num_channels + + +def get_size(inpt: torch.Tensor) -> list[int]: + if torch.jit.is_scripting(): + return get_size_image(inpt) + + _log_api_usage_once(get_size) + + kernel = _get_kernel(get_size, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(get_size, torch.Tensor) +@_register_kernel_internal(get_size, tv_tensors.Image, tv_tensor_wrapper=False) +def get_size_image(image: torch.Tensor) -> list[int]: + hw = list(image.shape[-2:]) + ndims = len(hw) + if ndims == 2: + return hw + else: + raise TypeError(f"Input tensor should have at least two dimensions, but got {ndims}") + + +@_register_kernel_internal(get_size, PIL.Image.Image) +def _get_size_image_pil(image: PIL.Image.Image) -> list[int]: + width, height = _FP.get_image_size(image) + return [height, width] + + +@_register_kernel_internal(get_size, tv_tensors.Video, tv_tensor_wrapper=False) +def get_size_video(video: torch.Tensor) -> list[int]: + return get_size_image(video) + + +@_register_kernel_internal(get_size, tv_tensors.Mask, tv_tensor_wrapper=False) +def get_size_mask(mask: torch.Tensor) -> list[int]: + return get_size_image(mask) + + +@_register_kernel_internal(get_size, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +def get_size_bounding_boxes(bounding_box: tv_tensors.BoundingBoxes) -> list[int]: + return list(bounding_box.canvas_size) + + +@_register_kernel_internal(get_size, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +def get_size_keypoints(keypoints: tv_tensors.KeyPoints) -> list[int]: + return list(keypoints.canvas_size) + + +def get_num_frames(inpt: torch.Tensor) -> int: + if torch.jit.is_scripting(): + return get_num_frames_video(inpt) + + _log_api_usage_once(get_num_frames) + + kernel = _get_kernel(get_num_frames, type(inpt)) + return kernel(inpt) + + +@_register_kernel_internal(get_num_frames, torch.Tensor) +@_register_kernel_internal(get_num_frames, tv_tensors.Video, tv_tensor_wrapper=False) +def get_num_frames_video(video: torch.Tensor) -> int: + return video.shape[-4] + + +def _xywh_to_xyxy(xywh: torch.Tensor, inplace: bool) -> torch.Tensor: + xyxy = xywh if inplace else xywh.clone() + xyxy[..., 2:] += xyxy[..., :2] + return xyxy + + +def _xyxy_to_xywh(xyxy: torch.Tensor, inplace: bool) -> torch.Tensor: + xywh = xyxy if inplace else xyxy.clone() + xywh[..., 2:] -= xywh[..., :2] + return xywh + + +def _xywh_to_cxcywh(xywh: torch.Tensor, inplace: bool) -> torch.Tensor: + if not inplace: + xywh = xywh.clone() + + # cx = x + width / 2, cy = y + height / 2, width and height stay the same + xywh[..., :2].add_(xywh[..., 2:].div(2, rounding_mode=None if xywh.is_floating_point() else "floor")) + + return xywh + + +def _cxcywh_to_xywh(cxcywh: torch.Tensor, inplace: bool) -> torch.Tensor: + # For integer tensors, use float arithmetic to match the behavior of the + # two-step conversion CXCYWH -> XYXY -> XYWH (where _cxcywh_to_xyxy uses + # float arithmetic, see PR #9322). + original = cxcywh + dtype = cxcywh.dtype + need_cast = not cxcywh.is_floating_point() + + if need_cast: + cxcywh = cxcywh.float() + elif not inplace: + cxcywh = cxcywh.clone() + + half_wh = cxcywh[..., 2:] / 2 + # x = cx - w/2, y = cy - h/2 + cxcywh[..., :2].sub_(half_wh) + + if need_cast: + # For integer types, truncation of x1/y1 and x2/y2 (= x1 + w, y1 + h) can change + # the effective width/height. Recompute w/h to match the two-step path. + x2y2 = (cxcywh[..., :2] + cxcywh[..., 2:]).to(dtype) + cxcywh = cxcywh.to(dtype) + cxcywh[..., 2:] = x2y2 - cxcywh[..., :2] + if inplace: + original[:] = cxcywh + return original + + return cxcywh + + +def _cxcywh_to_xyxy(cxcywh: torch.Tensor, inplace: bool) -> torch.Tensor: + # For integer tensors, use float arithmetic to match the behavior of + # `torchvision.ops._box_convert._box_cxcywh_to_xyxy`. + original = cxcywh + dtype = cxcywh.dtype + need_cast = not cxcywh.is_floating_point() + + if need_cast: + cxcywh = cxcywh.float() + elif not inplace: + cxcywh = cxcywh.clone() + + half_wh = cxcywh[..., 2:] / 2 + # (cx - width / 2) = x1, same for y1 + cxcywh[..., :2].sub_(half_wh) + # (x1 + width) = x2, same for y2 + cxcywh[..., 2:].add_(cxcywh[..., :2]) + + if need_cast: + cxcywh = cxcywh.to(dtype) + if inplace: + original[:] = cxcywh + return original + + return cxcywh + + +def _xyxy_to_cxcywh(xyxy: torch.Tensor, inplace: bool) -> torch.Tensor: + if not inplace: + xyxy = xyxy.clone() + + # (x2 - x1) = width, same for height + xyxy[..., 2:].sub_(xyxy[..., :2]) + # (x1 * 2 + width) / 2 = x1 + width / 2 = x1 + (x2-x1)/2 = (x1 + x2)/2 = cx, same for cy + xyxy[..., :2].mul_(2).add_(xyxy[..., 2:]).div_(2, rounding_mode=None if xyxy.is_floating_point() else "floor") + + return xyxy + + +def _xyxy_to_keypoints(bounding_boxes: torch.Tensor) -> torch.Tensor: + return bounding_boxes[:, [[0, 1], [2, 1], [2, 3], [0, 3]]] + + +def _xyxyxyxy_to_keypoints(bounding_boxes: torch.Tensor) -> torch.Tensor: + return bounding_boxes[:, [[0, 1], [2, 3], [4, 5], [6, 7]]] + + +def _cxcywhr_to_xywhr(cxcywhr: torch.Tensor, inplace: bool) -> torch.Tensor: + if not inplace: + cxcywhr = cxcywhr.clone() + + half_wh = cxcywhr[..., 2:-1].div(-2, rounding_mode=None if cxcywhr.is_floating_point() else "floor").abs_() + r_rad = cxcywhr[..., 4].mul(torch.pi).div(180.0) + cos, sin = r_rad.cos(), r_rad.sin() + # (cx - width / 2 * cos - height / 2 * sin) = x1 + cxcywhr[..., 0].sub_(half_wh[..., 0].mul(cos)).sub_(half_wh[..., 1].mul(sin)) + # (cy + width / 2 * sin - height / 2 * cos) = y1 + cxcywhr[..., 1].add_(half_wh[..., 0].mul(sin)).sub_(half_wh[..., 1].mul(cos)) + + return cxcywhr + + +def _xywhr_to_cxcywhr(xywhr: torch.Tensor, inplace: bool) -> torch.Tensor: + if not inplace: + xywhr = xywhr.clone() + + half_wh = xywhr[..., 2:-1].div(-2, rounding_mode=None if xywhr.is_floating_point() else "floor").abs_() + r_rad = xywhr[..., 4].mul(torch.pi).div(180.0) + cos, sin = r_rad.cos(), r_rad.sin() + # (x1 + width / 2 * cos + height / 2 * sin) = cx + xywhr[..., 0].add_(half_wh[..., 0].mul(cos)).add_(half_wh[..., 1].mul(sin)) + # (y1 - width / 2 * sin + height / 2 * cos) = cy + xywhr[..., 1].sub_(half_wh[..., 0].mul(sin)).add_(half_wh[..., 1].mul(cos)) + + return xywhr + + +def _xywhr_to_xyxyxyxy(xywhr: torch.Tensor, inplace: bool) -> torch.Tensor: + # NOTE: This function cannot modify the input tensor inplace as it requires a dimension change. + if not inplace: + xywhr = xywhr.clone() + + wh = xywhr[..., 2:-1] + r_rad = xywhr[..., 4].mul(torch.pi).div(180.0) + cos, sin = r_rad.cos(), r_rad.sin() + xywhr = xywhr[..., :2].tile((1, 4)) + # x1 + w * cos = x2 + xywhr[..., 2].add_(wh[..., 0].mul(cos)) + # y1 - w * sin = y2 + xywhr[..., 3].sub_(wh[..., 0].mul(sin)) + # x1 + w * cos + h * sin = x3 + xywhr[..., 4].add_(wh[..., 0].mul(cos).add(wh[..., 1].mul(sin))) + # y1 - w * sin + h * cos = y3 + xywhr[..., 5].sub_(wh[..., 0].mul(sin).sub(wh[..., 1].mul(cos))) + # x1 + h * sin = x4 + xywhr[..., 6].add_(wh[..., 1].mul(sin)) + # y1 + h * cos = y4 + xywhr[..., 7].add_(wh[..., 1].mul(cos)) + + return xywhr + + +def _xyxyxyxy_to_xywhr(xyxyxyxy: torch.Tensor, inplace: bool) -> torch.Tensor: + # NOTE: This function cannot modify the input tensor inplace as it requires a dimension change. + if not inplace: + xyxyxyxy = xyxyxyxy.clone() + + dtype = xyxyxyxy.dtype + acceptable_dtypes = [torch.float32, torch.float64] # Ensure consistency between CPU and GPU. + need_cast = dtype not in acceptable_dtypes + if need_cast: + # Up-case to avoid overflow for square operations + xyxyxyxy = xyxyxyxy.to(torch.float32) + + r_rad = torch.atan2(xyxyxyxy[..., 1].sub(xyxyxyxy[..., 3]), xyxyxyxy[..., 2].sub(xyxyxyxy[..., 0])) + # x1, y1, (x2 - x1), (y2 - y1), (x3 - x2), (y3 - y2) x4, y4 + xyxyxyxy[..., 4:6].sub_(xyxyxyxy[..., 2:4]) + xyxyxyxy[..., 2:4].sub_(xyxyxyxy[..., :2]) + # sqrt((x2 - x1) ** 2 + (y1 - y2) ** 2) = w + xyxyxyxy[..., 2] = xyxyxyxy[..., 2].pow(2).add(xyxyxyxy[..., 3].pow(2)).sqrt() + # sqrt((x2 - x3) ** 2 + (y2 - y3) ** 2) = h + xyxyxyxy[..., 3] = xyxyxyxy[..., 4].pow(2).add(xyxyxyxy[..., 5].pow(2)).sqrt() + xyxyxyxy[..., 4] = r_rad.div_(torch.pi).mul_(180.0) + + if need_cast: + xyxyxyxy = xyxyxyxy.to(dtype) + + return xyxyxyxy[..., :5] + + +def _convert_bounding_box_format( + bounding_boxes: torch.Tensor, old_format: BoundingBoxFormat, new_format: BoundingBoxFormat, inplace: bool = False +) -> torch.Tensor: + + if new_format == old_format: + return bounding_boxes + + if tv_tensors.is_rotated_bounding_format(old_format) ^ tv_tensors.is_rotated_bounding_format(new_format): + raise ValueError("Cannot convert between rotated and unrotated bounding boxes.") + + if old_format == BoundingBoxFormat.XYWH and new_format == BoundingBoxFormat.CXCYWH: + return _xywh_to_cxcywh(bounding_boxes, inplace) + if old_format == BoundingBoxFormat.CXCYWH and new_format == BoundingBoxFormat.XYWH: + return _cxcywh_to_xywh(bounding_boxes, inplace) + + if old_format == BoundingBoxFormat.XYWH: + bounding_boxes = _xywh_to_xyxy(bounding_boxes, inplace) + elif old_format == BoundingBoxFormat.CXCYWH: + bounding_boxes = _cxcywh_to_xyxy(bounding_boxes, inplace) + elif old_format == BoundingBoxFormat.CXCYWHR: + bounding_boxes = _cxcywhr_to_xywhr(bounding_boxes, inplace) + elif old_format == BoundingBoxFormat.XYXYXYXY: + bounding_boxes = _xyxyxyxy_to_xywhr(bounding_boxes, inplace) + + if new_format == BoundingBoxFormat.XYWH: + bounding_boxes = _xyxy_to_xywh(bounding_boxes, inplace) + elif new_format == BoundingBoxFormat.CXCYWH: + bounding_boxes = _xyxy_to_cxcywh(bounding_boxes, inplace) + elif new_format == BoundingBoxFormat.CXCYWHR: + bounding_boxes = _xywhr_to_cxcywhr(bounding_boxes, inplace) + elif new_format == BoundingBoxFormat.XYXYXYXY: + bounding_boxes = _xywhr_to_xyxyxyxy(bounding_boxes, inplace) + + return bounding_boxes + + +def convert_bounding_box_format( + inpt: torch.Tensor, + old_format: Optional[BoundingBoxFormat] = None, + new_format: Optional[BoundingBoxFormat] = None, + inplace: bool = False, +) -> torch.Tensor: + """See :func:`~torchvision.transforms.v2.ConvertBoundingBoxFormat` for details.""" + # This being a kernel / functional hybrid, we need an option to pass `old_format` explicitly for pure tensor + # inputs as well as extract it from `tv_tensors.BoundingBoxes` inputs. However, putting a default value on + # `old_format` means we also need to put one on `new_format` to have syntactically correct Python. Here we mimic the + # default error that would be thrown if `new_format` had no default value. + if new_format is None: + raise TypeError("convert_bounding_box_format() missing 1 required argument: 'new_format'") + + if not torch.jit.is_scripting(): + _log_api_usage_once(convert_bounding_box_format) + + if isinstance(old_format, str): + old_format = BoundingBoxFormat[old_format.upper()] + if isinstance(new_format, str): + new_format = BoundingBoxFormat[new_format.upper()] + + if torch.jit.is_scripting() or is_pure_tensor(inpt): + if old_format is None: + raise ValueError("For pure tensor inputs, `old_format` has to be passed.") + return _convert_bounding_box_format(inpt, old_format=old_format, new_format=new_format, inplace=inplace) + elif isinstance(inpt, tv_tensors.BoundingBoxes): + if old_format is not None: + raise ValueError("For bounding box tv_tensor inputs, `old_format` must not be passed.") + output = _convert_bounding_box_format( + inpt.as_subclass(torch.Tensor), old_format=inpt.format, new_format=new_format, inplace=inplace + ) + return tv_tensors.wrap(output, like=inpt, format=new_format) + else: + raise TypeError( + f"Input can either be a plain tensor or a bounding box tv_tensor, but got {type(inpt)} instead." + ) + + +def _clamp_bounding_boxes( + bounding_boxes: torch.Tensor, + format: BoundingBoxFormat, + canvas_size: tuple[int, int], + clamping_mode: CLAMPING_MODE_TYPE, +) -> torch.Tensor: + if clamping_mode is None: + return bounding_boxes.clone() + # TODO: Investigate if it makes sense from a performance perspective to have an implementation for every + # BoundingBoxFormat instead of converting back and forth + in_dtype = bounding_boxes.dtype + bounding_boxes = bounding_boxes.clone() if bounding_boxes.is_floating_point() else bounding_boxes.float() + xyxy_boxes = convert_bounding_box_format( + bounding_boxes, old_format=format, new_format=tv_tensors.BoundingBoxFormat.XYXY, inplace=True + ) + # hard and soft modes are equivalent for non-rotated boxes + xyxy_boxes[..., 0::2].clamp_(min=0, max=canvas_size[1]) + xyxy_boxes[..., 1::2].clamp_(min=0, max=canvas_size[0]) + out_boxes = convert_bounding_box_format( + xyxy_boxes, old_format=BoundingBoxFormat.XYXY, new_format=format, inplace=True + ) + return out_boxes.to(in_dtype) + + +def _order_bounding_boxes_points( + bounding_boxes: torch.Tensor, indices: Optional[torch.Tensor] = None +) -> tuple[torch.Tensor, torch.Tensor]: + """Re-order points in bounding boxes based on specific criteria or provided indices. + + This function reorders the points of bounding boxes either according to provided indices or + by a default ordering strategy. In the default strategy, (x1, y1) corresponds to the point + with the lowest x value. If multiple points have the same lowest x value, the point with the + lowest y value is chosen. + + Args: + bounding_boxes (torch.Tensor): A tensor containing bounding box coordinates in format [x1, y1, x2, y2, x3, y3, x4, y4]. + indices (torch.Tensor | None): Optional tensor containing indices for reordering. If None, default ordering is applied. + + Returns: + tuple[torch.Tensor, torch.Tensor]: A tuple containing: + - indices: The indices used for reordering + - reordered_boxes: The bounding boxes with reordered points + """ + if indices is None: + output_xyxyxyxy = bounding_boxes.reshape(-1, 8) + x, y = output_xyxyxyxy[..., 0::2], output_xyxyxyxy[..., 1::2] + y_max = torch.max(y.abs(), dim=1, keepdim=True)[0] + x_max = torch.max(x.abs(), dim=1, keepdim=True)[0] + _, x1 = (y / y_max + (x / x_max) * 100).min(dim=1) + indices = torch.ones_like(output_xyxyxyxy) + indices[..., 0] = x1.mul(2) + indices.cumsum_(1).remainder_(8) + return indices, bounding_boxes.gather(1, indices.to(torch.int64)) + + +def _get_slope_and_intercept(box: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """ + Calculate the slope and y-intercept of the lines defined by consecutive vertices in a bounding box. + This function computes the slope (a) and y-intercept (b) for each line segment in a bounding box, + where each line is defined by two consecutive vertices. + """ + x, y = box[..., ::2], box[..., 1::2] + a = y.diff(append=y[..., 0:1]) / x.diff(append=x[..., 0:1]) + b = y - a * x + return a, b + + +def _get_intersection_point(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + """ + Calculate the intersection point of two lines defined by their slopes and y-intercepts. + This function computes the intersection points between pairs of lines, where each line + is defined by the equation y = ax + b (slope and y-intercept form). + """ + batch_size = a.shape[0] + x = b.diff(prepend=b[..., 3:4]).neg() / a.diff(prepend=a[..., 3:4]) + y = a * x + b + return torch.cat((x.unsqueeze(-1), y.unsqueeze(-1)), dim=-1).view(batch_size, 8) + + +def _clamp_y_intercept( + bounding_boxes: torch.Tensor, + original_bounding_boxes: torch.Tensor, + canvas_size: tuple[int, int], + clamping_mode: CLAMPING_MODE_TYPE, +) -> torch.Tensor: + """ + Apply clamping to bounding box y-intercepts. This function handles two clamping strategies: + - Hard clamping: Ensures all box vertices stay within canvas boundaries, finding the largest + angle-preserving box enclosed within the original box and the image canvas. + - Soft clamping: Allows some vertices to extend beyond the canvas, finding the smallest + angle-preserving box that encloses the intersection of the original box and the image canvas. + + The function first calculates the slopes and y-intercepts of the lines forming the bounding box, + then applies various constraints to ensure the clamping conditions are respected. + """ + + # Calculate slopes and y-intercepts for bounding boxes + a, b = _get_slope_and_intercept(bounding_boxes) + a1, a2, a3, a4 = a.unbind(-1) + b1, b2, b3, b4 = b.unbind(-1) + + # Get y-intercepts from original bounding boxes + _, bm = _get_slope_and_intercept(original_bounding_boxes) + b1m, b2m, b3m, b4m = bm.unbind(-1) + + # Soft clamping: Clamp y-intercepts within canvas boundaries + b1 = b2.clamp(b1, b3).clamp(0, canvas_size[0]) + b4 = b3.clamp(b2, b4).clamp(0, canvas_size[0]) + + if clamping_mode is not None and clamping_mode == "hard": + # Hard clamping: Average b1 and b4, and adjust b2 and b3 for maximum area + b1 = b4 = (b1 + b4) / 2 + + # Calculate candidate values for b2 based on geometric constraints + b2_candidates = torch.stack( + [ + b1 * a2 / a1, # Constraint at y=0 + b3 * a2 / a3, # Constraint at y=0 + (a1 - a2) * canvas_size[1] + b1, # Constraint at x=canvas_width + (a3 - a2) * canvas_size[1] + b3, # Constraint at x=canvas_width + ], + dim=1, + ) + # Take maximum value that doesn't exceed original b2 + b2 = torch.max(b2_candidates, dim=1)[0].clamp(max=b2) + + # Calculate candidate values for b3 based on geometric constraints + b3_candidates = torch.stack( + [ + canvas_size[0] * (1 - a3 / a4) + b4 * a3 / a4, # Constraint at y=canvas_height + canvas_size[0] * (1 - a3 / a2) + b2 * a3 / a2, # Constraint at y=canvas_height + (a2 - a3) * canvas_size[1] + b2, # Constraint at x=canvas_width + (a4 - a3) * canvas_size[1] + b4, # Constraint at x=canvas_width + ], + dim=1, + ) + # Take minimum value that doesn't go below original b3 + b3 = torch.min(b3_candidates, dim=1)[0].clamp(min=b3) + + # Final clamping to ensure y-intercepts are within original box bounds + b1.clamp_(b1m, b3m) + b3.clamp_(b1m, b3m) + b2.clamp_(b2m, b4m) + b4.clamp_(b2m, b4m) + + return torch.stack([b1, b2, b3, b4], dim=-1) + + +def _clamp_along_y_axis( + bounding_boxes: torch.Tensor, + original_bounding_boxes: torch.Tensor, + canvas_size: tuple[int, int], + clamping_mode: CLAMPING_MODE_TYPE, +) -> torch.Tensor: + """ + Adjusts bounding boxes along the y-axis based on specific conditions. + + This function modifies the bounding boxes by evaluating different cases + and applying the appropriate transformation to ensure the bounding boxes + are clamped correctly along the y-axis. + + Args: + bounding_boxes (torch.Tensor): A tensor containing bounding box coordinates. + original_bounding_boxes (torch.Tensor): The original bounding boxes before any clamping is applied. + canvas_size (tuple[int, int]): The size of the canvas as (height, width). + clamping_mode (str, optional): The clamping strategy to use. + + Returns: + torch.Tensor: The adjusted bounding boxes. + """ + original_shape = bounding_boxes.shape + bounding_boxes = bounding_boxes.reshape(-1, 8) + original_bounding_boxes = original_bounding_boxes.reshape(-1, 8) + + # Calculate slopes (a) and y-intercepts (b) for all lines in the bounding boxes + a, b = _get_slope_and_intercept(bounding_boxes) + x1, y1, x2, y2, x3, y3, x4, y4 = bounding_boxes.unbind(-1) + b = _clamp_y_intercept(bounding_boxes, original_bounding_boxes, canvas_size, clamping_mode) + + case_a = _get_intersection_point(a, b) + case_b = bounding_boxes.clone() + case_b[..., 0].clamp_(0) # Clamp x1 to 0 + case_b[..., 6].clamp_(0) # Clamp x4 to 0 + case_c = torch.zeros_like(case_b) + + cond_a = (x1 < 0) & ~case_a.isnan().any(-1) # First point is outside left boundary + cond_b = y1.isclose(y2) | y3.isclose(y4) # First line is nearly vertical + cond_c = (x1 <= 0) & (x2 <= 0) & (x3 <= 0) & (x4 <= 0) # All points outside left boundary + cond_c = cond_c | y1.isclose(y4) | y2.isclose(y3) | (cond_b & x1.isclose(x2)) # First line is nearly horizontal + + for (cond, case) in zip( + [cond_a, cond_b, cond_c], + [case_a, case_b, case_c], + ): + bounding_boxes = torch.where(cond.unsqueeze(1).repeat(1, 8), case.reshape(-1, 8), bounding_boxes) + + return bounding_boxes.reshape(original_shape) + + +def _clamp_rotated_bounding_boxes( + bounding_boxes: torch.Tensor, + format: BoundingBoxFormat, + canvas_size: tuple[int, int], + clamping_mode: CLAMPING_MODE_TYPE, +) -> torch.Tensor: + """ + Clamp rotated bounding boxes to ensure they stay within the canvas boundaries. + + This function handles rotated bounding boxes by: + 1. Converting them to XYXYXYXY format (8 coordinates representing 4 corners). + 2. Re-ordering the points in the bounding boxes to ensure (x1, y1) corresponds to the point with the lowest x value + 2. Translates the points (x1, y1), (x2, y2) and (x3, y3) + to ensure the bounding box does not go out beyond the left boundary of the canvas. + 3. Rotate the bounding box four times and apply the same transformation to each vertex to ensure + the box does not go beyond the top, right, and bottom boundaries. + 3. Converting back to the original format and re-order the points as in the original input. + + Args: + bounding_boxes (torch.Tensor): Tensor containing rotated bounding box coordinates + format (BoundingBoxFormat): The format of the input bounding boxes + canvas_size (tuple[int, int]): The size of the canvas as (height, width) + + Returns: + torch.Tensor: Clamped bounding boxes in the original format and shape + """ + if clamping_mode is None: + return bounding_boxes.clone() + original_shape = bounding_boxes.shape + bounding_boxes = bounding_boxes.clone() + out_boxes = ( + convert_bounding_box_format( + bounding_boxes, old_format=format, new_format=tv_tensors.BoundingBoxFormat.XYXYXYXY, inplace=True + ) + ).reshape(-1, 8) + + original_boxes = out_boxes.clone() + for _ in range(4): # Iterate over the 4 vertices. + indices, out_boxes = _order_bounding_boxes_points(out_boxes) + _, original_boxes = _order_bounding_boxes_points(original_boxes, indices) + out_boxes = _clamp_along_y_axis(out_boxes, original_boxes, canvas_size, clamping_mode) + _, out_boxes = _order_bounding_boxes_points(out_boxes, indices) + _, original_boxes = _order_bounding_boxes_points(original_boxes, indices) + # rotate 90 degrees counter clock wise + out_boxes[:, ::2], out_boxes[:, 1::2] = ( + out_boxes[:, 1::2].clone(), + canvas_size[1] - out_boxes[:, ::2].clone(), + ) + original_boxes[:, ::2], original_boxes[:, 1::2] = ( + original_boxes[:, 1::2].clone(), + canvas_size[1] - original_boxes[:, ::2].clone(), + ) + canvas_size = (canvas_size[1], canvas_size[0]) + + out_boxes = convert_bounding_box_format( + out_boxes, old_format=tv_tensors.BoundingBoxFormat.XYXYXYXY, new_format=format, inplace=True + ).reshape(original_shape) + + return out_boxes + + +def clamp_bounding_boxes( + inpt: torch.Tensor, + format: Optional[BoundingBoxFormat] = None, + canvas_size: Optional[tuple[int, int]] = None, + clamping_mode: Union[CLAMPING_MODE_TYPE, str] = "auto", +) -> torch.Tensor: + """See :func:`~torchvision.transforms.v2.ClampBoundingBoxes` for details.""" + if not torch.jit.is_scripting(): + _log_api_usage_once(clamp_bounding_boxes) + + if clamping_mode is not None and clamping_mode not in ("soft", "hard", "auto"): + raise ValueError(f"clamping_mode must be soft, hard, auto or None, got {clamping_mode}") + + if torch.jit.is_scripting() or is_pure_tensor(inpt): + + if format is None or canvas_size is None or (clamping_mode is not None and clamping_mode == "auto"): + raise ValueError("For pure tensor inputs, `format`, `canvas_size` and `clamping_mode` have to be passed.") + if tv_tensors.is_rotated_bounding_format(format): + return _clamp_rotated_bounding_boxes( + inpt, format=format, canvas_size=canvas_size, clamping_mode=clamping_mode + ) + else: + return _clamp_bounding_boxes(inpt, format=format, canvas_size=canvas_size, clamping_mode=clamping_mode) + elif isinstance(inpt, tv_tensors.BoundingBoxes): + if format is not None or canvas_size is not None: + raise ValueError("For bounding box tv_tensor inputs, `format` and `canvas_size` must not be passed.") + if clamping_mode is not None and clamping_mode == "auto": + clamping_mode = inpt.clamping_mode + if tv_tensors.is_rotated_bounding_format(inpt.format): + output = _clamp_rotated_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + clamping_mode=clamping_mode, + ) + else: + output = _clamp_bounding_boxes( + inpt.as_subclass(torch.Tensor), + format=inpt.format, + canvas_size=inpt.canvas_size, + clamping_mode=clamping_mode, + ) + return tv_tensors.wrap(output, like=inpt) + else: + raise TypeError( + f"Input can either be a plain tensor or a bounding box tv_tensor, but got {type(inpt)} instead." + ) + + +def _clamp_keypoints(keypoints: torch.Tensor, canvas_size: tuple[int, int]) -> torch.Tensor: + dtype = keypoints.dtype + keypoints = keypoints.clone() if keypoints.is_floating_point() else keypoints.float() + # Note that max is canvas_size[i] - 1 and not can canvas_size[i] like for + # bounding boxes. + keypoints[..., 0].clamp_(min=0, max=canvas_size[1] - 1) + keypoints[..., 1].clamp_(min=0, max=canvas_size[0] - 1) + return keypoints.to(dtype=dtype) + + +def clamp_keypoints( + inpt: torch.Tensor, + canvas_size: Optional[tuple[int, int]] = None, +) -> torch.Tensor: + """See :func:`~torchvision.transforms.v2.ClampKeyPoints` for details.""" + if not torch.jit.is_scripting(): + _log_api_usage_once(clamp_keypoints) + + if torch.jit.is_scripting() or is_pure_tensor(inpt): + + if canvas_size is None: + raise ValueError("For pure tensor inputs, `canvas_size` has to be passed.") + return _clamp_keypoints(inpt, canvas_size=canvas_size) + elif isinstance(inpt, tv_tensors.KeyPoints): + if canvas_size is not None: + raise ValueError("For keypoints tv_tensor inputs, `canvas_size` must not be passed.") + output = _clamp_keypoints(inpt.as_subclass(torch.Tensor), canvas_size=inpt.canvas_size) + return tv_tensors.wrap(output, like=inpt) + else: + raise TypeError(f"Input can either be a plain tensor or a keypoints tv_tensor, but got {type(inpt)} instead.") diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_misc.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..55d085a2e241b7a0e54579b5b1ca657bbc1431f6 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_misc.py @@ -0,0 +1,517 @@ +import math +from typing import Optional + +import PIL.Image +import torch +from torch.nn.functional import conv2d, pad as torch_pad + +from torchvision import tv_tensors +from torchvision.transforms._functional_tensor import _max_value +from torchvision.transforms.functional import pil_to_tensor, to_pil_image + +from torchvision.utils import _log_api_usage_once + +from ._meta import _convert_bounding_box_format + +from ._utils import _get_kernel, _register_kernel_internal, is_pure_tensor + + +def normalize( + inpt: torch.Tensor, + mean: list[float], + std: list[float], + inplace: bool = False, +) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.Normalize` for details.""" + if torch.jit.is_scripting(): + return normalize_image(inpt, mean=mean, std=std, inplace=inplace) + + _log_api_usage_once(normalize) + + kernel = _get_kernel(normalize, type(inpt)) + return kernel(inpt, mean=mean, std=std, inplace=inplace) + + +@_register_kernel_internal(normalize, torch.Tensor) +@_register_kernel_internal(normalize, tv_tensors.Image) +def normalize_image(image: torch.Tensor, mean: list[float], std: list[float], inplace: bool = False) -> torch.Tensor: + if not image.is_floating_point(): + raise TypeError(f"Input tensor should be a float tensor. Got {image.dtype}.") + + if image.ndim < 3: + raise ValueError(f"Expected tensor to be a tensor image of size (..., C, H, W). Got {image.shape}.") + + if isinstance(std, (tuple, list)): + divzero = not all(std) + elif isinstance(std, (int, float)): + divzero = std == 0 + else: + divzero = False + if divzero: + raise ValueError("std evaluated to zero, leading to division by zero.") + + dtype = image.dtype + device = image.device + mean = torch.as_tensor(mean, dtype=dtype, device=device) + std = torch.as_tensor(std, dtype=dtype, device=device) + if mean.ndim == 1: + mean = mean.view(-1, 1, 1) + if std.ndim == 1: + std = std.view(-1, 1, 1) + + if inplace: + image = image.sub_(mean) + else: + image = image.sub(mean) + + return image.div_(std) + + +@_register_kernel_internal(normalize, tv_tensors.Video) +def normalize_video(video: torch.Tensor, mean: list[float], std: list[float], inplace: bool = False) -> torch.Tensor: + return normalize_image(video, mean, std, inplace=inplace) + + +def gaussian_blur(inpt: torch.Tensor, kernel_size: list[int], sigma: Optional[list[float]] = None) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.GaussianBlur` for details.""" + if torch.jit.is_scripting(): + return gaussian_blur_image(inpt, kernel_size=kernel_size, sigma=sigma) + + _log_api_usage_once(gaussian_blur) + + kernel = _get_kernel(gaussian_blur, type(inpt)) + return kernel(inpt, kernel_size=kernel_size, sigma=sigma) + + +def _get_gaussian_kernel1d(kernel_size: int, sigma: float, dtype: torch.dtype, device: torch.device) -> torch.Tensor: + lim = (kernel_size - 1) / (2.0 * math.sqrt(2.0)) + x = torch.linspace(-lim, lim, steps=kernel_size, dtype=dtype, device=device) + kernel1d = torch.softmax(x.div(sigma).pow(2).neg(), dim=0) + return kernel1d + + +def _get_gaussian_kernel2d( + kernel_size: list[int], sigma: list[float], dtype: torch.dtype, device: torch.device +) -> torch.Tensor: + kernel1d_x = _get_gaussian_kernel1d(kernel_size[0], sigma[0], dtype, device) + kernel1d_y = _get_gaussian_kernel1d(kernel_size[1], sigma[1], dtype, device) + kernel2d = kernel1d_y.unsqueeze(-1) * kernel1d_x + return kernel2d + + +@_register_kernel_internal(gaussian_blur, torch.Tensor) +@_register_kernel_internal(gaussian_blur, tv_tensors.Image) +def gaussian_blur_image( + image: torch.Tensor, kernel_size: list[int], sigma: Optional[list[float]] = None +) -> torch.Tensor: + # TODO: consider deprecating integers from sigma on the future + if isinstance(kernel_size, int): + kernel_size = [kernel_size, kernel_size] + elif len(kernel_size) != 2: + raise ValueError(f"If kernel_size is a sequence its length should be 2. Got {len(kernel_size)}") + for ksize in kernel_size: + if ksize % 2 == 0 or ksize < 0: + raise ValueError(f"kernel_size should have odd and positive integers. Got {kernel_size}") + + if sigma is None: + sigma = [ksize * 0.15 + 0.35 for ksize in kernel_size] + else: + if isinstance(sigma, (list, tuple)): + length = len(sigma) + if length == 1: + s = sigma[0] + sigma = [s, s] + elif length != 2: + raise ValueError(f"If sigma is a sequence, its length should be 2. Got {length}") + elif isinstance(sigma, (int, float)): + s = float(sigma) + sigma = [s, s] + else: + raise TypeError(f"sigma should be either float or sequence of floats. Got {type(sigma)}") + for s in sigma: + if s <= 0.0: + raise ValueError(f"sigma should have positive values. Got {sigma}") + + if image.numel() == 0: + return image + + dtype = image.dtype + shape = image.shape + ndim = image.ndim + if ndim == 3: + image = image.unsqueeze(dim=0) + elif ndim > 4: + image = image.reshape((-1,) + shape[-3:]) + + fp = torch.is_floating_point(image) + kernel = _get_gaussian_kernel2d(kernel_size, sigma, dtype=dtype if fp else torch.float32, device=image.device) + kernel = kernel.expand(shape[-3], 1, kernel.shape[0], kernel.shape[1]) + + output = image if fp else image.to(dtype=torch.float32) + + # padding = (left, right, top, bottom) + padding = [kernel_size[0] // 2, kernel_size[0] // 2, kernel_size[1] // 2, kernel_size[1] // 2] + output = torch_pad(output, padding, mode="reflect") + output = conv2d(output, kernel, groups=shape[-3]) + + if ndim == 3: + output = output.squeeze(dim=0) + elif ndim > 4: + output = output.reshape(shape) + + if not fp: + output = output.round_().to(dtype=dtype) + + return output + + +@_register_kernel_internal(gaussian_blur, PIL.Image.Image) +def _gaussian_blur_image_pil( + image: PIL.Image.Image, kernel_size: list[int], sigma: Optional[list[float]] = None +) -> PIL.Image.Image: + t_img = pil_to_tensor(image) + output = gaussian_blur_image(t_img, kernel_size=kernel_size, sigma=sigma) + return to_pil_image(output, mode=image.mode) + + +@_register_kernel_internal(gaussian_blur, tv_tensors.Video) +def gaussian_blur_video( + video: torch.Tensor, kernel_size: list[int], sigma: Optional[list[float]] = None +) -> torch.Tensor: + return gaussian_blur_image(video, kernel_size, sigma) + + +def gaussian_noise(inpt: torch.Tensor, mean: float = 0.0, sigma: float = 0.1, clip: bool = True) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.GaussianNoise`""" + if torch.jit.is_scripting(): + return gaussian_noise_image(inpt, mean=mean, sigma=sigma) + + _log_api_usage_once(gaussian_noise) + + kernel = _get_kernel(gaussian_noise, type(inpt)) + return kernel(inpt, mean=mean, sigma=sigma, clip=clip) + + +@_register_kernel_internal(gaussian_noise, torch.Tensor) +@_register_kernel_internal(gaussian_noise, tv_tensors.Image) +def gaussian_noise_image(image: torch.Tensor, mean: float = 0.0, sigma: float = 0.1, clip: bool = True) -> torch.Tensor: + if sigma < 0: + raise ValueError(f"sigma shouldn't be negative. Got {sigma}") + + if image.is_floating_point(): + noise = mean + torch.randn_like(image) * sigma + out = image + noise + if clip: + out = torch.clamp(out, 0, 1) + return out + + elif image.dtype == torch.uint8: + # Convert to intermediate dtype int16 to add to input more efficiently + # See https://github.com/pytorch/vision/pull/9169 for alternative implementations and benchmark + noise = ((mean * 255) + torch.randn_like(image, dtype=torch.float32) * (sigma * 255)).to(torch.int16) + out = image + noise + + if clip: + out = torch.clamp(out, 0, 255) + return out.to(torch.uint8) + + else: + raise ValueError(f"Input tensor is expected to be in uint8 or float dtype, got dtype={image.dtype}") + + +@_register_kernel_internal(gaussian_noise, tv_tensors.Video) +def gaussian_noise_video(video: torch.Tensor, mean: float = 0.0, sigma: float = 0.1, clip: bool = True) -> torch.Tensor: + return gaussian_noise_image(video, mean=mean, sigma=sigma, clip=clip) + + +@_register_kernel_internal(gaussian_noise, PIL.Image.Image) +def _gaussian_noise_pil( + video: torch.Tensor, mean: float = 0.0, sigma: float = 0.1, clip: bool = True +) -> PIL.Image.Image: + raise ValueError("Gaussian Noise is not implemented for PIL images.") + + +def to_dtype(inpt: torch.Tensor, dtype: torch.dtype = torch.float, scale: bool = False) -> torch.Tensor: + """See :func:`~torchvision.transforms.v2.ToDtype` for details.""" + if torch.jit.is_scripting(): + return to_dtype_image(inpt, dtype=dtype, scale=scale) + + _log_api_usage_once(to_dtype) + + kernel = _get_kernel(to_dtype, type(inpt)) + return kernel(inpt, dtype=dtype, scale=scale) + + +def _num_value_bits(dtype: torch.dtype) -> int: + if dtype == torch.uint8: + return 8 + elif dtype == torch.int8: + return 7 + elif dtype == torch.int16: + return 15 + elif dtype == torch.uint16: + return 16 + elif dtype == torch.int32: + return 31 + elif dtype == torch.int64: + return 63 + else: + raise TypeError(f"Number of value bits is only defined for integer dtypes, but got {dtype}.") + + +@_register_kernel_internal(to_dtype, torch.Tensor) +@_register_kernel_internal(to_dtype, tv_tensors.Image) +def to_dtype_image(image: torch.Tensor, dtype: torch.dtype = torch.float, scale: bool = False) -> torch.Tensor: + + if image.dtype == dtype: + return image + elif not scale: + return image.to(dtype) + + float_input = image.is_floating_point() + if torch.jit.is_scripting(): + # TODO: remove this branch as soon as `dtype.is_floating_point` is supported by JIT + float_output = torch.tensor(0, dtype=dtype).is_floating_point() + else: + float_output = dtype.is_floating_point + + if float_input: + # float to float + if float_output: + return image.to(dtype) + + # float to int + if (image.dtype == torch.float32 and dtype in (torch.int32, torch.int64)) or ( + image.dtype == torch.float64 and dtype == torch.int64 + ): + raise RuntimeError(f"The conversion from {image.dtype} to {dtype} cannot be performed safely.") + + # For data in the range `[0.0, 1.0]`, just multiplying by the maximum value of the integer range and converting + # to the integer dtype is not sufficient. For example, `torch.rand(...).mul(255).to(torch.uint8)` will only + # be `255` if the input is exactly `1.0`. See https://github.com/pytorch/vision/pull/2078#issuecomment-612045321 + # for a detailed analysis. + # To mitigate this, we could round before we convert to the integer dtype, but this is an extra operation. + # Instead, we can also multiply by the maximum value plus something close to `1`. See + # https://github.com/pytorch/vision/pull/2078#issuecomment-613524965 for details. + eps = 1e-3 + max_value = float(_max_value(dtype)) + # We need to scale first since the conversion would otherwise turn the input range `[0.0, 1.0]` into the + # discrete set `{0, 1}`. + return image.mul(max_value + 1.0 - eps).to(dtype) + else: + # int to float + if float_output: + return image.to(dtype).mul_(1.0 / _max_value(image.dtype)) + + # int to int + num_value_bits_input = _num_value_bits(image.dtype) + num_value_bits_output = _num_value_bits(dtype) + + # TODO: Remove if/else inner blocks once uint16 dtype supports bitwise shift operations. + shift_by = abs(num_value_bits_input - num_value_bits_output) + if num_value_bits_input > num_value_bits_output: + if image.dtype == torch.uint16: + return (image / 2 ** (shift_by)).to(dtype) + else: + return image.bitwise_right_shift(shift_by).to(dtype) + else: + if dtype == torch.uint16: + return image.to(dtype) * 2 ** (shift_by) + else: + return image.to(dtype).bitwise_left_shift_(shift_by) + + +# We encourage users to use to_dtype() instead but we keep this for BC +def convert_image_dtype(image: torch.Tensor, dtype: torch.dtype = torch.float32) -> torch.Tensor: + """[DEPRECATED] Use to_dtype() instead.""" + return to_dtype_image(image, dtype=dtype, scale=True) + + +@_register_kernel_internal(to_dtype, tv_tensors.Video) +def to_dtype_video(video: torch.Tensor, dtype: torch.dtype = torch.float, scale: bool = False) -> torch.Tensor: + return to_dtype_image(video, dtype, scale=scale) + + +@_register_kernel_internal(to_dtype, tv_tensors.KeyPoints, tv_tensor_wrapper=False) +@_register_kernel_internal(to_dtype, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False) +@_register_kernel_internal(to_dtype, tv_tensors.Mask, tv_tensor_wrapper=False) +def _to_dtype_tensor_dispatch(inpt: torch.Tensor, dtype: torch.dtype, scale: bool = False) -> torch.Tensor: + # We don't need to unwrap and rewrap here, since TVTensor.to() preserves the type + return inpt.to(dtype) + + +def sanitize_bounding_boxes( + bounding_boxes: torch.Tensor, + format: Optional[tv_tensors.BoundingBoxFormat] = None, + canvas_size: Optional[tuple[int, int]] = None, + min_size: float = 1.0, + min_area: float = 1.0, +) -> tuple[torch.Tensor, torch.Tensor]: + """Remove degenerate/invalid bounding boxes and return the corresponding indexing mask. + + This removes bounding boxes that: + + - are below a given ``min_size`` or ``min_area``: by default this also removes degenerate boxes that have e.g. X2 <= X1. + - have any coordinate outside of their corresponding image. You may want to + call :func:`~torchvision.transforms.v2.functional.clamp_bounding_boxes` first to avoid undesired removals. + + It is recommended to call it at the end of a pipeline, before passing the + input to the models. It is critical to call this transform if + :class:`~torchvision.transforms.v2.RandomIoUCrop` was called. + If you want to be extra careful, you may call it after all transforms that + may modify bounding boxes but once at the end should be enough in most + cases. + + Args: + bounding_boxes (Tensor or :class:`~torchvision.tv_tensors.BoundingBoxes`): The bounding boxes to be sanitized. + format (str or :class:`~torchvision.tv_tensors.BoundingBoxFormat`, optional): The format of the bounding boxes. + Must be left to none if ``bounding_boxes`` is a :class:`~torchvision.tv_tensors.BoundingBoxes` object. + canvas_size (tuple of int, optional): The canvas_size of the bounding boxes + (size of the corresponding image/video). + Must be left to none if ``bounding_boxes`` is a :class:`~torchvision.tv_tensors.BoundingBoxes` object. + min_size (float, optional) The size below which bounding boxes are removed. Default is 1. + min_area (float, optional) The area below which bounding boxes are removed. Default is 1. + + Returns: + out (tuple of Tensors): The subset of valid bounding boxes, and the corresponding indexing mask. + The mask can then be used to subset other tensors (e.g. labels) that are associated with the bounding boxes. + """ + if torch.jit.is_scripting() or is_pure_tensor(bounding_boxes): + if format is None or canvas_size is None: + raise ValueError( + "format and canvas_size cannot be None if bounding_boxes is a pure tensor. " + f"Got format={format} and canvas_size={canvas_size}." + "Set those to appropriate values or pass bounding_boxes as a tv_tensors.BoundingBoxes object." + ) + if isinstance(format, str): + format = tv_tensors.BoundingBoxFormat[format.upper()] + valid = _get_sanitize_bounding_boxes_mask( + bounding_boxes, format=format, canvas_size=canvas_size, min_size=min_size, min_area=min_area + ) + bounding_boxes = bounding_boxes[valid] + else: + if not isinstance(bounding_boxes, tv_tensors.BoundingBoxes): + raise ValueError("bounding_boxes must be a tv_tensors.BoundingBoxes instance or a pure tensor.") + if format is not None or canvas_size is not None: + raise ValueError( + "format and canvas_size must be None when bounding_boxes is a tv_tensors.BoundingBoxes instance. " + f"Got format={format} and canvas_size={canvas_size}. " + "Leave those to None or pass bounding_boxes as a pure tensor." + ) + valid = _get_sanitize_bounding_boxes_mask( + bounding_boxes, + format=bounding_boxes.format, + canvas_size=bounding_boxes.canvas_size, + min_size=min_size, + min_area=min_area, + ) + bounding_boxes = tv_tensors.wrap(bounding_boxes[valid], like=bounding_boxes) + + return bounding_boxes, valid + + +def _get_sanitize_bounding_boxes_mask( + bounding_boxes: torch.Tensor, + format: tv_tensors.BoundingBoxFormat, + canvas_size: tuple[int, int], + min_size: float = 1.0, + min_area: float = 1.0, +) -> torch.Tensor: + + is_rotated = tv_tensors.is_rotated_bounding_format(format) + intermediate_format = tv_tensors.BoundingBoxFormat.XYXYXYXY if is_rotated else tv_tensors.BoundingBoxFormat.XYXY + bounding_boxes = _convert_bounding_box_format(bounding_boxes, new_format=intermediate_format, old_format=format) + + image_h, image_w = canvas_size + if is_rotated: + dx12 = bounding_boxes[..., 0] - bounding_boxes[..., 2] + dy12 = bounding_boxes[..., 1] - bounding_boxes[..., 3] + dx23 = bounding_boxes[..., 3] - bounding_boxes[..., 5] + dy23 = bounding_boxes[..., 4] - bounding_boxes[..., 6] + ws = torch.sqrt(dx12.pow(2) + dy12.pow(2)) + hs = torch.sqrt(dx23.pow(2) + dy23.pow(2)) + else: + ws, hs = bounding_boxes[:, 2] - bounding_boxes[:, 0], bounding_boxes[:, 3] - bounding_boxes[:, 1] + valid = (ws >= min_size) & (hs >= min_size) & (bounding_boxes >= 0).all(dim=-1) & (ws * hs >= min_area) + # TODO: Do we really need to check for out of bounds here? All + # transforms should be clamping anyway, so this should never happen? + image_h, image_w = canvas_size + valid &= (bounding_boxes[:, 0] <= image_w) & (bounding_boxes[:, 2] <= image_w) + valid &= (bounding_boxes[:, 1] <= image_h) & (bounding_boxes[:, 3] <= image_h) + if is_rotated: + valid &= (bounding_boxes[..., 4] <= image_w) & (bounding_boxes[..., 5] <= image_h) + valid &= (bounding_boxes[..., 6] <= image_w) & (bounding_boxes[..., 7] <= image_h) + return valid + + +def sanitize_keypoints( + key_points: torch.Tensor, + canvas_size: Optional[tuple[int, int]] = None, +) -> tuple[torch.Tensor, torch.Tensor]: + """Remove keypoints outside of the image area and their corresponding labels (if any). + + This transform removes keypoints or groups of keypoints and their associated labels that + have coordinates outside of their corresponding image. + If you would instead like to clamp such keypoints to the image edges, use + :class:`~torchvision.transforms.v2.ClampKeyPoints`. + + It is recommended to call it at the end of a pipeline, before passing the + input to the models. + + Keypoints can be passed as a set of individual keypoints or as a set of objects + (e.g., polygons or polygonal chains) consisting of a fixed number of keypoints of shape ``[..., 2]``. + When groups of keypoints are passed (i.e., an at least 3-dimensional tensor), + this transform will only remove entire groups, not individual keypoints within a group. + + Args: + key_points (Tensor or :class:`~torchvision.tv_tensors.KeyPoints`): The keypoints to be sanitized. + canvas_size (tuple of int, optional): The canvas_size of the keypoints + (size of the corresponding image/video). + Must be left to none if ``key_points`` is a :class:`~torchvision.tv_tensors.KeyPoints` object. + + Returns: + out (tuple of Tensors): The subset of valid keypoints, and the corresponding indexing mask. + The mask can then be used to subset other tensors (e.g. labels) that are associated with the keypoints. + """ + if torch.jit.is_scripting() or is_pure_tensor(key_points): + if canvas_size is None: + raise ValueError( + "canvas_size cannot be None if key_points is a pure tensor. " + "Set it to an appropriate value or pass key_points as a tv_tensors.KeyPoints object." + ) + valid = _get_sanitize_keypoints_mask( + key_points, + canvas_size=canvas_size, + ) + key_points = key_points[valid] + else: + if not isinstance(key_points, tv_tensors.KeyPoints): + raise ValueError("key_points must be a tv_tensors.KeyPoints instance or a pure tensor.") + if canvas_size is not None: + raise ValueError( + "canvas_size must be None when key_points is a tv_tensors.KeyPoints instance. " + f"Got canvas_size={canvas_size}. " + "Leave it to None or pass key_points as a pure tensor." + ) + valid = _get_sanitize_keypoints_mask( + key_points, + canvas_size=key_points.canvas_size, + ) + key_points = tv_tensors.wrap(key_points[valid], like=key_points) + + return key_points, valid + + +def _get_sanitize_keypoints_mask( + key_points: torch.Tensor, + canvas_size: tuple[int, int], +) -> torch.Tensor: + + h, w = canvas_size + + x, y = key_points[..., 0], key_points[..., 1] + valid = (x >= 0) & (x < w) & (y >= 0) & (y < h) + + valid = valid.flatten(start_dim=1).all(dim=1) if valid.ndim > 1 else valid + + return valid diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_temporal.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_temporal.py new file mode 100644 index 0000000000000000000000000000000000000000..f932b06a295fd10316fba3e796ec4649053e92db --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_temporal.py @@ -0,0 +1,27 @@ +import torch + +from torchvision import tv_tensors + +from torchvision.utils import _log_api_usage_once + +from ._utils import _get_kernel, _register_kernel_internal + + +def uniform_temporal_subsample(inpt: torch.Tensor, num_samples: int) -> torch.Tensor: + """See :class:`~torchvision.transforms.v2.UniformTemporalSubsample` for details.""" + if torch.jit.is_scripting(): + return uniform_temporal_subsample_video(inpt, num_samples=num_samples) + + _log_api_usage_once(uniform_temporal_subsample) + + kernel = _get_kernel(uniform_temporal_subsample, type(inpt)) + return kernel(inpt, num_samples=num_samples) + + +@_register_kernel_internal(uniform_temporal_subsample, torch.Tensor) +@_register_kernel_internal(uniform_temporal_subsample, tv_tensors.Video) +def uniform_temporal_subsample_video(video: torch.Tensor, num_samples: int) -> torch.Tensor: + # Reference: https://github.com/facebookresearch/pytorchvideo/blob/a0a131e/pytorchvideo/transforms/functional.py#L19 + t_max = video.shape[-4] - 1 + indices = torch.linspace(0, t_max, num_samples, device=video.device).long() + return torch.index_select(video, -4, indices) diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_type_conversion.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_type_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..c5a731fe143c365400d5905db8370c538097583a --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_type_conversion.py @@ -0,0 +1,27 @@ +from typing import Union + +import numpy as np +import PIL.Image +import torch +from torchvision import tv_tensors +from torchvision.transforms import functional as _F + + +@torch.jit.unused +def to_image(inpt: Union[torch.Tensor, PIL.Image.Image, np.ndarray]) -> tv_tensors.Image: + """See :class:`~torchvision.transforms.v2.ToImage` for details.""" + if isinstance(inpt, np.ndarray): + output = torch.from_numpy(np.atleast_3d(inpt)).permute((2, 0, 1)).contiguous() + elif isinstance(inpt, PIL.Image.Image): + output = pil_to_tensor(inpt) + elif isinstance(inpt, torch.Tensor): + output = inpt + else: + raise TypeError( + f"Input can either be a pure Tensor, a numpy array, or a PIL image, but got {type(inpt)} instead." + ) + return tv_tensors.Image(output) + + +to_pil_image = _F.to_pil_image +pil_to_tensor = _F.pil_to_tensor diff --git a/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_utils.py b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b857285c891c8502ff95ed7c3ac998953aa04170 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/transforms/v2/functional/_utils.py @@ -0,0 +1,142 @@ +import functools +from collections.abc import Sequence +from typing import Any, Callable, Optional, Union + +import torch +from torchvision import tv_tensors + +_FillType = Union[int, float, Sequence[int], Sequence[float], None] +_FillTypeJIT = Optional[list[float]] + + +def is_pure_tensor(inpt: Any) -> bool: + return isinstance(inpt, torch.Tensor) and not isinstance(inpt, tv_tensors.TVTensor) + + +# {functional: {input_type: type_specific_kernel}} +_KERNEL_REGISTRY: dict[Callable, dict[type, Callable]] = {} + + +def _kernel_tv_tensor_wrapper(kernel): + @functools.wraps(kernel) + def wrapper(inpt, *args, **kwargs): + # If you're wondering whether we could / should get rid of this wrapper, + # the answer is no: we want to pass pure Tensors to avoid the overhead + # of the __torch_function__ machinery. Note that this is always valid, + # regardless of whether we override __torch_function__ in our base class + # or not. + # Also, even if we didn't call `as_subclass` here, we would still need + # this wrapper to call wrap(), because the TVTensor type would be + # lost after the first operation due to our own __torch_function__ + # logic. + output = kernel(inpt.as_subclass(torch.Tensor), *args, **kwargs) + return tv_tensors.wrap(output, like=inpt) + + return wrapper + + +def _register_kernel_internal(functional, input_type, *, tv_tensor_wrapper=True): + registry = _KERNEL_REGISTRY.setdefault(functional, {}) + if input_type in registry: + raise ValueError(f"Functional {functional} already has a kernel registered for type {input_type}.") + + def decorator(kernel): + registry[input_type] = ( + _kernel_tv_tensor_wrapper(kernel) + if issubclass(input_type, tv_tensors.TVTensor) and tv_tensor_wrapper + else kernel + ) + return kernel + + return decorator + + +def _name_to_functional(name): + import torchvision.transforms.v2.functional # noqa + + try: + return getattr(torchvision.transforms.v2.functional, name) + except AttributeError: + raise ValueError( + f"Could not find functional with name '{name}' in torchvision.transforms.v2.functional." + ) from None + + +_BUILTIN_DATAPOINT_TYPES = { + obj for obj in tv_tensors.__dict__.values() if isinstance(obj, type) and issubclass(obj, tv_tensors.TVTensor) +} + + +def register_kernel(functional, tv_tensor_cls): + """Decorate a kernel to register it for a functional and a (custom) tv_tensor type. + + See :ref:`sphx_glr_auto_examples_transforms_plot_custom_tv_tensors.py` for usage + details. + """ + if isinstance(functional, str): + functional = _name_to_functional(name=functional) + elif not ( + callable(functional) + and getattr(functional, "__module__", "").startswith("torchvision.transforms.v2.functional") + ): + raise ValueError( + f"Kernels can only be registered on functionals from the torchvision.transforms.v2.functional namespace, " + f"but got {functional}." + ) + + if not (isinstance(tv_tensor_cls, type) and issubclass(tv_tensor_cls, tv_tensors.TVTensor)): + raise ValueError( + f"Kernels can only be registered for subclasses of torchvision.tv_tensors.TVTensor, " + f"but got {tv_tensor_cls}." + ) + + if tv_tensor_cls in _BUILTIN_DATAPOINT_TYPES: + raise ValueError(f"Kernels cannot be registered for the builtin tv_tensor classes, but got {tv_tensor_cls}") + + return _register_kernel_internal(functional, tv_tensor_cls, tv_tensor_wrapper=False) + + +def _get_kernel(functional, input_type, *, allow_passthrough=False): + registry = _KERNEL_REGISTRY.get(functional) + if not registry: + raise ValueError(f"No kernel registered for functional {functional.__name__}.") + + for cls in input_type.__mro__: + if cls in registry: + return registry[cls] + elif cls is tv_tensors.TVTensor: + # We don't want user-defined tv_tensors to dispatch to the pure Tensor kernels, so we explicit stop the + # MRO traversal before hitting torch.Tensor. We can even stop at tv_tensors.TVTensor, since we don't + # allow kernels to be registered for tv_tensors.TVTensor anyway. + break + + if allow_passthrough: + return lambda inpt, *args, **kwargs: inpt + + raise TypeError( + f"Functional F.{functional.__name__} supports inputs of type {registry.keys()}, " + f"but got {input_type} instead." + ) + + +# This basically replicates _register_kernel_internal, but with a specialized wrapper for five_crop / ten_crop +# We could get rid of this by letting _register_kernel_internal take arbitrary functionals rather than wrap_kernel: bool +def _register_five_ten_crop_kernel_internal(functional, input_type): + registry = _KERNEL_REGISTRY.setdefault(functional, {}) + if input_type in registry: + raise TypeError(f"Functional '{functional}' already has a kernel registered for type '{input_type}'.") + + def wrap(kernel): + @functools.wraps(kernel) + def wrapper(inpt, *args, **kwargs): + output = kernel(inpt, *args, **kwargs) + container_type = type(output) + return container_type(tv_tensors.wrap(o, like=inpt) for o in output) + + return wrapper + + def decorator(kernel): + registry[input_type] = wrap(kernel) if issubclass(input_type, tv_tensors.TVTensor) else kernel + return kernel + + return decorator diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__init__.py b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7bc01c2b8b683de807d568be514cbe08ea1ace78 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__init__.py @@ -0,0 +1,35 @@ +import torch + +from ._bounding_boxes import BoundingBoxes, BoundingBoxFormat, is_rotated_bounding_format +from ._image import Image +from ._keypoints import KeyPoints +from ._mask import Mask +from ._torch_function_helpers import set_return_type +from ._tv_tensor import TVTensor +from ._video import Video + + +# TODO: Fix this. We skip this method as it leads to +# RecursionError: maximum recursion depth exceeded while calling a Python object +# Until `disable` is removed, there will be graph breaks after all calls to functional transforms +@torch.compiler.disable +def wrap(wrappee, *, like, **kwargs): + """Convert a :class:`torch.Tensor` (``wrappee``) into the same :class:`~torchvision.tv_tensors.TVTensor` subclass as ``like``. + + If ``like`` carries metadata (e.g. ``format``, ``canvas_size``), that + metadata is copied to the output. Individual metadata fields can be + overridden via ``kwargs``. + + Subclass authors can override :meth:`~torchvision.tv_tensors.TVTensor.wrap` + to define how their metadata is propagated. + + Args: + wrappee (Tensor): The tensor to convert. + like (:class:`~torchvision.tv_tensors.TVTensor`): The reference. + ``wrappee`` will be converted into the same subclass as ``like``. + kwargs: Metadata overrides passed to the subclass's + :meth:`~torchvision.tv_tensors.TVTensor.wrap` method. + """ + if (wrap_method := getattr(type(like), "wrap", None)) is not None: + return wrap_method(wrappee, like, **kwargs) + return wrappee.as_subclass(type(like)) diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5472a93c08ce0eef5956044d2326307800f9e9ec Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_bounding_boxes.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_bounding_boxes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0eaa86a87dc0700e515f579148e928b24e9369f Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_bounding_boxes.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_dataset_wrapper.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_dataset_wrapper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25cf02bd4af8d1be78287149d355792bcc93f282 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_dataset_wrapper.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_image.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_image.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92c0187b92ef34c603a6efa5024843c0590727ec Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_image.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_keypoints.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_keypoints.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f3a5c5cde679d2dd13c869c01805cf9ff58e61c Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_keypoints.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_mask.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_mask.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..978d5bbcc627d5f4101ad4ded39a3ef213180894 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_mask.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_torch_function_helpers.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_torch_function_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..022870a6ca24fa83857ab35416c114fd98661987 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_torch_function_helpers.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_tv_tensor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_tv_tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7177d83edffa02da3eb3605c5345f97c4131f3b Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_tv_tensor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_video.cpython-312.pyc b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_video.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c81da74e0f491af1bdb301581a61fa705928308 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/__pycache__/_video.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_bounding_boxes.py b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_bounding_boxes.py new file mode 100644 index 0000000000000000000000000000000000000000..dc1d0e6a0aaa85e11a680fbf5de282c0db8ff25c --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_bounding_boxes.py @@ -0,0 +1,179 @@ +from __future__ import annotations + +from collections.abc import Mapping, Sequence + +from enum import Enum +from typing import Any, Optional + +import torch +from torch.utils._pytree import tree_flatten + +from ._tv_tensor import TVTensor + + +class BoundingBoxFormat(Enum): + """Coordinate format of a bounding box. + + Available formats are: + + * ``XYXY``: bounding box represented via corners; x1, y1 being top left; + x2, y2 being bottom right. + * ``XYWH``: bounding box represented via corner, width and height; x1, y1 + being top left; w, h being width and height. + * ``CXCYWH``: bounding box represented via centre, width and height; cx, + cy being center of box; w, h being width and height. + * ``XYWHR``: rotated boxes represented via corner, width and height; x1, y1 + being top left; w, h being width and height. r is rotation angle in + degrees. + * ``CXCYWHR``: rotated boxes represented via center, width and height; cx, + cy being center of box; w, h being width and height. r is rotation angle + in degrees. + * ``XYXYXYXY``: rotated boxes represented via corners; x1, y1 being top + left; x2, y2 being top right; x3, y3 being bottom right; x4, y4 being + bottom left. + """ + + XYXY = "XYXY" + XYWH = "XYWH" + CXCYWH = "CXCYWH" + XYWHR = "XYWHR" + CXCYWHR = "CXCYWHR" + XYXYXYXY = "XYXYXYXY" + + +# TODO: Once torchscript supports Enums with staticmethod +# this can be put into BoundingBoxFormat as staticmethod +def is_rotated_bounding_format(format: BoundingBoxFormat | str) -> bool: + if isinstance(format, BoundingBoxFormat): + return ( + format == BoundingBoxFormat.XYWHR + or format == BoundingBoxFormat.CXCYWHR + or format == BoundingBoxFormat.XYXYXYXY + ) + elif isinstance(format, str): + return format in ("XYWHR", "CXCYWHR", "XYXYXYXY") + else: + raise ValueError(f"format should be str or BoundingBoxFormat, got {type(format)}") + + +# This should ideally be a Literal, but torchscript fails. +CLAMPING_MODE_TYPE = Optional[str] + + +class BoundingBoxes(TVTensor): + """:class:`torch.Tensor` subclass for bounding boxes with shape ``[N, K]``. + + .. note:: + Support for rotated bounding boxes was released in TorchVision 0.23 and + is currently a BETA feature. We don't expect the API to change, but + there may be some rare edge-cases. If you find any issues, please report + them on our bug tracker: + https://github.com/pytorch/vision/issues?q=is:open+is:issue + + Where ``N`` is the number of bounding boxes + and ``K`` is 4 for unrotated boxes, and 5 or 8 for rotated boxes. + + .. note:: + There should be only one :class:`~torchvision.tv_tensors.BoundingBoxes` + instance per sample e.g. ``{"img": img, "bbox": BoundingBoxes(...)}``, + although one :class:`~torchvision.tv_tensors.BoundingBoxes` object can + contain multiple bounding boxes. + + Args: + data: Any data that can be turned into a tensor with :func:`torch.as_tensor`. + format (BoundingBoxFormat, str): Format of the bounding box. + canvas_size (two-tuple of ints): Height and width of the corresponding image or video. + clamping_mode: The clamping mode to use when applying transforms that may result in bounding boxes + partially outside of the image. Possible values are: "soft", "hard", or ``None``. Read more in :ref:`clamping_mode_tuto`. + dtype (torch.dtype, optional): Desired data type of the bounding box. If omitted, will be inferred from + ``data``. + device (torch.device, optional): Desired device of the bounding box. If omitted and ``data`` is a + :class:`torch.Tensor`, the device is taken from it. Otherwise, the bounding box is constructed on the CPU. + requires_grad (bool, optional): Whether autograd should record operations on the bounding box. If omitted and + ``data`` is a :class:`torch.Tensor`, the value is taken from it. Otherwise, defaults to ``False``. + """ + + format: BoundingBoxFormat + canvas_size: tuple[int, int] + clamping_mode: CLAMPING_MODE_TYPE + + @classmethod + def _wrap(cls, tensor: torch.Tensor, *, format: BoundingBoxFormat | str, canvas_size: tuple[int, int], clamping_mode: CLAMPING_MODE_TYPE = "soft", check_dims: bool = True) -> BoundingBoxes: # type: ignore[override] + if check_dims: + if tensor.ndim == 1: + tensor = tensor.unsqueeze(0) + elif tensor.ndim != 2: + raise ValueError(f"Expected a 1D or 2D tensor, got {tensor.ndim}D") + if clamping_mode is not None and clamping_mode not in ("hard", "soft"): + raise ValueError(f"clamping_mode must be None, hard or soft, got {clamping_mode}.") + + if isinstance(format, str): + format = BoundingBoxFormat[format.upper()] + + bounding_boxes = tensor.as_subclass(cls) + bounding_boxes.format = format + bounding_boxes.canvas_size = canvas_size + bounding_boxes.clamping_mode = clamping_mode + return bounding_boxes + + @classmethod + def wrap(cls, tensor: torch.Tensor, like: BoundingBoxes, **kwargs: Any) -> BoundingBoxes: # type: ignore[override] + return cls._wrap( + tensor, + format=kwargs.get("format", like.format), + canvas_size=kwargs.get("canvas_size", like.canvas_size), + clamping_mode=kwargs.get("clamping_mode", like.clamping_mode), + ) + + def __new__( + cls, + data: Any, + *, + format: BoundingBoxFormat | str, + canvas_size: tuple[int, int], + clamping_mode: CLAMPING_MODE_TYPE = "soft", + dtype: torch.dtype | None = None, + device: torch.device | str | int | None = None, + requires_grad: bool | None = None, + ) -> BoundingBoxes: + tensor = cls._to_tensor(data, dtype=dtype, device=device, requires_grad=requires_grad) + if not torch.is_floating_point(tensor) and is_rotated_bounding_format(format): + raise ValueError(f"Rotated bounding boxes should be floating point tensors, got {tensor.dtype}.") + return cls._wrap(tensor, format=format, canvas_size=canvas_size, clamping_mode=clamping_mode) + + @classmethod + def _wrap_output( + cls, + output: torch.Tensor, + args: Sequence[Any] = (), + kwargs: Mapping[str, Any] | None = None, + ) -> BoundingBoxes: + # If there are BoundingBoxes instances in the output, their metadata got lost when we called + # super().__torch_function__. We need to restore the metadata somehow, so we choose to take + # the metadata from the first bbox in the parameters. + # This should be what we want in most cases. When it's not, it's probably a mis-use anyway, e.g. + # something like some_xyxy_bbox + some_xywh_bbox; we don't guard against those cases. + flat_params, _ = tree_flatten(args + (tuple(kwargs.values()) if kwargs else ())) # type: ignore[operator] + first_bbox_from_args = next(x for x in flat_params if isinstance(x, BoundingBoxes)) + format, canvas_size, clamping_mode = ( + first_bbox_from_args.format, + first_bbox_from_args.canvas_size, + first_bbox_from_args.clamping_mode, + ) + + if isinstance(output, torch.Tensor) and not isinstance(output, BoundingBoxes): + output = BoundingBoxes._wrap( + output, format=format, canvas_size=canvas_size, clamping_mode=clamping_mode, check_dims=False + ) + elif isinstance(output, (tuple, list)): + # This branch exists for chunk() and unbind() + output = type(output)( + BoundingBoxes._wrap( + part, format=format, canvas_size=canvas_size, clamping_mode=clamping_mode, check_dims=False + ) + for part in output + ) + return output + + def __repr__(self, *, tensor_contents: Any = None) -> str: # type: ignore[override] + return self._make_repr(format=self.format, canvas_size=self.canvas_size, clamping_mode=self.clamping_mode) diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_dataset_wrapper.py b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_dataset_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..23683221f6005a9ce6a55e785e59409a649d7928 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_dataset_wrapper.py @@ -0,0 +1,666 @@ +# type: ignore + +from __future__ import annotations + +import collections.abc + +import contextlib +from collections import defaultdict +from copy import copy + +import torch + +from torchvision import datasets, tv_tensors +from torchvision.transforms.v2 import functional as F + +__all__ = ["wrap_dataset_for_transforms_v2"] + + +def wrap_dataset_for_transforms_v2(dataset, target_keys=None): + """Wrap a ``torchvision.dataset`` for usage with :mod:`torchvision.transforms.v2`. + + Example: + >>> dataset = torchvision.datasets.CocoDetection(...) + >>> dataset = wrap_dataset_for_transforms_v2(dataset) + + .. note:: + + For now, only the most popular datasets are supported. Furthermore, the wrapper only supports dataset + configurations that are fully supported by ``torchvision.transforms.v2``. If you encounter an error prompting you + to raise an issue to ``torchvision`` for a dataset or configuration that you need, please do so. + + The dataset samples are wrapped according to the description below. + + Special cases: + + * :class:`~torchvision.datasets.CocoDetection`: Instead of returning the target as list of dicts, the wrapper + returns a dict of lists. In addition, the key-value-pairs ``"boxes"`` (in ``XYXY`` coordinate format), + ``"masks"`` and ``"labels"`` are added and wrap the data in the corresponding ``torchvision.tv_tensors``. + The original keys are preserved. If ``target_keys`` is omitted, returns only the values for the + ``"image_id"``, ``"boxes"``, and ``"labels"``. + * :class:`~torchvision.datasets.VOCDetection`: The key-value-pairs ``"boxes"`` and ``"labels"`` are added to + the target and wrap the data in the corresponding ``torchvision.tv_tensors``. The original keys are + preserved. If ``target_keys`` is omitted, returns only the values for the ``"boxes"`` and ``"labels"``. + * :class:`~torchvision.datasets.CelebA`: The target for ``target_type="bbox"`` is converted to the ``XYXY`` + coordinate format and wrapped into a :class:`~torchvision.tv_tensors.BoundingBoxes` tv_tensor. + * :class:`~torchvision.datasets.Kitti`: Instead returning the target as list of dicts, the wrapper returns a + dict of lists. In addition, the key-value-pairs ``"boxes"`` and ``"labels"`` are added and wrap the data + in the corresponding ``torchvision.tv_tensors``. The original keys are preserved. If ``target_keys`` is + omitted, returns only the values for the ``"boxes"`` and ``"labels"``. + * :class:`~torchvision.datasets.OxfordIIITPet`: The target for ``target_type="segmentation"`` is wrapped into a + :class:`~torchvision.tv_tensors.Mask` tv_tensor. + * :class:`~torchvision.datasets.Cityscapes`: The target for ``target_type="semantic"`` is wrapped into a + :class:`~torchvision.tv_tensors.Mask` tv_tensor. The target for ``target_type="instance"`` is *replaced* by + a dictionary with the key-value-pairs ``"masks"`` (as :class:`~torchvision.tv_tensors.Mask` tv_tensor) and + ``"labels"``. + * :class:`~torchvision.datasets.WIDERFace`: The value for key ``"bbox"`` in the target is converted to ``XYXY`` + coordinate format and wrapped into a :class:`~torchvision.tv_tensors.BoundingBoxes` tv_tensor. + + Image classification datasets + + This wrapper is a no-op for image classification datasets, since they were already fully supported by + :mod:`torchvision.transforms` and thus no change is needed for :mod:`torchvision.transforms.v2`. + + Segmentation datasets + + Segmentation datasets, e.g. :class:`~torchvision.datasets.VOCSegmentation`, return a two-tuple of + :class:`PIL.Image.Image`'s. This wrapper leaves the image as is (first item), while wrapping the + segmentation mask into a :class:`~torchvision.tv_tensors.Mask` (second item). + + Video classification datasets + + Video classification datasets, e.g. :class:`~torchvision.datasets.Kinetics`, return a three-tuple containing a + :class:`torch.Tensor` for the video and audio and a :class:`int` as label. This wrapper wraps the video into a + :class:`~torchvision.tv_tensors.Video` while leaving the other items as is. + + .. note:: + + Only datasets constructed with ``output_format="TCHW"`` are supported, since the alternative + ``output_format="THWC"`` is not supported by :mod:`torchvision.transforms.v2`. + + Args: + dataset: the dataset instance to wrap for compatibility with transforms v2. + target_keys: Target keys to return in case the target is a dictionary. If ``None`` (default), selected keys are + specific to the dataset. If ``"all"``, returns the full target. Can also be a collection of strings for + fine grained access. Currently only supported for :class:`~torchvision.datasets.CocoDetection`, + :class:`~torchvision.datasets.VOCDetection`, :class:`~torchvision.datasets.Kitti`, and + :class:`~torchvision.datasets.WIDERFace`. See above for details. + """ + if not ( + target_keys is None + or target_keys == "all" + or (isinstance(target_keys, collections.abc.Collection) and all(isinstance(key, str) for key in target_keys)) + ): + raise ValueError( + f"`target_keys` can be None, 'all', or a collection of strings denoting the keys to be returned, " + f"but got {target_keys}" + ) + + # Imagine we have isinstance(dataset, datasets.ImageNet). This will create a new class with the name + # "WrappedImageNet" at runtime that doubly inherits from VisionDatasetTVTensorWrapper (see below) as well as the + # original ImageNet class. This allows the user to do regular isinstance(wrapped_dataset, datasets.ImageNet) checks, + # while we can still inject everything that we need. + wrapped_dataset_cls = type(f"Wrapped{type(dataset).__name__}", (VisionDatasetTVTensorWrapper, type(dataset)), {}) + # Since VisionDatasetTVTensorWrapper comes before ImageNet in the MRO, calling the class hits + # VisionDatasetTVTensorWrapper.__init__ first. Since we are never doing super().__init__(...), the constructor of + # ImageNet is never hit. That is by design, since we don't want to create the dataset instance again, but rather + # have the existing instance as attribute on the new object. + return wrapped_dataset_cls(dataset, target_keys) + + +class WrapperFactories(dict): + def register(self, dataset_cls): + def decorator(wrapper_factory): + self[dataset_cls] = wrapper_factory + return wrapper_factory + + return decorator + + +# We need this two-stage design, i.e. a wrapper factory producing the actual wrapper, since some wrappers depend on the +# dataset instance rather than just the class, since they require the user defined instance attributes. Thus, we can +# provide a wrapping from the dataset class to the factory here, but can only instantiate the wrapper at runtime when +# we have access to the dataset instance. +WRAPPER_FACTORIES = WrapperFactories() + + +class VisionDatasetTVTensorWrapper: + def __init__(self, dataset, target_keys): + dataset_cls = type(dataset) + + if not isinstance(dataset, datasets.VisionDataset): + raise TypeError( + f"This wrapper is meant for subclasses of `torchvision.datasets.VisionDataset`, " + f"but got a '{dataset_cls.__name__}' instead.\n" + f"For an example of how to perform the wrapping for custom datasets, see\n\n" + "https://pytorch.org/vision/main/auto_examples/plot_tv_tensors.html#do-i-have-to-wrap-the-output-of-the-datasets-myself" + ) + + for cls in dataset_cls.mro(): + if cls in WRAPPER_FACTORIES: + wrapper_factory = WRAPPER_FACTORIES[cls] + if target_keys is not None and cls not in { + datasets.CocoDetection, + datasets.VOCDetection, + datasets.Kitti, + datasets.WIDERFace, + }: + raise ValueError( + f"`target_keys` is currently only supported for `CocoDetection`, `VOCDetection`, `Kitti`, " + f"and `WIDERFace`, but got {cls.__name__}." + ) + break + elif cls is datasets.VisionDataset: + # TODO: If we have documentation on how to do that, put a link in the error message. + msg = f"No wrapper exists for dataset class {dataset_cls.__name__}. Please wrap the output yourself." + if dataset_cls in datasets.__dict__.values(): + msg = ( + f"{msg} If an automated wrapper for this dataset would be useful for you, " + f"please open an issue at https://github.com/pytorch/vision/issues." + ) + raise TypeError(msg) + + self._dataset = dataset + self._target_keys = target_keys + self._wrapper = wrapper_factory(dataset, target_keys) + + # We need to disable the transforms on the dataset here to be able to inject the wrapping before we apply them. + # Although internally, `datasets.VisionDataset` merges `transform` and `target_transform` into the joint + # `transforms` + # https://github.com/pytorch/vision/blob/135a0f9ea9841b6324b4fe8974e2543cbb95709a/torchvision/datasets/vision.py#L52-L54 + # some (if not most) datasets still use `transform` and `target_transform` individually. Thus, we need to + # disable all three here to be able to extract the untransformed sample to wrap. + self.transform, dataset.transform = dataset.transform, None + self.target_transform, dataset.target_transform = dataset.target_transform, None + self.transforms, dataset.transforms = dataset.transforms, None + + def __getattr__(self, item): + with contextlib.suppress(AttributeError): + return object.__getattribute__(self, item) + + return getattr(self._dataset, item) + + def __getitem__(self, idx): + # This gets us the raw sample since we disabled the transforms for the underlying dataset in the constructor + # of this class + sample = self._dataset[idx] + + sample = self._wrapper(idx, sample) + + # Regardless of whether the user has supplied the transforms individually (`transform` and `target_transform`) + # or joint (`transforms`), we can access the full functionality through `transforms` + if self.transforms is not None: + sample = self.transforms(*sample) + + return sample + + def __len__(self): + return len(self._dataset) + + # TODO: maybe we should use __getstate__ and __setstate__ instead of __reduce__, as recommended in the docs. + def __reduce__(self): + # __reduce__ gets called when we try to pickle the dataset. + # In a DataLoader with spawn context, this gets called `num_workers` times from the main process. + + # We have to reset the [target_]transform[s] attributes of the dataset + # to their original values, because we previously set them to None in __init__(). + dataset = copy(self._dataset) + dataset.transform = self.transform + dataset.transforms = self.transforms + dataset.target_transform = self.target_transform + + return wrap_dataset_for_transforms_v2, (dataset, self._target_keys) + + +def raise_not_supported(description): + raise RuntimeError( + f"{description} is currently not supported by this wrapper. " + f"If this would be helpful for you, please open an issue at https://github.com/pytorch/vision/issues." + ) + + +def identity(item): + return item + + +def identity_wrapper_factory(dataset, target_keys): + def wrapper(idx, sample): + return sample + + return wrapper + + +def pil_image_to_mask(pil_image): + return tv_tensors.Mask(pil_image) + + +def parse_target_keys(target_keys, *, available, default): + if target_keys is None: + target_keys = default + if target_keys == "all": + target_keys = available + else: + target_keys = set(target_keys) + extra = target_keys - available + if extra: + raise ValueError(f"Target keys {sorted(extra)} are not available") + + return target_keys + + +def list_of_dicts_to_dict_of_lists(list_of_dicts): + dict_of_lists = defaultdict(list) + for dct in list_of_dicts: + for key, value in dct.items(): + dict_of_lists[key].append(value) + return dict(dict_of_lists) + + +def wrap_target_by_type(target, *, target_types, type_wrappers): + if not isinstance(target, (tuple, list)): + target = [target] + + wrapped_target = tuple( + type_wrappers.get(target_type, identity)(item) for target_type, item in zip(target_types, target) + ) + + if len(wrapped_target) == 1: + wrapped_target = wrapped_target[0] + + return wrapped_target + + +def classification_wrapper_factory(dataset, target_keys): + return identity_wrapper_factory(dataset, target_keys) + + +for dataset_cls in [ + datasets.Caltech256, + datasets.CIFAR10, + datasets.CIFAR100, + datasets.ImageNet, + datasets.MNIST, + datasets.FashionMNIST, + datasets.GTSRB, + datasets.DatasetFolder, + datasets.ImageFolder, + datasets.Imagenette, +]: + WRAPPER_FACTORIES.register(dataset_cls)(classification_wrapper_factory) + + +def segmentation_wrapper_factory(dataset, target_keys): + def wrapper(idx, sample): + image, mask = sample + return image, pil_image_to_mask(mask) + + return wrapper + + +for dataset_cls in [ + datasets.VOCSegmentation, +]: + WRAPPER_FACTORIES.register(dataset_cls)(segmentation_wrapper_factory) + + +def video_classification_wrapper_factory(dataset, target_keys): + if dataset.video_clips.output_format == "THWC": + raise RuntimeError( + f"{type(dataset).__name__} with `output_format='THWC'` is not supported by this wrapper, " + f"since it is not compatible with the transformations. Please use `output_format='TCHW'` instead." + ) + + def wrapper(idx, sample): + video, audio, label = sample + + video = tv_tensors.Video(video) + + return video, audio, label + + return wrapper + + +for dataset_cls in [ + datasets.HMDB51, + datasets.Kinetics, + datasets.UCF101, +]: + WRAPPER_FACTORIES.register(dataset_cls)(video_classification_wrapper_factory) + + +@WRAPPER_FACTORIES.register(datasets.Caltech101) +def caltech101_wrapper_factory(dataset, target_keys): + if "annotation" in dataset.target_type: + raise_not_supported("Caltech101 dataset with `target_type=['annotation', ...]`") + + return classification_wrapper_factory(dataset, target_keys) + + +@WRAPPER_FACTORIES.register(datasets.CocoDetection) +def coco_dectection_wrapper_factory(dataset, target_keys): + target_keys = parse_target_keys( + target_keys, + available={ + # native + "segmentation", + "area", + "iscrowd", + "image_id", + "bbox", + "category_id", + # added by the wrapper + "boxes", + "masks", + "labels", + }, + default={"image_id", "boxes", "labels"}, + ) + + def segmentation_to_mask(segmentation, *, canvas_size): + from pycocotools import mask + + if isinstance(segmentation, dict): + # if counts is a string, it is already an encoded RLE mask + if not isinstance(segmentation["counts"], str): + segmentation = mask.frPyObjects(segmentation, *canvas_size) + elif isinstance(segmentation, list): + segmentation = mask.merge(mask.frPyObjects(segmentation, *canvas_size)) + else: + raise ValueError(f"COCO segmentation expected to be a dict or a list, got {type(segmentation)}") + return torch.from_numpy(mask.decode(segmentation)) + + def wrapper(idx, sample): + image_id = dataset.ids[idx] + + image, target = sample + + if not target: + return image, dict(image_id=image_id) + + canvas_size = tuple(F.get_size(image)) + + batched_target = list_of_dicts_to_dict_of_lists(target) + target = {} + + if "image_id" in target_keys: + target["image_id"] = image_id + + if "boxes" in target_keys: + target["boxes"] = F.convert_bounding_box_format( + tv_tensors.BoundingBoxes( + batched_target["bbox"], + format=tv_tensors.BoundingBoxFormat.XYWH, + canvas_size=canvas_size, + ), + new_format=tv_tensors.BoundingBoxFormat.XYXY, + ) + + if "masks" in target_keys: + target["masks"] = tv_tensors.Mask( + torch.stack( + [ + segmentation_to_mask(segmentation, canvas_size=canvas_size) + for segmentation in batched_target["segmentation"] + ] + ), + ) + + if "labels" in target_keys: + target["labels"] = torch.tensor(batched_target["category_id"]) + + for target_key in target_keys - {"image_id", "boxes", "masks", "labels"}: + target[target_key] = batched_target[target_key] + + return image, target + + return wrapper + + +WRAPPER_FACTORIES.register(datasets.CocoCaptions)(identity_wrapper_factory) + + +VOC_DETECTION_CATEGORIES = [ + "__background__", + "aeroplane", + "bicycle", + "bird", + "boat", + "bottle", + "bus", + "car", + "cat", + "chair", + "cow", + "diningtable", + "dog", + "horse", + "motorbike", + "person", + "pottedplant", + "sheep", + "sofa", + "train", + "tvmonitor", +] +VOC_DETECTION_CATEGORY_TO_IDX = dict(zip(VOC_DETECTION_CATEGORIES, range(len(VOC_DETECTION_CATEGORIES)))) + + +@WRAPPER_FACTORIES.register(datasets.VOCDetection) +def voc_detection_wrapper_factory(dataset, target_keys): + target_keys = parse_target_keys( + target_keys, + available={ + # native + "annotation", + # added by the wrapper + "boxes", + "labels", + }, + default={"boxes", "labels"}, + ) + + def wrapper(idx, sample): + image, target = sample + + batched_instances = list_of_dicts_to_dict_of_lists(target["annotation"]["object"]) + + if "annotation" not in target_keys: + target = {} + + if "boxes" in target_keys: + target["boxes"] = tv_tensors.BoundingBoxes( + [ + [int(bndbox[part]) for part in ("xmin", "ymin", "xmax", "ymax")] + for bndbox in batched_instances["bndbox"] + ], + format=tv_tensors.BoundingBoxFormat.XYXY, + canvas_size=(image.height, image.width), + ) + + if "labels" in target_keys: + target["labels"] = torch.tensor( + [VOC_DETECTION_CATEGORY_TO_IDX[category] for category in batched_instances["name"]] + ) + + return image, target + + return wrapper + + +@WRAPPER_FACTORIES.register(datasets.SBDataset) +def sbd_wrapper(dataset, target_keys): + if dataset.mode == "boundaries": + raise_not_supported("SBDataset with mode='boundaries'") + + return segmentation_wrapper_factory(dataset, target_keys) + + +@WRAPPER_FACTORIES.register(datasets.CelebA) +def celeba_wrapper_factory(dataset, target_keys): + if any(target_type in dataset.target_type for target_type in ["attr", "landmarks"]): + raise_not_supported("`CelebA` dataset with `target_type=['attr', 'landmarks', ...]`") + + def wrapper(idx, sample): + image, target = sample + + target = wrap_target_by_type( + target, + target_types=dataset.target_type, + type_wrappers={ + "bbox": lambda item: F.convert_bounding_box_format( + tv_tensors.BoundingBoxes( + item, + format=tv_tensors.BoundingBoxFormat.XYWH, + canvas_size=(image.height, image.width), + ), + new_format=tv_tensors.BoundingBoxFormat.XYXY, + ), + }, + ) + + return image, target + + return wrapper + + +KITTI_CATEGORIES = ["Car", "Van", "Truck", "Pedestrian", "Person_sitting", "Cyclist", "Tram", "Misc", "DontCare"] +KITTI_CATEGORY_TO_IDX = dict(zip(KITTI_CATEGORIES, range(len(KITTI_CATEGORIES)))) + + +@WRAPPER_FACTORIES.register(datasets.Kitti) +def kitti_wrapper_factory(dataset, target_keys): + target_keys = parse_target_keys( + target_keys, + available={ + # native + "type", + "truncated", + "occluded", + "alpha", + "bbox", + "dimensions", + "location", + "rotation_y", + # added by the wrapper + "boxes", + "labels", + }, + default={"boxes", "labels"}, + ) + + def wrapper(idx, sample): + image, target = sample + + if target is None: + return image, target + + batched_target = list_of_dicts_to_dict_of_lists(target) + target = {} + + if "boxes" in target_keys: + target["boxes"] = tv_tensors.BoundingBoxes( + batched_target["bbox"], + format=tv_tensors.BoundingBoxFormat.XYXY, + canvas_size=(image.height, image.width), + ) + + if "labels" in target_keys: + target["labels"] = torch.tensor([KITTI_CATEGORY_TO_IDX[category] for category in batched_target["type"]]) + + for target_key in target_keys - {"boxes", "labels"}: + target[target_key] = batched_target[target_key] + + return image, target + + return wrapper + + +@WRAPPER_FACTORIES.register(datasets.OxfordIIITPet) +def oxford_iiit_pet_wrapper_factor(dataset, target_keys): + def wrapper(idx, sample): + image, target = sample + + if target is not None: + target = wrap_target_by_type( + target, + target_types=dataset._target_types, + type_wrappers={ + "segmentation": pil_image_to_mask, + }, + ) + + return image, target + + return wrapper + + +@WRAPPER_FACTORIES.register(datasets.Cityscapes) +def cityscapes_wrapper_factory(dataset, target_keys): + if any(target_type in dataset.target_type for target_type in ["polygon", "color"]): + raise_not_supported("`Cityscapes` dataset with `target_type=['polygon', 'color', ...]`") + + def instance_segmentation_wrapper(mask): + # See https://github.com/mcordts/cityscapesScripts/blob/8da5dd00c9069058ccc134654116aac52d4f6fa2/cityscapesscripts/preparation/json2instanceImg.py#L7-L21 + data = pil_image_to_mask(mask) + masks = [] + labels = [] + for id in data.unique(): + masks.append(data == id) + label = id + if label >= 1_000: + label //= 1_000 + labels.append(label) + return dict(masks=tv_tensors.Mask(torch.stack(masks)), labels=torch.stack(labels)) + + def wrapper(idx, sample): + image, target = sample + + target = wrap_target_by_type( + target, + target_types=dataset.target_type, + type_wrappers={ + "instance": instance_segmentation_wrapper, + "semantic": pil_image_to_mask, + }, + ) + + return image, target + + return wrapper + + +@WRAPPER_FACTORIES.register(datasets.WIDERFace) +def widerface_wrapper(dataset, target_keys): + target_keys = parse_target_keys( + target_keys, + available={ + "bbox", + "blur", + "expression", + "illumination", + "occlusion", + "pose", + "invalid", + }, + default="all", + ) + + def wrapper(idx, sample): + image, target = sample + + if target is None: + return image, target + + target = {key: target[key] for key in target_keys} + + if "bbox" in target_keys: + target["bbox"] = F.convert_bounding_box_format( + tv_tensors.BoundingBoxes( + target["bbox"], format=tv_tensors.BoundingBoxFormat.XYWH, canvas_size=(image.height, image.width) + ), + new_format=tv_tensors.BoundingBoxFormat.XYXY, + ) + + return image, target + + return wrapper diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_image.py b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_image.py new file mode 100644 index 0000000000000000000000000000000000000000..19fe468ac8103035ebb9dd87faa4f454f286de92 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_image.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from typing import Any + +import PIL.Image +import torch + +from ._tv_tensor import TVTensor + + +class Image(TVTensor): + """:class:`torch.Tensor` subclass for images with shape ``[..., C, H, W]``. + + .. note:: + + In the :ref:`transforms `, ``Image`` instances are largely + interchangeable with pure :class:`torch.Tensor`. See + :ref:`this note ` for more details. + + Args: + data (tensor-like, PIL.Image.Image): Any data that can be turned into a tensor with :func:`torch.as_tensor` as + well as PIL images. + dtype (torch.dtype, optional): Desired data type. If omitted, will be inferred from + ``data``. + device (torch.device, optional): Desired device. If omitted and ``data`` is a + :class:`torch.Tensor`, the device is taken from it. Otherwise, the image is constructed on the CPU. + requires_grad (bool, optional): Whether autograd should record operations. If omitted and + ``data`` is a :class:`torch.Tensor`, the value is taken from it. Otherwise, defaults to ``False``. + """ + + def __new__( + cls, + data: Any, + *, + dtype: torch.dtype | None = None, + device: torch.device | str | int | None = None, + requires_grad: bool | None = None, + ) -> Image: + if isinstance(data, PIL.Image.Image): + from torchvision.transforms.v2 import functional as F + + data = F.pil_to_tensor(data) + + tensor = cls._to_tensor(data, dtype=dtype, device=device, requires_grad=requires_grad) + if tensor.ndim < 2: + raise ValueError(f"Tensor must be 2D or higher, got {tensor.ndim}D tensor.") + elif tensor.ndim == 2: + tensor = tensor.unsqueeze(0) + + return tensor.as_subclass(cls) + + def __repr__(self, *, tensor_contents: Any = None) -> str: # type: ignore[override] + return self._make_repr() diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_keypoints.py b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_keypoints.py new file mode 100644 index 0000000000000000000000000000000000000000..73c03ddb5f2bc428f1a4608ea984891058a721d4 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_keypoints.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +from typing import Any, Mapping, Sequence + +import torch +from torch.utils._pytree import tree_flatten + +from ._tv_tensor import TVTensor + + +class KeyPoints(TVTensor): + """:class:`torch.Tensor` subclass for tensors with shape ``[..., 2]`` that represent points in an image. + + .. note:: + Support for keypoints was released in TorchVision 0.23 and is currently + a BETA feature. We don't expect the API to change, but there may be some + rare edge-cases. If you find any issues, please report them on our bug + tracker: https://github.com/pytorch/vision/issues?q=is:open+is:issue + Each point is represented by its X and Y coordinates along the width and + height dimensions, respectively. + + Each point is represented by its X and Y coordinates along the width and height dimensions, respectively. + + KeyPoints may represent any object that can be represented by sequences of 2D points: + + - `Polygonal chains `_, + including polylines, Bézier curves, etc., which can be of shape + ``[N_chains, N_points, 2]``. + - Polygons, which can be of shape ``[N_polygons, N_points, 2]``. + - Skeletons, which can be of shape ``[N_skeletons, N_bones, 2, 2]`` for + pose-estimation models. + + .. note:: + Like for :class:`torchvision.tv_tensors.BoundingBoxes`, there should + only be a single instance of the + :class:`torchvision.tv_tensors.KeyPoints` class per sample e.g. + ``{"img": img, "poins_of_interest": KeyPoints(...)}``, although one + :class:`torchvision.tv_tensors.KeyPoints` object can contain multiple + key points + + Args: + data: Any data that can be turned into a tensor with + :func:`torch.as_tensor`. + canvas_size (two-tuple of ints): Height and width of the corresponding + image or video. + dtype (torch.dtype, optional): Desired data type of the bounding box. If + omitted, will be inferred from ``data``. + device (torch.device, optional): Desired device of the bounding box. If + omitted and ``data`` is a :class:`torch.Tensor`, the device is taken + from it. Otherwise, the bounding box is constructed on the CPU. + requires_grad (bool, optional): Whether autograd should record + operations on the bounding box. If omitted and ``data`` is a + :class:`torch.Tensor`, the value is taken from it. Otherwise, + defaults to ``False``. + """ + + canvas_size: tuple[int, int] + + @classmethod + def _wrap(cls, tensor: torch.Tensor, *, canvas_size: tuple[int, int], check_dims: bool = True) -> KeyPoints: # type: ignore[override] + if check_dims: + if tensor.ndim == 1: + tensor = tensor.unsqueeze(0) + elif tensor.shape[-1] != 2: + raise ValueError(f"Expected a tensor of shape (..., 2), not {tensor.shape}") + points = tensor.as_subclass(cls) + points.canvas_size = canvas_size + return points + + @classmethod + def wrap(cls, tensor: torch.Tensor, like: KeyPoints, **kwargs: Any) -> KeyPoints: # type: ignore[override] + return cls._wrap( + tensor, + canvas_size=kwargs.get("canvas_size", like.canvas_size), + ) + + def __new__( + cls, + data: Any, + *, + canvas_size: tuple[int, int], + dtype: torch.dtype | None = None, + device: torch.device | str | int | None = None, + requires_grad: bool | None = None, + ) -> KeyPoints: + tensor = cls._to_tensor(data, dtype=dtype, device=device, requires_grad=requires_grad) + return cls._wrap(tensor, canvas_size=canvas_size) + + @classmethod + def _wrap_output( + cls, + output: torch.Tensor, + args: Sequence[Any] = (), + kwargs: Mapping[str, Any] | None = None, + ) -> KeyPoints: + # Similar to BoundingBoxes._wrap_output(), see comment there. + flat_params, _ = tree_flatten(args + (tuple(kwargs.values()) if kwargs else ())) # type: ignore[operator] + first_keypoints_from_args = next(x for x in flat_params if isinstance(x, KeyPoints)) + canvas_size = first_keypoints_from_args.canvas_size + + if isinstance(output, torch.Tensor) and not isinstance(output, KeyPoints): + output = KeyPoints._wrap(output, canvas_size=canvas_size, check_dims=False) + elif isinstance(output, (tuple, list)): + # This branch exists for chunk() and unbind() + output = type(output)(KeyPoints._wrap(part, canvas_size=canvas_size, check_dims=False) for part in output) + return output + + def __repr__(self, *, tensor_contents: Any = None) -> str: # type: ignore[override] + return self._make_repr(canvas_size=self.canvas_size) diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_mask.py b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..f43a5c7e2fd477fd129ef84df2117e1cd28b53e8 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_mask.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import Any + +import PIL.Image +import torch + +from ._tv_tensor import TVTensor + + +class Mask(TVTensor): + """:class:`torch.Tensor` subclass for segmentation and detection masks with shape ``[..., H, W]``. + + Args: + data (tensor-like, PIL.Image.Image): Any data that can be turned into a tensor with :func:`torch.as_tensor` as + well as PIL images. + dtype (torch.dtype, optional): Desired data type. If omitted, will be inferred from + ``data``. + device (torch.device, optional): Desired device. If omitted and ``data`` is a + :class:`torch.Tensor`, the device is taken from it. Otherwise, the mask is constructed on the CPU. + requires_grad (bool, optional): Whether autograd should record operations. If omitted and + ``data`` is a :class:`torch.Tensor`, the value is taken from it. Otherwise, defaults to ``False``. + """ + + def __new__( + cls, + data: Any, + *, + dtype: torch.dtype | None = None, + device: torch.device | str | int | None = None, + requires_grad: bool | None = None, + ) -> Mask: + if isinstance(data, PIL.Image.Image): + from torchvision.transforms.v2 import functional as F + + data = F.pil_to_tensor(data) + + tensor = cls._to_tensor(data, dtype=dtype, device=device, requires_grad=requires_grad) + return tensor.as_subclass(cls) diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_torch_function_helpers.py b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_torch_function_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..66812fb5ca641fc4dabd10aad281ee6614229168 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_torch_function_helpers.py @@ -0,0 +1,78 @@ +import torch + +_TORCHFUNCTION_SUBCLASS = False + + +class _ReturnTypeCM: + def __init__(self, to_restore): + self.to_restore = to_restore + + def __enter__(self): + return self + + def __exit__(self, *args): + global _TORCHFUNCTION_SUBCLASS + _TORCHFUNCTION_SUBCLASS = self.to_restore + + +def set_return_type(return_type: str): + """Set the return type of torch operations on :class:`~torchvision.tv_tensors.TVTensor`. + + This only affects the behaviour of torch operations. It has no effect on + ``torchvision`` transforms or functionals, which will always return as + output the same type that was passed as input. + + .. warning:: + + We recommend using :class:`~torchvision.transforms.v2.ToPureTensor` at + the end of your transform pipelines if you use + ``set_return_type("TVTensor")``. This will avoid the + ``__torch_function__`` overhead in the models ``forward()``. + + Can be used as a global flag for the entire program: + + .. code:: python + + img = tv_tensors.Image(torch.rand(3, 5, 5)) + img + 2 # This is a pure Tensor (default behaviour) + + set_return_type("TVTensor") + img + 2 # This is an Image + + or as a context manager to restrict the scope: + + .. code:: python + + img = tv_tensors.Image(torch.rand(3, 5, 5)) + img + 2 # This is a pure Tensor + with set_return_type("TVTensor"): + img + 2 # This is an Image + img + 2 # This is a pure Tensor + + Args: + return_type (str): Can be "TVTensor" or "Tensor" (case-insensitive). + Default is "Tensor" (i.e. pure :class:`torch.Tensor`). + """ + global _TORCHFUNCTION_SUBCLASS + to_restore = _TORCHFUNCTION_SUBCLASS + + try: + _TORCHFUNCTION_SUBCLASS = {"tensor": False, "tvtensor": True}[return_type.lower()] + except KeyError: + raise ValueError(f"return_type must be 'TVTensor' or 'Tensor', got {return_type}") from None + + return _ReturnTypeCM(to_restore) + + +def _must_return_subclass(): + return _TORCHFUNCTION_SUBCLASS + + +# For those ops we always want to preserve the original subclass instead of returning a pure Tensor +_FORCE_TORCHFUNCTION_SUBCLASS = { + torch.Tensor.clone, + torch.Tensor.to, + torch.Tensor.detach, + torch.Tensor.requires_grad_, + torch.Tensor.pin_memory, +} diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_tv_tensor.py b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_tv_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..4e261cd7418bcfed993c13504d908c1517ca32d5 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_tv_tensor.py @@ -0,0 +1,138 @@ +from __future__ import annotations + +from collections.abc import Mapping, Sequence + +from typing import Any, Callable, TypeVar + +import torch +from torch._C import DisableTorchFunctionSubclass +from torch.types import _device, _dtype, _size + +from torchvision.tv_tensors._torch_function_helpers import _FORCE_TORCHFUNCTION_SUBCLASS, _must_return_subclass + + +D = TypeVar("D", bound="TVTensor") + + +class TVTensor(torch.Tensor): + """Base class for all TVTensors. + + You probably don't want to use this class unless you're defining your own + custom TVTensors. See + :ref:`sphx_glr_auto_examples_transforms_plot_custom_tv_tensors.py` for details. + """ + + @staticmethod + def _to_tensor( + data: Any, + dtype: torch.dtype | None = None, + device: torch.device | str | int | None = None, + requires_grad: bool | None = None, + ) -> torch.Tensor: + if requires_grad is None: + requires_grad = data.requires_grad if isinstance(data, torch.Tensor) else False + return torch.as_tensor(data, dtype=dtype, device=device).requires_grad_(requires_grad) + + @classmethod + def _wrap_output( + cls, + output: torch.Tensor, + args: Sequence[Any] = (), + kwargs: Mapping[str, Any] | None = None, + ) -> torch.Tensor: + # Same as torch._tensor._convert + if isinstance(output, torch.Tensor) and not isinstance(output, cls): + output = output.as_subclass(cls) + + if isinstance(output, (tuple, list)): + # Also handles things like namedtuples + output = type(output)(cls._wrap_output(part, args, kwargs) for part in output) + return output + + @classmethod + def wrap(cls, tensor: torch.Tensor, like: TVTensor, **kwargs: Any) -> TVTensor: + return tensor.as_subclass(cls) + + @classmethod + def __torch_function__( + cls, + func: Callable[..., torch.Tensor], + types: tuple[type[torch.Tensor], ...], + args: Sequence[Any] = (), + kwargs: Mapping[str, Any] | None = None, + ) -> torch.Tensor: + """For general information about how the __torch_function__ protocol works, + see https://pytorch.org/docs/stable/notes/extending.html#extending-torch + + TL;DR: Every time a PyTorch operator is called, it goes through the inputs and looks for the + ``__torch_function__`` method. If one is found, it is invoked with the operator as ``func`` as well as the + ``args`` and ``kwargs`` of the original call. + + Why do we override this? Because the base implementation in torch.Tensor would preserve the TVTensor type + of the output. In our case, we want to return pure tensors instead (with a few exceptions). Refer to the + "TVTensors FAQ" gallery example for a rationale of this behaviour (TL;DR: perf + no silver bullet). + + Our implementation below is very similar to the base implementation in ``torch.Tensor`` - go check it out. + """ + if not all(issubclass(cls, t) for t in types): + return NotImplemented + + # Like in the base Tensor.__torch_function__ implementation, it's easier to always use + # DisableTorchFunctionSubclass and then manually re-wrap the output if necessary + with DisableTorchFunctionSubclass(): + output = func(*args, **kwargs or dict()) + + must_return_subclass = _must_return_subclass() + if must_return_subclass or (func in _FORCE_TORCHFUNCTION_SUBCLASS and isinstance(args[0], cls)): + # If you're wondering why we need the `isinstance(args[0], cls)` check, remove it and see what fails + # in test_to_tv_tensor_reference(). + # The __torch_function__ protocol will invoke the __torch_function__ method on *all* types involved in + # the computation by walking the MRO upwards. For example, + # `out = a_pure_tensor.to(an_image)` will invoke `Image.__torch_function__` with + # `args = (a_pure_tensor, an_image)` first. Without this guard, `out` would + # be wrapped into an `Image`. + return cls._wrap_output(output, args, kwargs) + + if not must_return_subclass and isinstance(output, cls): + # DisableTorchFunctionSubclass is ignored by inplace ops like `.add_(...)`, + # so for those, the output is still a TVTensor. Thus, we need to manually unwrap. + return output.as_subclass(torch.Tensor) + + return output + + def _make_repr(self, **kwargs: Any) -> str: + # This is a poor man's implementation of the proposal in https://github.com/pytorch/pytorch/issues/76532. + # If that ever gets implemented, remove this in favor of the solution on the `torch.Tensor` class. + extra_repr = ", ".join(f"{key}={value}" for key, value in kwargs.items()) + return f"{super().__repr__()[:-1]}, {extra_repr})" + + # Add properties for common attributes like shape, dtype, device, ndim etc + # this way we return the result without passing into __torch_function__ + @property + def shape(self) -> _size: # type: ignore[override] + with DisableTorchFunctionSubclass(): + return super().shape + + @property + def ndim(self) -> int: # type: ignore[override] + with DisableTorchFunctionSubclass(): + return super().ndim + + @property + def device(self, *args: Any, **kwargs: Any) -> _device: # type: ignore[override] + with DisableTorchFunctionSubclass(): + return super().device + + @property + def dtype(self) -> _dtype: # type: ignore[override] + with DisableTorchFunctionSubclass(): + return super().dtype + + def __deepcopy__(self: D, memo: dict[int, Any]) -> D: + # We need to detach first, since a plain `Tensor.clone` will be part of the computation graph, which does + # *not* happen for `deepcopy(Tensor)`. A side-effect from detaching is that the `Tensor.requires_grad` + # attribute is cleared, so we need to refill it before we return. + # Note: We don't explicitly handle deep-copying of the metadata here. The only metadata we currently have is + # `BoundingBoxes.format` and `BoundingBoxes.canvas_size`, which are immutable and thus implicitly deep-copied by + # `BoundingBoxes.clone()`. + return self.detach().clone().requires_grad_(self.requires_grad) # type: ignore[return-value] diff --git a/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_video.py b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_video.py new file mode 100644 index 0000000000000000000000000000000000000000..2dd9dafadde9fc11d58a98cc8c66480e50ed9ec2 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/tv_tensors/_video.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from typing import Any + +import torch + +from ._tv_tensor import TVTensor + + +class Video(TVTensor): + """:class:`torch.Tensor` subclass for videos with shape ``[..., T, C, H, W]``. + + Args: + data (tensor-like): Any data that can be turned into a tensor with :func:`torch.as_tensor`. + dtype (torch.dtype, optional): Desired data type. If omitted, will be inferred from + ``data``. + device (torch.device, optional): Desired device. If omitted and ``data`` is a + :class:`torch.Tensor`, the device is taken from it. Otherwise, the video is constructed on the CPU. + requires_grad (bool, optional): Whether autograd should record operations. If omitted and + ``data`` is a :class:`torch.Tensor`, the value is taken from it. Otherwise, defaults to ``False``. + """ + + def __new__( + cls, + data: Any, + *, + dtype: torch.dtype | None = None, + device: torch.device | str | int | None = None, + requires_grad: bool | None = None, + ) -> Video: + tensor = cls._to_tensor(data, dtype=dtype, device=device, requires_grad=requires_grad) + if data.ndim < 4: + raise ValueError + return tensor.as_subclass(cls) + + def __repr__(self, *, tensor_contents: Any = None) -> str: # type: ignore[override] + return self._make_repr() diff --git a/.venv/lib/python3.12/site-packages/torchvision/utils.py b/.venv/lib/python3.12/site-packages/torchvision/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..376911687273fbd986d07e53d15270b0668415b1 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/utils.py @@ -0,0 +1,807 @@ +import collections +import math +import pathlib +import warnings +from itertools import repeat +from types import FunctionType +from typing import Any, BinaryIO, Optional, Union + +import numpy as np +import torch +from PIL import __version__ as PILLOW_VERSION_STRING, Image, ImageColor, ImageDraw, ImageFont + +__all__ = [ + "_Image_fromarray", + "make_grid", + "save_image", + "draw_bounding_boxes", + "draw_segmentation_masks", + "draw_keypoints", + "flow_to_image", +] + + +@torch.no_grad() +def make_grid( + tensor: Union[torch.Tensor, list[torch.Tensor]], + nrow: int = 8, + padding: int = 2, + normalize: bool = False, + value_range: Optional[tuple[int, int]] = None, + scale_each: bool = False, + pad_value: float = 0.0, +) -> torch.Tensor: + """ + Make a grid of images. + + Args: + tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W) + or a list of images all of the same size. + nrow (int, optional): Number of images displayed in each row of the grid. + The final grid size is ``(B / nrow, nrow)``. Default: ``8``. + padding (int, optional): amount of padding. Default: ``2``. + normalize (bool, optional): If True, shift the image to the range (0, 1), + by the min and max values specified by ``value_range``. Default: ``False``. + value_range (tuple, optional): tuple (min, max) where min and max are numbers, + then these numbers are used to normalize the image. By default, min and max + are computed from the tensor. + scale_each (bool, optional): If ``True``, scale each image in the batch of + images separately rather than the (min, max) over all images. Default: ``False``. + pad_value (float, optional): Value for the padded pixels. Default: ``0``. + + Returns: + grid (Tensor): the tensor containing grid of images. + """ + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(make_grid) + if not torch.is_tensor(tensor): + if isinstance(tensor, list): + for t in tensor: + if not torch.is_tensor(t): + raise TypeError(f"tensor or list of tensors expected, got a list containing {type(t)}") + else: + raise TypeError(f"tensor or list of tensors expected, got {type(tensor)}") + + # if list of tensors, convert to a 4D mini-batch Tensor + if isinstance(tensor, list): + tensor = torch.stack(tensor, dim=0) + + if tensor.dim() == 2: # single image H x W + tensor = tensor.unsqueeze(0) + if tensor.dim() == 3: # single image + if tensor.size(0) == 1: # if single-channel, convert to 3-channel + tensor = torch.cat((tensor, tensor, tensor), 0) + tensor = tensor.unsqueeze(0) + + if tensor.dim() == 4 and tensor.size(1) == 1: # single-channel images + tensor = torch.cat((tensor, tensor, tensor), 1) + + if normalize is True: + tensor = tensor.clone() # avoid modifying tensor in-place + if value_range is not None and not isinstance(value_range, tuple): + raise TypeError("value_range has to be a tuple (min, max) if specified. min and max are numbers") + + def norm_ip(img, low, high): + img.clamp_(min=low, max=high) + img.sub_(low).div_(max(high - low, 1e-5)) + + def norm_range(t, value_range): + if value_range is not None: + norm_ip(t, value_range[0], value_range[1]) + else: + norm_ip(t, float(t.min()), float(t.max())) + + if scale_each is True: + for t in tensor: # loop over mini-batch dimension + norm_range(t, value_range) + else: + norm_range(tensor, value_range) + + if not isinstance(tensor, torch.Tensor): + raise TypeError("tensor should be of type torch.Tensor") + if tensor.size(0) == 1: + return tensor.squeeze(0) + + # make the mini-batch of images into a grid + nmaps = tensor.size(0) + xmaps = min(nrow, nmaps) + ymaps = int(math.ceil(float(nmaps) / xmaps)) + height, width = int(tensor.size(2) + padding), int(tensor.size(3) + padding) + num_channels = tensor.size(1) + grid = tensor.new_full((num_channels, height * ymaps + padding, width * xmaps + padding), pad_value) + k = 0 + for y in range(ymaps): + for x in range(xmaps): + if k >= nmaps: + break + # Tensor.copy_() is a valid method but seems to be missing from the stubs + # https://pytorch.org/docs/stable/tensors.html#torch.Tensor.copy_ + grid.narrow(1, y * height + padding, height - padding).narrow( # type: ignore[attr-defined] + 2, x * width + padding, width - padding + ).copy_(tensor[k]) + k = k + 1 + return grid + + +class _ImageDrawTV(ImageDraw.ImageDraw): + """ + A wrapper around PIL.ImageDraw to add functionalities for drawing rotated bounding boxes. + """ + + def oriented_rectangle(self, xy, fill=None, outline=None, width=1): + self.dashed_line(((xy[0], xy[1]), (xy[2], xy[3])), width=width, fill=outline) + for i in range(2, len(xy), 2): + self.line( + ((xy[i], xy[i + 1]), (xy[(i + 2) % len(xy)], xy[(i + 3) % len(xy)])), + width=width, + fill=outline, + ) + self.polygon(xy, fill=fill, outline=None, width=0) + + def dashed_line(self, xy, fill=None, width=0, joint=None, dash_length=5, space_length=5): + # Calculate the total length of the line + total_length = 0 + for i in range(1, len(xy)): + x1, y1 = xy[i - 1] + x2, y2 = xy[i] + total_length += ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 + # Initialize the current position and the current dash + current_position = 0 + current_dash = True + # Iterate over the coordinates of the line + for i in range(1, len(xy)): + x1, y1 = xy[i - 1] + x2, y2 = xy[i] + # Calculate the length of this segment + segment_length = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 + # While there are still dashes to draw on this segment + while segment_length > 0: + # Calculate the length of this dash + dash_length_to_draw = min(segment_length, dash_length if current_dash else space_length) + # Calculate the end point of this dash + dx = x2 - x1 + dy = y2 - y1 + angle = math.atan2(dy, dx) + end_x = x1 + math.cos(angle) * dash_length_to_draw + end_y = y1 + math.sin(angle) * dash_length_to_draw + # If this is a dash, draw it + if current_dash: + self.line([(x1, y1), (end_x, end_y)], fill, width, joint) + # Update the current position and the current dash + current_position += dash_length_to_draw + segment_length -= dash_length_to_draw + x1, y1 = end_x, end_y + current_dash = not current_dash + + +def _Image_fromarray( + obj: np.ndarray, + mode: str, +) -> Image.Image: + """ + A wrapper around PIL.Image.fromarray to mitigate the deprecation of the + mode parameter. See: + https://pillow.readthedocs.io/en/stable/releasenotes/11.3.0.html#image-fromarray-mode-parameter + """ + + # This may throw if the version string is from an install that comes from a + # non-stable or development version. We'll fall back to the old behavior in + # such cases. + try: + PILLOW_VERSION = tuple(int(x) for x in PILLOW_VERSION_STRING.split(".")) + except Exception: + PILLOW_VERSION = None + + if PILLOW_VERSION is not None and PILLOW_VERSION >= (11, 3): + # The actual PR that implements the deprecation has more context for why + # it was done, and also points out some problems: + # + # https://github.com/python-pillow/Pillow/pull/9018 + # + # Our use case falls into those problems. We actually rely on the old + # behavior of Image.fromarray(): + # + # new behavior: PIL will infer the image mode from the data passed + # in. That is, the type and shape determines the mode. + # + # old behavior: The mode will change how PIL reads the image, + # regardless of the data. That is, it will make the + # data work with the mode. + # + # Our uses of Image.fromarray() are effectively a "turn into PIL image + # AND convert the kind" operation. In particular, in + # functional.to_pil_image() and transforms.ToPILImage. + # + # However, Image.frombuffer() still performs this conversion. The code + # below is lifted from the new implementation of Image.fromarray(). We + # omit the code that infers the mode, and use the code that figures out + # from the data passed in (obj) what the correct parameters are to + # Image.frombuffer(). + # + # Note that the alternate solution below does not work: + # + # img = Image.fromarray(obj) + # img = img.convert(mode) + # + # The resulting image has very different actual pixel values than before. + # + # TODO: Issue #9151. Pillow has an open PR to restore the functionality + # we rely on: + # + # https://github.com/python-pillow/Pillow/pull/9063 + # + # When that is part of a release, we can revisit this hack below. + arr = obj.__array_interface__ + shape = arr["shape"] + ndim = len(shape) + size = 1 if ndim == 1 else shape[1], shape[0] + + strides = arr.get("strides", None) + contiguous_obj: Union[np.ndarray, bytes] = obj + if strides is not None: + # We require that the data is contiguous; if it is not, we need to + # convert it into a contiguous format. + if hasattr(obj, "tobytes"): + contiguous_obj = obj.tobytes() + elif hasattr(obj, "tostring"): + contiguous_obj = obj.tostring() + else: + raise ValueError("Unable to convert obj into contiguous format") + + return Image.frombuffer(mode, size, contiguous_obj, "raw", mode, 0, 1) + else: + return Image.fromarray(obj, mode) + + +@torch.no_grad() +def save_image( + tensor: Union[torch.Tensor, list[torch.Tensor]], + fp: Union[str, pathlib.Path, BinaryIO], + format: Optional[str] = None, + **kwargs, +) -> None: + """ + Save a given Tensor into an image file. + + Args: + tensor (Tensor or list): Image to be saved. If given a mini-batch tensor, + saves the tensor as a grid of images by calling ``make_grid``. + fp (string or file object): A filename or a file object + format(Optional): If omitted, the format to use is determined from the filename extension. + If a file object was used instead of a filename, this parameter should always be used. + **kwargs: Other arguments are documented in ``make_grid``. + """ + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(save_image) + grid = make_grid(tensor, **kwargs) + # Add 0.5 after unnormalizing to [0, 255] to round to the nearest integer + ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy() + im = Image.fromarray(ndarr) + im.save(fp, format=format) + + +@torch.no_grad() +def draw_bounding_boxes( + image: torch.Tensor, + boxes: torch.Tensor, + labels: Optional[list[str]] = None, + colors: Optional[Union[list[Union[str, tuple[int, int, int]]], str, tuple[int, int, int]]] = None, + fill: Optional[bool] = False, + width: int = 1, + font: Optional[str] = None, + font_size: Optional[int] = None, + label_colors: Optional[Union[list[Union[str, tuple[int, int, int]]], str, tuple[int, int, int]]] = None, + label_background_colors: Optional[Union[list[Union[str, tuple[int, int, int]]], str, tuple[int, int, int]]] = None, + fill_labels: bool = False, +) -> torch.Tensor: + """ + Draws bounding boxes on given RGB image. + The image values should be uint8 in [0, 255] or float in [0, 1]. + If fill is True, Resulting Tensor should be saved as PNG image. + + Args: + image (Tensor): Tensor of shape (C, H, W) and dtype uint8 or float. + boxes (Tensor): Tensor of size (N, 4) or (N, 8) containing bounding boxes. + For (N, 4), the format is (xmin, ymin, xmax, ymax) and the boxes are absolute coordinates with respect to the image. + In other words: `0 <= xmin < xmax < W` and `0 <= ymin < ymax < H`. + For (N, 8), the format is (x1, y1, x2, y2, x3, y3, x4, y4) and the boxes are absolute coordinates with respect to the underlying + object, so no need to verify the latter inequalities. + labels (List[str]): List containing the labels of bounding boxes. + colors (color or list of colors, optional): List containing the colors + of the boxes or single color for all boxes. The color can be represented as + PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``. + By default, random colors are generated for boxes. + fill (bool): If `True` fills the bounding box with specified color. + width (int): Width of bounding box. + font (str): A filename containing a TrueType font. If the file is not found in this filename, the loader may + also search in other directories, such as the `fonts/` directory on Windows or `/Library/Fonts/`, + `/System/Library/Fonts/` and `~/Library/Fonts/` on macOS. + font_size (int): The requested font size in points. + label_colors (color or list of colors, optional): Colors for the label text. See the description of the + `colors` argument for details. Defaults to the same colors used for the boxes, or to black if ``fill_labels`` is True. + label_background_colors (color or list of colors, optional): Colors for the label text box fill. Defaults to the + same colors used for the boxes. Ignored when ``fill_labels`` is False. + fill_labels (bool): If `True` fills the label background with specified color (from the ``label_background_colors`` parameter, + or from the ``colors`` parameter if not specified). Default: False. + + Returns: + img (Tensor[C, H, W]): Image Tensor of dtype uint8 with bounding boxes plotted. + + """ + import torchvision.transforms.v2.functional as F # noqa + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(draw_bounding_boxes) + if not isinstance(image, torch.Tensor): + raise TypeError(f"Tensor expected, got {type(image)}") + elif not (image.dtype == torch.uint8 or image.is_floating_point()): + raise ValueError(f"The image dtype must be uint8 or float, got {image.dtype}") + elif image.dim() != 3: + raise ValueError("Pass individual images, not batches") + elif image.size(0) not in {1, 3}: + raise ValueError("Only grayscale and RGB images are supported") + elif boxes.shape[-1] == 4 and ((boxes[:, 0] > boxes[:, 2]).any() or (boxes[:, 1] > boxes[:, 3]).any()): + raise ValueError( + "Boxes need to be in (xmin, ymin, xmax, ymax) format. Use torchvision.ops.box_convert to convert them" + ) + + num_boxes = boxes.shape[0] + + if num_boxes == 0: + warnings.warn("boxes doesn't contain any box. No box was drawn") + return image + + if labels is None: + labels: Union[list[str], list[None]] = [None] * num_boxes # type: ignore[no-redef] + elif len(labels) != num_boxes: + raise ValueError( + f"Number of boxes ({num_boxes}) and labels ({len(labels)}) mismatch. Please specify labels for each box." + ) + + colors = _parse_colors(colors, num_objects=num_boxes) # type: ignore[assignment] + if label_colors or fill_labels: + label_colors = _parse_colors(label_colors if label_colors else "black", num_objects=num_boxes) # type: ignore[assignment] + else: + label_colors = colors.copy() # type: ignore[assignment] + + if fill_labels and label_background_colors: + label_background_colors = _parse_colors(label_background_colors, num_objects=num_boxes) # type: ignore[assignment] + else: + label_background_colors = colors.copy() # type: ignore[assignment] + + if font is None: + if font_size is not None: + warnings.warn("Argument 'font_size' will be ignored since 'font' is not set.") + txt_font = ImageFont.load_default() + else: + txt_font = ImageFont.truetype(font=font, size=font_size or 10) + + # Handle Grayscale images + if image.size(0) == 1: + image = torch.tile(image, (3, 1, 1)) + + original_dtype = image.dtype + if original_dtype.is_floating_point: + image = F.to_dtype(image, dtype=torch.uint8, scale=True) + + img_to_draw = F.to_pil_image(image) + img_boxes = boxes.to(torch.int64).tolist() + + if fill: + draw = _ImageDrawTV(img_to_draw, "RGBA") + else: + draw = _ImageDrawTV(img_to_draw) + + for bbox, color, label, label_color, label_bg_color in zip(img_boxes, colors, labels, label_colors, label_background_colors): # type: ignore[arg-type] + draw_method = draw.oriented_rectangle if len(bbox) > 4 else draw.rectangle + fill_color = color + (100,) if fill else None + draw_method(bbox, width=width, outline=color, fill=fill_color) + + if label is not None: + box_margin = 1 + margin = width + box_margin + if fill_labels: + left, top, right, bottom = draw.textbbox((bbox[0] + margin, bbox[1] + margin), label, font=txt_font) + draw.rectangle( + (left - box_margin, top - box_margin, right + box_margin, bottom + box_margin), fill=label_bg_color # type: ignore[arg-type] + ) + draw.text((bbox[0] + margin, bbox[1] + margin), label, fill=label_color, font=txt_font) # type: ignore[arg-type] + + out = F.pil_to_tensor(img_to_draw) + if original_dtype.is_floating_point: + out = F.to_dtype(out, dtype=original_dtype, scale=True) + return out + + +@torch.no_grad() +def draw_segmentation_masks( + image: torch.Tensor, + masks: torch.Tensor, + alpha: float = 0.8, + colors: Optional[Union[list[Union[str, tuple[int, int, int]]], str, tuple[int, int, int]]] = None, +) -> torch.Tensor: + """ + Draws segmentation masks on given RGB image. + The image values should be uint8 in [0, 255] or float in [0, 1]. + + Args: + image (Tensor): Tensor of shape (3, H, W) and dtype uint8 or float. + masks (Tensor): Tensor of shape (num_masks, H, W) or (H, W) and dtype bool. + alpha (float): Float number between 0 and 1 denoting the transparency of the masks. + 0 means full transparency, 1 means no transparency. + colors (color or list of colors, optional): List containing the colors + of the masks or single color for all masks. The color can be represented as + PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``. + By default, random colors are generated for each mask. + + Returns: + img (Tensor[C, H, W]): Image Tensor, with segmentation masks drawn on top. + """ + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(draw_segmentation_masks) + if not isinstance(image, torch.Tensor): + raise TypeError(f"The image must be a tensor, got {type(image)}") + elif not (image.dtype == torch.uint8 or image.is_floating_point()): + raise ValueError(f"The image dtype must be uint8 or float, got {image.dtype}") + elif image.dim() != 3: + raise ValueError("Pass individual images, not batches") + elif image.size()[0] != 3: + raise ValueError("Pass an RGB image. Other Image formats are not supported") + if masks.ndim == 2: + masks = masks[None, :, :] + if masks.ndim != 3: + raise ValueError("masks must be of shape (H, W) or (batch_size, H, W)") + if masks.dtype != torch.bool: + raise ValueError(f"The masks must be of dtype bool. Got {masks.dtype}") + if masks.shape[-2:] != image.shape[-2:]: + raise ValueError("The image and the masks must have the same height and width") + + num_masks = masks.size()[0] + overlapping_masks = masks.sum(dim=0) > 1 + + if num_masks == 0: + warnings.warn("masks doesn't contain any mask. No mask was drawn") + return image + + original_dtype = image.dtype + colors = [ + torch.tensor(color, dtype=original_dtype, device=image.device) + for color in _parse_colors(colors, num_objects=num_masks, dtype=original_dtype) + ] + + img_to_draw = image.detach().clone() + # TODO: There might be a way to vectorize this + for mask, color in zip(masks, colors): + img_to_draw[:, mask] = color[:, None] + + img_to_draw[:, overlapping_masks] = 0 + + out = image * (1 - alpha) + img_to_draw * alpha + # Note: at this point, out is a float tensor in [0, 1] or [0, 255] depending on original_dtype + return out.to(original_dtype) + + +@torch.no_grad() +def draw_keypoints( + image: torch.Tensor, + keypoints: torch.Tensor, + connectivity: Optional[list[tuple[int, int]]] = None, + colors: Optional[Union[str, tuple[int, int, int]]] = None, + radius: int = 2, + width: int = 3, + visibility: Optional[torch.Tensor] = None, +) -> torch.Tensor: + """ + Draws Keypoints on given RGB image. + The image values should be uint8 in [0, 255] or float in [0, 1]. + Keypoints can be drawn for multiple instances at a time. + + This method allows that keypoints and their connectivity are drawn based on the visibility of this keypoint. + + Args: + image (Tensor): Tensor of shape (3, H, W) and dtype uint8 or float. + keypoints (Tensor): Tensor of shape (num_instances, K, 2) the K keypoint locations for each of the N instances, + in the format [x, y]. + connectivity (List[Tuple[int, int]]]): A List of tuple where each tuple contains a pair of keypoints + to be connected. + If at least one of the two connected keypoints has a ``visibility`` of False, + this specific connection is not drawn. + Exclusions due to invisibility are computed per-instance. + colors (str, Tuple): The color can be represented as + PIL strings e.g. "red" or "#FF00FF", or as RGB tuples e.g. ``(240, 10, 157)``. + radius (int): Integer denoting radius of keypoint. + width (int): Integer denoting width of line connecting keypoints. + visibility (Tensor): Tensor of shape (num_instances, K) specifying the visibility of the K + keypoints for each of the N instances. + True means that the respective keypoint is visible and should be drawn. + False means invisible, so neither the point nor possible connections containing it are drawn. + The input tensor will be cast to bool. + Default ``None`` means that all the keypoints are visible. + For more details, see :ref:`draw_keypoints_with_visibility`. + + Returns: + img (Tensor[C, H, W]): Image Tensor with keypoints drawn. + """ + + if not torch.jit.is_scripting() and not torch.jit.is_tracing(): + _log_api_usage_once(draw_keypoints) + # validate image + if not isinstance(image, torch.Tensor): + raise TypeError(f"The image must be a tensor, got {type(image)}") + elif not (image.dtype == torch.uint8 or image.is_floating_point()): + raise ValueError(f"The image dtype must be uint8 or float, got {image.dtype}") + elif image.dim() != 3: + raise ValueError("Pass individual images, not batches") + elif image.size()[0] != 3: + raise ValueError("Pass an RGB image. Other Image formats are not supported") + + # validate keypoints + if keypoints.ndim != 3: + raise ValueError("keypoints must be of shape (num_instances, K, 2)") + + # validate visibility + if visibility is None: # set default + visibility = torch.ones(keypoints.shape[:-1], dtype=torch.bool) + if visibility.ndim == 3: + # If visibility was passed as pred.split([2, 1], dim=-1), it will be of shape (num_instances, K, 1). + # We make sure it is of shape (num_instances, K). This isn't documented, we're just being nice. + visibility = visibility.squeeze(-1) + if visibility.ndim != 2: + raise ValueError(f"visibility must be of shape (num_instances, K). Got ndim={visibility.ndim}") + if visibility.shape != keypoints.shape[:-1]: + raise ValueError( + "keypoints and visibility must have the same dimensionality for num_instances and K. " + f"Got {visibility.shape=} and {keypoints.shape=}" + ) + + original_dtype = image.dtype + if original_dtype.is_floating_point: + from torchvision.transforms.v2.functional import to_dtype # noqa + + image = to_dtype(image, dtype=torch.uint8, scale=True) + + ndarr = image.permute(1, 2, 0).cpu().numpy() + img_to_draw = Image.fromarray(ndarr) + draw = ImageDraw.Draw(img_to_draw) + img_kpts = keypoints.to(torch.int64).tolist() + img_vis = visibility.cpu().bool().tolist() + + for kpt_inst, vis_inst in zip(img_kpts, img_vis): + for kpt_coord, kp_vis in zip(kpt_inst, vis_inst): + if not kp_vis: + continue + x1 = kpt_coord[0] - radius + x2 = kpt_coord[0] + radius + y1 = kpt_coord[1] - radius + y2 = kpt_coord[1] + radius + draw.ellipse([x1, y1, x2, y2], fill=colors, outline=None, width=0) + + if connectivity: + for connection in connectivity: + if (not vis_inst[connection[0]]) or (not vis_inst[connection[1]]): + continue + start_pt_x = kpt_inst[connection[0]][0] + start_pt_y = kpt_inst[connection[0]][1] + + end_pt_x = kpt_inst[connection[1]][0] + end_pt_y = kpt_inst[connection[1]][1] + + draw.line( + ((start_pt_x, start_pt_y), (end_pt_x, end_pt_y)), + width=width, + ) + + out = torch.from_numpy(np.array(img_to_draw)).permute(2, 0, 1) + if original_dtype.is_floating_point: + out = to_dtype(out, dtype=original_dtype, scale=True) + return out + + +# Flow visualization code adapted from https://github.com/tomrunia/OpticalFlow_Visualization +@torch.no_grad() +def flow_to_image(flow: torch.Tensor) -> torch.Tensor: + """ + Converts a flow to an RGB image. + + Args: + flow (Tensor): Flow of shape (N, 2, H, W) or (2, H, W) and dtype torch.float. + + Returns: + img (Tensor): Image Tensor of dtype uint8 where each color corresponds + to a given flow direction. Shape is (N, 3, H, W) or (3, H, W) depending on the input. + """ + + if flow.dtype != torch.float: + raise ValueError(f"Flow should be of dtype torch.float, got {flow.dtype}.") + + orig_shape = flow.shape + if flow.ndim == 3: + flow = flow[None] # Add batch dim + + if flow.ndim != 4 or flow.shape[1] != 2: + raise ValueError(f"Input flow should have shape (2, H, W) or (N, 2, H, W), got {orig_shape}.") + + max_norm = torch.sum(flow.pow(2), dim=1).sqrt().max() + epsilon = torch.finfo((flow).dtype).eps + normalized_flow = flow / (max_norm + epsilon) + img = _normalized_flow_to_image(normalized_flow) + + if len(orig_shape) == 3: + img = img[0] # Remove batch dim + return img + + +@torch.no_grad() +def _normalized_flow_to_image(normalized_flow: torch.Tensor) -> torch.Tensor: + """ + Converts a batch of normalized flow to an RGB image. + + Args: + normalized_flow (torch.Tensor): Normalized flow tensor of shape (N, 2, H, W) + Returns: + img (Tensor(N, 3, H, W)): Flow visualization image of dtype uint8. + """ + + N, _, H, W = normalized_flow.shape + device = normalized_flow.device + flow_image = torch.zeros((N, 3, H, W), dtype=torch.uint8, device=device) + colorwheel = _make_colorwheel().to(device) # shape [55x3] + num_cols = colorwheel.shape[0] + norm = torch.sum(normalized_flow.pow(2), dim=1).sqrt() + a = torch.atan2(-normalized_flow[:, 1, :, :], -normalized_flow[:, 0, :, :]) / torch.pi + fk = (a + 1) / 2 * (num_cols - 1) + k0 = torch.floor(fk).to(torch.long) + k1 = k0 + 1 + k1[k1 == num_cols] = 0 + f = fk - k0 + + for c in range(colorwheel.shape[1]): + tmp = colorwheel[:, c] + col0 = tmp[k0] / 255.0 + col1 = tmp[k1] / 255.0 + col = (1 - f) * col0 + f * col1 + col = 1 - norm * (1 - col) + flow_image[:, c, :, :] = torch.floor(255 * col) + return flow_image + + +def _make_colorwheel() -> torch.Tensor: + """ + Generates a color wheel for optical flow visualization as presented in: + Baker et al. "A Database and Evaluation Methodology for Optical Flow" (ICCV, 2007) + URL: http://vision.middlebury.edu/flow/flowEval-iccv07.pdf. + + Returns: + colorwheel (Tensor[55, 3]): Colorwheel Tensor. + """ + + RY = 15 + YG = 6 + GC = 4 + CB = 11 + BM = 13 + MR = 6 + + ncols = RY + YG + GC + CB + BM + MR + colorwheel = torch.zeros((ncols, 3)) + col = 0 + + # RY + colorwheel[0:RY, 0] = 255 + colorwheel[0:RY, 1] = torch.floor(255 * torch.arange(0, RY) / RY) + col = col + RY + # YG + colorwheel[col : col + YG, 0] = 255 - torch.floor(255 * torch.arange(0, YG) / YG) + colorwheel[col : col + YG, 1] = 255 + col = col + YG + # GC + colorwheel[col : col + GC, 1] = 255 + colorwheel[col : col + GC, 2] = torch.floor(255 * torch.arange(0, GC) / GC) + col = col + GC + # CB + colorwheel[col : col + CB, 1] = 255 - torch.floor(255 * torch.arange(CB) / CB) + colorwheel[col : col + CB, 2] = 255 + col = col + CB + # BM + colorwheel[col : col + BM, 2] = 255 + colorwheel[col : col + BM, 0] = torch.floor(255 * torch.arange(0, BM) / BM) + col = col + BM + # MR + colorwheel[col : col + MR, 2] = 255 - torch.floor(255 * torch.arange(MR) / MR) + colorwheel[col : col + MR, 0] = 255 + return colorwheel + + +def _generate_color_palette(num_objects: int): + palette = torch.tensor([2**25 - 1, 2**15 - 1, 2**21 - 1]) + return [tuple((i * palette) % 255) for i in range(num_objects)] + + +def _parse_colors( + colors: Union[None, str, tuple[int, int, int], list[Union[str, tuple[int, int, int]]]], + *, + num_objects: int, + dtype: torch.dtype = torch.uint8, +) -> list[tuple[int, int, int]]: + """ + Parses a specification of colors for a set of objects. + + Args: + colors: A specification of colors for the objects. This can be one of the following: + - None: to generate a color palette automatically. + - A list of colors: where each color is either a string (specifying a named color) or an RGB tuple. + - A string or an RGB tuple: to use the same color for all objects. + + If `colors` is a tuple, it should be a 3-tuple specifying the RGB values of the color. + If `colors` is a list, it should have at least as many elements as the number of objects to color. + + num_objects (int): The number of objects to color. + + Returns: + A list of 3-tuples, specifying the RGB values of the colors. + + Raises: + ValueError: If the number of colors in the list is less than the number of objects to color. + If `colors` is not a list, tuple, string or None. + """ + if colors is None: + colors = _generate_color_palette(num_objects) + elif isinstance(colors, list): + if len(colors) < num_objects: + raise ValueError( + f"Number of colors must be equal or larger than the number of objects, but got {len(colors)} < {num_objects}." + ) + elif not isinstance(colors, (tuple, str)): + raise ValueError(f"colors must be a tuple or a string, or a list thereof, but got {colors}.") + elif isinstance(colors, tuple) and len(colors) != 3: + raise ValueError(f"If passed as tuple, colors should be an RGB triplet, but got {colors}.") + else: # colors specifies a single color for all objects + colors = [colors] * num_objects + + colors = [ImageColor.getrgb(color) if isinstance(color, str) else color for color in colors] + if dtype.is_floating_point: # [0, 255] -> [0, 1] + colors = [tuple(v / 255 for v in color) for color in colors] # type: ignore[union-attr] + return colors # type: ignore[return-value] + + +def _log_api_usage_once(obj: Any) -> None: + """ + Logs API usage(module and name) within an organization. + In a large ecosystem, it's often useful to track the PyTorch and + TorchVision APIs usage. This API provides the similar functionality to the + logging module in the Python stdlib. It can be used for debugging purpose + to log which methods are used and by default it is inactive, unless the user + manually subscribes a logger via the `SetAPIUsageLogger method `_. + Please note it is triggered only once for the same API call within a process. + It does not collect any data from open-source users since it is no-op by default. + For more information, please refer to + * PyTorch note: https://pytorch.org/docs/stable/notes/large_scale_deployments.html#api-usage-logging; + * Logging policy: https://github.com/pytorch/vision/issues/5052; + + Args: + obj (class instance or method): an object to extract info from. + """ + module = obj.__module__ + if not module.startswith("torchvision"): + module = f"torchvision.internal.{module}" + name = obj.__class__.__name__ + if isinstance(obj, FunctionType): + name = obj.__name__ + torch._C._log_api_usage_once(f"{module}.{name}") + + +def _make_ntuple(x: Any, n: int) -> tuple[Any, ...]: + """ + Make n-tuple from input x. If x is an iterable, then we just convert it to tuple. + Otherwise, we will make a tuple of length n, all with value of x. + reference: https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/utils.py#L8 + + Args: + x (Any): input value + n (int): length of the resulting tuple + """ + if isinstance(x, collections.abc.Iterable): + return tuple(x) + return tuple(repeat(x, n)) diff --git a/.venv/lib/python3.12/site-packages/torchvision/version.py b/.venv/lib/python3.12/site-packages/torchvision/version.py new file mode 100644 index 0000000000000000000000000000000000000000..4b91c80b497b022c38d359654cd012a557899c87 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/torchvision/version.py @@ -0,0 +1,5 @@ +__version__ = '0.29.0+cpu' +git_version = 'fc73f5a8567734ffa4c988b24d5432f0d3005974' +from torchvision.extension import _check_cuda_version +if _check_cuda_version() > 0: + cuda = _check_cuda_version() diff --git a/.venv/lib/python3.12/site-packages/tqdm/__init__.py b/.venv/lib/python3.12/site-packages/tqdm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8081f77b8812f3b42d7949daa4195d2c35dc70ac --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/__init__.py @@ -0,0 +1,38 @@ +from ._monitor import TMonitor, TqdmSynchronisationWarning +from ._tqdm_pandas import tqdm_pandas +from .cli import main # TODO: remove in v5.0.0 +from .gui import tqdm as tqdm_gui # TODO: remove in v5.0.0 +from .gui import trange as tgrange # TODO: remove in v5.0.0 +from .std import ( + TqdmDeprecationWarning, TqdmExperimentalWarning, TqdmKeyError, TqdmMonitorWarning, + TqdmTypeError, TqdmWarning, tqdm, trange) +from .version import __version__ + +__all__ = ['tqdm', 'tqdm_gui', 'trange', 'tgrange', 'tqdm_pandas', + 'tqdm_notebook', 'tnrange', 'main', 'TMonitor', + 'TqdmTypeError', 'TqdmKeyError', + 'TqdmWarning', 'TqdmDeprecationWarning', + 'TqdmExperimentalWarning', + 'TqdmMonitorWarning', 'TqdmSynchronisationWarning', + '__version__'] + + +def tqdm_notebook(*args, **kwargs): # pragma: no cover + """See tqdm.notebook.tqdm for full documentation""" + from warnings import warn + + from .notebook import tqdm as _tqdm_notebook + warn("This function will be removed in tqdm==5.0.0\n" + "Please use `tqdm.notebook.tqdm` instead of `tqdm.tqdm_notebook`", + TqdmDeprecationWarning, stacklevel=2) + return _tqdm_notebook(*args, **kwargs) + + +def tnrange(*args, **kwargs): # pragma: no cover + """Shortcut for `tqdm.notebook.tqdm(range(*args), **kwargs)`.""" + from warnings import warn + + from .notebook import trange as _tnrange + warn("Please use `tqdm.notebook.trange` instead of `tqdm.tnrange`", + TqdmDeprecationWarning, stacklevel=2) + return _tnrange(*args, **kwargs) diff --git a/.venv/lib/python3.12/site-packages/tqdm/__main__.py b/.venv/lib/python3.12/site-packages/tqdm/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e28416e104515e90fca4b69cc60d0c61fd15d61 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +main() diff --git a/.venv/lib/python3.12/site-packages/tqdm/__pycache__/__init__.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7bf64282ad453fa07ba6c0be2f875751771bee9 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tqdm/__pycache__/_monitor.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/_monitor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad969b727c1d6376895e88bf83d6be2aa78d8207 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/_monitor.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tqdm/__pycache__/_tqdm_pandas.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/_tqdm_pandas.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c94967297810b54d1caa4c751e20d73baa3e51d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/_tqdm_pandas.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tqdm/__pycache__/cli.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/cli.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed236c43915292b76cc17f936f8682167def9d2d Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/cli.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tqdm/__pycache__/gui.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/gui.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab44ade71e249fb7ff290d83f0e0c46645f3a2b0 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/gui.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tqdm/__pycache__/std.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/std.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71e0002cf7a5f872b8cecfe0fa1e14f17f65410e Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/std.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tqdm/__pycache__/utils.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..584481fcc1280f0093bd409db2f03cfdd77b4733 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/utils.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tqdm/__pycache__/version.cpython-312.pyc b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7f6121f332a88ea433e3ef40f169327c70f92b5 Binary files /dev/null and b/.venv/lib/python3.12/site-packages/tqdm/__pycache__/version.cpython-312.pyc differ diff --git a/.venv/lib/python3.12/site-packages/tqdm/_main.py b/.venv/lib/python3.12/site-packages/tqdm/_main.py new file mode 100644 index 0000000000000000000000000000000000000000..04fdeeff17b5cc84b210f445b54b87d5b99e3748 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/_main.py @@ -0,0 +1,9 @@ +from warnings import warn + +from .cli import * # NOQA +from .cli import __all__ # NOQA +from .std import TqdmDeprecationWarning + +warn("This function will be removed in tqdm==5.0.0\n" + "Please use `tqdm.cli.*` instead of `tqdm._main.*`", + TqdmDeprecationWarning, stacklevel=2) diff --git a/.venv/lib/python3.12/site-packages/tqdm/_monitor.py b/.venv/lib/python3.12/site-packages/tqdm/_monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..9d97b8313770b7ced3639d43db3c89d41c5b9b67 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/_monitor.py @@ -0,0 +1,104 @@ +import atexit +from threading import Event, Thread, current_thread +from time import time +from warnings import warn + +__all__ = ["TMonitor", "TqdmSynchronisationWarning"] + + +class TqdmSynchronisationWarning(RuntimeWarning): + """ + tqdm multi-thread/-process errors which may cause incorrect nesting + but otherwise no adverse effects + """ + + +class TMonitor(Thread): + """ + Monitoring thread for tqdm bars. + Monitors if tqdm bars are taking too much time to display + and readjusts miniters automatically if necessary. + + Parameters + ---------- + tqdm_cls : class + tqdm class to use (can be core tqdm or a submodule). + sleep_interval : float + Time to sleep between monitoring checks. + """ + _test = {} # internal vars for unit testing + + def __init__(self, tqdm_cls, sleep_interval): + Thread.__init__(self, name="tqdm_monitor") + self.daemon = True # kill thread when main killed (KeyboardInterrupt) + self.woken = 0 # last time woken up, to sync with monitor + self.tqdm_cls = tqdm_cls + self.sleep_interval = sleep_interval + self._time = self._test.get("time", time) + self.was_killed = self._test.get("Event", Event)() + atexit.register(self._atexit_signal) + self.start() + + def _atexit_signal(self): + """ + Non-joining shutdown signal. + Avoids deadlocks at interpreter exit from other threads, dead forks, etc. + This daemon thread is auto-reaped on shutdown without needing a join. + """ + self.was_killed.set() + + def exit(self): + self.was_killed.set() + if self is not current_thread(): + self.join() + return self.report() + + def get_instances(self): + # returns a copy of started `tqdm_cls` instances + return [i for i in self.tqdm_cls._instances.copy() + # Avoid race by checking that the instance started + if hasattr(i, 'start_t')] + + def run(self): + cur_t = self._time() + while True: + # After processing and before sleeping, notify that we woke + # Need to be done just before sleeping + self.woken = cur_t + # Sleep some time... + self.was_killed.wait(self.sleep_interval) + # Quit if killed + if self.was_killed.is_set(): + return + # Then monitor! + # Acquire lock (to access _instances) + with self.tqdm_cls.get_lock(): + cur_t = self._time() + # Check tqdm instances are waiting too long to print + instances = self.get_instances() + for instance in instances: + # Check event in loop to reduce blocking time on exit + if self.was_killed.is_set(): + return + # Only if mininterval > 1 (else iterations are just slow) + # and last refresh exceeded maxinterval + if ( + instance.miniters > 1 + and (cur_t - instance.last_print_t) >= instance.maxinterval + ): + # force bypassing miniters on next iteration + # (dynamic_miniters adjusts mininterval automatically) + instance.miniters = 1 + # Refresh now! (works only for manual tqdm) + instance.refresh(nolock=True) + # Remove accidental long-lived strong reference + del instance + if instances != self.get_instances(): # pragma: nocover + warn("Set changed size during iteration" + + " (see https://github.com/tqdm/tqdm/issues/481)", + TqdmSynchronisationWarning, stacklevel=2) + # Remove accidental long-lived strong references + del instances + + def report(self): + return not self.was_killed.is_set() diff --git a/.venv/lib/python3.12/site-packages/tqdm/_tqdm.py b/.venv/lib/python3.12/site-packages/tqdm/_tqdm.py new file mode 100644 index 0000000000000000000000000000000000000000..7fc4962774a4651db7a739a3f143633b6215a9bd --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/_tqdm.py @@ -0,0 +1,9 @@ +from warnings import warn + +from .std import * # NOQA +from .std import __all__ # NOQA +from .std import TqdmDeprecationWarning + +warn("This function will be removed in tqdm==5.0.0\n" + "Please use `tqdm.std.*` instead of `tqdm._tqdm.*`", + TqdmDeprecationWarning, stacklevel=2) diff --git a/.venv/lib/python3.12/site-packages/tqdm/_tqdm_gui.py b/.venv/lib/python3.12/site-packages/tqdm/_tqdm_gui.py new file mode 100644 index 0000000000000000000000000000000000000000..f32aa894f54b3a5b47a0fbf4263c2fd20df56c9d --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/_tqdm_gui.py @@ -0,0 +1,9 @@ +from warnings import warn + +from .gui import * # NOQA +from .gui import __all__ # NOQA +from .std import TqdmDeprecationWarning + +warn("This function will be removed in tqdm==5.0.0\n" + "Please use `tqdm.gui.*` instead of `tqdm._tqdm_gui.*`", + TqdmDeprecationWarning, stacklevel=2) diff --git a/.venv/lib/python3.12/site-packages/tqdm/_tqdm_notebook.py b/.venv/lib/python3.12/site-packages/tqdm/_tqdm_notebook.py new file mode 100644 index 0000000000000000000000000000000000000000..f225fbf5b52d04987ccf68f4d5ee4b735e3158b0 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/_tqdm_notebook.py @@ -0,0 +1,9 @@ +from warnings import warn + +from .notebook import * # NOQA +from .notebook import __all__ # NOQA +from .std import TqdmDeprecationWarning + +warn("This function will be removed in tqdm==5.0.0\n" + "Please use `tqdm.notebook.*` instead of `tqdm._tqdm_notebook.*`", + TqdmDeprecationWarning, stacklevel=2) diff --git a/.venv/lib/python3.12/site-packages/tqdm/_tqdm_pandas.py b/.venv/lib/python3.12/site-packages/tqdm/_tqdm_pandas.py new file mode 100644 index 0000000000000000000000000000000000000000..c4fe6efdc603579e7f8acfa27ac10dccdf3e94ce --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/_tqdm_pandas.py @@ -0,0 +1,24 @@ +import sys + +__author__ = "github.com/casperdcl" +__all__ = ['tqdm_pandas'] + + +def tqdm_pandas(tclass, **tqdm_kwargs): + """ + Registers the given `tqdm` instance with + `pandas.core.groupby.DataFrameGroupBy.progress_apply`. + """ + from tqdm import TqdmDeprecationWarning + + if isinstance(tclass, type) or (getattr(tclass, '__name__', '').startswith( + 'tqdm_')): # delayed adapter case + TqdmDeprecationWarning( + "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm, ...)`.", + fp_write=getattr(tqdm_kwargs.get('file', None), 'write', sys.stderr.write)) + tclass.pandas(**tqdm_kwargs) + else: + TqdmDeprecationWarning( + "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm(...))`.", + fp_write=getattr(tclass.fp, 'write', sys.stderr.write)) + type(tclass).pandas(deprecated_t=tclass) diff --git a/.venv/lib/python3.12/site-packages/tqdm/_utils.py b/.venv/lib/python3.12/site-packages/tqdm/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..28665dfe7f518bfaabce9bd442e4f2b23aeac267 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/_utils.py @@ -0,0 +1,11 @@ +from warnings import warn + +from .std import TqdmDeprecationWarning +from .utils import ( # noqa: F401, pylint: disable=unused-import + CUR_OS, IS_NIX, IS_WIN, RE_ANSI, Comparable, FormatReplace, SimpleTextIOWrapper, + _environ_cols_wrapper, _is_ascii, _is_utf, _screen_shape_linux, _screen_shape_tput, + _screen_shape_windows, _screen_shape_wrapper, _supports_unicode, _term_move_up, colorama) + +warn("This function will be removed in tqdm==5.0.0\n" + "Please use `tqdm.utils.*` instead of `tqdm._utils.*`", + TqdmDeprecationWarning, stacklevel=2) diff --git a/.venv/lib/python3.12/site-packages/tqdm/asyncio.py b/.venv/lib/python3.12/site-packages/tqdm/asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..ac5c2e67119bb77d25d1fd38e6590393a65b3e93 --- /dev/null +++ b/.venv/lib/python3.12/site-packages/tqdm/asyncio.py @@ -0,0 +1,103 @@ +""" +Asynchronous progress bar decorator for iterators. +Includes a default `range` iterator printing to `stderr`. + +Usage: +>>> from tqdm.asyncio import trange, tqdm +>>> async for i in trange(10): +... ... +""" +import asyncio +from sys import version_info + +from .std import tqdm as std_tqdm + +__author__ = {"github.com/": ["casperdcl"]} +__all__ = ['tqdm_asyncio', 'tarange', 'tqdm', 'trange'] + + +class tqdm_asyncio(std_tqdm): + """ + Asynchronous-friendly version of tqdm. + """ + def __init__(self, iterable=None, *args, **kwargs): + super().__init__(iterable, *args, **kwargs) + self.iterable_awaitable = False + if iterable is not None: + if hasattr(iterable, "__anext__"): + self.iterable_next = iterable.__anext__ + self.iterable_awaitable = True + elif hasattr(iterable, "__aiter__"): + self.iterable_iterator = iterable.__aiter__() + self.iterable_next = self.iterable_iterator.__anext__ + self.iterable_awaitable = True + elif hasattr(iterable, "__next__"): + self.iterable_next = iterable.__next__ + else: + self.iterable_iterator = iter(iterable) + self.iterable_next = self.iterable_iterator.__next__ + + def __aiter__(self): + return self + + async def __anext__(self): + try: + if self.iterable_awaitable: + res = await self.iterable_next() + else: + res = self.iterable_next() + self.update() + return res + except StopIteration: + self.close() + raise StopAsyncIteration + except BaseException: + self.close() + raise + + def send(self, *args, **kwargs): + return self.iterable.send(*args, **kwargs) + + @classmethod + def as_completed(cls, fs, *, loop=None, timeout=None, total=None, **tqdm_kwargs): + """ + Wrapper for `asyncio.as_completed`. + """ + if total is None: + total = len(fs) + kwargs = {} + if version_info[:2] < (3, 10): + kwargs['loop'] = loop + yield from cls(asyncio.as_completed(fs, timeout=timeout, **kwargs), + total=total, **tqdm_kwargs) + + @classmethod + async def gather(cls, *fs, loop=None, timeout=None, total=None, return_exceptions=False, + **tqdm_kwargs): + """ + Wrapper for `asyncio.gather`. + """ + async def wrap_awaitable(i, f): + try: + return i, await f + except Exception as e: # noqa: BLE001 + if return_exceptions: + return i, e + raise + + ifs = [wrap_awaitable(i, f) for i, f in enumerate(fs)] + res = [await f for f in cls.as_completed(ifs, loop=loop, timeout=timeout, + total=total, **tqdm_kwargs)] + return [i for _, i in sorted(res)] + + +def tarange(*args, **kwargs): + """ + A shortcut for `tqdm.asyncio.tqdm(range(*args), **kwargs)`. + """ + return tqdm_asyncio(range(*args), **kwargs) + + +# Aliases +tqdm = tqdm_asyncio +trange = tarange